/**
 * @fileoverview This file has been coded to provide the comman utilities to various client side JavaScript API(s)
 * For using the class functions, first create an object of class. Then called the needed function(s) with their suitable arguments/Parameters
 * Class Name : Utility
 *
 *
 * @author Espre Team
 * @version 0.1
 */

var htmlTemplateTargetDiv=null;				// html target div for inclusion of html template

/**
* member functions of class Utility
*/
Utility.prototype.sendRequest=sendRequest;
Utility.prototype.setSync = setSync;
Utility.prototype.setMimetype = setMimetype;
Utility.prototype.setTransport = setTransport;
Utility.prototype.setError = setError;
Utility.prototype.setHandler=setHandler;
Utility.prototype.setUrl=setUrl;
Utility.prototype.prepareBindObject=prepareBindObject;
Utility.prototype.setLoad=setLoad;
Utility.prototype.setContent=setContent;

Utility.prototype.setTimeoutFun=setTimeoutFun;
Utility.prototype.sendPollRequest=sendPollRequest;
Utility.prototype.clearPollRequest=clearPollRequest;

/*
Utility.prototype.sendPollRequestConf = sendPollRequestConf;
Utility.prototype.sendPollRequestNew=sendPollRequestNew;
Utility.prototype.sendPollRequest_checkUserStatus = sendPollRequest_checkUserStatus;
Utility.prototype.sendPollRequest_getSentInvitationStatus = sendPollRequest_getSentInvitationStatus;
Utility.prototype.sendPollRequest_getInvitationStatus = sendPollRequest_getInvitationStatus;
Utility.prototype.sendPollRequest_invitedBuddyList = sendPollRequest_invitedBuddyList;
*/
/**
  * @constructor
 *  sets the fields of class Utility
 * @param 	{Array} attributeList
 */
function Utility(bindObject){

	if( bindObject){					// an important JSON object, bindObject, would be passed to dojo.io.bind,
		this.bindObject = bindObject;
	}
	else{
		this.bindObject = null;
	}
	this.url='';						// a default url can be there
	this.content=null;
	this.sync = true;					// synchronous or asynchronous request
	this.mimetype = '';
	this.transport = '';
	this.handler = null;				// callback response handler
	this.error = null;					// error handler, invoked when error come
	this.load = '';						// response handler
	this.timeoutSeconds=10000;			// seconds,waiting for response
	this.timeoutFun=null;					// called in case of time out
	this.method='POST';					//
	this.requestTimeout = 'default';
}
/**
 * Set the timeoutFun, the timeout callback function
 * @param {String} handler
 * @return {String} handler
 */
function setTimeoutFun(timeoutFun){
 this.timeoutFun = timeoutFun;
}

/**
 * Set the handler, the callback function
 * @param {String} handler
 * @return {String} handler
 */
function setHandler(handler){
 this.handler = handler;
}

/**
 * Set the content, to be sent to the server
 * @param {String} content
 * @return {String} content
 */
function setContent(content){

 this.content= content;
}

/**
 * Set the url, of the server
 * @param {String} url
 * @return {String} url
 */
function setUrl(url){
 this.url = url;
}


/**
 * Set the Mimetype, which is used to decide the type of response (like JSON, Text, XMl) for the dojo.io.bind menthod
 * @param {String} mimetype
 * @return {String} mimetype
 */
function setMimetype(mimetype){
 this.mimetype = mimetype;
}

/**
 * Set the Transport, which is used to decide the transport type for the request(like HTTPRequest, XMLHTTPRequest) for the dojo.io.bind menthod
 * @param {String} mimetype
 * @return {String} mimetype
 */
function setTransport(sytransportnc){
 this.transport = transport;
}
/**
 * Set the error, Method defined in this will be called once an error will accured while exexuting the request
 * @param {String} error (Method Name)
 */
function setError(error){
 this.error = error;
}
/**
 * Method defined in this will called, once the user gets the response from the dojo.io.bind.
 * @param {String} mimetype
 * @return {String} mimetype
 */
function setLoad(load){
 this.load = load;
}


/**
 * Set the syncronous and asyncronous request as true and false respectively
 */
function setSync(sync){
	this.sync = sync;
}

