// (c) IBM UK Ltd 2007

/**
 * Get an array of selected attributes which represents the item selected.
 * specified control prefix and productId.
 *
 * The array will contain objects from the generated attributeData Array.
 *
 * aForm - The form which contains the attribute selection controls
 * controlPrefix - The prefix used to identify the selection controls
 * controlProduct - The CatentryId of the product related to this attribute selection control
 */

var requestSubmitted = false;

function submitRequest() 
{
 if (!requestSubmitted )
  {
   requestSubmitted  = true;
   return true;
  }
 return false;
}

function getstockPercentage(product)
{
  var anItem;
  var stockCount = 0;
  var stockPercentage;
  var itemCount = itemData[product].length;
  for (var index = 0 ; index < itemData[product].length ; index++)
  {
    anItem = itemData[product][index];
	if (anItem.q > 0)
	{
	 stockCount++;
	}
  }
  stockPercentage = Math.round(stockCount/itemCount*100);
  return stockPercentage;
}

function getSelections(aForm,controlPrefix,controlProduct)
{
  var selections = new Array();
  var selectControl;
  var selectedOption;
  for (var index = 0; index < attributeData[controlProduct].length ; index++)
  {
    selectControl=eval("aForm."+controlPrefix+"_"+controlProduct+"_"+index);
	if ((0 != selectControl.selectedIndex) && (selectControl.type != 'hidden'))
	{
	  selectedOption=selectControl.options[selectControl.selectedIndex];
      selections[index]=attributeData[controlProduct][index][selectedOption.value];
	}
  }
  
  return selections;
}

/**
 * Return true if the item is defined by the selections.
 * See getSelections()
 *
 * The item in a object from the ItemData Array 
 *
 * item - An ItemData object (instances from ItemData Array)
 * selections - Array of selected defining attributes (instances from attributeData) 
 */
function isItemDefinedBySelections(item, selections)
{
  var selection;
 
  var attrKeys = item.attr.split(":");
  var match = true;

  for (var index = 0 ; (true == match) && (index < attrKeys.length) ; index++)
  {
	selection = selections[index];
	if (selection != undefined && null != selection) {
			match = (-1 < selection.keys.indexOf(attrKeys[index]));
	}  else	{
		 continue;
	}
  }
	
	return match;
}

/**
 * Find an Item specified by the selections for a product
 * 
 * The procduct is represented the CatentryId. The
 * selections 
 *
 * product - CatentryId of the product
 * selections - Array of selected defining attributes (instances from attributeData) 
 */
function findItem(product, selections)
{
var theItem;
var anItem
for (var index = 0; index < itemData[product].length ; index++)
   {
		anItem = itemData[product][index];
		if (true == isItemDefinedBySelections(anItem, selections))
		    {
			theItem = anItem;
			break;
			}
   }

   return theItem;
}

/*
 * Return true is the specified product has stock the to given selections
 *
 * product - CatentryId of the product
 * selections - Array of selected defining attributes (instances from attributeData)
 */
function hasInStockItemsFor(product,selections)
{
  var hasStock = false;
  var anItem;
    var s0 = selections[0];
	var s1 = selections[1];
	if (undefined != s0 && undefined != s1) {
	}
	for (var index = 0 ; index < itemData[product].length ; index++)
	{
		anItem = itemData[product][index];
		if (true == isItemDefinedBySelections(anItem, selections))
		{
			if (anItem.q > 0)
			{
				hasStock = true;
				break;
			}
		}
	}
	
	return hasStock;
}

/**
* Look up the current price for an item in the embedded arrays given the catentryId of the parent product
* and the selected drop down values.
* 
* product - the catentryId of the product
* selections - the selected valules from the drop down lists.
**/

