// Reg Expression for Email Validation
var emailAddressRegex = /^[^\W_](\.?[^<>(){\}[\]\\.,;:%\s@\"]+)*@([a-zA-Z0-9-]{2,}\.)+[a-zA-Z]{2,}$/;

/*******
#-------------------------------------------------------------------------
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,window_name) {
  
  var window_name = (window_name == null) ? "popup" : window_name;
  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,window_name,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 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 collectionDisplay(tabId) {
                                                                                                                          
    if(tabId == 'collection'){
        var id = 'siblings';
        var contentId = 'siblings';
    }else{
        var id = 'colours';
        var contentId = tabId;
    }
                                                                                                                          
    // These are for hiding and showing tabs
    document.getElementById('list-fabrics').className = "";
    document.getElementById('list-offers').className = "";
    document.getElementById('list-fabricDetails').className = "";
    document.getElementById('list-collection').className = "";
    document.getElementById('list-' + 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 (contentId) {
      document.getElementById(contentId).className = 'show';
      document.getElementById('tab').value = tabId;
    }
 }
 
/*******
#----------------------------------------------------------------------------------------------------
 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";
            addError(document.getElementById("emailBlock1").innerHTML);
        }
    }if (btnNumber==2){
        if (emailAddressRegex.test(document.Newsletter2.emailAddr2.value) )
        {
            document.Newsletter2.submit();
        }else{
            document.getElementById("emailBlock2").className="show";
            addError(document.getElementById("emailBlock2").innerHTML);
        }
    }
    submitOmniture();
}

/*******
#----------------------------------------------------------------------------  
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 adds the user errors into an array
#----------------------------------------------------------------------------
*******/
function addError (errorMsg) {
  if (typeof errorsArray == 'undefined') { var errorsArray = [];}
  errorsArray[errorsArray.length] = errorMsg;
}

/*******
#----------------------------------------------------------------------------
Function sends omniture data for tracking user experience
#----------------------------------------------------------------------------
*******/
function submitOmniture() {

  if (typeof errorsArray != "undefined" && (errorsArray).length > 0) {
    // remove html tags from teh error messages before populating in omniture vars
    s.prop14 = "ERROR: "+(errorsArray).join(" ").replace(/<(.|\n)+?>/g, '');
    if (typeof errorsArray[0] != "undefined") {s.prop24 = errorsArray[0].replace(/<(.|\n)+?>/g, '');}
    if (typeof errorsArray[1] != "undefined") {s.prop25 = errorsArray[1].replace(/<(.|\n)+?>/g, '');}
    if (typeof errorsArray[2] != "undefined") {s.prop26 = errorsArray[2].replace(/<(.|\n)+?>/g, '');}
    if (typeof errorsArray[3] != "undefined") {s.prop27 = errorsArray[3].replace(/<(.|\n)+?>/g, '');}
    if (typeof errorsArray[4] != "undefined") {s.prop28 = errorsArray[4].replace(/<(.|\n)+?>/g, '');}
    // Add event16 in case of user errors
    s.events = (s.events == "")? "event16" : s.events+',event16';
    var s_code=s.t();
    if(s_code)document.write(s_code);
  }
}

/*******
#----------------------------------------------------------------------------  
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";
            addError(document.getElementById("firstNameBlock").innerHTML);
            submitOmniture();
           return (false);
        }else{
            if (document.getElementById("surname").value==""){
                document.getElementById("surnameBlock").className="show";
                addError(document.getElementById("surnameBlock").innerHTML);
                submitOmniture();
                return (false);
            }else{
                if(document.getElementById("gender").value == "0"){
                    document.getElementById("genderBlock").className="show";
                    addError(document.getElementById("genderBlock").innerHTML);
                    submitOmniture();
                    return (false);
                }
            }
        }
        return (true);
    }
    document.getElementById("emailBlock").className="show";
    addError(document.getElementById("emailBlock").innerHTML);
    submitOmniture();
    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) % 6) == 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 zoomImagePopUp(link_name) {
   var zoomLink = document.getElementById(link_name);
   if (zoomLink && zoomLink.value) {
     openPopupWindow( zoomLink.value ,"toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,status=no,dependent=yes,alwaysLowered=yes,top=10,width=670,height=630");
   }
  }

  function setImageViewerPopupLink(link_name, link_value) {
   var zoomLink = document.getElementById('curr_'+link_name);
   if (zoomLink) {
    zoomLink.value = 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+$/,'');
   }

// disableOnChange and enableOnChange are implemented to support desired functionality
// for tabbing through multiple variation ASIN fields
                                                                                                                          
var disableOnChangeFlag = 0;
var nextActiveElement = 0;
                                                                                                                          
                                                                                                                          
function disableOnChange(event) {
    var srcObj;
                                                                                                                          
    // if is 'Enter' or 'Tab', trigger onChange event for keyboard accessability
    if(event.keyCode == 9 /* Tab */ || event.keyCode == 13 /* Enter */) {
        srcObj = event.srcElement || event.target;
        srcObj.onchange();
    } else {
        disableOnChangeFlag = 1;
    }
}
                                                                                                                          
