/*
 * 	 
 *		Repère touts les éléments avec la class add_sel et rajoute un lien juste après l'élément
 *		Les éléments avec la class add_sel doivent contenir une class productId=id
 *		fire addToSelReady quand le dom et AddToSel sont ready 
 * 
 */

var  AddToSel =  new Class(
		{
			_url : '',
			_selector : '.add_sel',
			_text : window.langs['SEL_ADD'],
			_ok : window.langs['SEL_OK'],
			_ko : window.langs['SEL_ERROR'], 
			_nan : window.langs['BAD_QTE'], 
			_jroot : 'jroot',
			_updater : null,

			addActionLink : function(){
			_jroot = $(this._jroot)? $(this._jroot).value : "";
			$$(this._selector).each(function(link){
				var regex = /product_id=([0-9]*)/;
				var match = regex.exec(link.className);
				if(!match)
					return;


				var addSel = new Element('a',{'class':'ajouter',title:this._text});
				addSel.set('text',this._text);

				addSel.productId = match[1];
				var position = 'after';

				regex = /position=(.*)/;
				match = regex.exec(link.className);
				if(match)
					position = match[1];

				this.addEventOnActionLink(addSel);
				addSel.inject(link,position);
			}.bind(this));

		},//addActionLink

		_updateQte: function(productId,qte,addMode,succes,idSel){

			if(undefined == addMode)
				addMode = true;
			if(isNaN(qte) ||(qte < 1 && addMode ) ){
				alert(this._nan)
				return;
			}

			var addToSelRequest = new Request({method: 'post', 
				url: _jroot+'index3.php?page=selection.add&option=com_virtuemart',
				onSuccess: function(t){
				$('mod_vm_selection_qte').set('html',t.trim());
				if(addMode)
					alert(this._ok); 
			 
				if(succes)
					succes();
			}.bind(this),
			onFailure:  function(){
				alert(this._ko);
			}.bind(this),
			noCache :true
			});

			addToSelRequest.send('product_id='+productId+"&quantity="+qte+"&addMode="+ addMode+(idSel ? "&id="+idSel:""));
		},//_updateQte

		updateQte: function(productId,qte,succes,idSel){
	
			if(this._updater) $clear( this._updater); 
		this._updater =  this._updateQte.delay(600,this,[productId,qte,false,succes,idSel]);
		},//updateQte

		addEventOnActionLink : function(link,qte,event){
			event = event || 'click';
			link.addEvent(event,function(e){
				e.stop();
				var qteValue = 1
				if(qte)
					qteValue = parseInt(qte.value);
				this._updateQte(link.productId,qteValue,true);

			}.bindWithEvent(this));
		}//addEventOnActionLink

		});
window.addEvent('domready', function() {

	var addToSel = new AddToSel();
	window.addToSel = addToSel;
	addToSel.addActionLink();
	window.fireEvent('addToSelReady');
});

