/*
Copyright (c) Botstation Technologies, 2006. All rights reserved.

BOTSTATION STWIDGET EVALUATION LICENSE AGREEMENT
The copyright of this software is owned by Botstation. All rights reserved.
Taking any step to set-up or install the product constitutes your assent to and 
acceptance of this License Agreement. If you do not agree with all the terms of this agreement, 
you may not use the product.

YOU MAY NOT:
(i) sublicense, rent, sell, or lease any portion of this software;
(ii) reverse engineer, decompile, disassemble, modify, translate, make any attempt to 
	discover the source code of this software, or create derivative works from this software; or
(iii) continue use of this software after your 30 day trial.

DISCLAIMER OF DAMAGES:
We have made every effort possible to ensure that this software is free of any bugs or errors, 
however in no way is this software to be considered error or bug free. 
By using this software you assume all responsibility for any damages or lost data 
that may result from any errors or bugs in this software. Regardless of whether any remedy 
set forth herein fails of its essential purpose, in no event will Botstation be liable 
to you for any special, consequential, indirect or similar damages, including any 
lost profits or lost data arising out of the use or inability to use this software.
*/

var autologin=false; //login without clicking the Login button
var autoaddbuddies="Bot Botstation";  //Additional chat buddies
var autochatpartner="Bot Botstation";  //default user selected as current chat partner
var automessage="hello";
var servletfolder="/ggljoke/servlet/";
var servletname="stchat";
var servletpath=servletfolder+servletname;
var stserver="";
var logintype="anonymous"; //"anonymous"  "token" "password"
var delayms=4000; //time (ms) to wait before fetching. Only when clientdelay=true
var xtramode="client"; // "client" "bot"  "person"  "statusperson"  "statuslist"
var fetchmode="smartfetch"; //"smartfetch"   "normal"  "serverpush"
var delaymsbotidle=10000; //time to wait before fetching when xtramode=bot
var delaymsbotactive=2500; //time to wait before fetching while expecting  answer from bot (only when xtramode=bot)
var servpushdelayms=2000; //delay between fetching data from server. when fetchmode=serverpush
var smartfetchdelayms=4000; //time to wait before fetching   (only when fetchmode=smartfetch)
var smartfetchincr=2;  //1.5 //increment factor for each step (1.5=50% longer time each step)
var smartfetchidleloops=30; //30  //how many periods each step lasts  (4000ms*30loops=120 seconds before increasing waiting time by  1.5)
var smartfetchsteps=3; //3  //increment max this amount of times
var smartstepscnt=0;  //current step number
var smartloopscnt=0;  //current loop number
var showtextstatus=false; //include text description of status to the right of buddy name
var showiconstatus=true;  //include status icon to the left of buddy list field
var showstatuschangesuccessmsg=true; //show statuschangedok_message message when user's status was successfully changed
var showstatuschangefailedsmsg=true; //show statuschangedfailed_message message when user's status was successfully changed
var allowhtml=true; //do not remove HTML tags from incoming messages
var allowjs=false; //do not remove javascript <script> tag from incoming messages
var submitonenter=true; //submit message for sending when pressing Enter key
var clearonsend=true; //clear input text field after message is sent
var hideanonname=false; //clear input text field after message is sent
var focusonmessage=true; //put focus to chat window when new message arrives
var setFocusToInput=true; //set focus to message input field after sending message
var transformlinks=false; //change incoming http: links to <link>
var usealiases=true; //apply aliases to names
var maxmsg=17; //number of last messages to show
var sessionid="";
var httpsoptions=0; //0=no https, 1=https only for login, 2=everything is https
var httpobj=null;
var relogin = false;
var stopFetching=true;
var status_onlineonly=false;
var limitshownmessages=true;
var convertlinks=true;  //convert incoming http:// and www. text to links
var lastbuddylist="";  //buddylist string with last know online sattuses
var showwarning=false;  //show warning when disconnected
var loggedin=false;
var isloggingout=false;
var isclosing=false;
var incorrectlogin=false;
var bl_array;  //Array with buddies derived from lastbuddylist string
var msg_counter=0;
var fetch_counter=0;
var connfailedcounter=0;
var lastrequest; var lastresponse;
var addpersonprompt="Enter the name of the person to add to the buddy list";
var reloggedin_message="<font color=\"#CC3300\"><b>You've lost contact with the web server, "+
"but now you are automatically connected again</b></font>";
var reconnected_message="<font color=\"#339933\"><b>Reconnected</b></font>";
var newbuddyadded_message="<font color=\"orange\"><b>New chat buddy was added successfully</b></font>";
var newbuddyfailed_message="<font color=\"#CC3300\"><b>Failed to add new chat buddy. ";
var statuschangedok_message="<font color=\"orange\"><b>Online status changed successfully</b></font>";
var statuschangedfailed_message="<font color=\"#CC3300\"><b>Failed to change online status</b></font>";
var connectfailed_message="<font color=\"#FF3300\"><b>Experiencing problems with connection to server.</b><br>Trying to reconnect(NN)...</font>";
var connectfailedsecond_message="<font color=\"#FF3300\">Reconnecting(NN)...</font>";
var connectfailedgiveup_message="<font color=\"#FF3300\"><b>- - - - - - - - - - -<br>Could not connect to server. Try again later.<br>- - - - - - - - - - -</b></font>";
var firstLoginFailed_message="<font color=\"red\" id=\"loginRetry\">First login attempt failed. Trying again...</font>";
var notloggedin_message="You are not logged in";
var showlast10msg_tip="Show only last 10 messages";
var showallmsg_tip="Show all messages";
var showallbuddies_tip="Show all";
var showonlinebuddies_tip="Show online only";
var automessagesend=false;   //Send message specified in automessage variable automatically when user is logged in.
var autoBuddyIsSet=false;  //changed to True when user is logged in and buddylist fetched
var autoaddbuddiesshow=false;  //do not output to user's screen when new auto-buddies are being added
var browser_ppc=navigator.userAgent.toLowerCase().indexOf("ppc")>0;   //type of web browser
var default_parameters="";
var tmpsessionid="00000000000000000000";  //temporary session id used for fetching while login is not completed
var buddylistfetched=false;
var isconnectionproblem=false;
var getbuddies=true;
var loginFailedTimes=0;
var currentchatpartner="";
var loginformcode="";
var mystatuscode="";
var lastselectedbuddy="";
var buddylistcode="";
var myname="";
var ssoname="";
var customtoken="";
var loginretryparameters="";
var lblBuddyList="Buddy list";
var buddiesArray=new Array();
var out_queue=new Array();
var nameAliases=new Array();
var nameAliasesRev=new Array();
var groupsArray=new Array();
var out_queue_cnt=0;
var myloginpassword="";
var myloginusername="";
var optionalCharset=""; //set to "; charset=UTF-8" for e.g. chinese letters support on Tomcat servlet engine
var ssoparname="LtpaToken";
var logoutWaitResponse=false; //do not wait response from server when clicking Logout button.
var showBuddyList=true; //show buddy list dialog box when logged in. Can be set to false for anonymous users chatting only with bot.
var showAddBuddyButton=true;  //show Add Buddy icon
var showAdminMessages=true;
var showAnnouncements=true;
var showSystemMessages=true;
var token="";  //token to use when logging in with "token" option
var lastreq="";
var lastTimerId;
if (document.location.href.indexOf("login=anonymous")>-1 || document.location.href.indexOf("logintype=anonymous")>-1) {servletname="stchat"; logintype="anonymous";}
if (document.location.href.indexOf("login=token")>-1 || document.location.href.indexOf("logintype=token")>-1) {servletname="stchat"; logintype="token";}
if (document.location.href.indexOf("login=password")>-1 || document.location.href.indexOf("logintype=password")>-1) {servletname="stchat"; logintype="password";}
servletpath=servletfolder+servletname;
tmpmsg=getURLParam("initialmsg");
if(tmpmsg!="") automessage=tmpmsg;
tmpbuddy=getURLParam("initialbuddy");
if(tmpbuddy!="") autochatpartner=tmpbuddy;
tmpbuddies=getURLParam("mybuddies");
if(tmpbuddies!="") autoaddbuddies=tmpbuddies;
tmptkn=getURLParam("ssotoken");
if(tmptkn!="") customtoken=tmptkn;
if(getURLParam("autosend")=="yes") automessagesend=true;
if(getURLParam("allowhtml")=="yes") allowhtml=true;
if(getURLParam("allowhtml")=="no") allowhtml=false;
if(getURLParam("allowjs")=="yes") allowjs=true;
if(getURLParam("allowjs")=="no") allowjs=false;
if(getURLParam("submitonenter")=="no") submitonenter=false;
if(getURLParam("clearonsend")=="no") clearonsend=false;
if(getURLParam("hideanonname")=="yes") hideanonname=true;
if(getURLParam("autologin")=="yes") autologin=true;
if(getURLParam("focusonmessage")=="no") focusonmessage=false;
if(getURLParam("transformlinks")=="yes") transformlinks=true;
if(getURLParam("usealiases")=="no") usealiases=false;
if(getURLParam("ssoname")!="")ssoname=getURLParam("ssoname");
if(getURLParam("ssoparname")!="")ssoparname=getURLParam("ssoparname");
if(getURLParam("delayms")!="") {
delayms=getURLParam("delayms");
delaymsbotactive=delayms; //override bot's interval with URL value
}
if(getURLParam("fetchmode")!="")fetchmode=getURLParam("fetchmode");
if(getURLParam("convertlinks")=="no") convertlinks=false;
if(getURLParam("getbuddies")=="no") getbuddies=false;
if(getURLParam("textstatus")=="yes") showtextstatus=true;
if(getURLParam("onlineonly")=="yes") status_onlineonly=true;
if(getURLParam("xtramode")!="")xtramode=getURLParam("xtramode");
if(logintype=="anonymous") showAddBuddyButton=false;

