/**
 * => Mootools 1.2
 * 	=> Core
 * @classDescription
 * Classe représentant le panier (page panier) du client
 * @author M@nu/Baphira
 */
var ShoppingCart = new Class({
	
	EMPTY_CLASS: 'cartEmptyContinue', // classe de l'élément qui sera affiché si le produit est vide

	/**
	 * @param {String} classProduct (ex: cartProduct)
	 * @param {String} urlForUpdate
	 * @param {ShoppingCartBox} cartBox
	 */
	initialize: function(classProduct, urlForUpdate, cartBox, STOCK_ALLOW_CHECKOUT) {
		this.classProduct = classProduct;
		this.products = $$('.'+classProduct);
		this.updater = new ShoppingCartUpdater(urlForUpdate);
		this.cartBox = cartBox;
		this.formEl = $('cart_quantity');
		this.checkOutBtn = $('ajaxcartCheckOutBtn');
		this.stockWarningEl = $('ajaxcartStockWarning');
		this.STOCK_ALLOW_CHECKOUT = STOCK_ALLOW_CHECKOUT;
		
		if($chk(this.formEl.getElement('.formBt'))) {
			this.formEl.getElement('.formBt').destroy();
		}
		this.products.each(function(el) {
			el.btnDelete = el.getElement('.cartDelete');
			el.idProduct = el.btnDelete.getElement('input').setStyle('display', 'none').get('value');
			el.productName = el.getElement('.cartName');
			el.stockIndicator = el.productName.getElement('.stockIndicator');
			el.inputQty = el.getElement('.cartQty').getElement('input');
			el.lastQtyValue = el.inputQty.get('value');
			el.productPrice = el.getElement('.cartPrice span');
			this.addEvents(el);
		}.bind(this));
		
		this.manageStockAlertEvent();
    },
	
	addEvents: function(el) {
		el.btnDelete.addEvent('click', function(e) {
			this.deleteProduct(el);
		}.bind(this));
		new Observer(el.inputQty, function() {
			var qty = el.inputQty.get('value').toInt();
			if(isNaN(qty) || qty <= 0) {
				el.inputQty.set('value', el.lastQtyValue);
			} else {
				el.inputQty.set('value', qty); // ex: 3a => 3
				el.lastQtyValue = qty;
				this.updateProductQty(el, qty);
			}
		}.bind(this), {delay: 400});
	},
	
	manageStockAlertEvent: function() {
		var anyOutOfStock = false;
		this.products.each(function(el) {
			if(this.isOutOfStock(el)) {
				anyOutOfStock = true;
			}
		}.bind(this));
		if($chk(this.checkOutBtn)) {
			this.checkOutBtn.removeEvents('click');
		}
		if(anyOutOfStock) {
			this.stockWarningEl.setStyle('display','block');
			if(!this.STOCK_ALLOW_CHECKOUT) {
				this.checkOutBtn.addEvent('click', function(e) {
					alert(this.stockWarningEl.get('text'));
					new Event(e).stop();
				}.bind(this));
			}
		} else if($chk(this.stockWarningEl)) {
			this.stockWarningEl.setStyle('display','none');
		}
	},
	
	isOutOfStock: function(el) {
		return $chk(el.stockIndicator) && el.stockIndicator.get('text').trim().length > 0;
	},
	
	deleteProduct: function(el) {
		this.updater.update(this.getRealProductId(el.idProduct), 0, 0, 0, new Helper().getAttributesById(el.idProduct), function(productInfos) {
			if($chk($('ajaxcartSubTotal'))) {
				var subTotalEl = $('ajaxcartSubTotal').getElement('.cartSubTotalValue');
				subTotalEl.set('html', productInfos.total);
			}
			if(productInfos.qty == 0) {
				this.deleteProductLine(el);
				if($chk(this.cartBox)) {
					this.cartBox.updateCart(productInfos);				
				}
			}
		}.bind(this));
	},

	deleteProductLine: function(el) {
		try {
			el.destroy();
			if ($$('.' + this.classProduct).length <= 0) {
				$$('.' + this.EMPTY_CLASS)[0].replaces($('cart_quantity')).set('styles', {
					'display': 'block'
				});
			}
			this.manageStockAlertEvent();
		} catch(e) {
			//Silence is golden.
		}
	},
	
	updateProductQty: function(el, qty) {
		var longueur = '';
		var largeur = '';
		if(el.getElement('.option2147483647')) {
			longueur = el.getElement('.option2147483647').get('text').toInt();
		}
		if(el.getElement('.option2147483646')) {
			largeur = el.getElement('.option2147483646').get('text').toInt();
		}
		this.updater.update(this.getRealProductId(el.idProduct), qty, longueur, largeur, new Helper().getAttributesById(el.idProduct), function(productInfos) {
			if(productInfos.qty_min_error == '1') {
				el.inputQty.value = productInfos.qty;
			} else {
				var subTotalEl = $('ajaxcartSubTotal').getElement('.cartSubTotalValue');
				subTotalEl.set('html', productInfos.total);
				el.productPrice.set('html', productInfos.productSum);
				if(productInfos.qty_min_error == '2') {
					this.deleteProductLine(el);
				} else if($chk(el.stockIndicator)) {
					// contrôle du stock
					if(productInfos.outOfStock.trim().length > 0) {
						el.stockIndicator.set('html', productInfos.outOfStock);
					} else {
						this.stockWarningEl.setStyle('display','none');
						el.stockIndicator.empty();
					}
					this.manageStockAlertEvent();
				}
				if($chk(this.cartBox)) {
					this.cartBox.updateCart(productInfos);
				}
			}
		}.bind(this));
	},
	
	getRealProductId: function(fullId) {
		return fullId.split('{')[0];
	}
	
});
