// from site-js
// important! this chunk needs to come first, because there
// are redefinitions below, so we need to preserve the ordering.


//Function changeImage() changes the image by overwriting the src of the image.
//Added for the topnav image change for mouse-over.
function changeImage(element, newImg) {
    if(document.images[element] && newImg) {
        document.images[element].src = newImg;
    }
}

function openPopupWindow(url,popup_options,popupName) {
//hack as I don't know who all are calling this function
   var propArray = popup_options.split(",");
   var len = propArray.length;
   var temp;
   var popupWidth;
   var popupHeight;
   for(i=0;i<len;i++){
      temp = propArray[i];
      if(temp.indexOf("height=") != -1){
         popupHeight = temp.substring(temp.indexOf("height=") + 7,temp.length);
      }else if(temp.indexOf("width=") != -1){
         popupWidth = temp.substring(temp.indexOf("width=") + 6,temp.length);
      }

   }
   var leftPos = (screen.width - popupWidth)/2;
   var topPos = (screen.height - popupHeight)/2;
   popup_options = reconstructPopOptions(propArray,leftPos,topPos);
   popupName = popupName ? popupName : 'popup';
   win = window.open(url,popupName,popup_options);
   if (win) {
       win.focus();
   }
}

function reconstructPopOptions(propArray,left,top){
   var opt ="";
   var len = propArray.length;
   for(i=0;i<len;i++){
      temp = propArray[i];
      if(temp.indexOf("left=") != -1 || temp.indexOf("top=") != -1){
         if(temp.indexOf("left=") != -1){
            temp = "left=" + left;
         }else{
            temp = "top=" + top;
         }
      }
      opt += temp + ",";
   }
   //add left and top position if not already present
   if(opt.indexOf("left=") == -1) {opt += "left=" + left;opt += ",";}
   if(opt.indexOf("top=") == -1) {opt += "top=" + top;opt += ",";}
   return opt;
}

function createTarget(form) {
  target = form.target;
  colon = target.indexOf(":");
//The following code stores the name and the parameters of the target in form.target and form.args respectively
  if(colon != -1) {
      form.target = target.substring(0,colon);
      form.args = target.substring(colon+1);
  } else if(typeof(form.args)=="undefined") {
      form.args = "";
  }
//The following line removes all the spaces
  form.args = form.args.replace(/ /g,"");
//The following code calls the window open function with the parameters retrieved above
  win = window.open('',form.target,form.args);
  if(typeof(focus)=="function"){
      win.focus();
      return true;
  }
}

//This function is used to hide Enter e-mail address message when the user clicks on the input box.
function checkEmail(obj,mode){
  if (mode == "f"){
     if (obj.value == "Enter e-mail address"){
        obj.value = "";
     }
  }else{
     if (obj.value == ""){
        obj.value = "Enter e-mail address";
     }
   }
}
//To hide all divs
function hideAllDivs() {
 var featureCount = document.getElementById('featureCount').value;
 for (featureTabCounter = 0; featureTabCounter < featureCount; featureTabCounter++) {
   document.getElementById("div"+featureTabCounter).style.display = "none";
 }
}




// generic function used for CSS-based effects
// show/hide items, etc. by changing their CSS class
function changeClass(id, classNameOld, classNameNew) {
        var element = document.getElementById(id);
        if (!element) return false;   
        var classes = element.className;        // is actually a space-delimited set of class names

        var matchOld = new RegExp("\\b" + classNameOld + "\\b");        // match whole word
        if (!matchOld.test(classes)) {
                return false;   // let caller know that no change was made
        }
        element.className = classes.replace(matchOld, classNameNew);
        return true;
}
 




// used with collapseList on the browse page
function toggleListState(id) {
	// change collapsed list to expanded
	var success = changeClass(id, "collapsed", "expanded");
	// if that fails, we need to do the opposite
	if (!success) {
		changeClass(id, "expanded", "collapsed");
	}
}

function featureTabClick(tabCount) {
	var featureCount = document.getElementById('featureCount').value;
	if (!featureCount) {
	  return;
	}
	
	for (i = 0; i < featureCount; i++) {
		var tab_id = 'tab' + i;
		var div_id = 'div' + i;	
		// change the elements' class and let the rendering engine do all the work
		if (i == tabCount) {
			changeClass(tab_id, "featureTabInactive", "featureTabActive");
			changeClass(div_id, "featureDivInactive", "featureDivActive");
		} else {
			changeClass(tab_id, "featureTabActive", "featureTabInactive");
			changeClass(div_id, "featureDivActive", "featureDivInactive");
		}
	} 
}

//############################## added for compare functionality

function changeClass(id, classNameOld, classNameNew) {

// useful for toggling between two classes

 var element = document.getElementById(id);
 if (!element) {
  return;
 }

 var classes = element.className; // is actually a space-delimited set of class names
 var matchOld = new RegExp("\\b" + classNameOld + "\\b"); // match whole word
 if (!matchOld.test(classes)) {
  return false; // let caller know that no change was made
 }
 element.className = classes.replace(matchOld, classNameNew);
 return true;
}

