ijs = {};

ijs.worker = {

	'actions': {},
	'worker_interval_id': 0,
	'actions_length': 0,
	'worker_step': 0,
	'debug': false,
	'debug_odd': 0,

	'add_debug': function(){


		this.debug_odd = 0;
		this.debug = document.createElement('div');
		this.debug.setAttribute('style', 'position:absolute;top:0px;left:0px;background:#FFF;border:5px solid #555;color:#666;padding:20px;font-size:16px;font-family:\'Lucida Console\'');
		this.debug.innerHTML = 'Worker started.';
		document.body.appendChild(this.debug);
		
		
	},

	'add': function(id, callback, context, odd){

		if(!this.actions[id])
			++this.actions_length;

		this.actions[id] = {
			'callback': callback,
			'context': context ? context : this,
			'id': id,
			'odd': odd ? odd : 1
		};



		if(!this.worker_interval_id){
			this.worker_step = 0;
			this.worker_interval_id = setInterval(function(){ 
				ijs.worker.work();
			} , 10);
		}

	},

	'work': function(){

		if(this.debug){
			switch(this.debug_odd){
				case 1: this.debug.innerHTML = '/';break;
				case 2: this.debug.innerHTML = '|';break;
				case 3: this.debug.innerHTML = '\\';this.debug_odd = -1;break;
				default: this.debug.innerHTML = '-';break;
			}
			this.debug.innerHTML += ' ' + this.actions_length +' ' + this.worker_step;
			++this.debug_odd;
		}

		if(!this.actions_length){
			clearInterval(this.worker_interval_id);
			this.worker_interval_id = null;
		}
		else{
			var action;
			for(var id in this.actions){
				action = this.actions[id];
				if(action && this.worker_step % action.odd == 0){
					if(action.callback.call(action.context) !== true){
						this.actions[id] = false;
						--this.actions_length;
					}
				}
			}
			++this.worker_step;
		}
	}
}
 