/*
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.
*/

function handleBUDDYLIST(resp,resprest){
	if(resprest.length>0) {
		if(resprest=="BUDDYLIST_FAILED" ){  //&& resprest!="BUDDYLIST_COMPLETED"
	//		getElement("BuddyListText").innerHTML="";		
		}else{
			addToBuddyListPanel(resprest);	
		}
		if(buddylistfetched==true && autoBuddyIsSet==false){
			if(resprest.indexOf(autochatpartner)>-1){autoBuddyIsSet=true; setSelectedBuddyListUser(autochatpartner);
			if(automessagesend==true) sendmessage();
			}
		}
		
		if(resprest.indexOf("$BUDDYLIST_COMPLETED$")>-1 || resprest=="BUDDYLIST_FAILED"){
			//addToMessagesPanel(resprest+"<br>");  //debug buddy list
			if(buddylistfetched==false && autoaddbuddies!="" ){  // The original buddylist was fetched, now we can add autobuddy users
				buddylistfetched=true;
				parameters='mysession='+sessionid+'&type=addnewbuddy&buddyname='+autoaddbuddies+'&autobuddy=yes';
				makeAsyncRequestOnce(parameters);
			}  // if(buddylistfetched==false){ 
		}
	}
}

function handleBUDDY(resp,resprest){   // buddy's status changed on server
	if(resprest.length>0) {
		//if (getPositionInBuddyList(resprest)==-1) ProcessBuddy(resprest);
		ProcessBuddy(resprest);
	}
}

function handleSYSTEM(resp,resprest){ //System messages 

	if(resp.indexOf("$|$000111000$|$")>-1 || resp.indexOf("$|$000222000$|$")>-1){
		stopFetching=true;
	}
	if(resprest.length>0) addToCurrentMessagesPanel(FormatHistory(resprest));
	getElement('BuddyListText').innerHTML="";
	sessionid=tmpsessionid;//"00000000000000000000";
	return;  
} 

function handleMYSTATUS(resp,resprest){   // my status changed on server

	if(resprest.length>0) showMyCurrentStatus(resprest);
}


function handleSETUSER(resp,resprest){   // my status changed on server
	if(resprest.length>0) {setSelectedBuddyListUser(resprest); setRecipient(resprest)}
}

function handleADMIN(resp,resprest){   //Messages from Admin. not implemented yet.
	if(resprest.length>0) addToAdminMessagesPanel(resprest);
}

function handleRELOGIN(resp,resprest){    //Automatic re-login not implemented. User is simply logged out and must login again manually.
	if(resprest.length==32) {
		//alert("re-logging in");
		addToAllMessagesPanel(reloggedin_message+"<br>");
		sessionid=resprest;
		relogin=true;
	}
}

function handleMESSAGES(resp,resprest){   // Received messages from users
	if(resprest.length>0) {
	smartstepscnt=0;
	smartloopscnt=0;
	if(fetchmode=="smartfetch") delayms=smartfetchdelayms;
	if(xtramode=="bot") delayms=delaymsbotidle; //bot's response received, reset fetch time to longer interval
	addToCurrentMessagesPanel(FormatHistory(resprest.replace("Announcement:", " Announcement:")));
if (blinkOnMessage==true) startPanelColorBlinking();
		if(focusonmessage==true) {
			try{
				if (parent.window){
					parent.window.focus();
					if(setFocusToInput==true && getElement("widgetmessagetext"))getElement("widgetmessagetext").focus();
				}else{
					window.focus();
					if(setFocusToInput==true && getElement("widgetmessagetext"))getElement("widgetmessagetext").focus();
				}
			}
			catch(err)
			{
				//Handle errors here
			}
		}
	}
}
function handleANNOUNCEMENTS(resp,resprest){   // Received announcement from users
	if(resprest.length>0) {
		addToCurrentAnnouncementsPanel(FormatHistory(resprest));
		if(focusonmessage==true) {
			try{
				if (parent.window){
					parent.window.focus();
				}else{
					window.focus();
					}
			}
			catch(err)
			{
				//Handle errors here
			}
		}
	}
}
function handleNEWBUDDY(resp,resprest){   // Result of adding a new buddy
	if(resprest.length>0) {
	 	if(resprest=="OK"){
			addToAllMessagesPanel(newbuddyadded_message+"<br>");
		}else{addToCurrentMessagesPanel(newbuddyfailed_message+resprest+"</b></font><br>");}
	 }
}
function handlePUBLICGROUP(resp,resprest){   // Result of adding a new buddy
//alert("public group:"+resprest);
	if(resprest.length>0) {
	 	if(resprest=="OK"){
			//processPublicGroupMember(resprest);
		}else{
			processPublicGroupMember(resprest);
		}
	 }
}
function handlePRIVATEGROUP(resp,resprest){   // Result of adding a new buddy
//alert("private group:"+resprest);
	if(resprest.length>0) {
	 	if(resprest=="OK"){
			//processPrivateGroupMember(resprest);
		}else{
			processPrivateGroupMember(resprest);
		}
	 }
}