function currentPriceFor(product,selections)
{
  	var hasStock = false;
  	var anItem;
  	var s0 = selections[0];
  	var s1 = selections[1];
  	var currentPrice;
	
	for (var index = 0 ; index < itemData[product].length ; index++) {
		anItem = itemData[product][index];
		if (true == isItemDefinedBySelections(anItem, selections)) {
			currentPrice = anItem.cp;
		}
	}
	
	return currentPrice;
}


/**
 * Action an attribite selection change for the specified control.
 * 
 * The related controls will be repopulated.
 
 * selectControl - the attribute selection control which changed.
 */
function attributeSelectionChanged(selectionControl)
{
	var form = selectionControl.form;
	var controlName = selectionControl.name.split("_");
	var controlPrefix = controlName[0];
	var controlProduct = controlName[1];
	var controlIndex = controlName[2];
	
	var selections = getSelections(form,controlPrefix,controlProduct);

	secondControl = eval("document.OrderItemAddForm." + controlPrefix + "_" + controlProduct +"_" + eval(controlIndex+1));
	if(controlIndex == 0 && secondControl != undefined && secondControl.type != 'hidden'){
		repopulateAttrSelection(controlProduct, eval(controlIndex+1), secondControl, selections );
	}
	if((controlIndex==1) || (controlIndex == 0 && (secondControl == undefined || secondControl == null || secondControl.type == 'hidden'))){
		if(selections.length == 0 || (controlIndex == 1 && selections.length == 1)){
			document.getElementById("price").innerHTML = document.getElementById("originalPrice").innerHTML;
		}
		else {
			writeWasNowNowPrices(controlProduct, selections);
		}
	}
}

/**
 * As above, with the exception that it sets the quantity for the main product on the page to 1
 */
function primaryProductSelectionChanged(selectionControl)
{
	attributeSelectionChanged(selectionControl);
	
	if(eval(document.OrderItemAddForm.quantity_1.length == null)){
		document.OrderItemAddForm.quantity_1.value=1;
	}
}

/**
* Apply the was was now pricing rules for the selected SKU and display them.
* The prices are in the javascript arrays on the product page.
*
* product - the catentryId of the product
* selections - the attributeData objects that were selected
**/
function writeWasNowNowPrices(product, selections){

	var item = findItem(product, selections);
	// Pricing Rules
	
		
	//Rule 1 - original price is less than the current price, only show the current price
	if(item.op <= item.cp ){
		document.getElementById("price").innerHTML = "<h3 class='context'>Price</h3><p><span class='price-actual'>&pound;" + item.cp.toFixed(2) + "</span></p> ";
	}
	// Rule 2 - Where Original > Current but Current >= Previous show Was (original) Now (current) only
	else if((item.op > item.cp) && (item.cp > item.pp)){
		document.getElementById("price").innerHTML = "<h3 class='context'>Price</h3><p><span class='price-former-01'>Was &pound;"	+ item.op.toFixed(2) + " ></span> " +
													 "<span class='price-actual sale'>Now &pound;" + item.cp.toFixed(2) + "</span></p> ";
	}
	// Rule 3 -	Where Original > Previous > Current show Was (original) Now (previous) Now (current)
    else if ((item.op > item.pp) && (item.pp > item.cp)){
    	document.getElementById("price").innerHTML = "<h3 class='context'>Price</h3><p><span class='price-former-01'>Was &pound;" +item.op.toFixed(2) + " ></span> " +
												 "<span class='price-former-02'>Now &pound;"	+ item.pp.toFixed(2) + " > </span> " +
												 "<span class='price-actual sale'>Now &pound;" + item.cp.toFixed(2) + "</span></p> ";
    }
    // Rule 4 Where Original > Current but Original < Previous show Was (previous) Now (current) only (this should never happen)      
    else if((item.op > item.cp) && item.op < item.pp){
    	document.getElementById("price").innerHTML = "<h3 class='context'>Price</h3><p><span class='price-former-01'>Was &pound;" +item.pp.toFixed(2) + " ></span> " +
    												  "<span class='price-actual sale'>Now &pound;" + item.cp.toFixed(2) + "</span></p> ";
    }
	// Rule 5 Where Original > Current and previous price is equivalent to original price.    
    else if((item.op > item.cp) && item.op == item.pp){
    	document.getElementById("price").innerHTML = "<h3 class='context'>Price</h3><p><span class='price-former-01'>Was &pound;" +item.pp.toFixed(2) + " ></span> " +
    												  "<span class='price-actual sale'>Now &pound;" + item.cp.toFixed(2) + "</span></p> ";
    }
	else{					
		document.getElementById("price").innerHTML = "<h3 class='context'>Price</h3><p><span class='price-actual'>&pound;" + item.cp.toFixed(2) + "</span></p> ";
	}
}
/**
 * Simple test for a selection within a control
 *
 * selectControl - the attribute selection control to test
 */