function enableOnChange(event) {
    disableOnChangeFlag = 0;
    if(event.keyCode == 13 /* Enter */ && nextActiveElement) {
       nextActiveElement.focus();
    }
    nextActiveElement = 0;
}

 // Function to show dietary text when hovered over the icons
 function fnShowOrHideDietaryText(showFlag, ASIN, pageType, text) {
   var linkObj = document.getElementById(ASIN + '_' + pageType + '_' + 'dietary_link');
   var spanObj = document.getElementById(ASIN + '_' + pageType + '_' + 'dietary_name');

   if (spanObj == undefined || linkObj == undefined)
        return;

   if (showFlag == 1) {
     spanObj.className = '';
     spanObj.innerHTML = text;
     linkObj.className = 'hide';
   } else {
     spanObj.innerHTML = '';
     spanObj.className = 'hide';
     linkObj.className = '';
   }
 }
 
 function showOrHideUnitPrice(asin, index, pageType) {
    var unitPriceObj;
    unitPriceObj= document.getElementById('unitPrice'+asin+pageType);
    if (unitPriceObj == undefined) {
        return;
    } else if (index == 0) {
        unitPriceObj.className = 'hide';
    } else {
    unitPriceObj.className = '';
    }
}

function validateFieldValue(e, regExpObj) {
   var keynum, keychar;
  
   if(window.event) // IE
      keynum = e.keyCode;
   else if(e.which) // Netscape/Firefox/Opera
      keynum = e.which;
   
   // Allow if its navigation or backspace
   if (keynum == undefined || keynum == 8) return true;

   keychar = String.fromCharCode(keynum);
   // return the validation result as boolean
   return regExpObj.test(keychar)
}


// This function is for displaying the blocked contents when the user clicks on the read more link and to hide the contents when the user clicks
// on the See Less link in customer reviews section on the detail page.  
function readMore(display, divDecider) {
  if (display == 1) {
      document.getElementById("readmore."+divDecider).style.display = "block";
      document.getElementById("seeless."+divDecider).style.display = "none";
  }
  else {
      document.getElementById("readmore."+divDecider).style.display = "none";
      document.getElementById("seeless."+divDecider).style.display = "block";

  }
}

//Generic Functions to show and hide div. Can be used by any ID passed in to toggle the div

function showDiv(divID) {
    document.getElementById(divID).style.display ="block";
}
                                                                                                                                                             
function hideDiv(divID) {
    document.getElementById(divID).style.display ="none";
}

function showFlyOver(e)
{
var reportLink= e;
                                                                                                                                                             
    // Walk up until we find popparent
    while (e.className != "popparent" && e != e.parentNode) {
        e = e.parentNode;
    }
                                                                                                                                                             
    // Walk the children until we find popover
    e = e.firstChild;
    while (e.className != "popover") {
        e = e.nextSibling;
    }
    e.style.display = "block";
    e.reportLink = reportLink;
}
                                                                                                                                                             
function hideFlyOver(e)
{
    while (e.className != "popover") e = e.parentNode;
    e.style.display = "none";
}


