/* Javascripts related to the Variation Select Window - March 10, 2010*/

//this contains the array of objects which contain info on the products on a page.

var products = new Object();
var	imageSet = new Array();
var cache = [];
var productIdVariationWindow = 0;
var pairObjects = new Array();
var clearObject;
var disableLoadingIndicator = false;
var jsonLoaded = false;
var callcount = 0;
var responsecount = 0;
var stritem = '';
var executedready = 0;
var countElementsOnPage = 0;
var showCart = true;

var onDemandImageLoaded = false;
var onDemandOptionsLoaded = false;

var newOverlayHeight = 0;

//prepare variation select windows
$(document).ready(function(){
	//Variation Select Window events/properties
	$('#variationSnapShot').jqm({
		trigger: 'a.ChooseLink',
		onShow: function(h)
		{
			$('#OutOfStockMessage').html('');
			$('#OutOfStockMessage').css('height','38px');
			$('#OutOfStockMessage').css('padding-top','0px');
			$('#OutOfStockMessage').css('padding-bottom','0px');			
			if (jsonLoaded == false)
			{
				ShowLoadingOnOverlay();
			}

			//remove scrollbars
			$('#variationSnapShot').css('height','515px');
			h.w.show();		
			/*
			elem = document.getElementById('variationSnapShot');
			  if (elem.clientHeight < elem.scrollHeight)
				alert(elem.clientHeight + "," + elem.scrollHeight + ",The element has a vertical scrollbar!");
			   else
				alert(elem.clientHeight + "," + elem.scrollHeight + ",The element doesn't have a vertical scrollbar.");
			*/
			scroll(0,0);
			if ((onDemandOptionsLoaded) && (onDemandImageLoaded) && (typeof isIE6 === 'undefined'))
			{			
				var elem = document.getElementById('variationSnapShot');
				$('#variationSnapShot').css('height',elem.scrollHeight);
				newOverlayHeight = elem.scrollHeight;
			}
			//alert(elem.clientHeight + "," + elem.scrollHeight);
			if (typeof isIE6 === 'undefined')
			{
				//don't do anything
			}
			else
			{
				//Form elements in IE6 are always on top of other elements, so this will be hidden instead.
				//alert('Hello IE6');
				$('#Cat').attr("disabled","disabled");
				$('#Cat').css("display","none");
				$('#Color').attr("disabled","disabled");
				$('#Color').css("display","none");
				$('#Color2').attr("disabled","disabled");
				$('#Color2').css("display","none");					
				//$('#OutOfStockMessage').
				//$('#OutOfStockMessage').
			}
		},
		onHide: function(h)
		{
			$('#variationSnapShot').css('height','515px');
			$('#standardImage').removeAttr('height');
			$('#standardImage').removeAttr('width');		
			HideLoadingOnOverlay();		
			h.o.remove();
			$('#OutOfStockMessage').html('');
			$('#OutOfStockMessage').css('height','38px');
			$('#OutOfStockMessage').css('padding-top','0px');
			$('#OutOfStockMessage').css('padding-bottom','0px');				
			document.getElementById('productPrice').innerHTML = '<img src="' + config.ShopPath + smallLoadingGifPath + '">';
			document.getElementById('currentStock').innerHTML = '<img src="' + config.ShopPath + smallLoadingGifPath + '">';
			document.getElementById('standardImage').src = config.ShopPath + largeLoadingGifPath;
			document.getElementById('variationsContainer').innerHTML = '<center>Loading Options...<br><br><img src="' + config.ShopPath + smallLoadingGifPath + '"></center>';		
			document.getElementById('clipQty').value = '1';
			//h.w.fadeOut("fast");
			h.w.hide();
			if (typeof isIE6 === 'undefined')
			{
				//don't do anything
			}
			else
			{
				$('#Cat').removeAttr("disabled","disabled");
				$('#Cat').css("display","");
				$('#Color').removeAttr("disabled","disabled");
				$('#Color').css("display","");
				$('#Color2').removeAttr("disabled","disabled");
				$('#Color2').css("display","");					
			}			
		}
	});
	$('#AddToCartArea').hide();
	$('#AddToCartButton').hide();
	
	hideAddToCartOnPage();
});