xtramode="bot";
automessage="joke";
clearonsend=false;
automessagesend=true;
autologin=true;



if(navigator.userAgent.indexOf('iPhone')>-1){
	window.onorientationchange = function(){adjustOrientationGUI()}
	window.title="STWidget - Sametime chat for iPhone";
};

if(customtoken==""){token=getToken(ssoparname)} else {token=escape(customtoken)}  //token to use when logging in with "token" option
lblBuddyList=((showiconstatus==true) ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+lblBuddyList : lblBuddyList);
if(fetchmode=="smartfetch") delayms=smartfetchdelayms; 
if(fetchmode=="serverpush") delayms=servpushdelayms; 
if(xtramode=="bot"){
fetchmode="smartfetch";
delayms=delaymsbotactive;
smartfetchdelayms=delaymsbotactive; //time to wait before fetching   (only when fetchmode=smartfetch)
smartfetchsteps=3;  //increment max this amount of times
smartfetchincr=2;  //increment factor for each step (1.5=50% longer time each step)
smartfetchidleloops=5; //how many periods each step lasts  (4000ms*30loops=120 seconds before increasing waiting time by  1.5)
smartstepscnt=0;  //current step number
}
if(xtramode=="helpdesk"){
fetchmode="smartfetch";
delayms=smartfetchdelayms; 
smartfetchdelayms=delaymsbotactive; //time to wait before fetching   (only when fetchmode=smartfetch)
smartfetchsteps=3;  //increment max this amount of times
smartfetchincr=2;  //increment factor for each step (1.5=50% longer time each step)
smartfetchidleloops=5; //how many periods each step lasts  (4000ms*30loops=120 seconds before increasing waiting time by  1.5)
smartstepscnt=0;  //current step number
}

function runAfterLogin(){
if(navigator.userAgent.indexOf("MSIE")>-1){
	if(getElement("trbl"))document.getElementById("trbl").style.display="block";
}else{
	if(getElement("trbl"))document.getElementById("trbl").style.display="table-row";
}

	hideElement("antitrbl");
	if(autochatpartner!="")ProcessBuddy(autochatpartner+"$|$-CUSTOMBUDDY-$-UNKNOWN ()");
	if(xtramode=="helpdesk"){
		addon_helpdesk();
	}
	if(xtramode=="bot"){
		addon_bot();
	}
	if(navigator.userAgent.indexOf('iPhone')>-1){
		addon_browserIPhone();
	}
	
}

function initHTTP(){
	var http_request = false;
	if (window.XMLHttpRequest) {  // Mozilla
		http_request = new XMLHttpRequest();
		} 
	else if (window.ActiveXObject) {  // IE
		try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Your web browser is not compatible');
		return false;
	}		
	return http_request;		
}


function makeAsyncRequest(parameters) {
	if (parameters=="") parameters=default_parameters;
	http_arequest=initHTTP();	
	http_arequest.onreadystatechange = function() { readyhandler(http_arequest, true); };
	
	http_arequest.open('POST', stserver+servletpath, true); //+"&unv="+urlunique(), 
	parameters=parameters+"&unv="+urlunique();
	http_arequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"+optionalCharset); //(( "text/xml" ); 
	http_arequest.setRequestHeader("Content-length", parameters.length);
	http_arequest.setRequestHeader("Connection", "Keep-Alive");
	http_arequest.send(parameters);
	lastrequest=new Date();


	
}
function makeAsyncRequestOnce(parameters, reuseConnection){
	//makeAsyncRequestOnce does not loop waiting for response, it simply sends the request and then exits. 
	var http_arequest2=initHTTP();  
	if(logoutWaitResponse==true){
		//wait while response is received and then process it
		http_arequest2.onreadystatechange = function() { readyhandler(http_arequest2, false); };
	}
	http_arequest2.open('POST', stserver+servletpath, true); //+"&unv="+urlunique(), true);		
	parameters=parameters+"&unv="+urlunique();
	http_arequest2.setRequestHeader("Content-type","application/x-www-form-urlencoded"+optionalCharset);
	http_arequest2.setRequestHeader("Content-length", parameters.length);
	http_arequest2.setRequestHeader("Connection", "Keep-Alive"); 
	http_arequest2.send(parameters);
}