function hasSelection(selectionControl)
{
  return (selectionControl.selectedIndex > 0);
}

/**
* deprecated (?)
**/
function showPriceFor(selections)
{
	var showPrice = true;
	var aSelection;
	for (var i=0; showPrice && (i < selections.length - 1) ; i++)
	{
		aSelection = selections[i];
		showPrice = (undefined != aSelection && null != aSelection);
	}
	
	return showPrice;
}

/**
 * Populate an attribute selection control with no selections.
 *
 * product - CatentryId which represents the product
 * attrIndex - The index of the definingAttribute (e.g 0=Colour, 1=Size) The order is set by the Attribute sequence 
 * selectControl - the attribute selection control to populate
 */
function populateAttrSelection(product, attrIndex, selectControl) 
{
   repopulateAttrSelection(product, attrIndex, selectControl,[]);
}

/**
* If the product has multiple SKUs populate the colour and size drop down boxes
*
* product - the catentryId of the product to populate
**/

function populateSelections(product,productFlag){

	var numberOfDefiningAttributes = attributeData[product].length;
	var definingAttributesWithMultipleValues= false;
	
	for(var i=0; i < numberOfDefiningAttributes; i++){
		aSelectionControl = eval("document.OrderItemAddForm.defattr_"+product+"_"+i);
		if(aSelectionControl.type != 'hidden'){
			populateAttrSelection(product, i, aSelectionControl);
			definingAttributesWithMultipleValues = true;
		}
	}
	if(!definingAttributesWithMultipleValues && (document.OrderItemAddForm.quantity_1.value == "") && productFlag){
		document.OrderItemAddForm.quantity_1.value=1;
	}
	
}

function populateAllAttrSelections(product){

	//popualte the selections for the product
	var productFlag = true; // Trac 01326A
	populateSelections(product,productFlag);	
	
	// populate drop down boxes for cross sells, if there is more than one 
	// product on the page.
	var prodonpagecount=document.OrderItemAddForm.productcount.value;
	if(prodonpagecount > 1){
		productFlag=false;
		for(var i=2; i <= prodonpagecount; i++){
			populateSelections(eval("document.OrderItemAddForm.entryId_"+i+".value"),productFlag);
		}
  		document.getElementById("more-items").innerHTML = "or choose more items below";
	}
}

/**
 * Repopulate an attribute selection drop down lists with defining attribute values and append stock and price information.
 * The selections are used to determine the stock status and price.
 *
 * product - CatentryId which represents the product
 * attrIndex - The index of the definingAttribute (e.g 0=Colour, 1=Size) The order is set by the Attribute sequence
 * selectControl - the attribute selection control to populate
 */
 
