/**
##############################################################################################
#
#		Title: BBC RaW - User Preferences Store
#
#		Description: Behaviour for widget which stores preferences for the RaW website
#
##############################################################################################
#   $Source: $
#   $Author: Michael Koderisch $
#   $Revision: $
#   $Date: $ 
##############################################################################################
*/

/**
 * JS storage API object
 */
function UserPrefsStore(){
	/**
	 * Properties
	 */
	this.callBackFunctions = {};
	this.cbFuncId = 0;

	// Load cookies
	bbcjs.cookies.loadCookies();
	
	
	/**
	 * Function: addPrefsChangeListener
	 *
	 * Description: allows multiple callbacks to be registered
	 *
	 * @param CbFunction - callback function to be added
	 */
	this.addPrefsChangeListener = function(CbFunction){
		var id = this.cbFuncId++;
		this.callBackFunctions['fn_'+id] = CbFunction;
		return id;
	};
	
	/**
	 * Function: removePrefsChangeListener
	 *
	 * Description: any callbacks can be removed using the method below
	 *
	 * @param {uint} id - id of callback function to be removed
	 */
	this.removePrefsChangeListener = function(id){
		delete this.callBackFunctions['fn_'+id];
	};
	
	/**
	 * Function: executeCallBackFunctions
	 *
	 * Description: executes all registered callback functions
	 */
	this.executeCallBackFunctions = function(){
		for (i in this.callBackFunctions)
		{
			this.callBackFunctions[i]();
		}		
	};
	
	/**
	 * Function: getPrefs
	 *
	 * Description: read data from cookie
	 */
	this.getPrefs = function(){
		//console.log('getPrefs returned:'); console.dir(bbcjs.cookies.cookieData.rawPrefs);
		return bbcjs.cookies.cookieData.rawPrefs;
	};

	/**
	 * Function: setPrefs
	 *
	 * Description: write data to userdata as well as cookie and then execute all callback functions
	 *	
	 * @param {Object} Prefs - object to be stored in user store
	 */
	this.setPrefs = function(Prefs){
		bbcjs.cookies.setCookie('rawPrefs', Prefs, null, '/raw');
		//console.log('setPrefs received:'); console.dir(Prefs);
		this.executeCallBackFunctions(); // execute callback functions
	};

	/**
	 * Function: mergePrefs
	 *
	 * Description: merge supplied data into existing store
	 *
	 * @param {Object} Prefs - object containing key/value pairs to be added/updated to/in user store
	 */
	this.mergePrefs = function(Prefs){
		//console.log('mergePrefs received:'); console.dir(Prefs);
		var CurrentPrefs = this.getPrefs(); // get current preferences from user store
		
		// if the cookie does not yet exist create an empty object as starting point for merge
		if (!CurrentPrefs) CurrentPrefs = {}; 
		for (key in Prefs){
			CurrentPrefs[key] = Prefs[key];
		}
		this.setPrefs(CurrentPrefs);
		
	};
	
}
