/*
 * (c) Copyright 2001-2009 Hellriser Customs. All Rights Reserved. 
 */
 
var addthis_pub="pciccone";
var addthis_options = 'email, facebook, twitter, digg, myspace, stumbleupon, delicious, google, linkedin';
var addthis_brand = "Hellriser Customs";
var addthis_hover_delay = 450;
var addthis_email = 'ddkdkdkd@fjfjfjf.com';

var descExpanded = false;
var mouseX;
var mouseY;

function matchColorWithSize( colors, sizes ) {
  var index = -1;
  for (var i=0; i < colors.length; i++) {
    var pn = colors[i].part_no;
    for (var l=0; l < sizes.length; l++) {
      if ( sizes[l].part_no == colors[i].part_no ) {
        return(i);
      }
    };
  };
  // In case of non-uniform sets we don't find a match and here is how we signal that event
  return(index);
}

function matchSizeWithColor( sizes, colors ) {
  var index = -1;
  for (var i=0; i < sizes.length; i++) {
    var pn = sizes[i].part_no;
    for (var l=0; l < colors.length; l++) {
      if ( colors[l].part_no == sizes[i].part_no ) {
        return(i);
      }
    };
  };
  // In case of non-uniform sets we don't find a match and here is how we signal that event
  return(index);
}


function flyoverMessage( str ) {
  $("#addToCartNotice").html(str).css({ left: mouseX, top: mouseY+10 }).fadeIn("fast");
  setTimeout(function() {
    $('#addToCartNotice').fadeOut('slow');
  },5000 );
}

function addToWishlist( memberid, bikeModel, itemNo, partNo ) {
  var url = "/garage_to_wishlist.php?memberid=" + memberid + "&prod_group=" + bikeModel + "&item_no=" + itemNo + "&part_no=" + partNo;
  $.get($url,function() {
    flyoverMessage("Product added to your wish list");
  })
}

var disabledClassName = 'opt_disabled';

function filterOptions (partNos, target) {
  var l = partNos.length;
  var options = target.find("option[class!='first_opt']");

  // Array used to keep track of which option elements pass the test
  var flags = new Array();
  for (var i=0; i < options.length; i++) {
    flags[i] = false;
  };
  
  // Scan the part numbers form the main element that triggers this function
  for (var i=0; i < l; i++) {
    var partNo = partNos[i].part_no;
    // Scan the target elements that need to be enabled/disabled
    for (var i2=0; i2 < options.length; i2++) {
      // If we alreaqdy found a match in a previous iteration then there is no
      // need to test this element again. Next!
      if (flags[i2]) {
        continue;
      }
      var found = false;
      // Get the Target Data converted from the JSON string. This is an object with
      // itemNo information and an incldued array of part numbers for that given fitment
      var tgData = JSON.parse(options[i2].value);  // A little optimization, access the DOM element directly 
      var tgPartNos = tgData.part_nos;
      // Scan the part numbers and if one of them is matchine the current part number then
      // the target is enabled.
      for (var i3=0; i3 < tgPartNos.length; i3++) {
        if (tgPartNos[i3].part_no == partNo) {
          found = true;
          break;
        }
      };
      flags[i2] = found;
    };
  };
  for (var i=0; i < options.length; i++) {
    if (flags[i]) {
      $(options[i]).removeAttr('disabled').removeClass(disabledClassName);
    }
    else {
      $(options[i]).attr('disabled',true).addClass(disabledClassName);
    }
  };
}

// ==========
// = jQuery =
// ==========

