/*global ut */

ut.calendar = {};


/**
 * Constructor.
 * 
 * Calendar context.
 * 
 * @param params
 */
ut.calendar.Context = function(params) {
    /**
     * Aggregator of navigators
     */
    this._navigators = [];
    
    this._current_query = {};
    
    this._queryReadyCallbacks = [];
    
    this._notifyQueryReady = true;
};


ut.calendar.Context.prototype.addNavigator = function(sel) {
    this._navigators.push(sel); // FIXME does this work in IE?
};


/**
 * Gets notified about a change in one of the navigators.
 * 
 * The event object contans the following properties:
 *  target: object of the navigator that emitted the event
 * 
 * @param event
 * @return boolean, true if handled, false if not
 */
ut.calendar.Context.prototype.onChange = function(event) {
    var query = {};
    query = this.filterQuery(query);
    
    this.notifyQueryReady(query);
    
    return true;
};

ut.calendar.Context.prototype.invalidate = function(event) {
	this.onChange({});
};

ut.calendar.Context.prototype.notifyQueryReady = function(query) {
	if(!this._notifyQueryReady){
		return;
	}
	var self = this;
    
    this._queryReadyCallbacks.forEach(function(callback){
        callback.call(self, query);
    });
};


ut.calendar.Context.prototype.onQueryReady = function(callback) {
    this._queryReadyCallbacks.push(callback);
};


/**
 * Sends the query object to all the registered navigators so they can update
 * it with their current state.
 * 
 * Returns the changed query object.
 * Might return another query object, depending on the implementation.
 * 
 * @param query not guarantied not to change
 * @return query
 */
ut.calendar.Context.prototype.filterQuery = function(query) {
    var navigators = this._navigators;
    for (var i=0, len=navigators.length; i < len; i++){
        query = navigators[i].filterQuery(query);
    }
    return query;
};

/**
 * Sets state from params
 */
ut.calendar.Context.prototype.setStateByQuery = function(query) {
	this._notifyQueryReady = false;
	var navigators = this._navigators;
    for (var i=0, len=navigators.length; i < len; i++){
        navigators[i].setStateByQuery(query);
    }
    this._notifyQueryReady = true;
    
    this.notifyQueryReady(query);
};


