/**
 * => Mootools 1.2
 * 	=> Core
 * @classDescription
 * Classe qui vérifie si le produit est disponible ou épuisé suivant les attributs sélectionnés 
 * @author M@nu/Baphira
 */
var AvailabilityChecker = new Class({
	
	/**
	 * Constructor
	 * @param {String} attributesClass la "class" de(s) la/les liste(s) d'es attributs
	 */
	initialize: function(attributesClass, urlForUpdate, msgArea){
		this.urlForUpdate = urlForUpdate;
		this.msgArea = msgArea;
		this.attributesClass = attributesClass;
		this.attributes = $$('.'+this.attributesClass);
		this.effect = new Fx.Morph(this.msgArea, {
			transition: Fx.Transitions.linear,
			duration: 2000
		});

		this.attributes.each(function(attribute) {
			if(attribute.get('tag') == 'input') {
				// radio buttons
				attribute.getParent().getElements('input').each(function(el){
				// attribute.form.getElements('input[name="'+attribute.getProperty('name')+'"]').each(function(el){ //BUG IE
					el.addEvent('click', function(e) {
						this.check();
					}.bind(this));
				}.bind(this));
			} else {
				// select
				attribute.addEvent('change', function(e) {
					this.check();
				}.bind(this));				
			}
		}.bind(this));

		new Observer($('products_quantity'), function() {
			this.check();
		}.bind(this), {delay: 400});
    },
	
	check: function(){
		var xhr = new Request({
			url: this.urlForUpdate,
			method: 'post',
			onSuccess: function(responseText) {
				try {
					eval('var checkInfo = '+responseText+';');
					if(checkInfo.available != 'unknown') {
						this.msgArea.setStyle('opacity',0);
						this.msgArea.set('html',checkInfo.msg);
						new Fx.Morph (this.msgArea, {
							transition: Fx.Transitions.linear,
							duration: 2000
						}).start({
							opacity: [0,1]
						});
					} else {
						this.msgArea.empty();
					}
				} catch(e) {
					alert(e);
				}
			}.bind(this)
		});
		
		//var queryString = 'product_id='+$('products_id').value; // bug IE (pour liquido) name=products_id présent dans la liste déroulante des produits, ce qui inhibe la valeur du formulaire qui nous interesse...
		var queryString = 'product_id='+$('cart_quantity').products_id.value;
		var attributes = new Helper().getAttributes($('cart_quantity'));
		if($chk(attributes)) {
			for (var i = 0; i < this.attributes.length; i++) {
				queryString += '&idattr['+i+']='+attributes[i].idAttr;
				queryString += '&idattrvalue['+i+']='+attributes[i].idAttrValue;
			}
		}
		queryString += '&product_qty='+($('products_quantity').value.toInt() + shoppingCartUpdater.cart.getProductQty($('products_id').value, attributes));
		xhr.send(queryString);
	}
	
});