function handleALIAS(resp,resprest){   // Alias changed to belong to another person
	if(resprest.length>0) {
		updateAliasMapping(resprest);
	}
}

function handleMYNAME(resp,resprest){   // Result of adding a new buddy
	myname=resprest;
}

function handleLOGGEDOUT(resp,resprest){   // User has been logged out
	loginretryparameters="";


	//if(resprest=="host unreachable") resprest="Chat server is not responding";
	if(resprest=="operation succeeded"){
		resprest="Logged out successfully";
		if(loggedin==true){
			getElement("LoginProgress").innerHTML="<center><font color=\"orange\">"+resprest+"</font></center><br/>";
			showElement("LoginProgress");
		}
	}
	else{
		
		if(loggedin==true){ 
		
			addToAllMessagesPanel("<font color=red><b>Logged out ("+resprest+")</b></font><br>");
			getElement("LoginProgress").innerHTML="<font color=\"red\">"+resprest+"</font><br/>";
			showElement("LoginProgress");
		}
		else{
			return;
		}
					
	}
		
	
	loggedin=false;
	stopFetching=true;
	isloggingout=false;
	lastbuddylist="";
	buddylistfetched=false;
	sessionid=tmpsessionid;//"00000000000000000000";
	hideElement("BuddyListPanel");
	hideElement("BuddyListAdd");
	getElement("MessagesHistoryText").innerHTML=loginformcode;
	getElement("MyStatus").innerHTML=mystatuscode;
	getElement("widgetmessagetext").value="";
	hideElement("InputPanel");
	hideElement("LogoutButton");
	getElement("buddyselect").style.backgroundColor="#FFF8DC";
	buddiesArray=new Array(); //clear messages history
	myloginpassword=""; myloginusername="";	loginretryparameters="";
	incorrectlogin=true;
	if(navigator.userAgent.indexOf("MSIE")>-1){
		 hideElement("trbl");
	}else{
		if(getElement("trbl"))document.getElementById("trbl").style.display="none";
	}
	showElement("antitrbl");
	//getElement("MyStatus").innerHTML="";
	stopPanelColorBlinking();
}