function readyhandler(http_requestobj, fetchloop)	{
lastresponse=new Date();
if(isclosing==true) return;
var xmlDoc;
httpobj=http_requestobj;
relogin=false;
if (isLoggedIn()){
	if (http_requestobj.readyState == 4){
		
		//fix for Firefox when server not available 
		var httpstatus = 500;
		try{
  			httpstatus = http_requestobj.status;
    	}
		catch(e){
  			httpstatus = 500;
		}

		if (httpstatus == 500){
			 //alert(http_requestobj.responseText);  //show full error message
			getElement("LoginProgress").innerHTML="<br><font color=\"red\">Script error on server. Please try again.</font><br><br>";
			return;
		}
		if (http_requestobj.status == 200) {
			resptxt=http_requestobj.responseText;
			//alert(resptxt);
			if(connfailedcounter>0) addToCurrentMessagesPanel(reconnected_message+"<br>");
			connfailedcounter=0;  //reset counter of failed connections
		if(resptxt!=null && resptxt!=""){
		
		if (document.implementation.createDocument){ 
    	// Mozilla, create a new DOMParser 
    		var oDOMParser = new DOMParser(); 
   			xmlDoc = oDOMParser.parseFromString(resptxt, "text/xml"); 
  		} else if (window.ActiveXObject){ 
    		// Internet Explorer, create a new XML document using ActiveX 
    		// and use loadXML as a DOM parser. 
    		xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
    		xmlDoc.async="false"; 
   		 xmlDoc.loadXML(resptxt);
  		}
		
		var respNodes=xmlDoc.getElementsByTagName("RESPONSE")[0];
				
		if(respNodes!=null){
			if(respNodes.childNodes!=null)nodesLength=respNodes.childNodes.length;
			if(respNodes.childNodes==null)nodesLength=-1;
		}else{
			nodesLength=-1;
		}		
		
		var loginprocessed=false;
		//This situation can happen if LOGGEDIN was added to the response 
		//AFTER the BUDDYLIST was added. So we must first check if user is logged in.
		if(nodesLength>0)loggedinelem=respNodes.getElementsByTagName("LOGGEDIN");
		if(nodesLength>0 && loggedinelem.length>0){
			resp=unescape(loggedinelem[0].firstChild.nodeValue.replace(/\+/g, " "));
		 	if(resp!="OK" && loggedinelem.length>1) resp=unescape(loggedinelem[0].firstChild.nodeValue.replace(/\+/g, " "));
			resp=UTF8Decode(resp);
			resprest=resp;
		 	handleLOGGEDIN(resp,resprest);
			loginprocessed=true;
		}
		
		var msgcnt=0;
		
   		while(msgcnt<nodesLength) {
		
			if(respNodes==null || respNodes.childNodes[msgcnt]==null || respNodes.childNodes[msgcnt].firstChild==null){msgcnt++; continue;}
        
			resp=unescape(respNodes.childNodes[msgcnt].firstChild.nodeValue.replace(/\+/g, " "));
			resp=UTF8Decode(resp);
			resprest=resp;
			resptype=respNodes.childNodes[msgcnt].nodeName;

			msghistory=resp;
			msgcnt++;
		
			if(resptype=="NONE" && fetch_counter<20)fetch_counter=fetch_counter+9; //do not make 20 extra calls if response was once "NONE", probably all status changes were already fetched
			if(resptype=="LOGGEDIN" && loginprocessed==false) {handleLOGGEDIN(resp,resprest); } //Result of loggin in
    		if(resptype=="BUDDYLIST") { handleBUDDYLIST(resp,resprest);  }  //updates in buddies' online status (all buddies put together)
			if(resptype=="BUDDY") { handleBUDDY(resp,resprest);  }  //updates in online status of 1 buddy
			if(resptype=="SYSTEM" & showSystemMessages==true) { handleSYSTEM(resp,resprest); } //system messages
			if(resptype=="MYSTATUS") { handleMYSTATUS(resp,resprest); }  //My status changed on server for some reason
			if(resptype=="ADMIN" && showAadminMessages==true) { handleADMIN(resp,resprest);  } //messages from admin
			if(resptype=="RELOGIN") { handleRELOGIN(resp,resprest); } 
			if(resptype=="MESSAGE") { handleMESSAGES(resp,resprest);  }  //Regular messages from users
			if(resptype=="ANNOUNCEMENT" && showAnnouncements==true) { handleANNOUNCEMENTS(resp,resprest);  }  //Regular messages from users
			if(resptype=="NEWBUDDY") { handleNEWBUDDY(resp,resprest);  } 
			if(resptype=="SETUSER") { handleSETUSER(resp,resprest);  }   //Set another selected user
			if(resptype=="LOGGEDOUT") { handleLOGGEDOUT(resp,resprest);   }  //Result of logout command or forced logout
			if(resptype=="NEWSTATUS") { handleNEWSTATUS(resp,resprest);    } //Response to manual status change request
			if(resptype=="MYNAME") { handleMYNAME(resp,resprest);    }
			if(resptype=="PUBLICGROUP") { handlePUBLICGROUP(resp,resprest);  }
			if(resptype=="PRIVATEGROUP") { handlePRIVATEGROUP(resp,resprest);  }
			if(resptype=="ALIAS") { handleALIAS(resp,resprest);  }
		} //while
			loginprocessed=false; 
		} // if(resptxt!=null && resptxt!="")
		http_requestobj=false;
	}else{  // if status==200
			if(connfailedcounter==0){
				addToCurrentMessagesPanel(connectfailed_message.replace("NN",connfailedcounter+1)+"<br>");
			}else{
			addToCurrentMessagesPanel(connectfailedsecond_message.replace("NN",connfailedcounter+1)+"<br>"); 
			}
			connfailedcounter++;
			if(connfailedcounter==5){
				addToCurrentMessagesPanel(connectfailedgiveup_message+"<br>");
				stopFetching=true;
				lastbuddylist="";
				buddylistfetched=false;
				sessionid="";
				hideOnConnectionBroken();
			}
		}  // if status==200
		
		if(sessionid.length==32){
			fetchData(fetchloop);
		}else{
			sessionid="";
			//Retry to login after initial login connection attempt failed
			if(loggedin==false && incorrectlogin==false && loginretryparameters!="")setTimeout("makeAsyncRequest('"+loginretryparameters+"&re=1')", 3000);  //retry after 3 seconds
		} //if(sessionid.length==32){
	
		fetchloop=true;
	} // if readystate==4 
}  //if (isLoggedIn())
	return;
}

function fetchData(fetchloop){
	default_parameters='mysession='+sessionid+'&type=fetch';
	if(fetchmode=="smartfetch" && fetch_counter>=20){
		if(smartloopscnt<smartfetchidleloops) {
			smartloopscnt=smartloopscnt+1;
		}
		if(smartloopscnt==smartfetchidleloops){
			smartstepscnt=smartstepscnt+1;
			if(smartstepscnt<smartfetchsteps){
				delayms=smartfetchdelayms*smartfetchincr*smartstepscnt;						
				smartloopscnt=0;
			}
				
		}	
	
	}
	if(fetchloop==true) {				
		if(fetchmode!="serverpush"){  //server releases connection immediately without waiting X seconds. For "normal" and "smartfetch" types.
			fetch_counter++;
			//do not delay for 20 first fetches, required for proper fetch of buddy list
			if(fetch_counter<20) {tmpdelay=200}else{tmpdelay=delayms}			
			lastTimerId=setTimeout("makeAsyncRequest('"+default_parameters+"&nowait=yes')", tmpdelay);
		}else{  //serverpush
			tmpdelay=servpushdelayms; //wait 2 seconds between fetches. Mostly for purpose of showing to iPhone user that the app is working properly
			//makeAsyncRequest(default_parameters);
			setTimeout("makeAsyncRequest('"+default_parameters+"')", tmpdelay); //make a small delay before next fetch
		}
	} 
}