function resizeProductImageOnOverlay()
{
	
	$('#standardImage').css('display','none');

	//Resize image if needed
	var imagePath = document.getElementById('standardImage').src;
	//alert(imagePath);
	var productImage = new Image();
	productImage.src = imagePath;
	$('#standardImage').removeAttr('height');
	$('#standardImage').removeAttr('width');	
	
	//productImage.onload = function()
	//{
		//$('#standardImage').css('display','none');
		document.getElementById('standardImage').src = imagePath;	
		var productImageWidth = productImage.width;
		var productImageHeight = productImage.height;
		$('#standardImage').css('width','');
		$('#standardImage').css('height','');

		if ((productImageWidth > productImageHeight) && (productImageWidth > 220))
		{
			$('#standardImage').attr('width',210);
			$('#standardImage').removeAttr('height');
			$('#standardImage').css('height','');
			
		}
		else if ((productImageHeight > productImageWidth) && (productImageHeight > 220))
		{
			$('#standardImage').attr('height',210);
			$('#standardImage').removeAttr('width');
			$('#standardImage').css('width','');
		}
		else if ((productImageWidth > 220) &&  (productImageHeight > 220))
		{
			$('#standardImage').attr('height',210);
			$('#standardImage').attr('width',210);
			$('#standardImage').css('width','');
			$('#standardImage').css('height','');			
		}
		$('#standardImage').css('display','');

		var elem = document.getElementById('variationSnapShot');
		
		if (typeof isIE6 === 'undefined')
		{
			$('#variationSnapShot').css('height',newOverlayHeight);
			if (elem.clientHeight < elem.scrollHeight)
			{
				$('#variationSnapShot').css('height',elem.scrollHeight);
			}
		}
	//}

	//document.getElementById('standardImage').src = config.ShopPath + largeLoadingGifPath;
}


function showFloatingButton(productId)
{
	$('.floatButton').hide();
	var floatName = '#float' + productId;
	var linkName = '#link' + productId;
	$(floatName).show();
	
	if ($(linkName).attr("onclick") == '')
	{
		alert('test');
	}
}

function hideFloatingButton()
{
	$('.floatButton').hide();
}