function confirmReport(e, url , nonjsUrl)
{
    var httpRequest;
    var ready;
    var parent;
    var text;
    var newSpan;
    var READY_STATE_COMPLETE = 4;
                                                                                                                                                             
    while (e.className != "popover") e = e.parentNode;
    e.style.display = "none";
                                                                                                                                                             
    e = e.reportLink;
    parent = e.parentNode;
                                                                                                                                                             
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }


   httpRequest.onreadystatechange=function() {
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200 )  {
            var reqText= httpRequest.responseText;
            var pattern = /userNotSignedIn/; 

            if (!pattern.test(reqText)) {
                var newDiv= document.createElement("div");
                parent.removeChild(e);
                newDiv.className = "confirmText";
                var text = document.createTextNode("Thank you. Your Report has been sent to Marks and Spencer for review.");
                newDiv.appendChild(text);
                parent.appendChild(newDiv);
            } else {
            //redirect user to signin since we send an error back if they're not recognized.
                window.location = nonjsUrl;
                 return true;
            }
        } else {
            //something else is wrong. try again
             newDiv= document.createElement("div");
             text = document.createTextNode("Please Try again");
             newDiv.appendChild(text);
             parent.appendChild(newDiv);
        }
    } else {
        return false;
    }
   }
   httpRequest.open("POST", url, true);
   //httpRequest.setRequestHeader("Content-type", "application/x-form-urlencoded");
   httpRequest.send("");
}

// Plan price display on Wine widget
function selectPrice(planID) {
 jQuery('#winePlanPrice').html(jQuery(document).children().find("input:hidden[name='nowLabel']").val() +" "+
      planPrices[planID] + "<br/>" + jQuery(document).children().find("input:hidden[name='introductoryOfferLabel']").val());
}
jQuery(document).ready( function() {
  var allInputTags = jQuery(document).children().find("input[name=planID]");
  if( allInputTags != null && allInputTags != undefined && allInputTags.length > 0){
    var i;
    for (i=0; i<allInputTags.length; i++) {
      var tag = allInputTags[i];
      if (tag.checked) {
        selectPrice (tag.value);
        break;
      }
    }
    if(i==allInputTags.length){
      allInputTags[0].checked = true;
      selectPrice (allInputTags[0].value);
    }
  }

});

jQuery(document).ready(function() {
	//Show the 'Need Help' image when javascript is enabled
	jQuery('.needHelpSection').show();
	jQuery('.triggerHelp').click(function(){
			toggleHelpText();
		}
	);

	jQuery('.postalCodeHelp').click(
		function(){
			var helpUrl = jQuery('.postalCodeHelp').attr('href');
			var contextWindow = window.open(helpUrl, 'PostCodeHelp', 'width=800,height=625,resizeable=1,scrollbars=1,toolbar=0,status=1');
			contextWindow.focus();
			return false;
		}
	);
	
});

function toggleHelpText() {
	jQuery('.helpText').toggle();
}


// Minicart javascript
// Move to minicart.js when final

