// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

var currentSwatch = '';
$(document).ready(function(){
  var bcFlag = false, bcSep = false;
  var bcPath = $("#breadcrumbs a.bcItem:first").attr('href');
  // This works as long as URLs are NOT custom, or at least shows a hierarchy to check against
  if ( $("#breadcrumbs .bcGrouping").length > 1 ) {
    if ( document.referrer.length ) {
      $("#breadcrumbs .bcGrouping").each(function() {
        if ( $(this).find("a[href*='"+document.referrer.replace('http://www.winecellarinnovations.com', '')+"']").length ) {
          // this is one we want
        } else {
          $(this).remove();
        }
      });
    } else {
      $("#breadcrumbs .bcGrouping:gt(0)").remove();
    }
  }
  $('div#breadcrumbs').append(' <span class="separator">&raquo;</span> <span class="last">' + $("div #productDescription h1").text() + '</span>');
  $("#breadcrumbs").show();
  
  $("#detailTabs > ul > li:not(.separator) a").each(function() {
    var id = $(this).attr('href').replace('#', '');
    if ( !$("#detailTabs div#" + id).get(0) ) {
      $("#detailTabs").append('<div id="' + id + '"><div class="tabContent"></div></div>');
    }
  });
  var $tabs = $("#detailTabs > ul").tabs();
  $("#detailTabs").show();
  if ( $("#detailTabs #tabSpecs").text() ) {
    $tabs.tabs('select', 1);
  } else {
    var i = 0;
    $("#detailTabs > ul > li:not(.separator) a").each(function() {
      var id = $(this).attr('href').replace('#', '');
      if ( $("#detailTabs div#" + id).text() ) {
        $tabs.tabs('select', i);
        return false;
      }
      i++;
    });
  }
  $("#tabFinishes .tabContent > table tr:eq(1) td:eq(1)").wrapInner('<div id="productDetailFinishesTab"></div>');
  $("#tabFinishes .tabContent > table tr:eq(1) td:eq(1)").css('vertical-align', 'top');
  
  $("div#productOptions div.productChoices div.productChoiceName:contains('Wood')").parent().find("div.productChoiceItems div").each(function(){
    $(this).addClass("woodType");
  });

  // Dynamically insert thumbnail images into product options
  // Wood Stains
  $("div#productOptions div.productChoices div.productChoiceName:contains('Stain')").parent().find("div.productChoiceItems div").each(function(){
    $(this).addClass("woodStain");
    $(this).find("span").hide();
    switch ($(this).find("span").text()) {
      case "Unstained":
        $(this).prepend('<img src="/stain-unstained.gif" width="24" height="24" alt="Unstained" title="Unstained" /><br />');
        break;
      case "Light":
        $(this).prepend('<img src="/stain-light.gif" width="24" height="24" alt="Light" title="Light" /><br />');
        break;
      case "Premium Light":
        $(this).prepend('<img src="/stain-premium-light.gif" width="24" height="24" alt="Premium Light" title="Premium Light" /><br />');
        break;
      case "Classic Mahogany":
        $(this).prepend('<img src="/stain-classic-mahogany.gif" width="24" height="24" alt="Classic Mahogany" title="Classic Mahogany" /><br />');
        break;
      case "Dark Walnut":
        $(this).prepend('<img src="/stain-dark-walnut.gif" width="24" height="24" alt="Dark Walnut" title="Dark Walnut" /><br />');
        break;
      case "Midnight Black":
        $(this).prepend('<img src="/stain-midnight-black.gif" width="24" height="24" alt="Midnight Black" title="Midnight Black" /><br />');
        break;
    }
  });
  $("div#productOptions div.productChoices div.productChoiceName:contains('Stain')").parent().append('<div id="swatchLink"><a href="#finishes">click to view all accurate wood &amp; stain swatches</a></div>');
  $("#swatchLink a").click(function() {
    $("a[href='#tabFinishes']").click();
    return true;
  });
  // Heights
  $("div#productOptions div.productChoices div.productChoiceName:contains('Height')").parent().find("div.productChoiceItems div").each(function(){
    $(this).addClass("rackHeight");
    $(this).find("span").hide();
    switch ($(this).find("span").text()) {
      case "3Ft":
      case "3 Ft":
        $(this).append('<img src="/height-3ft.gif" width="48" height="18" alt="3Ft" title="3Ft" style="padding-top: 8px;" />');
        break;
      case "4Ft":
      case "4 Ft":
        $(this).append('<img src="/height-4ft.gif" width="48" height="26" alt="4Ft" title="4Ft" />');
        break;
      case "7Ft":
      case "7 Ft":
        $(this).append('<img src="/height-7ft.gif" width="48" height="43" alt="7Ft" title="7Ft" />');
        break;
      case "8Ft":
      case "8 Ft":
        $(this).append('<img src="/height-8ft.gif" width="48" height="52" alt="8Ft" title="8Ft" />');
        break;
    }
  });
  // Heights
  $("div#productOptions div.productChoices div.productChoiceName:contains('Platform')").parent().find("div.productChoiceItems div").each(function(){
    $(this).addClass("platform");
  });
  $("div#productOptions div.productChoices div.productChoiceName:contains('Platform')").parent().prepend('<div style="float: right; margin: 20px 0 0; width: 150px; text-align: right; font-weight: bold;">view platform details</div>');

  var isOpts = false;
  $("div#productOptions div.productChoiceItems").each(function(){
    var opts = this.getElementsByTagName('input');
    if ( opts.length ) {
      isOpts = true;
      opts[0].checked = true;
    }
  });
  
  var sku = $(".productSku").text().replace('Item # ', '');
  var t = 'http://store.winecellarinnovations.com/Images/products/';
  if ( $("#additionalImages img.imageThumbnail:eq(0)").attr('src') == (t + sku + '_M.jpg') &&
       $("#additionalImages img.imageThumbnail:eq(1)").attr('src') == (t + '-' + sku + '_additional_0.jpg') )
    $("#additionalImages img.imageThumbnail:eq(0)").remove();

  var wishlistLink = $("a[href*='AddToWishlist.aspx']").attr('href');
  $("a[href*='AddToWishlist.aspx']").attr('href', wishlistLink.replace(sku, escape(sku)));
  
  if ( priceJson ) {
    // Add any different additional images to clickable thumbnails if specified in the Json
    var images = [];
    $.each(priceJson, function(i, val) {
      images.push(val[1]);
    });
    images = images.unique();
    $.each(images, function(i, val) {
      if ( !$("#additionalImages img.imageThumbnail[src='http://store.winecellarinnovations.com/"+val+"']").get(0) ) {
        $("img.imageThumbnail:last").after('<img src="http://store.winecellarinnovations.com/'+val+'" width="43" height="58" class="imageThumbnail" alt="" />');
      }
    });
    updateProductOptionPrice();

    $("div.productChoices input[type='radio']").click(function() {
      updateProductOptionPrice();
      // Build swatch value
      var wood = $("div.woodType input:checked + span").text();
      var stain = $("div.woodStain input:checked + span").text();
      if ( wood.length && stain.length ) {
        var swatch = lookupName(wood) + '_' + lookupName(stain);
        if ( swatch != currentSwatch ) {
          // update swatch & image stuff
          if ( !$("#productImageSwatch").length ) {
            $("#productImage").append('<div id="productImageSwatch"></div>');
          }
          $("#productImage img:first").width(267).height(359);
          $("#productImageSwatch").html('<img src="/'+swatch+'-th.jpg" width="135" height="36" alt="" /><br />' + wood + ' | ' + stain);
        }
        currentSwatch = swatch;
      }
      return true;
    });
    $("div.productChoices input[type='radio']:first").click();
  }

  // Handle the image switching here:
  $('#productImageToolbar img.imageThumbnail').click(function() {
    var thisPath = $(this).attr('src');
    if ( thisPath != 'http://www.winecellarinnovations.com/' ) {
      $('#productImage img:first').attr('src', thisPath);
      return true;
    }
    return false;
  });
  $('#productImageToolbar img.imageThumbnail').mouseup(function() {
    if ( priceJson ) {
      var thisPath = $(this).attr('src');
      // testing to make options switch too....
      var filename = thisPath.replace('http://store.winecellarinnovations.com/', '');
      // cycle through priceJson data knowing the "Wood" id... looking for first instance of filename...
      var woodsel = $(".woodType input:checked").val();
      $.each(priceJson, function(i, val) {
        if ( val[1] == filename ) {
          // Switch to this instance. "i" contains our hash.
          var tmpids = i.split(',');
          var sels = [];
          var ln = tmpids.length;
          var counter = 0;
          for ( j = 0; j < ln; j++ ) {
            for ( k = 1; k <= ln; k++ ) {
              if ( $("#productChoice"+k+" input[value*='"+tmpids[j]+"']").length ) {
                sels.push("#productChoice"+k+" input[value*='"+tmpids[j]+"']");
                counter++;
              }
            }
          }
          if ( counter == ln ) {
            for ( j = 0; j < sels.length; j++ ) {
              $(sels[j]).attr('checked', 'checked');
              $(sels[j]).click();
            }
            //break out of "each" iterator
            return false;
          }
        }
        /*
        if ( i.indexOf(woodsel) > -1 ) {
          if ( val[1] == filename ) {
            $(".woodStain input[value*='"+i.replace(woodsel, '').replace(',', '')+"']").attr('checked', 'checked');
            $(".woodStain input[value*='"+i.replace(woodsel, '').replace(',', '')+"']").click();
            //break out of "each" iterator
            return false;
          }
        }
        */
      });
      return true;
    }
  });

  // Sets the large image's src to the first thumbnail:
  $('#productImage img:first').attr('src', $('#productImageToolbar img.imageThumbnail:first').attr('src'));

  $("#dynamicProductPrice").show();
});