function showMyCurrentStatus(statustxt){
	
	userstatus=statustxt.substring(0,statustxt.indexOf("(")).toUpperCase().replace(/^\s*|\s*$/g,"");

	switch (userstatus)
  {
    case "ACTIVE": { showMyStatus("icon_active.gif", statustxt, "BuddyStatusActive", "Online"); break }
    case "AWAY": { showMyStatus("icon_away.gif", statustxt, "BuddyStatusAway", "Away"); break }
	case "DND": { showMyStatus("icon_dnd.gif", statustxt, "BuddyStatusDND", "Do Not Disturb"); break }
	case "ACTIVEMOBILE":case "ACTIVE MOBILE": { showMyStatus("icon_activemobile.gif", statustxt, "BuddyStatusMobile", "Online, mobile"); break }
	case "MOBILE": { showMyStatus("icon_mobile.gif", statustxt, "BuddyStatusMobile", "Online, mobile"); break }
    case "OFFLINE": { showMyStatus("icon_offline.gif", statustxt, "BuddyStatusOffline", "Offline");   break}
	case "UNKNOWN": { showMyStatus("icon_unknown.gif", statustxt, "BuddyStatusUnknown", "Getting status...");  break}
	case "NOTUSING":case "NOT USING": { showMyStatus("icon_notusing.gif", statustxt, "BuddyStatusNotusing", "Not using"); break }
	
    default: { showMyStatus("icon_unknown.gif", statustxt, "BuddyListBlue", "Unknown"); break } 
  }
}

function showMyStatus(icon, alttitle, spanclass, onlinestatus){
	spantxt="<span style=\"vertical-align: middle\"><img src=\""+icon+"\" title=\"My status: "+toProperCase(alttitle)+"\" alt=\"My status: "+toProperCase(alttitle)+"\" border=\"0\"></span><span id=ShowMyStatus style=\"vertical-align: middle\" class=\""+spanclass+"\">"+" "+onlinestatus+"</span>";
	getElement("MyStatus").innerHTML=spantxt;
	getElement("ShowMyStatus").innerHTML="<a onmouseover=\"this.style.cursor='pointer'\" onClick=\"return clickreturnvalue();\" onMousedown=\"dropdownmenu(this, event, menu1, '80px');return false;\">"+getElement("ShowMyStatus").innerHTML+"</a>";
}

function urlunique(){
	var d = new Date();
	return (d.getDate()+""+d.getHours() +""+ d.getMinutes() +""+ d.getSeconds() +""+d.getMilliseconds());
	
}
function isLoggedIn(){
	return !stopFetching;
}

function login(firstLoginFailed){
	isclosing=false;
	incorrectlogin=false;
	if(firstLoginFailed==false) loginFailedTimes=0;
	if(logintype=="token"){loginWithToken(firstLoginFailed); return;}
	if(logintype=="anonymous"){loginAsAnonymous(firstLoginFailed); return;}
	if(logintype=="password"){loginWithPassword(firstLoginFailed); return;}
	return;
}

function loginAsAnonymous(firstLoginFailed) {
	loggedin==false;
	stopFetching=false;
	isloggingout=false;
	if(firstLoginFailed==false) loginFailedTimes=0  //Reset login fail counter on manual login
	
	if (loginformcode=="") loginformcode=getElement("MessagesHistoryText").innerHTML;
	if (mystatuscode=="") mystatuscode=getElement("MyStatus").innerHTML;
	
	if(getElement("LoginProgress").innerHTML.indexOf("loginRetry")==-1){
		getElement("LoginProgress").innerHTML="<br><img src=\"waiting.gif\"> Logging in...<br><br>";
		showElement("LoginProgress");
	}
	
	sessionid=tmpsessionid;
	//save myloginpassword as variable because the password-type field looses it's value on submit event
	if(firstLoginFailed==false) {
		myloginpassword=escape(getElement("loginpassword").value);
	}
	parameters='type=loginanonymous&stusername='+
	escape(getElement("loginname").value)+'&stpassword='+myloginpassword;
	if(getbuddies==false) parameters=parameters+'&nobuddies=yes';
	loginretryparameters=parameters;
	makeAsyncRequest(parameters);
}
   
function loginWithPassword(firstLoginFailed) {
	loggedin==false;
	stopFetching=false;
	isloggingout=false;
	if(firstLoginFailed==false) loginFailedTimes=0  //Reset login fail counter onmanual login
	
	if (loginformcode=="") loginformcode=getElement("MessagesHistoryText").innerHTML;
	if (mystatuscode=="") mystatuscode=getElement("MyStatus").innerHTML;
	
	getElement("LoginProgress").innerHTML="<br><img src=\"waiting.gif\"> Logging in...<br><br>";
	showElement("LoginProgress");
	
	sessionid=tmpsessionid;
	//save myloginpassword as variable because the password-type field looses it's value on submit event
	if(firstLoginFailed==false) {
		myloginpassword=escape(getElement("loginpassword").value);
		myloginusername=escape(getElement("loginname").value);
	}
	parameters='type=login&stusername='+myloginusername+'&stpassword='+myloginpassword;
	if(getbuddies==false) parameters=parameters+'&nobuddies=yes';
	loginretryparameters=parameters;
	makeAsyncRequest(parameters);
}

function loginWithToken(firstLoginFailed) {
	loggedin==false;
	stopFetching=false;
	isloggingout=false;
	if(firstLoginFailed==false) loginFailedTimes=0  //Reset login fail counter onmanual login
	
	if (loginformcode=="") loginformcode=getElement("MessagesHistoryText").innerHTML;
	if (mystatuscode=="") mystatuscode=getElement("MyStatus").innerHTML;
	
	getElement("LoginProgress").innerHTML="<br><img src=\"waiting.gif\"> Logging in...<br><br>";
	showElement("LoginProgress");
	
	sessionid=tmpsessionid;
	myloginpassword="";myloginusername="";
	
	if(ssoname=="") ssoname=escape(getElement("loginname").value);
	parameters='type=logintoken&token='+token+'&stusername='+ssoname+'&stpassword='+myloginpassword;
	if(getbuddies==false) parameters=parameters+'&nobuddies=yes';
	loginretryparameters=parameters;
	makeAsyncRequest(parameters);
}

function getElement(elementname){
	if(!browser_ppc){return document.getElementById(elementname);
	}else{return elementname}
	
}

function hideElement(elementname){
	elm=getElement(elementname);
	if(elm) elm.style.display="none";
}

function showElement(elementname){
	elm=getElement(elementname);
	if(elm) elm.style.display="block";
}

function sendmessage() {
	if (!isLoggedIn()){
		alert(notloggedin_message);
		return;
	}
	if(getRecipient()==""){
		alert("Please select a person to send message to.");
		return;	
	}
	setRecipient(getRecipient());  //set recipient to currently chosen name in list in case buddylist could not correctly set the autochat name
	parameters='mysession='+sessionid+'&type=message&sendto='+
	escape(getNameByAlias(getRecipient()))+'&message='+replaceReservedChars(document.getElementById("widgetmessagetext").value);
	timeNowTxt=getCurrentTime(); 
	addToCurrentMessagesPanel("<font color=green><b>"+timeNowTxt+" <i>You: "+
	"</i></b>"+replaceSpecialChars(getElement("widgetmessagetext").value)+"</font><br>");
	smartstepscnt=0;
	smartloopscnt=0;
	
	if(xtramode=="bot"){
		delayms=delaymsbotactive; //reset longer wait time to shorter in order to quickly get bot's response
		clearTimeout(lastTimerId); //abort previous fetch request and issue a new request with shorter fetch interval
		makeAsyncRequestOnce(parameters);
		fetchData(true);
	}else if(fetchmode=="smartfetch"){
		delayms=smartfetchdelayms; //*smartfetchinc*smartstepscnt; //reset longer wait time to shorter in order to quickly get bot's response
		clearTimeout(lastTimerId); //abort previous fetch request and issue a new request with shorter fetch interval
		makeAsyncRequestOnce(parameters);
		fetchData(true);	
	}else{
		makeAsyncRequestOnce(parameters);
	}
	if(clearonsend==true) getElement("widgetmessagetext").value="";
}

