/* ------------------------------------------------------------------
  Filename:        product.js
  Author:          Kailash
  Description:     Basic JavaScript functions
  								
  -------------------------------------------------------------------
 */
	
// function to bookmark the page
function bookmarkpage(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "");
else
alert("Sorry, your browser doesn't support this");
}


/**
 * Function to make the ajax call to add the product to comparison
 * 
 */ 
function addToComparison(url, styleCode, destHTML)
{ 

	var redirectToCookiePage = document.getElementById("redirectToCookiePage");
	if (redirectToCookiePage != null){
		window.top.location.replace("/sol/no_cookies.jsp");
	} else {

	    var xhr; 
	    try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
	    catch (e) 
	    {
	        try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
	        catch (e2) 
	        {
	          try {  xhr = new XMLHttpRequest();     }
	          catch (e3) {  xhr = false;   }
	        }
	     }
	    xhr.onreadystatechange  = function()
	    { 
	         if(xhr.readyState  == 4)
	         {
	              if(xhr.status  == 200)
	              {
	                processReponse(xhr.responseText, styleCode, destHTML)
	              }
	              else
	              { 
	                 alert("Error code " + xhr.status);
	              }
	         }
	    }; 
	
	   xhr.open('GET', url,  true); 
	   xhr.send(null);
	  
	   return false; 
  }
} 

/**
 * FUnction to parse the Ajax response from the addToComparison method. 
 * This checks for the presence of the tags for the minibasket and updates the same on the page.  
 **/ 
function processReponse(resText, styleCode, destHTML)
{
    var startIndex = resText.indexOf('<dl')
    var endIndex = resText.indexOf('</dl')
    var divSubString = resText.substring(startIndex, endIndex+5);
    if(document.getElementById("minibasket") != null ){
    document.getElementById("minibasket").innerHTML = divSubString;
    }
    
    if(document.getElementById(styleCode) != null ){
    document.getElementById(styleCode).innerHTML = destHTML;
    }
}

/**
 * Function invoked when the user clicks  the Show All link on the on the 
 * guided navigation component for disaplaying all the brands 
 **/ 
function showAll(divName)
{
    var showAllDivId = 'showAllDiv' + divName;
    var showAllValuesDivId = 'showAllValuesDiv' + divName;

    if(document.getElementById(showAllValuesDivId) != null ){
    document.getElementById(showAllValuesDivId).style.display = 'block';
    }
    if(document.getElementById(showAllDivId) != null) {
    document.getElementById(showAllDivId).style.display = 'none';
    }
}

/**
 * Function invoked on the body on load of the product browse screens.
 * It changes the Show All divs on the guided navigation component for the 
 * JS enabled and disabled    
 **/ 
function clearShowAll()
{
  lis=document.getElementsByTagName('li');
  for (var i=0;i<lis.length;i++)
  { 
    if (lis[i].id.indexOf('showAllDiv')==0)
    { 
      lis[i].style.display='block'; 
    } 
  } 

  divs=document.getElementsByTagName('div');
  for (var i=0;i<divs.length;i++)
  { 
    if(divs[i].id.indexOf('showAllValuesDiv')==0)
    { 
      divs[i].style.display='none'; 
    } 
  } 
}

/**
 * Function to check whether javascript is enable or not
 * If enabled it will show the bookmark and print link 
 **/ 
function checkScript()
{
    if (document.getElementById("bookmarkpage") != null)
    { 
       document.getElementById("bookmarkpage").style.display = "block";
    }
    if (document.getElementById("printpage") != null)
    { 
      document.getElementById("printpage").style.display = "block";
    }
    if (document.getElementById("viewmoreimages") !=null)
    {
      document.getElementById("viewmoreimages").style.display = "block";
    }
    clearShowAll();
}

/**
 *function for MultiSku items
 **/ 
function addOption(diff1Val, diff2Val, itemCode, 
		pricePounds, pricePence, priceRange, showWasNow, wasPrice, savePrice, pricesVary, nectarPoints, 
		inStock, imageUrl, roundelUrl, 
		promotions, deliveryPromotions,
		unselectedDiffs,
		standardDeliveryPrice,
		premiumDeliveryPrice) {    
  var index = productOptionsList.length;
  productOptionsList[index] = new Object();
  productOptionsList[index].key = Array(diff1Val, diff2Val);
  var opt = new Object();
  opt.itemCode = itemCode;
  opt.pricePounds = pricePounds;
  opt.pricePence = pricePence;
  opt.priceRange = priceRange;
  opt.showWasNow = showWasNow;
  opt.wasPrice = wasPrice;
  opt.savePrice = savePrice;
  opt.pricesVary = pricesVary;
  opt.nectarPoints = nectarPoints;
  opt.inStock = inStock;
  opt.imageUrl = imageUrl;
  opt.roundelUrl = roundelUrl;
  opt.promotions = promotions;
  opt.deliveryPromotions = deliveryPromotions;
  opt.unselectedDiffs = unselectedDiffs;
  opt.standardDeliveryPrice = standardDeliveryPrice;
  opt.premiumDeliveryPrice = premiumDeliveryPrice;
  productOptionsList[index++].value = opt;
  return opt;
}