var guids = [];
var oldhref1, oldhref2;
function updateProductOptionPrice() {
  if ( !guids.length ) {
    // Get the order of guids that the API built; doesn't necessarily match the order
    // of product option choices being rendered in HTML
    var keyStr = '';
    $.each(priceJson, function(i, val) {
      keyStr = i;
      return false;
    });
    if ( keyStr ) {
      var guiAry = keyStr.split(',');
      var id;
      if ( $("#productOptions").children().length ) {
        $.each(guiAry, function(i, val) {
          id = $("input[value='" + val + "']").attr('name');
          guids.push( id.replace('optionCount', '') );
        });
      } else {
        guids.push(guiAry[0]);
      }
    }
  }
  // based on the order of guids, build our hash
  var hash = '';
  if ( $("#productOptions").children().length ) {
    $.each(guids, function(i, val) {
      if ( hash ) {
        hash += ',';
      }
      hash += $("input[name='optionCount" + val + "']:checked").val();
    });
  } else {
    hash = guids[0];
  }
  
  if ( priceJson[hash] ) {
    //alert(hash + ': ' + priceJson[hash]);
    var priceVar = priceJson[hash][0];
    var price = parseFloat(priceVar);
    $("#dynamicSku").text(priceJson[hash][2]);
    if ( priceJson[hash][1] != '' && priceJson[hash][1] != 'http://www.winecellarinnovations.com/' ) {
      $("img.imageThumbnail[src*='"+priceJson[hash][1]+"']").click();
    }
    if ( price > 0 ) {
      //$("#dynamicProductPrice").text(price.toFixed(2));
      // Check for Sale price: compare MSRP (if it's present && > 0) against site price
      var listpriceVar = priceJson[hash][7];
      var listprice = parseFloat(listpriceVar);
      if ( listprice > price ) {
        $("#dynamicProductPrice").text(listprice.toFixed(2));
        $(".productPrice").addClass('listPriceDisplay');
        $(".productPrice").after('<div class="salePrice">Sale Price: $'+price.toFixed(2)+'</div>');
      } else {
        $("#dynamicProductPrice").text(price.toFixed(2));
        $("div.salePrice").remove();
        $(".productPrice").removeClass('listPriceDisplay');
      }
      if ( $(".productAddToCartNotAvail").length ) {
        $(".productAddToCartNotAvail").remove();
        $("#addToCartButton").html('<input type="image" value="Add to Cart" src="/button-add-to-cart.gif" />');
        $("#designRequestButton").attr('href', oldhref1).css('cursor', 'pointer');
        $("#addToProjectsButton").attr('href', oldhref2).css('cursor', 'pointer');
        $("#designRequestButton img").attr('src', '/button-design-request.gif');
        $("#addToProjectsButton img").attr('src', '/button-add-to-wishlist.gif');
        $(".productAddToCart").show();
      }
    } else {
      if ( $(".productAddToCartNotAvail").length ) {
        $(".productAddToCartNotAvail").remove();
      }
      $(".productAddToCart").after('<div class="productAddToCartNotAvail"><br /><strong>Not Available</strong><br /></div>');
      $("#addToCartButton").html('<img src="/button-add-to-cart-disabled.gif" width="129" height="27" alt="Not available" />');
      oldhref1 = $("#designRequestButton").attr('href');
      oldhref2 = $("#addToProjectsButton").attr('href');
      $("#designRequestButton").attr('href', '#').css('cursor', 'default');
      $("#addToProjectsButton").attr('href', '#').css('cursor', 'default');
      $("#designRequestButton img").attr('src', '/button-design-request-disabled.gif');
      $("#addToProjectsButton img").attr('src', '/button-add-to-wishlist-disabled.gif');
      $(".productAddToCart").hide();
    }
  }
}

function lookupName( name ) {
    if ( name.toLowerCase().indexOf('amber blaze') > -1 )
        return 'AB';
    if ( name.toLowerCase().indexOf('allheart') > -1 )
        return 'AH';
    if ( name.toLowerCase().indexOf('pine') > -1 )
        return 'PN';
    if ( name.toLowerCase().indexOf('premium redwood') > -1 )
        return 'PR';
    if ( name.toLowerCase().indexOf('red oak') > -1 )
        return 'RO';
    if ( name.toLowerCase().indexOf('prime') > -1 )
        return 'PM';
    if ( name.toLowerCase().indexOf('select') > -1 )
        return 'SM';
    if ( name.toLowerCase().indexOf('unstained') > -1 )
        return 'UN';
    if ( name.toLowerCase().indexOf('classic') > -1 )
        return 'CM';
    if ( name.toLowerCase().indexOf('black') > -1 )
        return 'BLK';
    if ( name.toLowerCase().indexOf('premium light') > -1 )
        return 'PL';
    if ( name.toLowerCase().indexOf('light') > -1 )
        return 'LS';
    if ( name.toLowerCase().indexOf('dark') > -1 )
        return 'DW';
}
