/**
 * => Mootools 1.2
 * 	=> Core
 * @classDescription
 * Permet de modifier le panier du client en AJAX.
 * @author M@nu/Baphira
 */
var ShoppingCartUpdater = new Class({

	updateLock: false,

	/**
	 * Constructor
	 * @param {String} urlForUpdate
	 * @param {ShoppingCartBox} cart
	 */
	initialize: function(urlForUpdate, cart){
		this.urlForUpdate = urlForUpdate;
		this.cart = cart;
    },
	
	/**
	 * Mets à jour le panier en passant par le serveur en AJAX
	 * @param {String} idProduct
	 * @param {int} qty
	 * @param {Object} attributes
	 * 	[{
	 * 		idAttr: '1', idAttrValue: '11'
	 * 	}, {
	 * 		idAttr: '2', idAttrValue: '22'
	 * 	}]
	 * @param {Object} showConfirmCoordinates el.getCoordinates();
	 * 	Si les coordonnées ne sont pas mentionnées il n'y aura pas de panneau de confirmation après la mise à jour du panier
	 */
	updateCartBox: function(idProduct, qty, attributes, showConfirmCoordinates) {
		if(this.updateLock) {
			return;
		}
		
		this.update(idProduct, qty, attributes, function(productInfo) {
			if($chk(productInfo.needsAttributes)){
				//La mise à jour du panier ne s'est pas effectuée car il manquait les attributs.
				//on redirige alors vers la fiche produit
				document.location.href = productInfo.needsAttributes;
			} else {
				this.cart.updateCart(productInfo);
				if($chk(showConfirmCoordinates)) {
					this.showConfirmUpdate(showConfirmCoordinates);
				}
			}
		}.bind(this));
	},
	
	update: function(idProduct, qty, attributes, onComplete) {
	
		var xhr = new Request({
			url: this.urlForUpdate,
			method: 'post',
			onSuccess: function(responseText) {
				try {
					eval('var productInfo = '+responseText+';');
					onComplete.run([productInfo]);
				} catch(e) {
					alert(e);
				}
			}.bind(this)
		});
		
		var queryString = 'product_id='+idProduct+'&product_qty='+qty;
		if($chk(attributes)) {
			for (var i = 0; i < attributes.length; i++) {
				queryString += '&idattr['+i+']='+attributes[i].idAttr;
				queryString += '&idattrvalue['+i+']='+attributes[i].idAttrValue;
			}
		}
		xhr.send(queryString);

	},
	
	showConfirmUpdate: function(showConfirmCoordinates) {
		var panel = $('shoppingCartUpdatedPanel');
		if ($chk(panel)) {
			this.lock(true);
			
			panel.inject(document.body);
			panel.set('styles', {
					'position': 'absolute',
					'display': 'block'
				})
				.set('styles', showConfirmCoordinates);
			
			var updater = this;
			$('continueShopping').addEvent('click', function() {
				updater.lock(false);
				panel.removeProperty('style').set('styles', {'display': 'none'});
				this.removeEvent('click');
			});
		}
	},
	
	lock: function(locked) {
		this.updateLock = locked;
	}
	
});