// http://app52/web1/heroes.html //

var stopFlag = false;
//var handledFirstUpdate = false;
var dataHandlerFunction;


function stopAnyProgress()
{
	logMessage(LEVEL_DEBUG, "marking stop flag to 'true'.");
	stopFlag = true;
}


function setDataHandlerFunction(func)
{
	dataHandlerFunction = func
}


/**
general functions
**/

function padNumber(num)
{
	if (num < 10)
		return "0" + num;;
	return "" + num;
}
function logMessage(level,msg)
{
	if (showLog != 1)
		return;
	if (level > debugLevel)
		return;

	o = document.getElementById("log");
	
	var levelMsg = '';
	var color    = "#000000";
	switch (level)
	{
		case LEVEL_ALWAYS:
			levelMsg = "ALWAYS";
			break;
		case LEVEL_ERROR:
			levelMsg = "ERROR";
			color  = "#FF0000";
			break;
		case LEVEL_WARNING:
			levelMsg = "WARNING";
			color  = "#FF4444";
			break;
		case LEVEL_INFO:
			levelMsg = "INFO";
			//color  = "#FF6622";
			break;
		case LEVEL_DEBUG:
			levelMsg = "DEBUG";
			color  = "#777777";
			break;
		default:
			levelMsg = "UNKNOWN";
			break;
			
	}
	var d = new Date();
	
	o.innerHTML += "<span style=\"Color:" + color+ ";\">" + padNumber(d.getHours()) + ":" + padNumber(d.getMinutes()) + ":" +  padNumber(d.getSeconds()) + " - [" + levelMsg + "] - " + msg + "</span><br/>";

}

function xmlencode(string) {
	return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}


/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;
}


function getRandomNumber(range)
{
	return Math.floor(Math.random() * range);
}

/**
session code
**/

function simulateSessionUsingPlainAjax()
{
	logMessage(LEVEL_DEBUG,"simulateSessionUsingPlainAjax()");
	stopFlag = false
	//handledFirstUpdate = false;
	//var LastGoodData;
	 
	var last_modified;

	invokeInitialWebUpdateServlet();

}

function handleError(jqXHR, textStatus, errorThrown)
{
	alert (textStatus);
	alert (errorThrown);
}


/**
invokeInitialWebUpdateServlet
**/
var retries = 0;
var max_retries = 5;

function invokeInitialWebUpdateServlet()
{
	logMessage(LEVEL_DEBUG,"invokeInitialWebUpdateServlet()");
	logMessage(LEVEL_INFO, "invoking get request to '" + InitialWebUpdateServletUrl + "'.");
	$.ajax({
		type: "GET",   
		url: InitialWebUpdateServletUrl,   
		//error: handleError,
		//complete: endInitialWebUpdateServletUrl,
		//dataType: "xml",
		dataType: "text",
			success: parseInitialWebUpdateServlet,
			error: function (jqXHR, textStatus, errorThrown){ 
				logMessage(LEVEL_ERROR, "invokeInitialWebUpdateServlet() Failed!.");
				logMessage(LEVEL_ERROR, jqXHR);
				logMessage(LEVEL_ERROR, textStatus);
				if (retries < max_retries)
				{
					retries++;
					logMessage(LEVEL_DEBUG, "trying calling it again.");
					setTimeout ( "invokeInitialWebUpdateServlet()", 3000 );
					
				} else {
					logMessage(LEVEL_ERROR, "too many failed retries");
				}
			
			}

	});
}



function parseInitialWebUpdateServlet(data, status, xmlHttpRequest)
{
	retries = 0;
	logMessage(LEVEL_DEBUG, "parseInitialWebUpdateServlet()");
	logMessage(LEVEL_INFO, "got response from '" + InitialWebUpdateServletUrl + "'.");
	logMessage(LEVEL_DEBUG, "Response Status : " + xmlHttpRequest.status);
	if (xmlHttpRequest.responseText.length == 0)
	{
		logMessage(LEVEL_WARNING, "Response is empty!");
		setTimeout ( "invokeInitialWebUpdateServlet()", 3000 );
	} else {
	
		logMessage(LEVEL_DEBUG, "ResponseText: " + xmlencode(xmlHttpRequest.responseText));
		//LastGoodData = xmlHttpRequest.responseText;
		dataHandlerFunction(xmlHttpRequest.responseText);
		
		try
		{
			xml = $.parseXML( xmlHttpRequest.responseText);
		}
		catch(err)
		{
			logMessage(LEVEL_ERROR, "Exception during XML parsing (" + xmlHttpRequest.responseText + ") : " + err);
			logMessage(LEVEL_ERROR, "Reinvoking invokeWebUpdateServlet()");
			invokeWebUpdateServlet();
			return;
		}
		
		
		
		last_modified = $(xml).find("UPDATES").attr("LAST_MODIFIED");
		//alternativly : newLastModified = xmlHttpRequest.getResponseHeader("Last-Modified");
		logMessage(LEVEL_DEBUG, "last modified is '" + last_modified + "'.");
		invokeWebUpdateServlet();
		/*
		InvokeParticipantUserServlet();
		*/
	}
	
	
	
}

