
jQuery(document).ready(function() {
	// ---- INI

// -----------------------------------------------------------------
	// jQZoom plugin call
// -----------------------------------------------------------------
	var zoomOptions = {
		zoomType: 'reverse',
	    zoomWidth: 410,
	    zoomHeight: 343,
            xOffset: 10,
            yOffset: 0,
            lens: true,
            position: "right"
	};

	 // check for not supported browsers (Safari on Mac)
	if (!(navigator.userAgent.toLowerCase().indexOf("safari") > -1 && navigator.userAgent.toLowerCase().indexOf("mac os") > -1)) {
		jQuery("a.zoomMe").jqzoom(zoomOptions);
		
		// wierd behaviour of Safari/Chrome - needs to change the img source first to make it work :-@
		var sTemp = jQuery("#productImage a.zoomMe img").attr("src");
		jQuery("#productImage a.zoomMe img").attr({"src": "blank.jpg"});
		jQuery("#productImage a.zoomMe img").attr({"src": sTemp});

		// when zooming details, hide the whole right column
		jQuery("#productImage a").hover(function(e)
		{
			jQuery("#productDetails").css('visibility','hidden')
		},function()
		{
			jQuery("#productDetails").css('visibility','visible')
		});

	} else {
		jQuery("a.zoomMe").attr({'target':'_blank'});
	}


	// END jQZoom plugin call
// -----------------------------------------------------------------


// -----------------------------------------------------------------
// Swap the additional image being "hovered" across
	jQuery('#AdditionalImages img').mouseover(function() {
		//Retrieve the "hovered over" img src value
		var sImgSrc = jQuery(this).attr('src');

		rExp = /additional/;
		//Substitute the "additonal" folder with the "standard" - the folder to display the new standard image
		var sSubstitute = 'standard';
		var newImgSrc = sImgSrc.replace(rExp, sSubstitute);
		//Substitute the "additonal" folder with the "zoom" - the folder to display the zoom image
		sSubstitute = 'zoom';
		var newZoomSrc = sImgSrc.replace(rExp, sSubstitute);

		// swapping values in standard image
		// main image
		jQuery("#productImage a.zoomMe img").attr({"src": newImgSrc});
		// zoom details link
		jQuery("#productImage a.zoomMe").attr({"href": newZoomSrc});
		// zoom whole image link
		jQuery("a#zoomImageLink").attr({"href": newZoomSrc});
	});
// -----------------------------------------------------------------


	jQuery('#AddToWishlist a#wishlistAddItem').click(function() {

			var jqForm = jQuery('#form_'+jQuery(this).attr('rel'));
			var sProdCode = jqForm.children("input#prod").attr('value')
			var sVariantCode = jqForm.children("input#variantid").attr('value')
			var sVariant_option1 = jqForm.children("input#item_variant_option1").attr('value')
			var sVariant_option2 = jqForm.children("input#item_variant_option2").attr('value')
			var iQty = jQuery("#qtyentrybox input#productQty").attr('value')
			var sCtlg = jqForm.children("input#ctlg").attr('value')
			var iPrice = jqForm.children("input#varPrice").attr('value')
			var sFunction = 'addtotemplatefunction';
			var sProdName = jqForm.children("input#prodname").attr('value')
			var sImageName = jqForm.children("input#item_image_filename").attr('value')
			var iTaxStatus = jqForm.children("input#item_product_TaxStatus").attr('value')

			var sCurrencySymbol = '&#163;';
			var sProductDetails =	'';
			sProductDetails = sProductDetails +	'<table><tr>';
			sProductDetails = sProductDetails +	'<td valign="top" class="basket_img">';
			sProductDetails = sProductDetails +	'<div id="ajax_wishlist_img"><img src="/public/pictures/products/small/' + sImageName + '"onerror="this.src=&#39;/public/pictures/products/additional/noimage.gif&#39;"/> </div>';
			sProductDetails = sProductDetails +	'</td>';
			sProductDetails = sProductDetails +	'<td valign="top">';
			sProductDetails = sProductDetails +	'<p id="ajax_wishlist_prodName">'+ sProdName + '</p>';
			sProductDetails = sProductDetails + '<p id="ajax_wishlist_cost">' + sCurrencySymbol + iPrice + '</p>';
			sProductDetails = sProductDetails + '<p id="ajax_wishlist_variants">' +  sVariant_option1+ '<br />';
			sProductDetails = sProductDetails + sVariant_option2 + '</p>';
			sProductDetails = sProductDetails +	'</td>';
			sProductDetails = sProductDetails +	'</tr></table>';
			
			jQuery("#wishlistVariantInfo").html(sProductDetails);


		// check if the link is enabled (in the title attribute it reads Add To Your Wishlist)
		// = proper variant was selected
		if(jQuery(this).attr("title")=="Add To Your Wishlist"){
			//jQuery("#AddToWishlist p.wishlistConfirm").hide();
			var url = '/core_2/core_AJAX/runFunction.asp?item_ctlg=' + sCtlg + '&function=' + sFunction + '&item_product_id=' + sProdCode + '&item_item_key=' + sVariantCode + '&item_qty='+ iQty + '&item_variant_option1=' + sVariant_option1 + '&item_variant_option2=' + sVariant_option2 + "&item_product_ListPrice=" + iPrice + "&template_name=WishList&item_product_Name=" + sProdName + "&item_image_filename=" + sImageName + "&item_product_TaxStatus=" + iTaxStatus;
			jQuery.get(url, '', function(data){
				// adding was successful, show the Nyro confirmation box
				if(data=="1"){
					var NyroContent = jQuery("#oWishlistContainer").html();
					jQuery.nyroModalManual({
					      bgColor: '#cccccc',
					      width: 360,
					      minHeight: 200,
					      content: NyroContent
					    });
					timerComfirmation = self.setTimeout(function() {jQuery.nyroModalRemove()}, 5000)
					//jQuery("#AddToWishlist p.wishlistConfirm").show();
					} 
					
//			    alert("Data returned: " + data);
			  });
		}else{
			alert(jQuery(this).attr('title'));
		}
		return false;
	});


// -----------------------------------------------------------------
// ------ PRODUCT VARIANTS SELECT BOXES (For Multioptions variants)
// -----------------------------------------------------------------

	// CLASS for cells in a column -- 		tbl_variantSelection_Colour
	// columnHeaderName CLASS --			selected_variantSelection_Colour
	// selectBox ID -- 						variantSelection_Colour

	var debugBuffer = "";

	// if the table with Multioptions comes
	if(jQuery("table#productVariantsBase").length > 0) {
		// first disable the Wishlist link until a variant is selected
		DisableWishlistLink();

		// fill-in the first selectBox
		var sFirstVariantOptionClass = (jQuery("#productVariantsBase th[className^='selected_']:first").attr("class")).replace(/selected_/, "tbl_");
		createVariantSelect(sFirstVariantOptionClass);
	}


	// after change, pass the Select Box to a function /trigger(change) from other places didnt work for some reason/
	jQuery("#variantsSelectionBox select.variantSelection").change(function(){
		afterItemIsSelected(jQuery(this))
	});

	function afterItemIsSelected(jqSelectBox){
			debugBuffer += "<p>.. "+jqSelectBox.find(":selected").val()+" was selected</p>"

			var jqCellColumnHeader = jQuery("#productVariantsBase th.selected_" + jqSelectBox.attr('id'))

			// write the SelectBox value to Table column header
			jqCellColumnHeader.text(jqSelectBox.find(":selected").val());

			// clear all other subsequent Table column headers
			jqCellColumnHeader.nextAll("[className^='selected_']").text("").css('background-color','green');

			// remove the 'Please select' option
			jqSelectBox.children("option[value='']").remove();

			// fill in another select box if applicable
			if(jqCellColumnHeader.next("[className^='selected_']").length > 0) {
				var nextColumnVariantClass = (jqCellColumnHeader.next("[className^='selected_']").attr('class')).replace(/selected_/, "tbl_")
				createVariantSelect(nextColumnVariantClass);
			// otherwise if the last SelectBox is selected, assign values to form data and send the data
			}else{
				checkTheButton();
			}
	}

	function checkTheButton(){
		// get all the appropriate data from selected row (should be just one if all variants are distinct !!)
		// and assign the data from table cells to form fields

		// load the values from table to variables
		var noValueString = 'no value';
		var TRFilterString = TRFilterString = getTRFilterString();
		var sProductCode = jQuery("#variantsSelectionBox input#prod").val();
		var jqFinalVariantRow = jQuery("#productVariantsBase " + TRFilterString);
		var sVariantID = jqFinalVariantRow.children(".tblVariantID:first").text();
		var sVariantPrice = jqFinalVariantRow.children(".tblVariantPrice:first").text();
		var sVariantOption1 = jqFinalVariantRow.children(".tbl_variantSelection_Colour:first").text();
		var sVariantOption2 = jqFinalVariantRow.children(".tbl_variantSelection_Size:first").text();
		var sVariantBackorder = jqFinalVariantRow.children(".tblVariantWeeks:first").text();
			var aVariantBackorder = sVariantBackorder.split("|");
			var sVariantBackorderDate = aVariantBackorder[0];
			var sVariantBackorderWeeks = aVariantBackorder[1]; 
		var sVariantEnable = jQuery.trim(jqFinalVariantRow.children(".tblVariantEnable:first").text());

		// fetch the values from variables to hidden input fields
		jQuery("#variantsSelectionBox input#variantid").attr('value',sVariantID)
		jQuery("#variantsSelectionBox input#varPrice").attr('value',sVariantPrice)
		jQuery("#variantsSelectionBox input#item_variant_backorderdate").attr('value',sVariantBackorderDate)
		jQuery("#variantsSelectionBox input#item_variant_backorderweeks").attr('value',sVariantBackorderWeeks)
		jQuery("#variantsSelectionBox input#item_variant_option1").attr('value',sVariantOption1==noValueString?'':sVariantOption1)
		jQuery("#variantsSelectionBox input#item_variant_option2").attr('value',sVariantOption2==noValueString?'':sVariantOption2)
		debugBuffer += "<p>" + "varOpt1: " + jQuery("#variantsSelectionBox input#item_variant_option1").attr('value') + " || varOpt2: " + jQuery("#variantsSelectionBox input#item_variant_option2").attr('value')  + " || backorder: " + jQuery("#variantsSelectionBox input#item_variant_backorderweeks").attr('value') + "</p>"

		// just a debuging line in baseTable to observe that correct data were assigned
//		jQuery("table tr#tblDebug td").html("").html(debugBuffer);

		// Enable item to be added to wishlist
		EnableWishlistLink()

		// check the shopping button
		if(sVariantEnable=='1'){
			EnableBuyButton(sProductCode)
		}else{
			DisableBuyButton(sProductCode,'')
		}

	}


	function createVariantSelect(variantOption){
		// create filter string for options from table column headers
		// variantOption is a class for table column cells

		var JQSelectboxString = "#variantsSelectionBox select#" + variantOption.replace(/tbl_/, "");
		var sLastVariantOptionClass = (jQuery("#productVariantsBase th[className^='selected_']:last").attr("class")).replace(/selected_/, "tbl_");
		var variantName = variantOption.replace(/tbl_variantSelection_/,"").toLowerCase();
	//	alert("last variant is: " + sLastVariantOptionClass);
	//	alert("select box to fill in: " + JQSelectboxString);
		debugBuffer += "<p>creating selectBox: " +JQSelectboxString+ "</p>"

		var TRFilterString = TRFilterString = getTRFilterString();


		// clear all the options from Select Box
		jQuery(JQSelectboxString).empty();
		jQuery(JQSelectboxString).append("<option value=''>Please select "+ variantName +".. </option>");

		// select only CELLS passing the filter and fill the select box with distinct values
		var sUsedValues = ",";
		// catching the values for Select Box into these two arrays
		var aItemsToDisplay = new Array();
		var aItemsToPass = new Array();
		jQuery("#productVariantsBase "+ TRFilterString + " td." + variantOption).each(function(){
			var textToDisplay = jQuery(this).text();
			// if the value has not been used yet.. (is distinct)
			if(sUsedValues.indexOf(","+textToDisplay+",") < 0) {
				// if this is the last variant column, display stock msg too
				if(variantOption==sLastVariantOptionClass){
					textToDisplay += jQuery(this).parent().children("td.tblVariantMsg").text();
				}
				aItemsToDisplay.push(textToDisplay);
				aItemsToPass.push(jQuery(this).text());
				sUsedValues += textToDisplay + ","
			}
		});
		// check out how many options are returned
		var itemsCount = aItemsToDisplay.length
		if(itemsCount > 1) {
			for ( var i=0; i<itemsCount; ++i ){
				jQuery(JQSelectboxString).append("<option value='"+ aItemsToPass[i] +"'>"+ aItemsToDisplay[i] +"</option>");
				jQuery(JQSelectboxString).show();
			}
		// no options were found for this select box
		} else {
			// clear the Select Box options
			jQuery(JQSelectboxString).empty();

			// there is one option in the select box
			if(itemsCount == 1) {
				for ( var i=0; i<itemsCount; ++i ){
					jQuery(JQSelectboxString).append("<option value='"+ aItemsToPass[i] +"'>"+ aItemsToDisplay[i] +"</option>");
				}
				jQuery(JQSelectboxString).show();
			}
//			jQuery(JQSelectboxString).trigger('change');
			afterItemIsSelected(jQuery(JQSelectboxString))
		}
	// alert(sUsedValues);
	}


	function getTRFilterString(){
		// create filtering string for TRs (from table column headers) - select only rows passing the filter
		// example :: jQuery("#productVariantsBase tr:has(td.tbl_variantSelection_Colour:contains('Grey')):has(td.tblVariantSize:contains('small'))").css('background-color','yellow');
		var sFilterString = "tr";

		jQuery("#productVariantsBase tr th[className^='selected_variantSelection_']").each(function(){
			sFilterString += ":has(td."+ (jQuery(this).attr('className')).replace(/selected_/, "tbl_") +":contains('"+ jQuery(this).text() +"'))";
		});

		// just some debuging coloring to see which rows have been selected ..
		jQuery("#productVariantsBase tr td").css('background-color','white');
		jQuery("#productVariantsBase "+ sFilterString + " td").css('background-color','yellow');

		return sFilterString;
	}

	// Display "first" of the select boxes that has "options"
		jQuery("select.variantSelection:has(option)").hide();
		jQuery("select.variantSelection:has(option):first").show();

// -----------------------------------------------------------------
// ------ END PRODUCT VARIANTS SELECT BOXES
// -----------------------------------------------------------------

});
// END OF JQUERY READY function


	function EnableWishlistLink(){
		jQuery("#AddToWishlist a#wishlistAddItem").attr("title","Add To Your Wishlist");
	}
	function DisableWishlistLink(){
		jQuery("#AddToWishlist a#wishlistAddItem").attr("title","Please, select your product options first");
	}