function selectedDiff(elementId) {
  var diffElement = document.getElementById(elementId);
  if (diffElement == null) {
    return "default";
  }
  return diffElement.value;
}

function findOption(key) {
  for (i = 0; i < productOptionsList.length; i++) {
    var testOption = productOptionsList[i];
   if(testOption.key[0] == key[0] && testOption.key[1] == key[1]) {
      return testOption.value;
    }
  }
}

function getDisplayLabelFromDropdownValue(val) {
  if (val == "default") {
    return "Please select";
  }
  return val;
}

function updateDropdownOptions(updatedDiffIndex, updatedValue, otherDiffIndex, otherDiffPos) {
  var selectedOption = Array();
  selectedOption[updatedDiffIndex] = updatedValue;
  selectedOption[otherDiffIndex] = selectedDiff("diff" + otherDiffPos + "List");
  
  for(diffIndex = 0; diffIndex < 2; diffIndex++){
  	//e.g. if diffIndex = 0, we are updating the second dropdown based upon the option selected in the first 
    var diffPos = diffIndex + 1;
    var selectedValue = selectedOption[diffIndex];
    if (selectedValue == null) {
    	selectedValue = "default";
    }
    var otherDiffIndex = 1 - diffIndex; // 1= size, 0 = colour
    var otherDiffPos = 2 - diffIndex; // 2= size, 1 = colour
    var otherSelectedValue = selectedOption[otherDiffIndex];
    if (otherSelectedValue == null) {
    	otherSelectedValue = "default";
    }
    var selectElement = document.getElementById("diff" + (otherDiffPos) + "List");
    if (selectElement != null) {
	    var selChildren = selectElement.childNodes;
	    
	    var updates = Array();
	    
	    for (childIndex = 0; childIndex < selChildren.length; childIndex++) {
	      var child = selChildren[childIndex];
	      if (child.tagName == "OPTION") {
	        var diffValue = child.value;
	        var key = Array();
	        key[diffIndex] = selectedValue;
	        key[otherDiffIndex] = diffValue;
	        
	        var opt = findOption(key);
			var newLabel = getDisplayLabelFromDropdownValue(diffValue);        
	        if (opt != null) {
	          if (diffValue != "default" && otherSelectedValue != diffValue) {
					if (opt.pricesVary) {
						newLabel += " (";
						if (opt.priceRange) {
						  newLabel += "From ";
						}
						newLabel += "&pound;" + opt.pricePounds + "." + opt.pricePence;
						if (!opt.inStock) {
						  newLabel += ", out of stock";
						}
						newLabel += ")";
	 	            } else if (!opt.inStock) {
	 	            	newLabel += " (out of stock)";
	 	            }
	          }
	          child.innerHTML = newLabel;
	          child.disabled = null;
	          child.style.color = "black";
	        } else if (diffValue != "default") {
	          newLabel += " (not available)";
	          child.innerHTML = newLabel;
	          child.disabled = "disabled";
	          child.style.color = "gray";
	        }
	      }
	    }
	  }
  }
}
function selectOption(diffPos, value) {
	if (!dropdownInitialised[diffPos - 1]) {
		return;
	}

	var diff1;
	if (diffPos == 1) {
	  diff1 = value;
	} else {
	  diff1 = selectedDiff("diff1List");
	}
	var diff2;
	if (diffPos == 2) {
	  diff2 = value;
	} else {
	  diff2 = selectedDiff("diff2List");
	}
	
  	var otherDiffIndex = 2 - diffPos; // 1= size, 0 = colour
  	var otherDiffPos = 3 - diffPos; // 2= size, 1 = colour
	
	updateDropdownOptions(diffPos - 1, value, otherDiffIndex, otherDiffPos);
	
	
	var key = Array(diff1, diff2);
	var opt = findOption(key);
	var optionExists = true;
	if (opt == null) {
	  var diffList;
	  if(diffPos == 2){
	  	diff1 = "default";
	  	diff2 = value;
	  	diffList = "diff1List";
	  }
	  else{
	  	diff1 = value;
	  	diff2 = "default";
	  	diffList = "diff2List";
	  }
	  
	  updateDropdownOptions(otherDiffIndex, "default", diffPos - 1, diffPos);
	  key = Array(diff1, diff2);
	  opt = findOption(key);
	  document.getElementById(diffList).selectedIndex = 0;
	  document.getElementById(diffList).options[0].selected = true;
	}

	var canAdd = opt.inStock;
	var optionSelected = (diff1 != "default" || diff1Options.length <= 1) && (diff2 != "default" || diff2Options.length <= 1);	
	var addButtonDisplayStyle = "none";
	
	var skuCode = opt.itemCode;
	if (!optionSelected) {
		skuCode = "";
	}

	if (canAdd) {
		addButtonDisplayStyle = "block";

		//document.getElementById("addToBasketButton1").style.display = "block";
		 
		if (document.getElementById("mainskucode") != null)
		{
			document.getElementById("mainskucode").value = skuCode;
		}
		updateAllCrossSellSkuCodes(opt.itemCode);

	}

	if(document.getElementById("addToBasketButton1")!=null) {
		document.getElementById("addToBasketButton1").style.display = addButtonDisplayStyle;
	}      
	if(document.getElementById("addToBasketButton2")!=null) {
		document.getElementById("addToBasketButton2").style.display = addButtonDisplayStyle;
	}      
    if(document.getElementById("addToBasketQuantity")!=null) {
    	document.getElementById("addToBasketQuantity").style.display = addButtonDisplayStyle;
    } 

  if (optionExists) {
    document.getElementById("nowPrice").innerHTML = opt.pricePounds + "<span class=\"priceDecimal\">." + opt.pricePence + "</span>";
  } else {
  	document.getElementById("nowPrice").innerHTML = "&nbsp;";
  }
  priceLabelElement = document.getElementById("nowPriceLabel");
  
  if (priceLabelElement != null) {
	  if (opt.priceRange) {
	    priceLabelElement.innerHTML = "<strong>From</strong>";
	    priceLabelElement.style.display = "inline";
	  } else if (opt.showWasNow) {
	    priceLabelElement.innerHTML = "<strong>Now</strong>";
	    priceLabelElement.style.display = "inline";
	  } else {
	    priceLabelElement.innerHTML = "";
	    priceLabelElement.style.display = "none";
	  }
	  
	  var savePriceElement = document.getElementById("savePrice");
	  var wasPriceElement = document.getElementById("wasPrice");

	  if (opt.showWasNow) {

	    savePriceElement.innerHTML = "Save \u00a3" + opt.savePrice;
	    savePriceElement.style.display = "inline";
	    wasPriceElement.innerHTML = "&nbsp;Was <del>\u00a3" + opt.wasPrice + "</del>"
	    wasPriceElement.style.display = "inline";
	  } else {
	    savePriceElement.innerHTML = "";
	    savePriceElement.style.display = "none";
	    wasPriceElement.innerHTML = "";
	    wasPriceElement.style.display = "none";	    
	  }
  }
  if (opt.nectarPoints != null) {
    document.getElementById("nectarPoints").innerHTML = "Nectar points: " + opt.nectarPoints;
  } else {
    document.getElementById("nectarPoints").innerHTML = "";
  }
  if (opt.inStock) {
      document.getElementById("stockStatus").innerHTML = "In stock";
      if(document.getElementById("contactMeButton1")!=null) {
      	document.getElementById("contactMeButton1").style.display = "none";
      }
      if(document.getElementById("contactMeButton2")!=null) {
      	document.getElementById("contactMeButton2").style.display = "none";
      } 
  } else if (optionExists && (diff1 != "default" || diff1Options.length <= 1) && (diff2 != "default" || diff2Options.length <= 1)) {
      document.getElementById("stockStatus").innerHTML = "Out of stock";
      if(document.getElementById("contactMeButton1")!=null) { 
          var emailUrl =  document.getElementById("emailUrl") ;            
        	if (emailUrl!= null){  		       
                 var endIndex = emailUrl.href.indexOf('&skuCode=');                
                 var emailUrlString =  emailUrl.href.substring(0, endIndex+9);              
  			         emailUrl.href = emailUrlString + opt.itemCode;  			       
  	      }        
      	document.getElementById("contactMeButton1").style.display = "block";
      }
      if(document.getElementById("contactMeButton2")!=null) {
      var emailUrl =  document.getElementById("emailUrlCrossSell") ;            
            if (emailUrl!= null){              
                 var endIndex = emailUrl.href.indexOf('&skuCode=');                
                 var emailUrlString =  emailUrl.href.substring(0, endIndex+9);              
                     emailUrl.href = emailUrlString + opt.itemCode;                    
          } 
      	document.getElementById("contactMeButton2").style.display = "block";
      }
  } else {
      document.getElementById("stockStatus").innerHTML = "&nbsp;";
      if(document.getElementById("contactMeButton1")!=null) {
      	document.getElementById("contactMeButton1").style.display = "none";
      }
      if(document.getElementById("contactMeButton2")!=null) {
      	document.getElementById("contactMeButton2").style.display = "none";
      }   
  }
   //alert( opt.imageUrl);
  document.getElementById("bigImage").src = opt.imageUrl;
  document.getElementById("itemCode").innerHTML = "Item code: " + opt.itemCode;
  
  var unselectedDiffsElement = document.getElementById("unselectedDiffs");
  if (unselectedDiffsElement != null) {
	  unselectedDiffsElement.value = opt.unselectedDiffs;
  }
  
  var roundelElement = document.getElementById("roundel");
  var roundelIE6Element = document.getElementById("roundelIE6");
  
  var roundelUrl = "";
  if (opt.roundelUrl != null) {
  	roundelUrl = opt.roundelUrl;
  }
  
  if (roundelElement != null) {
  	//roundelElement.style.backgroundImage.url = roundelUrl;
  	roundelElement.style.backgroundImage = "url("+roundelUrl+")";
  }
  if (roundelIE6Element != null) {
  	roundelIE6Element.style.background.filter=
		"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', src='" 
 			 + roundelUrl + "');";
  }
  setPromotions(document.getElementById("productPromotions"), opt.promotions);
  setDeliveryPromotions(document.getElementById("deliveryOptions"), opt.deliveryPromotions);
  
  if((opt.standardDeliveryPrice != null) && (document.getElementById("standardDeliveryPrice") != null)){
  		document.getElementById("standardDeliveryPrice").innerHTML = opt.standardDeliveryPrice;
  }
  
    if((opt.premiumDeliveryPrice != null) && (document.getElementById("premiumDeliveryPrice") != null)){
  		document.getElementById("premiumDeliveryPrice").innerHTML = opt.premiumDeliveryPrice;
  }
}