function repopulateAttrSelection(product,attrIndex, selectControl, selections) 
{
    var attrVals = attributeData[product][attrIndex];
	var attrVal;
	var option;
	var stock;
	// If this product a cross sell, the first item in the drop down should be either "choose colour" or "choose size"
	if(product != document.OrderItemAddForm.entryId_1.value){
		if(attrIndex == 0){
			option = new Option("choose colour","X");
		}
		if(attrIndex == 1){
			option = new Option("choose size","X");
		}
	}
	// else if it is the main product the first item in the list should be blank
	else{
		option = new Option("","X");
	}
	if(selectControl.type != 'hidden') {
		selectControl.options[0]=option;
		for (var index = 0 ; index < attrVals.length ; index++)
		{
		  attrVal = attrVals[index];
		  selections[attrIndex]=attrVal; 
		  // If this is the main product on the page popualte the list and append stok and price information
		  if( document.OrderItemAddForm.entryId_1.value == product ) {
		  	if (attrIndex == 0){
		  	var secondControl = eval("document.OrderItemAddForm.defattr_" + product + "_1");
		  		// If the product has both colour and size drop down lists the first list should only have the attribute value, with no price or
		  		// stock information
		  		if ((secondControl != null) && (secondControl.type != 'hidden')){	
			  		option = new Option(attrVal.val,attrVal.id);
			  	}
			  	// if not the price and stock should be appended to the attribute value
			  	else {
		  			stock = hasInStockItemsFor(product,selections) ? " - £" + currentPriceFor(product,selections).toFixed(2) : "- out of stock";
		  			option = new Option(attrVal.val+stock,attrVal.id);
		  		}
		  	}
		  	// Always add stock and price iformation is there is only one drop down list.
		  	else{
		  		stock = hasInStockItemsFor(product,selections) ? " - £" + currentPriceFor(product,selections).toFixed(2) : "- out of stock";
		  		option = new Option(attrVal.val+stock,attrVal.id);
		  	}
		  }
		  // otherwise just populate the list
		  else{
		  	option = new Option(attrVal.val,attrVal.id);
		  }
		  selectControl.options[index+1]=option;
		}
	}
}

/**
* If the product page is called from the basket using the Amend URL this function is called to 
* repopulate the drop down boxes with the appropriate drop down values for the item that the 
* shopper added to their basket.
*
* productId - catentryId of the parent product of the SKU that was added to the basket.
* skuId - catentryId of the SKU that was added to the basket.
**/

function findChosenAttributes (productId, skuId){

  populateAllAttrSelections(productId);
  for (var index = 0; index < itemData[productId].length ; index++) {
  	
	var attrval = itemData[productId][index];
    if(attrval.id == skuId) {

    	var controlName = attrval.attr.split(":");
    	for (var i = 0; i < attributeData[productId].length ; i++){

    		var attrvals= attributeData[productId][i];
    		for (var j = 0; j < attrvals.length ; j++){
    			var specificAttrVals = attrvals[j];
    			if (specificAttrVals != undefined && null != specificAttrVals) {
    			
					// there are always the same number of controls as there is elements in the attributeData array
					if (-1 != specificAttrVals.keys.indexOf(controlName[i])){
						var dropDownIndex = eval(specificAttrVals.id);
						selectControl=eval("document.OrderItemAddForm.defattr_"+productId+"_"+i);
						selectControl.value = dropDownIndex;
						break;
					}
				}  
    		}
    	}
    	break;
    }
  }
  var prodonpagecount=document.OrderItemAddForm.productcount.value;
  if(prodonpagecount > 1){
  	document.getElementById("more-items").innerHTML = "or choose more items below";
  }
  
  var form = eval("document.OrderItemAddForm");
  var controlPrefix = "defattr";
  writeWasNowNowPrices(productId, getSelections(form,controlPrefix,productId));
}


/**
* When one of the text boxes on the merchanidsing association (cross sells) this function populates the hidden field catentry_x ( where
* x is the sequence number of the catentry in the list of associations. It populates it with the catentry_id of the SKU that has been
* selected, provided the quantity selected was greater than 0. This is so that the command the processes the Add to Basket Command knows 
* which cantentry_id the user wants to order.
*
* catentid - the catentryId of the SKU that was selected.
* seq - the sequence number of the catentry in the cross sell list.
**/