function tweetButton()
{
	if (document.getElementById('tweetMeme'))
	{
		// Get page URL
		var _url = window.location.href;

		// Remove illegal characters
		var _url = _url.replace(/((?:\?|&)?fbc_receiver=.+)?(?:#.*)?$/, "");

		// Convert your custom script parameters into local JavaScript variables.
		// Make sure they are strings and escape illegal characters.
		var url = escape(typeof tweetmeme_url == "string" ? tweetmeme_url : typeof TWEETMEME_URL == "string" ? TWEETMEME_URL : _url).replace(/\+/g, "%2b");
	
		var tweetVar="";
		tweetVar += "<iframe src=\"http:\/\/api.tweetmeme.com\/button.js?url=" +url+ "&amp;style=normal&amp;\" scrolling=\"no\" frameborder=\"0\" width=\"50\" height=\"61\" ><\/iframe> ";
		$('#tweetMeme').append(tweetVar);
	}
}

//request five products at a time
function init()
{
	//load Twitter button if the div is on the page.
	//Disabled at NSHCs request - June 22
	//tweetButton();
	
	//preload loading GIFs
	var smallLoadingImage = new Image();
	smallLoadingImage.src = config.ShopPath + smallLoadingGifPath;
	var largeLoadingImage = new Image();
	largeLoadingImage.src = config.ShopPath + largeLoadingGifPath;
	
	//debug
	executedready++;
	jQuery.each(products, function(key, value)
	{ 
		countElementsOnPage++;
	});

	var currentLoopPass = 0;
	var currentList = new Array();	
	var currentElementCount = countElementsOnPage;
	
	jQuery.each(products, function(key, value)
	{ 
		currentList[currentLoopPass] = products[key].id;
		currentLoopPass++;
		currentElementCount = currentElementCount - 1;
		
		if (currentElementCount > 0)
		{
			if (currentLoopPass == 5)
			{
				var joinedList = currentList.join(',');
				currentLoopPass = 0;
				var jsonRequest = {returnset:true, pid: joinedList};
				var serializedRequest = JSON.stringify(jsonRequest);  
				$.post(variationsetPath,{obj:serializedRequest},function(data){storeProductSetData(data)});
				callcount++;					
				currentList = new Array();	
			}
		}
		else
		{
			var joinedList = currentList.join(',');
			var jsonRequest = {returnset:true, pid: joinedList};
			var serializedRequest = JSON.stringify(jsonRequest);  
			$.post(variationsetPath,{obj:serializedRequest},function(data){storeProductSetData(data)});
			callcount++;
		}
		stritem += key + ',';
	});
	
	//Fix issue with long LI elements when the elements havent loaded yet - August 2
		var ele       = $('.Content .ProductList:not(.List) li'),
			maxHeight = 0;

		ele
			// reset the height just in case it was set by the stylesheet so
			// we can detect it
			.css('height', 'auto')
			// get the one with the greatest height
			.each(function() {
				if ($(this).height() > maxHeight) {
					maxHeight = $(this).height();
				}
			})
			// and set them all to the greatest height
			.css('height', maxHeight);	
	
	

}

//process sets of data, instead of just one product per request, X products per request.
function storeProductSetData(data)
{
	eval("response="+data);
	//alert(response.test1);
	responsecount++;
	jQuery.each(response, function(key, value)
	{
		products[key] = response[key];
		//preload images
		
		jQuery.each(products[key], function(item, itemvalue)
		{
			imageSet[imageSet.length] = itemvalue.ThumbPath;
			imageSet[imageSet.length] = itemvalue.StandardImagePath;
		});
		
	});
	if (callcount == responsecount)
	{
		onDemandOptionsLoaded = true;
		ShowAddToCartArea();
		jsonLoaded = true;
		showAddToCartOnPage();
	}

	/* deactivated; there are too many images - May 31
	if (callcount == responsecount)
	{
		//start preloading the images
		preloadImages();
	}
	*/
}

function ShowAddToCartArea()
{
	if ((onDemandOptionsLoaded) && (onDemandImageLoaded))
	{
		resizeProductImageOnOverlay();
		HideLoadingOnOverlay();	
		$('#AddToCartArea').show();
		$('#AddToCartButton').show();

		if (typeof isIE6 === 'undefined')
		{
		
			//remove scrollbars
			$('#variationSnapShot').css('height','515px');
			var elem = document.getElementById('variationSnapShot');
			$('#variationSnapShot').css('height',elem.scrollHeight);
			newOverlayHeight = elem.scrollHeight;
		}			
	}
	//alert(onDemandOptionsLoaded + ',' + onDemandImageLoaded);

}

function preloadImages()
{
    for (var i = imageSet.length - 1; i--;) 
	{
		var cacheImage = document.createElement('img');
		cacheImage.src = imageSet[i];
		cache.push(cacheImage);
    }

}

//Store data on the variations to an array
function storeProductData(data, identifier)
{
	eval("response="+data);
	var indexLocation = 'Pid'+response.productId;	
	products[indexLocation] = response;	
	responsecount++;
}

//This function executes once a user clicks 'Choose Options' on the home/category pages.
function RequestVariationOptions(productId, productName, prodLink)
{
	ShowLoadingOnOverlay();	
	disableLoadingIndicator = true;
	document.getElementById('productNameHeading').innerHTML = productName;
	document.getElementById('ProdLink').value = prodLink;
	
	document.getElementById('productPageLink').href = prodLink;
	document.getElementById('thumbLink').href = prodLink;
	
	var incompleteLoad = false;
	if (products['Pid' + productId].productId == undefined)
	{
		document.getElementById('productPrice').innerHTML = '<img src="' + config.ShopPath + smallLoadingGifPath + '">';
		//document.getElementById('variationsContainer').innerHTML = '<img src="' + config.ShopPath + smallLoadingGifPath + '">';
		document.getElementById('variationsContainer').innerHTML = '<center>Loading Options...<br><br><img src="' + config.ShopPath + smallLoadingGifPath + '"></center>';			
		incompleteLoad = true;	
	}
	else
	{
		document.getElementById('productPrice').innerHTML = products['Pid' + productId].defaultPrice;
		document.getElementById('currentStock').innerHTML = products['Pid' + productId].defaultStock;
		document.getElementById('ProductId').value = products['Pid' + productId].productId;
		document.getElementById('CombinationId').value = products['Pid' + productId].defaultCombinationId;
		document.getElementById('variationsContainer').innerHTML = products['Pid' + productId].variationValues;
		
		document.getElementById('standardImage').src = config.ShopPath + largeLoadingGifPath;

		document.getElementById('ThumbLink').value = products['Pid' + productId].imageFileThumb;
		var temp = products['Pid' + productId].variationOptionsList;
		variationOptionList = temp.split(',');		
		
		var image = new Image();
		image.onload = function()
		{
			onDemandImageLoaded = true;
			$('#standardImage').css('display','none');			
			document.getElementById('standardImage').src = products['Pid' + productId].imageFileStd;
			ShowAddToCartArea();
		}
		image.src = products['Pid' + productId].imageFileStd;
	}
	if (incompleteLoad == true)
	{	
		disableLoadingIndicator = false;
		//if data about the product is not yet available, retrieve it now.
		PidObj = {action: 'getVariationOptions', pid: productId};
		mySerializedPid = JSON.stringify(PidObj);  
		$.post(variationoptionsPath,{obj:mySerializedPid},function(data){GetVariationOptions(data)});	
	}
}

//execute this in case the data is not yet finished downloading via JSON
function GetVariationOptions(data)
{
	eval("options="+data);
	document.getElementById('productPrice').innerHTML = options.defaultPrice;
	document.getElementById('currentStock').innerHTML = options.defaultStock;
	document.getElementById('ProductId').value = options.productId;
	document.getElementById('CombinationId').value = options.defaultCombinationId;	
	document.getElementById('variationsContainer').innerHTML = options.variationValues;
	
	document.getElementById('standardImage').src = config.ShopPath + largeLoadingGifPath;

	document.getElementById('ThumbLink').value = options.imageFileThumb;	
	var temp = options.variationOptionsList;
	variationOptionList = temp.split(',');
	disableLoadingIndicator = false;	
	
	var image = new Image();
	image.onload = function()
	{
		onDemandImageLoaded = true;
		$('#standardImage').css('display','none');
		document.getElementById('standardImage').src = options.imageFileStd;
		ShowAddToCartArea();
	}
	image.src = options.imageFileStd;	
}

function ShowLoadingOnOverlay() {
	$('#OverlayLoading').css('position', 'absolute');
	$('#OverlayLoading').css('top', '1px');
	$('#OverlayLoading').css('left', parseInt((602-150)/2)+"px");
	$('#OverlayLoading').show();
}

function HideLoadingOnOverlay()
{
	$('#OverlayLoading').hide();	
}

//use if (opList.length == opCount). if true, execute this to get the combination.
function findCombination(productId, opList, opCount)
{
	var result = 0;
	
	//iterate through the elements for this product.
	jQuery.each(products['Pid' + productId], function(key, value)
	{ 
		if (key.toString().substr(0,3) == 'Cid')
		{
			//check if this is the matching product variation.
			if (value.vcoptionids == opList.join(','))
			{
				 result = value;
			}
		}
	});		
	return result;
}

function findOptions(productId, opList, opCount)
{
	//build a list of the option IDs that must be enabled.
	//this is based on the option list that is given to this function.
	var result = new Array();
	var count = 0;
	jQuery.each(products['Pid' + productId], function(key, value)
	{ 
		if (key.toString().substr(0,3) == 'Cid')
		{
			if (value.vcoptionids.indexOf(opList.join(',')) > -1)
			{
				//value found, break this vcoptionid list then get the first element that is different.
				var tempOptionIds = value.vcoptionids.split(',');			
				for (var i = 0; i < tempOptionIds.length; i++)
				{
					if (tempOptionIds[i] == opList[i]) 
					{
						continue;
					}
					else
					{
						result[count] = tempOptionIds[i];
						count++;
						break;	
					}
				}				
			}
		}			
	});
	return result;
}

function loadVariationOnWindow(prodId, itemNumber, itemValue, variationCount)
{

	$('#standardImage').removeAttr('height');
	$('#standardImage').removeAttr('width');
	$('#OutOfStockMessage').css('height','38px');
	$('#OutOfStockMessage').css('padding-top','0px');
	$('#OutOfStockMessage').css('padding-bottom','0px');			
	$('#OutOfStockMessage').html('');
	if (typeof isIE6 === 'undefined')
	{		
		var elem = document.getElementById('variationSnapShot');	
		$('#variationSnapShot').css('height',newOverlayHeight);
		if (elem.clientHeight < elem.scrollHeight)
		{
			$('#variationSnapShot').css('height',elem.scrollHeight);
		}
	}
	//newOverlayHeight = elem.scrollHeight;
	//alert(newOverlayHeight);
	disableLoadingIndicator = true;

	//Update productID value on form
	document.getElementById('ProductId').value = prodId;

	//These variables are for common.js, the one initiating the showing/hiding of the loading gif.
	productIdVariationWindow = prodId;
	currentItem = itemNumber;
	currentVariationCount = variationCount;

	var optionIdString = "";
	var optionIdList = new Array();
	var optionIdListElement = 0;
	
	for (var i=1;i<=variationCount;i++)
	{
		var currentVariation = "variation[" + i + "]";
		if (document.cartVariationSelectWindow.elements[currentVariation].type == undefined)
		{
			var radiolength = document.cartVariationSelectWindow.elements[currentVariation].length;
			for (var j=0;j < radiolength;j++)
			{
				if ((document.cartVariationSelectWindow.elements[currentVariation][j].checked) && (document.cartVariationSelectWindow.elements[currentVariation][j].disabled == false))
				{
					optionIdList[optionIdListElement] = document.cartVariationSelectWindow.elements[currentVariation][j].value;
					optionIdListElement++;
				}
			}
		}
		else
		{
			if (document.cartVariationSelectWindow.elements[currentVariation].disabled == false)
			{
				optionIdList[optionIdListElement] = document.cartVariationSelectWindow.elements[currentVariation].value;
				optionIdListElement++;				
			}
		}
	}
	
	//check the list of options given. if (opList.length == opCount), execute findCombination. Else, execute findOptions if true, execute this to get the combination.
	if (optionIdList.length == variationCount)
	{
		var ComboIdKey = findCombination(prodId, optionIdList, variationCount);
		if (ComboIdKey == 0)
		{
			$('#OutOfStockMessage').html("This option is temporarily out of stock.");
			$('#OutOfStockMessage').show();
			var t=setTimeout("$('#OutOfStockMessage').html('')",5000);
			resetItem(itemNumber);
			$('#CombinationId').val('');
			HideLoadingOnOverlay();	
		}
		else loadCombination(ComboIdKey);
	}
	else
	{
		var OptionArray = findOptions(prodId, optionIdList, variationCount);
		//the above set is the set of ids to enable.
		var nextElement = itemNumber + 1;
		var nextVariation = "variation[" + nextElement + "]";			
		
		if (document.cartVariationSelectWindow.elements[nextVariation].type == "select-one")
		{
			//enable select box first
			document.cartVariationSelectWindow.elements[nextVariation].disabled = false;		
		}
		
		for (var i=0; i<OptionArray.length; i++)
		{
			//enable these controls
			var id = "val" + OptionArray[i];
			document.getElementById(id).disabled = false;			
		}
		
	}
	
}

function resetItem(itemNumber)
{
	var currentVariation = "variation[" + itemNumber + "]";	
	if (document.cartVariationSelectWindow.elements[currentVariation].type == undefined)
	{
		//radio
		document.cartVariationSelectWindow.elements[currentVariation][0].checked = true;
	}
	else
	{
		document.cartVariationSelectWindow.elements[currentVariation].selectedIndex = 0;
	}
}

function loadCombination(combo)
{
	//Show loading bar
	ShowLoadingOnOverlay();
	document.getElementById('productPrice').innerHTML = combo.vcprice;
	document.getElementById('currentStock').innerHTML = combo.vcstock;
	document.getElementById('CombinationId').value = combo.CombinationId;
	document.getElementById('ThumbLink').value = combo.ThumbPath;
	
	document.getElementById('standardImage').src = config.ShopPath + largeLoadingGifPath;
	
	//load image first....show loading bar while image is loading
	var image = new Image();
	image.onload = function()
	{
		HideLoadingOnOverlay();
		$('#standardImage').css('display','none');
		document.getElementById('standardImage').src = combo.StandardImagePath;
		resizeProductImageOnOverlay();		
	}
	image.src = combo.StandardImagePath;
	
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

/*This is the same function updateSelectedVariation() in product.functions.js, 
just renamed variables so it doesn't conflict when the footer is loaded on the Product Details page.*/

var baseVariation = {};

function updateVariationOnWindow(parent, variation, id) {
	if(parent == undefined) {
		parent = $('body');
	}
	else {
		parent = $(parent);
	}

	if(typeof(baseVariation.price) == 'undefined') {
		if($('.AddCartButton', parent).css('display') == "none") {
			var cartVisible = false;
		}
		else {
			var cartVisible = true;
		}

		var stockMessageVisible = false;
		if($('.OutOfStockMessage', parent).css('display') != 'none') {
			stockMessageVisible = true;
		}

		baseVariation = {
			saveAmount: $.trim($('.YouSaveAmount', parent).html()),
			price: $.trim($('.VariationProductPrice', parent).html()),
			//sku: $.trim($('.VariationProductSKU', parent).html()),
			weight: $.trim($('.VariationProductWeight', parent).html()),
			//thumb: $.trim($('.ProductThumbImage img', parent).attr('src')),
			cartButton: cartVisible,
			stockMessage: stockMessageVisible,
			stockMessageText: $('.OutOfStockMessage', parent).html()
		};
	}

	// Show the defaults again
	if(typeof(variation) == 'undefined') {
		if(baseVariation.saveAmount) {
			$('.YouSave', parent).show();
			$('.YouSaveAmount').html(baseVariation.saveAmount);
		} else {
			$('.YouSave', parent).hide();
		}
		//$('.VariationProductPrice', parent).html(baseVariation.price);
		//$('.VariationProductSKU', parent).html(baseVariation.sku);
		$('.VariationProductWeight', parent).html(baseVariation.weight);
		$('.CartVariationId', parent).val('');
		//$('.ProductThumbImage img', parent).attr('src', baseVariation.thumb);
		$(parent).attr('currentVariation', '');
		$(parent).attr('currentVariationImage', '')
		if(baseVariation.sku == '') {
			$('.ProductSKU', parent).hide();
		}
		if(baseVariation.cartButton) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
		}

		if(baseVariation.stockMessage) {
			$('.OutOfStockMessage', parent)
				.show()
				.html(baseVariation.stockMessageText)
			;
		}
		else {
			$('.OutOfStockMessage').hide();
		}

		$('.InventoryLevel', parent).hide();
	}
	// Othersie, showing a specific variation
	else {
		$('.VariationProductPrice', parent).html(variation.price);
		if(variation.sku != '') {
			$('.VariationProductSKU', parent).html(variation.sku);
			//$('.ProductSKU', parent).show();
		}
		else {
			$('.VariationProductSKU', parent).html(baseVariation.sku);
			if(baseVariation.sku) {
				//$('.ProductSKU', parent).show();
			}
			else {
				$('.ProductSKU', parent).hide();
			}
		}
		$('.VariationProductWeight', parent).html(variation.weight);
		$('.CartVariationId', parent).val(id);
		if(variation.instock == true) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
			$('.OutOfStockMessage', parent).hide();
		}
		else {
			$('.AddCartButton, .QuantityInput', parent).hide();
			$('.OutOfStockMessage', parent).html(lang.VariationSoldOutMessage);
			$('.OutOfStockMessage', parent).show();
		}
		if(variation.thumb != '') {
			ShowVariationThumb = true;
			$('.ProductThumbImage img', parent).attr('src', variation.thumb);
			$(parent).attr('currentVariation', id);
			$(parent).attr('currentVariationImage', variation.image);
			
			//update link for modal cart overlay...
			$('#ThumbLink').attr('value', variation.smallimage);
			
			$('.ProductThumbImage a').attr("href", '');
		}
		else {
			//$('.ProductThumbImage img', parent).attr('src', baseVariation.thumb);
			$(parent).attr('currentVariation', '');
			$(parent).attr('currentVariationImage', '')
		}
		if(variation.stock) {
			$('.InventoryLevel', parent).show();
			$('.VariationProductInventory', parent).html(variation.stock);
		}
		else {
			$('.InventoryLevel', parent).hide();
		}
		if(variation.saveAmount) {
			$('.YouSave', parent).show();
			$('.YouSaveAmount').html(variation.saveAmount);
		} else {
			$('.YouSave', parent).hide();
		}
	}
}

//function from product.functions.js, renamed to avoid conflict with the function being used on the product details pages.
function WindowCheckEventDate() {

	var result = true;

	if(typeof(eventDateData) == 'undefined')
		return true;

	if ($('#EventDateDay').val() == -1 || $('#EventDateMonth').val() == -1 || $('#EventDateYear').val() == -1) {
		alert(eventDateData['invalidMessage']);
		return false;
	}

	if (eventDateData['type'] == 1) {

		if (new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) > new Date(eventDateData['compDateEnd'])
		 || new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) < new Date(eventDateData['compDate'])
		) {
			result = false;
		}

	} else if (eventDateData['type'] == 2) {
		if (new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) < new Date(eventDateData['compDate'])) {
			result = false;
		}

	} else if (eventDateData['type'] == 3) {
		if (new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) > new Date(eventDateData['compDate'])) {
			result = false;
		}
	} else {
		result = true;
	}

	if (!result) {
		alert(eventDateData['errorMessage']);
	}
	return result;
}