$(document).ready(function() {
  // Refresh the cart summary
  $.get("/cartservices.php?action=summary", function(data) {
    $("#newCartSummary").html(data);
  })

  // Save the given record as a JSON string, in the "rel" attribute and HTML-escaped 
  var saveMetadata = function( rec, id ) {
    var str = JSON.stringify(rec).replace('""','&quot;');
    $( id ).attr('rel',str);
  }

  $(".prodDescExpanded").expander({
    slicePoint: 400,
    expandEffect: 'fadeIn',
    expandSpeed: 1500,
    expandText: '<br><span>Click here for more</span>',
    userCollapseText: '<span>Click to reduce</span>'
  });

  // if the "item" HTTP var is selected cause a scroll to the named link with the same name of the value contained in the variable
  var searchItem = $("#searchItem").val();
  var targetOffset;
  if (searchItem != '0') {
    targetOffset = $("#item_" + searchItem).offset().top;
    $('html,body').animate({scrollTop: targetOffset}, 1000);    
  }

  checkIE6();

  // Logging
  url = Base64.encode(document.referrer);
  $.get('/log_visits/index/' + url + "/" + screen.width + "/" + screen.height );

  var highlightColor = "#9EC9E3";  // Color used to highlight the price changes 
  var lastPrice = 0;
  // Event handler for the selection of colors. The has_size field determines if there is also
  // a linked "size" property. If this is the case then both combo boxes have to have a selected
  // value before we can determin which part # is selected
  $('.selColors').change(function() {
    var theSelect = $(this);   // save the pointer to the select control
    var prodInfo = JSON.parse($(this).val());      // retrieve the serialized object containing all the information about the product
    var fieldId = $(this).attr('id');
    var itemNo = fieldId.match(/^colors_(.+)/)[1]; // find our current item_no
    // Both color and size must be selected
    if (prodInfo.has_size) {
      var sizeId = "#sizes_" + itemNo;
      // Retrieve the object
      var size = JSON.parse($(sizeId).val());

      if (prodInfo.item_no == '') {
        $(sizeId).find('option').removeAttr('disabled').removeClass(disabledClassName);
        return;
      }
      
      filterOptions(prodInfo.part_nos,$(sizeId));
            
      if (size.item_no == '') {
        $("#price_" + itemNo).html('Pick a size');
        return;
      }
      else {
        var prodIndex = matchColorWithSize(prodInfo.part_nos, size.part_nos)
        var partNo = prodInfo.part_nos[prodIndex];
        var desc = $("#sizes_" + itemNo + " > :selected").html() + ' ' + theSelect.children(":selected").html();
        desc = desc.replace('"','&quot;');
        $("#listPrice_" + itemNo).html('$' + partNo.list_price);
        var priceDiv = $("#price_" + itemNo);
        priceDiv.text('$' + partNo.price);
        if ( lastPrice != partNo.price ) {
          lastPrice = partNo.price;
          priceDiv.animate({ backgroundColor: highlightColor },1200).animate({ backgroundColor: '#000'},800);
        };
        // Enable the Buy/Wishlist buttons
        saveMetadata({ 
             bikeModel: prodInfo.bikeModel,
             brandCode: prodInfo.brand,
             itemNo: prodInfo.item_no,
             partNo: partNo.part_no,
             description: desc
        }, "#buy_" + itemNo );
        // Show availability
        $("#avail_" + itemNo).html(partNo.avail);
      }
    }
    // only the color is needed
    else{
      var partNo = prodInfo.part_nos[0]; // There is only one record so we grab element 0        
      $("#listPrice_" + itemNo).text('$' + partNo.list_price);
      var priceDiv = $("#price_" + itemNo);
      priceDiv.text('$' + partNo.price);
      priceDiv.animate({ backgroundColor: highlightColor },1200).animate({ backgroundColor: '#000'},800);
      var desc = theSelect.children(":selected").html();
      desc = desc.replace('"','&quot;');                  
      saveMetadata({ 
           bikeModel: prodInfo.bikeModel,
           brandCode: prodInfo.brand,
           itemNo: prodInfo.item_no,
           partNo: partNo.part_no,
           description: desc
      }, "#buy_" + itemNo );
      // Show availability
      $("#avail_" + itemNo).html(partNo.avail);
    }
  });

  // Event handler for the selection of sizes. The has_color field determines if there is also
  // a linked "color" property. If this is the case then both combo boxes have to have a selected
  // value before we can determin which part # is selected
  $('.selSizes').change(function() {
    var theSelect = $(this);   // save the pointer to the select control
    var prodInfo = JSON.parse($(this).val());
    var fieldId = $(this).attr('id');
    var itemNo = fieldId.match(/^sizes_(.+)/)[1];   // find our current item_no
    // Both size and color must be selected
    if (prodInfo.has_color) {
      var colorId = "#colors_" + itemNo;
      // Retrieve the object
      color = JSON.parse($(colorId).val());
      
      if (prodInfo.item_no == '') {
        $(colorId).find('option').removeAttr('disabled').removeClass(disabledClassName);
        return;
      }
      filterOptions(prodInfo.part_nos,$(colorId));
      
      if (color.item_no == '') {
        $("#price_" + itemNo).html('Pick a color');
        return;
      }
      else {
        if (color == null) {
          alert("Combination of color and size not available!");
          return;
        }
        var prodIndex = matchSizeWithColor(prodInfo.part_nos, color.part_nos);
        if (prodIndex == -1) {
          alert('This is not a valid combination of color and size');
          return;
        }
        var partNo = prodInfo.part_nos[prodIndex];
        var desc = theSelect.children(":selected").html() + ' ' + $("#colors_" + itemNo + " > :selected").html();
        desc = desc.replace('"','&quot;');          
        $("#listPrice_" + itemNo).html('$' + partNo.list_price);
        var priceDiv = $("#price_" + itemNo);
        priceDiv.text('$' + partNo.price);
        if ( lastPrice != partNo.price ) {
          lastPrice = partNo.price;          
        }
        priceDiv.animate({ backgroundColor: highlightColor },1200).animate({ backgroundColor: '#000' },800);
        saveMetadata({ 
             bikeModel: prodInfo.bikeModel,
             brandCode: prodInfo.brand,
             itemNo: prodInfo.item_no,
             partNo: partNo.part_no,
             description: desc
        }, "#buy_" + itemNo );
       // Show availability
       $("#avail_" + itemNo).html(partNo.avail);                                   
      }
    }
    else{
      var partNo = prodInfo.part_nos[0]; // There is only one record so we grab element 0
      $("#listPrice_" + itemNo).text('$' + partNo.list_price);
      var priceDiv = $("#price_" + itemNo);
      priceDiv.text('$' + partNo.price);
      priceDiv.animate({ backgroundColor: highlightColor },1200).animate({ backgroundColor: '#000'},800);
      var desc = theSelect.children(":selected").html();
      desc = desc.replace('"','&quot;');          
      saveMetadata({ 
           bikeModel: prodInfo.bikeModel,
           brandCode: prodInfo.brand,
           itemNo: prodInfo.item_no,
           partNo: partNo.part_no,
           description: desc
      }, "#buy_" + itemNo );
      // Show availability
      $("#avail_" + itemNo).html(partNo.avail);
    }
  });
    
  /* Keep track of the mouse coors so that we can display the notification 
   * messages where the user's eyes are
  */
  $("body").mousemove(function(event) {
    mouseX = event.pageX;
    mouseY = event.pageY;
  });


  $(".btnBuy").click(function(ev) {
    ev.preventDefault();
    var params = JSON.parse($(this).attr('rel'));
    if (params.prompt != undefined) {
      alert(params.prompt);
    }
    else {
      itemNo = String(params.itemNo).replace(/\+/,'%2B');
      partNo = String(params.partNo).replace(/\+/,'%2B');
      $("#addToCartNotice").html("Adding the product to the cart...").css({ left: mouseX, top: mouseY+10 }).fadeIn("fast");
      $.get("/cartservices.php?action=addItem&qty=1&brand=" + params.brandCode + "&bikeType=" + params.bikeModel + "&itemNo=" + itemNo + "&partNo=" + partNo,
            function( event ) { 
              partNo = partNo.replace(/%2B/,'+'); 
              $("#addToCartNotice").html("Part # " + partNo + ' "' + params.description + '" has been added to your cart').css({ left: mouseX, top: mouseY+10 }).fadeIn("fast");
              setTimeout(function() {
                  $('#addToCartNotice').fadeOut('slow');
                },5000 );

              $.get("/cartservices.php?action=summary", function(data) {
                  $("#selectorCartSummary").html(data);
              });
            });
    }
  });
  
  $(".btnWL").click(function(ev){
    ev.preventDefault();
    var params = JSON.parse($(this).attr('href'));
    if (params.url != undefined) {
      window.location = params.url;
      return;
    }
    var url = "/garage_to_wishlist.php?prod_group=" + params.bikeModel + "&item_no=" + params.itemNo + "&part_no=" + params.partNo;
    $.get(url,function() {
      flyoverMessage("Product added to your wish list");
    })    
  });
  
  // Tooltips
  var hiConfig = {
    sensitivity:  1,
    interval:     80,
    timeout:      50    
  };
  
  $(".singleTip").cluetip( {
       arrows: true,
       leftOffset: 10,
       dropShadow: false,
//       sticky: true,
       onShow: function( elem ) {
         var w = $("#tooltipImage").width();
         if (w != undefined) {
           $("#cluetip").css("width", w+20);
         }
         return true; 
       },
      hoverIntent: hiConfig
  });
  $(".multiTip").cluetip( {
       arrows: true,
       leftOffset: 10,
       dropShadow: false,
       sticky: true,
       mouseOutClose: true,
       closePosition: 'title',
       onShow: function( elem ) {
         var w = $("#hrcGallery").width();
         if (w != undefined) {
           $("#cluetip").css("width", w+20);
         }
         $("#hrcGallery").cycle( { 
           fx: 'fade',
           delay: 250,
           pause: true,
           pager: "#ssPager",
           // callback fn that creates a thumbnail to use as pager anchor 
           pagerAnchorBuilder: function(idx, slide) {
             var img = $(slide).children('img')[0];
              return '<li><a href="#"><img src="' + img.src + '"  height="50" /></a></li>'; 
           }           
         });
         return true; 
       }
  });

  $("div.wrenches").cluetip({
    local: true, 
    cursor: 'pointer',
    arrows: true
  });

  $(".btnWL").cluetip({
    cursor: 'pointer',
    arrows: false,
    local: true,
    showTitle: false,
    positionBy: 'mouse',
    leftOffset: 15
  });


  $("div.reviewStars").cluetip({
    cursor: 'pointer',
    arrows: true,
    sticky: true,
    height: 650,
    width: 600,
    dropShadow: false,
    mouseOutClose: true,
    attribute: 'rel',
    closePosition: 'title',
    // the ajaxProcess callback is necessary to override clueTip  default
    // behavior of escaping embedded CSS and JavaScript in the loaded page.
    ajaxProcess: function(data) { return data; }
  });

  $(".info").cluetip({
    cursor: 'pointer',
    arrows: true,
    splitTitle: "|",
    hoverIntent: hiConfig,
    dropShadow: true  
  });
  
  
  // Workaround for brain-dead IE 6 unable of using transparend PNGs
  if ( $.browser.msie && ($.browser.version.substr(0,1) <= "6") ) {
    $(".reviewStars").css("background-image", "url(/images/ui/icons/star.gif)");
  }

  $("a.overlay").overlay(function() {              
    // grab wrapper element inside content 
    var wrap = this.getContent().find("div.wrap");
    var trigger = this.getTrigger();
    if (trigger.hasClass('iframe')) {
      wrap.html('<iframe src="' + trigger.attr("href") + '" allowtransparency="true" frameborder=0></iframe>');        
    }
    else {
      wrap.load(trigger.attr("href"));
    }
  });   

  // Workaround for Safari nor setting the hidden atrtribute of the overlay panel background image
  $("img[src$='gray.png']").hide();
  
}); // jQuery