function logout(showwarning) {
	if (!isLoggedIn()){
		if(showwarning==true){alert(notloggedin_message);}
		return;
	}
	hideBuddyWindow();
	clearVariables();
	parameters='mysession='+sessionid+'&type=logout';
	sessionid=tmpsessionid;
	isloggingout=true;
	resp=makeAsyncRequestOnce(parameters);
	sessionid=tmpsessionid; //"00000000000000000000";
	if(logoutWaitResponse==true) {
		addToCurrentMessagesPanel("<font color=red><b>Logging out...</b></font><br>");
	}else{
		handleLOGGEDOUT("operation succeeded", "operation succeeded")
	}
	hidemenu();
}

function resetLoggingout(){
 isloggingout=false;
}

function clearVariables(){

}
function toProperCase(s)
{
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
          function($1) { return $1.toUpperCase(); });
}
function ProcessBuddy(buddydata){  //FormatBuddyList
username=buddydata.substring(0,buddydata.indexOf("$|$"));
if(usealiases==true)username=getAliasByName(username);
propcasebuddy=toProperCase(buddydata.substring(0,buddydata.indexOf("$|$")));
payload=buddydata.substring(buddydata.lastIndexOf("$|$")+3, buddydata.length);
userstatus=getProperUserStatus(payload.substring(0,payload.indexOf("(")).replace(/^\s*|\s*$/g,""));
if(userstatus=="UNKNOWN" && buddiesArray[propcasebuddy+"_status"]!=undefined){
	return ""; //do not set temporary status to "Unknown" if it was already set to real status
}else if(userstatus==buddiesArray[propcasebuddy+"_status"]){
	return ""; //no status change was detected
}

if(typeof(buddiesArray[propcasebuddy+"_msgcounter"])=="undefined") buddiesArray[propcasebuddy+"_msgcounter"]=0;
if(typeof(buddiesArray[propcasebuddy+"_messages_0"])=="undefined")	buddiesArray[propcasebuddy+"_messages_0"]="";

buddiesArray[propcasebuddy+"_status"]=userstatus;
if(usealiases==true)buddiesArray[username+"_status"]=userstatus;
	buddypos=getPositionInBuddyList(getAliasByName(username));
	blElem=document.getElementById("selectbuddy");
	if(buddypos==-1){
	buddypos=blElem.options.length;
	blElem.options[blElem.options.length] = new Option(username,username);
	}
	if(buddypos!=-1){
		switch (userstatus)
  			{
    			case "ACTIVE": {blElem[buddypos].className="BuddyStatusActive";if(showtextstatus==true) blElem[buddypos].text=username+" (online)" ; break }
				case "AWAY": { blElem[buddypos].className="BuddyStatusAway";if(showtextstatus==true) blElem[buddypos].text=username+" (away)" ; break }
				case "DND": { blElem[buddypos].className="BuddyStatusDND";if(showtextstatus==true) blElem[buddypos].text=username+" (dnd)"; break }
				case "ACTIVEMOBILE":case "ACTIVE MOBILE": { blElem[buddypos].className="BuddyStatusMobile";if(showtextstatus==true) blElem[buddypos].text=username+" (mobile)" ; break }
				case "MOBILE": {blElem[buddypos].className="BuddyStatusMobile";if(showtextstatus==true) blElem[buddypos].text=username+" (mobile)"; break}
				case "OFFLINE": if(!status_onlineonly){blElem[buddypos].className="BuddyStatusOffline";if(showtextstatus==true) blElem[buddypos].text=username+" (offline)" } break
				case "UNKNOWN": if(!status_onlineonly){blElem[buddypos].className="BuddyStatusUnknown";if(showtextstatus==true) blElem[buddypos].text=username+" (unknown)" } break
				case "NOTUSING":case "NOT USING": { blElem[buddypos].className="BuddyStatusNotusing";if(showtextstatus==true) blElem[buddypos].text=username+" (not using)" ; break }
	
				default: if(!status_onlineonly){ 
				blElem[buddypos].className="BuddyStatusUnknown";
				if(showtextstatus==true) blElem[buddypos].text=username+" (unknown)";}	break
  			} //switch
	}
	if(showiconstatus==true && getElement("BuddyListIcon")!=null && (getElement("selectbuddy").value==propcasebuddy || getElement("selectbuddy").value==username)){
		var lookname=propcasebuddy;
		if (getElement("selectbuddy").value==propcasebuddy){lookname=propcasebuddy}else{lookname=username}
		lookname=username;
		imgname=getProperStatusIcon(buddiesArray[lookname+"_status"].toLowerCase());
		getElement("BuddyListIcon").innerHTML="<img width=\"14\" height=\"14\" src=\"icon_"+imgname+".gif\" title=\"User's online status: "+toProperCase(buddiesArray[lookname+"_status"])+"\">";
	}
	listSort(blElem);
	if(autoBuddyIsSet==false && propcasebuddy.toLowerCase().indexOf(autochatpartner.toLowerCase())>-1){
		autoBuddyIsSet=true; 
		setTimeout("sendInitialMessage()",1500);  //wait 1.5 sec before sending message, otherwise visual status is not getting set properly
	}
	return "";
}
function ProcessBuddyList(buddylist){  //FormatBuddyList
	return "";
}
function sendInitialMessage(){
	autoBuddyIsSet=true; 
	setSelectedBuddyListUser(autochatpartner);
	if(automessagesend==true) sendmessage();
}
function handleBuddy(text){
	if (text.indexOf(">"+lastselectedbuddy+"<")>-1){
		text=text.replace("<option ", "<option selected ");
	}else{
		if (text.indexOf("<option selected")>-1) text=text.replace("<option selected ", "<option ");
	}
	buddylistcode=buddylistcode+text+"\n";
}
function handleSelectedBuddyChange(){
	lastselectedbuddy=document.getElementById("selectbuddy").value;
	setRecipient(document.getElementById("selectbuddy").value);
	if(typeof(buddiesArray[lastselectedbuddy+"_status"])=="undefined") return;
	if(showiconstatus==true && getElement("BuddyListIcon")!=null) getElement("BuddyListIcon").innerHTML="<img width=\"14\" height=\"14\" src=\"icon_"+getProperStatusIcon(buddiesArray[lastselectedbuddy+"_status"].toLowerCase())+".gif\" title=\"User's online status: "+toProperCase(buddiesArray[lastselectedbuddy+"_status"])+"\">";
	
}
function getCurrentTime(){
	timeNow = new Date();
	thours=("0"+timeNow.getHours());
	tminutes=("0"+timeNow.getMinutes());
	if(thours.length==2){thours=thours.substring(0,2)} else {thours=thours.substring(1,3)}
	if(tminutes.length==2){tminutes=tminutes.substring(0,2)} else {tminutes=tminutes.substring(1,3)}
	return thours+":"+tminutes;
}
function FormatHistory(msghistory){
	
	var msg_array=msghistory.split("<BR>");
	
	messages="";
	var i=0;
	for(i=0; i<=msg_array.length-1;i++){
		current_message=msg_array[i];
		user=current_message.substring(0,current_message.indexOf("$|$"));
		user=getAliasByName(user);
		msg=current_message.substring(current_message.lastIndexOf("$|$")+3, current_message.length);
		if (user+msg!="") {
			timeNowTxt=getCurrentTime();
			if(user=="SYSTEM"){
				messages=messages+"<span class=\"systemmsg\">"+replaceSpecialChars(msg)+"</span><BR>";
			}else{				
				if(user.indexOf(" ")==-1)firstname=user; else firstname=user.substring(0, user.indexOf(" "));
				if(user.indexOf("/")==-1)firstname=user; else firstname=user.substring(0, user.indexOf("/"));
				if(user.indexOf(",")==-1)firstname=user; else firstname=user.substring(0, user.indexOf(","));
				if(convertlinks==true){
					var httpPrefix="";
					var linkStart=msg.toLowerCase().indexOf("http://");
					if(linkStart==-1){linkStart=msg.toLowerCase().indexOf("www.");httpPrefix="http://"}
					if(linkStart>-1){
						var linkEnd=msg.indexOf(" ",linkStart);
						if(linkEnd==-1) linkEnd=msg.length;
						msg=msg.substring(0,linkStart)+"<a href=\"#\" title=\""+httpPrefix+msg.substring(linkStart, linkEnd)+"\" onClick=\"window.open('"+httpPrefix+msg.substring(linkStart, linkEnd)+"','_blank');return false;\">Link</a>"+msg.substring(linkEnd, msg.length);
					}
				}
				replaceSpecialChars(msg);
				if (msg.indexOf("Announcement:")==0){
					messages=messages+"<span title=\"Announcement from "+user+"\" class=\"annfrom\">"+timeNowTxt+" "+firstname+": </span><span class=\"anncolor\">"+msg+"</span><BR>";
				}else{
					messages=messages+"<span title=\"Message from "+user+"\" class=\"msgfrom\">"+timeNowTxt+" "+firstname+": </span>"+msg+"<BR>";
				}
			}
		}
	}
	return "<span class=\"msgcolor\">"+messages+"</span>";
}
function switchToBuddy(buddyname){
}
function addToBuddyList(buddyname){
}
function addToCurrentAnnouncementsPanel(text){
	addToCurrentMessagesPanel(text, 2)
}
function addToCurrentMessagesPanel(text, mtype){
	if(mtype==null) mtype=1;
	//1=Message, 2=Announcement, 3=Admin message, 4=Other, 0=Other
	if(mtype==3){
		addToMessagesPanel(currentchatpartner, "<span class=\"adminmsg\">Message from administrator:<BR>"+text+"</span>", mtype); 
		return;
	}
	if (mtype==2){
		mtypestr="announcement";
	}else if (mtype==3){
		mtypestr="administrator message";
	}else{		
		mtypestr="message";
	}

	usernamePos=text.indexOf("<span title=\"Message from ");
	if (usernamePos>-1){
		msgfrom=text.substring(usernamePos+26, text.indexOf("\"", usernamePos+26));
	}
	else{
		msgfrom=currentchatpartner;
	}
	if(usernamePos==-1){
	usernamePos=text.indexOf("<span title=\"Announcement from ");
	if (usernamePos>-1){
		msgfrom=text.substring(usernamePos+31, text.indexOf("\"", usernamePos+31));
	}
	else{
		msgfrom=currentchatpartner;
	}
	}
	//msgfrom=getNameByAlias(msgfrom);
	if(msgfrom!=currentchatpartner) {
		addToMessagesPanel(currentchatpartner, "New "+mtypestr+" from <a href=\"#\" onclick=\"setRecipient('"+msgfrom+"');handleSelectedBuddyChange()\">"+msgfrom+"</a><br>", mtype); //javascript: void(setRecipient('"+msgfrom+"'))\">"+msgfrom+"</a><br>
	}
	if (mtype==2) text=text.replace("<span title=\"Message from ", "<span title=\"Announcement from ");
	addToMessagesPanel(msgfrom, text, mtype);
}
function addNewTempUserToBuddyListMenu(user){
	var elem=document.getElementById("selectbuddy");
	if(user!="")elem.options[elem.options.length] = new Option(user,user);
}
function addToAllMessagesPanel(text){
	if (text.indexOf("<BR>")<text.length-3 && text.indexOf("<br>")<text.length-3){
		text=text+"<BR>";
	}
	addToMessagesPanel(currentchatpartner, text, 1)
}
function addToAdminMessagesPanel(text){
	if (text.indexOf("<BR>")<text.length-3 && text.indexOf("<br>")<text.length-3){
		text=text+"<BR>";
	}
	addToCurrentMessagesPanel(text, 3)
}
function addToMessagesPanel(user, text, mtype){
	var tmp="";
	if(typeof(buddiesArray[user+"_msgcounter"])=="undefined") buddiesArray[user+"_msgcounter"]=1;
	if(buddiesArray[user+"_msgcounter"]==0) buddiesArray[user+"_msgcounter"]=1;
	
	for(i=1;i<=maxmsg+1;i++){
		if(typeof(buddiesArray[user+"_messages_"+i])=="undefined")	buddiesArray[user+"_messages_"+i]="";
	}
	
	if(buddiesArray[user+"_msgcounter"]<=maxmsg){
		buddiesArray[user+"_messages_"+buddiesArray[user+"_msgcounter"]]=text;
	}else{
		buddiesArray[user+"_messages_"+(maxmsg+1)]=text;
		for(i=1;i<=maxmsg;i++){ 
			buddiesArray[user+"_messages_"+i]=buddiesArray[user+"_messages_"+(i+1)];
		}
	}
	buddiesArray[user+"_msgcounter"]=buddiesArray[user+"_msgcounter"]+1;
	if(buddiesArray[user+"_msgcounter"]>(maxmsg+1))buddiesArray[user+"_msgcounter"]=maxmsg+1;
	
	elem=getElement("MessagesHistoryText");
	if(limitshownmessages==true){
		tmpmsg="";
		for(i=1; i<=maxmsg; i++){ 
			if(buddiesArray[user+"_messages_"+i]!="")tmpmsg=tmpmsg+buddiesArray[user+"_messages_"+i]
		}
		if(user==currentchatpartner)elem.innerHTML=tmpmsg;
	}else{
		if(user==currentchatpartner)elem.innerHTML=elem.innerHTML+text;
	}

	//scroll to the bottom of the panel to see the last added messages
	if(!browser_ppc){elem.scrollTop = elem.scrollHeight;}
	
}

