

jQuery(document).ready(function() {
	// ---- INI

	// ---- EVENTS

	//Display the zoom image when the relevant button is selected
	jQuery('#zoom-image-link').click(function() {
		//Retrieve the "main image" img src value
		var sImgSrc = jQuery('#mainImage img').attr('src');

		//Substitute the "zoom" folder with the "standard" the folder to display the new relevant image
		rExp = /standard/;
		var sSubstitute = 'zoom';
		var newImgSrc = sImgSrc.replace(rExp, sSubstitute);
		jQuery('#zoom-image').attr({src: newImgSrc});

		//Display the zoom Image container
		//jQuery('#zoom-image-group').css("display", "block");
		jQuery('#zoom-image-group').fadeIn(1500);
		jQuery('#zoom-image-group').focus();
		return false;
	});

	//Display the zoom image when the relevant button is selected
	jQuery('#zoom-image-close').click(function() {
		jQuery('#zoom-image-group').fadeOut(1500);
		return false;
	});


	// catch the additional image being "hovered" across
	jQuery('#AdditionalImages img').mouseover(function() {
		//Retrieve the "hovered over" img src value
		var sImgSrc = jQuery(this).attr('src');

		//Substitute the "additonal" folder with the "standard" the folder to display the new relevant image
		rExp = /small/;
		var sSubstitute = 'standard';
		var newImgSrc = sImgSrc.replace(rExp, sSubstitute);
		
		jQuery('#mainImage img').attr({src: newImgSrc});
	});


	// catch the grid image being selected
	jQuery('#ProductGrid td img').click(function() {

		//Retrieve the selected img src value
		var sOnGridSrc = jQuery(this).attr('src');

		// Retrieve the previously selected img src value
		var sOffGridSrc = jQuery("#stockstatus").val();

		// If the image src contains "nostock" OR the previous image is the same as the selected image,  the item is out of stock and no more action can be taken
		if((sOnGridSrc.indexOf('nostock') == -1)) {


			// Set the previous and current image IDs in variables
			var sOffGridID = 'Grid_' + jQuery('#variantid').val();
			var sOnGridID = jQuery(this).attr('id');

			// Ensure the same image is not being reselected
			if((sOnGridID != sOffGridID) || (sOffGridSrc.length == 0)) {
				if(sOffGridSrc.length > 0) {
					//Provided the previous img src is not blank, set the old image back to its previous image (nostock.gif, lowstock.gif, instock.gif)
					jQuery('#' + sOffGridID).attr({src: sOffGridSrc});
				}
				// Store the latest image src value
				jQuery("#stockstatus").val(sOnGridSrc);


				// Please note - varVariantID has "Grid_" as a prefix to its variantid - this must be removed
				var varVariantID = jQuery(this).attr('id')
				varVariantID = varVariantID.substr(varVariantID.indexOf('_')+1);
				jQuery("#variantid").val(varVariantID);

				DisableBuyButton(jQuery('#prod').val(),"");

				// Set the selected image to "selected.gif"
				jQuery(this).attr({src: '/public/images/cm/selected.gif'});

				// AJAX call to retrieve all variant pricing and set relevant hidden inputs for purchasing/future use
				productGridPrice_Ajax(jQuery('#prod').val(), varVariantID, jQuery('#qty').val(), jQuery('#varOptionNames').val());

				// Enable the buy button
				EnableBuyButton(jQuery('#prod').val());
			}

		} else {

			alert('Sorry, this one is out of stock!');

		}

	});

	//Call the CalTotal function if the product is a single variant product - ie, "singleVarProd" input has a value of 1
	if(jQuery('#singleVarProd').val()==1) {
		//CalTotal(getObject('qty'), 'form_' + jQuery('#prod').val());
		//jQuery('#prod').val(),jQuery('#item_overridecourier').val()
		//CalTotalSingleVariant (oQty, sForm,stock_behavior,sVarId,sPrice,sStock,sIsObsolete,sColour,sSize,sWeight,sOverRideCourier)
			CalTotalSingleVariant (getObject('qty'), 'form_' + jQuery('#prod').val(), jQuery('#item_product_StockCountdown').val() , jQuery('#variantid').val(), jQuery('#varPrice').val(),jQuery('#item_stock').val(),jQuery('#isobsolete').val(),jQuery('#item_variant_option1').val(),jQuery('#item_variant_option2').val(),jQuery('#item_weight').val(),jQuery('#item_overridecourier').val())
		
	}


});