/**
InvokeParticipantUserServlet
**/
/*
function InvokeParticipantUserServlet()
{
	logMessage(LEVEL_DEBUG, "InvokeParticipantUserServlet()");
	logMessage(LEVEL_INFO, "invoking post request to  '" + ParticipantUserServletUrl+ "'.");
	var userName = '1234567410';
	var password = '12345678'
	var loginData = '<LOGIN USER_NAME="' + xmlencode(userName) + '" PASSWORD="' + xmlencode(password) + '" PLATFORM_ID="33" LANGUAGE_ID="1" />';
	//login
	//
	$.ajax({
		type: "POST",   
		contentType: "text/xml",
		processData: false,
		data: loginData,   
		url: ParticipantUserServletUrl,   
			success: parseParticipantUserServlet,
	});
	
}
function parseParticipantUserServlet(data, status, xmlHttpRequest)
{
	logMessage(LEVEL_DEBUG, "parseParticipantUserServlet()");
	logMessage(LEVEL_DEBUG, "got response from '" + ParticipantUserServletUrl + "'.");
	logMessage(LEVEL_DEBUG, "status code is '" + xmlHttpRequest.status+ "'.");
	//logMessage(xmlHttpRequest.responseXML);
	logMessage(LEVEL_DEBUG, xmlencode(xmlHttpRequest.responseText));
	//logMessage(LEVEL_DEBUG, data);
}
*/


/**
invokeWebUpdateServlet
**/

function invokeWebUpdateServlet()
{
	logMessage(LEVEL_DEBUG, "invokeWebUpdateServlet()");
	logMessage(LEVEL_INFO, "invoking get request (with If-Modified-Since) from  '" + WebUpdateServletUrl+ "'.");
	$.ajax({
		type: "GET",   
		headers: {
				'If-Modified-Since' : last_modified
                 },
		url: WebUpdateServletUrl,   
		dataType: "text",
		success: parseWebUpdateServlet,
		error: function (jqXHR, textStatus, errorThrown){ 
		logMessage(LEVEL_ERROR, "invokeWebUpdateServlet() Failed!.");
		logMessage(LEVEL_ERROR, jqXHR);
		logMessage(LEVEL_ERROR, textStatus);
		logMessage(LEVEL_ERROR, "reinvoking");
		setTimeout ( "invokeWebUpdateServlet()", 3000 );
		
		}
    });
}


function parseWebUpdateServlet(data, status, xmlHttpRequest)
{
	logMessage(LEVEL_DEBUG, "parseWebUpdateServlet()");
	logMessage(LEVEL_INFO, "got response from '" + WebUpdateServletUrl+ "'.");
	logMessage(LEVEL_DEBUG, "status code is '" + xmlHttpRequest.status+ "'.");

	switch(xmlHttpRequest.status)
	{
		case 200:
			logMessage(LEVEL_DEBUG, "new update available.");

			logMessage(LEVEL_DEBUG, xmlencode(xmlHttpRequest.responseText));
			//LastGoodData = xmlHttpRequest.responseText;
			
			//handle changes
			//dataHandlerFunction(LastGoodData);
			dataHandlerFunction(xmlHttpRequest.responseText);
			
			//save the last modified value.
			newLastModified = xmlHttpRequest.getResponseHeader("Last-Modified");
			logMessage(LEVEL_DEBUG, "newLastModified = '" + newLastModified + "'.");
			last_modified = newLastModified;
			
			logMessage(LEVEL_DEBUG, "reinvokeing in 1 second.");
			//wait one second and then reinvoke  invokeWebUpdateServlet
			setTimeout ( "invokeWebUpdateServlet()", 1000 );
			break;
		case 304:
			/*
			if (handledFirstUpdate == false)
			{
				dataHandlerFunction(LastGoodData);
				handledFirstUpdate = true;
			}
			*/
			if (stopFlag == true)
			{
				logMessage(LEVEL_DEBUG, "no change, but no reinvokation due to stop flag.");
			} else {
				logMessage(LEVEL_DEBUG, "no change, reinvoking.");
				invokeWebUpdateServlet();
			}

			break;
		default:
			logMessage(LEVEL_WARNING, "no handling for this status code.");
			// in case of error, should restart the whole process.
			invokeInitialWebUpdateServlet();
			break;
	}
	//logMessage(LEVEL_DEBUG, "last modified is '" + last_modified + "'.");
}

function participateEvent(question,answer_value)
{
	//organize the data properly
	//var identifier = '10401000000';
	var identifier = '10401000' + pad (getRandomNumber(1000),3);
	var question_index = 1;
	
	
	logMessage(LEVEL_INFO, "event id is : '" + question.event_id + "'");
	
	
	var selectionSubmitData = '<EVENT EVENT_TYPE_ID="' + xmlencode (question.event_type_id + "")  + '" EVENT_ID="' + xmlencode (question.event_id + "") + 
					 '" PLATFORM_ID="' + xmlencode (platform_id) + '" LANGUAGE_ID="' + xmlencode (language_id) +
					 '" PROVIDER_ID="' + xmlencode (provider_id) + '" IDENTIFIER="' + xmlencode (identifier) + '">' +
					 '<ANSWERS><ANSWER INDEX="' + xmlencode (question_index + "") +'" VALUE="' + xmlencode (answer_value + "") +'" /></ANSWERS></EVENT>';
					 

	logMessage(LEVEL_DEBUG, "submitting data : '" + xmlencode(selectionSubmitData) + "' to url '" + ParticipantServletUrl + "'");
	$.ajax({
		type: "POST",   
		contentType: "text/xml",
		processData: false,
		dataType: "text",		
		data: selectionSubmitData,   
		url: ParticipantServletUrl,   
		success: function (data, status, xmlHttpRequest) { 
			logMessage(LEVEL_INFO, "reply from submit:" + xmlencode(xmlHttpRequest.responseText));
			//handle replt
		} ,
		error: function (data, status, xmlHttpRequest) { logMessage(LEVEL_ERROR, "participateEvent() Failed!.");}
		
    });

}




