﻿// this is largely a re-worked version of Options.js, but is designed specifically for Collection pages (basically department pages showing multiple products
// where you can buy multiple products with the same add-to-basket - so we need to show separate option dropdowns for each product. - tricky.																										 

// mind dump of what needs to happen:

/*

	All the colour/size/option divs that hold the selects will be prefixed with the sku.
	All the option data itself will be held in an associative array, keyed by the sku.
	
	we then need to loop over the option data array and update each option div with the required select list etc.


optiondata needs these keys building by the template. template will need to add to this structure as it templates each product:

OptionsData =  new Array();
OptionsData[0] = new Object();
OptionsData[0]["price"] = 70.0000;
OptionsData[0]["colour"] = "No Colour";
OptionsData[0]["l_colour_img"] = "0";
OptionsData[0]["specialprice"] = "0";
OptionsData[0]["description"] = "2284818905223";
OptionsData[0]["s_colour_img"] = "0";
OptionsData[0]["cost"] = 70.0000;
OptionsData[0]["size"] = "One Size";
OptionsData[0]["vatrate"] = 17.5000;
OptionsData[0]["stocklevel"] = 9999;


============================================
Assumes the following has been built in the product rendering template in javascript:

// --- following in department page template, above the products ----
OptionsData = new Array();

// --- /end ---------------------------------------------------------

// --- following in the product rendering template ------------------
OptionsData["%pub.product.skuEscaped%"] = new Array();
currentProductOptionCount = 0;
%pub.loopover|pub.product.complexOptions|products/complexOptionJSOutput|complexOption%

----- following in the looping option template "complexOptionJSOutput" ------

%complexOptionstart%
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount] = new Object();
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].price = %pub.product.complexOptions.price.valueFormatted%;
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].rrp = %pub.product.complexOptions.price.rrpFormatted%;
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].colour = '%pub.product.complexOptions.colour.description%';
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].size = '%pub.product.complexOptions.size.description%';
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].option = '%pub.product.complexOptions.option.description%';
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].largeColourSwatch = TO DO!;
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].smallColourSwatch = TO DO!;
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].vatRate = %pub.product.complexOptions.price.vat.rate%;
OptionsData["%pub.product.complexOptions.parentSkuEscaped%"][currentProductOptionCount].stockLevel = %pub.product.stock.level%;
currentProductOptionCount++;
%complexOptionend%
----------- end loop ------------------------


*/


//document.getElementById('add2cart').style.display="";

// I may wany to add some checking in at some point to ensure all the elements I am using below actually exist



// Populate the colours drop down box
function setupcolours(escapedProductSku){
	clearComplexFeature(escapedProductSku);		
	var thecolours=eval("document.le_form.colours_"+escapedProductSku);
	var thesizes=eval("document.le_form.sizes_"+escapedProductSku);
	var tmpOptionsData=eval("OptionsData['"+escapedProductSku+"']");

	var thecurrentcolourselection=thecolours[thecolours.selectedIndex].value;
	ClearOptions(thecolours);
	AddToOptionList(thecolours, "blank", "Select a colour");
	if (thesizes[thesizes.selectedIndex].value != "blank"){
		var tmpcolourarray = new Array();
		var tmpcolourarray_arr_pos=0;		
		for(od=0; od < OptionsData.length; od++) {
			if(tmpOptionsData[od].size == thesizes[thesizes.selectedIndex].value){
				tmpcolourarray[tmpcolourarray_arr_pos] = tmpOptionsData[od].colour;						
				tmpcolourarray_arr_pos++;	
			}		
		}
		tmpcolourarray.sort();
		for(i=0; i < tmpcolourarray.length; i++){
			AddToOptionList(thecolours, tmpcolourarray[i], tmpcolourarray[i]);
			if(thecurrentcolourselection == tmpcolourarray[i])
				var tmp_setselected=thecolours.options[thecolours.length-1].selected = true;
		}
		setupComplexFeature(escapedProductSku);
	} else {
		var tmpcolourarray=new Array();
		for(od=0; od < tmpOptionsData.length; od++) {
			if (od == 0) {
				tmpcolourarray[tmpcolourarray.length]=tmpOptionsData[od].colour;
			} 
			else {
				var addItem = true;
				for(ca=0; ca < tmpcolourarray.length; ca++) {
					if(tmpOptionsData[od].colour == tmpcolourarray[ca])
						addItem = false;
				}
				if (addItem)
					tmpcolourarray[tmpcolourarray.length] = tmpOptionsData[od].colour;	
			}
		}	
		tmpcolourarray.sort();
		for(i=0; i < tmpcolourarray.length; i++){
			AddToOptionList(thecolours, tmpcolourarray[i], tmpcolourarray[i]);
		}
	}	
}	
// Populate the sizes drop down box
function setupsizes(escapedProductSku){
	clearComplexFeature(escapedProductSku);

	var thecolours=eval("document.le_form.colours_"+escapedProductSku);
	var thesizes=eval("document.le_form.sizes_"+escapedProductSku);
	var tmpOptionsData=eval("OptionsData['"+escapedProductSku+"']");

	var thecurrentsizeselection=thesizes[thesizes.selectedIndex].value;
	ClearOptions(thesizes);
	if (thecolours[thecolours.selectedIndex].value != "blank"){
		AddToOptionList(thesizes, "blank", "Select a size");
		var tmpsizearray_arr_pos=0;	
		tmpsizearray=new Array();
		for(od=0; od < tmpOptionsData.length; od++) {
			if(tmpOptionsData[od].colour == thecolours[thecolours.selectedIndex].value){
				tmpsizearray[tmpsizearray_arr_pos]=new Object();
				tmpsizearray[tmpsizearray_arr_pos]["size"]=tmpOptionsData[od].size;
				tmpsizearray[tmpsizearray_arr_pos]["price"]=tmpOptionsData[od].price;
				tmpsizearray[tmpsizearray_arr_pos]["stocklevel"]=tmpOptionsData[od].stockLevel;					
				tmpsizearray_arr_pos++;	
			}		
		}			
//		myBubbleSort(tmpsizearray,tmpsizearray.length);			
		for(i=0; i < tmpsizearray.length; i++){
			//alert("price_fixed = "+tmpsizearray[i].price+" = "+ parseFloat(tmpsizearray[i].price));
			var	price_fixed = parseFloat(tmpsizearray[i].price);
			if(tmpsizearray[i].stocklevel == 0)
				var Opttext = tmpsizearray[i].size + " £" + price_fixed.toFixed(2) + " Out of stock";
			else
				var Opttext = tmpsizearray[i].size + " £" + price_fixed.toFixed(2);
			AddToOptionList(thesizes, tmpsizearray[i].size, Opttext);
			if(thecurrentsizeselection == tmpsizearray[i].size)
				var tmp_setselected=thesizes.options[thesizes.length-1].selected = true;
		}
		setupComplexFeature(escapedProductSku);
	} else {
		AddToOptionList(thesizes, "blank", " ............................ ");
		setupcolours(escapedProductSku);
	}	
}		
function myBubbleSort(arrayName,length) {
    for (var i=0; i<(length-1); i++) {
        for (var j=i+1; j<length; j++) {
            if (arrayName[j].size < arrayName[i].size) {
                var dummy = arrayName[i];
                arrayName[i] = arrayName[j];
                arrayName[j] = dummy;
            }
		}	
	}
}

