/**
Super smart MVC JS framework
	proposed bystac
		30 Sept 2007			
*/

function bugme(strss) {
	alert(strss);
}

var JSEngine = {	
	
	require: function (libraryName) {
				// I can write DOM extending to insert the new script tag element
				// but why loose time when we can copy the code from scriptaculos library.
				document.write('<script type="text/javascript" src="js/'+libraryName+'"></script>');
			},
			
	loadLibraries: function() {
			
			// load libraries
			['remotejson', 'cookies', 'cart'].each(function(el) {				
				JSEngine.require(el+'.js');
			});

			// load data
			['config', 'categories', 'products'].each(function(el) {				
				JSEngine.require('data/' +el+'.dat.js');
			});
		
		},
	
	getCurrentPage: function() {
			//var query = window.location;
			var thePage=unescape(location.href);
			
			if( thePage.indexOf('?') !== -1 )
				thePage = thePage.substring(0,thePage.indexOf('?') );

			thePage=thePage.substr(thePage.lastIndexOf('/')+1);
			thePage=thePage.substr(0,thePage.lastIndexOf('.'));			
			
			//bugme(thePage.toString());
			
			// Bug: if no page in address bar eg: http://someurl.com/
			// then the function will return empty string. 			
			if (thePage.toString() == '')
				return 'index';
			
			return thePage.toString();
		},
	
	getQuery: function( key_name ) {
			var qs = window.location.search.substring(1);
			var val_found = '';
			
			qs.split('&').each(function (pair) {			
				var qf=pair.split('=');
				if (key_name == qf[0] ) val_found = qf[1]; 
			} );
			
			return val_found;
		},
	
	navigateProduct: function() {
		var mySB = $('selectorProduct');
		var dest = mySB.options[mySB.selectedIndex].value;
		if (dest.length > 0) location.href = dest;
	}, 
	// some problems with cookie on the same page cannot be set only the next page
	// manully set the values
	updateCartItems: function(inPriceTotal, inTotalItems) {
			var currentPriceTotal = CookieJar.get('cart_pricetotal');
			var currentTotalItems = CookieJar.get('cart_items');
			
			//
			// set default values
			// http://www.cherny.com/webdev/60/javascript-function-arguments-default-values-passing-objects-and-overloading
			//
			inPriceTotal = inPriceTotal || 0;
			inTotalItems = inTotalItems || 0;
			
			if ( Number(inPriceTotal) > 0 && Number(inTotalItems) > 0 ) {
				currentPriceTotal = inPriceTotal;
				currentTotalItems = inTotalItems;
			}
			
			$('cart_pricetotal').update('$' + currentPriceTotal );		
			var strItems = (currentTotalItems==0 
										? '0 items' 
										: (currentTotalItems==1 
												? '1 item' 
												: '' + currentTotalItems + ' items' )
							);
			$('cart_items').update( '(' + strItems + ')' );
	},
	
	constructor: function() {}
}


// load additional libraries
JSEngine.loadLibraries();

Event.observe(window, 'load', function() {
		// load shopping cart
		//objCart = new ShopCart('objdispatch');
		ShopCart.loadSession();
		
		//cart_pricetotal, cart_items
		JSEngine.updateCartItems();
	}
);