function updateAllCrossSellSkuCodes(itemcode) {

	var primarySkuElements = document.getElementsByName("ADD_CART_ITEM_ARRAY._primaryProductSkuCode");
	for (i = 0; i < primarySkuElements.length; i++) {
		var element = primarySkuElements[i];
		if (element != null) {
			var isService = false;
			var parentElement = element.parentNode;
			if (parentElement != null) {
				var siblings = parentElement.childNodes;
				for (j = 0; j < siblings.length; j++) {
					if (siblings[j] != null 
						&& siblings[j].name == "ADD_CART_ITEM_ARRAY._isService"
						&& siblings[j].value == "true") {
						isService = true;
					}
				}
			}
			if (isService) {
				element.value = itemcode;
			}
		}
	}
}

function setPromotions(element, promos) {
  var newList = "";
  if (promos != null && promos.length > 0) {
    newList = "<p class=\"offerTeaser\"><strong>Great offers</strong></p>";
    for (i = 0; i < promos.length; i++) {
      newList += "<p>" + promos[i] + "</p>";
    }
    element.style.background = "rgb(254, 249, 235)";
  } else {
    element.style.background = "white";
  }
  element.innerHTML = newList;
}

function initDropdowns() {
	for (diffPos = 1; diffPos <= 2; diffPos++) {
		var diffDropdownId = "diff" + diffPos + "List";
		var diffValue = selectedDiff(diffDropdownId);
		
		dropdownInitialised[diffPos - 1] = true;
		selectOption(diffPos, diffValue);
		
	}
}
/**
 * function to open the more images pop up when the view more images link is clicked
 **/ 
