var jsonCart = null;
var cartDiv = null;
var cartTimerId = 0;

function addToCart(form, button) {
	var softAdd = true;
	if (global_URL_Encode_Current_ProductCode.toUpperCase() =="GFT") {
		softAdd = false;
	}
	if (!softAdd) {
		return true;
	}
	else {
		var qstr;
	  var bttnName = button.name;
		button.disabled = true;
		if (form.elements['ReturnTo']) {
			form.elements['ReturnTo'].value = "";
		}
		qstr = serialize(form, bttnName + '.x', '5', bttnName + '.y', '5');
		sendAjax('POST','/ProductDetails.asp?ProductCode=' + global_URL_Encode_Current_ProductCode + '&AjaxError=Y', qstr, retrieveProductError ,displayServerError,false);
		button.disabled = false;
		return false;
	}
}

function removeFromCart(index)
{
	sendAjax('GET','/ShoppingCart.asp?remove=' + index, '', retrieveCart, null, false);
}

function retrieveProductError(result, statusCode) {
	var ele = document.getElementById('listOfErrorsSpan');
	var errorIndex = result.indexOf('<carterror>');
	var productIndex = result.indexOf('<ProductIndex>');
	
	if (errorIndex != -1) {
		ele.innerHTML = result.slice(errorIndex + 11, result.indexOf('</carterror>'));
	}
	else {
		ele.innerHTML = "";
		if (productIndex == -1) {
		sendAjax('GET','/AjaxCart.asp?GetIndex=True', '', showCart, null, false);
		}
		else {
		productIndex = result.slice(productIndex + 14, result.indexOf('</ProductIndex>'));
		sendAjax('GET','/AjaxCart.asp?Index=' + productIndex, '', showCart, null, false);
		}
	}
}

function displayServerError(result, statusCode) {
	if (statusCode = 500) {
		var ele = document.getElementById('listOfErrorsSpan');
	ele.innerHTML = "<table width=500 border=0 cellpadding=10 cellspacing=3 bgcolor=#CC0000><tr><td bgcolor=#FFFFFF><font color=#FFFFFF face=sans-serif><strong><font color=#CC0000>An error has occurred.</font></strong></font> Please try your request again, or contact customer service for assistance. Thank you.<br><font color=999999>Please provide Reference #000000 if contacting customer service.</font></td></tr></table>";
	}
}

function buildCartFromJson(result, statusCode)
{
	jsonCart = eval('(' + result + ')');
}

function retrieveCart()
{
	sendAjax('GET','/AjaxCart.asp' , '', showCart, null, false);
}

function showCart(result, statusCode)
{
	var drawIndex = 0;
	buildCartFromJson(result, statusCode);
	drawIndex = parseInt(jsonCart.Totals[0].LastProduct);
	drawCart(drawIndex);
}

function getLineItemHTML(product)
{
	var productHTML, imageSource, productName, quantity, productPrice, hasOptions, productIndex, isProduct;

	product.ImageSource == undefined ? imageSource = '' : imageSource = '<img src="' + product.ImageSource + '" height="50px" width="50px"/>';
	product.ProductIndex == undefined ? productIndex = '' : productIndex = product.ProductIndex;
	product.ProductName == undefined ? productName = '' : productName = product.ProductName;
	product.ProductPrice == undefined ? productPrice = '' : productPrice = product.ProductPrice;
	product.HasOptions == undefined ? hasOptions = 'N' : hasOptions = product.HasOptions;
	product.IsProduct == undefined ? isProduct = 'N' : isProduct = product.IsProduct;
	product.Quantity == undefined ? quantity = '' : quantity = product.Quantity;
	productHTML = '<tr><td class="icon">' + imageSource + '</td>';
	productHTML += '<td class="description"><span class="product_name">' + productName + '</span>';
	productHTML += '<span class="product_id">'
		// 12/24/2009 Pavel Shklenik VSIX-1091 Soft add to cart "Options" link fails when SEO friendly is enabled
		if (hasOptions == "Y") {
			productHTML += '<a href="javascript:void(0);" onclick="javascript:OpenNewWindow(\'/Help_CartItemDetails.asp?CartID=' + product.ProductIndex + '\',\'425\',\'300\');">Options</a>';
		}
	productHTML += '</span></td>';
  productHTML += '<td class="quantity">' + quantity + '</td>';
  productHTML += '<td class="price"><span id="product_price">' + productPrice + '</span></td>';
  productHTML += '<td class="remove">';
	if (isProduct == "Y") {
		productHTML += '<a href="" class="aremove" onclick="removeFromCart(' + productIndex + '); return false;">remove</a>';
	}
	productHTML += '</td></tr>';
	return productHTML;
}

