// Reg Expression for Email Validation
var emailAddressRegex = /^\w+([\.-\\+]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

/*******
#-------------------------------------------------------------------------
Function boxOnClick is used for search box press event. this function will 
clear the text.
#-------------------------------------------------------------------------
*******/

function boxOnClick( box, msg) {
        if(box.value == msg){
             box.value='';
             box.style.color = "#000000";
        }
}
/*******
#-------------------------------------------------------------------------
Function boxOnBlur is used for search box blur event. this
function will add the original text if the search box is empty.
#-------------------------------------------------------------------------
*******/

function boxOnBlur( box, msg) {
        if(box.value == '') {
             box.value = msg;
             box.style.color = "#666666"; 
        }
}


/*******
#-------------------------------------------------------------------------
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, altText) {
        if(document.images[element] && newImg) {
           document.images[element].src = newImg;
           document.images[element].alt = altText;
        }
}

/*******
#-----------------------------------------------------------------------
Function displayItems is used to display all the items under 'Add a
Little Extra' when 'See More Extras' link is clicked.
#-----------------------------------------------------------------------
*******/
function displayItems() {
  document.getElementById("moreExtras").style.display = "none";
  document.getElementById("lessItems").style.display = "block";
}

/*******
#-------------------------------------------------------------------------
Function openPopupWindow is used for pop up window.
#-------------------------------------------------------------------------
*******/
function openPopupWindow(url,popup_options) {
  
  var heightParam = popup_options.match(/height\s*=\s*\d+\s*/ig);
  
  if (heightParam !== null)
  {  
      var currentHeight = eval(heightParam[0].split('=')[1]);
      screenHeight = eval(document.body.offsetHeight + 55);
      newHeight = screenHeight < currentHeight ? screenHeight: currentHeight;
      popup_options = popup_options.replace(heightParam[0],"height= "+newHeight);
  }
  win = window.open(url,'popup',popup_options);
  if (win) {
    win.focus();
  }
}

/*******
#-------------------------------------------------------------------------
Function to submit wishlist form
#-------------------------------------------------------------------------
*******/
function wishlistSubmit() {
     document.getElementById('wishlistButton').innerHTML ='<input type="hidden" name="submit.add-to-registry.wishlist" id="submit.add-to-registry.wishlist" value="1"/>';
    document.handleBuy.submit();
    return false;
}

/*******
#-------------------------------------------------------------------------
Function switchOrder() changes the order display to the newer or older
order.
Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/

function switchOrder(page) {

  clearOrderDisplay();
  var currentOrder = document.getElementById('currentOrder').value;

  // for the previous / next order respectively
  if(page == "newer") {
    if (currentOrder == 0) {
      document.getElementById('order.0.'+currentOrder).style.display = "inline";
      return;  
    }
    currentOrder--;
  }
  else if(page == "older") {
    currentOrder++;
    if(document.getElementById('orderCount').value == currentOrder) {
      currentOrder--;
      document.getElementById('order.0.'+currentOrder).style.display = "inline";
      return; 
    }
  }

  // set the order display
  if(document.getElementById('order.0.'+currentOrder) != null) {
      document.getElementById('order.0.'+currentOrder).style.display = "inline";
  }

  // update the order index
  document.getElementById('currentOrder').value = currentOrder;

  // Finally update the paging links to reflect
  // the current order's position
  changePagingLink(page);
}

/*******
#-------------------------------------------------------------------------
Function changePagingLink() enables or disables the 'newer' & 'older'
hyperlinks so that the user cannot go to the zeroeth or the (n+1)th pg.
Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/

function changePagingLink(page) {

  var currentOrder = document.getElementById('currentOrder').value;
  var orderCount = document.getElementById('orderCount').value;

  // We want to hide all paging links if there's only one order.
  if(orderCount < 2 && page == "load") {
    document.getElementById('orderPager').style.visibility = 'hidden';
    var lineBreaker = document.getElementById('lineBreaker');
    if ( lineBreaker ) {
      lineBreaker.innerHTML = '';
    }
    return;
  }

  // enable or disable the 'newer' link
  if(currentOrder == 0) {
    document.getElementById('newerLink').disabled = true;
    document.getElementById('newerLink').style.textDecoration = 'none';
  }
  else {
    document.getElementById('newerLink').disabled = false;
    document.getElementById('newerLink').style.textDecoration = 'underline';
  }

  // enable or disable the 'older' link
  if(currentOrder == (orderCount - 1)) {
    document.getElementById('olderLink').disabled = true;
    document.getElementById('olderLink').style.textDecoration = 'none';
  }
  else {
    document.getElementById('olderLink').disabled = false;
    document.getElementById('olderLink').style.textDecoration = 'underline';
  }
}

/*******
#-------------------------------------------------------------------------
Function searchOrderItem() is to update the order display to show items/orders
starting with the typed-in text.

Also, 'Browse Recent Orders' should be invisible on load of the page.
It should appear from the time a search (order/item) returns empty.

Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/

function searchOrderItem() {
  
  if(document.getElementById('orderSearch').value.replace(/^\s+/g, '').replace(/\s+$/g, '') == '') {

    clearOrderDisplay();

    document.getElementById('orderPager').style.display = "none";
 // TODO: Remove hardcoding.
    document.getElementById("orderError").innerHTML ="Please enter an item title, item number, or order number you wish to find.";
    document.getElementById("orderError").className = "show error";
  } else {

    clearOrderDisplay();

    document.getElementById("orderError").className = "hide";
    var hasSearchResults = searchOrder();

    // Couldn't find any orders.. So now let's search on item titles.
    if(hasSearchResults == 0) {
      hasSearchResults = searchItem();
    }

    document.getElementById('orderPager').style.display = "none";
  }
}

/*******
#-------------------------------------------------------------------------
Function searchOrder() is to update the order display to show orders
starting with the typed-in text.
Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/

function searchOrder() {

  var hasSearchResults = 0;
  var orderSearch = document.getElementById('orderSearch').value.replace(/^\s+/g, '').replace(/\s+$/g, '');
  var orderSearchLength = orderSearch.length;

  var orderCount = document.getElementById('orderCount').value;
  for(i=0; i<orderCount; i++) {
    var thisOrder = document.getElementById('orderId.'+i).value;
    if(thisOrder.length >= orderSearchLength && thisOrder.substr(0,orderSearchLength) == orderSearch) {
      document.getElementById('order.0.'+i).style.display = "inline";
      hasSearchResults = 1;
    } 
  }
  return hasSearchResults;
}

/*******
#-------------------------------------------------------------------------
Function searchItem() is to update the order display to show items
having titles starting with the typed-in text.
Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/

function searchItem() {

  var hasSearchResults = 0;
  var itemCount = document.getElementById('itemCount').value;
  var showText = document.getElementById('orderSearch').value.replace(/^\s+/g, '').replace(/\s+$/g, '');
  var textSearch = showText.toLowerCase();
  var textSearchLength = textSearch.length;

  for(i=0; i<itemCount; i++) {
    var thisItem = document.getElementById('itemTitle.'+i).value;
    if(thisItem.length >= textSearchLength && thisItem.search(textSearch) != -1) {
      document.getElementById('itemDisplay.'+i).style.display = "block";
      hasSearchResults = 1;
    }
  }

    if (hasSearchResults == 0){
// TODO: Remove hardcoding.
    document.getElementById("orderError").innerHTML ="We found no results that closely match your search for '"+showText+"'. Please try searching again.";
    document.getElementById("orderError").className = "show error";
    }

  return hasSearchResults;
}

/*******
#-------------------------------------------------------------------------
Function browseRecentOrders() will show the most recent orders.
Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/

function browseRecentOrders() {

  clearOrderDisplay();

  document.getElementById('orderPager').style.display = "block";
  document.getElementById('order.0.0').style.display = "inline";

  // update the order index
  document.getElementById('currentOrder').value = 0;

  // make the paging links proper
  changePagingLink('load');
}

/*******
#-------------------------------------------------------------------------
Function addToPreview() will add an item from the search box on left to
the preview box.
Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/


function addToPreview(order, ship, item) {
  document.getElementById('order.1.'+order).style.display = "block";
  document.getElementById('shipment.1.'+ship).style.display = "block";
  document.getElementById('item.1.'+item).style.display = "block";

  document.getElementById('addmain.'+item).style.display = "none";
  document.getElementById('addtitle.'+item).style.display = "none";

  document.getElementById('clearButton').style.display = "inline";
}

/*******
#-------------------------------------------------------------------------
Function removeFromPreview() will remove an item that had been added by the user
to the preview box. This will cause the ADD button to re-appear on
the search box on the left (we had made it disappear when the item
was initially added to the preview box).

The functionality ::: First hide the item. Next, hide the shipment.
For this, loop through the shipment's items. For each item, check the
style of display. If this is "block", exit function. If you couldn't
find any, hide the shipment and then proceed to step 3 - 'hide the order'.

To hide the order, lop through the order's shipments. For each shipment,
check the style of display. If this is "block", exit function. If at the
end of the loop, you couldn't find any, then hide the order.

Added for the Order Search page of Contact Us.
#-------------------------------------------------------------------------
*******/


function removeFromPreview(order, ship, item) {

  document.getElementById('item.1.'+item).style.display = "none";

  document.getElementById('addmain.'+item).style.display = "inline";
  document.getElementById('addtitle.'+item).style.display = "inline";

  for(i=0; i<shipArray[ship].length; i++) {
    if(document.getElementById('item.1.'+shipArray[ship][i]).style.display == "block") {
      return;
    }
  }
  document.getElementById('shipment.1.'+ship).style.display = "none";

  for(j=0; j<orderArray[order].length; j++) {
    if(document.getElementById('shipment.1.'+orderArray[order][j]).style.display == "block") {
      return;
    }
  }

  document.getElementById('order.1.'+order).style.display = "none";

  var orderCount = document.getElementById('orderCount').value;
  for(i=0; i<orderCount; i++) {
    if(document.getElementById('order.1.'+i).style.display == "block") {
      return;
    }
  }

  document.getElementById('clearButton').style.display = "none";
}

/*******
#-----------------------------------------------------------------------
Function clearPreview clears all the items that had been added to the
preview. This is called on click of the 'Clear' button on the preview box.

Loop through orders. If any order is on display, hide it and loop through
its shipments. If any shipment is on display, hide it and loop through
its items. Hide all the items unconditionally.

Added for the Order Search page of Contact Us.
#-----------------------------------------------------------------------
*******/
function clearPreview() {
  var orderCount = document.getElementById('orderCount').value;
  for(i=0; i<orderCount; i++) {
    if(document.getElementById('order.1.'+i).style.display == "block") {
      document.getElementById('order.1.'+i).style.display = "none";
      for(j=0; j<orderArray[i].length; j++) {

        if(document.getElementById('shipment.1.'+orderArray[i][j]).style.display == "block") {
          var shipIndex = orderArray[i][j];
          document.getElementById('shipment.1.'+shipIndex).style.display = "none";
          for(k=0; k<shipArray[shipIndex].length; k++) {
            document.getElementById('item.1.'+shipArray[shipIndex][k]).style.display = "none";
            document.getElementById('addmain.'+shipArray[shipIndex][k]).style.display = "inline";
            document.getElementById('addtitle.'+shipArray[shipIndex][k]).style.display = "inline";
          }
        }
      }
    }
  }

  document.getElementById('clearButton').style.display = "none";
}

/*******
#-----------------------------------------------------------------------
Function clearOrderDisplay clears the display under the paging links

This will be called only by the above js functions. This is required
1. on search by item/order
2. on click of paging links 
3. on click of 'browse recent orders'
 
Added for the Order Search page of Contact Us.
#-----------------------------------------------------------------------
*******/
function clearOrderDisplay() {
  var orderCount = document.getElementById('orderCount').value;
  for(i=0; i<orderCount; i++) {
    document.getElementById('order.0.'+i).style.display = "none";
  }
  
  var itemCount = document.getElementById('itemCount').value;
  for(i=0; i<itemCount; i++) {
    document.getElementById('itemDisplay.'+i).style.display = "none"; 

  }
}

/*******
#-----------------------------------------------------------------------
Function loadOrderDisplay takes care of first-load appearance
of the page. Shows the newest order.

Added for the Order Search page of Contact Us.
#-----------------------------------------------------------------------
*******/
function loadOrderDisplay() {

  if(document.getElementById('order.0.0') != null) {
      document.getElementById('order.0.0').style.display = "inline";
  }
  changePagingLink('load');

  var display = '';
  var itemCount = document.getElementById('itemCount').value;
  for(i=0; i<itemCount; i++) {
    display += "<div id='itemDisplay."+i+"' class='hide'>";

    display += "<span id='addtitle."+i+"' >";
    display += document.getElementById('hideAddtitle.'+i).innerHTML;
    display += "</span>";

    display += document.getElementById('hideItemDisplay.'+i).innerHTML;
    display += "</div>";
  }

  document.getElementById('itemSearchDisplay').innerHTML = display;
}

/*******
#-----------------------------------------------------------------------
Function submitContactOrders enters the selected items into a hidden
field to be used to know which were the orders/shipments/items that
the user had added to the preview box.

Loop through items. If the item is on display, enter the item index
into a hidden field. Keep adding to the hidden field with item indices
separated by '-'.

This is called on click of the Continue button on the Order Search page
of Contact Us.
#-----------------------------------------------------------------------
*******/
function submitContactOrders() {
  var orders = '-';
  var shipments = '-';
  var items = '-';

  var orderCount = document.getElementById('orderCount').value;
  for(i=0; i<orderCount; i++) {
    if(document.getElementById('order.1.'+i).style.display == "block") {
      orders = orders + i + '-';

      for(j=0; j<orderArray[i].length; j++) {
        if(document.getElementById('shipment.1.'+orderArray[i][j]).style.display == "block") {
          shipments = shipments + orderArray[i][j] + '-';

          var shipIndex = orderArray[i][j];
          for(k=0; k<shipArray[shipIndex].length; k++) {
            if(document.getElementById('item.1.'+shipArray[shipIndex][k]).style.display == "block") {
              items = items + shipArray[shipIndex][k] + '-';
            }
          }
        }
      }
    }
  }

  document.getElementById('selectedOrders').value = orders;
  document.getElementById('selectedShipments').value = shipments;
  document.getElementById('selectedItems').value = items;
}

/*******
#-----------------------------------------------------------------------
Function switchDisplay takes care to display the Wishlist Creation form on 
click of the link to create a New Wishlist. Its actually a generic function
that switches between two Elements being displayed on the page.

Added for the Owner List Chooser page of Wishlist.
#-----------------------------------------------------------------------
*******/
function switchDisplay(switchToDisplay, originalDisplay) {
  document.getElementById(switchToDisplay).style.display = "block";
  document.getElementById(originalDisplay).style.display = "none";
}

/*******
#-----------------------------------------------------------------------
Function submitForm is used to submit a form on click of a text
#-----------------------------------------------------------------------
*******/

function submitForm (form){
    form.submit();
}

/*******
#------------------------------------------------------------------------
Function for displaying customizable message text box.
#------------------------------------------------------------------------
*******/
function displayMessage() {
  document.getElementById('customizeMessage').style.visibility="visible";
  document.getElementById('customizeMessage').style.display="inline";
}

/*******
#------------------------------------------------------------------------
Function to hide customizable message text box.
#------------------------------------------------------------------------
*******/
function hideMessage() {
  document.getElementById('customizeMessage').style.visibility="hidden";
  document.getElementById('customizeMessage').style.display="none";
}

/*******
#------------------------------------------------------------------------
Function to switch between the forms on store locator page on change of location.
#------------------------------------------------------------------------
*******/
function changeLocation(locationType) {
  if (locationType=='UK&Ireland') {
    document.getElementById('findStore').style.display='block';
    document.getElementById('findCountry').style.display='none';
  }
  else if (locationType=='Worldwide') {
    document.getElementById('findStore').style.display='none';
    document.getElementById('findCountry').style.display='block';
  }
}

/*******
#------------------------------------------------------------------------
Function will swap with the main image corresponding to the color-swatch clicked.
#------------------------------------------------------------------------
*******/
function updateImage(imageName, imagePath, colorName, ASIN) {
   document.images[imageName].src = imagePath;
   var updated = 0;
   for (i = 0; i< arrSelectedColors.length; i++)
   {
       var obj = arrSelectedColors[i];
       if (obj.ASIN == ASIN)
       {
          obj.color = colorName;
          updated = 1;
          break;
       }
   }
   if (updated == 0)
   {
       arrSelectedColors[arrSelectedColors.length] = new setSelectedColors(ASIN, colorName);
   }
}

/*******
#------------------------------------------------------------------------
Function to store the Array of ASIN, color and ImageId of the color-swatch clicked.
#------------------------------------------------------------------------
*******/
var arrSelectedColors = new Array();
function setSelectedColors(ASIN, color, imageId)
{
  this.ASIN = ASIN;
  this.color = color;
  this.imageId = imageId;
}

/*******
#------------------------------------------------------------------------
Function will update the Color Name on mouseover.  
#------------------------------------------------------------------------
*******/
function updateColorText(colorName, currentImageId, viewID, ASIN) {
   var swatchColorName = document.getElementById("selectedColor_" + ASIN).innerHTML;
   if (swatchColorName != colorName){
            if (viewID == 'quickview')
            {
               document.getElementById("selectedColor_" + ASIN).innerHTML = '<span class="small">'+colorName+'</span>';
            }
            else
            {
               document.getElementById("selectedColor_" + ASIN).innerHTML = '<span class="swatchText">'+colorName+'</span>';
            }
   }
   // Highlighting the image
   document.getElementById(currentImageId).className = 'pImg';
}

/*******
#----------------------------------------------------------------------------
Function resets the color Name Text for the Swatch Color Palette on mouseout.
#----------------------------------------------------------------------------
*******/
function resetColorText(currentImageId, viewID, ASIN){
    var swatchClickedColor = "";
    for (i = 0; i< arrSelectedColors.length; i++)
    {
       if (arrSelectedColors[i].ASIN == ASIN)
       {
          swatchClickedColor = arrSelectedColors[i].color;
          break;
       }
    }
   
    if (viewID == 'quickview')
    {
       document.getElementById("selectedColor_" + ASIN).innerHTML = '<span class="small">'+swatchClickedColor+'</span>';
    }
    else
    {
       document.getElementById("selectedColor_" + ASIN).innerHTML = '<span class="swatchText">'+swatchClickedColor+'</span>';
    }
    
    var  selectedImageId = "";   
    for (i = 0; i< arrSelectedColors.length; i++)
    {
       if (arrSelectedColors[i].ASIN == ASIN)
       {
          selectedImageId = arrSelectedColors[i].imageId;
          break;
       }
    }

    if (currentImageId == selectedImageId)
    {
        // Make the image selected
    	document.getElementById(currentImageId).className = 'sImg';
    }
    else
    {
        // Removing the highlighting from the image
        document.getElementById(currentImageId).className = 'nImg';
    }
}

/*******
#----------------------------------------------------------------------------  
Function sets the style class name for the swatch Images
#----------------------------------------------------------------------------  
*******/
function setImageBorder(selectedImage , imageCount, ASIN) {
    var updated = 0;
    for (i = 0; i< arrSelectedColors.length; i++)
    {
       if (arrSelectedColors[i].ASIN == ASIN)
       {
          arrSelectedColors[i].imageId = selectedImage;
          updated = 1;
          break;
       }
    }

    if (updated == 0)
    {
      arrSelectedColors[arrSelectedColors.length] = new setSelectedColors(ASIN, "", selectedImage);
    }

    if (!ASIN) {
        ASIN = '';
    }
    for (var i=1; i <= imageCount; i++ ) {
        if (document.getElementById("swatch_image_"+ASIN+i)) {
            document.getElementById("swatch_image_"+ASIN+i).className = 'nImg';
        }
    }
    document.getElementById(selectedImage).className = 'sImg';
}

/*******
#------------------------------------------------------------------------
Function will swap style options for UK and non-UK
---------------------------------------------------------------------
*******/

function displayAddEditAddressCountry() {
  document.getElementById("ukcountry").style.display = "none";
  document.getElementById("nonukcountry").style.display = "inline";
  document.getElementById("ukzip").style.display = "none";
  document.getElementById("nonukzip").style.display = "inline";
  document.getElementById("ukstate").style.display = "none";
  document.getElementById("nonukstate").style.display = "inline";
  document.getElementById("ukoneclick").style.display = "none";
  document.getElementById("ukoneclick2").style.display = "none";
  document.forms['addeditaddress'].countryName.options[0] = new Option('-select Country-', '-select Country-');
  document.forms['addeditaddress'].countryName.options[0].selected = "selected";
}

/*******
#------------------------------------------------------------------------
Function will change the style if the country is UK
---------------------------------------------------------------------
*******/


function changeAddEditAddressCountry(what) {
    var selected = what.options[what.selectedIndex].text;
    if (selected == "United Kingdom")
    {
        document.getElementById("ukcountry").style.display = "inline";
        document.getElementById("nonukcountry").style.display = "none";
        document.getElementById("ukzip").style.display = "inline";
        document.getElementById("nonukzip").style.display = "none";
        document.getElementById("ukstate").style.display = "inline";
        document.getElementById("nonukstate").style.display = "none";
        document.getElementById("ukoneclick").style.display = "inline";
        document.getElementById("ukoneclick2").style.display = "inline";
        document.forms['addeditaddress'].countryName.options[0] = new Option('United Kingdom', 'United Kingdom');
        document.forms['addeditaddress'].countryName.options[0].selected = "selected";
    }
}

/*******
#----------------------------------------------------------------------------------
Function to make the customizable textboxes read only after saving the information.
#----------------------------------------------------------------------------------
*******/
function readOnlyText() {
   var argv = readOnlyText.arguments;
   var argc = argv.length;
   for (var i = 0; i < argc; i++) {
     document.getElementById(argv[i]).readOnly = true;
   }
   document.getElementById("saveText").className = "hide";
   document.getElementById("editText").className = "block";
}
 
/*******
#----------------------------------------------------------------------------------
Function to make the customizable textboxes editable.
#----------------------------------------------------------------------------------
*******/
 function editableText() {
   var argv = editableText.arguments;
   var argc = argv.length;
   for (var i = 0; i < argc; i++) {
     document.getElementById(argv[i]).readOnly = false;
   }
   document.getElementById("saveText").className = "block";
   document.getElementById("editText").className = "hide";
 }
  
/*******
#----------------------------------------------------------------
 Function to display the clicked tab content on collection page.
#----------------------------------------------------------------
*******/
 function display(id, colourId, tableId, tabId) {
    // These are for hiding and showing tabs
    document.getElementById('ListFabrics').className = "";
    document.getElementById('ListOffers').className = "";
    document.getElementById('ListFabricDetails').className = "";
    document.getElementById('ListCollection').className = "";
    document.getElementById(tabId).className = "sel";
    
    // These are for hiding and showing tab contents
    document.getElementById('colours').className = 'hide';
    document.getElementById('fabrics').className = 'hide';
    document.getElementById('fabricDetails').className = 'hide';
    document.getElementById('offers').className = 'hide';
    document.getElementById('siblings').className = 'hide';
    document.getElementById(id).className='show noTopBorder';
    if (colourId) {
      document.getElementById(colourId).className = 'show';
      document.getElementById('tab').value = colourId;
    }
 }
  
/*******
#----------------------------------------------------------------------------------------------------
 Function to update the color combo box corresponding to the swatch image clicked in collection tabs.
#----------------------------------------------------------------------------------------------------
*******/
 function updateColorMaterial(color, material, dimension1, dimension2) {
    if (dimension1 == 'color_name') {
      dimension1Name = color.replace(/^\s*|\s*$/g,"");
      dimension2Name = material.replace(/^\s*|\s*$/g,"");
    } else {
      dimension1Name = material.replace(/^\s*|\s*$/g,"");
      dimension2Name = color.replace(/^\s*|\s*$/g,"");
    }
    dimension1DropDownOptions = document.handleBuy[dimension1];
    dimension2DropDownOptions = document.handleBuy[dimension2];
    var allDimension1 = dimension1DropDownOptions.options;
    var allDimension2 = dimension2DropDownOptions.options;
    for(var i=0;i<allDimension1.length;i++) {
      if(allDimension1[i].text == dimension1Name) {
        allDimension1[i].selected = true;
      }
    }
    populateDropDown(dimension2DropDownOptions, dimension1Name);
    for(var i=0;i<allDimension2.length;i++) {
      if(allDimension2[i].value == dimension2Name) {
        allDimension2[i].selected = true;
      }
   }
   populateDropDown(dimension2Name);
   dpShowVariationPrice();
 }

/*******
#----------------------------------------------------------------------------  
Function clears the warnings on the newsletter homepage
#----------------------------------------------------------------------------  
*******/
function fnClearWarnings(){
    document.getElementById("emailBlock1").className="hide";
    document.getElementById("emailBlock2").className="hide";
}

/*******
#----------------------------------------------------------------------------  
Function validates the mail id
#----------------------------------------------------------------------------  
*******/
function checkEmail(btnNumber){
    fnClearWarnings();

    if (btnNumber==1){
        if (emailAddressRegex.test(document.Newsletter1.emailAddr1.value) )
        {
            document.Newsletter1.submit();
        }else{
            document.getElementById("emailBlock1").className="show";
        }
    }if (btnNumber==2){
        if (emailAddressRegex.test(document.Newsletter2.emailAddr2.value) )
        {
            document.Newsletter2.submit();
        }else{
            document.getElementById("emailBlock2").className="show";
        }
    }
}

/*******
#----------------------------------------------------------------------------  
Function checks and unchecks the checkboxes in the newsletter-preferences page 
#----------------------------------------------------------------------------  
*******/
function checkAll(count){
    for(i=1;i<=9;i++){
        if(count == 1){
        document.getElementById("check"+i).checked=true;
        }else{
        document.getElementById("check"+i).checked=false;
        }
    }
}

/*******
#----------------------------------------------------------------------------  
Function clears the warnings on the newsletter-preference page
#----------------------------------------------------------------------------  
*******/
function fnClearWarnings1(){
    document.getElementById("emailBlock").className="hide";
    document.getElementById("firstNameBlock").className="hide";
    document.getElementById("surnameBlock").className="hide";
    document.getElementById("genderBlock").className="hide";
}

/*******
#----------------------------------------------------------------------------  
Function validates the fields in the newsletter preference page 
#----------------------------------------------------------------------------  
*******/
function checkFields(myForm) {
    fnClearWarnings1();
    if (emailAddressRegex.test(myForm.editEmail.value)){
        if (document.getElementById("firstName").value==""){
            document.getElementById("firstNameBlock").className="show";
            return (false);
        }else{
            if (document.getElementById("surname").value==""){
                document.getElementById("surnameBlock").className="show";
                return (false);
            }else{
                if(document.getElementById("gender").value == "0"){
                    document.getElementById("genderBlock").className="show";
                    return (false);
                }
            }
        }
        return (true);
    }
    document.getElementById("emailBlock").className="show";
    return (false);
}

/*******
#----------------------------------------------------------------------------  
Function to disable or enable subscription preference checkbox
#----------------------------------------------------------------------------  
*******/
function updatePreferences(value) {
    for (iCounter = 1; iCounter <= 12; iCounter++)
    {
       var obj = document.getElementById("check"+iCounter);
       
       if (obj)
       {
           if(value == 1)
              obj.disabled = false;
           else
              obj.disabled = true;	                    
       }
    }
}

/*******
#----------------------------------------------------------------------------  
Function displays the textbox in newsletter-preference page
#----------------------------------------------------------------------------  
*******/
function unhideEmailBox(){
    document.getElementById("mailTxtBox").className="show";
    document.getElementById("emailValue").className="hide";
}

/*******
#----------------------------------------------------------------------------  
Function that expands the promotions in the detail page
#----------------------------------------------------------------------------  
*******/

  function displayAllPromotions(asin) {
    document.getElementById("onePromotion"+asin).className = "hide";
    document.getElementById("allPromotions"+asin).className = "show prm";
  }

/*******
#----------------------------------------------------------------------------  
Function that collapses the promotions in the detail page
#----------------------------------------------------------------------------  
*******/

  function displayOnePromotion(asin) {
    document.getElementById("onePromotion"+asin).className = "show prm";
    document.getElementById("allPromotions"+asin).className = "hide";
  }

/*******
#----------------------------------------------------------------------------
Function to display feature bullets and to unhide the same
#----------------------------------------------------------------------------
*******/

function showFeatureList(asin,count) {
  if(count==1){
    document.getElementById("showFeatures_"+asin).className="show";
    document.getElementById("clickToCollapse"+asin).className="show";
    document.getElementById("seeMore"+asin).className="hide";
  }else{
    document.getElementById("showFeatures_"+asin).className="hide";
    document.getElementById("clickToCollapse"+asin).className="hide";
    document.getElementById("seeMore"+asin).className="show";
  }
}

/*******
#----------------------------------------------------------------------------
Function for popover in left-nav
#----------------------------------------------------------------------------
*******/
function insertSizeData(bin){
    sizeStyleStr = "<style>.sizeFloat {background-color:white; border: solid 1px #333333; z-index:400; position:absolute;}</style>";

    divStr = '<div class="sizeFloat" id="isFloat' + bin + '" onMouseout=""></div>';

    document.write(sizeStyleStr);
    document.write(divStr);

    hidePopover('isFloat' + bin);

}

var populated = 0;

/*******
#----------------------------------------------------------------------------
Function for popover in left-nav
#----------------------------------------------------------------------------
*******/
function showSizeData(bin, label1, label2, useULTag){

    var divDisp = document.getElementById('sizebin' + bin);
    var divIdFloat = document.getElementById('isFloat' + bin);

    divIdFloat.style.left = divDisp.offsetLeft - 0;
    divIdFloat.style.top = divDisp.offsetTop + 10;
    divIdFloat.style.visibility = 'visible';


  if (populated == 0)
  {
   var popovercontent = '<div class="margin12px"><table  class="sizePop"><tr class="even"><td colspan="6" class="padLeft12px lbl1">'+ label1 +'</td></tr><tr><td colspan="6" class="lbl2">'+ label2 +'</td></tr><tr>'

    var ArrLinks = new Array();
    ArrLinks = sizeLinks[bin];
    var linkCount = ArrLinks.length;
    var colspanValue = 6 - (linkCount % 6);
    var padRtClass = '';
    
    for (i = 0; i < linkCount; i++) {
        if ( ((i+1) % 6) == 0 ) {
            padRtClass = 'padRight12px';
        } else {
            padRtClass = '';
        }
        if (  useULTag ) {
            popovercontent = popovercontent + '<td class="sizeCell ' + padRtClass + '"><ul class="default">'+ ArrLinks[i]  + '</ul></td>';
        }else {
            popovercontent = popovercontent + '<td class="sizeCell ' + padRtClass + '">' + ArrLinks[i] + '</td>';
        }
        if ( ((i+1) % 6) == 0 ) {
             popovercontent = popovercontent + '</tr><tr>';
        }
    }

    popovercontent = popovercontent + '<td colspan=' + colspanValue + '>&nbsp;</td></tr></table></div>';
    divIdFloat.innerHTML = popovercontent;
   }
    insertIFrameBehindPopup(divIdFloat);
    populated = 1;
}

  function insertIFrameBehindPopup(divIdFloat) {


	var iframe = document.getElementById("iframeMarker");

	if(iframe && navigator.appVersion.substr(22,3)!="5.0")
  			iframe.innerHTML = "<iframe id='menu_iframe' scrolling='no' frameborder='0' height=100% width=100%></iframe>";

        if(iframe)
  	{
	     iframe.style.position = "absolute";
	     iframe.style.top = divIdFloat.offsetTop - 0.5;
	     iframe.style.left = divIdFloat.offsetLeft - 0.5;
	     iframe.style.width = divIdFloat.clientWidth + 5;
	     iframe.style.height = divIdFloat.clientHeight + 5;
             iframe.style.display = "inline";
  	}
  }

function toggleMenuElement(el) {
        var element = el.offsetParent;
        if(element.className.indexOf('unhide') !=-1){
                element.className = element.className.replace(/unhide/,"min");
        }else{
                        if(element.className.indexOf('min') !=-1){
                                element.className = element.className.replace(/min/,"unhide");
                        }
        }
}

function toggleLeftMenu(el) {
        var element = el.offsetParent;
        if(element.className.indexOf('max') !=-1){
                element.className = element.className.replace(/max/,"min");
        }else{
                        if(element.className.indexOf('min') !=-1){
                                element.className = element.className.replace(/min/,"max");
                        }
        }
}

/*******
#----------------------------------------------------------------------------
#Function for Change Favourites - IYR
#----------------------------------------------------------------------------
*******/

function toggle(el) {
        var element = el;
        if(element.className.indexOf('jfyShow') !=-1){
                element.className = element.className.replace(/jfyShow/,"hide");
        }else{
                        if(element.className.indexOf('hide') !=-1){
                                element.className = element.className.replace(/hide/,"jfyShow");
                        }
        }
}

/*******
#----------------------------------------------------------------------------
Functions for popover swatches
#----------------------------------------------------------------------------
*******/
 
// CSS style for 'Swatches' popover
 function insertSwatchData(asin){
     styleStr = "<style>.swatchDataFloat {background-color:white !important; padding:4px; border: solid 1px #333333; z-index:400; width:130px; position:absolute;}</style>";
 
     divStr = '<div class="swatchDataFloat" id="isFloat' + asin + '"></div>';
 
     document.write(styleStr);
     document.write(divStr);
 
     hidePopover('isFloat' + asin);
 }
 
 // Show the 'Swatches' popover
 function showSwatchData(asin, allColors, swatchClose, widget){
     var divDisp = document.getElementById('swatches' + asin + widget);
     var divIdFloat = document.getElementById('isFloat' + asin + widget);
 
     divIdFloat.style.left = divDisp.offsetLeft - 30;
     divIdFloat.style.top = divDisp.offsetTop - 30;
     divIdFloat.style.visibility = 'visible';
 
  // TODO: Put close popover image here
     var popovercontent = '<a href="javascript:hidePopover(\'isFloat' + asin + widget + '\')">' +
                           swatchClose + '</a><h6>' + allColors + '&nbsp;Colours</h6><div class="samples">'
 
     var ArrImages = new Array();
     if (widget != '') {
       ArrImages = eval('swatchImages'+asin)[asin];
     } else {
       ArrImages = swatchImages[asin];
     }
     for (i=0; i<ArrImages.length; i++) {
         popovercontent = popovercontent + ArrImages[i] + '&nbsp;';
         if ( ((i+1) % 4) == 0 ) {
              popovercontent = popovercontent + '<br />';
         }
     }
 
     popovercontent = popovercontent + '</div>';
     divIdFloat.innerHTML = popovercontent;
 }
 
 
 function hidePopover(isFloatID){
     var divIdFloat = document.getElementById(isFloatID);
     divIdFloat.style.visibility = 'hidden';

     if (document.getElementById("iframeMarker")) {
        document.getElementById("iframeMarker").style.display = "none";
     }    
 
 }

function updateStartIndex(delta,totalViews,viewableCount) {
   var obj = document.getElementById('hdnStartIndex');
   var currentVal = eval(obj.value);
   obj.value = currentVal + eval(delta);
   updateView(obj.value,totalViews,viewableCount);
}

function updateView(curStartIndex,totalViews,viewableCount){
   curStartIndex = eval(curStartIndex );

   document.getElementById('leftArrow').className = 'hide';
   document.getElementById('leftpadder').className = 'unhide';
   document.getElementById('rightArrow').className = 'hide';
   document.getElementById('rightpadder').className = 'unhide';

   if (curStartIndex != 1)
   {
        document.getElementById('leftArrow').className = 'unhide middle';
        document.getElementById('leftpadder').className = 'hide';
   }

   if (curStartIndex <= (totalViews - viewableCount))
   {
        document.getElementById('rightArrow').className = 'unhide middle';
        document.getElementById('rightpadder').className = 'hide';
   }

   for (iCount = 0; iCount < totalViews; iCount++)
   {
       var obj = document.getElementById('image_'+iCount);

       if (obj && (iCount + 1 >= curStartIndex  && iCount + 1 < (curStartIndex + viewableCount) )) {
          obj.className = "unhide";
       }
       else if (obj) {
           obj.className = "hide";
       }
   }
}

function changeRating (asin,rate,name) {
    if ( rate == 'OWN') {
        document.getElementById(asin + '.rating.owned').value = "OWN";
    } else {
        document.getElementById(asin + '.rating.onetofive').value = rate;
    }

    formName = asin + '_' + name;
    document.forms[formName].submit();
}

function toggleRv (e1, currClassName) {
    element = e1.offsetParent;
    singleRv(element, currClassName);
    if(element.className == currClassName + " max") {
        element.className = currClassName + " min";
    } else{
        element.className = currClassName + " max";
    }
}

function singleRv(element, currClassName){
    if(element.id != 'singleId'){ //resets if this is a new element
        if(old = document.getElementById('singleId')){
            old.className = currClassName + " min";
            old.id = "";
        }
        element.id = "singleId"; //rename to id
    }
}

// Function to get all elements of the id passed in the page
function getElementsById(sId)
{
  var outArray = new Array();
  if(typeof(sId)!='string' || !sId)
  {
	return outArray;
  };

  if(document.evaluate)
  {
	var xpathString = "//*[@id='" + sId.toString() + "']"
	var xpathResult = document.evaluate(xpathString, document, null, 0, null);
	while ((outArray[outArray.length] = xpathResult.iterateNext())) { }
	outArray.pop();
  }
  else if(document.all)
  {
        if (!document.all[sId])
             return;

	for(var i=0,j=document.all[sId].length;i<j;i+=1){
	outArray[i] =  document.all[sId][i];}

  }else if(document.getElementsByTagName)
  {

	var aEl = document.getElementsByTagName( '*' );
	for(var i=0,j=aEl.length;i<j;i+=1){

		if(aEl[i].id == sId )
		{
			outArray.push(aEl[i]);
		};
	};

  };

  return outArray;
 }

  function setImageViewerPopupLink(link_name, link_value) {
    link_value = "openPopupWindow('" + link_value +"', "
                 +"'toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,status=no,"
                 +"dependent=yes,alwaysLowered=yes,top=10,width=670,height=630');return false";
    var linkObj = document.getElementById(link_name);
    if (linkObj) {
     // Introduced one more hack in regex due to omniture clickmap issue TT# 0003193764 
     var myReg = /(['"]openPopupWindow.+false?['"])|(['"]javascript.+false;['"])|(['"]s_objectID.+true?['"])/ig;
     linkObj.innerHTML = (linkObj.innerHTML).replace(myReg, '"'+link_value+'"');
    }
  }

  function showProductDetail(asin,count,seemore,clickToCollapse,seeMoreImage,collapseImage,spacerImage) {
    if(count==1){
      document.getElementById("seeMore"+asin).innerHTML = '<a class="noUln bulletLink" href="javascript:showProductDetail(\''+asin+'\',2,\''+seemore+
      '\',\''+clickToCollapse+'\',\''+seeMoreImage+'\',\''+collapseImage+'\',\''+spacerImage+'\')" title="'+clickToCollapse+'"><img src="'+collapseImage+
      '" align="absmiddle" border="0"><img src="'+spacerImage+'" border="0" height="1" width="6">'+clickToCollapse+'</a>';
      document.getElementById("showFeatures_"+asin).className="show";
    }else{
      document.getElementById("seeMore"+asin).innerHTML = '<a class="noUln bulletLink" href="javascript:showProductDetail(\''+asin+'\',1,\''+seemore+
      '\',\''+clickToCollapse+'\',\''+seeMoreImage+'\',\''+collapseImage+'\',\''+spacerImage+'\')" title="'+seemore+'"><img src="'+seeMoreImage+
      '" align="absmiddle" border="0"><img src="'+spacerImage+'" border="0" height="1" width="6">'+seemore+'</a>';
      document.getElementById("showFeatures_"+asin).className="hide";
    }
  }

// Function to hide all Select (dropdowns) behind a div
function hideAdjacentSelectObjs( targetDiv ) {
    if (navigator.appName != "Microsoft Internet Explorer")
      return;
    targetDiv = document.getElementById(targetDiv);
    
    for(var i = 0; i < document.all.tags( "SELECT" ).length; ++i) {
        obj = document.all.tags( "SELECT" )[i];
        obj.style.visibility = "hidden";
        obj.tempHidden = '0';
    }
}

// Function to show all Select (dropdowns) in the document
function showAllSelectObjs() {
    if (navigator.appName != "Microsoft Internet Explorer")
      return;

    var arrSelect = document.getElementsByTagName("SELECT");
    for(var i = 0; i < arrSelect.length; ++i) {
        if (arrSelect[i].tempHidden == '0') {
            arrSelect[i].style.visibility = "visible";
            arrSelect[i].tempHidden = '';
        }
    }
}

// Function to position the top-nav tabs
function positionTab(div, parentObj) {
  divObj = document.getElementById(div);
  var top = findPosY(parentObj);
  var left = findPosX(parentObj);
  if (navigator.appName == "Microsoft Internet Explorer") {
     divObj.style.top = top + 32;
     divObj.style.left = left + 1;
  } else {
     divObj.style.top = top + 9;
     divObj.style.left = left - 1.5;

  }
}

 // Function to find the X position of an element
 function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

 // Function to find the Y position of an element
  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

  //function to create a cookie
  function addCookie(name,value,days) {
       if (days) {
           var date = new Date();
           date.setTime(date.getTime()+(days*24*60*60*1000));
           var expires = "; expires="+date.toGMTString();
       }
       else var expires = "";
            document.cookie = name+"="+value+expires+"; path=/";
  }

   // Sets the cookie splash-id with the required values
   // Cookie format: "email1=flashid,email2=flashid,email3=flash3,"
   // For anonymous users: "session-id=flashid,email1-flashid,"
   function setSplashCookie(email, value, splashCookie) {
     var cookieString = "";
     // If the cookie for the current user is not found, 
     // just append it
     if (splashCookie == null || splashCookie.indexOf(email) == -1) {
          cookieString = ((splashCookie == null)?"":splashCookie) + email + "=" + value + ":";
     } else {
        // If the cookie is found, replace the existing one to update
        // the splash Id
         var arrTemp = splashCookie.split(":");
         for(i = 0; i < arrTemp.length; i++) {
            if (arrTemp[i].indexOf(email) >= 0) {
               cookieString += email+"="+value+":";
            } else if (arrTemp[i] != '') {
               cookieString += arrTemp[i]+":";
            }
         }
     }

     // Add the cookie, expires after 365 days
     addCookie("splash-id",cookieString, 365);
   }

   function trim(s){
     if((s==null)||(typeof(s)!='string')||!s.length)return'';
     return s.replace(/^\s+/,'').replace(/\s+$/,'');
   }
