/**
 * All functions have been moved to product.functions.js
 * This is because this file was used in the control panel as well as the front end, but the
 * below initialization code is only meant for the frontend.
 */
productDetailPage = true;
var tempProductImageThumb = '';
var tempProductSelected = new Array();
 
$(document).ready(function() {

	//product image resize:
	//resizeProductImage(true);

	initiateImageCarousel();
	initiateImageZoomer();

	if(typeof(HideProductTabs) != 'undefined' && HideProductTabs == 0) {
		GenerateProductTabs();
		if (CurrentProdTab && CurrentProdTab != "") {
			ActiveProductTab(CurrentProdTab);
			document.location.href = '#ProductTabs';
		}
	} else {
		$('.ProductSectionSeparator').show();
	}

	// are there any videos in the middle column?
	if($('.videoRow').size() > 0) {
		$('.videoRow').bind('click', function () {
			var videoId = $(this).attr('id').replace('video_', '');
			$('#FeaturedVideo').html('<object width="320" height="265">'
				+ '<param name="movie" value="http://www.youtube.com/v/' + videoId + '?fs=1"></param>'
				+ '<param name="allowFullScreen" value="true"></param>'
				+ '<param name="allowscriptaccess" value="always"></param>'
				+ '<embed src="http://www.youtube.com/v/'  + videoId + '?&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="265"></embed>'
				+ '</object>'
			);
			selectCurrentVideo(videoId);
		});
	}

	// are there any videos in the left or right columns?
	if($('.sideVideoRow').size() > 0) {
		$('.sideVideoRow a').bind('click', function () {
			// grab the video id out of the tag id
			var videoId = $(this).attr('id').replace('sidevideo_', '');

			if(config.ProductImageMode == 'lightbox') {
				// we need to hide any objects on the page as they appear onto of our modal window
				$('#VideoContainer object').css('visibility', 'hidden');

				$.iModal({
					data: '<object width="480" height="385">'
						+ '<param name="movie" value="http://www.youtube.com/v/' + videoId + '?fs=1"></param>'
						+ '<param name="allowFullScreen" value="true"></param>'
						+ '<param name="allowscriptaccess" value="always"></param>'
						+ '<embed src="http://www.youtube.com/v/'  + videoId + '?&fs=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>'
						+ '</object>',
					title: $(this).find('img').attr('title'),
					width: 510,
					buttons: '<input type="button" onclick="$.iModal.close();" value="  ' + lang.Close +'  " />',
					onBeforeClose: function() {
						// reshow any objects that were hidden
						$('#VideoContainer object').css('visibility', 'visible');
					}
				});
			} else {
				showVideoPopup(videoId);
			}
			return false;
		});
	}

	/*
	
	// disable all but the first variation box
	$(".VariationSelect:gt(0)").attr('disabled', 'disabled');

	$(".VariationSelect").change(function() {
		// get the index of this select
		var index = $('.VariationSelect').index($(this));

		// deselected an option, disable all select's greater than this and reset their selected option

		if (this.selectedIndex == 0) {
			$('.VariationSelect:gt(' + index + ')')
				.attr('disabled', 'disabled')
				.attr('selectedIndex', 0);

			updateSelectedVariation($('body'));
			return;
		}
		else {
			// disable selects greater than the next and reset their selected option
			$('.VariationSelect:gt(' + (index + 1) + ')')
				.attr('disabled', 'disabled')
				.attr('selectedIndex', 0);
		}

		//serialize the options of the variation selects
		var optionIds = '';
		$('.VariationSelect:lt(' + (index + 1) + ')').each(function() {
			if (optionIds != '') {
				optionIds += ',';
			}

			optionIds += $(this).val();
		});
		// request values for this option
		$.getJSON(
			config.AppPath + '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIds,
			function(data) {
				// were options returned?
				if (data.hasOptions) {
					// load options into the next select, disable and focus it
					$('.VariationSelect:eq(' + (index + 1) + ') option:gt(0)').remove();
					$('.VariationSelect:eq(' + (index + 1) + ')').append(data.options).attr('disabled', '').focus();
				}
				else if (data.comboFound) { // was a combination found instead?
					// display price, image etc
					updateSelectedVariation($('body'), data, data.combinationid);
				}
			}
		);
	});
	
	//radio button variations
	$('.ProductOptionList input[type=radio]').click(function() {
		//current selected option id
		var optionId = $(this).val();
		// request values for this option
		$.getJSON(
			config.AppPath + '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionId,
			function(data) {
				if (data.comboFound) { // was a combination found instead?
					// display price, image etc
					updateSelectedVariation($('body'), data, data.combinationid);
				}
			}
		);
	});
	
	// get the index of this select
	var index = $('.VariationSelect').index($(this));

	// deselected an option, disable all select's greater than this and reset their selected option
	if (this.selectedIndex == 0) {
		$('.VariationSelect:gt(' + index + ')')
			.attr('disabled', 'disabled')
			.attr('selectedIndex', 0);

		updateSelectedVariation($('body'));
		return;
	}
	else {
		// disable selects greater than the next and reset their selected option
		$('.VariationSelect:gt(' + (index + 1) + ')')
			.attr('disabled', 'disabled')
			.attr('selectedIndex', 0);
	}

	//serialize the options of the variation selects
	var optionIds = '';
	$('.VariationSelect:lt(' + (index + 1) + ')').each(function() {
		if (optionIds != '') {
			optionIds += ',';
		}

		optionIds += $(this).val();
	});
	// request values for this option
	$.getJSON(
		config.AppPath + '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIds,
		function(data) {
			// were options returned?
			if (data.hasOptions) {
				// load options into the next select, disable and focus it
				$('.VariationSelect:eq(' + (index + 1) + ') option:gt(0)').remove();
				$('.VariationSelect:eq(' + (index + 1) + ')').append(data.options).attr('disabled', '').focus();
			}
			else if (data.comboFound) { // was a combination found instead?
				// display price, image etc
				updateSelectedVariation($('body'), data, data.combinationid);
			}
		}
	);
	*/
	
	
	/* uncomment to enable default cart options.
  
	  if (document.cartForm)
	  {
		 var varcontent = document.getElementsByTagName('select');  
		 var total = varcontent.length;
		 var count = 0;	 
		 var variationCount = 0; 

		 while (count < total)
		 {
			var test = varcontent[count].getAttribute("name");
			if (test.indexOf('variation') > -1)
			{
				variationCount++;
			}
			count++;
		 }

		//loop through the number of items in variationCount
		for (var i=1; i<variationCount + 1; i++)
		{
			var elementValue = "variation[" + i + "]";
			document.cartForm.elements[elementValue].selectedIndex = 1;
		}
		//$(".VariationSelect").change();
	  }  
  	*/
	
	//Code for NSHC's variation list.
	//February 19, 2010
	//Disable all except first variation option.
	

//	$(".NSHCVariation[name^='variation']").attr('disabled', 'disabled');
//	$(".NSHCVariation option").attr('disabled', 'disabled');	
//	$(".NSHCVariation[name^='variation\\[1\\]']").attr('disabled', '');
//	$(".NSHCVariation[name^='variation\\[1\\]'] option").attr('disabled', '');


	//Code for NSHC's variation list.
	//February 19, 2010	
});