//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//
//  OAJAXBASKET 								//
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//

function oAJAXBasket() {

	this.initialise 				= _initialise;

	this.AJAX_AddtoBasket 			= _AJAX_AddtoBasket;
	this.AJAX_ConfirmAddToBasket 	= _AJAX_ConfirmAddToBasket;

	this.isValidQty					= _isValidQty;
	this.setBasketProdImg			= _setBasketProdImg
	this.hideBasket					= _hideBasket;
	this.hideDiv					= _hideDiv;
	this.positionBasket				= _positionBasket;
	this.returnFormFieldsExclude	= _returnFormFieldsExclude;
	this.setURL						= _setURL;

	var p_sSiteURL					= '';
	//var oBasketBck 					= null;
	var oForm						= null;

	var sBasketProdImg				= '';
	var timerComfirmation			= null;
	var oBasketContainer 			= null;
	var p_sProdCode ='';


	// ----------------------------------------------------------------------------- _initialise()
	function _initialise() {
		//oBasketBck = getObject("oBasketBck")
		//oBasketBck.style.backgroundImage = "url(/public/images/basket_box.gif)";

		oBasketContainer = getObject('oBasketContainer');
	}

	// ----------------------------------------------------------------------------- _setBasketProdImg()
	function _setBasketProdImg(sPath_p) {
		sBasketProdImg = sPath_p;
	}

	// ----------------------------------------------------------------------------- _setURL()
	function _setURL(sSiteURL_p) {
		p_sSiteURL = sSiteURL_p;
	}
	// START OF [1.1]
	function _setCBL(bCompletethelook_p){
			p_bCompletethelook=bCompletethelook_p;
	}
	//END OF [1.1]

	// ----------------------------------------------------------------------------- _AJAX_AddtoBasket()
	function _AJAX_AddtoBasket(sFormName, sProdCode)
	{
		oForm = document.forms[sFormName];
		var iQty = oForm.elements['qty'].value;

		var sFormParams = _returnFormFieldsExclude(oForm, 'serial|prodname|timestamp');

		if (_isValidQty(iQty))
		{
			//var sURL = p_sSiteURL + '/core_2/core_ajax/EventListener.asp?' + sFormParams + '&inc_price=true&rQty=' + iQty;
			var sURL = p_sSiteURL + '/core_2/core_ajax/EventListener.asp?' + sFormParams;
			var oAJAXAddToBasket = new AjaxXMLDelegate(sURL, _AJAX_ConfirmAddToBasket);
			oAJAXAddToBasket.Fetch();

		}

	}

	// ----------------------------------------------------------------------------- _AJAX_ConfirmAddToBasket()
	function _AJAX_ConfirmAddToBasket(url, oXML)
	{
			// Update the basket total in the page header (via updateBasketTotal in layout.xsl)
			updateBasketTotal();

			//Retrieve new basket values
			var iBasketItemCount = oXML.getElementsByTagName('basket_totalitem_count')[0].firstChild.data;
			var iBasketTotal = oXML.getElementsByTagName('basket_price_total')[0].firstChild.data;

			//Set new ProductCode global variable
			p_sProdCode = oForm.elements['prod'].value;

			//determine the correct currency symbol
			var sCurrencySymbol = '&#163;';

			// Populate the popup basket success message

			var sProductDetails =	'';
			/*sProductDetails = sProductDetails +	'<div class="floatLeft">';
			sProductDetails = sProductDetails +	'<div class="ajax_basket_img"><img src="/public/pictures/products/small/' + oForm.elements['item_image_filename'].value + '" border="0" onerror="this.src=&#39;/public/pictures/products/small/noimage.gif&#39;"/> </div>';

			sProductDetails = sProductDetails +	'<div class="ajax_basket_name" >' + oForm.elements['prodname'].value + '</div>';
			sProductDetails = sProductDetails +	'<div class="ajax_basket_details">' + oForm.elements['item_variant_option1'].value.replace(',','<br>') + '<br>' + oForm.elements['item_variant_option2'].value.replace(',','<br>')+ '</div>';
			sProductDetails = sProductDetails +	'</div>';
			sProductDetails = sProductDetails +	'<div class="clear"><img src="/public/images/spacer.gif" /></div>';
			sProductDetails = sProductDetails +	'<div class="productDivider"><img src="/public/images/spacer.gif" /></div>';

			sProductDetails = sProductDetails +	'<div><div class="ajax_basket_qty">Qty: ' + oForm.elements['qty'].value + '</div>';
			var productCost = parseFloat(oForm.elements['item_product_ListPrice'].value * parseInt(oForm.elements['qty'].value,10));
			sProductDetails = sProductDetails +	'<div class="ajax_basket_cost">Line total: ' + sCurrencySymbol + productCost.toFixed(2) + '</div>';
			sProductDetails = sProductDetails +	'<div class="clear"><img src="/public/images/spacer.gif" /></div></div>';
			sProductDetails = sProductDetails +	'<div class="productDivider"><img src="/public/images/spacer.gif" /></div>';
			*/

			sProductDetails = sProductDetails +	'<table cellspacing=5 cellpadding=5 >';
			sProductDetails = sProductDetails +	'<tr>';
			sProductDetails = sProductDetails +	'<td>';
			sProductDetails = sProductDetails +	'<div class="ajax_basket_img"><img src="/public/pictures/products/small/' + oForm.elements['item_image_filename'].value + '" style="border:solid 1px #EAEAEA;" onerror="this.src=&#39;/public/pictures/products/small/noimage.gif&#39;"/> </div>';
			sProductDetails = sProductDetails +	'</td>';
			sProductDetails = sProductDetails +	'<td valign=top  style="padding-left:10px;"><b>';
			sProductDetails = sProductDetails +	oForm.elements['prodname'].value + '</b>';
			sProductDetails = sProductDetails + '<br><br>' + oForm.elements['item_variant_option1'].value.replace(',','<br>') + '<br>' + oForm.elements['item_variant_option2'].value.replace(',','<br>');
			sProductDetails = sProductDetails +	'</td>';
			sProductDetails = sProductDetails +	'</tr>';
			sProductDetails = sProductDetails +	'<tr><td height="5px" colspan="2">&nbsp;<td></tr>';
			sProductDetails = sProductDetails +	'<tr height="15px">';
			sProductDetails = sProductDetails +	'<td style="padding-left:3px;">';
			sProductDetails = sProductDetails +	'<b>Qty: ' + oForm.elements['qty'].value + '</b>';
			var productCost = parseFloat(oForm.elements['varPrice'].value * parseInt(oForm.elements['qty'].value,10));
			sProductDetails = sProductDetails +	'</td >';
			sProductDetails = sProductDetails +	'<td align="right">';
			sProductDetails = sProductDetails +	'<b>Line total: ' + sCurrencySymbol + productCost.toFixed(2) + '</b>';
			sProductDetails = sProductDetails +	'</td >';
			sProductDetails = sProductDetails +	'</tr>';
			sProductDetails = sProductDetails +	'</table>';

			var oVariantInfo = getObject("oVariantInfo");
			oVariantInfo.innerHTML = sProductDetails;
			//alert(sProductDetails);
			_positionBasket();

			//Display the basket success message
			oBasketContainer.style.display = "block";
			var nClientHeight = 0;
			if( typeof( window.innerWidth ) == 'number' ) {
				nClientHeight = parseFloat(self.innerHeight + self.pageYOffset);
			} else {
				nClientHeight = parseFloat(document.documentElement.clientHeight + document.documentElement.scrollTop);
			}
			var iYPosition = nClientHeight - ((parseFloat(oBasketContainer.style.height.replace('px',''))-22) * 2);

			jQuery('#oBasketContainer').animate( {top: iYPosition}, {duration: 500}, 'linear' );

			timerComfirmation = self.setTimeout(function() {_hideBasket()}, 5000)

			// END [1.6]

	}

	// ----------------------------------------------------------------------------- _isValidQty()
	function _isValidQty(iVal) {
		var rIsNotNumeric = /[^0-9]/
		var rIsNotZero = /[1-9]+/
		var bValid = true;

		if ( rIsNotNumeric.test(iVal) || !rIsNotZero.test(iVal) ) {
			bValid = false
			alert("Quantity must be valid number greater than 0");
		}

		return bValid;
	}

	// ----------------------------------------------------------------------------- _hideBasket()
	function _hideBasket() {
		self.clearTimeout(timerComfirmation);
		if (oBasketContainer.style.display == "block") {

			// [1.6] - moving the AJAX basket confirmation
			var iYPosition = parseFloat(document.documentElement.clientHeight + document.documentElement.scrollTop);
			jQuery('#oBasketContainer').animate( {top: iYPosition}, {duration: 500, complete: function() {_hideDiv();}}, 'linear' );
		}

	}


	// ----------------------------------------------------------------------------- _hideDiv()
	function _hideDiv() {
		oBasketContainer.style.display = "none";
		// start [1.7] Reset "Add To Basket" button
		var oAddToBasketButtonTop = getObject('btnAdd' + p_sProdCode + '_top');
		if(oAddToBasketButtonTop) {
			oAddToBasketButtonTop.src = '/public/images/buttons/addtoyourbasket.gif';
		}
		var oAddToBasketButton = getObject('btnAdd' + p_sProdCode);
		oAddToBasketButton.src = '/public/images/buttons/addtoyourbasket.gif';
		var oAddToBasketLinkTop =  getObject('form_' + p_sProdCode + 'link_top');
		if(oAddToBasketLinkTop) {
			oAddToBasketLinkTop.href = "javascript:void(ValidateAndSubmit('form_" + p_sProdCode + "','" + p_sProdCode + "'))";
		}
		var oAddToBasketLink =  getObject('form_' + p_sProdCode + 'link');
		oAddToBasketLink.href = "javascript:void(ValidateAndSubmit('form_" + p_sProdCode + "','" + p_sProdCode + "'))";
		//END [1.7]

	}

	// ----------------------------------------------------------------------------- _positionBasket()
	function _positionBasket() {

		// Position the basket confirmation msg
		var iCenterHeight = (self.pageYOffset) ? parseFloat(self.innerHeight + self.pageYOffset) - (parseFloat(oBasketContainer.style.height.replace('px',''))) : parseFloat(document.documentElement.clientHeight + document.documentElement.scrollTop) - (parseFloat(oBasketContainer.style.height.replace('px','')));
		//Adding 30px to the width - to handle the padding
		var iCenterWidth = 960 - (parseFloat(oBasketContainer.style.width.replace('px','')) + 30);

		oBasketContainer.style.left = iCenterWidth + "px";
		oBasketContainer.style.top = iCenterHeight + "px";
		oBasketContainer.style.display = "none";
	}

	// ----------------------------------------------------------------------------- _returnFormFieldsExclude()
	function _returnFormFieldsExclude(oForm, sExclude) {
	/* Used to gather all the form fields in the incoming form object */
		sExcludesArray = new Array
		sExcludesArray = sExclude.split("|");

		var sMsg = '';
		var sFormParams = '';
		var bAdd = false;

		for(i=0; i<oForm.elements.length; i++) {

			bAdd = ( (oForm.elements[i].value=='') || (oForm.elements[i].type=="radio" && !(oForm.elements[i].checked)) ||  (oForm.elements[i].type=="checkbox" && !(oForm.elements[i].checked)  && (oForm.elements[i].disabled==false)) ) ? false : true;

			if (bAdd) {
				for (s in sExcludesArray) {
					if (oForm.elements[i].name.indexOf(sExcludesArray[s]) == 0){
						bAdd = false;
					}
				}
				if (bAdd == true) {
					sMsg = sMsg + (oForm.elements[i].name + " = " + oForm.elements[i].value + "\n");
					sFormParams = sFormParams + ("&" + oForm.elements[i].name + "=" + oForm.elements[i].value);
				}
			}
		}

		if (leftStr(sFormParams,1) == "&")  sFormParams = rightStr(sFormParams, sFormParams.length - 1)

		return sFormParams
	}


	// ----------------------------------------------------------------------------- Get positions
	function getYPosition( oElement ) {
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetTop;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	}


	function getXPosition( oElement ) {
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetLeft;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	}
}


