//the cookie will expire in 1 days 
var options = {expires: 1};

/**
 * will take the product array of json objects stored as string in the product
 * cookie and convert them to an array of navitve json jquery objects
 */

var returnfuncRef;

var order_collection;
var stationary_costs;
function setJSONStr(serverside_json_strIN){	
	order_collection = $.parseJSON(serverside_json_strIN);		
	//in case it hasn't been set reset it
	$.cookie(COOKIE_ID,order_collection.id,options);
}


function assignStationaryCosts(serverside_json_strIN){
	//parse the stationary costs to json object so we can cross reference based on what was entered
	stationary_costs = $.parseJSON(serverside_json_strIN);	
	updateShoppingCartView();	
}

function displayEncodedHTML(html){	
	var escaped = unescape(html);	
	escaped = $('<div/>').text(escaped).html();	
	return escaped;
}


function assignRemovalListners(){
	$('.view_item').click(function() {
		var idx = this.id.split('view_link')[1]; 		
		items = order_collection.items;
		var product = items[idx];
		
		$('#heading_text').val(displayEncodedHTML(product.heading_text));
		$('#sub_heading_text').val(displayEncodedHTML(product.sub_heading_text));
		$('input:[name='+fo_module_id+'text_color]').val(product.text_color);
		$('#position').val(product.position);
		$('input:[name='+fo_module_id+'font]').val(product.font);
		$('select:[name='+fo_module_id+'border_url]').val(product.border_url);
		$('input:[name='+fo_module_id+'icon_url]').val(product.icon_url);
		$('#heading_font_size').val(product.heading_font_size);
		$('#sh_font_size ').val(product.sh_font_size);
		$('select[name='+fo_module_id+'qty]').val(product.qty);
		$('select[name='+fo_module_id+'paper_size]').val(product.paper_size);
		
		
		$('select[name='+fo_module_id+'stamps_id]').val(product.stamps_id);			
		clearColorSelection();
		$('#'+ fo_module_id+product.text_color).addClass('selected');		
		clearIconSelection();
		$.each($('#icon_url li a'), function() { 
			if ($(this).attr('rel') == product.icon_url){
				$(this).addClass('selected');
			}
		});
		
		try{
			updateFlash();
		}catch(e){}
	
	});		
	$('.remove_from_cart').click(function() {
		var idx = this.id.split('rp_link')[1]; 				
		items = order_collection.items;
		// attempt to remove product from the products array
		if (idx > -1){				
			items.splice(idx,1);
			var stringified = JSON.stringify(items);			
			//OLD XAJAX
			//xajax_StoreClientCartOrders($.cookie(COOKIE_ID), stringified);				
			xajax.call('XAJAXManager_callMethod', {parameters:["StationaryManager","StoreClientCartOrders", $.cookie(COOKIE_ID), stringified],mode:'synchronous'});					
			updateShoppingCartView();
		}

	});		
}	


function updateShoppingCartView(){		
	$('#shopping_cart').html('');			
	//OLD XAJAX
	//xajax_GetClientCartOrders($.cookie(COOKIE_ID));
	xajax.call('XAJAXManager_callMethod', {parameters:["StationaryManager","GetClientCartOrders", $.cookie(COOKIE_ID)],mode:'synchronous'});			
}

var total;


function findStationaryObject(paper_size_id, qty_id){
	for (var i =0; i < stationary_costs.length; i++){
		if (stationary_costs[i].paper_size_id == paper_size_id && stationary_costs[i].qty_id == qty_id){			
			return stationary_costs[i];
		}
	}	
}

