/**
 * JS for cart functionality.
 **/
// Handle the Add to Cart submission
$(document).ready(function() { //Begin Wrapper

var names = {
	cartForm: 'form.cart-add-form',
	quantityTarget: '.cart-quantity',
	cartLi: 'li.your_cart',
	cartAddButton: 'span.button input'
};

var forwardTo = false; //Set

//Callback for when animated Add To Cart finishes playing.
//For now, reload the page, till we set up the re-calculation/update this page. 
var buttonDone = function() {
	if(window.location.pathname.indexOf('cart/index') > -1) {
		window.location.reload(true);
	}
	
	if(forwardTo) {
		window.location.assign(forwardTo);
	}
	
};

//Does the Flying BUtton effect...
var buttonEffect = function(el, target) {
	
	var stub = $(el).clone().appendTo(document.body);

	$(stub).css(
		{
			position: 'absolute',
			'top': $(el).offset().top,
			'left': $(el).offset().left
		}
	);

	$(stub).animate(
		{
			top: $(document).scrollTop(),
			left: $(target).offset().left,
			opacity: 0.5
		}, 
		{ complete: buttonDone }
	)
	.fadeOut('fast');
};

var cartHandlers =  {
	
	success: function(result, code, form) {

		$(names.cartLi).css({"background-color": 'yellow'});		
		$(names.cartLi).animate(
				{ backgroundColor: "white"}, 2000
			);


		$(names.quantityTarget).html(result['text']);
		
		forwardTo = result.forwardTo || false;
						
		var but = $(form[0]).find(names.cartAddButton);
		//Change to ADDED image. Using the rollover state as placeholder. 
		$(but).attr('src', 'img/cart/en/buttons/item_added.gif');

		buttonEffect(but, names.cartLi);


	},
	
	error: function() {
		
	},

	//Would use .ajax option of beforeSend, (or even the globals) except for the life of me, 
	//when using the plugin, i cant see how to get the form doing the submitting.
	//the usual handlers have this = document, which is a bit useless. Of course, it could just be my inexperience
	//In any case, beforeSubmit gives me what I want. 
	beforeSubmit: function( formData, jqForm, options) {
		var but = $(jqForm).find(names.cartAddButton);
		$(but).attr('disabled', true);
		
		//Replace image with loading....
		$(but).attr('src', 'img/cart/loader_button.gif');
		return true;
	}

};

//Using target option, so any element with 
//.cart-quantity will get updated with the value.
var options = {
	success: cartHandlers.success,
	beforeSubmit: cartHandlers.beforeSubmit,
	dataType: 'json'
};

$(names.cartForm).ajaxForm(options);

$('div.print').click(function() {
	window.print();
});

});//End Wrapper	