// Set up complex feature value
function setupComplexFeature(escapedProductSku) {
	var theform = document.le_form;

	var thecolours=eval("document.le_form.colours_"+escapedProductSku);
	var thesizes=eval("document.le_form.sizes_"+escapedProductSku);
	var thecomplexfeature=eval("document.le_form.ComplexFeatures_"+escapedProductSku);
	var tmpOptionsData=eval("OptionsData['"+escapedProductSku+"']");
	
	var sel_col = thecolours.selectedIndex;
	var sel_siz = thesizes.selectedIndex;	
	
	if(thesizes[sel_siz].value == "blank"){
		thecomplexfeature.value = "";
	} else {
		var compset=false;
		for(od=0; od < tmpOptionsData.length; od++){
			if(tmpOptionsData[od].size == thesizes[sel_siz].value && 	tmpOptionsData[od].colour == thecolours[sel_col].value && tmpOptionsData[od].stocklevel != 0){
				var selectedOption = tmpOptionsData[od].colour + " |" + tmpOptionsData[od].size + " |" + tmpOptionsData[od].option + " |" + tmpOptionsData[od].price;
				thecomplexfeature.value = selectedOption;
				var	normalprice_fixed = parseFloat(tmpOptionsData[od].rrp);
				var	specprice_fixed = parseFloat(tmpOptionsData[od].price);
				if(document.getElementById('normalprice_'+escapedProductSku)){
					if (specprice_fixed != 0 && specprice_fixed < normalprice_fixed){
						document.getElementById('normalprice_'+escapedProductSku).innerHTML = "WAS £" + normalprice_fixed.toFixed(2);	
						document.getElementById('specialprice_'+escapedProductSku).innerHTML = "NOW £" + specprice_fixed.toFixed(2);
					}	
					else {
						document.getElementById('normalprice_'+escapedProductSku).innerHTML = "";					
						document.getElementById('specialprice_'+escapedProductSku).innerHTML = "Price £" + normalprice_fixed.toFixed(2);					
					}
				}	
				compset=true;					
			}
			if(!compset)
				clearComplexFeature(escapedProductSku);
		}			
	}	
}
function clearComplexFeature(escapedProductSku) {
	tmpCF = eval("document.le_form.ComplexFeatures_"+escapedProductSku);
	tmpCF.value = "";
}		
function ClearOptions(OptionList) {
	// Always clear an option list from the last entry to the first
	for (x = OptionList.length; x >= 0; x--) {
		OptionList[x] = null;
	}
}
function AddToOptionList(OptionList, OptionValue, OptionText) {
   // Add option to the bottom of the list
   var optnew = OptionText.replace("&#189;",String.fromCharCode(189));
   optnew = optnew.replace("&#189;",String.fromCharCode(189));
   optnew = optnew.replace("&#189;",String.fromCharCode(189));   
   OptionList[OptionList.length] = new Option(optnew, OptionValue);
}