//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//
//  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() {

		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];
		oForm.elements['qty'].value = oForm.elements['productQty'].value;
		var iQty = oForm.elements['productQty'].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 productCost = parseFloat(oForm.elements['varPrice'].value * parseInt(oForm.elements['productQty'].value,10));
			var sProductDetails =	'';
			sProductDetails = sProductDetails +	'<table>';
			sProductDetails = sProductDetails +	'<tr>';
			sProductDetails = sProductDetails +	'<td valign="top" class="basket_img">';
			sProductDetails = sProductDetails +	'<div id="ajax_basket_img"><img src="/public/pictures/products/small/' + oForm.elements['item_image_filename'].value + '"onerror="this.src=&#39;/public/pictures/products/additional/noimage.gif&#39;"/> </div>';
			sProductDetails = sProductDetails +	'</td>';
			sProductDetails = sProductDetails +	'<td valign="top">';
			sProductDetails = sProductDetails +	'<p id="ajax_basket_prodName">'+ oForm.elements['prodname'].value + '</p>';
			sProductDetails = sProductDetails + '<p id="ajax_basket_cost">' + sCurrencySymbol + productCost.toFixed(2) + '</p>';
			sProductDetails = sProductDetails + '<p id="ajax_basket_variants">' +  oForm.elements['item_variant_option1'].value.replace(',','<br />') ;
			if (oForm.elements['item_variant_option2'].value.length > 0) {
				sProductDetails = sProductDetails + '<p id="ajax_basket_cost">' +  oForm.elements['item_variant_option2'].value.replace(',','<br />') ;
			}
			sProductDetails = sProductDetails +	'</p>';
			sProductDetails = sProductDetails +	'<p id="ajax_basket_qty">Qty: ' + oForm.elements['productQty'].value + '</p>';
			sProductDetails = sProductDetails +	'</td>';
			sProductDetails = sProductDetails +	'</tr>';

			sProductDetails = sProductDetails +	'</table>';