function fnHighlightImage(obj,state){
  idStr = obj.id;
  if(state == true){  
  // setActiveState(obj.id);
    setActiveState("product-"+idStr);  
  }else{
   //setActiveState(obj.id,false);
    setActiveState(("product-"+idStr),false);
  }
}

//////////////////////////////////////////////////////







//////////////////////////////////////////////////////







///////////////////////////////////////////////////

// collapseList calls this, but we renamed the method

function toggleListState(id) {
 toggleExpandedState(id);
}


var comparedASINs = [];

var maxCompareItems = 5;

function showError(text) {
 // stub code. this function should insert text into
 // #dhtmlPopupMessage and raise that to the front
 alert(text);
}


function addASINToComparedASINs(ASIN) {
 // return value: whether add was performed
 if (comparedASINs.length == maxCompareItems) {
  showError(error_NoAvailableSlots);
  return false;
 }
 //if (comparedASINs.contains(ASIN)) {
 if (Array_contains(comparedASINs, ASIN)) {
  showError(error_AlreadyAdded);
  return false;
 }
 comparedASINs.push(ASIN);

 return true;
}

// by convention from expand/collapse, we pass in
// the productFloat's id, not its number

function addToCompareList(itemId) {
 // which item did we click on?
//var itemNumber = itemId.replace(/item/,'');
 // is it a valid id number? // showError(error_BadItemId);
// var asin = getASINFromItemNumber(itemNumber);
 //var success = addASINToComparedASINs(asin);
 //if (success) {
//  magic CSS:
  setActiveState(itemId);
  setExpandedState('compareBar'); // might be open already
  //var imgUrl = thumbnailsPath + 'micro-' + asin + '.gif';
 // var slot = getSlotFromItemNumber(comparedASINs.length - 1);
  // A "slot" is one of the 5 spaces inside the compareBar.
 // setTitleForSlot(slot, 'Green Watch');
  // what we want to do:
  // create a new img element and span element
 // discard children of slot, and replace with this
 //}
}

function getASINFromItemNumber(n) {
 return displayedASINs[n];
}

function getSlotFromItemNumber(n) {
 return $('slot' + n);
}

function setTitleForSlot(slot,title) {
 var titleSpan = slot.getElementsByTagName('SPAN')[0];
 titleSpan.firstChild.nodeValue = title;
 // doesn't work :-(
}

// accepts parent, not parentId!

function getChildByClassname(parent, classname) {
 if (!parent) {
  // yes, this handles empty string
  return;
 }
 // use XPath => no IE4
}

function showDhtmlPopup(currentAsin) {
 if (errorDivId != null){
     popUpOldId = $(errorDivId);
     popUpOldId.style.display = 'none';  
 }
 var popup = $('dhtmlPopupMessage'+currentAsin);
 popup.style.display = 'block';
 errorDivId = 'dhtmlPopupMessage'+currentAsin;
}
function hideDhtmlPopup(id) {
 document.getElementById(id).style.display = 'none';
}
function showDhtmlPopupOne() {
 var popup = $('dhtmlPopupMessageOne');
 popup.style.display = 'block';
}

function removeColumnFromTable(target) {
 var cell = target.parentNode;
 var row = cell.parentNode;
 var table = row.parentNode.parentNode;
 var rows = table.getElementsByTagName('TR');
 for (i = 0; i < rows.length; i++) {
  var row = rows[i];
  var cells = row.getElementsByTagName('TD'); // never <th>, the heading column will never be deleted
  var cellToRemove = cells[columnNumber-1]; // NB: this array does not contain the <th>. off by one
  row.removeChild(cellToRemove);
  //cellToRemove.style.backgroundColor = 'red';
  // delete.
 }
}

//end addition for comare functionality

//This function is called on click of compare products button
function compare(){ 
  var addedAsinCount = addedAsinArray.length;
  if(addedAsinCount < 2){
    showDhtmlPopupOne();
  }else{
    var compareAsinListString = fnConvertToString(addedAsinArray);
    window.document.forms["comparison"].compareListASINs.value = compareAsinListString;
    window.document.forms["comparison"].submit();
  }
}

function fnConvertAsinStrToArray(){
  var oldASINs = window.document.forms["comparison"].compareListASINs.value;
  var addASINs = window.document.forms["comparison"].addedASINs.value;
  var removedASINs = window.document.forms["comparison"].removeASINs.value;
  var addedImagesStr = window.document.forms["comparison"].addedImages.value;
  var addedTitlesStr = window.document.forms["comparison"].addedTitles.value;

  if('' != oldASINs){
   compareAsinArray = oldASINs.split(","); 
   addedAsinArray = oldASINs.split(",");
   window.document.forms["comparison"].addedASINs.value= oldASINs;
  }else{
    if('' != addASINs){
      addedAsinArray = addASINs.split(",");
    }
    if('' != removedASINs){
      removedAsinArray = removedASINs.split(",");
    }
  }
  if('' != addedImagesStr) {
    addedImagesArray = addedImagesStr.split(",");
  }
  if('' != addedTitlesStr) {
    addedTitlesArray = addedTitlesStr.split(",");
  }
}

// This function is invoked on  click of check box to add items to compare bar