//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//
//  PRODUCT PAGE FUNCTIONS						//
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//

function productGridPrice_Ajax(varProductID, varVariantID, iQty, varOptionNames) {

	//Display disable overlay and please wait image
	jQuery('#_oDisableOverlay').css("display", "block");
	jQuery('#gridWait').css("display", "inline");
alert("/Shopping/productgridprice_ajax.asp?productid=" + varProductID +"&variantid=" + varVariantID + "&qty=" + iQty + "&varOptionNames=" + varOptionNames);
	// Update the product total cost
	jQuery.ajax({
		type: "POST",
		//async: false,
		url: "/Shopping/productgridprice_ajax.asp?productid=" + varProductID +"&variantid=" + varVariantID + "&qty=" + iQty + "&varOptionNames=" + varOptionNames,
		success: function(xml){

			//This simple XPath XML function looks through the returned XML data
			//All tags can now be accessed within the loop
			var _variantprice = "";
			var _variantitemprice = "";
			var _xrate_variantprice = "";
			var _option1 = "";
			var _option2 = "";


			//This function will loop for each match on mini-basket
			jQuery("gridvariantprice", xml).each(function(){
				_variantprice = jQuery("variantprice", this).text();
				_variantitemprice = jQuery("variantitemprice", this).text();
				_xrate_variantprice = jQuery("xrate_variantprice", this).text();
				_option1 = jQuery("soption1", this).text();
				_option2 = jQuery("soption2", this).text();

				jQuery("#varPrice").val(_variantitemprice);
				jQuery("#varPriceShow").val(_variantprice);
				jQuery("#varXRatePriceShow").val(_xrate_variantprice);
				jQuery("#item_variant_option1").val(_option1);
				jQuery("#item_variant_option2").val(_option2);

			});


			//Set variant selected options
			var sVariantOptions = jQuery('#item_variant_option_titles').val();
			var aVariantOptions = sVariantOptions.split('|');
			var sVariantOptionsText ='';
			for(var i=0; i<aVariantOptions.length; i++) {
				if(sVariantOptionsText.length > 0) {
					sVariantOptionsText = sVariantOptionsText + ', ';
				}
				sVariantOptionsText = sVariantOptionsText + aVariantOptions[i] + ': '
				sVariantOptionsText = sVariantOptionsText + jQuery('#' + aVariantOptions[i+1]).val();
				i++;
			}
			jQuery('#item_variant_option').val(sVariantOptionsText);


			//Remove disable overlay and please wait image
			jQuery('#gridWait').css("display", "none");
			jQuery('#_oDisableOverlay').css("display", "none");



		}
	});




}