function checkSelectionAndSubmit()
{
	userResponseMessage = "";
	for (var currentProductSku in OptionsData) {
		coloursSelect = eval("document.le_form.colours_"+currentProductSku);
		sizesSelect = eval("document.le_form.sizes_"+currentProductSku);
		qtySelect=eval("document.le_form.Quantity_"+currentProductSku);	
		complexFeatureField=eval("document.le_form.complexfeatures_"+currentProductSku);
	
		tmpMsg = "";
		if(qtySelect.selectedIndex)
		{
		
			if(coloursSelect.options[coloursSelect.selectedIndex].value != "blank" && sizesSelect.options[sizesSelect.selectedIndex].value != "blank" && complexFeatureField.value == "")
			{
				userResponseMessage += "The product ["+productTitles[currentProductSku]+"] is unfortunately out of stock and has been removed from your selection.\n";
				qtySelect.selectedIndex = 0;
			}
			else if(coloursSelect.selectedIndex == 0 && sizesSelect.selectedIndex == 0)
				userResponseMessage += "Colour and Size not selected for product ["+productTitles[currentProductSku]+"].\n";
			else if(coloursSelect.selectedIndex == 0)
				userResponseMessage += "Colour not selected for product ["+productTitles[currentProductSku]+"].\n";
			else if(sizeSelect.selectedIndex == 0)
				userResponseMessage += "Size not selected for product ["+productTitles[currentProductSku]+"].\n";

		}
	}
	if(userResponseMessage != "") 
	{
		alert("There has been a problem adding your selection to the basket for the following reason(s): \n\n" + userResponseMessage);
		return false;
	}
	return true;
	
}

	
	/* OLD!

function checkselectedoptions(obj){
	var theform = document.le_form;
	
	var thecolours=eval("document.le_form.colours_"+escapedProductSku);
	var thesizes=eval("document.le_form.sizes_"+escapedProductSku);
	var thequantity=eval("document.le_form.select_qty_"+escapedProductSku);	
	var thecomplexfeature=eval("document.le_form.complexfeatures_"+escapedProductSku);
	
	var sel_col = thecolours.selectedIndex;
	var sel_siz = thesizes.selectedIndex;
	var sel_qty = thequantity.selectedIndex;
	
	if(thecolours[sel_col].value == "blank"){
		alert("Please select a colour");
		return false;
	}
	if(thesizes[sel_siz].value == "blank"){
		alert("Please select a size");
		return false;
	}
	if(thecolours[sel_col].value != "blank" && thecolours[sel_col].value != "blank" && theComplexFeature.value == ""){
		warnProductOutOfStock(escapedProductSku);		
		return false;			
	}
	obj.disabled = true;
//	dcsMultiTrack('DCS.dcsuri','/mall/addToBasket.cfm','WT.ti','Add to Basket','WT.mc_id','','WT.srch','','WT.si_n','shop','WT.si_x','2','WT.pn_sku',theform.number.value,'WT.tx_u',theform.select_qty[sel_qty].value,'WT.tx_e','a');
	theform.submit();	
}

*/

// standard base select objects for colours + sizes


function collectionInit()
{
	// loop over add divs with classes 'sizes' and 'colours', and insert the default selects
//	$(".colours").each(function() {
 //      this.innerHTML = coloursdd_from});

//	$(".sizes").each(function() {
 //      this.innerHTML = sizesdd_from});

for (var currentProductSku in OptionsData) {
	coloursDiv = document.getElementById("colours_div_"+currentProductSku);
	sizesDiv = document.getElementById("sizes_div_"+currentProductSku);
	
	coloursDiv.innerHTML = '<select name="colours_'+currentProductSku+'" id="colours_'+currentProductSku+'" onchange="setupsizes(\''+currentProductSku+'\')"><option value="blank">Select a colour</option></select>';	
	sizesDiv.innerHTML = '<select name="sizes_'+currentProductSku+'" id="sizes_'+currentProductSku+'" onchange="setupComplexFeature(\''+currentProductSku+'\')"><option value="blank"> ............................ </option></select>';
	setupcolours(currentProductSku);
}


	
	
}





//if (document.le_form){
//	if (document.le_form.addtocart){
//		document.le_form.addtocart.onclick = ;
//	}
//}	

/*
// Make the javascript version of the product image popup appear	
if (document.getElementById('productimagelink'))	
	document.getElementById('productimagelink').style.display = "block";
// Make the javascript version of the product swatch object appear
//if (document.getElementById('swatch_objectjs'))	
//	document.getElementById('swatch_objectjs').style.display = "block";	

function changeimg(id){
	document.getElementById('prodimg').src=colourarray[id];
	swatchhighlighter(id);
}
function swatchhighlighter(id){
	for(i=0;i<colourarray.length-1;i++){
		document.getElementById('swatch_' + i).className="noborder";
	}
	document.getElementById('swatch_' + id).className="border";
	var colour=id+1;
	document.le_form.colours.options[colour].selected=true;		
	setupsizes();
}	
		*/
	