function fnCreateASINArray(obj,fromSpanStr){
  hideDhtmlPopup('dhtmlPopupMessageOne');
  if(fromSpanStr == 'link'){
    fnLinkClick(obj);
  }else {
    fnCheckImageClick(obj);
      if(addedAsinArray && sixthAsin && addedAsinArray.length < 5){
         hideDhtmlPopup('dhtmlPopupMessage' + sixthAsin);
      }
  }
}

function fnCheckImageClick(obj) {
  var currentAsin = obj.getAttribute("value");
  var asinIndex = fnContains(addedAsinArray,currentAsin);
  if(asinIndex == -1)
  { 
     fnLinkClick(obj);
  }else {
     var slotNo= getSlotNumberFromAsin(currentAsin);
     fnRemoveItems(slotNo,currentAsin);
  }
}
var sixthAsin;
function fnLinkClick(obj) {
  var currentAsin = obj.getAttribute("value");
  var asinIndex = fnContains(addedAsinArray,currentAsin);
  if(asinIndex == -1)
  { 
    var addedAsinCount = addedAsinArray.length;
    if(addedAsinCount < 5){
      var index = fnContains(removedAsinArray,currentAsin);
      if(index != -1){
         fnRemove(removedAsinArray,index);
      }
      addedAsinArray[addedAsinArray.length] = currentAsin;
      var addASINstring = fnConvertToString(addedAsinArray);
      window.document.forms["comparison"].addedASINs.value = addASINstring;
      updateAddedImagesArray(currentAsin);
      updateAddedTitlesArray(currentAsin);
      fnHighlightImage(obj,true);
      setExpandedState('compareBar');
      updateDisplay();
      changeText(currentAsin);
      changeClass('displayCompareWatch'+currentAsin,'srTitle','srTitleText');
    }else{
      sixthAsin = currentAsin;
      showDhtmlPopup(currentAsin);
    }
  }
}

function fnServerUpdateDisplay() {
  var addedItemArrayLength = addedAsinArray.length;
  for(addedItemCount =0; addedItemCount < addedItemArrayLength; addedItemCount++){
    var slotIdStr = 'slot' + addedItemCount;
    idSlot = document.getElementById(slotIdStr);
    var imageId = 'image' + addedItemCount;
    var image = $(imageId);
    image.src = addedImagesArray[addedItemCount];
    image.alt = addedTitlesArray[addedItemCount];
    image.title = addedTitlesArray[addedItemCount];
    setActiveState(slotIdStr);
    slotTitleStr = "title"+addedItemCount ;
    idSlotTitle = document.getElementById(slotTitleStr);
    idSlotTitle.style.visibility = "";
  }
}

function updateDisplay() {
  var imagePath ='';
  var title = '';
  var addedItemArrayLength = addedAsinArray.length;
  for(addedItemCount =0; addedItemCount < addedItemArrayLength; addedItemCount++){
   if(fnContainsDouble(imagesArray,addedAsinArray[addedItemCount]) != -1) {
     var index = fnContainsDouble(imagesArray,addedAsinArray[addedItemCount]);
     imagePath = imagesArray[index][1];
     title = imagesArray[index][2];
   }else {
     imagePath = addedImagesArray[addedItemCount];
     title = addedTitlesArray[addedItemCount];
   }
    var slotIdStr = 'slot' + addedItemCount;
    idSlot = document.getElementById(slotIdStr);
    var imageId = 'image' + addedItemCount;
    var image = $(imageId);
    image.src = imagePath;
    image.alt = title;
    image.title = title;
    setActiveState(slotIdStr);
    slotTitleStr = "title"+addedItemCount ;
    idSlotTitle = document.getElementById(slotTitleStr);
    idSlotTitle.style.visibility = "";
  }

  for(count = addedItemArrayLength; count < 5; count++) {
    var slotId = 'slot' + count;
    clearActiveState(slotId);
    var slotTitleStr = "title"+ count;
    idTitleSlot =  document.getElementById(slotTitleStr);   
    idTitleSlot.style.visibility = "hidden";
  }
}
function updateAddedImagesArray(asin) {
  var asinIndex = fnContainsDouble(imagesArray,asin);
  if(asinIndex != -1) {
    var imagePath = imagesArray[asinIndex][1];
    addedImagesArray[addedImagesArray.length] = imagePath;
    var addedImagesString = fnConvertToString(addedImagesArray); 
    window.document.forms["comparison"].addedImages.value = addedImagesString;
  } 
}
function updateAddedTitlesArray(asin) {
  var asinIndex = fnContainsDouble(imagesArray,asin);
  if(asinIndex != -1) {
    var title = imagesArray[asinIndex][2];
    addedTitlesArray[addedTitlesArray.length] = title;
    var addedTitleString = fnConvertToString(addedTitlesArray);
    window.document.forms["comparison"].addedTitles.value = addedTitleString;
  }
}
function removeItemFromComparison(obj) {
  var slotNo = obj.getAttribute('value');
  idTitle = document.getElementById('title'+slotNo);
  idTitle.style.visibility = "hidden";
  var removedAsin = getAsinFromSlotNumber(slotNo);
  fnRemoveItems(slotNo,removedAsin);
}