function assignCatentry(catentid,seq) {

	var selections = getSelections(document.OrderItemAddForm,"defattr",catentid);
	var item = findItem(catentid, selections);
	var field= eval("document.OrderItemAddForm.catEntryId_"+seq);
	if(eval("document.OrderItemAddForm.quantity_"+seq).value !=0) {
		field.value = item.id;
	} else {
		field.value="";
	}
}

/**
* Add items to the shopping cart
*
* 1. Find the attribtues that were selected on the page.
* 2. Find the catentry those attributes belong to
* 3. Validate the attributes
* 4. Determine whether it is an Amend, a Gift Centre add or a Add to Basket and submit the form.
*
* index - Used to indicate if this product should be added to a gift list or the basket
* productId - The catentryId of the product to add to the basket
**/

function addtocart(index, productId, linkIdStr, giftListUrl) {
   
 	var prodonpagecount=document.OrderItemAddForm.productcount.value;
	var selections = new Array();

	if(linkIdStr != null && linkIdStr != ""){
		_hbLink(linkIdStr);
	}
	
	selections = getSelections(document.OrderItemAddForm, "defattr", productId);
	var item = findItem(productId, selections);
	document.OrderItemAddForm.catEntryId_1.value = item.id;

	if(validateattribute(productId)){
		if(document.OrderItemAddForm.quantity_1.value==0) {
			document.OrderItemAddForm.catEntryId_1.value="";
		}	
	    if(document.OrderItemAddForm.pageAction.value=="AMEND") {
	       	 document.OrderItemAddForm.action="OrderItemAdd";
	         document.OrderItemAddForm.URL.value="OrderCalculate?URL=DEB_AmendProductCntrCmd";
	         if(submitRequest()){
	          document.OrderItemAddForm.submit();
	         }
	         else {
              return false;
             } 
	    }            
	    else if(document.OrderItemAddForm.pageAction.value=="GiftCenter" && index=="1"){
	         var submit_url = getAddToGiftListUrl();
	         document.getElementById('giftListFrameId').src = submit_url;
	         prompt(giftListUrl);
	    }
	    else {
	         document.OrderItemAddForm.action="DebOrderItemAdd";
	         document.OrderItemAddForm.URL.value='OrderCalculate?URL=OrderItemDisplay?orderId=&partNumber*=&quantity*=';
	         if(submitRequest()){
	          document.OrderItemAddForm.submit();
	         }
	         else {
              return false;
             } 
	    }
	}
}	

function openguide(url) {
	if(url.indexOf("Size_Guide")>=0)
		var tmp= window.open("HelpView?propFile="+escape(url),"","top=15,left=100,width=700,height=653,resizable=0,scrollbars=1")
	else
 		var tmp= window.open("HelpView?propFile="+escape(url),"","top=200,left=200,width=600,height=400,resizable=0,scrollbars=1")
}

// Called from the swatch images if they appear on the product page.
function selectcolor(control,dropdownseq) {
	
	eval(control).value=dropdownseq;
	
	if(eval("document.OrderItemAddForm.quantity_1").length == null){
		document.OrderItemAddForm.quantity_1.value=1;
	}
	
	// attributeSelectionChanged needs to be fired to update the drop down to make it the same value as the user clicked on.
	attributeSelectionChanged(eval(control));
}