function handleLOGGEDIN(resp,resprest){   // User has been logged in
	if(resprest.length>0) {
		ConsoleDump(resp);
		if(resprest.indexOf("is wrong")>-1) {loginretryparameters="";incorrectlogin=true;}
		if(resprest.indexOf("host unreachable")>-1) resprest="Chat server is not responding. Try again later.";
		sessionid=resprest;		
		if(sessionid.length==32 && loggedin==false) {
			loggedin=true;
			incorrectlogin=false;
			loginFailedTimes=0;
			loginretryparameters=""; myloginpassword=""; myloginusername="";
			if(autochatpartner!=null && autochatpartner!="") {
				setRecipient(autochatpartner);				
			}
			if(showBuddyList==true)showElement("BuddyListPanel");
			if(showAddBuddyButton==true)showElement("BuddyListAdd");
			showElement("InputPanel");
			hideElement("LoginInput");
			showElement("LogoutButton");	
			hideElement("LoginProgress");
			getElement("buddyselect").style.backgroundColor="#FFFF99";
			//addToMessagesPanel("<font color=\"green\"><b>Logged in to chat server</b></font><br>");
			default_parameters='mysession='+sessionid+'&type=fetch';
			runAfterLogin();
			
		}else{  //if(sessionid.length==32 && loggedin==false)
			loginFailedTimes++;
			//ConsoleDump("Failed times: "+loginFailedTimes);
			if(loginFailedTimes==1){  //Try to login once again, sometimes login fail for unknown reason
				//ConsoleDump("Failed to login the first time: "+resprest+" . Relogin.");
				getElement("LoginProgress").innerHTML="<br><img src=\"waiting.gif\"> "+firstLoginFailed_message+"<br><br>";
				showElement("LoginProgress");
				login(true);
				myloginpassword=""; myloginusername="";
				return;
			}
			
			stopFetching=true;
			//getElement("BuddyListText").innerHTML="";
			//ConsoleDump("sessionid: "+sessionid);
			
			getElement("LoginProgress").innerHTML="<br><font color=\"red\">"+sessionid+"</font><br><br>";
			showElement("LoginProgress");
			
		}  // sessionid.length==32
	}  // resprest.length>0
} //resptype=="LOGGEDIN"

function handleNEWSTATUS(resp,resprest){   // Response on MANUAL status change request
	if(resprest.length>0) {
		if(resprest=="OK"){
			if(showstatuschangesuccessmsg)addToAllMessagesPanel(statuschangedok_message+"<br>");
		}else{
			if(showstatuschangefailedsmsg)addToAllMessagesPanel(statuschangedfailed_message+"<br>");
		} //if(resprest=="OK")
	} //if(resprest.length>0)
}	//else if(resptype=="NEWSTATUS"){		
function ConsoleDump(aMessage) {
 //alert(aMessage);
}

function startPanelColorBlinking(){
	stopPanelColorBlinking();  //stop previous blinking if exists
	blinkInterval = setInterval("blinkPanel()",500);  //change color every 0.5 seconds
}

window.addEventListener("touchstart", "stopPanelColorBlinking()", false);
getElement("MessagesHistoryText").addEventListener("click", "stopPanelColorBlinking()", false);


function stopPanelColorBlinking(){

 if (blinkOnMessage==true && blinkInterval){
   clearInterval(blinkInterval);
   if(lastBlinkColor==blinkColor){
	lastBlinkColor="#FFF8DC";
	getElement("MessagesHistoryText").style.backgroundColor=lastBlinkColor;
    }
 }
}
function blinkPanel(){
  if(lastBlinkColor==blinkColor){
	lastBlinkColor="#FFF8DC";
  }else{
	lastBlinkColor=blinkColor;
  }
   getElement("MessagesHistoryText").style.backgroundColor=lastBlinkColor;
}

function hideOnConnectionBroken(){
	myloginpassword=""; myloginusername="";loginretryparameters="";
	//sessionid="";
	tmpsessionid="";
	buddylistfetched=false;
	buddiesArray=new Array(); //clear messages history
	getElement("buddyselect").style.backgroundColor="#FFF8DC";
	getElement("InputPanelHolder").style.backgroundColor="#FFF8DC";
	hideElement("LoginInput");
	hideElement("LoginProgress");
	hideElement("LogoutButton");
	hideElement("BudyListHolder");
	getElement("BuddyListPanel").innerHTML="";	
	getElement("ShowMyStatus").innerHTML="";
	hideElement("widgetmessagetext");
	hideElement("SendMessage");
	if(getElement("BuddyListText"))getElement("BuddyListText").innerHTML="";
	if(getElement("MyStatus"))getElement("MyStatus").innerHTML=""; //hideElement("MyStatus");
	getElement("MyStatus").style.backgroundColor="#FBF1C7";
	stopPanelColorBlinking();
}

function resetAll(){
//reset all variables to default
stopPanelColorBlinking();
hideOnConnectionBroken();
getElement("buddyselect").innerHTML="";
getElement("loginpassword").value="";
getElement("loginname").value="";
}