function fnRemoveItems(slotNo,removedAsin) {
  fnRemoveTitle(slotNo);
  fnRemoveImagePath(slotNo);
  fnRemoveAsinFromArray(slotNo);
  if( fnContainsDouble(imagesArray, removedAsin) != -1) {
    idProduct = document.getElementById(removedAsin);
    fnHighlightImage(idProduct,false);
    changeText(removedAsin,'false');
  }
  updateDisplay();
  var addedAsinCount = addedAsinArray.length;
  if(addedAsinCount == 0){
      setExpandedState('compareBar',false);
  } 
}
function getAsinFromSlotNumber(slotNumber) {
  return addedAsinArray[slotNumber];
}
function getSlotNumberFromAsin(removedAsin) {
 var index = fnContains(addedAsinArray,removedAsin);
 return index;
}
function fnRemoveAsinFromArray(slotNo) {
  var removedAsin = getAsinFromSlotNumber(slotNo);
  var addedAsinCount = addedAsinArray.length;
  var index = fnContains(addedAsinArray,removedAsin);
  if(index != -1){
     fnRemove(addedAsinArray,index);
     var addedAsinString =  fnConvertToString(addedAsinArray);
     window.document.forms["comparison"].addedASINs.value = addedAsinString;
  }
  var removedAsinIndex = fnContains(removedAsinArray);
  if(removedAsinIndex == -1) {
    removedAsinArray[removedAsinArray.length] = removedAsin;
    var removedASINstring = fnConvertToString(removedAsinArray);
    window.document.forms["comparison"].removeASINs.value = removedASINstring;
  }
}
function fnRemoveTitle(slotNo) {
  idTitle = document.getElementById('title'+slotNo);
  idTitle.style.visibility = "hidden";
  
  fnRemove(addedTitlesArray,slotNo);
  var titlesString = fnConvertToString(addedTitlesArray);
  window.document.forms["comparison"].addedTitles.value = titlesString;
}
function fnRemoveImagePath(slotNo) {
  imageId = document.getElementById('image'+slotNo);
  fnRemove(addedImagesArray,slotNo);
  var imagesPathString = fnConvertToString(addedImagesArray);
  window.document.forms["comparison"].addedImages.value = imagesPathString;  
}

//This function is called to restore the compare across pagination
function fnRestoreCompareBar(){
  if(addedAsinArray != null && addedAsinArray.length > 0){
     setExpandedState('compareBar');
     fnServerUpdateDisplay();
  }
}

function fnRestoreImages(){
  for(count =0; count < addedAsinArray.length; count++){
    obj = document.getElementById(addedAsinArray[count]);
    if(obj != null){
       fnHighlightImage(obj,true);      
    }
  }
}

function fnDynamicImageHighlight() {
  for(count=0; count < addedAsinArray.length; count++) {
    if(fnContainsDouble(imagesArray,addedAsinArray[count]) != -1) {
      obj = document.getElementById(addedAsinArray[count]);
      fnHighlightImage(obj,true);
      changeText(addedAsinArray[count]);
      changeClass('displayCompareWatch'+addedAsinArray[count],'srTitle','srTitleText');
    }
  }
}
function fnBuildCompareBar(asinString){
 obj = document.getElementById(asinString);
 if(fnContainsDouble(imagesArray,asinString) != -1) {
   fnHighlightImage(obj,true);
   changeText(asinString);
 }
}

//Start of utilities function

//iterates through a array to match a string and returns the index, if match not found returns -1
function fnContains(arrayObj,str){
 if(arrayObj== null || arrayObj.length == 0){
  return -1
 }else{
   for(countAr=0; countAr < arrayObj.length; countAr++){
      if(arrayObj[countAr] == str){
        return countAr;
      }
   }
   return -1;
 }
}

//iterates through a double dimension array to match a string for index=0, and returns the -1 if match not found
function fnContainsDouble(arrayObj, str) {
 if(arrayObj== null || arrayObj.length == 0){
  return -1
 }else{
   for(countAr=0; countAr < arrayObj.length; countAr++){
     if(arrayObj[countAr][0] == str){
        return countAr;
      }
   }
   return -1
 }
}

//the function removes a element from the array
function fnRemove(arrayObj,index){
 if(arrayObj== null || arrayObj.length == 0 || arrayObj.length < (index-1)){
  return -1
 }else{
    if(sixthAsin && sixthAsin != null && sixthAsin != ""){
       hideDhtmlPopup('dhtmlPopupMessage' + sixthAsin);
    }
  arrayObj.splice(index,1);
  return 1;
 }
}

//the function converts array to comma seperated string
function fnConvertToString(arrayObj){
 var stringObj = '';
 if(arrayObj== null || arrayObj.length == 0 ){
  return stringObj;
 }else{
   if(arrayObj.length == 1){
     stringObj = arrayObj[0];
   }else{
     for(count=0; count < arrayObj.length; count++){
        if(  count == 0){
           stringObj= arrayObj[0];
         }else{
            if(arrayObj[count] != ''){
              stringObj= stringObj +","+  arrayObj[count];
            }
        }
    }
   }
 }
 return stringObj;
}