jQuery(document).ready(function(){
  miniCartHandler.initialize();
  quickOrderComponent.initialize();
});
var miniCartHandler = {
  jBasket : null,
  jBasketTitle  : null,
  jAjaxCartContainer : null,
  cartHtml : null,
  hoverContentInProgress : false,
  isIE : false,
  iframeShim : null,
  itemsToDisplay: 1,
  mouseOverPopOver: null,

  // initalize the object
  initialize : function() {

    this.jBasket = jQuery('#basket');
    this.jBasketTitle = this.jBasket.find('.basketTitle');
    
    // create the container 
    this.jAjaxCartContainer = jQuery('<div></div>');
    this.jAjaxCartContainer.addClass('ajaxContainer');
    this.jAjaxCartContainer.hide();
    this.jBasket.append(this.jAjaxCartContainer);
    
    // we be IE?
    var isIE = (jQuery.browser.msie && parseInt(jQuery.browser.version) >= 6);
    this.iframeShim = jQuery(document.createElement("iframe")).addClass("shim").attr("src", "javascript:false;");
    this.jBasket.append(this.iframeShim);
    this.mouseOverPopOver = false;

    this.attachEvents();
  },

  // helper method to figure out if the cart is displayable
  isMiniCartDisplayable : function() {
    var numberOfItemsString = jQuery('#basket').find('span.basketItems > span#inlineCart').html();
    var numberOfItems = parseInt(numberOfItemsString);
    if (numberOfItems > 0) {
      return true;
    } else {
      return false;
    }
  },
  
  // define events
  attachEvents : function() {
    var parentThis = this;
    var shim = null;

    this.jAjaxCartContainer.mouseover(function(){
        parentThis.mouseOverPopOver = true;
    });

    this.jAjaxCartContainer.mouseout(function(){
           parentThis.mouseOverPopOver = false;
    });
  },

  // stateless recurring handlers go here
  attachRecurringHandlers : function(parentThis) {
    jQuery('.jCloseMiniCart > img').click(function(){parentThis.closeCart(parentThis);});
    jQuery('.jCloseMiniCart > a').click(function(){parentThis.closeCart(parentThis);return false;});
  },

  // responsible for de-duping ajax calls
  displayCart : function() {
    this.isClosingTimeOver = false;
    if (this.cartHtml == null) {
      this.callAjaxCart();
    } else {
      this.renderAsync(this.cartHtml);
    }
  },

  // hides the cart
  closeCart : function(parentThis) {
    parentThis.jAjaxCartContainer.stop();
    parentThis.jAjaxCartContainer.attr("style", "");
    parentThis.jAjaxCartContainer.hide();
    parentThis.iframeShim.hide();
  },

  // responsible for rendering html retrieved via ajax
  renderAsync : function(cartHtml) {
    cartHtml = cartHtml.replace(/^\s*/, "").replace(/\s*$/, "");
    
    this.cartHtml = cartHtml;
    this.jAjaxCartContainer.html(this.cartHtml);
    this.jAjaxCartContainer.show();
    this.iframeShim.height(this.jAjaxCartContainer.height()); 
    this.iframeShim.css('top',this.jAjaxCartContainer.offset().top);
    this.jAjaxCartContainer.hide();
    this.iframeShim.slideDown(2000);
    var parentThis = this;
    this.jAjaxCartContainer.slideDown(2000,function(){
        if(typeof(DBAG_OmnitureInitializer) != 'undefined' && DBAG_OmnitureInitializer!=null){
            DBAG_OmnitureInitializer.initialize();
        }
        window.setTimeout( function(){parentThis.closePopup();}, 8000);
    });
    this.attachRecurringHandlers(this);
  },

  closePopup: function(){
    var parentThis = this;
    if(!this.mouseOverPopOver){
      this.jAjaxCartContainer.slideUp(2000);
      this.iframeShim.slideUp(2000);
    } else {
        window.setTimeout(function(){parentThis.closePopup();} , 100);
    }
  },
  // calls the cart application
  callAjaxCart : function(maxRecentItems) {
    var url = '/ajaxCart?maxRecentItems=';
    if(maxRecentItems && maxRecentItems > 0){
      url += maxRecentItems;
      this.itemsToDisplay = maxRecentItems;
    }
    else{
      url += this.itemsToDisplay;
    }
    var parentThis = this;
    jQuery.ajax({
      type    : 'GET',
      url     : url,
      cache    : false,
      error   : function(html,status) {
        //gobble errors
      },
      success : function(html,status) {
        parentThis.renderAsync(html)
      },
      timeout : 10000
    });
  }
};

function updateMiniBasket(responseHtml){
  responseHtml = jQuery(responseHtml);
  var cartCountInput = responseHtml.find('input[name="cartActiveItemTotalQuantity"]:first');
  if (cartCountInput && cartCountInput.length && cartCountInput.val()) {
    var cartCount = cartCountInput.val();
    cartCount = cartCount.replace(/(\n)|(\s)/g, "");
    var spanElement = jQuery('div#basket').find('span#inlineCart');
    if (spanElement && spanElement.length && cartCount) {
      spanElement.html(cartCount);
    }
  }
  updateProceedToCheckoutCount();
}

function updateProceedToCheckoutCount(){
  var basket = jQuery('div#basket');
  var checkoutLink = basket.find('span.proceedToCheckout a:first');
  if (!checkoutLink || !checkoutLink.length || checkoutLink.length < 1) {
    var link = jQuery(document.createElement('a'));
    link.attr('href', '/gp/cart/?proceedToCheckout.x=1');
    link.text('Proceed to checkout');
    var span = jQuery(document.createElement('span'));
    span.attr('class', 'proceedToCheckout');
    span.html(link);
    basket.append(span);
  }
}