function openViewMoreImagesPopUp(stylecode)
{
    infoBox('/sol/browse/more_images.jsp?styleCode=' + stylecode);
}

function setDeliveryPromotions(element, promos) {
  var newList = "";
  if (element!= null){
   traverseNode = element.firstChild;
    var i=1;
    while(traverseNode) {
     var traverseNodeName = traverseNode.getAttribute('name');
      if(traverseNodeName == 'freeDeliveryPromotion'){
         element.removeChild(traverseNode);
      }
      traverseNode = element.childNodes[i++];
      }
     }
    if (promos != null && promos.length > 0) {
      for (i = 0; i < promos.length; i++) {
        var newChild = document.createElement('dl');
        newChild.setAttribute('name','freeDeliveryPromotion');
        newChild.innerHTML = "<dt>" + promos[i] + "</dt><dd> </dd>";
        element.appendChild(newChild);
        }
      }  
}

/**
 * function to append/update 'sort' query variable to URL for persistence across pages
 **/
function setSort(ddObject)
{
	var sortString=ddObject.options[ddObject.selectedIndex].value;
	var urlString=new String(window.location);
	var newUrlString = changeUrlParam(changeUrlParam(urlString, 
			"pageNumber", 1),
			"sort", sortString); 

	window.location=newUrlString;
}

