(function($) {
  var karmaloopTvHost = 'www.karmaloop.com';
  var klickableCartID = 'klickableCartContainer';
  /******************************************************************************
                            KLICKABLE VIDEO CALLBACK
  ******************************************************************************/
  window['KlickableTV_GetProductDetails'] = function(productID) {
    // test if the product has already been fetched
    if(!KlickableTV_GetProductDetails.p)
      KlickableTV_GetProductDetails.p = {};
    if(KlickableTV_GetProductDetails.p[productID])
      return false;
    KlickableTV_GetProductDetails.p[productID] = true;
    // fetch the items details
    $.getJSON('http://' + karmaloopTvHost + '/JSON/KlickableTV.aspx?p=' + 
              productID + 
              '&r=' + Math.random() + 
              '&jsoncallback=?',
              function(data) {
                if(!data.success) {
                  KlickableTV_CallbackFailure(data);
                  return false;
                }
                KlickableTV_CallbackSuccess(data, productID);            
              });
  }// end KlickableTV_GetProductDetails(productID)
  /******************************************************************************
                            KLICKABLE FAILURE CALLBACK
  ******************************************************************************/
  function KlickableTV_CallbackFailure(data) {

  }// end KlickableTV_CallbackFailure(data)
  /******************************************************************************
                            KLICKABLE SUCCESS CALLBACK
  ******************************************************************************/
  function KlickableTV_CallbackSuccess(data, productID) {	
      var topMargin             = 0;
      var cartItemContainer     = $('<div id="'                     + 
                                    klickableCartID                 + 
                                    '" style="margin-top:'          + 
                                    topMargin                       + 
                                    'px;'                           + 
                                    'max-height:442px;overflow-y:auto;' + 
                                    'overflow-x:hidden;width:198px"/>');
      var addToCartButton       = $('<img '                             + 
                                    'src="http://' + karmaloopTvHost + '/' + 
                                    'images/products/button-addtocart'  + 
                                    '.gif" alt="Add To Cart" style='    + 
                                    '"cursor:pointer;"/>').
                                  click(AddToCartClick);
      var addToCartContainer     = $('<div style="margin-top:20px;text-align:right;"/>').
                                     append(addToCartButton);
      var rightColumnReplacement = $('<div/>').
                                        append(cartItemContainer).
                                        append(addToCartContainer);
      $('#klickable_holder').
        replaceWith(rightColumnReplacement);

    // build the cart
    var cartContainer = $('#' + klickableCartID);
    var entry         = $('#KlickableCartTemplate').
                            clone().
                            removeAttr('id').
                            show().
                            hover(
                              ListItemMouseOverCallback,
                              ListItemMouseOutCallback).
                            data('productID', productID);
    var rmeoveButton  = entry.find('.kl-remove-button').
                          click(RemoveFromList).
                          data('entry',entry);
    var img           = entry.find('.kl-nail');
    img.attr({src:data.thumbUrl,alt:data.title});
    entry.find('.kl-title').text(data.title);
    entry.find('.kl-brand').text('By ' + data.brand)
    entry.find('.kl-price').text('$'   + data.price);
    var sizes = entry.find('.kl-sizes');
    // item may be out of stock
    if(data.sizes && data.sizes.length) {
      $.each(
        data.sizes,
        function(index, value) {
          var option  = $('<option/>').val(value.skuid);
          option.text(value.size);
          sizes.append(option);
        });
    }
    // show out of stock if there are no more skus
    else {
      sizes.parent().css('text-align', 'left');
      sizes.replaceWith('Out of stock');
      entry.find('.kl-qty-price-container').hide();
    }
    cartContainer.prepend(entry);
  }// end KlickableTV_CallbackSuccess(data)
  /******************************************************************************
                                ADD TO CART CALLBACK
  ******************************************************************************/
  function AddToCartClick() {
    var qtyMap = {};
    $('#' + klickableCartID + ' .kl-cart-item:visible').
      each(
        function() {
          var cartItem = $(this);
          var qty      = parseInt(cartItem.find('input.kl-qty').val());
          if(isNaN(qty) || 1>qty)
            return;
          var sku = parseInt(cartItem.find('.kl-sizes').val());
          if(isNaN(sku) || 1>sku)
            return;
          qtyMap[sku] = qty;
        });
    var form = $('<form method="post" action="https://' + karmaloopTvHost + '/scripts/AddToCart.aspx"/>').hide();
    $.each(
      qtyMap,
      function(key,value) {
        var input = $('<input type="hidden"/>').
                      attr({'name' : key,
                            'value': value});
        form.append(input);        
      });    
    form.append($('<input type="hidden" name="f"  value="klickable" />')).
         append($('<input type="hidden" name="fd" value="' + 
                  location.pathname.replace(/^\//, '')     + 
                  location.search                          + 
                  '" />'));
    $('body').append(form);
    // track the add to cart click
    /*
    if(window.Karmaloop && Karmaloop.track)
      Karmaloop.track('/clickthrough/klickable/AddToCart');
    */
    form.submit();
  }// end AddToCartClick()
  /******************************************************************************
                                REMOVE FROM LIST CALLBACK
  ******************************************************************************/
  function RemoveFromList() {
    var entry = $(this).data('entry');
    delete KlickableTV_GetProductDetails.p[entry.data('productID')];
    entry.fadeOut();
  }// end RemoveFromList()
  /******************************************************************************
                              LIST ITEM MOUSE OVER CALLBACK
  ******************************************************************************/
  function ListItemMouseOverCallback() {
    $(this).find('.kl-remove-button').fadeIn();
  }// end ListItemMouseOverCallback()
  /******************************************************************************
                              LIST ITEM MOUSE OUT CALLBACK
  ******************************************************************************/
  function ListItemMouseOutCallback() {
    $(this).find('.kl-remove-button').fadeOut();
  }// end ListItemMouseOutCallback()
})(jQuery);
