// version note [1.01] - ZCH - 2008-01-3107 - js fix for multioptions

var g_variantprice = 0;
var g_variantpricenumber = 0;
var g_variantitemprice = 0;
var g_xrate_variantprice = 0;
var g_xrate_variantpricenumber = 0;
var g_xrate_symbol = "";

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-iframe').show();
		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);
		jQuery('#zoom-image-iframe').hide();
		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 = /additional/;
		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());
	}


	//Clear the Monogramming Letters input if clicked
	jQuery('#item_monogramming_letters').click(function() {
		jQuery('#item_monogramming_letters').val('');
		return false;
	});

	//Hide the ajax popup when the continue shopping link is selected
	jQuery('#AjaxPopupContinueLink').click(function() {
		oAJAXBasket.hideBasket();
		return false;
	});

	//handle the Monogramming style change
	jQuery('#item_monogramming_style').change(function() {
		updatePersonalisation();
	});
	
	//handle the Monogramming letters change
	jQuery('#item_monogramming_letters').change(function() {
		updatePersonalisation();
	});

	//handle the Monogramming letters blur - ("change" doesn't when input is blank)
	jQuery('#item_monogramming_letters').blur(function() {
		updatePersonalisation();
	});
	
	//handle the Monogramming location change
	jQuery('#item_monogramming_location').change(function() {
		updatePersonalisation();
	});
	
	//handle the Monogramming colour change
	jQuery('#item_monogramming_colour').change(function() {
		updatePersonalisation();
	});			

	//handle the sleeve change
	jQuery('#item_sleeve_length').change(function() {
		updatePersonalisation();
	});	

	function updatePersonalisation() {
		
		var Personalisationcost = 0;
		var Personalisationcost_xrate = 0;	
		var variantprice = 0;
		var variantitemprice = 0;
		var xrate_variantprice = 0;			
		if(MonogramminingSelected()) {
			Personalisationcost = parseFloat(Personalisationcost) + (parseFloat(jQuery("#monogrammingcost").val()) * jQuery('#item_monogramming_letters').val().length);
			Personalisationcost_xrate = parseFloat(Personalisationcost_xrate) + (parseFloat(jQuery("#monogrammingcostxrate").val()) * jQuery('#item_monogramming_letters').val().length);
			//Personalisationcost = parseFloat(Personalisationcost) + parseFloat(jQuery("#monogrammingcost").val());			
			//Personalisationcost_xrate = parseFloat(Personalisationcost_xrate) + parseFloat(jQuery("#monogrammingcostxrate").val());
		}	
		
		if(jQuery("#item_sleeve_length").val().length > 0 && jQuery("#personalisationflag").val() == 'true') {
			Personalisationcost = parseFloat(Personalisationcost) + parseFloat(jQuery("#sleevecost").val());
			Personalisationcost_xrate = parseFloat(Personalisationcost_xrate) + parseFloat(jQuery("#sleevecostxrate").val());
		}		
		
		variantprice = parseFloat(g_variantpricenumber) + parseFloat(Personalisationcost);
		variantitemprice = variantprice;
		variantprice = String.fromCharCode(163) + variantprice.toFixed(2).toString();
		xrate_variantprice = parseFloat(g_xrate_variantpricenumber) + parseFloat(Personalisationcost_xrate);
		xrate_variantprice = g_xrate_symbol + xrate_variantprice.toFixed(2);
		
		jQuery("#varPrice").val(variantitemprice);
		jQuery("#varPriceShow").val(variantprice);
		if(parseFloat(g_xrate_variantpricenumber) > 0) {
			jQuery("#varXRatePriceShow").val(xrate_variantprice);			
		}
	}


});