function $(id) {
 // idiom taken from Prototype ajax library
 return document.getElementById(id);
}
//End of Utilities function








// This function is called on click of page number
// while going to next page
function constructASINList(output){
  var allAddedASINs;
  var allRemoveASINs;
  allAddedASINs = window.document.forms["comparison"].addedASINs.value;
  allRemoveASINs = window.document.forms["comparison"].removeASINs.value;
  addedImages = window.document.forms["comparison"].addedImages.value;
  addedTitles = window.document.forms["comparison"].addedTitles.value;
  path = output.href + '&addedASINs=' + allAddedASINs + '&removeASINs=' + allRemoveASINs + '&addedImages=' + addedImages + '&addedTitles=' + addedTitles;
  output.setAttribute("href",path);
}
function changeText(checkBoxName) {
 idImage= document.getElementById("image-"+checkBoxName);
 idText = document.getElementById("displayCompareWatch"+checkBoxName);
 if( idImage.src == checkImagePath) {
   idImage.src = uncheckImagePath;
   idText.innerHTML =  "<span class='srTitle'><a href='javascript:void(0)'>"+addToCompBarStr+"</a></span>";
 }else {
   idImage.src = checkImagePath;
   idText.innerHTML =  addedToComBarStr;
 }
}

////////////////////////////////////////
// END site-js
////////////////////////////////////////








///////////////////////////////////////////////////
// DOM utility functions
///////////////////////////////////////////////////
function $(id) {
// common idiom for DOM coding
// http://prototype.conio.net, MIT license
	return document.getElementById(id);
}
///////////////////////////////////////////////////
function findAncestorByTagName(element, findTagName) {
  // climb up the DOM tree until we find the nearest
  // ancestor with specified tagName
  // for example, given a TD we want to find its TABLE
  if (!element || !findTagName) return;
  if (element.tagName == 'HTML' || findTagName == 'HTML') {
    // don't need to climb for this
    return(document.getElementsByTagName('HTML'));
  }
  var ancestor = element.parentNode;
  while (ancestor.tagName != findTagName
           && ancestor.tagName != 'HTML') {
    ancestor = ancestor.parentNode;
  }
  return ancestor;
}
/////////////////////////////////////////////////////////////////
function getPositionInParent(child) {
  // counts parent's children, including self
  // and returns position in the list
  // only counting children with same tagName as self
  if (!child) return;
  var parent = child.parentNode;
  if (!parent) return;
  var elements = parent.getElementsByTagName(child.tagName);
  for (var i=0; i < elements.length; i++) {
    if (elements[i] == child) {
      return i;
    }
  }
}
/////////////////////////////////////////////////////////////////
function getCountInParent(child) {
  // counts parent's children, including self
  // only counting children with same tagName as self
  if (!child) return;
  var parent = child.parentNode;
  if (!parent) return;
  var elements = parent.getElementsByTagName(child.tagName);
  return elements.length;
}
/////////////////////////////////////////////////////////////////
function getChildrenByClassname(parent, classname) {
  if (!parent || !classname) return;
  var children = parent.childNodes;
  var matchingChildren = [];
  for (i = 0; i < children.length; i++) {
    var child = children[i];
    if (child.nodeType != 1) continue; // ignore text nodes
    childClassName = child.className;
    if(!childClassName) continue; // no classes == null attribute
    if (childClassName.contains(classname)) {
      matchingChildren.push(child);
    }
  }
  return matchingChildren;
}

//End of utilities functions

//////////////////////////////////////////////////////
// support functions for dynamic CSS
//////////////////////////////////////////////////////
function setActiveState(id, state) {
// productHighlightId = document.getElementById("product-"+id);
// var stateClass=productHighlightId.className;
 argLength = arguments.length;
 if (argLength == 0 || !id) {
  return;
 }
 // default for state is true
 if (state == true || argLength == 1) {
  //changeClass(productHighlightId.id, "inactive", "active");
  changeClass(id, "inactive", "active");
 } else {
  //changeClass(productHighlightId.id, "active", "inactive");
   changeClass(id, "active", "inactive");
 }
}
//////////////////////////////////////////////////////
function setExpandedState(id, state) { 
 argLength = arguments.length;
 if (argLength == 0 || !id) {
  return;
 }
 // default value for state is true
 state = (state == true || argLength == 1);
 if (state == true) {
  changeClass(id, "collapsed", "expanded");
 } else {
  changeClass(id, "expanded", "collapsed");
 }
 return state;
}
//////////////////////////////////////////////////////
function clearActiveState(id) {
 return setActiveState(id, false);
}
//////////////////////////////////////////////////////
function clearExpandedState(id) {
 return setExpandedState(id, false);
}
//////////////////////////////////////////////////////
function toggleActiveState(id) {
 var success = changeClass(id, "active", "inactive");
 if (!success) {
  changeClass(id, "inactive", "active");
 }
}
//////////////////////////////////////////////////////
function toggleExpandedState(id) {
 var success = changeClass(id, "collapsed", "expanded");
 if (!success) {
  changeClass(id, "expanded", "collapsed");
 }
}
///////////////////////////////////////////////////
String.prototype.contains = function(str) {
  return (this.indexOf(str) > -1);
}
///////////////////////////////////////////////////
// can't add these to prototype without breaking N2 :(
///////////////////////////////////////////////////
//Array.prototype.contains = function(value) {
function Array_contains(ary, value) {
  return (ary.indexOf(value) > -1);
}
///////////////////////////////////////////////////
//Array.prototype.indexOf = function(value) {
function Array_indexOf(ary, value) {
  if (!value) return -1;
	for (i = 0; i < ary.length; i++) {
		if (ary[i] == value) return i;
	}
  return -1;
}
///////////////////////////////////////////////////
//Array.prototype.removeEmpty = function() {
function Array_removeEmpty(ary) {
	// get rid of elements containing null, empty string, etc.
	for (var i = 0; i < ary.length; i++) {
		var val = ary[i];
		if (isEmptyNonZero(val)) {	// val is 'empty' but not zero
			ary.splice(i, 1);				  // note: alters loop length
		}
	}
}
///////////////////////////////////////////////////
function isEmptyNonZero(n) {
  // for when you want to treat 0 differently from null
	return (n !== 0 && !n);
}