function changeButton(oButtona, oButtonb)
{
	if (oButtona)
	{
		oButtona.disabled=false;
		oButtona.src='/public/images/buttons/selected.gif';
	}
	if (oButtonb)
	{
		oButtonb.src='/public/images/buttons/addtoyourbasket.gif';
	}
}

function EnableBuyButton(prodcode)
{
	
	var oElementbtop = getObject('btnAdd' + prodcode + '_top');
	var oElementctop = getObject('form_' + prodcode + 'link_top');
	var oElementb = getObject('btnAdd' + prodcode);
	var oElementc = getObject('form_' + prodcode + 'link');

	if(document.forms['form_' + prodcode].elements['varPrice'].value != '')
	{
		oElementc.href = 'javascript:ValidateAndSubmit(\'form_' + prodcode + '\',\'' + prodcode + '\' )';
		changeButton('', oElementb);
		if(oElementctop) {
			oElementctop.href = 'javascript:ValidateAndSubmit(\'form_' + prodcode + '\',\'' + prodcode + '\' )';
			changeButton('', oElementbtop);
		}
	}
}


function DisableBuyButton(prodcode, message)
{
	
	var oElementbtop = getObject('btnAdd' + prodcode + '_top');
	var oElementctop = getObject('form_' + prodcode + 'link_top');
	var oElementb = getObject('btnAdd' + prodcode);
	var oElementc = getObject('form_' + prodcode + 'link');

	if(document.forms['form_' + prodcode].elements['varPrice'].value != '')
	{
		if (message.length > 0 ) {
			oElementc.href = "javascript:alert('" + message+ "')";
		}
		else {
			oElementc.href = "javascript:alert('Please select your option before adding to the basket.')";
		}
		oElementb.src='/public/images/buttons/addtoyourbasket_dis.gif';
	}
}


