$(function(){
  // Pre-load CSS hover images
  new Image().src = '/images/common/cart.arrow.png';
  new Image().src = '/images/common/cart.loader.gif';
  
  // Clicking the "Add to Cart" button should render a jQuery UI transfer effect 
  $('input.add_to_cart').click(function(){
    // Button ID is prefixed with "add_to_cart_", so skip that to obtain slug
    var slug = $(this).attr('id').substr(12);
    $('img[alt="' + slug + '"]').effect('transfer', { to: $('a.cart-droppable:first') }, 1000);
  });
  
  // Allow product images to be dragged and dropped into the shopping cart
  $('img.cart-draggable').each(function(){
    var height = $(this).height(), width = $(this).width();
    
    var qtip_text = 'Drag this to your cart to purchase';
    
    if ($(this).parent('a').length) {
      qtip_text += ' or click to view more information';
    }
    
    $(this)
      .draggable({
        containment: 'window',
        cursor: 'move',
        cursorAt: { top: height / 4, left: width / 4 },
        helper: function(){ return $(this).clone().height(height / 2).width(width / 2); },
        opacity: 0.8,
        revert: 'invalid', 
        scope: 'products',
        zIndex: 5
      })
      .bind('dragstart', function(){ $('#cart-arrow').show(); })
      .bind('dragstop', function(){ $('#cart-arrow').hide(); })
      .hover(
        function(){ $('#cart-arrow').show(); },
        function(){ if (!$('img.ui-draggable-dragging').length) { $('#cart-arrow').hide(); } }
      )
      .qtip({
        content: { text: qtip_text },
        position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
        show: { delay: 0, when: 'mouseover' },
        hide: { delay: 0, when: 'mouseout' },
        style: { border: { radius: 3, width: 1 }, name: 'dark', textAlign: 'center', tip: 'bottomMiddle' } 
      });
  });
  
  $('a.cart-droppable').droppable({
    drop: function(e, ui) {
      var slug = $(ui.helper).attr('alt');
      $('#add_to_cart_' + slug).closest('form').submit();
    },
    hoverClass: 'cart-droppable-hover',
    scope: 'products',
    tolerance: 'touch'
  });
});
