var ShoppingCart = Class.create({
	currentTimer: null,
	
	// OJO: los cálculos tienen que hacerse igual en JavaScript que en PHP. Los cálculos
	// en PHP se realizan en la clase pb_ecommerce_ShoppingCart
	// 	'shoppingCartItemAmount_' + itemId: cantidad
	// 	'shoppingCartItemPrize_' + itemId: precio unitario. (solo lectura)
	// 	'shoppingCartItemDiscount_' + itemId: descuento. (solo lectura)
	// 	'shoppingCartItemTaxes_' + itemId: impuestos aplicables a ese artículo. (solo lectura)
	// 	'shoppingCartItemTotal_' + itemId + '_text': total que hay que calcular
	//
	updateShoppingCartThumbnail: function() {
		// TODO: Cuando se añada el icono de la cesta de la compra, esta función debe
		// actualizar el número de elementos que contiene.
	},

	autoUpdate:function(forceDelete) {
		if( this.currentTimer ) {
			clearTimeout(this.currentTimer);
		}
		if( forceDelete ) {
			this.currentTimer = setTimeout('shoppingCart.updateTotals(true)',1000);
		}
		else {
			this.currentTimer = setTimeout('shoppingCart.updateTotals()',1000);
		}
	},

	showUpdateButton: function() {
		var button = $('shoppingCartUpdateTotalsButton');
		if( button ) {
			this.markTextAsOutOfDate();
			Effect.Appear('shoppingCartUpdateTotalsButton',{duration:0.5});
		}
	},
	
	markTextAsOutOfDate: function() {
		$('shoppingCartTotalsSubtotal').setStyle({color:'red'});
		$('shoppingCartTotalsTaxes').setStyle({color:'red'});
		$('shoppingCartTotalsTotal').setStyle({color:'red'});
	},
	
	hideUpdateButton: function() {
		var button = $('shoppingCartUpdateTotalsButton');
		if( button ) {
			Effect.Fade('shoppingCartUpdateTotalsButton',{duration:0.5});
		}
	},

	updateItemTotals:function(itemId) {
		var amountField = $('shoppingCartItemAmount_'+itemId);
		var prizeField = $('shoppingCartItemPrize_'+itemId);
		var discountField = $('shoppingCartItemDiscount_'+itemId);
		var taxesField = $('shoppingCartItemTaxes_'+itemId);
		var totalField = $('shoppingCartItemTotal_'+itemId+'_text');
		this.markTextAsOutOfDate();
		
		if( amountField && prizeField && discountField && taxesField && totalField ) {
			var amount = amountField.value;
			var total = amount * prizeField.value;
			totalField.innerHTML = total - (discountField.value * total)/100;
			this.autoUpdate();
		}
	},

	incrementAmount:function(itemId) {
		var text = $('shoppingCartItemAmount_' + itemId);
		if( text ) {
			text.value = Number(text.value) + 1;
			this.updateItemTotals(itemId);
		}
	},

	decrementAmount:function(itemId) {
		var text = $('shoppingCartItemAmount_' + itemId);
		if( text && text.value>1 ) {
			text.value = Number(text.value) - 1;
			this.updateItemTotals(itemId);
		}
	},
	
	removeItem:function(itemId) {
		var item = $('shoppingCartItem_' + itemId);
		if( item ) {
			item.remove();
			this.autoUpdate(true);
		}
	},
	
	updateTotals:function(forceDelete) {
		var form = $('shoppingCartForm');
		if( form ) {
			var force = 'false';
			if( forceDelete ) {
				force = 'true';
			}
			var parameters = form.serialize(true);
			parameters.command = 'updateTotals';
			parameters.style = system.getCurrentStyle();
			parameters.force = force;
			new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
				method:'post',
				parameters:parameters,
				onSuccess:function(transport) {
					shoppingCart.insertShoppingCart('shoppingCartContainer');
				}
			});
		}
	},

	addItemToCart: function(description,prize,taxes,discount) {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
			method:'post',
			parameters:{command:'addItem',style:system.getCurrentStyle(),description:description,prize:prize,taxes:taxes,discount:discount},
			onSuccess: function(transport) {
				shoppingCart.updateShoppingCartThumbnail();
			}
		});
	},
	
	buyItem: function(description,prize,taxes,discount,shoppingCartPageId) {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
			method:'post',
			parameters:{command:'addItem',style:system.getCurrentStyle(),description:description,prize:prize,taxes:taxes,discount:discount},
			onSuccess: function(transport) {
				shoppingCart.updateShoppingCartThumbnail();
				system.getPageManager().configureAjax(system.getLibraryPath() + 'plasticbriqFramework/actions/_page_renderer.php','pageContainer');
				contextManager.setVariable('pageId',shoppingCartPageId);
				contextManager.updateHash();
				system.getPageManager().openPageFromDatabase(shoppingCartPageId);
			}
		});
	},
	
	goToShop: function(shopPageId) {
		system.getPageManager().configureAjax(system.getLibraryPath() + 'plasticbriqFramework/actions/_page_renderer.php','pageContainer');
		contextManager.setVariable('pageId',shopPageId);
		contextManager.updateHash();
		system.getPageManager().openPageFromDatabase(shopPageId);
	},

	// Función de depuración
	addItem: function(shoppingCartContainerId) {
		var reload = false;

		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
			method:'post',
			parameters:{command:'addItemDebug',style:system.getCurrentStyle()},
			onSuccess:function(transport) {
				if( transport.responseText=='OK' ) {
					system.getMessageManager().hideMessage();
					// Recarga del carrito de la compra
					shoppingCart.insertShoppingCart(shoppingCartContainerId);
				}
				else {
					system.getMessageManager().showMessage(transport.responseText,{color:'red'});
				}
			}
		});
	},

	insertShoppingCart: function(containerId) {
		var container = $(containerId);
		if( container ) {
			var discountCouponContainer = $('shoppingCartDiscountCupponsContainer');
			var allowCoupons = 'false';
			if( discountCouponContainer ) {
				allowCoupons = 'true'
			}
			new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
				method:'post',
				parameters:{command:'insertShoppingCart',style:system.getCurrentStyle(),allowCoupons:allowCoupons},
				onSuccess:function(transport) {
					container.innerHTML = transport.responseText;
					system.evalAllScripts(containerId);
					shoppingCart.hideUpdateButton();
				}
			});
		}
	},
	
	validateDiscountCuppon: function() {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
			method:'post',
			parameters:{command:'validateDiscountCuppon',style:system.getCurrentStyle(),password:$('newCupponCode').value},
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					$('shoppingCartDiscountCupponMessage').hide();
					shoppingCart.updateTotals();
				}
				else {
					$('shoppingCartDiscountCupponMessage').innerHTML = transport.responseText;
					$('shoppingCartDiscountCupponMessage').setStyle({color:'red'});
				}
			}
		});
	},
	
	removeDiscountCuppon: function(couponId) {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_shopping_cart_actions.php',{
			method:'post',
			parameters:{command:'removeCoupon',style:system.getCurrentStyle(),couponId:couponId},
			onSuccess:function(transport){
				if(transport.responseText=='OK'){
					$('shoppingCartDiscountCupponMessage').hide();
					$('shoppingCartDiscountCouponItem_' + couponId).remove();
					shoppingCart.autoUpdate();
				}
				else{
					$('shoppingCartDiscountCupponMessage').innerHTML = transport.responseText;
					$('shoppingCartDiscountCupponMessage').setStyle({color:'red'});
				}
			}
		});
		shoppingCart.updateTotals();
	}
});

var shoppingCart = new ShoppingCart();