//			var oVariantInfo = getObject("oVariantInfo");
//			oVariantInfo.innerHTML = sProductDetails;
//			alert(sProductDetails);
//			_positionBasket();

			 // fetch ProductDetails to corresponding DIV
			jQuery("#oVariantInfo").html(sProductDetails);

			//Display the basket success message
			oBasketContainer.style.display = "block";

			 // Call NYRO plugin to show the ajaxBasket in the overlay
			var NyroContent = jQuery("#oBasketContainer").html();
			jQuery.nyroModalManual({
			      bgColor: '#cccccc',
			      width: 360,
			      minHeight: 200,
			      content: NyroContent
			    });
			timerComfirmation = self.setTimeout(function() {jQuery.nyroModalRemove()}, 5000)
			 // re-enable shopping button
			jQuery("a#form_" + p_sProdCode + "link").attr('href',"javascript:void(ValidateAndSubmit('form_" + p_sProdCode + "','" + p_sProdCode + "'))")
			jQuery("a#form_" + p_sProdCode + "link img").attr('src',"/public/images/buttons/addtoyourbag.gif")


//			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);
//			iYPosition = iYPosition - 500;
//			show_the_overlay();
//			document.getElementById('oBasketContainer').style.zIndex = 1000;
//			document.getElementById('display_overlay_bg').style.zIndex = 50;
//			oBasketContainer;
//			jQuery('#oBasketContainer').animate( {top: iYPosition}, {duration: 500}, 'linear' );

