

//********************************************
//********* START INIT FUNCTIONS *************
//********************************************

jQuery(function(){
	initGlobal();
	initProductOrCatalogue();
	initShoppingCart(false);
	initCheckOut();
	initReceipt();
});

/* Global UI updates */
function initGlobal(){
	
	var selectedCatalogue;
	selectedCatalogue = jQuery('#catalogueTrail a:last-child').text();
	
	if(jQuery('ul.catalogueList li.catalogueItemNotFound').length == 1)
		jQuery("ul.catalogueList").hide();

	if(jQuery('ul.productList li.productItemNotFound').length == 1)
		jQuery("ul.productList").hide();
		
	if(jQuery('.productLarge').length == 0){
		/* output the title */
		jQuery("h2#catalogue-title").text(selectedCatalogue);
	}
	/*we're in a product detail page so hide the title*/
	else{
		jQuery("h2#catalogue-title").hide();
		jQuery("ul.catalogueList").hide();
	}
	/*write the catalogue breadcrumb to the master template */
	if(jQuery('#ShoppingBreadcrumb').length == 1)
		jQuery("#breadcrumbs p").html(jQuery('#ShoppingBreadcrumb').html());
	if(jQuery('#catalogueTrail').length == 1){
		var breadcrumbsHTML = jQuery("#catalogueTrail").html();
		//remove default colon seperators		
		breadcrumbsHTML = breadcrumbsHTML.replace(/:/g, "");
		jQuery("#catalogueTrail").html(breadcrumbsHTML);		
	}
}
  
function initShoppingCart(reload){

	jQuery('#ShippingOptions').change(
		function(){
			return initShoppingCart(true);
		}
	);
	//detect changes in the discount code fields
	jQuery('.discountcodeInput').change(
		function(){
			initShoppingCart(true);
		}
	);
	//detect changes in the quantity fields
	jQuery('.cartInputText').change(
		function(){
			initShoppingCart(true);
		}
	);

	jQuery('#catshopbuy').click(
		function(){
			return captureOrder();
		}
	);

	//obligate the user to select a shipping option country and shipping option
	if(jQuery('#shippingCountry').length > 0 && jQuery('#ShippingOptions').length > 0 && !reload)
		resetShippingOptions();		
}

function initCheckOut(){

	//is there a setbilling address checkbox?
	if(jQuery('#SetBilling').length > 0){

		jQuery('#SetBilling').click(
		
			function(){
				if (jQuery(this).is(':checked')) {
					jQuery('#BillingAddress').val(jQuery('#ShippingAddress').val()); 
					jQuery('#BillingCity').val(jQuery('#ShippingCity').val());
					jQuery('#BillingState').val(jQuery('#ShippingState').val()); 
					jQuery('#BillingZip').val(jQuery('#ShippingZip').val()); 
					jQuery('#BillingCountry').val(jQuery('#ShippingCountry').val()); 
				} else {
					jQuery('#BillingAddress').val(''); 
					jQuery('#BillingCity').val(''); 
					jQuery('#BillingState').val(''); 
					jQuery('#BillingZip').val(''); 
					jQuery('#BillingCountry').val(''); 
				}
			}
		);
	}
}

function initProductOrCatalogue(){

	/*refactor of the catalogue and product lists*/
	if(jQuery(".product-or-catalogue").length > 0){
		/*is this a product or catalogue list?*/
		var productOrCatalogue;
		
		if(jQuery('ul.catalogueList .product-or-catalogue').length > 0)
			productOrCatalogue = "catalogue";
		else
			productOrCatalogue = "product";	
			
		/*create the links to the catalogues or products*/
		jQuery(".product-or-catalogue").each(
			 function(){ 
				/*catalogue*/
				if(productOrCatalogue == "catalogue"){
					/*get the link from the h3 element*/
					var catalogueLink = jQuery(this).find('h3 a').attr('href'); 
					var catalogueTitle = jQuery(this).find('h3').text();
					/*recreate the link below*/
					jQuery(this).append('<p><a class="catalogue-link" href="' + catalogueLink + '">View this catalogue</a></p>');
				}
				/*product*/
				else{
					
					/*get the link from the title p element*/
					var productLink = jQuery(this).find('h3 a').attr('href'); 
					var productTitle = jQuery(this).find('h3').text();
					/*remove the link in the title p*/
					jQuery(this).find('p.title strong').html(productTitle);
					/*recreate the link below*/
					jQuery(this).append('<p><a class="product-link" href="' + productLink + '">View in detail</a></p>');
				}
			}
		);
	}
}