/*
$(document).load(function(){
	resizeProductImage();
});
*/

//June 11, 2010 - Add Item to Cart without loading the page

function addToCartOnPage()
{
	var operation = 'add'
	if ($('#pageCombinationId').val() > 0) 
	{
		operation = 'addvariation';
	}
	var productId = $('#pageProductId').val();
	var combinationId = $('#pageCombinationId').val();
	var currencyId = $('#pageCurrencyId').val();
	var clipQty = $('#text_qty_').val();
	$('#pageOutOfStockMessage').css('color','green');
	$('#pageOutOfStockMessage').html("Adding item to your cart...");
	$('#pageOutOfStockMessage').show();

	PidObj = {action: operation, pid: productId, cid: combinationId, curid: currencyId, qty: clipQty};
	mySerializedPid = JSON.stringify(PidObj);  		
	$.post(jscartPath,{obj:mySerializedPid},function(data){addToCartOnPageResult(data)});			

}

function addToCartOnPageResult(data)
{
	eval("cart="+data);
	if (cart.status === 1)
	{
		$('#pageOutOfStockMessage').css('color','green');	
		var message = 'The item was added to your shopping cart.';
		//alert(dump(cart));
		updateSideCart(cart);
	}
	else
	{
		$('#pageOutOfStockMessage').css('color','red');
		var message =  cart.error_msg;		
	}
	$('#pageOutOfStockMessage').html(message);
	$('#pageOutOfStockMessage').show();		
}


//June 11, 2010 - Add Item to Cart without loading the page