/**
 * Send request to the requested URL using dojo.io.bind method.Function can load the data, handle the error and
 * can call the callback methods.You can make the sync and async call to the server.Mimtype will be to decide the
 * return type from the server.
 */
function sendRequest(bindObject)//requestedURL, callback, actionName)
{

		if(bindObject){							// user have freedom to set bindObject through senRequest function
			this.bindObject = bindObject		// it will override any previously defined bindObject
			dojo.io.bind(this.bindObject);
		}

		if(!this.bindObject){					// if bindObject is not set either

			dojo.io.bind({
                       url: this.url,
                       handler: this.handler,
					   load:this.load,
					   sync :this.sync,
					   content:this.content,
					   error:this.error,
					   timeoutSeconds:this.timeoutSeconds,
					   timeout:this.timeoutFun
            });
		}//		dojo.io.bind(this.bindObject);
}

function sendPollRequest() {
	//alert("Load 11:"+this.load);	
	//debugger;
	dojo.io.bind({
       url: this.url,
	   load: eval(this.load), 
	   sync :this.sync,
	   content:this.content
    });    	
	this.requestTimeout = dojo.lang.setTimeout(this,sendPollRequest, PRESENCE_REFRESH_TIME);	 
	//alert("requestTimeout 11 =>"+this.requestTimeout);
}

function clearPollRequest()
{
	if(this.requestTimeout != 'default') {
    	dojo.lang.clearTimeout(this.requestTimeout); 
   		//alert("Cleared successfully =>"+this.requestTimeout);
   		return true;
	}
	return false;
}

/*
var pollurl,pollload,pollsync,pollcontent;

function sendPollRequest(){
	//alert("sendPollRequest");
	pollurl=this.url;
	pollload='getUsersPresenceStatusCallBackFunction';
	pollsync=this.sync;
	pollcontent=this.content;


	pollServer();

}

function pollServer(){

		//alert("pollServer");
	dojo.io.bind({
                       url: pollurl,
					   load:getUsersPresenceStatusCallBackFunction, //function getData(type,data,evt){alert(data);},
					   sync :pollsync,
					   content:pollcontent
            });

	setTimeout('pollServer()',5000);
}

// Updates for conference and Presence management
function sendPollRequestConf(){	
	pollurl=this.url;
	pollload='getJoinedUsersCallBackFunction';
	pollsync=this.sync;
	pollcontentjoin=this.content;
	pollServerConf();
}

function pollServerConf(){		
	dojo.io.bind({
       url: pollurl,
	   load:getJoinedUsersCallBackFunction, //function getData(type,data,evt){alert(data);},
	   sync :pollsync,
	   content:pollcontentjoin
    });	
	setTimeout('pollServerConf()',7000);
}

function sendPollRequestNew(){	
	pollurl=this.url;	
	pollload='getInvitedConferenceCallBackFunction';
	pollsync=this.sync;
	pollcontentinvite=this.content;
	pollServerNew();
}

function pollServerNew(){			
	dojo.io.bind({
	   url: pollurl,				    			   
	   load:getInvitedConferenceCallBackFunction,
	   sync :pollsync,
	   content:pollcontentinvite
    });
	setTimeout('pollServerNew()',7000);
}

function sendPollRequest_checkUserStatus(){	
	pollurl=this.url;	
	pollload='getUsersConferenceStatusCallBackFunction';
	pollsync=this.sync;
	pollcontentinvite=this.content;
	pollServer_checkUserStatus();
}

function pollServer_checkUserStatus(){
	dojo.io.bind({
	   url: pollurl,				    			   
	   load:getUsersConferenceStatusCallBackFunction,
	   sync :pollsync,
	   content:pollcontentinvite
    });
	setTimeout('pollServer_checkUserStatus()',7000);
}

function sendPollRequest_getInvitationStatus(){	
	pollurl=this.url;	
	pollload='checkGetInvitedConferenceCallBackFunction';
	pollsync=this.sync;
	pollcontentinviteuser=this.content;
	pollServer_getInvitationStatus();
}

function pollServer_getInvitationStatus(){			
	dojo.io.bind({
	   url: pollurl,				    			   
	   load:checkGetInvitedConferenceCallBackFunction,
	   sync :pollsync,
	   content:pollcontentinviteuser
    });
	setTimeout('pollServer_getInvitationStatus()',7000);
}


function sendPollRequest_invitedBuddyList(){	
	pollurl=this.url;
	//alert(pollurl);
	pollload='getInvitedBuddyList_CallBackFunction';
	//alert(pollload);
	pollsync=this.sync;
	pollcontentinvite1 = this.content;
	PollRequest_invitedBuddyList();
}
function PollRequest_invitedBuddyList(){			
	dojo.io.bind({
	   url: pollurl,				    			   
	   load: getInvitedBuddyList_CallBackFunction,
 	  // load: function test(type,data,evt){alert("Inside teh dojo"+type);},			//'getInvitedBuddyList_CallBackFunction',
	   sync:pollsync,
	   content:pollcontentinvite1
    });
	setTimeout('PollRequest_invitedBuddyList()',5000);				
}

function sendPollRequest_getSentInvitationStatus(){	
	pollurl=this.url;	
	pollload='getSentInvitationStatusCallBackFunction';
	pollsync=this.sync;
	pollcontentinvite=this.content;
	pollServer_getSentInvitationStatus();
}

function pollServer_getSentInvitationStatus(){
	dojo.io.bind({
	   url: pollurl,				    			   
	   load:getSentInvitationStatusCallBackFunction,
	   sync :pollsync,
	   content:pollcontentinvite
    });
	setTimeout('pollServer_getSentInvitationStatus()',7000);
}
*/
/********************************************** Updates Ends Here**************************/