//we want to add order summary to the receipt page
function initReceipt(){
	
	if(jQuery('#custOrders').length > 0){
	   // read contents of cookie
		what = prefs.load();
					
		var html2add = '';
		//go through products in cookie
		for(i = 0; i < what.products.length; i++){

			var remainder = (i + 1) % 2;
			var rowClass;
			
			if(remainder === 0)
				rowClass = 'odd';
			else
				rowClass = 'even';
				
			html2add += '<tr class="' + rowClass + '"><td>' + what.products[i].name + '</td><td>' + what.products[i].quantity + '</td><td>' + what.products[i].price + '</td></tr>';

		//add rows to table body
		jQuery('#custOrders tbody').html(html2add);
		
		}
		//fill in the order totals
		jQuery('#custOrders tfoot td#subTotal').html(what.order.SubTotal);
		jQuery('#custOrders tfoot td#shipping').html(what.order.Shipping);
		jQuery('#custOrders tfoot td#total').html(what.order.Total);		
	}
}

//********************************************
//********* END INIT FUNCTIONS *************
//********************************************


function resetShippingOptions(){
	
	//obligate the customer to select shipping option
	var shippingTotal = jQuery('#ShippingAmount').text();
	shippingTotal = shippingTotal.substring(1);
	shippingTotal = shippingTotal.replace(',','');
	shippingTotal = parseInt(shippingTotal);	
	//obligate the user to select a shipping option country and shipping option
	if(shippingTotal == "0"){
		//all the options in the dropdown
		var shippingOptionsDD = jQuery('#shippingCountry option');
	
		var shippingOptions = new Array();
		
		for(i = 0; i < shippingOptionsDD.length; i++){
			//iterate through the shipping options
			var shippingOption = {};
			shippingOption.name = jQuery(shippingOptionsDD[i]).text();
			shippingOption.value = jQuery(shippingOptionsDD[i]).val();
			
			//add these options to the shippingOptions array
			shippingOptions.push(shippingOption);
		}
		
		var html2add = '<option value="-1">-- Please Select -- </option>';
		
		for(k=0;k<shippingOptions.length;k++){
			//go through all the shippingOptions in the shippingOptions array
			//and build up the relevant HTML
			html2add += '<option value="' + shippingOptions[k].value + '">' + shippingOptions[k].name + '</option>';
		}
		//add this HTML to the select object on the page
		jQuery('select#shippingCountry').html(html2add);
	
		jQuery("#ShippingOptions option[value='-1']").attr('selected', 'selected');
	}
}

//click event for the Checkout button
//we want to add the details of the order to a cookie
function captureOrder() { 
	//product names, and quantities
	var prodnames = jQuery('#prodname div a');
	var prodquantities = jQuery('#quantity div input');
	var prodprices = jQuery('#price div');

	var myproducts = new Array();

	var j =	jQuery('#prodname > div').size();
	//go through the products
	for(k=0; k<j; k++){
		//create an object to add to the cookie
		var product = {};
		//fill out the product						
		product.name = jQuery(prodnames[k]).text();
		product.quantity = jQuery(prodquantities[k]).val();
		product.price = jQuery(prodprices[k]).text();
		//add to array of products
		myproducts[k] = product;
	}
	//save to cookie
	prefs.data.products = myproducts;

	prefs.save();

	var shippingTotal = jQuery('#ShippingAmount').text();
	shippingTotal = shippingTotal.substring(1);
	shippingTotal = shippingTotal.replace(',','');
	shippingTotal = parseInt(shippingTotal);
	
	var totalAmount = jQuery('#TotalAmount').text();
	totalAmount = totalAmount.substring(1);
	totalAmount = totalAmount.replace(',','');
	totalAmount = parseInt(totalAmount);

	var subTotal = jQuery('#SubTotal').text();
	subTotal = subTotal.substring(1);
	subTotal = subTotal.replace(',','');
	subTotal = parseInt(subTotal);

	var order = {};
	order.SubTotal = subTotal;
	order.Shipping = shippingTotal;
	order.Total = totalAmount;
	
	//save to cookie
	prefs.data.order = order;
	
	prefs.save();
	
	return true;
} 
