/*
 * @project talenthouse
 * @package th.cron
 * @since   22.07.2009
 *
 */
th.cron = {

	active_jobs: [],
	
	
	/**
	 * @method add
	 * 
	 * Executes a function, '_func',  each '_interval' milliseconds
	 * until it has executed '_limitExec' times. 
	 * 
	 * @param	_func		The function to execute 
	 * 
	 * @param	_interval	Time in milliseconds between executions
	 * 
	 * @param	_key		Unique identifier for this cron job; used to remove jobs, if desired
	 * 
	 * @param	_limitExec	Execute only this many times; empty or -1 for infinite execution
	 * 
	 * @param	_execNow	Whether to run the function immediately; or only after the first interval 
	 * 						has expired; default false;
	 * 
	 */
 	add: function( _func, _interval, _key, _limitExec, _execNow ) {
		
		try
		{
			if ( typeof _key == 'undefined' ) {
				c = String((new Date()).getTime()).replace(/\D/gi,'');
			}
			if ( typeof _limitExec == 'undefined' ) {
				_limitExec = -1;
			}

			if ( typeof _func != 'function' ) {
				th.log('ERROR: th.cron.start: _func parameter is not a function!');
				return false;
			}
			
			var func = _func;
			var interval = _interval;
			var key = _key;
			var limitExec = _limitExec;
			var execNow = _execNow;
		
			if ( typeof execNow != 'undefined' && execNow === true ) {
				func();
				limitExec = limitExec - 1;
			}
			
			var timerId = setTimeout(function() {
								func();

								limitExec = limitExec - 1;
								if ( limitExec !== 0 ) { 
									th.cron.add( func, interval, key, limitExec );
								}
							} , interval );
						
			th.cron.active_jobs[key] = timerId;
		
			return true;
		} catch (e) {
			th.log('ERROR: th.cron.start: Caught exception: ' + e);
		}
	},
	
	remove: function( _key ) {
		var key = _key;
		
		if ( typeof th.cron.active_jobs[key] != 'undefined' ) {
	   		clearTimeout( th.cron.active_jobs[i].timerid );
	   		delete th.cron.active_jobs[key];
	   		return true;
		};
		
		th.log('ERROR: th.cron.stop: Key Not Found!');
		return false;
	}
	
};
