// Ajax class for Varnish

var BlocksAjaxClass = Class.create({
	
	  initialize: function() {
	    this.blocks = new Array();
	    this.ajaxUrl = CURRENT_BASE_URL+'ajaxifier/call/index/';
	  },
	  // Methode pour ajouter un block Ajax
	  addBlock: function(name,success_dest, error_dest,oncomplete,param) {
	    if(this.getBlockDetailsByName(name) == null) {
	    	var blockArray = new Array();
	    	
	    	//console.log('show ajax loader(s) ?');
	    	this.showLoaders();
	    	
		    blockArray['success_dest'] = success_dest;
		    blockArray['error_dest'] = error_dest;
		    blockArray['name'] = name;
		    blockArray['onComplete'] = oncomplete;
		    
		    if(Object.isUndefined(param) == false)
		    	blockArray['param'] = param;
		    else
		    	blockArray['param'] = 0;
		    this.blocks[this.blocks.length] =  blockArray;
	    } else {
	    	//console.log("le block suivant est déjà initialisé :"+ name);
	  	}
	  },
	  
	  getParameters: function (){
		var params = "no_cache&";
		this.blocks.each(function(item){ params = params + item['name'] +"="+item['param']+ "&";});

		return params;
	  },
	  
	  launchRequest : function(){
		  if(this.blocks.length)
		  {
		    new Ajax.Request(this.ajaxUrl,
			{ method: 'get',
			  parameters :  this.getParameters() ,
			  onSuccess : function(resp)
				{
		    	
					var resp = resp.responseJSON;
					for( var blockname in resp)
					{
						var respblock = resp[blockname];
						var blockdetails = BlocksAjax.getBlockDetailsByName(blockname);
						if(blockdetails != null) {
							if( Object.isUndefined(respblock.error) == false){
								$(blockdetails['error_dest']).update(respblock.error);
							}
					
							if( Object.isUndefined(respblock.success) == false) { 
								$(blockdetails['success_dest']).update(respblock.success);
							}	
						}
					}
				},
				onComplete: function()
				{
					BlocksAjax.blocks.each(
						function(item){
							if(item['onComplete'].empty() == false )
								window[item['onComplete']]();
						});
					BlocksAjax.blocks = new Array();
				},
				onFailure: function() {
					//console.log('Erreur lors de l\'appel ajax.');
				}
			});
		  }
	  },
	  getBlockDetailsByName: function(name){
		  var result = null;
		  this.blocks.each(function(item){ 
			  	if(item['name'] == name) 
			  		result = item;
			  	});
		  return result;
	  },
	  showLoaders : function(){
		  var html = '<img src="/skin/frontend/default/complicce/images/ajax_loader_transparent.gif" />';
		  this.blocks.each(function(item){
			  var blockdetails = BlocksAjax.getBlockDetailsByName(item['name']);
			  $(blockdetails['success_dest']).update(html);
		  });
	  }
});

//Initialisation de l'objet à utiliser pour initialiser l'url Ajax et ajouter des blocks Ajax
var BlocksAjax = new BlocksAjaxClass;