//function from common.js, this is the same as check_add_to_cart
//It was renamed to avoid conflict with the product detail pages.

function checkAddToCartWindow(form, required) {
	var valid = true;
	var qtyInputs = $(form).find('input.qtyInput');
	qtyInputs.each(function() {
		if(isNaN($(this).val()) || $(this).val() <= 0) {
			alert(lang.InvalidQuantity);
			this.focus();
			this.select();
			valid = false;
			return false;
		}
		/* Alert message, removed
		if (parseInt($('#currentStock').html()) < parseInt($(this).val()))
		{
			alert('There is not enough stock of this item.');
			showCart = false;
			return false;
		}
		*/
	});
	if(valid == false) {
		return false;
	}

	if(!CheckProductConfigurableFields(form)) {
		return false;
	}

	if(required && !$(form).find('.CartVariationId').val()) {
		alert(lang.OptionMessage);
		var select = $(form).find('select').get(0);
		if(select) {
			select.focus();
		}
		var radio = $(form).find('input[type=radio]').get(0);
		if(radio) {
			radio.focus();
		}
		return false;
	}

	if (!WindowCheckEventDate()) {
		return false;
	}

	return true;
}

//updateCartWithVariation(this.action.value, this.product_id.value, this.variation_id.value)
function updateCartWithVariation()
{
	if (showCart)
	{
		var operation = 'addvariation';
		var productId = $('#ProductId').val();
		var combinationId = $('#CombinationId').val();
		var currencyId = $('#CurrencyId').val();
		var clipQty = $('#clipQty').val();
		//var standardImage = document.getElementById('standardImage').src;
		var prodLink = $('#ProdLink').val();
		var thumbLink = $('#ThumbLink').val();
		var productName = $('#productNameHeading').html();
		
		//get object from products object array
		var cidName = 'Cid' + combinationId;
		var pidName = 'Pid' + productId;
		if (products[pidName].variationPresent == false)
		{
			operation = 'add';
			$('#OutOfStockMessage').css('height','38px');
			if (typeof isIE6 === 'undefined')
			{
				var elem = document.getElementById('variationSnapShot');	
				$('#variationSnapShot').css('height',elem.scrollHeight);
			}				
			$('#OutOfStockMessage').css('color','green');
			$('#OutOfStockMessage').html("Adding item to your cart...");
			$('#OutOfStockMessage').show();	
			PidObj = {action: operation, pid: productId, cid: combinationId, curid: currencyId, qty: clipQty};
			mySerializedPid = JSON.stringify(PidObj);  		
			$.post(jscartPath,{obj:mySerializedPid},function(data){ShowAddToCartResult(data)});	
			return;
		}
		eval("productVariation=products['" + pidName + "']." + cidName);
		if (productVariation.vcpair != 0)
		{
			var pairObjectIds = productVariation.vcpairids;
			var pairIdArray = pairObjectIds.split(',');
			
			//loop
			for (var i = 0; i < pairIdArray.length; i++)
			{
				var cidPairItem = 'Cid' + pairIdArray[i];
				eval("pairObjects[" + i + "]=products['" + pidName + "']." + cidPairItem);
			}
		}
		
		var variationProperties = '(';
		for (var i = 0; i < variationOptionList.length; i++)
		{
			var elementid = parseInt(i) + 1;
			var currentVariation = "variation[" + elementid + "]";
			variationProperties += variationOptionList[i] + ':';
			if (document.cartVariationSelectWindow.elements[currentVariation].type == undefined)
			{
				var radiolength = document.cartVariationSelectWindow.elements[currentVariation].length;
				for (j=0;j < radiolength;j++)
				{
					if ((document.cartVariationSelectWindow.elements[currentVariation][j].checked) && (document.cartVariationSelectWindow.elements[currentVariation][j].disabled == false))
					{
						//remove nbsp
						var text = document.cartVariationSelectWindow.elements[currentVariation][j].nextSibling.nodeValue;
						text = text.replace(/^(\s|&nbsp;)+|(\s|&nbsp;)+$/g,"");
						variationProperties += text;		
					}
				}
			}
			else
			{
				if (document.cartVariationSelectWindow.elements[currentVariation].disabled == false)
				{
					var index = document.cartVariationSelectWindow.elements[currentVariation].selectedIndex;
					if (index != undefined)
					{
						variationProperties += document.cartVariationSelectWindow.elements[currentVariation].options[index].text;
					}
					else
					{
						variationProperties += document.cartVariationSelectWindow.elements[currentVariation].text;
					}
				}
			}
			if (i < variationOptionList.length - 1)
			{
				variationProperties += ', ';
			}
			else
			{
				variationProperties += ')';		
			}
		}	

		//build record on cart overlay.	
		//if not item pair...
		if (clipQty == null) clipQty = 1;

		/*
		if (pairObjects.length == 0)
		{
			addRowToCartOverlay(productId, combinationId, prodLink, thumbLink, productName, variationProperties);
				
			PidObj = {action: operation, pid: productId, cid: combinationId, curid: currencyId, qty: clipQty};
			mySerializedPid = JSON.stringify(PidObj);  		
			$.post("jscart.php",{obj:mySerializedPid},function(data){GetVariationResult(data)});
					
		}
		else
		{
			for (var i = 0;i < pairObjects.length; i++)
			{
				addRowToCartOverlay(productId, pairObjects[i].CombinationId, prodLink, pairObjects[i].ThumbPath, productName, pairObjects[i].VariationDescription);
				
				PidObj = {action: operation, pid: productId, cid: pairObjects[i].CombinationId, curid: currencyId, qty: clipQty};
				mySerializedPid = JSON.stringify(PidObj); 
				$.post("jscart.php",{obj:mySerializedPid},function(data){GetVariationResult(data)});	
								
			}
			pairObjects = new Array();
		}
		*/

		
		//Code to post to cart page, and show cart page...	
		//$.post("cart.php",{action: "add", product_id: productId, variation_id: combinationId, currency_id: currencyId, 'qty[]': [clipQty]},function(data){location.href = "cart.php"});	
		
		//Add to cart without showing the cart itself - Added May 30 - June 1
		$('#OutOfStockMessage').css('height','38px');
		if (typeof isIE6 === 'undefined')
		{		
			var elem = document.getElementById('variationSnapShot');	
			$('#variationSnapShot').css('height',elem.scrollHeight);
		}			
		$('#OutOfStockMessage').css('color','green');
		$('#OutOfStockMessage').html("Adding item to your cart...");
		$('#OutOfStockMessage').show();	
		PidObj = {action: operation, pid: productId, cid: combinationId, curid: currencyId, qty: clipQty};
		mySerializedPid = JSON.stringify(PidObj);  		
		$.post(jscartPath,{obj:mySerializedPid},function(data){ShowAddToCartResult(data)});			
	
		/* uncomment to run the CART overlay
		
		PidObj = {action: operation, pid: productId, cid: combinationId, curid: currencyId, qty: clipQty};
		mySerializedPid = JSON.stringify(PidObj);  		
		$.post("jscart.php",{obj:mySerializedPid},function(data){GetVariationResult(data)});	
		
		//test only
		$('#variationSnapShot').jqmHide();
		$('#ex2').jqmShow();	
		
		*/
	}
	else
	{
		//reset variable probably set by checkAddToCartWindow()
		showCart = true;
	}
}