////////////////////////////////////////////////
// cookie functions
////////////////////////////////////////////////
function getCookie(cookieName) {
	var cookies = document.cookie;
	var prefix = cookieName + '=';
	if (!cookies.contains(prefix)) return;  // cookie not set

	var pos = cookies.indexOf(prefix);
	var start = pos + prefix.length;
	var end = cookies.indexOf(";", start);
	if (end == -1) {
		end = cookies.length;
	}
	var value = cookies.substring(start, end);
	return unescape(value);
}
////////////////////////////////////////////////
function setCookie(cookieName, value, hours, path, domain, secure) {
	if (!cookieName) return;
	var cookieStr = cookieName + '=' + value;
	
	// all other parameters optional
	var hourInMilliseconds = 60 * 60 * 1000;
	var expiry = hours ? new Date((new Date()).getTime( ) + hourInMilliseconds * hours) : null;	
	
	if (expiry)	cookieStr += ';expires=' + expiry;
	if (path)		cookieStr += ';path=' + path;
	if (domain)	cookieStr += ';domain=' + domain;
	if (secure)	cookieStr += ';secure=' + secure;	
	document.cookie = cookieStr;
}
////////////////////////////////////////////////
function unsetCookie(cookieName) {
	if (!cookieName) return;
	setCookie(cookieName, '', -1) // expiration date in the past
}
////////////////////////////////////////////////

///////////////////////////////////////////////////
// Function for "Add another address" link on 
// OPL : Choose shipping address page
///////////////////////////////////////////////////
function addNewAddress()
{
   var fieldObj=document.getElementById("addAnotherAddr");
   fieldObj.name = 'addAnotherAddress';
   fieldObj.value= 'addAnotherAddress.x';
}

///////////////////////////////////////
//To prevent the print button from 
//appearing on the print out 
///////////////////////////////////////
function fnPrint(id1,id2){
   var obj1 = $(id1);
   var obj2 = $(id2);
   obj1.style.display = "none";
   obj2.style.display = "none";
   window.print();
   obj1.style.display = "";
   obj2.style.display = "";
}
////////////////////////////////////////


////////////////////////////////////////
//Following functions are used by the 
//newsletter popup functionality
////////////////////////////////////////
function fnGrayPageBackground(){
   var docHeight = window.document.body.scrollHeight;
   var qs1 = new Querystring();
   var signFlag1 = qs.get("signupFlag");
   docHeight = docHeight < 720 ? 740 : docHeight + 200; 
   var popupTop  = (docHeight - 720) + "px" ;
   
   // giving these some more logical names
   var grayPane = $("bkFrm");
   var grayPaneHolder = $("m2");
   var newsletterIFrame = $("Iframe");
   var newsletterIFrameHolder = $("frameI");
   
    try{
         grayPaneHolder.style.display = "";
         grayPaneHolder.style.height = docHeight;
         newsletterIFrameHolder.className='showNewsletter';
    }catch(e){}
    try{ 
         newsletterIFrameHolder.style.top  = "0px";
         newsletterIFrame.style.height = docHeight;
         grayPane.style.height = docHeight + 100;
    }catch(e){}
}

function Querystring(qs) { // optionally pass a querystring to parse
   this.params = new Object();
   this.get=Querystring_get;
    
   if (qs == null)
         qs=location.search.substring(1,location.search.length);
    
   if (qs.length == 0) return;
       qs = qs.replace(/\+/g, ' ');
       var args = qs.split('&'); // parse out name/value pairs separated via &

       for (var i=0;i<args.length;i++) {
            var value;
            var pair = args[i].split('=');
            var name = unescape(pair[0]);

            if (pair.length == 2)
                value = unescape(pair[1]);
            else
                value = name;

            this.params[name] = value;
      }
}

function Querystring_get(key, default_) {
   if (default_ == null) default_ = null;

   var value=this.params[key];
   if (value==null) value=default_;

   return value;
}

function fnHidePopup(popupname){
    $(popupname).className='hideNewsletter';
    $("frameI").className='hideNewsletter';
    cleanup();
}