var quickOrderComponent = {
    arrayOfItemAsins: null,
    quickBuyForm: null,
    quickBuyItemContainers: null,
    errorContent: null,
    currentSelectedAsins: null,
    
    initialize: function(){
        this.quickBuyItemContainers = new Array();
        this.errorContent = '<td colspan="4" class="padLeft12px"><div id="m0" class="message"><div id="m0" class="mError"><h3>Important Message</h3>Please select product options and quantity and try again.</div></div></td>';
        var itemsAsinsString = jQuery("input[name$='codeListAsin']").val();
        this.arrayOfItemAsins = new Array();
        if (itemsAsinsString) {
            this.arrayOfItemAsins = itemsAsinsString.split(",");
            this.currentSelectedAsins = itemsAsinsString.split(",");
        }
        this.quickBuyForm = jQuery("#handleBuy");
        var allQuickBuyTables = this.quickBuyForm.find("#quickResults");
        var parentThis = this;
        var i = 0;
        
        allQuickBuyTables.each(function(){
            if (jQuery(this).find("select").length > 0) {
                parentThis.quickBuyItemContainers[i] = jQuery(this);
                var thisItemString = parentThis.currentSelectedAsins[i];
                var selectsInTheItem = jQuery(this).find('select.md');
                for (k = 0; k < selectsInTheItem.length - 1; k++) {
                  thisItemString += ('.' + selectsInTheItem.eq(k).val());
                }
                var asin = undefined;
                if (childVariationsToAsinHash) {
                  asin = childVariationsToAsinHash[thisItemString];
                  if (typeof(asin) == 'undefined' && thisItemString.length == 10) {
                    asin = thisItemString;
                  }

                  if(typeof(asin) == 'undefined'){
                    asin = parentThis.currentSelectedAsins[i];
                  }
                  parentThis.currentSelectedAsins[i] = asin;
                  i++;
               }
             }
        });

        this.bindEvents();
    },
    
    bindEvents: function(){
        var parentThis = this;
        var allQuickBuyTables = this.quickBuyForm.find("#quickResults");
        var parentThis = this;

	allQuickBuyTables.each(function(){
            if(jQuery(this).find("select").length > 0){
	        var thisItemContainer = jQuery(this);
                var selectsInTheItem = thisItemContainer.find('select.md');
                if(selectsInTheItem.length>1){
                   for (j = 0; j < selectsInTheItem.length - 1; j++) {
                       selectsInTheItem.eq(j).change(function(){
			  var thisItemString = jQuery(this).attr("thisItemAsin");
			  for(index=0;index<parentThis.arrayOfItemAsins.length;index++){
			      if(parentThis.arrayOfItemAsins[index]==thisItemString){
			          break;
			      }
                          }
                          for (k = 0; k < selectsInTheItem.length - 1; k++) {
                             thisItemString += ('.' + selectsInTheItem.eq(k).val());
                          }
                          var asin = undefined;
                          if (childVariationsToAsinHash) {
                             asin = childVariationsToAsinHash[thisItemString];
                          }
                          if (typeof(asin) == 'undefined' && thisItemString.length == 10) {
                             asin = thisItemString;
                          }
                         
                          if(typeof(asin) == 'undefined'){
                              asin = jQuery(this).attr("thisItemAsin");
                          }
                          jQuery(document.getElementById("availmsg_"+parentThis.currentSelectedAsins[index])).hide();
                          jQuery(document.getElementById("availmsg_"+asin)).show();
	                  parentThis.currentSelectedAsins[index] = asin;
                      });
                   }
               }
            }
        });
 
        this.quickBuyForm.submit(function(){
            var urlParamString = "";
            var itemsNum = 0;
            var toBeAddedItemsContainer = new Array();
            
            for (i = 0; i < parentThis.arrayOfItemAsins.length; i++) {
                var thisItemContainer = parentThis.quickBuyItemContainers[i];
                var selectsInTheItem = thisItemContainer.find('select.md');
                var thisItemString = parentThis.arrayOfItemAsins[i];
                for (j = 0; j < selectsInTheItem.length - 1; j++) {
                    thisItemString += ('.' + selectsInTheItem.eq(j).val());
                }
                var asin = undefined;
                if (childVariationsToAsinHash) {
                    asin = childVariationsToAsinHash[thisItemString];
                }
                if (typeof(asin) == 'undefined' && thisItemString.length == 10) {
                    asin = thisItemString;
                }
                else 
                    if (typeof(asin) == 'undefined') {
                        asin = '';
                    }
                
                var thisContainerTextInputs = thisItemContainer.find("input[type$='text']");
                var customMessage = null;
                var customAge = null;
                thisContainerTextInputs.each(function(){
                    if (jQuery(this).attr("id").indexOf("customizeNumber") > -1) {
                        customAge = jQuery(this);
                    }
                    if (jQuery(this).attr("id").indexOf("customizeMessage") > -1) {
                        customMessage = jQuery(this);
                    }
                });
                
                var qty = selectsInTheItem.eq(selectsInTheItem.length - 1).val();
                if (asin != '' && qty > 0) {
                    toBeAddedItemsContainer[itemsNum] = thisItemContainer;
                    urlParamString += ('&item.' + itemsNum + '.asin=' + asin + '&item.' + itemsNum + '.qty=' + qty);
                    if (customMessage != null) {
                        urlParamString += ('&item.' + itemsNum + '.CUST-Message=' + customMessage.val());
                    }
                    if (customAge != null) {
                        urlParamString += ('&item.' + itemsNum + '.CUST-Number=' + customAge.val());
                    }
                    itemsNum++;
                }
            }
			
			//To handle Add little extra.
			
			for (i = 0; i < parentThis.arrayOfItemAsins.length; i++) {
				var thisItemContainer = parentThis.quickBuyItemContainers[i];
				var selectsInTheItem = thisItemContainer.find('select.md');
				var qty = selectsInTheItem.eq(selectsInTheItem.length - 1).val();
				
				var aleCheckboxes = thisItemContainer.find("input[type$='checkbox']");
				aleCheckboxes.each(function(){
					if (itemsNum != -1) {
						var aleCheckbox = jQuery(this);
						var thisAleCheckboxId = aleCheckbox.attr("id");
						var isAleCheckbox = thisAleCheckboxId.indexOf("addExtraToFlowers.");
						
						if (isAleCheckbox > -1 && document.getElementById(thisAleCheckboxId).checked) {
							var thisAleCheckboxIndex = thisAleCheckboxId.substring(18);
							var thisAleAsin = jQuery(document.getElementById('asin.' + thisAleCheckboxIndex)).val();
							if (thisAleAsin && qty > 0) {
								urlParamString += ('&item.' + itemsNum + '.asin=' + thisAleAsin + '&item.' + itemsNum + '.qty=1');
								itemsNum++;
							}
							else 
								if (qty < 1) {
									var errorElement = jQuery('#errorInAddToCart');
									if (errorElement.length < 1) {
										errorElement = jQuery("<tr id='errorInAddToCart'></tr>");
										jQuery('#quickResults').eq(0).find('tr').eq(0).after(errorElement);
									}
									window.scroll(0, 0);
									errorElement.html('<td colspan="4" class="padLeft12px"><div id="m0" class="message"><div id="m0" class="mError"><h3>Important Message</h3>Extra Items can not be added to basket without the main item. </div></div></td>');
									itemsNum = -1;
								}
						}
					}
				});
			}
			
			
			//To handle add extra portions.
			if(itemsNum!=-1){
				for (i = 0; i < parentThis.arrayOfItemAsins.length; i++) {
					var thisItemContainer = parentThis.quickBuyItemContainers[i];
					var thisItemString = parentThis.arrayOfItemAsins[i];
					var addExtraPortionsContainer = thisItemContainer.find("#extraPortionsDisplay"+thisItemString);
					var extraPortionItems = addExtraPortionsContainer.find(".negBotMargin12px");
					
					extraPortionItems.each(function(){
						var thisItemContainer = jQuery(this);
						var selectsInTheItem = thisItemContainer.find('select.mdDP');
						var qty = selectsInTheItem.eq(selectsInTheItem.length - 1).val();
						var index = selectsInTheItem.eq(selectsInTheItem.length - 1).attr("id").substring(9);
						var thisItemString = jQuery(document.getElementById("asin."+index)).val(); 
						 
						for (j = 0; j < selectsInTheItem.length - 1; j++) {
		                    thisItemString += ('.' + selectsInTheItem.eq(j).val());
		                }
						
						var asin='';
						if(typeof(extraPortionsJsonData)!='undefined'){
							asin = extraPortionsJsonData[thisItemString];
						} else {
							asin = jQuery(document.getElementById("asin."+index)).val(); 
						}
						
						if(asin && qty>0){
							urlParamString += ('&item.' + itemsNum + '.asin=' + asin + '&item.' + itemsNum + '.qty=' + qty);
							itemsNum++;
						}
					});
				}
			}
			
            if (itemsNum == 0) {
                var errorElement = jQuery('#errorInAddToCart');
                if (errorElement.length < 1) {
                    errorElement = jQuery("<tr id='errorInAddToCart'></tr>");
                    jQuery('#quickResults').eq(0).find('tr').eq(0).after(errorElement);
                }
                window.scroll(0, 0);
                errorElement.html(parentThis.errorContent);
            }
            else if(itemsNum > 0) {
                var url = '/secureAjaxCart?cartAction=ADD' + urlParamString;
                jQuery.ajax({
                    type: 'GET',
                    url: url,
                    cache: false,
                    error: function(html, status){
                        var errorElement = jQuery('#errorInAddToCart');
                        if (errorElement.length < 1) {
                            errorElement = jQuery("<tr id='errorInAddToCart'></tr>");
                            jQuery('#quickResults').eq(0).find('tr').eq(0).after(errorElement);
                        }
                        window.scroll(0, 0);
                        errorElement.html('<td colspan="4" class="padLeft12px"><div id="m0" class="message"><div id="m0" class="mError"><h3>Important Message</h3>We\'re sorry. An error occurred when we tried to process your request. Rest assured, we\'re working to resolve the problem as soon as possible.</div></div></td>');
                    },
                    success: function(html, status){
                        jQuery('#errorInAddToCart').remove();
                        for (j = 0; j < toBeAddedItemsContainer.length; j++) {
                            toBeAddedItemsContainer[j].find(".error").remove();
                        }
                        if (html.indexOf('jMiniCartContainer') < 0) {
                            for (j = 0; j < toBeAddedItemsContainer.length; j++) {
                                toBeAddedItemsContainer[j].find(".error").remove();
                                if (html.indexOf('MESSAGE_HAS_SPECIAL_CHARACTERS.' + j) > -1) {
                                    var customizeMessageInput = null;
                                    var thisContainerTextInputs = toBeAddedItemsContainer[j].find("input[type$='text']");
                                    thisContainerTextInputs.each(function(){
                                        if (jQuery(this).attr("id").indexOf("customizeMessage") > -1) {
                                            customizeMessageInput = jQuery(this);
                                        }
                                    });
                                    if (customizeMessageInput != null) {
                                        customizeMessageInput.after('<div class="error"><span class="error">Sorry your personalised message cannot contain special charcters.</span></div>');
                                    }
                                }
                                else 
                                    if (html.indexOf('MESSAGE_HAS_PROFANITY.' + j) > -1) {
                                        var customizeMessageInput = null;
                                        var thisContainerTextInputs = toBeAddedItemsContainer[j].find("input[type$='text']");
                                        thisContainerTextInputs.each(function(){
                                            if (jQuery(this).attr("id").indexOf("customizeMessage") > -1) {
                                                customizeMessageInput = jQuery(this);
                                            }
                                        });
                                        if (customizeMessageInput != null) {
                                            customizeMessageInput.after('<div class="error"><span class="error">Sorry your personalised message cannot contain profanity.</span></div>');
                                        }
                                    }
                                    else 
                                        if (html.indexOf('AGE_IS_NON_NUMERIC.' + j) > -1) {
                                            var customizeNumberInput = null;
                                            var thisContainerTextInputs = toBeAddedItemsContainer[j].find("input[type$='text']");
                                            thisContainerTextInputs.each(function(){
                                                if (jQuery(this).attr("id").indexOf("customizeNumber") > -1) {
                                                    customizeNumberInput = jQuery(this);
                                                }
                                            });
                                            if (customizeNumberInput != null) {
                                                customizeNumberInput.after('<div class="error"><span class="error">Sorry, age must be numeric.</span></div>');
                                            }
                                        }
                            }
                        }
                        else {
                            updateMiniBasket(html);
                            window.scroll(0, 0);
                            miniCartHandler.renderAsync(html);
                        }
                    },
                    timeout: 10000
                });
            }
            return false;
        });
    }
};

