var mzSyncronize = new Class({

	options: {
		autoStart:true,
		timeOut:true,
		timeOutTime:60000,
		bar:false,
		loaderbarClass:"loaderbar",
		onStart: Class.empty,
		onComplete: Class.empty,
		onAllComplete: Class.empty,
		onCheck: Class.empty,
		onCancel: Class.empty,
		onTimeout: Class.empty
	}, 

	initialize: function(actions, options) {

		this.setOptions(options);
		this.actions = actions;
		if(this.options.autoStart) this.start();
	},
	
	start: function(action) {
		
		if(action){
		
			this.fireEvent('onStart',action);
	
		}else{

			if (this.aniTimer) window.clearTimeout(this.aniTimer);
			this.actionsleft = this.actions;
			this.actiontotal = this.getTimesleft();
			if(this.options.bar) {
				this.options.bar.getElement("div[class="+this.options.loaderbarClass+"]").setStyle("width",0);
				this.options.bar.setStyle("display","block");
			}
			$each(this.actionsleft, function(value, key){
	    			this.start(key);
			}.bind(this));
			this.aniTimer = window.setTimeout(this.timeOut.bind(this), this.options.timeOutTime)		
			
		}
	},
	
	end: function(action) {

		if(action){
		
			this.fireEvent('onComplete',action);
			if(this.getTimesleft()==0) this.end();
	
		}else{

			if (this.aniTimer) window.clearTimeout(this.aniTimer);
			if(this.options.bar) this.options.bar.setStyle("display","none");
			this.fireEvent('onAllComplete');	

		}
	},

	check: function(action) {
	
		(this.actionsleft[action]<=0) ? this.actionsleft[action]=0 : this.actionsleft[action]--;
		//if(this.options.bar) this.options.bar.getElement("div[class="+this.options.loaderbarClass+"]").setHTML(this.getTimesleft());
		
		if(this.options.bar) this.options.bar.getElement("div[class="+this.options.loaderbarClass+"]").setStyle("width",Math.floor((this.options.bar.getStyle("width").toInt()/this.actiontotal)*(this.actiontotal-this.getTimesleft())));
		this.fireEvent('onCheck',action);	
		if(this.actionsleft[action]==0) this.end(action);
	
	},

	cancel: function(action) {

		if(action){
		
			this.actionsleft[action]=0
			this.fireEvent('onCancel',action);
			if(this.getTimesleft()==0 && this.aniTimer) window.clearTimeout(this.aniTimer);
	
		}else{

			$each(this.actionsleft, function(value, key){
    				this.actionsleft[key]=0;
			}.bind(this));

			if (this.aniTimer) window.clearTimeout(this.aniTimer);
			if(this.options.bar) this.options.bar.setStyle("display","none");

			this.fireEvent('onCancel');
		}

	},
	
	timeOut: function() {
		
		if (this.aniTimer) window.clearTimeout(this.aniTimer);
		this.cancel();

	},

	getTimesleft: function() {
	
		var timesleft=0;
		
		$each(this.actionsleft, function(value, key){
    			timesleft+=value;
		});
		
		return timesleft;

	}
});

mzSyncronize.implement(new Events, new Options);

