(function($) {

	$.extend({
	  add2cart: function(source_id, target_id, callback) {

      var source = $('#' + source_id );
      var target = $('#' + target_id );
      var display_image = $('#' + source_id).attr('src');
      var shadow = $('#' + source_id + '_shadow');
 
      if( !shadow.attr('id') ) {
          $('body').prepend('<img id="'+source.attr('id')+'_shadow" style="display: none; background-color: #ddd; border: solid 1px darkgray; position: static; top: 0px; z-index: 100000;" src="'+display_image+'" alt="" />');
          var shadow = $('#'+source.attr('id')+'_shadow');
      }
      
      if( shadow == undefined ) {
          alert('Cannot create the shadow div');
      }
      
      shadow
      	.width(source.css('width'))
      	.height(source.css('height'))
      	.css('top', source.offset().top)
      	.css('left', source.offset().left)
      	.css('opacity', 0.75).show()
      	.css('position', 'absolute');
      
      //shadow.animate( { width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: 300 } )
      //  .animate( { opacity: 0 }, { duration: 100, complete: callback } );
        
        shadow.animate(
                { width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left },
                300,
                'linear'
            ).animate(
                { opacity: 0 },
                100,
                function(){
                    shadow.hide();
                }
            ).animate(
                { opacity: 0 },
                { duration: 0, complete: callback }
            );
        
		}
	});
})(jQuery);


$(document).ready(function(){
	
	$('.ajaxadd form').each(function() {
	
		$(this).submit(function() {
			// create fly-to-cart animation
			$.add2cart( $(this).find('img').attr("id"), 'module_cart' );

			// get quantity or min_qty
			var qty = $(this).find('input[name=quantity]').val();
			var minqty = $(this).find('input[name=min_qty]').val();
			if (qty == undefined) { qty = 1; }
			if (minqty == undefined) { minqty = 1; }
			if (qty < minqty) {
				qty = minqty;
			}
			
			// get selected options
			var options = []; 
			$(this).find('select :selected').each(function(i, selected){
				options[i] = $(selected).val();
			});
			
			// get current product id
			var pid = $(this).find('input[name=product_id]').val();
			
			// AjaxCallback with the product id, quantity, and options
			$('#module_cart').load('?controller=cart&action=addAjax&product_id='+pid+'&quantity='+qty+'&options='+options);
			
			return false;
		});
	});
});
