/**
 * @author b.starr@meta-fusion.com
 * Needed .js Libraries:
 * jquery-1.3.2
 * jquery.json-2.2
 * 
 * The JS code in the html file that calls the EconomicUpate might look something like this:
 * 
 * 			function newDataReceived (data) {
 *				//Do Something with the data:
 *				//alert ("newDataReceived");
 *				//alert (data.text);
 *			}
 *			
 *			
 *			$(document).ready(function() {
 *				var phpUpdateUrl = "http://192.168.0.12/testing/JSON_Ajax_Test/server.php";
 *				var txtFileUrl = "http://192.168.0.12/kongresse/meta-webplayer_test/updatecheckfiles/Livepage 3.txt";
 *
 *				//create the EconomicUpdate Object 
 *				var EU = new com.metafusion.EconomicUpdate (newDataReceived, phpUpdateUrl, txtFileUrl);
 *				//start polling data from the server
 *				EU.startPolling();
 *			});
 * 
 */


com.metafusion.EconomicUpdate = function (dataHandlingFunction, _phpUpdateUrl, _txtFileUrl) {

	//-----// constants (not really but these values shouldn't be changed) //-----//
	
	/**
	 * How long should be waited (minimum) before a new update is made after a change of the update intervall?
	 * 
	 *  This is to prevent the possibility that the next updaterequest is sent almost immediatly if the random function for the 
	 *  updateChangeIntervall returns a very low value (see XXXXX Function) 
	 */
	var UPDATE_DELAY = 5000;

	/**
	 * How many milliseconds should be added to the errorupdatedelay in case of an
	 * unsuccessfull connection attempt? 
	 */
	var ERROR_UPDATEDELAY_INCREMENT_TIME = 5000;
	
	/**
	 * txtFileData stores the information received from a txtfile on the server
	 * timestamp : a unixtimestamp marking the time of the last dataupdate
	 * updateintervall : how often should be looked for updated data 
	 */
	var txtFileData = {
		timestamp : "",
		updateIntervall : ""
	};
	
	/**
	 * Just a counter for some debuggingpurposes, not of a great importance...
	 */
	var counter = 0;
		
	//-----// private members //-----//
	/**
	 * last unixtimestamp read from Textfile
	 */
	var lastTimestamp = "";

	/**
	 * polling_active:
	 * Should updates be polled or not
	 */
	var polling_active = true;

	/**
	 * How often should be checked for new data (in ms)
	 */
	var updateInterval = 11000;

	/**
	 * How long to wait before the next update (ms)
	 */
	var nextupdateIn = 30000;

	/**
	 * URL to the txtFile that contains the updateInformation
	 */
	var updateTxtFileUrl = "";
 
	/**
	 * URL to the PHP Script that returns the required Information
	 */
	var phpUpdateUrl = "";
 
	/**
	 * Has the timestamp been changed since the last updaterequest?
	 */
 	var timestampChanged = true;

	/**
	 * Has the updateInterval been changed since the last updaterequest?
	 */
	var updateIntervalChanged = false;
 
	/**
	 * The JSON Object to store the date recieved from the server
	 */
 	var JSONData = "";
	
	/**
	 * Are we waiting for the result of a network operation?
	 */
 	var receivingInProgress= false;
	
	/**
	 * ErrorInConnection: has the last connection (getting the txt-file or the 
	 * Result of the PHP Script) been successfull?
	 * 
	 * error_update_delay: how much time should be added to the updateIntervall befor we try again
	 * (in case of an error)
	 */
	var lastConnectionSuccessfull = true;
	var error_updatedelay = 0;
 
	
	/**
	 * Start polling of the data
	 */
	com.metafusion.EconomicUpdate.prototype.startPolling = function () {
		polling_active = true;
		requestTxtFileData();
	}
	
	/**
	 * Stop polling of the data
	 */
	com.metafusion.EconomicUpdate.prototype.stopPolling = function () {
		polling_active = false;
	}
	
	/**
	 * Request data from the textfile (the returned data is handled in
	 * the receiveTxtFileData function)  
	 */
	function requestTxtFileData() {
		counter++;
		//$("#debug1").html("Counter: " + counter);
		//$("#debug3").html(counter+") requestTxtFileData");
		receivinginProgress = true;
		if (polling_active) {
			var tmpEUdate = new Date();
			var newtextFileURL = _txtFileUrl + "#"+tmpEUdate.getTime();
			//alert (newtextFileURL);
			$.ajax({
				method: "get",
				url: _txtFileUrl,
				cache: false,
				success: function(result){ // data has been received successfull -> continue proccessing
					//alert ("success:" + result);
					error_updatedelay = 0;
					lastConnectionSuccessfull = true;
					receiveTxtFileData(result);
				},
				error: function(xhr, ajaxOptions, thrownError){ // there has been an error receiving the data. Increase intervall before trying to get the data again
					lastConnectionSuccessfull = false;
					error_updatedelay += ERROR_UPDATEDELAY_INCREMENT_TIME;
					//alert(xhr.status);
					//alert(thrownError);
					setNextUpdateTime();
				}
			});
		}
	}
	/**
	 * This funcion is called upon (successfull) receiving the contents of the txtFile
	 * Here the received data it is split and stored into the txtFileData Object 
	 * @param {Object} dataObject
	 */
	function receiveTxtFileData (dataObject){
			receivinginProgress = false;
			var tmpar = dataObject.split('|');
			txtFileData.timestamp = tmpar[0];
			txtFileData.updateIntervall = tmpar[1] * 1000;
			//$("#debug4").html(counter+") TS - lTS: " + txtFileData.timestamp + " - " + lastTimestamp);

			//alert ("TS - lTS: " + txtFileData.timestamp + " - " + lastTimestamp);

		if (txtFileData.timestamp != lastTimestamp) {
			lastTimestamp = txtFileData.timestamp;
			//alert ("lastTimestamp: " + lastTimestamp + " - txtFileData.timestamp: "+ txtFileData.timestamp);
			timestampChanged = true;
		}
		if (txtFileData.updateIntervall != updateInterval) {
			updateInterval = txtFileData.updateIntervall;
			updateIntervalChanged = true;
		}
		decideWhetherDatabaseUpdateIsNeeded();
	}

	/**
	 * Fresh data only has to be requested from the database, when the timestamp in the txtfile
	 * has changed since the last pollingtime
	 */
	function decideWhetherDatabaseUpdateIsNeeded () {
		//$("#debug5").html(counter+") decideWhetherDatabaseUpdateIsNeeded");

		//alert ("decideWhetherDatabaseUpdateIsNeeded");
		if (timestampChanged) { // timestamp has changed = new data in the database. So we are going to request it from the server
			requestJSONDataFromPHP();
		} else {
			setNextUpdateTime();
		}
	}
	
	/**
	 * Request new data from the server (only if polling is set to active) 
	 * 
	 */
	function requestJSONDataFromPHP () {
		receivinginProgress = true;
			var tmpEUdate = new Date();
			var newphpFileURL = _phpUpdateUrl + "&"+tmpEUdate.getTime();
			//alert (newphpFileURL);
		
		if (polling_active) {
			$.ajax({
				method: "get",
				url: newphpFileURL,
				success: function(result){ // data has been received successfull -> continue proccessing
					//$("#debug7").html(counter+") receivedDataFromPHP: " + result.text);
					lastConnectionSuccessfull = true;
					error_updatedelay = 0;
					JSONData = $.evalJSON(result);
					recievedJSONData();
				},
				error: function(xhr, ajaxOptions, thrownError){ // there has been an error receiving the data. Increase intervall before trying to get the data again
					//alert(xhr.status);
					//alert(thrownError);
					lastConnectionSuccessfull = false;
					error_updatedelay += ERROR_UPDATEDELAY_INCREMENT_TIME;
					setNextUpdateTime();
				}
			});
		}
	}

	/**
	 * New Data from the database has arrived
	 * - set some variables
	 * - call the passed function of the parent script with dataObject (containing the new databasedata)  
	 * - set the next updateTime
	 */
	function recievedJSONData () {
		receivinginProgress = false;
		timestampChanged = false;
		JSONData.receivedNewData = true;
		dataHandlingFunction(JSONData);
		setNextUpdateTime();
	}	
	
	/**
	 * Calculate and set when the next updateRequest should be sent 
	 */
	function setNextUpdateTime () {
		if (updateIntervalChanged) { // we need to distribute every user evenly in the new intervall 

			var randomnumber=Math.floor(Math.random()* updateInterval)+ UPDATE_DELAY; // UPDATE_DELAY because: don't start immediatly but leave the server some time (5 secs) to process the ongoing requests
			nextupdateIn = randomnumber;
			updateIntervalChanged = false;
			//$("#debug9").html(counter+") Intervall changed. Next update in: " + nextupdateIn + " - UpdateIntervall: " + updateInterval);
		} else {
			nextupdateIn = updateInterval + error_updatedelay;
		}
		//$("#debug8").html(counter+") setNextUpdateTime + nextupdateIn:" + nextupdateIn);
		var timeNOW = new Date();
		var uniqueIdentifier = _txtFileUrl + timeNOW.getTime();
		$(this).oneTime(nextupdateIn, uniqueIdentifier, requestTxtFileData);
	}	
	
	
	
}