//			timerComfirmation = self.setTimeout(function() {_hideBasket()}, 5000)
	}

	// ----------------------------------------------------------------------------- _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);
//			hide_the_overlay();
//			jQuery('#oBasketContainer').animate( {top: iYPosition}, {duration: 500, complete: function() {_hideDiv();}}, 'linear' );

		}

	}


	// ----------------------------------------------------------------------------- _hideDiv()
	function _hideDiv() {
		oBasketContainer.style.display = "none";
		// start  Reset "Add To Basket" button

		var oAddToBasketButton = getObject('btnAdd' + p_sProdCode);
		oAddToBasketButton.src = '/public/images/buttons/addtoyourbag.gif';

		var oAddToBasketLink =  getObject('form_' + p_sProdCode + 'link');
		oAddToBasketLink.href = "javascript:void(ValidateAndSubmit('form_" + p_sProdCode + "','" + p_sProdCode + "'))";


	}

	// ----------------------------------------------------------------------------- _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 = 600 - (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 changeButton(oButtona, oButtonb)
{
	if (oButtona)
	{
		oButtona.disabled=false;
		oButtona.src='/public/images/buttons/selected.gif';
	}
	if (oButtonb)
	{
		oButtonb.src='/public/images/buttons/addtoyourbag.gif';
	}
}