/**
 * prepares bindObject from Utility attributes
 */
function prepareBindObject(){


/*
	var strJson='{';

	var bindProperties = ['sync', 'mimetype', 'transport', 'error', 'load', 'timeoutSeconds', 'timeout', 'method'];
	var propUtil;
	for(property in bindProperties){
		propUtil = eval('this.'+bindProperties[property])
		if( propUtil && propUtil!='' && propUtil!=null){		// if property is set already
			strJson=strJson+ bindProperties[property] + ":" + "'"+propUtil+"'"+",";
		}
	}

	strJson+='}';

	strJson=strJson.replace(/,}/g,"}");					// chop the last comma
	//this.bindObject = this.bindObjec
	strJson="{name: 'value2'}";
	//alert(typeof(strJson));
	this.bindObject = eval(strJson);
	//alert(this.bindObject);
	//for(i in this.bindObject)
		//alert(i+"::"+this.bindObject.i);
*/
}

/**
 * return string representation of json
 * this version don't convert nested jsons or arrays
 */

function  jsonToString(jsonstr){

	var requestStr='{';
		for(key in jsonstr)
		 requestStr = requestStr + key +":'" + jsonstr[key]+"',";

		requestStr =requestStr +"}";
		requestStr = requestStr.replace(',}','}');

	return requestStr;
}
function addServerAction(paramList,MethodName,serverAction){

	if(paramList)
		return "{" + paramList + ", ACTIONID: ' " + serverAction +"'}";
	else if(serverAction)
		return "{ACTIONID: ' " + serverAction +"'}";
	else
		return;
}

// delay execution for millis milliseconds
function wait(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}
/*
 * This function has been used to made the visibility of element/div to visible
 */
function showDiv(d){
	if($(d)){   								// this condition check's whether the objects exists
		$(d).style.visibility = 'visible';
		$(d).style.display = 'block';
	}
}
/*
 * This function has been used to made the display of element/div to None
 */
function hideDiv(d){
	if($(d)){   								// this condition check's whether the objects exists
		$(d).style.display = 'none';
		$(d).style.visibility = 'hidden';
	}
}
/*
 * This function will return object, after fetching it from the document on the basis of its id
 */
function $(e){
	return document.getElementById(e);
}

/**
 * prepares Json object from result xml string
 * @param 	{Sring} resultXML, a formated xml string
 * @return	josn object
 */
function resultXMLToJson( resultXML )
{

	//alert(resultXML);
	var xmlDom = parseXml(resultXML);           // parse the input xml

	var jsonText = xml2json.parser(xmlDom, ""); // get Json Text from xmlDom
	var objJson = eval('(' + jsonText + ')');
	//alert(jsonText);
	//alert(resultXML);
	response =
		{
		"actionstatus": objJson.RESPONSE.ACTIONSTATUS
		}; // create global response object

	if (objJson.RESPONSE.ACTIONSTATUS == "false")
		throw new Error(objJson.RESPONSE.Error.ExceptionMsg);

	return objJson;
}