function loadProduct(prodId, itemNumber, itemValue, variationCount)
{
	if (ShowVariationThumb != 'undefined') ShowVariationThumb = true;
	fromCarousel = false;
	disableLoadingIndicator = true;
	//$('#pageOutOfStockMessage').hide();
	document.getElementById('pageProductId').value = 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 + "]";
		//alert(currentVariation);
		
		if (document.cartForm.elements[currentVariation].type == undefined)
		{
			var radiolength = document.cartForm.elements[currentVariation].length;
			for (var j=0;j < radiolength;j++)
			{
				if ((document.cartForm.elements[currentVariation][j].checked) && (document.cartForm.elements[currentVariation][j].disabled == false))
				{
					optionIdList[optionIdListElement] = document.cartForm.elements[currentVariation][j].value;
					optionIdListElement++;
				}
			}
		}
		else
		{
			if (document.cartForm.elements[currentVariation].disabled == false)
			{
				optionIdList[optionIdListElement] = document.cartForm.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);
		//alert(dump(ComboIdKey));
		if (ComboIdKey == 0)
		{
			//alert("none found...");
			//$('#AddToCartArea').hide();
			if ((productDetailPage) && (jsonLoaded == false))
			{
				$('#pageOutOfStockMessage').css('color','green');	
				$('#pageOutOfStockMessage').html('Loading...Please wait.');
				$('#pageOutOfStockMessage').show();		
			}
			else
			{
				$('#pageOutOfStockMessage').html(lang.NonExistentVariation);
				$('#pageOutOfStockMessage').show();
			}
			//store options in array for later use
			tempProductSelected[0] = prodId;
			tempProductSelected[1] = itemNumber;
			tempProductSelected[2] = itemValue;
			tempProductSelected[3] =  variationCount;
			
			//var t=setTimeout("delayedProductLoad('" + prodId + "','" + itemNumber  + "','" +  itemValue + "','" + variationCount + "')",5000);
			//var t=setTimeout("$('#pageOutOfStockMessage').hide()",5000);
			//resetPageItem(itemNumber);
			$('#pageCombinationId').val('');				
		}
		else loadPageCombination(ComboIdKey);
	}
	else
	{
		var OptionArray = findOptions(prodId, optionIdList, variationCount);
		//the above set is the set of ids to enable.
		//alert(OptionArray.join(','));
		var nextElement = itemNumber + 1;
		var nextVariation = "variation[" + nextElement + "]";			
		
		if (document.cartForm.elements[nextVariation].type == "select-one")
		{
			//enable select box first
			document.cartForm.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 delayedProductLoad(prodId, itemNumber, itemValue, variationCount)
{
	//$('#pageOutOfStockMessage').hide();
	loadProduct(prodId, itemNumber, itemValue, variationCount);
}

function resizeProductImage()
{
	//Resize image if needed
	var imagePath = document.getElementById('pageStandardImage').src;
	var productImage = new Image();
	$('#pageStandardImage').removeAttr('height');
	$('#pageStandardImage').removeAttr('width');
	document.getElementById('pageStandardImage').src = config.ShopPath + largeLoadingGifPath;	
	productImage.onload = function()
	{
		//$('#pageStandardImage').css('display','none');
		document.getElementById('pageStandardImage').src = imagePath;	
		var productImageWidth = productImage.width;
		var productImageHeight = productImage.height;
		$('#pageThumbLink').css('width','');
		$('#pageThumbLink').css('height','');

		if ((productImageWidth > productImageHeight) && (productImageWidth > 150))
		{
			$('#pageStandardImage').attr('width',150);
			$('#pageStandardImage').removeAttr('height');
			$('#pageStandardImage').css('height','');
			
		}
		else if ((productImageHeight > productImageWidth) && (productImageHeight > 150))
		{
			$('#pageStandardImage').attr('height',150);
			$('#pageStandardImage').removeAttr('width');
			$('#pageStandardImage').css('width','');
		}
		else if ((productImageWidth > 150) &&  (productImageHeight > 150))
		{
			$('#pageStandardImage').attr('height',150);
			$('#pageStandardImage').attr('width',150);
			$('#pageStandardImage').css('width','');
			$('#pageStandardImage').css('height','');			
		}
		$('#pageStandardImage').css('display','');
		
		// image zoomer
		
		$('.ProductThumbImage a').attr("href", "");
		$('.ProductThumbImage a').css({'cursor':'pointer'});
		// image zoomer
	}
	productImage.src = imagePath;
}

function loadPageCombination(combo)
{
	//$('#pageOutOfStockMessage').hide();
	document.getElementById('pageProductPrice').innerHTML = combo.vcprice;
	document.getElementById('pageCurrentStock').innerHTML = combo.vcstock;
	document.getElementById('pageCombinationId').value = combo.CombinationId;	
	document.getElementById('pageStandardImage').src = combo.StandardImagePath;
	document.getElementById('pageThumbLink').value = combo.ThumbPath;
	resizeProductImage();

}

function resetPageItem(itemNumber)
{
	var currentVariation = "variation[" + itemNumber + "]";	
	if (document.cartForm.elements[currentVariation].type == undefined)
	{
		//radio
		document.cartForm.elements[currentVariation][0].checked = true;
	}
	else
	{
		document.cartForm.elements[currentVariation].selectedIndex = 0;
	}
}

/*
function loadProduct(itemNumber, itemValue, variationCount)
{
	//These variables are for common.js, the one initiating the showing/hiding of the loading gif.
	currentItem = itemNumber;
	currentVariationCount = variationCount;
	//$('#AjaxLoading').show();
	//if any form elements after this one are enabled, disable them all.
	for (i = itemNumber; i <= variationCount; i++)
	{
		if (i == itemNumber) 
		{
			//skip this element.
			continue;
		}
		var currentVariation = "variation[" + i + "]";		
		if (document.cartForm.elements[currentVariation].type == undefined)
		{
			//radio
			var radiolength = document.cartForm.elements[currentVariation].length;
			var radioValueFound = false;
			for (j=0;j < radiolength;j++)
			{
				if ((document.cartForm.elements[currentVariation][j].checked)||(document.cartForm.elements[currentVariation][j].disabled == false))
				{
					//an element is checked, therefore disable this entire set...
					radioValueFound = true;
					document.cartForm.elements[currentVariation][j].checked = false;
					break;
				}
			}
			if (radioValueFound)
			{
				//disable all radio buttons under this variation.
				//alert("Values found in..." + currentVariation);
				for (j=0;j < radiolength;j++)
				{
					document.cartForm.elements[currentVariation][j].disabled = true;
				}				
			}
		}
		else
		{
			for (j=0;j < document.cartForm.elements[currentVariation].options.length; j++)
			{
				document.cartForm.elements[currentVariation].options[j].disabled = true;
			}
			document.cartForm.elements[currentVariation].selectedIndex = 0;
			//disable select box as well.
			document.cartForm.elements[currentVariation].disabled = true;
		}
		updateSelectedVariation($('body'));			
	}

	var optionIdString = "";
	var optionIdList = new Array();
	var optionIdListElement = 0;
	
	for (i=1;i<=variationCount;i++)
	{
		var currentVariation = "variation[" + i + "]";
		if (document.cartForm.elements[currentVariation].type == undefined)
		{
			var radiolength = document.cartForm.elements[currentVariation].length;
			for (j=0;j < radiolength;j++)
			{
				if ((document.cartForm.elements[currentVariation][j].checked) && (document.cartForm.elements[currentVariation][j].disabled == false))
				{
					optionIdList[optionIdListElement] = document.cartForm.elements[currentVariation][j].value;
					optionIdListElement++;
				}
			}
		}
		else
		{
			if (document.cartForm.elements[currentVariation].disabled == false)
			{
				optionIdList[optionIdListElement] = document.cartForm.elements[currentVariation].value;
				optionIdListElement++;				
			}
		}
	}
	
	//build comma separated string based on array elements.
	
	for (i=0; i < optionIdList.length; i++)
	{
		if ((optionIdList[i] == null)||(optionIdList[i] == undefined))
		{
			break;
		}
		//string them together
		optionIdString += optionIdList[i];
		optionIdString += ",";
	}
	//take out the last comma
	optionIdString = optionIdString.substring(0,optionIdString.length - 1);	

	//alert(optionIdString);
	//alert(config.AppPath + '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIdString);
	$.getJSON(
		config.AppPath + '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIdString,
		function(data) {
			// were options returned?
			//alert(data.comboFound);
			if (data.hasOptions) {
				var optionsAvailable = data.options.split(',');
				
				var nextElement = itemNumber + 1;
				var nextVariation = "variation[" + nextElement + "]";			
				
				if (document.cartForm.elements[nextVariation].type == "select-one")
				{
					//enable select box first
					document.cartForm.elements[nextVariation].disabled = false;
				}
				for (i=0; i < optionsAvailable.length; i++)
				{
					if (optionsAvailable[i].length == 0)
					{
						//this is an empty option, just skip.
						continue;
					}
					var id = "val" + optionsAvailable[i];
					//alert(id);
					document.getElementById(id).disabled = false;
				}
				$('.VariationProductInventory').html('---');
			}
			else if (data.comboFound) { // was a combination found instead?
				// display price, image etc
				//alert("combo found");
				updateSelectedVariation($('body'), data, data.combinationid);
			}
		}
	);
	//$('#AjaxLoading').hide();	
}*/
