/* ---------->>> Shopping Cart Functions <<<-------------------------------------------------*/
jQuery(function($) { 	
	// Validate input as either a canadian or US postal code
	$("#zipcode").keyup(function() {
		if(this.value.length >= 5 && isNaN(this.value)) {
			postal_type = 'CA';
		} else if(this.value.length == 5 && parseInt(this.value))  {
			postal_type = 'US';
		}
		
		if(document.getElementById("shippingMethod").value == '') {
			$("#shippingMethod").css("backgroundColor","#f7f265");
		}

	});
	
	
	// Validate fields before submitting ajax command to update basket data
	$("a.zip-go").click(function() {
		shippingMethod = document.getElementById("shippingMethod").value;
		zipcode = document.getElementById("zipcode").value;

		if(shippingMethod == '' || zipcode.length < 5) {
			confirm("You must enter a valid ZipCode and select a shipper to continue",false);
			return false;
		} else {
			setCommand("update",'','');
			return true;
		}
	});
	
});

function confirm(message, callback) {
	//Set callback to false if you just want to alert. Otherwise use a function call.
	$('#confirm').modal({
		closeHTML:"<a href='#' title='Close' class='modal-close'>x</a>",
		position: ["20%",],
		overlayId:'confirm-overlay',
		containerId:'confirm-container',
		modal: true,
		onShow: function (dialog) {
			$('.message', dialog.data[0]).append(message);
			
			if($.isFunction(callback)) {
				// if the user clicks "yes"
				$('.yes', dialog.data[0]).click(function () {
					// call the callback
					if ($.isFunction(callback)) {
						callback.apply();
					} 
					// close the dialog
					$.modal.close();
					return false;
				});

			} else {
				$("#confirm span").html("Warning!");
				$('.yes').css({'display':'none'});
				$('.no').html("Ok").click(function () {
					$.modal.close();
					return false;
				});
			}
		}
	});
}


function updateSessionData() {
	// update session data when ajax call is made for debugging.
	$.post("shopping/getbasket.php", {sessionid: session_id, cmd:'showsessiondata'}, 
		function(data){						
			if (data.length > 0){
				$('#showsessiondata').html(data);
			}
		}
	);
}

// Primary cart update function initiated by flash configurator 
function updateCart(data) {	
	$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});

	$.post("shopping/getbasket.php", {sessionid: session_id, orderid: order_id},
		function(data) { 
			var json_obj = eval("(" + data + ")");
			$("#cart_basket").html(json_obj.minicart);
			$("#cart_status").html(json_obj.cartstatus);
		}, "html" 
	);

}

function setCommand(cmd, itemid, qty) {	
	$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});
	
	//sessionid & orderid is set globally in header.php
	var processor = "shopping/getbasket.php";
	var params = {cmd:cmd, sessionid:session_id, orderid:order_id, basketid: itemid, quantity: qty, zipcode: zipcode, shippingMethod:shippingMethod};

	if(cmd == "display" || cmd == "update" || cmd == "add" || cmd == "addstock") {
		$.post(processor, params , function(data) { 
				var json_obj = eval("(" + data + ")");
					if(json_obj.stockitem.length > 0) {
						$.get("shopping/update_cart.php", {data: json_obj.stockitem},function(data) {}, "html");
						window.location.href = "customfoam.php";
					}
				
				var cartobj = document.getElementById("cart_basket");

				if(cartobj != null) {
					$("#cart_basket").html(json_obj.minicart);
				}
				$("#cart_status").html(json_obj.cartstatus);
			}, "html" );  
		
	} else if(cmd == "delete") {
		confirm("Are you sure you want to remove this item from cart?", function() {
			$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});
			$.post(processor, params, function(data) { 
				var json_obj = eval("(" + data + ")"); 
				$("#cart_basket").html(json_obj.minicart);
				$("#cart_status").html(json_obj.cartstatus);					
			}, "html" );		
		});
	} else if(cmd == "empty") {
		confirm("Are you sure you want to empty the entire cart?", function() {
			$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});
			$.post(processor, params, function(data) { 
				var json_obj = eval("(" + data + ")"); 
				$("#cart_basket").html(json_obj.minicart);
				$("#cart_status").html(json_obj.cartstatus);					
			}, "html" );
		});
	} 
	return false;
}

