/**
 * @author Abdellah Boutmouzzar abdellah@3wkom.net
 * TODO: 
 */
var abAjaxCart = new Class({
	Implements: Options,
	options: {
		abAddToCartLink: 'abAddToCart',
		abQtySelector: 'qtySelector',
		abAttrForm: 'attrForm',
		abCartHolder: 'cart',
		abQtySlider: '.abQtySlider',
		abAttrSelector: '.attrSelector',
		abTvaAlterer: '.abTvaAlterer',
		abCartDetailsHolder: 'tabpanier',
		abLangId: 1,
		abMode: 'add',
		abNoAjax: true
    },
	initialize: function(options){
		this.setOptions(options);
		this.abAddToCartLink = this.options.abAddToCartLink;
		this.abQtySelector = this.options.abQtySelector;
		this.abAttrForm = this.options.abAttrForm;
		this.abLinkProperties = this.options.abLinkProperties;
		this.abCartHolder = this.options.abCartHolder;
		this.abQtySlider = this.options.abQtySlider;
		this.abAttrSelector = this.options.abAttrSelector;
		this.abTvaAlterer = this.options.abTvaAlterer;
		this.abCartDetailsHolder = this.options.abCartDetailsHolder;
		this.abLangId = this.options.abLangId;
		this.abMode = this.options.abMode;
		this.abNoAjax = this.options.abNoAjax;
		//initialiser la quantité à 1
		this.abQty = 1;
		//initialiser les attributs
		this.abAttrIds = [];
		//on peut vouloir par exemple "highlight"er un sélecteur?
		this.abDelay = 0;

		if (this.abMode == 'alter') {
			this.abHandleAlter();
		}
		else{
			if ($type(document.id(this.abAddToCartLink)) != "element") 
				return;
			
			this.abOriginalLink = document.id(this.abAddToCartLink).get('href');
			this.abOriginalTitle = document.id(this.abAddToCartLink).get('title');
			this.abOriginalRel = document.id(this.abAddToCartLink).get('rel');
			this.abURI = new URI(this.abOriginalLink);
			this.abQueryString = this.abURI.get('query');
			this.abDiscountsLink = '/content.php?lang_id=' + this.abLangId + '&do=discounts&' + this.abQueryString;
			this.abQtyRequired = '/content.php?lang_id=' + this.abLangId + '&do=qty&' + this.abQueryString;
			this.abBadQty = '/content.php?lang_id=' + this.abLangId + '&do=qty&error=badQty&' + this.abQueryString;
			this.abConfirmLink = '/content.php?do=confirm&lang_id=' + this.abLangId + '&' + this.abQueryString;
			this.abAttrRequiredLink = '/content.php?do=attr&lang_id=' + this.abLangId + '&' + this.abQueryString;
			
			//ce flag nous permet de savoir si tout est ok
			this.abLinkIsReady = true;
			//ce flag nous permet de savoir si la quantité est correcte
			this.abQtyIsOk = false;
			//ce flag nous permet de savoir si les attributs sont ok
			this.abAttrIsOk = false;
			
			this.abHandleAdd();
		}
    },
	abHandleAdd: function(){
		document.id(this.abAddToCartLink).addEvents({
			"click": function(e){
				e.stop();
				//si besoin est de vérifier la quantité (présence du sélecteur)
				if (document.id(this.abAddToCartLink).hasClass('hasDiscount') && $type(document.id(this.abQtySelector)) == 'element') {
					this.abCheckQty();
					document.id(this.abQtySelector).addEvent("blur", function(e){
						this.abCheckQty();
					}.bind(this));
				}
				if (document.id(this.abAddToCartLink).hasClass('hasAttr') && $type(document.id(this.abAttrForm)) == 'element') {
					$$($(this.abAttrForm), $$(this.abAttrSelector)).set('tween', {duration: 2000});
					this.abCheckAttr();
				}
	
				//si tout est ok, on effectue un post en ajax sur this.abOriginalLink et on affiche la popup de confirmation
				if(this.abLinkIsReady){
					this.abRequest();
				}
				//on n'est pas encore prêt: afficher l'invite de choix de quantité
				else{
					this.abShow();
				}
			}.bind(this),
			"dblclick": function(e){
				e.stop();
				this.abHandleAdd();
				return false;
			}.bind(this)
		});
	},
	abCheckQty: function(){
		if($type(document.id(this.abQtySelector)) == 'element') {
			var minQty = document.id(this.abQtySelector).alt.split('-')[1].toInt();
			var incrementQty = document.id(this.abQtySelector).className;
			incrementQty = incrementQty.split('-')[1].toInt();
			var isChecked = true;
			document.id('qtySelectorHolder').removeClass('abBadQty');
			//algorithme à améliorer / optimiser un de ces jours ;)
			if(incrementQty >= minQty) {
				this.abQty = document.id(this.abQtySelector).value.toInt();
				if(incrementQty > 1 && (this.abQty % incrementQty) != 0) {
					document.id('qtySelectorHolder').addClass('abBadQty');
					isChecked = false;
				}
			}
			else if (incrementQty < minQty) {
				this.abQty = document.id(this.abQtySelector).value.toInt();
				if(this.abQty < minQty) {
					document.id('qtySelectorHolder').addClass('abBadQty');
					isChecked = false;
				}
			}
			else {
				isChecked = true;
			}
			this.abQty = document.id(this.abQtySelector).value.toInt();
			if(this.abQty >= minQty && isChecked ){
				this.abSetLinkToConfirm();
				//le lien est prêt !!
				this.abLinkIsReady = true;
				this.abQtyIsOk = true;
				//mais il faut vérifier les attributs si nécessaire !!
				if(!this.abAttrIsOk) {
					this.abCheckAttr();
				}
			}
			else{
				if(document.id('qtySelectorHolder').hasClass('abBadQty')) {
					this.abSetLinkToBadQty();
				}
				else if(document.id('qtySelectorHolder').hasClass('abHasDiscount')) {
					this.abSetLinkToDiscounts();
				}
				else {
					this.abSetLinkToQtyRequired();
				}
				//le lien n'est pas prêt !!
				this.abLinkIsReady = false;
			}
		}
	},
	abCheckAttr: function(){
		this.abAttrRequiredLink = this.abAttrRequiredLink.split('&attr')[0];
		var attLabels = [];
		var isValidAttr = true;
		$$(this.abAttrSelector).each(function(el, i) {
			this.abAttrIds[i] = el.getSelected()[0].value;
			if(this.abAttrIds[i] == -1) {
				attLabels[i] = el.get('title');
				isValidAttr = false;
			}
		}.bind(this));
		if(isValidAttr) {
			this.abLinkIsReady = true;
			//mais il faut là aussi vérifier la quantité minimale si nécessaire
			if(!this.abQtyIsOk) {
				this.abCheckQty();
			}
		}
		else {
			this.abDelay = 2000;
			$$($(this.abAttrForm), $$(this.abAttrSelector)).highlight('#ff0000');
			this.abLinkIsReady = false;
			attLabels.each(function(v, k) {
				this.abAttrRequiredLink += '&attr[' + k + ']=' + v;
			}.bind(this));
			this.abSetLinkToAttrRequired();
		}
	},
	abRequest: function(){
		var appendedQS = '';
		//si une option a été choisie
		$each($$('.abAttributes'), function(attr, i){
			var current = attr.getSelected()[0];
			if($type(current) == 'element' && current.value > 0) {
				appendedQS += '&attr_id[]=' + current.value;
			}
		});

		//si on veut aller directement dans le panier, sans afficher la popup
		if(this.abNoAjax) {
			window.location.href = this.abOriginalLink + '&abQty=' + this.abQty + appendedQS;
		}
		else {
			new Request.HTML({
				url: this.abOriginalLink,
				data: 'from=abAjax&abQty=' + this.abQty + appendedQS,
				update: document.id(this.abCartHolder),
				useSpinner: true,
				spinnerOptions: {
					width: '200px',
					height: '32px'
				},
				spinnerTarget: this.abAddToCartLink,
				onSuccess: function(){
					(function(){document.id(this.abCartHolder).highlight('#ff0000');}.bind(this)).delay(1000);
					this.abSetLinkToConfirm();
					this.abShow();
				}.bind(this),
				onRequest: function(){
				}.bind(this)
			}).send();
		}
	},
	abSetLinkToConfirm: function(){
		document.id(this.abAddToCartLink).set('href', this.abConfirmLink).set('title', this.abOriginalTitle).set('rel', this.abOriginalRel);
	},
	abSetLinkToDiscounts: function(){
		document.id(this.abAddToCartLink).set('href', this.abDiscountsLink).set('title', 'Discounts').set('rel', 'width:500,height:380');
	},
	abSetLinkToQtyRequired: function(){
		document.id(this.abAddToCartLink).set('href', this.abQtyRequired).set('title', 'Qté minimale requise').set('rel', this.abOriginalRel);
	},
	abSetLinkToAttrRequired: function(){
		var abUri = new URI();
		var abHost = abUri.get('host');
		document.id(this.abAddToCartLink).set('href', this.abAttrRequiredLink).set('title', abHost).set('rel', this.abOriginalRel);
	},
	abSetLinkToBadQty: function(){
		document.id(this.abAddToCartLink).set('href', this.abBadQty).set('title', 'Qté non valide').set('rel', this.abOriginalRel);
	},
	abSetLinkBack: function(){
		document.id(this.abAddToCartLink).set('href', this.abOriginalLink).set('title', this.abOriginalTitle).set('rel', this.abOriginalRel);
	},
	abShow: function(){
		abBox.content.erase(document.id(this.abAddToCartLink));
		abBox.content.push(document.id(this.abAddToCartLink));
		(function() {
			abBox.open(document.id(this.abAddToCartLink));
			if(this.abLinkIsReady) {
				this.abSetLinkBack();
				this.abDelay = 0;
			}
		}.bind(this)).delay(this.abDelay);
	},
	abHandleAlter: function(){
		if ($type(document.id(this.abCartDetailsHolder)) != "element" || $$(this.abQtySlider).length <= 0) 
			return;
	
		$$(this.abQtySlider).each(function(slider, i){
			var tipText = slider.get('title').split('-');
			this.abTips = new Tips(slider, {title: function(){return tipText[0];}, text: function(){return tipText[1];}});
			slider.addEvent('click', function(e){
				e.stop();
				new Request.HTML({
					url: slider.get('href'),
					data: 'from=abAjax',
					update: document.id(this.abCartDetailsHolder),
					useSpinner: true,
					spinnerOptions: {
						width: '12px',
						height: '12px'
					},
					spinnerTarget: slider,
					onSuccess: function(){
						if($type($('table')) == 'element') $('table').highlight('#663300');
						$$('.tip-wrap').dispose();
						if($$('.disabled').length > 0) {
							$each($$('.disabled'), function(dis) {
								new Tips(dis, {title: function(){return dis.get('title').split('-')[0];}, text: function(){return dis.get('title').split('-')[1];}});
							});
							//new Tips($$('.disabled'), {title: function(){return $$('.disabled')[0].get('title').split('-')[0];}, text: function(){return $$('.disabled')[0].get('title').split('-')[1];}});
						}
						//this.abHandleAlter();
					}.bind(this),
					onRequest: function(){
						
					}.bind(this)
				}).send();
				new Request.HTML({
					url: slider.get('rev'),
					data: 'from=abAjax',
					update: document.id(this.abCartHolder),
					useSpinner: true,
					spinnerOptions: {
						width: '12px',
						height: '12px'
					},
					spinnerTarget: slider,
					onSuccess: function(){
						document.id(this.abCartHolder).highlight('#663300');
						this.abHandleAlter();
					}.bind(this),
					onRequest: function(){
					}.bind(this)
				}).send();
			}.bind(this));
		}.bind(this));			
	
		//radio du choix de type particulier / entreperise en france / europe
		if($$(this.abTvaAlterer).length > 0){
			$$(this.abTvaAlterer).each(function(el, i){
				el.addEvent('click', function(e){
					e.stop();
					new Request.HTML({
						url: '/add-panier.php?do=' + el.get('id'),
						data: 'from=abAjax',
						update: document.id(this.abCartDetailsHolder),
						useSpinner: true,
						spinnerOptions: {
							width: '12px',
							height: '12px'
						},
						spinnerTarget: el,
						onSuccess: function(){
							document.id(this.abCartDetailsHolder).highlight('#663300');
							this.abHandleAlter();
						}.bind(this),
						onRequest: function(){
						}.bind(this)
					}).send();
				}.bind(this));
			}.bind(this));			
		}
	},
	abAlterRequest: function(){
	},
	abCountRequest: function(){
	}
});

	/*
	window.addEvent("domready", function(){
		var abLinkProperties = new Hash();
		var abRequest = new Request.HTML({
			url: 'add-panier.php',
			onSuccess: function(html){
				$('cart').set('html', '');
				$('cart').adopt(html);
			}
		});
		if($type($("abAddToCart")) == "element") {
			if($("abAddToCart").hasClass('hasDiscount') && $type($('qtySelector')) == 'element') {
				abLinkProperties.set('originalLink', $("abAddToCart").get('href'));
				var queryString = abLinkProperties.get('originalLink').split('?')[1];
				abLinkProperties.set('newLink', '<?php echo $url_lang;?>content.php?lang_id=<?php echo $lang_id;?>&do=discounts&' + queryString);
				abLinkProperties.set('originalTitle', $("abAddToCart").get('title'));
				abLinkProperties.set('originalRel', $("abAddToCart").get('rel'));
				$("abAddToCart").addEvent("click", function(e){
					e.stop();
					checkQty('qtySelector', 'abAddToCart', abLinkProperties);
					abBox.content.push($('abAddToCart'));
					abBox.open($('abAddToCart'));
				});
				$("qtySelector").addEvent("change", function(e){
					checkQty('qtySelector', 'abAddToCart', abLinkProperties);
				});
			}
		}
	});
	*/