function showBuddyMessages(user){
	tmpmsg="";
	for(i=1;i<=maxmsg;i++){
		if(typeof(buddiesArray[user+"_messages_"+i])!="undefined" && buddiesArray[user+"_messages_"+i]!="")tmpmsg=tmpmsg+buddiesArray[user+"_messages_"+i];
	}
	if(getElement("MessagesHistoryText").innerHTML.indexOf("login(false); return false")>-1){
			getElement("MessagesHistoryText").innerHTML=tmpmsg+getElement("MessagesHistoryText").innerHTML;
	}else{
			getElement("MessagesHistoryText").innerHTML=tmpmsg;
	}	
	if(setFocusToInput==true && getElement("InputPanel").style.display=="block")getElement("widgetmessagetext").focus();
}

function addToBuddyListPanel(text){
	lastbuddylist=text;	
	ProcessBuddyList(text);
}

function replaceSpecialChars(text){
	if (allowjs==false){   //replace Script and Javascript tags
		text=text.replace(/<s/g,"&lt;s");
		text=text.replace(/<S/g,"&lt;S");
		text=text.replace(/<j/g,"&lt;j");
		text=text.replace(/<J/g,"&lt;J");
	}
	if (allowhtml==false) {
	//replace HTML tags
		text=text.replace(/</g,"&lt;");
		text=text.replace(/>/g,"&gt;");
		text=text.replace(/\n/g,"<br>");
		text=text.replace(/\\\"/g,"\"");
	}
	return text;
}