//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//
//  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="basketPopupImg floatLeft"><img src="/public/pictures/products/additional/' + oForm.elements['item_image_filename'].value + '" border="0" onerror="this.src=&#39;/public/pictures/products/additional/noimage.gif&#39;"/> </div>';
			sProductDetails = sProductDetails +	'<div class="basketPopupDetails floatLeft">';
			sProductDetails = sProductDetails +	'<div class="ajax_basket_name">' + oForm.elements['prodname'].value + '</div>';
			sProductDetails = sProductDetails +	'<div class="ajax_basket_details">' + oForm.elements['item_variant_option'].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="ajax_basket_cost">Line total: ' + oForm.elements['varPriceShow'].value + '</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>';
			var oVariantInfo = getObject("oVariantInfo");
			oVariantInfo.innerHTML = 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',''))-42) * 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','')) + 0);

		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");

	// Update the product total cost
	jQuery.ajax({
		type: "POST",
		//async: false,
		data: {},
		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 _variantpricenumber = "";
			var _variantitemprice = "";
			var _xrate_variantprice = "";
			var _xrate_variantpricenumber = "";
			var _variant_count;
			var _option1 = "";
			var _option2 = "";
			var _embeddedcode = "";

			//This function will loop for each match on mini-basket
			jQuery("gridvariantprice", xml).each(function(){
				g_variantprice = jQuery("variantprice", this).text();
				g_variantpricenumber = jQuery("variantpricenumber", this).text();
				g_variantitemprice = jQuery("variantitemprice", this).text();
				g_xrate_variantprice = jQuery("xrate_variantprice", this).text();
				g_xrate_variantpricenumber = jQuery("xrate_variantpricenumber", this).text();
				g_xrate_symbol = jQuery("xrate_symbol", this).text();
				_variant_count = parseInt(jQuery("variant_count", this).text(),10);
				_option1 = jQuery("soption1", this).text();
				_option2 = jQuery("soption2", this).text();
				_embeddedcode = jQuery("embeddedcode", this).text();

				var Personalisationcost = 0;
				var Personalisationcost_xrate = 0;
				

				if(MonogramminingSelected()) {
					
					Personalisationcost = parseFloat(Personalisationcost) + (parseFloat(jQuery("#monogrammingcost").val()) * jQuery('#item_monogramming_letters').val().length);
					Personalisationcost_xrate = parseFloat(Personalisationcost_xrate) + (parseFloat(jQuery("#monogrammingcostxrate").val()) * jQuery('#item_monogramming_letters').val().length);	
					//Personalisationcost = parseFloat(Personalisationcost) + parseFloat(jQuery("#monogrammingcost").val());
					//Personalisationcost_xrate = parseFloat(Personalisationcost_xrate) + parseFloat(jQuery("#monogrammingcostxrate").val());
				}
				
				if(jQuery("#personalisationflag").val() == 'true') {
					if(jQuery("#item_sleeve_length").val().length > 0) {
						Personalisationcost = parseFloat(Personalisationcost) + parseFloat(jQuery("#sleevecost").val());
						Personalisationcost_xrate = parseFloat(Personalisationcost_xrate) + parseFloat(jQuery("#sleevecostxrate").val());
					}
				}
				
				_variantprice = parseFloat(g_variantpricenumber) + parseFloat(Personalisationcost);
				_variantitemprice = _variantprice;
				_variantprice = String.fromCharCode(163) + _variantprice.toFixed(2).toString();
				_xrate_variantprice = parseFloat(g_xrate_variantpricenumber) + parseFloat(Personalisationcost_xrate);
				_xrate_variantprice = g_xrate_symbol + _xrate_variantprice.toFixed(2);
 
				jQuery("#varPrice").val(_variantitemprice);
				jQuery("#varPriceShow").val(_variantprice);
			
				if( parseFloat(g_xrate_variantpricenumber) > 0) {				
					jQuery("#varXRatePriceShow").val(_xrate_variantprice);
				}					
				// Update the variant option values if the product has multi-variants
				if(_variant_count != 1) {
					jQuery("#item_variant_option1").val(_option1);
					jQuery("#item_variant_option2").val(_option2);
				}
				
				jQuery("#item_embedded_code").val(_embeddedcode);

			});

			// Update the variant option values if the product has multi-variants
			if(_variant_count != 1) {
				//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 + ', ';
					}
					if(aVariantOptions[i].length > 0) {
						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 != '')
	{
		if(oElementc) {
			oElementc.href = 'javascript:ValidateAndSubmit(\'form_' + prodcode + '\',\'' + prodcode + '\' )';
			changeButton('', oElementb);
		}

		if(oElementctop) {
			oElementctop.href = 'javascript:ValidateAndSubmit(\'form_' + prodcode + '\',\'' + prodcode + '\' )';
			changeButton('', oElementbtop);
		}
	}
}


function DisableBuyButton(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 != '')
	{
		if(oElementc) {
			oElementc.href = "javascript:alert('Please select your option before adding to the basket.')";
			oElementb.src='/public/images/buttons/addtoyourbasket_dis.gif';
		}

		if(oElementctop) {
			oElementctop.href = "javascript:alert('Please select your option before adding to the basket.')";
			oElementbtop.src='/public/images/buttons/addtoyourbasket_dis.gif';
		}
	}
}