function showCartOnConfirm() {
	$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});

	// update session data when ajax call is made for debugging.
	$.getJSON("shopping/getbasket.php", {sessionid: session_id, orderid: order_id}, 
		function(data){						
			if (data.viewcart.length > 0){
				//$("div#viewcart-container").html(data.viewcart);
				//Using classic javascript for compatibility with IE.
				document.getElementById("viewcart-container").innerHTML = data.viewcart;
			} else {
				//$("#viewcart-container").html("There was an error..");
				//Using classic javascript for compatibility with IE.
				document.getElementById("viewcart-container").innerHTML = "There was an error...";
			}
		}
	);
}

function updateShipMethod(ship_code) {
	$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});

	// update shipping radio button display with cost when clicked
	zipcode = $("#shipping_zip").val();
	shipcode = ship_code;
	
	$.getJSON("shopping/getbasket.php", {sessionid: session_id, cmd : 'getShippingCostSelectBox', zipcode : zipcode, shippingMethod: shipcode}, 
		function(data){	
			if (data.shippingdata.length > 0){
				$('#shipping_method_box').html(data.shippingdata);
				$("#cart_status").html(data.cartstatus);
			}
		}
	);
}

// Function removes options from Item in basket ie. Dacron, Bullnose or Rounded Edges 
function removeOption(basket_id, bullnose, dacron, rounded) {
	confirm("Are you sure you want to remove this option?", function() {	
		$("#cartlogo").attr({src : "media/images/cart/progress.grey.gif"});

		$.post("shopping/getbasket.php", {sessionid: session_id, orderid: order_id, cmd: 'removeoption', basketid: basket_id, bull: bullnose, dacron: dacron, rnd_edge: rounded}, function(data) {
			var json_obj = eval("(" + data + ")");
			var cartobj = document.getElementById("cart_basket");

			if(cartobj != null) {
				$("#cart_basket").html(json_obj.minicart);
			}
			$("#cart_status").html(json_obj.cartstatus);
		}, "html" );
	});

	return false;
}

function isNumericVal(qty, itemid){
	var re = /^\d+(?:\.\d*)?$/;
	if(qty.value.match(re)) {
		if(qty.value == 0) {
			setCommand("delete", itemid, "");
		} else {
			setCommand("update", itemid, qty.value);
		}		
	} else {
	  confirm('Please only enter numeric values.',false);
	  qty.value = document.getElementById('storeQty').value;
	}

}

function storeQtyTemp(theField) {
	document.getElementById('storeQty').value = theField.value;
}

function expandItem(divname,thislink) {
	$('#'+divname).toggle();
	$(thislink).toggleClass('minimizeDetail');
}

function getkey(e) {
	if (window.event)
	   return window.event.keyCode;
	else if (e)
	   return e.which;
	else
	   return null;
}