function ShowAddToCartResult(data)
{
	HideLoadingOnOverlay();
	eval("cart="+data);
	if (cart.status === 1)
	{
		$('#OutOfStockMessage').css('color','green');
		$('#OutOfStockMessage').css('height','38px');		
		var message = 'The item was added to your shopping cart.';
		updateSideCart(cart);
	}
	else
	{
		$('#OutOfStockMessage').css('color','red');
		$('#OutOfStockMessage').css('height','auto');
		$('#OutOfStockMessage').css('padding-top','5px');
		$('#OutOfStockMessage').css('padding-bottom','5px');

		var message =  cart.error_msg;		
	}
	var elem = document.getElementById('variationSnapShot');	
	//newOverlayHeight = elem.scrollHeight;
	$('#OutOfStockMessage').html(message);
	$('#OutOfStockMessage').show();
	if (typeof isIE6 === 'undefined')
	{	
		$('#variationSnapShot').css('height',elem.scrollHeight);
	}
	//scroll down if needed
	var objDiv = document.getElementById("variationSnapShot");
	objDiv.scrollTop = objDiv.scrollHeight;
}

function GetVariationResult(data)
{
	eval("cart="+data);
	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;
			var identifier = + cart[i].product_id + 'Cid' + cart[i].variation_id;
			var divId = '#Qty' + identifier;
			$(divId).html(cart[i].quantity);
			divId = '#PrcCell' + identifier;
			$(divId).html(FormatCurrency(cart[i].product_price));
			divId = '#TotalPrcCell' + identifier;
			$(divId).html('<em class="ProductPrice">' + FormatCurrency(itemTotal) + '</em>');						
		}
		$('#ItemsLabel').html('<em class="ProductPrice">' + FormatCurrency(CartTotal) + '</em>');
		$('#SubtotalLabel').html('<em class="ProductPrice">' + FormatCurrency(CartTotal) + '</em>');			
	}
	else
	{
		alert('An error occurred while updating your cart. Code: ' + cart.error_code);
		$('#CartErrorMessage').html('Error ' + cart.error_code + ': ' + cart.error_msg);
	}
}

