// This needs to run immediately...
//if ( location.search.indexOf('?buy-now') > -1 && !$("#productOptions").children().length ) {
if ( location.search.indexOf('?buy-now') > -1 ) {
  $("#buttonAddToCart").click();
}

var guids = [];

$(document).ready(function(){
  var bcFlag = false, bcSep = false;
  var bcPath = $("#breadcrumbs a.bcItem:first").attr('href');
  $("#breadcrumbs").children().each(function() {
    if ( !($(this).hasClass('home') || $(this).hasClass('rightCap')) ) {
      if ( bcFlag ) {
        $(this).remove();
      } else if ( $(this).hasClass('bcItem') ) {
        var path = $(this).attr('href');
        if ( path.indexOf(bcPath) == -1 || !bcSep ) {
          $(this).remove();
          bcFlag = true;
        }
        bcSep = false;
      } else if ( $(this).hasClass('separator') ) {
        bcSep = true;
      }
    }
  });
  $('div#breadcrumbs').append(' <span class="separator"><img src="/breadcrumbs-separator.gif" width="18" height="24" alt=" &rsaquo; " /></span> <span class="last">' + $("#productDetail #productCart h1").text() + '</span>');
  $("#breadcrumbs").show();
  
  if ( !$("#productCart .shortDescription").text() ) {
    $("#productCart .shortDescription").hide();
  }
  
  $("#detailTabs > ul").tabs();
  $("#detailTabs").show();
  
  $(".ui-tabs-nav a")
    .append('<img src="/product-tab-l.png" class="leftCap" width="15" height="30" alt="" />')
    .append('<img src="/product-tab-r.png" class="rightCap" width="15" height="30" alt="" />');

  $("#tabDetails table[border='1'] td").css({
    'margin': '0px auto',
    'padding': '1px'
  });
  
  var sku = $(".sku").text().replace('SKU: ', '');
  var t = 'http://store.aedbrands.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(1)").remove();

  if ( priceJson && $("#productOptions select").length ) {
    // 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.aedbrands.com/"+val+"']").get(0) ) {
        $("img.imageThumbnail:last").after('<img src="http://store.aedbrands.com/'+val+'" width="64" height="64" class="imageThumbnail" alt="" />');
      }
    });
    updateProductOptionJson();
  }
  
  // Handle the image switching here:
  $("#additionalImages img.imageThumbnail").each(function() {
    $(this).click(function() {
      var thisPath = $(this).attr('src');
      $("#productDetailImage").attr('src', thisPath);
    });
  });
  
  // Sets the large image's src to the first thumbnail:
  if ( $("#additionalImages img.imageThumbnail").length ) {
    $("#productDetailImage").attr('src', $("#additionalImages img.imageThumbnail:first").attr('src'));
  }
  
  $("#productDetailImage").click(function() {
    var thisImgUrl = $(this).attr('src');
    window.open(thisImgUrl, 'Images', 'width=620,height=620,menubar=no,scrollbars=no,resizable=yes,status=no,toolbar=no');
    return false;
  });
  
  var price = $("#dynamicProductPrice").text();
  price = price.replace(',', '');
  if ( parseFloat(price) >= 99 ) {
    $("#productCart .freeShipping").show();
  } else if ( parseFloat(price) < 10 ) {
    if ( parseFloat(price) >= 1 ) {
      $("#dynamicProductPrice").text(parseFloat(price).toFixed(2));
    } else {
      var tmp = parseFloat(price).toFixed(2).toString();
      $("#dynamicProductPrice").text(tmp.replace('0.', '.'));
    }
  }
  
  if ( typeof(customFieldData) != 'undefined' ) {
    var html = '';
    if ( customFieldData.Brochure ) {
      html += '<div><a href="/' + customFieldData.Brochure + '"><img src="/brochure-button.gif" width="150" height="23" alt="View Brochure" /></a></div>';
    }
    if ( customFieldData.Video ) {
      html += '<div><a href="#" onclick="javascript:window.open(\'/video-player/?vid=' + customFieldData.Video + '\', \'Video\', \'width=500,height=400,menubar=no,scrollbars=no,resizable=yes,status=no,toolbar=no\'); return false;"><img src="/video-button.gif" width="150" height="23" alt="View Demonstration" /></a></div>';
    }
    if ( html ) {
      $("#storeCustomFields").append(html);
      $("#storeCustomFields").show();
    }
  }

  if ( $(".productReview").length > 1 ) {
    $(".productReview:not(:last)").after('<hr />');
  }
  
  $(".crossSell").each(function() {
    var csprice = $(this).find(".crossSellPrice").text();
    csprice = csprice.replace(',', '');
    if ( parseFloat(csprice) >= 99 ) {
      $(this).find(".freeShipping").css('visibility', 'visible');//show();
    } else if ( parseFloat(csprice) < 10 ) {
      if ( parseFloat(csprice) >= 1 ) {
        $(this).find(".crossSellPrice").text(parseFloat(csprice).toFixed(2));
      } else {
        var tmp = parseFloat(csprice).toFixed(2).toString();
        $(this).find(".crossSellPrice").text(tmp.replace('0.', '.'));
      }
    }
  });

});

if ( priceJson && $("#productOptions select").length ) {
  $("#productOptions select").change(function() {
    updateProductOptionJson();
  });
}

function updateProductOptionJson() {
  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;
      $.each(guiAry, function(i, val) {
        id = $("option[value='" + val + "']").parent().attr('name');
        guids.push( id.replace('optionCount', '') );
      });
    }
  }
  // based on the order of guids, build our hash
  var hash = '';
  $.each(guids, function(i, val) {
    if ( hash ) {
      hash += ',';
    }
    hash += $("select[name='optionCount" + val + "']").val();
  });
  
  if ( priceJson[hash] ) {
    //alert(hash + ': ' + priceJson[hash]);
    var priceVar = priceJson[hash][0];
    var price = parseFloat(priceVar);
    $("#dynamicProductPrice").text(price.toFixed(2));
    $("img.imageThumbnail[src*='"+priceJson[hash][1]+"']").click();
  }
}