function updateCartDisplay(){	
	items = order_collection.items;	
	total = 0;
	var quantity = "";	
	var shopping_cart_html = "<ul>";	
	var stationary_obj;
				
	if(items.length == 0)
	{
		$('#xajax_checkout_button').css('display', 'none');
		$('#display_text').html('There are no items in your cart.  Please <a href="index.php?page=product-categories">continue shopping</a> and add items to your cart before checking out.'); 
	}
	else
	{
		$('#display_text').html('');
		$('#xajax_checkout_button').css('display', 'block');	
	}

	for (var i = 0; i < items.length; i++){			
		
		if (items[i].type !="product"){
			var stamp_str = '';
			shopping_cart_html += "<li>";
			// price implemented here based on value (so multiple items can have the
			// same price)
			var price = 0;
			
			var stationary_obj = findStationaryObject(items[i].paper_size,items[i].qty);			
			
			quantity = stationary_obj.name			
			total += parseFloat(stationary_obj.price);
			price = parseFloat(stationary_obj.price);
						
			shopping_cart_html += "<div class='order_details'>";
			
			if (items[i].paper_size == 1){
				shopping_cart_html += "Paper size: Notepaper (202mm x 142mm)";
			}else{
				shopping_cart_html += "Paper size: Flat notecards (142mm x 101mm)";			
			}
			shopping_cart_html += "<br />Heading Line 1: " + displayEncodedHTML(items[i].heading_text);
			if (items[i].paper_size != 2){
				shopping_cart_html += "<br />Heading Line 2: " + displayEncodedHTML(items[i].sub_heading_text);				
			}
			shopping_cart_html += "<br />Font: " + items[i].font_name;
			shopping_cart_html += "<br />Icon: " + items[i].icon_name;
			shopping_cart_html += "<br />Colour: " + items[i].color_name;			
			shopping_cart_html += "<br />Quantity: " + quantity;	
			
			shopping_cart_html += "<br />";
			if (items[i].stamps_id == 1){
				total += 6.0;
				price += 6.0; 
				shopping_cart_html += "Stamps included?: Yes";						
			}else{
				shopping_cart_html += "Stamps included?: No";										
			}
			
			shopping_cart_html += "</div>";

			shopping_cart_html += "<div class='order_details_right'>";		
			shopping_cart_html += "<div class='price'>"+price+"</div>";		
			shopping_cart_html += "<a href='javascript:void(-1);' id='rp_link"+i+"' class='remove_from_cart'>remove</a>";
			shopping_cart_html += "</div>";			
			shopping_cart_html += "<div style='clear:both;'>&nbsp;</div>";
			shopping_cart_html += "</li>";
		}else if (items[i].type =="product"){
			total += items[i].cost; 			
			shopping_cart_html += "<li>";			
			shopping_cart_html += "<div class='order_details'>";
			shopping_cart_html += items[i].product_name;
			
			
			for (r = 0; r < items[i].attributes.length; r++){
				if (items[i].attributes[r].value != ""){
					shopping_cart_html += "<br />" + items[i].attributes[r].display_name + " - " + displayEncodedHTML(items[i].attributes[r].value);
				}				
			}			
			shopping_cart_html += "</div>"; 
			
			shopping_cart_html += "<div class='order_details_right'>";		
			shopping_cart_html += "<div class='price'>"+items[i].cost+"</div>";		
			shopping_cart_html += "<a href='javascript:void(-1);' id='rp_link"+i+"' class='remove_from_cart'>remove</a>";
			shopping_cart_html += "</div>";			
			shopping_cart_html += "<div style='clear:both;'>&nbsp;</div>";
			
			shopping_cart_html += "</li>";
			
		}
		
	}
	shopping_cart_html += "</ul>";
	calcShippingCost(items.length);
	
	$('#shopping_cart').html(shopping_cart_html);
	
	$('#total').formatCurrency();
	$('.price').formatCurrency();
	
	//update the heading at the top
	var text = 'Your shopping cart contains ';	
	if (items.length > 0){
		text += '';		
		text += items.length;
		if (items.length > 1){
			text += ' items';
		}else{
			text += ' item';
		}
		text += ' <a href="index.php?page=checkout">Check Out</a>';
		
		try{
		$('#but_place_another').css('display', 'block');		
		}catch(e){}
	}else{
		text += '0 items. <a href="index.php?page=add-to-cart">Order now.</a>';
		try{
		$('#but_place_another').css('display', 'none');		
		}catch(e){}
		
	}
	$('#shop_link_text').html(text);

	assignRemovalListners();

	fix_li_items();
	$("#shopping_cart ul li:even").addClass("li_2");
	$("#shopping_cart ul li:odd").addClass("li_1");	
}


function calcShippingCost(itemsInCart){
	try{
		var id = $('select:[name='+sm_frontend_checkout_id+'shipping_cost]').val();
		var code = $('input:[name='+sm_frontend_checkout_id+'promotional_code]').val();
		

		//OLD XAJAX
		//xajax_StationaryManager_CalcShippingCost(id,itemsInCart,code);
		xajax.call('XAJAXManager_callMethod', {parameters:["StationaryManager","StationaryManager_CalcShippingCost", id,itemsInCart,code],mode:'synchronous'});					
	}catch(e){}		
}

var shipping_cost = 0;
function updateShippingCost(newShippingCost){
	shipping_cost = newShippingCost;
	discount = 0;
	$('#shipping_cost').html(shipping_cost);
	$('#shipping_cost').formatCurrency();
	calcTotal();
}

function calcDiscount(){
	var value = $('input:[name='+sm_frontend_checkout_id+'promotional_code]').val();
	var shipping_id = $('select:[name='+sm_frontend_checkout_id+'shipping_cost]').val();	
	//OLD XAJAX
	//xajax_StationaryManager_CalcShippingCost(shipping_id,items.length,value);	
	xajax.call('XAJAXManager_callMethod', {parameters:["StationaryManager","StationaryManager_CalcShippingCost", shipping_id,items.length,value],mode:'synchronous'});	
}
var discount = 0;


//called via xajax
function updateDiscountedPrice(discountIn){	
	discount = discountIn;
	calcTotal();
}

var giftcertificate_amount = 0; 
var giftvoucher_status = '';

