var PidObj = {};
var mySerializedPid;
var ProductName = '';
var ProductLink = '';
var variationOptionList = new Array();
var jscartPath = "/jscart.php";
var variationsetPath = "/variationset.php";
var variationoptionsPath = "/variationoptions.php";
var smallLoadingGifPath = "/javascript/jqmodal/modload.gif";
var largeLoadingGifPath = "/templates/Nshc/images/Loading.gif";

$(document).ready(function() {
  $('#ex2').jqm({trigger: 'a.AddLink',
   onShow: function(h) {	
      //mySerializedPid = JSON.stringify(PidObj);   
      //$.post(jscartPath,{obj:mySerializedPid},function(data){PrintPage(data)});
      h.w.show();
   },
   onHide: function(h) { 
      h.o.remove(); // remove overlay
      h.w.fadeOut("slow"); // hide window  
  }  
  });
  //On load, preload previous cart contents, if any.	
  
  PidObj = {action: 'get'};
  mySerializedPid = JSON.stringify(PidObj);
  $.post(jscartPath,{obj:mySerializedPid},function(data){PrintPage(data)});
});

function UrlEncode(str) 
{
	return escape(str).replace(/-/g, '%252d').replace(/%20/g, '-');
}

function FormatCurrency(num) 
{
	if (num == null) num = 0;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	{
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	{
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	{	
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	}
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function GetItemTotal(amount, quantity)
{
	return amount * quantity;
}

function GetPath()
{
	//var path = document.location.protocol + '//' + document.location.host;
	var path = 'http://' + window.location.hostname;
/*
	if ((document.location.pathname == '/') == false)
	{	
		path += document.location.pathname;
		path = path.substring(0,path.length - 1);
	}
*/	
	return path;
}

function PrintPage(data)
{
	var htmlcontent = '';
	eval("cart="+data);
	var elem = document.getElementById("ex2");
	if (cart.status === 1)
	{
		//var path = GetPath();
		var CartTotal = 0;
		htmlcontent += '<div align="right"><img src="/javascript/jqmodal/close.gif" onclick="javascript:$(\'#ex2\').jqmHide();"></div>';	
		htmlcontent += '<div id="CartErrorMessage" class="Block Moveable Panel" style="display:none;">';
		htmlcontent += '<p id="ErrorMsgArea" class="ErrorMessage">test</p></div>';
		htmlcontent += '<div class="Block Moveable Panel" id="CartHeader"><h2>Your Shopping Cart</h2></div>';
		
		//Add 'edit cart' to top of window?
		//htmlcontent += '<div class="FloatLeft" style="display:"><a href="' + path + '/cart.php" title="Edit your Cart"><img src="' + path + '/templates/Custom2/images/yellow/EditCart.gif" alt="" /></a></div>';		
		
		htmlcontent += '<div class="ProceedToCheckout"><div class="CheckoutButton" style=""><a href="/checkout.php" title="Click here to proceed to checkout"><img src="/templates/Custom2/images/yellow/CheckoutButton.gif" alt="" /></a></div>';
		htmlcontent += '<table id= "CartTable" class="CartContents Stylize General" cellspacing="0" cellpadding="0">';
		htmlcontent += '<thead><tr><th colspan="2">Cart Items</th><th style="text-align: center; white-space: nowrap;">Qty</th><th style="text-align: center; white-space: nowrap;">Item Price</th><th style="text-align: right; white-space: nowrap;">Item Total</th></tr></thead><tbody>';

		for (var i=0; i< cart.product_count; i++)
		{
			var productPath = '/products.php?product=' + cart[i].product_name;
			var itemTotal = GetItemTotal(cart[i].product_price, cart[i].quantity);
			var imagePath = '/product_images/' + cart[i].data.imagefile;
			var cid = '';
			var variationDescription = '';
			if (cart[i].variation_id > 0) 
			{
				cid = 'Cid' + cart[i].variation_id.toString();
				variationDescription = '<br><small>(';
				jQuery.each(cart[i].options, function(key, value)
				{
					variationDescription += key.toString() + ':' + value.toString() + ', ';
				});
				//remove last comma and space.
			    variationDescription = variationDescription.substring(0, variationDescription.length - 2);
				variationDescription += ')</small><br>';
			}
			CartTotal += itemTotal;
			htmlcontent += '<tr id="Pid' + cart[i].product_id + cid + '">';
			htmlcontent += '<td class="CartThumb" style=""><a href="' + productPath + '"><img src="' + imagePath + '" alt="" /></a>&nbsp;</td>';
			htmlcontent += '<td class="ProductName" colspan="1"><a href="' + productPath + '">' + cart[i].product_name + '</a>' + variationDescription + '</td>';
			htmlcontent += '<td id="Qty' + cart[i].product_id +  + cid + '" align="center" class="CartItemQuantity">' + cart[i].quantity + '</td>';
			htmlcontent += '<td id="PrcCell' + cart[i].product_id +  + cid + '" align="center" class="CartItemIndividualPrice">' + FormatCurrency(cart[i].product_price) + '</td>';
			htmlcontent += '<td id="TotalPrcCell' + cart[i].product_id +  + cid + '" align="right" class="CartItemTotalPrice"><em class="ProductPrice">' + FormatCurrency(itemTotal) + '</em></td>';
			htmlcontent += '</tr>';
			
		}
		htmlcontent += '<tr class="SubTotal"><td colspan="4">Items:</td><td id="ItemsLabel"><em class="ProductPrice">' + FormatCurrency(CartTotal) + '</em></td></tr>';
		htmlcontent += '<tr class="SubTotal"><td colspan="4">Subtotal:</td><td id="SubtotalLabel"><em class="ProductPrice">' + FormatCurrency(CartTotal) + '</em></td></tr>';
		htmlcontent += '</tbody></table>';
		htmlcontent += '<div class="FloatLeft" style="display:"><a href="/cart.php" title="Edit your Cart"><img src="/templates/Custom2/images/yellow/EditCart.gif" alt="" /></a></div>';		
		htmlcontent += '<div class="ProceedToCheckout"><div class="CheckoutButton" style=""><a href="/checkout.php" title="Click here to proceed to checkout"><img src="/templates/Custom2/images/yellow/CheckoutButton.gif" alt="" /></a></div></div>';
		elem.innerHTML = htmlcontent;
	}
	else
	{
		elem.innerHTML = 'An error occurred in generating your shopping cart. Code:' + cart.error_code + ' </b>';
	}
}

function GetResult(data, ProductIdWithUpdate)
{
	eval("cart="+data);
	var Quantity = 0;
	var ItemPrice = 0;
	var PidItemTotal = 0;
	if (cart.status === 1)
	{
		var CartTotal = 0;	
		for (var i=0; i< cart.product_count; i++)
		{
			var itemTotal = GetItemTotal(cart[i].product_price, cart[i].quantity);
			CartTotal += itemTotal;
			
			//if this is the current updating item, save values.
			if (cart[i].product_id == ProductIdWithUpdate)
			{
				Quantity = cart[i].quantity;
				ItemPrice = cart[i].product_price;
				PidItemTotal = itemTotal;
			}
		}	
		document.getElementById('Qty' + ProductIdWithUpdate).innerHTML = Quantity;
		document.getElementById('PrcCell' + ProductIdWithUpdate).innerHTML = FormatCurrency(ItemPrice);
		document.getElementById('TotalPrcCell' + ProductIdWithUpdate).innerHTML = '<em class="ProductPrice">' + FormatCurrency(PidItemTotal) + '</em>';			
		document.getElementById('ItemsLabel').innerHTML = '<em class="ProductPrice">' + FormatCurrency(CartTotal) + '</em>';			
		document.getElementById('SubtotalLabel').innerHTML = '<em class="ProductPrice">' + FormatCurrency(CartTotal) + '</em>';
	}
	else
	{
		alert('An error occurred while updating your cart. Code: ' + cart.error_code);
		$('#ex2').jqmHide();
    		PidObj = {action: 'get'};
	        mySerializedPid = JSON.stringify(PidObj);
		$.post(jscartPath,{obj:mySerializedPid},function(data){PrintPage(data)});		
	}
}

function UpdateCart(operation, p, q, pname, plink, pimg)
{
	if (q == null) q = 1;
	PidObj = {action: operation, pid: p, qty: q};
	ProductName = pname;
	ProductLink = plink;
	var table = document.getElementById("CartTable");
	
	if (document.getElementById('Pid' + p) != null)
	{
		var row = document.getElementById('Pid' + p);
		table.deleteRow(row.rowIndex);	
	}
	
	var newRow = table.insertRow(1);
	newRow.setAttribute('id', 'Pid' + p);

	var newCell = newRow.insertCell(0);
	newCell.setAttribute('class', 'CartThumb');
	newCell.setAttribute('style', '');
	newCell.innerHTML = '<a href="' + plink + '"><img src="' + pimg + '" alt="" /></a>&nbsp;';

	newCell = newRow.insertCell(1);
	newCell.setAttribute('class', 'ProductName');
	newCell.setAttribute('colspan', '1');
	newCell.innerHTML = '<a href="' + plink + '">' + pname + '</a>';

	newCell = newRow.insertCell(2);
	newCell.setAttribute('id', 'Qty' + p);	
	newCell.setAttribute('align', 'center');
	newCell.setAttribute('class', 'CartItemQuantity');
	newCell.innerHTML = '<img src="javascript/jqmodal/modload.gif">';

	newCell = newRow.insertCell(3);
	newCell.setAttribute('id', 'PrcCell' + p);		
	newCell.setAttribute('align', 'center');
	newCell.setAttribute('class', 'CartItemIndividualPrice');
	newCell.innerHTML = '<img src="javascript/jqmodal/modload.gif">';

	newCell = newRow.insertCell(4);
	newCell.setAttribute('id', 'TotalPrcCell' + p);
	newCell.setAttribute('align', 'right');
	newCell.setAttribute('class', 'CartItemTotalPrice');//TotalPrcCell
	newCell.innerHTML = '<em class="ProductPrice"><img src="javascript/jqmodal/modload.gif"></em>';
	
	document.getElementById('ItemsLabel').innerHTML = '<em class="ProductPrice"><img src="javascript/jqmodal/modload.gif"></em>';			
	document.getElementById('SubtotalLabel').innerHTML = '<em class="ProductPrice"><img src="javascript/jqmodal/modload.gif"></em>';
	
	mySerializedPid = JSON.stringify(PidObj);   
	$.post(jscartPath,{obj:mySerializedPid},function(data){GetResult(data,p)});
}