function amz_js_PopWin(url,name,options){
//this function is no longer valid. All poups should call openPopupWindow function (dhir@)
//  var contextWindow = window.open(url,name,options);
//  contextWindow.focus();
  openPopupWindow(url,options,name);
  return false;
}


function fnShowPopup(popupname){
     var docHeight = window.document.body.scrollHeight;
     docHeight = docHeight < 720 ? 740 : docHeight;
     if(goFlag == "true" && popupname != "thankyou"){
          prepopulate();
          clearErrors();
     }
     $(popupname).className='showNewsletter';
     closeOther(popupname);
     
     // give these more meaningful names
     var newsletterIFrame = $("Iframe");
     var newsletterIFrameHolder = $("frameI");
     var grayPane = $("bkFrm");
     var grayPaneHolder = $("m2");     
     
     try{
         grayPaneHolder.style.display = "";
         if (navigator.appVersion.indexOf("MSIE")!=-1){
           grayPaneHolder.style.height = docHeight + 55;
         }
         else{
           grayPaneHolder.style.height = docHeight;
         }
         newsletterIFrameHolder.className='showNewsletter';
     }catch(e){}
     
     // disable these to keep IE from bringing them to the top
     var selectElements = document.getElementsByTagName("select");
     for(i=0;i<selectElements.length;i++){
       try{
           selectElements[i].disabled = true;
       }catch(e){}
     }
     var popupTop  = (docHeight - 720) + "px" ;
     $(popupname).style.top  = popupTop;
     try{
         newsletterIFrameHolder.style.top  = "0px";
         newsletterIFrame.style.height = docHeight;
         grayPane.style.height = docHeight + 100 + "px";
     }catch(e){}
     try{
      width = document.body.clientWidth ? document.body.clientWidth : window.innerWidth;
      popupLeft = (width - popupWidth)/2 + "px"; 
     }catch(e){
         //document object is still not ready to be used; using window instead.
     }
     $(popupname).style.left = popupLeft;
     $('zipCode').focus(); 
  }

    
    function prepopulate(){
      $('email').value = $('emailFooter').value == 'Enter e-mail address' ? ""
                                               : $('emailFooter').value;
    }

    function cleanup(){
       $('email').value = "";
       $('fname').value = "";
       $('lname').value = "";
       $('zipCode').value = "";
       goFlag = false;
       var currLocation = window.location.href;
       var index = currLocation.indexOf("signupFlag");
       if( index != -1 ){
           currLocation = currLocation.substr(0,index - 1);
           window.location = currLocation;
       }
       
       var grayPaneHolder = $("m2");
       var newsletterIFrameHolder = $("frameI");
       
       grayPaneHolder.style.display = "none";
       newsletterIFrameHolder.className='hideNewsletter';
       var selectElements = document.getElementsByTagName("select");
       for(i=0;i<selectElements.length;i++){
         try{
             selectElements[i].style.backgroundColor = "#FFFFFF";
             selectElements[i].disabled = false;
         }catch(e){}
       }
    }
    
    function fnValidateGiftOptions()
    {
      var fieldKeywords = document.giftFinderForm.field_keywords;
      var node = document.giftFinderForm.node;
      
      var priceBin = document.giftFinderForm.p_3;
       
      if(!(fieldKeywords.value || node.value || priceBin.value)) {
        alert("Please select an occasion, recipient and/or price range in the Timex Gift Finder.");
        return false;
      }else if(!(fieldKeywords.value || node.value)) {
        alert("Please select an occasion and recipient in the Timex Gift Finder.");
        return false;
      }else if(!fieldKeywords.value) {
        alert("Please select an occasion in the Timex Gift Finder.");
        return false;
      }else if(!node.value) {
        alert("Please select a recipient in the Timex Gift Finder.");
        return false;
      }
    // Changing field_keywords name as we need to pass argument as field-keywords to search but 
    // select does not return any value if tag name has -
      document.getElementById("field_keywords").name = 'field-keywords';
      return true;
    }
      
    function fnGiftFinder() {
       if (fnValidateGiftOptions() == true) {
         document.giftFinderForm.submit();
       } else {
         return;
       }
    }

    //This function changes the name of the hidden field from /gp/ordering/checkout/item/select.m and
    //submits the form.
    //-----------------------------------------------------------------------------------------------
    function enterNewAddress()
    {
      document.getElementById("newAddress").name = 'addAddress';
      document.multipleShipping.submit();
    }    

    function fnSignUp(){
        $('newsletter').className='hideNewsletter';
        document.signUpFrm.signupFlag.value = "T";
    }

    function closeOther(popupname){
      try{
         switch (popupname){
            case "newsletter" : {$("thankyou").className='hideNewsletter';break;}
            case "thankyou"   : {$("newsletter").className='hideNewsletter';break;}
         }
      }catch(e){}
    }