function drawCart(index)
{
	var quantity;
	var cartTotal;
	var discountTotal;
	var cartLength = 0;
	if (jsonCart != null) {
		cartLength = jsonCart.Products.length;
	}

	quantity = jsonCart.Totals[0].Quantity;
	cartTotal = jsonCart.Totals[0].CartTotal;
	discountTotal = jsonCart.Totals[0].DiscountTotal;

	var i = 0;
	var cartHTML = '<div class="soft_add_wrapper" onmouseover="setTimer();">';
	cartHTML += '<div class="soft_add_header_shadow">';
  cartHTML += '<div class="soft_add_header"><span class="soft_add_span">Added to cart</span><a href="" class="close_btn" onclick="hideCart(); return false;">Close</a></div></div>'
	cartHTML += '<div class="soft_add_content_shadow"><div class="soft_add_content_wrapper">';
	cartHTML += '<div class="soft_add_content_area" onscroll="setTimer();"><table class="cart_table" cellpadding="0" cellspacing="0" border="0">';
	if (cartLength != 0) {
		cartHTML += cartLoop(index, cartLength);
		if (index != 0) {
			cartHTML += cartLoop(0, index);
		}
		if (discountTotal != "0") {
			var discountProduct = {
    		ProductName: "Discount(s)",
    		ProductPrice: '<span style="color:red">' + discountTotal + '</span>'
			}
			cartHTML += getLineItemHTML(discountProduct);
		}
	}
	cartHTML += '</table></div><div class="soft_add_sub_total"><div class="number_of_items">' + quantity + ' items in cart</div>';
  cartHTML += '<div class="sub_total">';
	cartHTML += 'Subtotal: <span class="sub_total_amount">' + cartTotal + '</span>';
	cartHTML += '</div>';
  cartHTML += '</div><div class="soft_add_action_area"><a href="/ShoppingCart.asp" class="check_out">Check Out</a>';
	cartHTML += '<a href="" class="continue_shopping" onclick="hideCart(); return false;">Continue shopping</a></div></div></div></div>';
	if (cartDiv == null) {
		cartDiv = document.createElement('div');
		document.body.appendChild(cartDiv);
	}
	cartDiv.innerHTML = cartHTML;
	setTimer();
}

function hideCart()
{
	clearTimer();
	if (cartDiv != null)
	{
		cartDiv.innerHTML = "";
	}
}

function addCartLink()
{
	var sPath = window.location.pathname;
	if (sPath.substring(sPath.lastIndexOf('/') + 1).toLowerCase() != 'shoppingcart.asp') {
		var aElements = document.getElementsByTagName('a');
		for (var i=0; i < aElements.length; i++) {
    	if(aElements[i].href.match(/shoppingcart\.asp$/i) != null) {
				aElements[i].onmouseover = retrieveCart;
				break;
			}
		}
	}
}

function setTimer()
{
	clearTimer();
	cartTimerId = setTimeout('hideCart();', 10000);
}

function clearTimer()
{
	if (cartTimerId != 0) {
		clearTimeout(cartTimerId);
		cartTimerId = 0;
	}
}

function cartLoop(start, length)
{
	var loopHTML = "";
	for (i=start;i<length;i++) {
		if (jsonCart.Products[i].Display == "Y") {
			loopHTML += getLineItemHTML(jsonCart.Products[i]);
		}
	}
	return loopHTML;
}