function CalTotal(oQty, sForm)
{
	var oFormVar = document.forms[sForm];
	var varProductID = oFormVar.elements['prod'].value;
	var varVariantID = oFormVar.elements['variantid'].value;
	var varOptionNames = oFormVar.elements['varOptionNames'].value;

	if (oQty.value.indexOf('.') > 0)
	{
		var iQty=Math.round(oQty.value);
		oFormVar.elements['qty'].value=iQty;
		productGridPrice_Ajax(varProductID, varVariantID, iQty, varOptionNames);
		return false;
	}
	if (isNaN(oQty.value))
	{
		alert("Quantity must be valid number greater than 0");
		oFormVar.elements['qty'].value = 1;
		productGridPrice_Ajax(varProductID, varVariantID, 1, varOptionNames);
		return false;

	}
	else if(oQty.value <= 0 )
	{
		alert("Quantity must be valid number greater than 0");
		oFormVar.elements['qty'].value = 1;
		productGridPrice_Ajax(varProductID, varVariantID, 1, varOptionNames);
		return false;
	}
	else
	{
		var iQty = oQty.value;
		productGridPrice_Ajax(varProductID, varVariantID, iQty, varOptionNames);
		return true;
	}
}

function ValidateAndSubmit(frm, sProdCode) {
	var oForm=document.forms[frm];
	var rIsNotNumeric=/[^0-9]/
	var rIsNotZero=/[1-9]+/
	var bValid=true

	var oMonogrammingflag = getObject('item_monogrammingflag');
	var oSleeveflag = getObject('item_sleeveflag');
	oMonogrammingflag.value = 'false';
	oSleeveflag.value = 'false';

	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) {
		
		var oMonogrammingLetters = getObject('item_monogramming_letters');
		if(oMonogrammingLetters){
			if(oMonogrammingLetters.value.length > 4) {
				oMonogrammingLetters.value = '';
			}
		}
	}

	//Validate monogramming selections - return a message if a monogramming selection is required
	if (bValid) {
		var oMonogramming = getObject('product_monogramming');
		// [1.01] start - moving one level up from the condition
		var oPersflag = getObject('item_persflag');
		// [1.01] end
		if(oMonogramming.value == 'Y') {
			var oMonogrammingStyle = getObject('item_monogramming_style');
			var oMonogrammingLetters = getObject('item_monogramming_letters');
			var oMonogrammingLocation = getObject('item_monogramming_location');
			var oMonogrammingColour = getObject('item_monogramming_colour');
			var sMonogrammingMsg = "";
			var bMonogramming = false;
			oPersflag.value = '';

			if(oMonogrammingStyle.value.length == 0) {
				sMonogrammingMsg = sMonogrammingMsg + "Please select your monogramming style \n";
			} else {
				  bMonogramming = true;
			}
			if(oMonogrammingLetters.value.length == 0) {
				sMonogrammingMsg = sMonogrammingMsg + "Please select your monogramming letters \n";
			} else {
				  bMonogramming = true;
			} 
			if(oMonogrammingLocation.value.length == 0) {
				sMonogrammingMsg = sMonogrammingMsg + "Please select your monogramming location \n";
			} else {
				  bMonogramming = true;
			} 
			if(oMonogrammingColour.value.length == 0) {
				sMonogrammingMsg = sMonogrammingMsg + "Please select your monogramming colour \n";
			} else {
				  bMonogramming = true;
			}	
			
			if(bMonogramming && sMonogrammingMsg.length > 0) {
				alert(sMonogrammingMsg);
				bValid = false;
			} else if(bMonogramming && sMonogrammingMsg.length == 0){
				oMonogrammingflag.value = 'true';			
			}
		}
		
		var oSleeveLength = getObject('item_sleeve_length');
		if(oSleeveLength) {
			if(oSleeveLength.value.length > 0 && jQuery("#personalisationflag").val() == 'true') {
				oSleeveflag.value = 'true';
			}
		}


		if(oMonogrammingflag.value == 'true' || oSleeveflag.value == 'true') {
			oPersflag.value = '1';
		}
	}	
	
	

	if (bValid) {


		//Display the oBasketContainer iframe
		jQuery('#oBasketContainer-iframe').show();


		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);

	}
}

function MonogramminingSelected() {
	var oMonogrammingStyle = getObject('item_monogramming_style');
	var oMonogrammingLetters = getObject('item_monogramming_letters');
	var oMonogrammingLocation = getObject('item_monogramming_location');
	var oMonogrammingColour = getObject('item_monogramming_colour');
	var bMonogramming = false;
	
	if(oMonogrammingStyle && oMonogrammingLetters && oMonogrammingLetters && oMonogrammingLocation && oMonogrammingColour) {
		if((oMonogrammingStyle.value.length > 0) && (oMonogrammingLetters.value.length > 0 && oMonogrammingLetters.value.length < 4) && (oMonogrammingLocation.value.length > 0) && (oMonogrammingColour.value.length > 0)) {
			bMonogramming = true;
		}
	}
	return bMonogramming;
}
