(function (){
    jQuery.fn.extend({
        apply: function (){
            var application = arguments[0] || function (){};
            application.apply(this);
            return this;
        }
    })
})()

$(document).ready(function() {
	$(".product .image a").fancybox({
		'zoomSpeedIn':	300, 
		'zoomSpeedOut':	300, 
		'overlayShow':	false
	});
	
	$("#header").localScroll({
		'duration': 200
	});
	
	$("#header #links a").click(function () {
		$("#header #links li").removeClass("active");
		$("#header #links a").removeClass("active");
		$(this).addClass("active");
		$(this).parent().addClass("active");
	});
	
	$(".product .info .add").click(addProduct);
});

function addProduct()
{	
	if($("#cart .cartProduct").length == 0)
	{
		if(!$("#checkout").length)
		{
			var checkout = $('<div id="checkout"><div class="checkout"><p>Checkout &raquo;</p></div><div class="empty"><p>Empty Cart</p></div></div>')
			.hide()
			.css({
				'right' : 50,
				'bottom' : 100,
				'z-index' : 2
			});
			
			$(document.body).prepend(checkout);
			$(".checkout").click(function()
			{
				window.location = "/checkout/shipping.php";
			});
			
			$(".empty").click(function()
			{
		      	$(".cartProduct .X").each(function()
		      	{
		      		$(this).apply(removeProduct);
		      	});
			
			});
		}
		
		$("#checkout").animate({
			height : 'show'
		}, {
			'complete' : function()
			{
				$("#checkout .checkout p").pulse({
					backgroundColors: ['#333', '#000'],
					speed: 500
				});
			}
		}); 
	}
	
	var prodPrice = $(".info .quantity select", $(this).parent().parent().parent()).val();
	if(!$('#id' + prodPrice).length)
	{
		var div = $("<div>")
			.css({ 
				'display' : 'inline-block',
				'float' : 'left'
			})
			.addClass('cartProduct')
			.hide();
			
		$("#cartProducts").prepend(div)

		div.animate({width:'show'}, function()
		{
			if($("#cartProducts .cartProduct").length == 5)
			{
				$("#cart").animate({'opacity' : $("#cart").css('opacity')}, 1000).animate({'height' : $("#cart").height() + 70});
			}
		});
		
		var theOffsetTop = div.offset().top;
		var theOffsetLeft = div.offset().left;
		
	} else
	{
		var theOffsetTop = $('#id' + prodPrice).offset().top;
		var theOffsetLeft = $('#id' + prodPrice).offset().left;
	}
		
	
	var prodLocY = $(".image img", $(this).parent().parent().parent()).offset().top;
	var prodLocX = $(".image img", $(this).parent().parent().parent()).offset().left;
	
	var pOverlay = $("<div>")
	.css({
		'width' : $(this).parent().parent().parent().width(),
		'height' : $(this).parent().parent().parent().height(),
		'background' : 'white',
		'opacity' : '.85',
		'filter' : 'alpha(opacity=85)',
		'position' : 'absolute'
	})
	.addClass('blocker' + prodPrice)
	.addClass('blocker')
	.hide()
	.html('<p>Remove Item From Cart to Reactivate</p>');
	
	$(this).parent().parent().parent().prepend(pOverlay);
	
	pOverlay.animate({opacity : 'show'});
	
						
	var scroll = $(window).scrollTop();
	
	var clone = $(".image img", $(this).parent().parent().parent()).clone();
	
	clone.prependTo($(".image", $(this).parent().parent().parent()))
	.css({
		'position' : 'absolute',
		'z-index'  : '3'
	})
	.animate({
		marginTop: theOffsetTop-prodLocY+5,
		marginLeft: theOffsetLeft-prodLocX+5,
		width: 100,
		opacity: .8
      }, 1000, function(){
      
      	
      	// on complete
      	$.post('/req/cart/add.php', 'p=' + prodPrice, function(data)
      	{
      		// refresh cart data
      		cartData(data);
      		
      		// protect from leaks
      		clone.remove();
      		
      		// update the total
      		updateTotal();
      		
      		$(".cartProduct .X").click(removeProduct, 'html');
      	});
	});
}

function updateCartShipping()
{
	$.post('/req/cart/add.php?noqty=1', 'p=update', function(data)
	{
		cartData(data);
		
	    $(".cartProduct .X").click(removeProduct, 'html');
	});

}

function rebuildCart()
{
	$.post('/req/cart/rebuild.php', 'p=1', function(data)
	{
	
		var d = eval(data);
		for(var i in d)
		{
			if(d[i]['id'] !== null)
			{
				$("#qty_" + d[i]['id']).val(d[i]['qtyid']);
				$(".info .add", $(".product" + d[i]['id'])).apply(addProduct);
			}
		}
		
	    $(".cartProduct .X").click(removeProduct, 'html');
	    
	});

}

function removeProduct()
{
	if($("#cart .cartProduct").length == 1)
	{
		$("#checkout").animate({height : 'hide'});
	}
	
		var overlay = $("<div>");
		overlay.css({
			'border-radius' : '5px',
			'-moz-border-radius' : '5px',
			'padding' : '20px',
			'position' : 'fixed',
			'top' : ($(window).height()/2) - 20,
			'left' : ($(window).width()/2) - 70,
			'color' : 'white',
			'opacity' : .8,
			'background' : 'black',
			'z-index' : 99
		})
		.html('Removing From Cart').hide();
		
		$('body').prepend(overlay);
		
    var q = $("input[name=qtyPrice]",$(this).parent()).val();

		overlay.animate({opacity : 'show'}, 500, function()
		{
		$.post('/req/cart/remove.php', 'p=' + q, function(data)
      	{
      		overlay.animate({opacity : 'hide'}, function()
      		{
      			overlay.remove();
      			updateTotal();
      			
      		});
      			
      	}, 'html');
		});
		
		// fly the product out
		var flyTo = $(".product .prod"+$("input[name=product]",$(this).parent()).val()).offset();
		var flyToTop = flyTo.top;
		var flyToLeft = flyTo.left;
		
		$(".product .blocker"+$("input[name=qtyPrice]",$(this).parent()).val()).animate({
			height : 'hide'
		},
		{
			'duration' : 'slow',
			'complete' : function()
			{
				$(this).remove();
		}
	});
	
	// fly the image back to its "spot"
		$("img", $(this).parent())
		.css({
			'z-index' : 0,
			'position' : 'absolute'
		})
		.animate({
			'marginTop' : -$(this).offset().top+flyToTop-8,
			'marginLeft' : -$(this).offset().left+flyToLeft+133,
			'width': '250px'
		}, 1000);
	
	// "collapse" the cart product
		$(this).parent()
		.animate({
			width : 'hide',
			marginLeft: '-20px',
			opacity: 0
		},
		{
			'duration' : 1000,
			'complete' : function()
			{
				$(this).remove();
			}
		});

		// fade the title
		$(".qty", $(this).parent()).remove();
		  	
		// fade the "x" button			
		$(".X", $(this).parent()).remove();
		
	}
		

function cartData(data)
{
	$("#cart .opener").hide();
	$("#cart #cartProducts").html(data);
}

function updateTotal()
{
	$.post('/req/cart/add.php', function(data)
  	{
  		$("#total p").html(data);	
  	}, 'html');
 }