function EnableBuyButton(prodcode)
{

	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);
	}

	// also enable Wishlist link
	EnableWishlistLink()
}


function DisableBuyButton(prodcode, message)
{

	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/addtoyourbag_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.productQty.value)) {
			bValid=false
			alert("Quantity must be valid number greater than 0");
			oForm.productQty.focus()
		}
		else if (!rIsNotZero.test(oForm.productQty.value)) {
			bValid=false
			alert("Quantity must be valid number greater than 0");
			oForm.productQty.focus()
		}
	}

	if (bValid) {
		//if (parseInt(oForm.productQty.value)>parseInt(oForm.item_stock.value) ) {
		if ( parseInt(oForm.item_product_StockCountdown.value ) < 2) {
//			if (parseInt(oForm.productQty.value)>parseInt(oForm.item_stock.value) {
			if (parseInt(oForm.productQty.value)>parseInt(oForm.item_stock.value) && parseInt(oForm.prodbehonzero.value)<2) {
				bValid=false;
				alert("Please select a different quantity, only " + oForm.item_stock.value + " available.");
				oForm.productQty.focus();
			}
		}
	}

	if (bValid) {
		oAJAXBasket.hideBasket();

		var oAddToBasketButton = getObject('btnAdd' + sProdCode);
		oAddToBasketButton.src = '/public/images/buttons/addingtobag.gif';

		 // disable shopping button
		jQuery("a#form_" + sProdCode + "link").attr('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);
	}
}


