var PeriodicUpdatesManager = function(options) {
	this.options = {
		eventsManager: null,
		updateInterval: 600000, // 5 mins default
		eoUpdateCallback: null // this callback function will be executed for each event occurrence that has an actual update
	};
	( typeof(options) == 'object' ) && $.extend(this.options, options);
	if ( typeof(this.options.eventsManager) != "object" || !(this.options.eventsManager instanceof EventsManager) ) this.options.eventsManager = new EventsManager();
	
	this.eoIDList = [];
	this.timer = null;
	this._lastUpdateRequest = Math.round((new Date()) / 1000);
};
$.extend(PeriodicUpdatesManager.prototype, {
	_getActualUpdates: function() {
		var new_since = Math.round((new Date()) / 1000),
			that = this;
		this.options.eventsManager.getActualUpdates(this.eoIDList, this._lastUpdateRequest, function(data) {
			var eoIndex = 0;
			$.each(data, function(i, d) {
				eoIndex = $.inArray(i, that.eoIDList);
				
				if ( "function" == typeof(that.options.eoUpdateCallback) ) {
					data[i].id = i;
					if ( null == data[i].unit ) data[i].unit = '';
					if ( null == data[i].verdict ) data[i].verdict = '';
					that.options.eoUpdateCallback(data[i]);
				}
			});
		});
		that._lastUpdateRequest = new_since;
	},
	
	start: function() {
		if ( null == this.timer ) {
			var that = this;
			this.timer = setInterval(function() {
				that._getActualUpdates();
			}, this.options.updateInterval);
		}
	},
	stop: function() {
		this.timer != null && clearTimeout(this.timer);
		this.timer = null;
	},
	reset: function() {
		this.eoIDList = [];
		this.timer != null && clearTimeout(this.timer);
		this.timer = null;
	},
	
	setEoUpdateCallback: function(callback) {
		this.options.eoUpdateCallback = callback;
	},
	
	/**
	 * @param eo_ids Array of event occurrence IDs to be checked for actual updates. 
	 */
	addEventOccurrences: function(eo_ids) {
		$.merge(this.eoIDList, eo_ids);
	},
	
	/**
	 * @param eo_ids Array of event occurrence IDs to be removed from the queue. 
	 */
	removeEventOccurrences: function(eo_ids) {
		var l = eo_ids.length, eoIndex = 0;
		for ( var i = 0; i < l; i++ ) {
			eoIndex = $.inArray(eo_ids[i]);
			if ( typeof(this.eoIDList[eoIndex]) != "undefined" )
				delete this.eoIDList[eoIndex];
		}
	}
});