function goodchars(e, goods) {
	var key, keychar;
	key = getkey(e);
	if (key == null) return true;

	// get character
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	goods = goods.toLowerCase();

	// check goodkeys
	if (goods.indexOf(keychar) != -1)
			return true;

	// control keys
	if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
	   return true;

	// else return false
	return false;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function validateCreditCard(s) {

	// remove non-numerics
	var v = "0123456789";
	var w = "";
	for (i=0; i < s.length; i++) {
		x = s.charAt(i);
		if (v.indexOf(x,0) != -1)
		w += x;
	}
	
	// validate number
	j = w.length / 2;
	if (j < 6.5 || j > 8 || j == 7) return false;
	k = Math.floor(j);
	m = Math.ceil(j) - k;
	c = 0;
	for (i=0; i<k; i++) {
		a = w.charAt(i*2+m) * 2;
		c += a > 9 ? Math.floor(a/10 + a%10) : a;
	}
	for (i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
	return (c%10 == 0);

}

function validateStartedOrder() {
	var started_order = $("#started_order").val();

	if(started_order == 0) { 
		confirm("Can not continue until you have items in your cart",false); 
		return false;
	} else return true;
}

function confirmBillingEmail() {
	
	if ($('#email2').val() == $('#bill_email').val()) {
		return true;
	} else {
		return false; 
	}
	
}	

function updatePrice(item_id){
	$('#itemvalue').val(item_id);
	
	var prod_cost = 0;
	var prod_quantity = 0;
	var getItemPrice = 0;
	var size = $('#size_'+item_id+' :selected').text();
	var productid = $('#size_'+item_id+' :selected').val();
	var price_flag = $('#size_'+item_id+' :selected').attr('title');
	var board_foot_price = $('#size_'+item_id+' :selected').attr('id');

		getItemPrice = stockItems.item[productid].price;
		getItemTitle = stockItems.item[productid].title;
		getItemDescr = stockItems.item[productid].descr;
		getItemId = stockItems.item[productid].itemid;

	if(!size){
		$('#slabprice_'+item_id).html();
		$('#slabtotal_'+item_id).html();
		return;
	}
	size = size.split( /\s*[x|X]\s*/ );

	if(size.length < 3 || price_flag == 1){
		
		//Get price of item
		var optionCnt = document.getElementById('size_'+item_id);

		//Add price adjustment if set in configuration table
		getItemPrice = (parseFloat(getItemPrice)+parseFloat(((getItemPrice/100)*price_adjust))).toFixed(2);
		prod_quantity = document.getElementById('qty_'+item_id).value.replace(/\D/g ,'').substr(0,3);

		//Calculate extended cost based on quantity
		prod_cost = (Math.round(getItemPrice*prod_quantity*100)/100);;
		$('#slabprice_'+item_id).html('$'+getItemPrice);
		$('#qty_'+item_id).val(prod_quantity);
		
		document.getElementById('slabtotal_'+item_id).innerHTML = '$'+(prod_cost).toFixed(2);
		document.getElementById('tipItemid_'+item_id).innerHTML = getItemId;
		document.getElementById('tipDescr_'+item_id).innerHTML = getItemDescr;
		document.getElementById('prodDescr_'+item_id).innerHTML = getItemTitle;
	} else {
		//Get price of item
		var board_foot = ((size[2]*size[1]*size[0])/144);
		getItemPrice = (board_foot * board_foot_price);		

		//Add price adjustment if set in configuration table
		getItemPrice = (parseFloat(getItemPrice)+parseFloat(((getItemPrice/100)*price_adjust))).toFixed(2);
		prod_quantity = document.getElementById('qty_'+item_id).value.replace(/\D/g ,'').substr(0,3);

		prod_cost = (Math.round(getItemPrice*prod_quantity*100)/100);
		$('#slabprice_'+item_id).html('$'+getItemPrice);
		$('#qty_'+item_id).val(prod_quantity);	

		document.getElementById('slabtotal_'+item_id).innerHTML = '$'+(prod_cost).toFixed(2);
		document.getElementById('tipItemid_'+item_id).innerHTML = getItemId;
		document.getElementById('tipDescr_'+item_id).innerHTML = getItemDescr;
		document.getElementById('prodDescr_'+item_id).innerHTML = getItemTitle;
	}
}

function getTooltip(this_elem) {
	//Grab needed elements: image path and hidden tooltip div 
	var infoTip_elem = document.getElementById('cart_info');
	var imgPath = this_elem.getAttribute('rel');
	
	// Make our tip visible and put in out image
	infoTip_elem.style.display = 'block';
	infoTip_elem.innerHTML = '<img src=\"'+imgPath+'\">';
	var cTip_height = infoTip_elem.offsetHeight;

	// Detect location of mouse and set distance of tip from mouseovered element
	$(document).mousemove(function(e) {
		infoTip_elem.style.top = ( e.pageY - ( 10 + cTip_height ) ) + 'px';
		infoTip_elem.style.left = (e.pageX + 10) + 'px';
		
		//Detect current target under mouse. If it doesnt match our selected element, then hide tip
		if (!e) var e = window.event;
		var tg = (window.event) ? e.srcElement : e.target;
		if (tg.nodeName != 'A') infoTip_elem.style.display = 'none';

	});

}

// old school cookie functions grabbed off the web
var Cookies = {};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
}

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
}

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
}