function calcTotal(){	
	giftvoucher_status = '';
	giftcertificate_amount = 0;
	//total - stores the line cost of items (including statmp cost and quanity)
	var final_price = total; 

	//add the shipping cost
	final_price += shipping_cost; 
	if (discount > 0){
		final_price = final_price - (final_price * (discount/100));	
	}
	
	var giftcert_code = $('input:[name='+sm_frontend_checkout_id+'giftcertificate_code]').val();
	giftcert_code = $.trim(giftcert_code);
	$('input:[name='+sm_frontend_checkout_id+'giftcertificate_code]').val(giftcert_code);
	
	
	if (giftcert_code != ""){
		//as this particular method is now running SYNCHRONOUSLY the execution will pause until the certifcate is calculated
		xajax.call('XAJAXManager_callMethod', {parameters:["GiftCertificateManager","loadCertificate",giftcert_code],mode:'synchronous'});
		xajax.call('XAJAXManager_callMethod', {parameters:["GiftCertificateManager","getCertificateStatusByCode",giftcert_code],mode:'synchronous'});
		final_price = final_price - giftcertificate_amount;
		if (final_price < 0 && giftvoucher_status =='AC'){
			final_price = 0;
			$('#code_desc').html('Your shopping cart value is less than your voucher amount. Any remaining voucher value will be forfeited. <br /><a href="index.php?page=product-categories">Click here if you would you like to continue shopping to spend the rest of your voucher</a>');
		}else if (giftcertificate_amount > 0 && giftvoucher_status =='AC'){
			$('#code_desc').html('<br />Thank you for using your voucher');
		}else{		
			if (giftvoucher_status == 'RE'){
					$('#code_desc').html('<br />This voucher has already been redeemed.  Please contact Ellis Benson on (03) 9818 0084 for further information.');
			}else{
				$('#code_desc').html('');
			}
		}
	}
	

	
	if (final_price == 0){
		$('.credit_card').css('display', 'none');
	}else{		
		if ( $.browser.msie && $.browser.version <= 7) {
			$('.credit_card').css('display', 'block');
		}else{
			$('.credit_card').css('display', 'table-row');
		}	
	}
	$('.final_submit').css('display', 'block');
	

	if (final_price != 'NaN'){
		$('#total_price').html(final_price);
		$('#total_price').formatCurrency();
		
		try
		{
			$('input:[name='+sm_fc_module_id+'amount]').val(final_price)		
		}
		catch(e){}	
		
	}
	
	
	
}

$(document).ready(function(){ 	
	// array of existing product id to compare
	var shoppingCartArr;
	
	$("#add_to_shopping_cart_tip").hide();
	
	 // hides the my favorites popup
	 
	$('#add_to_shopping_cart').click(function() {		
		if (!$('#agree_chk').is(':checked')){
			 alert("You must confirm that your have reviewed your order by clicking the checkbox");
			 return false;
		}		
		shoppingCartArr = order_collection.items;
		var new_product = {	heading_text: escape($('#heading_text').val()),
							sub_heading_text: escape($('#sub_heading_text').val()),
							text_color: $('input:[name='+fo_module_id+'text_color]').val(),
							position: $('#position').val(),
							font: $('input:[name='+fo_module_id+'font]').val(),
							border_url: $('select:[name='+fo_module_id+'border_url]').val(),
							icon_url: $('input:[name='+fo_module_id+'icon_url]').val(),
							heading_font_size: $('#heading_font_size').val(),
							sh_font_size: $('#sh_font_size ').val(),
							qty: $('select[name='+fo_module_id+'qty]').val(),
							paper_size: $('select[name='+fo_module_id+'paper_size]').val(),							
							stamps_id: $('select[name='+fo_module_id+'stamps_id]').val(),							
							color_name: $('#text_color li.selected .swatch').attr('title'),
							icon_name: $('#icon_url a.selected img').attr('title'),
							font_name: $('#font li.selected span').attr('title')							
							};	
		
		shoppingCartArr.push(new_product);

		var stringified = JSON.stringify(shoppingCartArr);
		
		//OLD XAJAX
		//xajax_StoreClientCartOrders($.cookie(COOKIE_ID), stringified);	
		xajax.call('XAJAXManager_callMethod', {parameters:["StationaryManager","StoreClientCartOrders", $.cookie(COOKIE_ID), stringified],mode:'synchronous'});			
	});		
	//OLD XAJAX
	//xajax_StationaryManager_LoadStationaryCosts();	
	xajax.call('XAJAXManager_callMethod', {parameters:["StationaryManager","StationaryManager_LoadStationaryCosts"],mode:'synchronous'});	
	
});


function finishedAddToCart(){
	updateShoppingCartView();
	// update the cookie for later retieval
	$("#add_to_shopping_cart_tip").text("The item has been added successfully");
	$("#add_to_shopping_cart_tip").fadeIn("slow", callback);		
}

//callback function to bring a hidden box back
function callback(){
	setTimeout(function(){
		$("#add_to_shopping_cart_tip").hide();
	}, 2000);
};