function ValidateAndSubmit(frm, sProdCode) {
	var oForm=document.forms[frm];
	var rIsNotNumeric=/[^0-9]/
	var rIsNotZero=/[1-9]+/
	var bValid=true

	if (bValid) {
		if (rIsNotNumeric.test(oForm.qty.value)) {
			bValid=false
			alert("Quantity must be valid number greater than 0");
			oForm.qty.focus()
		}
		else if (!rIsNotZero.test(oForm.qty.value)) {
			bValid=false
			alert("Quantity must be valid number greater than 0");
			oForm.qty.focus()
		}
	}

	if (bValid) {
		if (parseInt(oForm.qty.value)>parseInt(oForm.item_stock.value)) {
			bValid=false;
			alert("Please select a different quantity, only " + oForm.item_stock.value + " available.");
			oForm.qty.focus();
		}
	}

	if (bValid) {
		oAJAXBasket.hideBasket();
		var oAddToBasketButtonTop = getObject('btnAdd' + sProdCode + '_top');
		if(oAddToBasketButtonTop) {
			oAddToBasketButtonTop.src = '/public/images/buttons/addingtobasket.gif';
		}
		var oAddToBasketButton = getObject('btnAdd' + sProdCode);
		oAddToBasketButton.src = '/public/images/buttons/addingtobasket.gif';
		var oAddToBasketLinkTop =  getObject('form_' + sProdCode + 'link_top');
		if(oAddToBasketLinkTop) {
			oAddToBasketLinkTop.href='javascript:alert(\'Please wait whilst your item is added to your basket.\')';
		}
		var oAddToBasketLink =  getObject('form_' + sProdCode + 'link');
		oAddToBasketLink.href='javascript:alert(\'Please wait whilst your item is added to your basket.\')';
		oAJAXBasket.AJAX_AddtoBasket(frm, sProdCode);

	}
}


