jQuery(document).ready(function() {
	jQuery('#confirmDeleteBasket').click(function() {
		return confirm('Chcete naozaj zmazať obsah Vášho košíka?');
	});
	jQuery('.addToCart').click(mapAddToCartSubmitButton);
	jQuery('.addToCartFull').click(mapAddToCartSubmitButton);
});

jQuery.fn.wait = function(time, type) {
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
        	jQuery(self).dequeue();
        }, time);
    });
};

function mapAddToCartSubmitButton(e) {
	var element = e.target;
	var productId = 0;
	var amount = 0;		
	jQuery(element).siblings("input").each(function (index, domElement) {
		switch (domElement.name) {
			case "productId":
				productId = this.value;
				break;
			case "amount":				
				amount = this.value;				
				break;
		}			
	});
	addToBasket(productId, amount);
	return false;
}

function addToBasket(p_productId, p_Amount) {
	
	jQuery.post('/ajax/basket/add', { productId: p_productId, amount: p_Amount }, function(data, textStatus) {		
		if (undefined !== data.itemsCount) {
			jQuery("#itemsCount").text(data.itemsCount);
		}
		var basketImage = jQuery("#addToBasketForm_" + p_productId + " input[type='image']");
		if (p_Amount > 0) {
			basketImage.removeClass('addToCart').addClass('addToCartFull');
		} else {
			basketImage.removeClass('addToCartFull').addClass('addToCart');
		}
		
		var id = 'messager'; 
		if (data.error) { id = 'messager_error'; }
		if (data.warning) { id = 'messager_warning'; }
		
		var messager = jQuery('#' + id);
		messager.append("<p>"+ data.message +"</p>").stop(true, true).show().wait(2000).fadeOut(1000, function() {			 
			messager.empty();
		});
	}, "json");	
	
}