/**
 * includes the html template file into the other html
 * id of Div is required, in which it will render the template
 * @param {Object} templateName
 * @param {Object} trgDiv
 */
function includeHtmlTemplate(templateName,trgDiv){

			htmlTemplateTargetDiv=trgDiv;
			util = new Utility();
			util.setUrl(templateName);
			util.setLoad(includeHtmlTemplateCallback);
			util.setSync(true);
			util.sendRequest();
}

/**
 * callback method for includeHtmlTemplate method ajax call
 * @param {Object} type
 * @param {Object} data
 * @param {Object} evt
 */
function includeHtmlTemplateCallback(type, data, evt){

			var objDiv = document.getElementById(htmlTemplateTargetDiv);
			objDiv.innerHTML = data;
}

/**
 * prepares an array of given Tag from resultXML
 * @param 	{String} JsonObj, a JSON object
 * @param	(String) Tag, Tag of the input array
 * @return	an array of User objects
 * @type	Array
 */
function resultXMLToArray( JsonObj, Tag )
{
	if(typeof(JsonObj) == "undefined")
		return false;
	var xmlTag = eval("JsonObj.RESPONSE.Result");

	if (!xmlTag)
	{
		//alert("Inside The Object");
		return false;
	}

	if (Tag != null)
		xmlTag = eval("JsonObj.RESPONSE.Result." + Tag);

	if (!xmlTag)
	{ //nothing is returned
		return false;
	}
	/* populate array from json */
	var arrayLength = xmlTag.length;

	var resultArray = new Array(); // array to be returned
	/* if only one result is in Json, treat it seperate */
	if (isNaN(arrayLength))
	{
		var associativeArray = new Array();

		for (i in xmlTag)
		{
			associativeArray[i] = eval("xmlTag." + i);
		}

		resultArray[0] = associativeArray;
		return resultArray;
	}

	/* if more than one groups are in result Json */
	for (var loopIndex = 0; loopIndex < arrayLength; loopIndex++)
	{
		var associativeArray = new Array();

		for (var i in xmlTag[loopIndex])
		{
			associativeArray[i] = eval("xmlTag[loopIndex]." + i);
		}

		resultArray[loopIndex] = associativeArray;
	}

	return resultArray;
}
function resultXMLToJsonText( resultXML )
{

//alert(resultXML );
var xmlDom = parseXml(resultXML); // parse the input xml
var jsonText = xml2json.parser(xmlDom, ""); // get Json Text from xmlDom
//var objJson = eval('(' + jsonText + ')');
//alert(jsonText);
//alert(resultXML);
response =
{
"actionstatus": objJson.RESPONSE.ACTIONSTATUS
}; // create global response object

if (objJson.RESPONSE.ACTIONSTATUS == "false")
throw new Error(objJson.RESPONSE.Error.ExceptionMsg);

return jsonText;
}

function addslashes(str) {
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\0/g,'\\0');
return str;
}

function stripslashes(str) {
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\\\/g,'\\');
str=str.replace(/\\0/g,'\0');
return str;
}

function changeToForwardSlashes(str) {
str=str.replace(/\'/g,'/\'');
str=str.replace(/\"/g,'/\"');
str=str.replace(/\\/g,'/\\');
str=str.replace(/\0/g,'/\0');
return str;
}

var AJAX={
	ajax_load:function(url, t){
	var page_request = false
	var bustcacheparameter=""
	if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE6 or below
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false
	page_request.onreadystatechange=function(){AJAX.ajax_loadpage(page_request, t)}
	if (this.ajaxbustcache) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, false)
	page_request.send(null)
},

ajax_loadpage:function(page_request, t){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
	t.innerHTML=page_request.responseText
	}
}
}


/**
 * checks that file path is absolute e.g. starts with file: or http:
 */

/**
* This method checks that file path is absolute e.g. starts with file: or http:
* @param (String) path
* @return (Boolean) True/False
*/
function isAbsolutePath(_path)
{
       if((_path !== null) && (typeof _path == "string")){
                // check is a valid path style (i.e. n:\xx)
                var re = /^([a-z|A-Z]:){1}/; // pattern to find e.g. C:
                if(_path.search(re) != -1){
                     return true;
                }
            }
            return false;      
}