/* for html menu */

		function setVarOptionsSingleVariant(oForm,sProdID,stock_behavior,sVarId,sPrice,sStock,sIsObsolete,sColour,sSize,sWeight,sOverRideCourier)
		{
			var oFormVar = document.forms[oForm];
			oFormVar.elements['item_variant_option1'].value = sColour;
			oFormVar.elements['item_variant_option2'].value = sSize;
			oFormVar.elements['variantid'].value = sVarId ;
			oFormVar.elements['varPrice'].value = sPrice ;
			oFormVar.elements['item_weight'].value = sWeight ;
			oFormVar.elements['item_overridecourier'].value = sOverRideCourier ;
			var iQty = oFormVar.elements['qty'].value;
	
			if (sStock > parseInt(outofstockvalue) || stock_behavior > 1) {
				
				if (CheckValidQty(iQty)) {
					
					var oElementb = getObject('btnAdd' + sProdID);
					var oElementc = getObject('form_' + sProdID + 'link');
					if(document.forms['form_' + sProdID].elements['varPrice'].value != '')
					{
						oElementc.href =  "javascript:ValidateAndSubmit('" + oForm +  "','" + sProdID +  "')";
						changeButton('', oElementb);
						
					}
				}
				else {
					
					DisableBuyButton(sProdID,"Quantity must be valid number greater than 0");
				}
			}
			else {
				DisableBuyButton(sProdID,"Out of stock!");
			}

		}
		

		function setVarOptions(oSelect,oForm,sName,sProdID,stock_behavior)
		{

			var selectedVarValue = oSelect.options[oSelect.selectedIndex].value;
			//alert(selectedVarValue);
			var arrVarVal = selectedVarValue.split("+");

			var sVarId = arrVarVal[0];
			var sPrice = arrVarVal[1];
			var sStock = arrVarVal[2];
			var sIsObsolete = arrVarVal[3];
			var sColour = arrVarVal[4];
			var sSize = arrVarVal[5];
			var sWeight = arrVarVal[6];
			var sOverRideCourier = arrVarVal[7];
			
			oForm.elements['item_variant_option1'].value = sColour;
			oForm.elements['item_variant_option2'].value = sSize;

			oForm.elements['variantid'].value = sVarId ;
			oForm.elements['varPrice'].value = sPrice ;
			oForm.elements['item_weight'].value = sWeight ;
			oForm.elements['item_overridecourier'].value = sOverRideCourier ;
			var iQty = oForm.elements['qty'].value;

			if (sStock > parseInt(outofstockvalue) || stock_behavior > 1) {
				if (CheckValidQty(iQty)) {
					EnableBuyButton(sProdID);
				}
				else {
					DisableBuyButton(sProdID,"Quantity must be valid number greater than 0");
				}
			}
			else {
				DisableBuyButton(sProdID,"Out of stock!");
			}


		}

		function setSizes(colourObj,sProdID,stock_behavior)
		{
			DisableBuyButton(sProdID,"");
			var selectedColour = colourObj.options[colourObj.selectedIndex].value;
			var arrResult = arrVariants.find(selectedColour);

			if (selectedColour ==0) {

					var sizedropbox = getObject("select_size_option")
					var i;
					for(i=sizedropbox.options.length-1;i>=0;i--)
					{
						sizedropbox.remove(i);
					}


			}

			else {

					getObject("select_size_option").length = 0;
					var optn = document.createElement("OPTION");
					optn.text = "Select a Size...";
					optn.value = "0";
					getObject("select_size_option").options.add(optn);

					for (var i = 0;i<arrResult.length;i++)
					{
						var tmpStr = new String(arrVariants[arrResult[i]]);
						var arrStr = tmpStr.split("+");

						var sVarId = arrStr[0];
						var sPrice = arrStr[1];
						var sStock = arrStr[2];
						var sIsObsolete = arrStr[3];

						var sColour = arrStr[4];
						var sSize = arrStr[5];
						var sWeight = arrStr[6];
						var sOverRideCourier = arrStr[7];
						var sAction = "NOSHOW" //DONT SHOW IN DROPDOWN

						optn = document.createElement("OPTION");

						if(stock_behavior == "0") // <!--stock behaviour Remove -->
						{
							if (sStock > parseInt(outofstockvalue)  && sIsObsolete != 1)
							{
								sAction = "I"; // SHOW AS INSTOCK
							}
						}
						else if(stock_behavior == "1") // <!-- stock behaviour display out of stock -->
						{
							if (sStock < parseInt(outofstockvalue)   && sIsObsolete != 1)
							{
								sAction = "O"; // SHOW AS OUT OF STOCK
							}
							else if (sStock > parseInt(outofstockvalue)   && sIsObsolete != 1)
							{
								sAction = "I"; // SHOW AS INSTOCK
							}
						}
						else if(stock_behavior == "2") // <!-- stock behaviour Allow back orders -->
						{
							if(sIsObsolete != 1)
							{
								sAction = "I"; // SHOW AS INSTOCK
							}
						}
						else if(stock_behavior == "3") // <!-- stock behaviour Allow as normal order -->
						{
							if(sIsObsolete != 1)
							{
								sAction = "I"; // SHOW AS INSTOCK
							}
						}

						if(sAction != "NOSHOW")
						{

							if (sStock <= parseInt(lowstockvalue) ) {
								if (sStock > outofstockvalue) {

									optn.text = sSize + ' - ' + lowstockmessage ; // + (sAction == "" ? "" : (" => " + sAction));
								}
								else {

									optn.text = sSize + ' - ' + outofstockmessage ;
								}

							}
							else {

								optn.text = sSize ;
							}
							optn.value = sAction == "O" ? "0" : tmpStr;
							getObject("select_size_option").options.add(optn);
						}

						else {

							optn.text = sSize + ' - ' + outofstockmessage ; // + (sAction == "" ? "" : (" => " + sAction));
							optn.value = sAction == "O" ? "0" : tmpStr;
							getObject("select_size_option").options.add(optn);
						    }
					}

				}
		}

		

		Array.prototype.find = function(searchStr)
		{

			var returnArray = false;

			 for (i=0; i<this.length; i++)
			 {

			 	if (typeof(searchStr) == 'function')
			 	{

			 		if (searchStr.test(this[i]))
			 		{
			 			if (!returnArray)
			 			{
			 				returnArray = []
			 			}

			 			returnArray.push(i);
			 		}
			 	}
			 	else
			 	{
					var objStr = new String(this[i])

					if (objStr.indexOf(searchStr) != -1)
			 	      	{
			 	      		if (!returnArray)
			 	      		{
			 	      			returnArray = []
			 	      		}

			 	      		returnArray.push(i);
			 	      	}
				}
			}

			return returnArray;
		}