/**
* Validate that the user has selected a valid quantity for all the products they have selected drop down values for before adding to the basket.
* Validate that the user has selected atrributes from all the drop down lists for which they have entered a quantity.
*
**/
function validateattribute() {
	
	var selections = new Array();
	var selectControl;
	var selectedOption;
	
	var prodonpagecount=document.OrderItemAddForm.productcount.value;
		
		// ensure there is at least one quantity on the page that is greater than 0
		var validQuantity = false;
		
		for (var i = 1; i <= prodonpagecount ; i++) {
	  		if((eval("document.OrderItemAddForm.quantity_"+i).value != "") && (eval("document.OrderItemAddForm.quantity_"+i).value != 0)){
				validQuantity = true;
			
				product = eval("document.OrderItemAddForm.entryId_" + i + ".value");
				
				// Check that if the user has selected a colour or size they have also entered a quantity
				// and that if they have entered a quantity they have also made selections from all the 
				// drop down lists.
			  	for (var index = 0; index < attributeData[product].length ; index++)
			  	{
			    	selectControl=eval("document.OrderItemAddForm.defattr_"+product+"_"+index);
					if (selectControl.type != 'hidden')
					{
						if(selectControl.selectedIndex == 0 && (eval("document.OrderItemAddForm.quantity_"+i).value != "")){
							alert("Please select a colour and/or size for the product you wish to add to the basket.");
				  			return false;
						}
						else if(selectControl.selectedIndex != 0 && (eval("document.OrderItemAddForm.quantity_"+i).value == "")){
							alert("Please enter a quantity greater than 0  for the product you wish to add to the basket.");
							return false;
						}
						else if(selectControl.selectedIndex != 0 && (eval("document.OrderItemAddForm.quantity_"+i).value == 0)){
							alert("Please enter a quantity greater than 0  for the product you wish to add to the basket.");
							return false;
						}
				  		selectedOption=selectControl.options[selectControl.selectedIndex];
				  		if(selectedOption.text.indexOf("out of stock") != -1){
				  			alert("The product you have selected is out of stock. Please choose a different colour or size.");
				  			return false;
				  		}
					}
			  	}
		  	}
	  	}
	  	
	  	if (!validQuantity){
	  		alert("Please enter a quantity greater than 0 for the product you wish to add to the basket.");
	  		return false;
	  	}
	  	
	return true;
}


/**
* [CR-175]Prepares the URL for making a background request to the server
**/ 
function getAddToGiftListUrl() {
    var storeId=document.OrderItemAddForm.storeId.value;
	var catalogId=document.OrderItemAddForm.catalogId.value;
	var langId=document.OrderItemAddForm.langId.value;
	var orderId=document.OrderItemAddForm.orderId.value;
	var URL='DEB_GiftCenterAddCntrCmd';
	var errorViewName=document.OrderItemAddForm.errorViewName.value;
	var entryId_1=document.OrderItemAddForm.entryId_1.value;
	var catEntryId_1=document.OrderItemAddForm.catEntryId_1.value;
	var categoryId=document.OrderItemAddForm.categoryId.value;
	var productId=document.OrderItemAddForm.productId.value;
	var websideStoryCatText=document.OrderItemAddForm.websideStoryCatText.value;
	var pageName=document.OrderItemAddForm.pageName.value;
	var pageAction=document.OrderItemAddForm.pageAction.value;
	var quantity_1=document.OrderItemAddForm.quantity_1.value;
	var submit_url='/webapp/wcs/stores/servlet/OrderItemAdd?storeId='+storeId+'&catalogId='+catalogId;
	submit_url=submit_url+'&langId='+langId+'&orderId='+orderId+'&URL='+URL+'&errorViewName='+errorViewName;
	submit_url=submit_url+'&entryId_1='+entryId_1+'&catEntryId_1='+catEntryId_1+'&categoryId='+categoryId;
	submit_url=submit_url+'&productId='+productId+'&websideStoryCatText='+websideStoryCatText;
	submit_url=submit_url+'&pageName='+pageName+'&pageAction='+pageAction+'&quantity_1='+quantity_1;
	return submit_url;
}	
   
/**
* 1.[CR-175] Prompts the user with a option of adding more products or return to debenhamsweddings.com site
* 2.[CR-175] Builds the URL for the debenhamsweddings.com
* 
* giftListUrl - The URL of the debenhams' weddings site
**/                      
function prompt(giftListUrl) {
    
    var answer = confirm ("Please press on OK to add more products, or CANCEL to review the products you have already added.");
    if (!answer)
    window.location = giftListUrl;
}    