//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//
//  HTML MENU FUNCTIONS							//
//	(Up to 4 variant options can be used)		//
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 	//

	// setVarSelections - Process the selection from the current dropdown box and display the next if applicable
	function _setVarSelections(varObj, oForm, iPosition, sProdID, stock_behavior) {
		//iPosition is the number associated to each dropdown box

		//Set the number of variant options
		var varLimit = jQuery("select.variantSelection:has(option)").length;

		DisableBuyButton(sProdID,"");
		var selectedValue = varObj.options[varObj.selectedIndex].value;

		//Hide all unrequired dropdown boxes
		for(i=iPosition+1;i<=varLimit;i++) {
			jQuery("#select_variant_option"+i).hide();
		}

		//Reset all variant lists
		if(iPosition==1) {
			arrVariantsFiltered = arrVariants;
			arrVariants2 = arrVariantsFiltered;
			arrVariants3 = arrVariants;
			arrVariants4 = arrVariants;

		} else if(iPosition==2) {
			arrVariantsFiltered = arrVariants2;
			arrVariants3 = arrVariants2;
			arrVariants4 = arrVariants2;

		} else if(iPosition==3) {
			arrVariantsFiltered = arrVariants3;
			arrVariants4 = arrVariants3;
		} else if(iPosition==4) {
			arrVariantsFiltered = arrVariants4;
		}

		//The search term could span multiple variant option fields and therefore only the specific value should be checked
		//use "iPosition-1" to reference the correct value in the + delimited string
		var arrSearchTerms = new Array();
		for(i=0;i<arrVariantsFiltered.length;i++) {
			sSearchString = arrVariantsFiltered[i].split("+")[iPosition-1];
			arrSearchTerms.push(sSearchString);
		}

		//Search for dropdown list value returning the found position indexes
		var arrResult = arrSearchTerms.find(selectedValue);


		//Filter the results found and create a new temporary array containing the matched values
		var arrTemp = new Array();
		for(var i=0; i<arrResult.length; i++) {
			arrTemp.push(arrVariantsFiltered[arrResult[i]]);
		}

		//Set the arrVariantsFiltered array to contain only the latest matched values
		arrVariantsFiltered = arrTemp;

		//Process selection made from the dropdown box
		if (selectedValue ==0) {
			//The dropdown value selected is either out of stock or not a valid product variant option
			DisableBuyButton(sProdID,"");
		} else {
			//The dropdown value selected is a valid product variant option
			var nextSelectionObj;
			var bFound = false;

			//For each subsequent dropdown box
			//Find the next populated dropdown box and process.  Each dropdown box is populated with data on the page load if possible.
			for(var i=iPosition+1; i<=varLimit; i++) {
				nextSelectionObj = getObject('select_variant_option' + i);
				if(nextSelectionObj.options.length > 0) {
					currentIndex = i;

					//Set a found flag
					var bFound = true;

					//Display the next dropdown list and exit loop
					nextSelectionObj.style.display = 'inline';
					break;
				}
			}

			//If not found, there are no further selection boxes to populate
			//Enable the buy button and populate the form product/variant data
			if(!bFound) {
				EnableBuyButton(sProdID)
				var selectedVarValue = arrVariantsFiltered[0];
				var arrVarVal = selectedVarValue.split("+");
				var sVar1 = arrVarVal[0];
				var sVar2 = arrVarVal[1];
				var sVar3 = arrVarVal[2];
				var sVar4 = arrVarVal[3];
				var sVarId = arrVarVal[4];
				var sPrice = arrVarVal[5];
				var sStock = arrVarVal[6];
				var sIsObsolete = arrVarVal[7];

				jQuery('#item_variant_option1').val(sVar1);
				jQuery('#item_variant_option2').val(sVar2);
				jQuery('#item_variant_option3').val(sVar3);
				jQuery('#item_variant_option4').val(sVar4);
                jQuery('#variantid').val(sVarId);
                jQuery('#varPrice').val(sPrice);
                jQuery('#item_stock').val(sStock);

				return;
			}

			//Process the new values for the latest dropdown box to be display
			//Remove all current selection options
			for(var i=nextSelectionObj.options.length-1;i>=0;i--) {
				nextSelectionObj.remove(i);
			}

			//Create a new "Please Select..." initial option
			var optn = document.createElement("OPTION");
			optn.text = "Please Select... ";
			optn.value = "0";
			nextSelectionObj.options.add(optn);

			//Only distinct option values are displayed. The array is sorted so checking the previous value against the current should be sufficient.
			//Set variable to hold the previous option value
			var sPreviousValue = '';

			//Process each of the matched values held within the filtered array
			for(var i = 0;i<arrResult.length;i++) {

				//Each filtered array value contains a string of '+' delimited values.  (all required values for individual variant options eg, option1..optionN, variantID, price, stock)
				var tmpStr = new String(arrVariantsFiltered[i]);
				var arrStr = tmpStr.split("+");

				//PLEASE NOTE:  The value position within each array element is constant.
				//Therefore the dropdown value can be determined by subtracting 1 from the currentIndex variable set above
				var dropDownVar = arrStr[(currentIndex-1)];

				//If the dropdown value doesn't match the previous value - ie, valid new value to display
				if(sPreviousValue != dropDownVar) {
					var sVar1 = arrStr[0];
					var sVar2 = arrStr[1];
					var sVar3 = arrStr[2];
					var sVar4 = arrStr[3];
					var sVarId = arrStr[4];
					var sPrice = arrStr[5];
					var sStock = arrStr[6];
					var sIsObsolete = arrStr[7];
					var sAction = "NOSHOW" //DONT SHOW IN DROPDOWN

					optn = document.createElement("OPTION");

					//Determine whether there are further selections lists to choose from.  Determine the number and store in a variable
					var xCounter = 0;
					for(var x=iPosition; x<varLimit; x++) {
						if(arrStr[x].length > 0) {
							xCounter++;
						}
					}

					//xCounter = 1 :  This will be the last selection box to be show.
					if(xCounter == 1) {
						//Display any stock information
						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" && sIsObsolete != 1) { // <!-- stock behaviour Allow back orders -->
							if(sIsObsolete != 1) {
								sAction = "I"; // SHOW AS INSTOCK
							}
						} else if(stock_behavior == "3" && sIsObsolete != 1) { // <!-- 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 = dropDownVar + ' - ' + lowstockmessage ; // + (sAction == "" ? "" : (" => " + sAction));
								} else {
									optn.text = dropDownVar + ' - ' + outofstockmessage ;
								}
							} else {
								optn.text = dropDownVar ;
							}
							optn.value = sAction == "O" ? "0" : dropDownVar;
							nextSelectionObj.options.add(optn);
						} else {
							//Variant is set to hide from displaying
							//optn.text = dropDownVar + ' - ' + outofstockmessage ; // + (sAction == "" ? "" : (" => " + sAction));
							//optn.value = sAction == "O" ? "0" : dropDownVar;
							//nextSelectionObj.options.add(optn);
						}
					} else {
						//Display no stock information
						optn.text = dropDownVar;
						optn.value = dropDownVar;
						nextSelectionObj.options.add(optn);
					}
				}

				sPreviousValue = dropDownVar;

				//Set all variant lists
				if(iPosition==1) {
					arrVariants2 = arrVariantsFiltered;
					arrVariants3 = arrVariants2;
					arrVariants4 = arrVariants2;

				} else if(iPosition==2) {
					arrVariants3 = arrVariantsFiltered;
					arrVariants4 = arrVariants3;

				} else if(iPosition==3) {
					arrVariants4 = arrVariantsFiltered;
				} else if(iPosition==4) {
				}


			}
		}
	}

// -----------------------------



/* for html menu */

		function setVarOptionsSingleVariant(oForm,sProdID,stock_behavior,sVarId,sPrice,sStock,sIsObsolete,sColour,sSize,svariant_image)
		{
			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_variant_image'].value = svariant_image ;
			var iQty = oFormVar.elements['productQty'].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,"");
			}

		}


		function setVarOptions(oSelect,oForm,sName,sProdID,stock_behavior)
		{
			var selectedVarValue = oSelect.options[oSelect.selectedIndex].value;
			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 svariant_image = arrVarVal[6];


			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_variant_image'].value = svariant_image ;

			var iQty = oForm.elements['productQty'].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,"");
			}


		}

		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 svariant_image = arrStr[6];

						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,svariant_image)

{
	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 , svariant_image )

	if(document.forms['form_' + varProductID].elements['varPrice'].value != '')
	{
		oElementc.href = "javascript:ValidateAndSubmit('" + sForm +  "','" + varProductID +  "')";
		changeButton('', oElementb);
	}

}

/* Quantity validation */
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;
	}




function show_the_overlay() {
	document.getElementById('display_overlay_holder').style.display = 'block';
	}

function hide_the_overlay() {
	document.getElementById('display_overlay_holder').style.display = 'none';
	}