function CalTotal(oQty, sForm,stock_behavior)
{
	var oFormVar = document.forms[sForm];
	var varProductID = oFormVar.elements['prod'].value;
	EnableBuyButton(varProductID);
	var selectobject
	var actionofcolour  = jQuery('#select_colour_option').attr('onChange');
	var actionofsize  = jQuery('#select_size_option').attr('onChange');

	if (actionofsize == undefined) {
		selectobject = getObject("select_colour_option")
	}
	else {
		selectobject = getObject("select_size_option")
	}

	setVarOptions(selectobject,oFormVar,'',varProductID,stock_behavior)
}


/* Product having single variants Single variants   */ 
function CalTotalSingleVariant (oQty, sForm,stock_behavior,sVarId,sPrice,sStock,sIsObsolete,sColour,sSize,sWeight,sOverRideCourier)

{
	var oFormVar = document.forms[sForm];
	var varProductID = oFormVar.elements['prod'].value;
	var oElementb = getObject('btnAdd' + varProductID);
	var oElementc = getObject('form_' + varProductID + 'link');
	setVarOptionsSingleVariant( sForm , varProductID , stock_behavior ,sVarId ,  sPrice ,  sStock ,sIsObsolete ,  sColour , sSize ,sWeight,sOverRideCourier)
}

function CheckValidQty(iVal) {
		var rIsNotNumeric = /[^0-9]/
		var rIsNotZero = /[1-9]+/
		var bValid = true;

		if ( rIsNotNumeric.test(iVal) || !rIsNotZero.test(iVal) ) {
			bValid = false

		}

		return bValid;
	}