function replaceReservedChars(text){
	text=text.replace(/%/g,"%25");
	text=text.replace(/&/g,"%26");
	text=text.replace(/\+/g,"%2B");
	return text;
}

function getRecipient(){
	return document.getElementById("selectbuddy").value; 
}

function setRecipient(username){
	lastselectedbuddy=username;
	getElement("SendToUser").innerHTML=username;
	currentchatpartner=username;
	showBuddyMessages(username);
	setSelectedBuddyListUser(username);
}
function setSelectedBuddyListUser(username){
	var userpos=getPositionInBuddyList(username);
	if (userpos==-1) {
		addNewTempUserToBuddyListMenu(username);
	}else{
		var blElem=document.getElementById("selectbuddy");
		if(blElem.selectedIndex!=userpos) blElem.selectedIndex=userpos;
	}
}

function getPositionInBuddyList(username){
	var userpos=-1;
	var blElem=document.getElementById("selectbuddy");
	if(blElem){
		if (blElem.selectedIndex>-1 && blElem[blElem.selectedIndex].value==username) userpos=blElem.selectedIndex;	
		if (blElem.selectedIndex>-1 && blElem[blElem.selectedIndex].value!=username){
		var x;
		for(x=0;x<blElem.length; x++){
			if(blElem[x].value==username){
				userpos=x;				
				lastselectedbuddy=username;				
			}
		}
	}
	}
	return userpos;
}

function changeMyStatus(newstatus){	
	if (!isLoggedIn()){
		alert(notloggedin_message);
		return;
	}
	mystatus=newstatus; 
	parameters='mysession='+sessionid+'&type=changestatus&status='+mystatus;
	//parameters=default_parameters;
	makeAsyncRequestOnce(parameters);
	
}
function addNewRecipient(){
	if (!isLoggedIn()){
		alert(notloggedin_message);
		return;
	}
	showBuddyWindow();
}
function acceptNewBuddy(){
	if (!isLoggedIn()){
		alert(notloggedin_message);
		return;
	}
	var name = document.getElementById('newbuddyname').value;
	if(name==null || name=="") {alert("Please enter a name");return;}
	hideBuddyWindow();
	parameters='mysession='+sessionid+'&type=addnewbuddy&buddyname='+name;
	makeAsyncRequestOnce(parameters);
}

function switchBuddyList(){
	elem=getElement("buddyswitcher");
	if(status_onlineonly==true){
		elem.innerHTML=elem.innerHTML.replace("collapsed", "expanded");
		elem.innerHTML=elem.innerHTML.replace('alt="'+showallbuddies_tip+'"', 'alt="'+showonlinebuddies_tip+'"');
		elem.innerHTML=elem.innerHTML.replace('title="'+showallbuddies_tip+'"', 'title="'+showonlinebuddies_tip+'"');
		status_onlineonly=false;
		addToBuddyListPanel(lastbuddylist);
	}
	else{
		elem.innerHTML=elem.innerHTML.replace("expanded", "collapsed");
		elem.innerHTML=elem.innerHTML.replace('alt="'+showonlinebuddies_tip+'"', 'alt="'+showallbuddies_tip+'"');
		elem.innerHTML=elem.innerHTML.replace('title="'+showonlinebuddies_tip+'"', 'title="'+showallbuddies_tip+'"');
		status_onlineonly=true;
		addToBuddyListPanel(lastbuddylist);
	}
}

function switchMessagesView(){
	elem=getElement("messagesswitcher");
	if(limitshownmessages==false){
		elem.innerHTML=elem.innerHTML.replace("expanded", "collapsed");		
		elem.innerHTML=elem.innerHTML.replace('alt="'+showlast10msg_tip+'"', 'alt="'+showallmsg_tip+'"');
		elem.innerHTML=elem.innerHTML.replace('title="'+showlast10msg_tip+'"', 'title="'+showallmsg_tip+'"');
		limitshownmessages=true;
		elem=getElement("MessagesHistoryText");
		tmpmsg="";
		for(i=0; i<=9; i++){
			if(msg_array[i]!="")tmpmsg=tmpmsg+msg_array[i];
		}
		elem.innerHTML=tmpmsg;
		if(!browser_ppc){elem.scrollTop = 0}
	}
	else{		
		elem.innerHTML=elem.innerHTML.replace("collapsed", "expanded");
		elem.innerHTML=elem.innerHTML.replace('alt="'+showallmsg_tip+'"', 'alt="'+showlast10msg_tip+'"');
		elem.innerHTML=elem.innerHTML.replace('title="'+showallmsg_tip+'"', 'title="'+showlast10msg_tip+'"');
		limitshownmessages=false;
	}
}

function addToOutgoingQueue(parameters){
	//called from makeAsyncRequestOnce function
	out_queue_cnt++;
	out_queue[out_queue_cnt]=parameters;
	
}
function getFirstFromOutgoingQueue(){
	if(out_queue_cnt<=0){
		out_queue_cnt=0;
		return null;	
	}
	var i=0;
	var answer=out_queue[0];
	for(i=0;i<out_queue_cnt-1; i++){
		out_queue[i]=out_queue[i+1];
	}
	out_queue_cnt--;
	return answer;
}

function hideNonPasswordElements(){
	hideElement("usernameAnonymous");
	hideElement("loginButtonAnonymous");
	showElement("loginButtonPassword");
	showElement("usernamePassword");
	showElement("usernamePassword");
	showElement("loginname");
	showElement("passwordPassword");
	showElement("loginpassword");
	showAddBuddyButton=true;
	if(xtramode=="helpdesk")showAddBuddyButton=false;
	
}
function hideNonTokenElements(){
	hideElement("usernameAnonymous");
	hideElement("usernamePassword");
	hideElement("loginname");
	hideElement("loginpassword");
	hideElement("passwordPassword");
	hideElement("loginButtonPassword");
	showElement("loginButtonAnonymous");
	showAddBuddyButton=true;
	if(xtramode=="helpdesk")showAddBuddyButton=false;
	
}
function hideNonAnonymousElements(){
	hideElement("usernamePassword");
	hideElement("usernamePassword");
	hideElement("passwordPassword");
	hideElement("loginpassword");
	hideElement("loginButtonPassword");
	showElement("loginButtonAnonymous");
	showElement("usernameAnonymous");
	if(hideanonname==true)hideElement("usernameAnonymous");
	if(hideanonname==true)hideElement("loginname");
	
}

function displayRightLoginForm(){
	if(navigator.userAgent.indexOf('iPhone')>-1){
		adjustOrientationGUI();
		hide_addressbar();
	}
	watchHttpObjects();
	revertnames(); 
	if(logintype=="password") hideNonPasswordElements();
	if(logintype=="anonymous") hideNonAnonymousElements();
	if(logintype=="token") hideNonTokenElements();	
	if(automessage!="") setMessageText(automessage);
	if (autologin==true) login(false);
}