var errorString = "Please fix the errors marked in red below. When you are done, please click the \"Sign Me Up\" button to resend your information." + "<br />";
    function fnSetErrors(obj_array){
      var numErrors = obj_array.length -1 ;
      for (i=0;i<numErrors;i++){
        switch(obj_array[i]){
          case "zipCode" : {
            $("zipCodeFieldbox").className = "fieldBox errorField";
            $("zipError").className = "showErrorMessage";
            break;
          }
          case "firstName" : {
            $("fnameFieldbox").className = "fieldBox errorField";
            $("firstNameError").className = "showErrorMessage";
            break;
          }
          case "lastName" : {
            $("lnameFieldbox").className = "fieldBox errorField";
            $("lastNameError").className = "showErrorMessage";
            break;
          }
          case "email" : {
            $("emailFieldbox").className = "fieldBox errorField";
            $("emailError").className = "showErrorMessage";
            break;
          }
        }
      }
      if(obj_array.length > 0){
          $("errors").style.display='';
          $("errors").innerHTML = errorString;
      }
    }

    function clearErrors(){
      $("zipCode").className = "";
      $("zipLabel").className = "";
      $("fnameFieldbox").className = "fieldBox";
      $("lnameFieldbox").className = "fieldBox";
      $("emailFieldbox").className = "fieldBox";
      
      $("errors").style.display='none';
    }

    var popupHeight = 500;
    var popupWidth  = 580;
    var popupLeft = (window.screen.availWidth - popupWidth)/2 + "px";


    function updateRemChars(objComment,limit){
        if(objComment.value.length > limit){
           objComment.value = objComment.value.substring(0,limit);
        }
        var remChars = limit - objComment.value.length;
        $("charLimit").innerHTML = remChars;
    }

    function fnChangeImg(obj,state,mode){
        //state = mouse state
        //state = over - out - down
        //mode = zoom in - zoom out - reset
        //mode = in - out - reset
        var dis = obj.src.indexOf('disabled');
        if (dis != -1) return; 
        if(state == 'over'){
           if(mode == 'in'){
             obj.src = zoomInMouseOver; 
           }
           else if(mode == 'out'){
             obj.src = zoomOutMouseOver; 
           }else if(mode == 'reset'){
             obj.src = zoomResetMouseOver;
           }  
        }else if(state == 'out'){
           if(mode == 'in'){
             obj.src = zoomInMouseOut;
           }
           else if(mode == 'out'){
             obj.src = zoomOutMouseOut;
           }else if(mode == 'reset'){
             obj.src = zoomResetMouseOut;
           }
        }else if(state == 'down'){
           if(mode == 'in'){
             obj.src = zoomInMouseDown;
           }
           else if(mode == 'out'){
             obj.src = zoomOutMouseDown;
           }else if(mode == 'reset'){
             obj.src = zoomResetMouseDown;
           }
        } 
    }

    function convertBreaks(obj){
         var temp;
         while(obj.indexOf("\n") != -1){
             temp = obj.indexOf("\n");
             obj = obj.substring(0,temp-1) + "#%#" + obj.substring(temp+1,obj.length);
         }
         obj = convertSpaces(obj);
         $('pMessage').value = obj;
    }

    function convertSpaces(obj){
         var temp;
         while(obj.indexOf(" ") != -1){
             temp = obj.indexOf(" ");
             obj = obj.substring(0,temp) + "-#-" + obj.substring(temp+1,obj.length);
         }
         return obj;
    }    
    
    function reCreateMessage(obj,chars,sub){
         var temp;
         var len = chars.length;
         while(obj.indexOf(chars) != -1){
             temp = obj.indexOf(chars);
             obj = obj.substring(0,temp) + sub + obj.substring(temp+len,obj.length);
         }
         $('mess').value = obj;
    }

    function adjustPopUpPosition(){
      var width = document.body.clientWidth ? document.body.clientWidth : window.innerWidth
      var popupWidth  = 580;
      var popupLeft = (width - popupWidth)/2 + "px";
      if($("newsletter").className == "showNewsletter"){
          $("newsletter").style.left = popupLeft;
      }else if($("thankyou").className == "showNewsletter"){
          $("thankyou").style.left = popupLeft;
      }
   }


var preloadedImages = [];
//////////////////////////////////////////////////
function getImageObject(url) {
  var img = new Image(0,0);
  img.src = url;
  return img;
}
function preloadImages(urlArray) {
  if (!urlArray) return;
  for (var i = 0; i < urlArray.length; i++) {
    var url = urlArray[i];
    preloadedImages.push(getImageObject(url));
  }
}
// separate version since this is a 2D array
function preloadThumbnailImages(urlArray) {
  if (!urlArray) return;
  for (var i = 0; i < urlArray.length; i++) {
    var url = urlArray[i][1];
    preloadedImages.push(getImageObject(url));
  }
}
//////////////////////////////////////////////////
// populated in site-js.mi
if (imagePreloadUrls) {
  preloadImages(imagePreloadUrls);
}



// from start.mi
function fnFocus()
{
    if(document.signin.email.value == '' )
    {
      document.signin.email.focus();
    }
    else
    {
     document.signin.password.focus();
    }
}

// from new-account-form
function getUserName()
{
  if($('firstName').value == '' || $('lastName').value == '' ){
    return;
  }
  $('signInUserName').value = $('firstName').value + ' ' + $('lastName').value;
}