function addRowToCartOverlay(productId, combinationId, prodLink, thumbLink, productName, variationProperties)
{
	var table = document.getElementById("CartTable");
	
	if (document.getElementById('Pid' + productId + 'Cid' + combinationId) != null)
	{
		var row = document.getElementById('Pid' + productId + 'Cid' + combinationId);
		table.deleteRow(row.rowIndex);	
	}	
	
	var newRow = table.insertRow(1);
	newRow.setAttribute('id', 'Pid' + productId + 'Cid' + combinationId);
	
	var newCell = newRow.insertCell(0);
	newCell.setAttribute('class', 'CartThumb');
	newCell.setAttribute('style', '');
	newCell.innerHTML = '<a href="' + prodLink + '"><img src="' + thumbLink + '" alt="" /></a>&nbsp;';
	
	newCell = newRow.insertCell(1);
	newCell.setAttribute('class', 'ProductName');
	newCell.setAttribute('colspan', '1');
	newCell.innerHTML = '<a href="' + prodLink + '">' + productName + '</a>' + '<br><small>' + variationProperties + '</small><br>';

	newCell = newRow.insertCell(2);
	newCell.setAttribute('id', 'Qty' + productId + 'Cid' + combinationId);	
	newCell.setAttribute('align', 'center');
	newCell.setAttribute('class', 'CartItemQuantity');
	newCell.innerHTML = '<img src="' + config.ShopPath + smallLoadingGifPath + '">';

	newCell = newRow.insertCell(3);
	newCell.setAttribute('id', 'PrcCell' + productId + 'Cid' + combinationId);	
	newCell.setAttribute('align', 'center');
	newCell.setAttribute('class', 'CartItemIndividualPrice');
	newCell.innerHTML = '<img src="' + config.ShopPath + smallLoadingGifPath + '">';

	newCell = newRow.insertCell(4);
	newCell.setAttribute('id', 'TotalPrcCell' + productId + 'Cid' + combinationId);	
	newCell.setAttribute('align', 'right');
	newCell.setAttribute('class', 'CartItemTotalPrice');//TotalPrcCell
	newCell.innerHTML = '<em class="ProductPrice"><img src="' + config.ShopPath + smallLoadingGifPath + '"></em>';	
}

window.onload = init;