function handleUnload(){
	if (isLoggedIn() && isloggingout==false){
		isclosing=true;
		if(httpobj!=null)httpobj.abort();
	}
}
function getMessageText(){
	return escape(document.getElementById("widgetmessagetext").value);
}
function setMessageText(msgtext){
	document.getElementById("widgetmessagetext").value=msgtext;
}
function getURLParam(name){
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return UTF8Decode(unescape(results[1]));
	
}
var hrc=0;
var hrt;
function watchHttpObjects(){
if(typeof(http_arequest)=="object"){	
	if(http_arequest.readyState==0) {		
	//	makeAsyncRequest("");
	}
}
hrc++;
//hrt=setTimeout("watchHttpObjects()",5000)
}
function getProperStatusIcon(buddystatus){
	var imgname=buddystatus.replace(" ","").replace("+","");
	if(imgname.indexOf("$-")!=-1) imgname=imgname.substring(imgname.lastIndexOf("$-")+2, imgname.length);
	if(imgname.indexOf("$")!=-1) imgname=imgname.substring(imgname.lastIndexOf("$")+1, imgname.length);
	return imgname;
}
function getProperUserStatus(buddystatus){
	var statusname=buddystatus.replace(" ","").replace("+","");
	if(statusname.indexOf("$-")!=-1) statusname=statusname.substring(statusname.lastIndexOf("$-")+2, statusname.length);
	if(statusname.indexOf("$")!=-1) statusname=statusname.substring(statusname.lastIndexOf("$")+1, istatusname.length);
	return statusname;
}
function checkEnterSubmit2(){
	return true;
}
function checkEnterSubmit(ev){ //check if Enter key must submit the message
	if(submitonenter==true){
	var keyCode = window.event ? ev.keyCode : ev.which;
	if(keyCode==13) {
			sendmessage();
			return false;
		}
	}
	return true;
}
function checkLoginSubmit(ev){
var keyCode = window.event ? ev.keyCode : ev.which;
	if(keyCode==13) {
		if(logintype=="anonymous") document.all.loginButtonAnonymous.click();
		if(logintype=="password") document.all.loginButtonPassword.click();
		return false;
	}
	return true;
}
function UTF8Decode (utftext) {
	//if (true) return utftext;
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}
	
	function UTF8Encode (pstring) {
		if(true) return pstring;
		pstring = pstring.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < pstring.length; n++) {

			var c = pstring.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	}
	
/*
var rcmessage="Right-click is not allowed.";
function clickIE4(){
if (event.button==2){
alert(rcmessage);
return false;
}
}

function clickNS4(e){
if (document.layers || document.getElementById && !document.all){
if (e.which==2||e.which==3){
alert(rcmessage);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(rcmessage);return false;")
*/
function getToken(tokenname){  
	tmptoken=document.cookie+"&";
	tokpos=tmptoken.indexOf(tokenname);
	tokpos2=tmptoken.indexOf( "&", tokpos+1);
	if(tokpos>-1){
		token=tmptoken.substring(tokpos+tokenname.length+1,tokpos2);
		if(token.indexOf(";")>-1) token=token.substring(0,token.indexOf(";"));
		return token;
	}else{
		return "";
	}
}
function hideBuddyWindow()
	{	
		document.getElementById('selectbuddy').style.display="inline";
		document.getElementById('useraddwindow').style.display="none";
		document.getElementById('newbuddyname').value="Firstname Lastname"; //reset name to default
		//document.getElementById('coverit').style.display="none";
	}	

function showBuddyWindow()
	{
		//document.getElementById('coverit').style.display="block";
		document.getElementById('selectbuddy').style.display="none";
		document.getElementById('useraddwindow').style.display="block";
	}
function checkBuddySubmit(ev){ //check if Enter key must submit the message
var keyCode = window.event ? ev.keyCode : ev.which;
if(keyCode==13) { //window.event && window.event.keyCode
		acceptNewBuddy();
		return false;
	}
	return true;
}
function processPublicGroupMember(resp){
	var users="";
	var group="";
	var user;
	return;
	group=resp.substring(0,current_message.indexOf("$|$"));
	users=resp.substring(current_message.lastIndexOf("$|$")+3, resp.length);
	usersarr=users.split(",");
	for(x=0;x<usersarr.length;x++){		
	user=usersarr[x];
	if(buddiesArray[user+"_status"]==null) buddiesArray[user+"_status"]="UNKNOWN()";
	if(groupsArray[group+"_users"]==null){
		groupsArray[group+"_users"]=user;
	}else{
		groupsArray[group+"_users"]=buddiesArray[group+"_users"]+","+user;
	}
	}
}
function processPrivateGroupMember(resp){
	var users="";
	var group="";
	var user;
	return;
	group=resp.substring(0,current_message.indexOf("$|$"));
	users=resp.substring(current_message.lastIndexOf("$|$")+3, resp.length);
	usersarr=users.split(",");
	for(x=0;x<usersarr.length;x++){		
	user=usersarr[x];
	if(buddiesArray[user+"_status"]==null) buddiesArray[user+"_status"]="UNKNOWN()";
	if(groupsArray[group+"_users"]==null){
		groupsArray[group+"_users"]=user;
	}else{
		groupsArray[group+"_users"]=buddiesArray[group+"_users"]+","+user;
	}
	}
}

function updateAliasMapping(resp){
return;
	var alias="";
	var user;
	alias=resp.substring(0,resp.indexOf("$|$"));
	user=resp.substring(resp.lastIndexOf("$|$")+3, resp.length);
	
	updateAliasesInBuddyList(alias, user);
}

function updateAliasesInBuddyList(alias, user){
return;
var userpos=-1;
	var blElem=document.getElementById("selectbuddy");
	if(blElem){
		if (blElem.selectedIndex>-1 && blElem[blElem.selectedIndex].value==username) userpos=blElem.selectedIndex;	
		if (blElem.selectedIndex>-1 && blElem[blElem.selectedIndex].value!=username){
		var x;
		for(x=0;x<blElem.length; x++){
			if(blElem[x].value==alias){
				userpos=x;	
				break;
			}
		}
	}
	}
	if(userpos==blElem.selectedIndex){
		//change status icon	
		buddiesArray[user+"_status"]=buddiesArray[getNameByAlias(alias)+"_status"];
	}else if (userpos>-1){
		buddiesArray[user+"_status"]=buddiesArray[getNameByAlias(alias)+"_status"];
	}
	nameAliases[getNameByAlias(alias)]=null;
	nameAliases[user]=alias;
}

function listSort(idGiven) { 
var lb=idGiven; 
var oldValue; 
try { 
oldValue = lb[lb.selectedIndex].value; 
	arrTexts = new Array(); 
	for(i=0; i<lb.length; i++) { 
		arrTexts[i] = lb.options[i].text+':'+lb.options[i].value+':'+lb.options[i].className; 
	} 
	arrTexts.sort(); 
	for(i=0; i<lb.length; i++) { 
		el = arrTexts[i].split(':'); 
		lb.options[i].text = el[0]; 
		lb.options[i].value = el[1]; 
		lb.options[i].className = el[2];
		if(oldValue == lb.options[i].value){
			lb.options[i].selected = true;
		}else{
			lb.options[i].selected = false; 
		}
	} 	
}catch(e) {
//In case of any error, dont do anything. 
lb=idGiven; 
} 
}

