
/**
 * @author Espre Team
 * @version 0.1
 */
/**
 * Include the script dynamically on the HTML page after creating the proper script tag on it
 * @return
 * @type
 * @param 	file Name as string, which need to be included dynamically
 */

 //declare the global variable
var statusResult=null;

var gUserId=null;
var addBuddyToGroupWindow=null;
var returnUsersInfo= null;
var currentPresenceStatus = null;
var ifTreeCreated = false ;

var forgotPassword = null;

var chatUserArray = new Array();

var loggedUserID = null;
var statusDivOpened = false ;
var palmtree = null ;
var smiliesFolder = WWWROOT+"/refimpl/images/smilies" ;
var imagesFolder = WWWROOT+"/refimpl/images" ;
var statusArr = new Array() ;
var posX;
var posY;
var arrGlobalTreeNodes = new Array() ;
var arrGlobalTreeChilds = new Array();
var rightMouseClick = false ;
var arrayUserName= new Array();
var isOnline=false;
var isCamHidden=true;

var presence_Obj = false;
var refreshPresence_Obj = false;
//var checkStatus=true;

var divBgChanged = null;

bV  = parseInt(navigator.appVersion);
bNS = navigator.appName=="Netscape"	 ;
bIE = navigator.appName=="Microsoft Internet Explorer" ;

 function createImageTag( strImageName )
 {
	return '<img src="'+imagesFolder+'/'+strImageName+'" border="0" width="20" height="20" />' ;	  
 }


function createStatusArr()
{

	try
	{
		
		var returnPresenceArray = new Array();
		var paramList = "userId:'1'";		

		var cont = new Controller('getPresenceDescriptions','PresenceManagementWidget',paramList);
		var returnPresenceArray = cont.getResult();	
		
		
		for(var i=0; i<returnPresenceArray.length;i++)
		{	
			
				var presenceStatus   = returnPresenceArray[i].getStatus();					
				var presenceStatusId = returnPresenceArray[i].getPresenceStateId();
				switch(presenceStatus)
				{
					case "Invisible" :
						window.statusArr[presenceStatusId] = new Array();
						statusArr[presenceStatusId]["image"] =  createImageTag( "status_invisible.gif" );
						statusArr[presenceStatusId]["text"]  = "&nbsp;-&nbsp;"+presenceStatus;
						continue;

					case "Available" :
						window.statusArr[presenceStatusId] = new Array();
						statusArr[presenceStatusId]["image"] =  createImageTag( "status_online.gif" );
						statusArr[presenceStatusId]["text"]  = "&nbsp;-&nbsp;"+presenceStatus;
						continue;
					
					default :	
						window.statusArr[presenceStatusId] = new Array();
						statusArr[presenceStatusId]["image"] =  createImageTag( "status_busy.gif" );
						statusArr[presenceStatusId]["text"]  = "&nbsp;-&nbsp;"+presenceStatus;
				}
			
		}
		
	}catch(e)
	{	
		showAlertMessage("Caught Exception while creating status array >> "+e.message);
	}
}



//var loginUserStatus = "Busy" ;
var loginUserStatus = null ;

var arrFriends = new Array();

function setMouseXY()
{
   var event = window.event;
   posX = event.pageX||(event.clientX+ (document.documentElement.scrollLeft||document.body.scrollLeft));
   posY = event.pageY||(event.clientY+ (document.documentElement.scrollTop||document.body.scrollTop));

   //window.status = "X== "+ posX + "Y== "+ posY ;

   //alert(posX);
   //alert(posY);

}
function showEditStatusSelect()
{
	edit_select_visible = true;
	document.getElementById('status_editor').style.display='block';
	document.getElementById('edit_status_select').style.display='block';
	document.getElementById('edit_status_select').style.background.color='black';
	//ge('edit_status_toggle').style.backgroundImage='url(/images/status_on.gif)';
	//document.getElementById('edit_status_toggle').style.backgroundColor='#fff';
}


function include_js( script_filename )
{
	var script = document.createElement("script"); //create a script element
	script.setAttribute("type", "text/javascript"); //set its type
	script.setAttribute("src",  script_filename); //set its src
	document.getElementsByTagName("head")[0].appendChild(script);
}

/**
 * This array has been used to hold the values of the script files, to be included at the run time.
 */
var scriptsToLoad = new Array();
//scriptsToLoad[0]='../js/dojo/dojo.js';
//	scriptsToLoad[1]='../Widgets/userWidget/widgetAPI/UserWidget.js';
//	scriptsToLoad[2]='../Widgets/PresenceWidget/widgetAPI/PresenceManagementWidget.js';
//	scriptsToLoad[3]='../Controller/controller.js';
//	scriptsToLoad[4]='../Controller/config.js';
//	scriptsToLoad[5]='../Utilities/utilities.js';
//	scriptsToLoad[6]='../Utilities/xml2json.js';   //xml2json.js

//	scriptsToLoad[7]='../Widgets/windowfiles/dhtmlwindow.css';
//	scriptsToLoad[8]='../Widgets/windowfiles/dhtmlwindow.js';   //xml2json.js


/**
 *Calling the Include_js fuction till the lenth of array for including the js files dynamically on the page
 */
for( var index = 0;index<scriptsToLoad.length;index++)
{
	include_js(scriptsToLoad[index]);
}




/**
 * Sign Up the user, this will be done by SignIn the user from the table users
 * It will fist invoke the controller and fetch its mapping from there, then call the getUserSignIn method of UserWidget
 * @return
 * @type
 * @param userLoginId, password
 */
function _SignInUser()
{
 		 try
 		 {
			var userName = document.getElementById('userLoginId').value ;
			var Password = document.getElementById('password').value;
			var  paramList = "userLoginId:'" + userName + "',Password:'" + Password + "'";

			var cont = new Controller('getUserSignIn','UserWidget',paramList);			
			var returnMessage = cont.getResult();

			//alert(returnMessage);

			if(returnMessage)
			{
				var cont = new Controller('checkIfAlreadyLogin','UserWidget',paramList);			
				var accessCheck = cont.getResult();							

				if( accessCheck == true )
				{
					error_login(document.getElementById('loginid_error'),'Access denied!!User already logged in from other window.')
					//alert("Access denied!!User already logged in from other window.");					
				}
				else
				{
					document.location.href = "index.php";
				}			
			
			}else
			{
				//alert(document.getElementById('loginid_error'));

				error_login(document.getElementById('loginid_error'),'Username or password is wrong.')
				//alert("Username or password is wrong.");
				document.getElementById('password').value = '';
				document.getElementById('password').focus();
			
/*		      var checkLogin = isUserAlreadyLogin(userName);

               if(checkLogin){

					alert("Access Denied!!User already Logged in from Other Window.");

					}else{

						alert("Username or password is wrong.");

						}
									 
				
				 document.getElementById('password').value = '';
				 */
			}
		 }catch(e)
		 {
			error_login(document.getElementById('loginid_error'),"Caught Exception while login >> " + e.message);
		 }
}


function error_login(errorObject,errorMessage)
{	
	errorObject.style.visibilty='visible';
	errorObject.style.display='';
	errorObject.style.backgroundColor='#d0dde6';
	errorObject.style.width='290px';

	//errorObject.innerHTML='<div class="errormsg_login" >'+errorMessage+'</div>';
	errorObject.innerHTML= "<font size='1' color='red'>"+errorMessage+"</font>" ;
}


/**
 * Sign Out the user, this will be done by SignIn the user from the table users
 * It will fist invoke the controller and fetch its mapping from there, then call the getUserSignOut method of UserWidget
 * @return
 * @type
 * @param userLoginId, password
 */
function _signout_user()
{
		//alert("_signout_user --> called");
		 try
		 {
		    // alert("online==="+isOnline);
			 if(isOnline.toLowerCase()=='true') 
				 changeCamStatus(cuurentUserId(),'False');

			 var paramList = "userLoginName:'1'";
		     //var setStatus = _changePresenceStatus('Invisible', true);
			 //_changePresenceStatus(presencestateid)
			 _update_User_Presence_Status(gUserId, '7');
			 var cont = new Controller('getUserSignOut','UserWidget',paramList);
			 var returnMessage = cont.getResult();
			 if(returnMessage)
			 {
   			    	var strLocation = 'login.htm'
					window.location = strLocation;
					document.location.href = strLocation;
			 }else
				showAlertMessage("log out not successful");
		 }catch(e)
		 {
			showAlertMessage("Caught Exception while logout >> "+e.message);
		}
}


/**
 * Get presence ID related to presence status
 * It will fist invoke the controller and fetch its mapping from there, then call the findAllPresenceStatus method of PresenceManagementWidget
 * @return
 * @type
 * @param status
 */
function get_Presence_ID(presenceStatus)
{	
	try
	{
		var returnPresenceArray = new Array();
		var paramList = "userId:'1'";
		var cont = new Controller('getPresenceDescriptions','PresenceManagementWidget',paramList);
		var returnPresenceArray = cont.getResult();
		
		var presenceID = 0;

		//alert(returnPresenceArray);
		for(var i=0; i<returnPresenceArray.length;i++)
		{	
			if(returnPresenceArray[i].getStatus() == presenceStatus)
			{	presenceID = returnPresenceArray[i].getPresenceId();
				break;
			}
		}
		//alert(presenceID);
		return presenceID;

	}catch(e)
	{	
		showAlertMessage("Caught Exception >> "+e.message);
	}
}


function set_Presence_Status(gUserId, status)
{
	var paramList = "userId:'"+gUserId+"',presencestateId:'"+status+"'";
	var cont = new Controller("setMyPresenceStatus","PresenceManagementWidget",paramList);

	//var presenceID = get_Presence_ID(status);
	//var paramList = "userId:'"+gUserId+"',presenceId:'"+presenceID+"'";
	//var cont = new Controller("setMyPresenceStatus",'PresenceManagementWidget',paramList);
}

/**
 * get the login users information, this will be done by find all buddy user from the table userbuddyrelation
 * It will fist invoke the controller and fetch its mapping from there, then call the findAllBuddyUsers method of UserWidget
 * @return
 * @type
 */
function _getLoggedInUserInfo()
{
    //try{
			//alert("In _getLoggedInUserInfo ");
			var  paramList = "userLoginId:'1'";
			var cons = new Controller('getLoggedInUserInfo', 'UserWidget', paramList);
			returnUsersInfo = cons.getResult();

			
			gUserId = returnUsersInfo[0].getUserId();			
			var loginUserName = returnUsersInfo[0].getUserLoginId();

			if(loginUserName.length > 1)
			{
				loginUserName = loginUserName.substr(0,1).toUpperCase() + loginUserName.substr(1,loginUserName.length);
			}			

			$('welcomeDiv').innerHTML="<font style=\"color:#FFFFFF\">You are logged in as <font style=\"font-weight:bold\">"+loginUserName+"</font>&nbsp;</font>";
			//alert($('welcomeDiv').innerHTML);
			//alert("In _getLoggedInUserInfo 1");
			//alert("In _getLoggedInUserInfo 2");			
			_find_allBuddyUsers(gUserId);
			
			//alert("In _getLoggedInUserInfo 3");						

/*			}
			catch(e)
			{
				alert("Error Throw : "+e.message);
				var location = 'login.htm'
				window.location = location;
				document.location.href=location;
			}
			*/
}

function _refresh_presence_status(t_userid, presenceId)
{
	var paramList = "userId:'"+ t_userid + "',presencestateId:'"+presenceId+"',callBackMethod:'refreshPresenceStatusDisplayCallback'";
	var cont = new Controller("refreshPresenceStatus","PresenceManagementWidget",paramList, 'refreshPresenceObj', true);
	refreshPresence_Obj = true;
}
function _stop_refresh_presence_status()
{
	 var paramList = "userId:'1'";
 	 var conts = new Controller("stopRefreshPresenceStatus","PresenceManagementWidget",paramList,'refreshPresenceObj');		
}
function refreshPresenceStatusDisplayCallback(refreshResult)
{
	if (refreshResult) {
		//alert("true");			
	} else {
		//alert("false");
	}	
}



function _find_by_id(gUserId){
		try{
			var paramList = "userId:'"+gUserId+"'";
			var cont = new Controller("findByUserId",'UserWidget',paramList);
			var statusResult = cont.getResult();
			return statusResult;
			}catch(e){
				showAlertMessage("Caught Exception While find user by ID >> "+e.message);
		}
}

/**
 * get the users information, this will be done by find all buddy user from the table userbuddyrelation
 * It will fist invoke the controller and fetch its mapping from there, then call the findAllBuddyUsers method of UserWidget
 * @return
 * @type
 */
function _getUserInfo(user)
{
        return returnUsersInfo[0].getUserLoginId();
}


function _getLoggedInUserID(user)
{
        return returnUsersInfo[0].getUserId();
}

/**
 * Find all buddy users, this will be done by find all buddy user from the table userbuddyrelation
 * It will fist invoke the controller and fetch its mapping from there, then call the findAllBuddyUsers method of UserWidget
 * @return
 * @type
 */
function _find_allBuddyUsers(userID)
{
    
	currentPresenceStatus = get_Current_Presence_Status(gUserId);
	//alert("current user status=="+currentPresenceStatus);

	if (currentPresenceStatus == "false")
 		 {
 		 	var setStatus = set_Presence_Status(userID, 1);
			currentPresenceStatus = get_Current_Presence_Status(userID);		 	
 		 } else {
 		 	var t_presence = currentPresenceStatus.split(":");				
		 	var t_PresenceStatus = t_presence[1];
     	 
			if (t_PresenceStatus =='Invisible') {
				var setStatus = set_Presence_Status(userID, 1);
				currentPresenceStatus = get_Current_Presence_Status(userID);
			}			
 		 }


/*	if((currentPresenceStatus =='Invisible') || (currentPresenceStatus == "false")) {
		var setStatus = set_Presence_Status(gUserId, '1');
		currentPresenceStatus = get_Current_Presence_Status(gUserId);
	}
*/

	var t_presence = currentPresenceStatus.split(":");
	loginUserStatus = t_presence[0];
	currentPresenceStatus = t_presence[1];
	
    //This method is used to publish user presence status and time.
	 if (refreshPresence_Obj == true){	_stop_refresh_presence_status(); }
	 _refresh_presence_status(gUserId, loginUserStatus);


     var paramList = "userId:0";
	 // var cont = new Controller("findAllUsers",'UserWidget', paramList);
	 var cont = new Controller("findAllActiveUsers",'UserWidget', paramList);
	
	 statusResult = cont.getResult();
	 
  	 if(statusResult.length == 0)
	 {
		_set_User_Presence_Status(gUserId);
	 }else
	 {
		
		var j = 0;
		var u = 0
		var arrayUserId= new Array();
		for(var i=0; i<statusResult.length;i++){
				
		 		arrayUserId[j++] = statusResult[i].getUserId();
				//alert(statusResult[i].getUserLoginId(););
				arrayUserName[u++] = statusResult[i].getUserLoginId();
		 	} //end for loop
			//alert(arrayUserId)
			
			if (presence_Obj ==  true) {
			   _stop_GetUsersPresenceStatus();
			}
		 	_get_Users_Presence_Status(arrayUserId);

	 }    // end else
	//checkStatus=false;
	//document.getElementById('status_image').innerHTML=statusArr[currentPresenceStatus]["image"];
	//document.getElementById('status_text').innerHTML=statusArr[currentPresenceStatus]["text"];

//	presenceStatus
    userPresenceStatus();


}

/*
* Function set User Presence Status
*/
function _set_User_Presence_Status(gUserId)
{
 		presenceStatus = get_Current_Presence_Status(gUserId);
		var t_presence = currentPresenceStatus.split(":");
		var presenceStatus = t_presence[0];


  		//var paramList = "userId:'"+gUserId+"',status:'"+presenceStatus+"'";
  		var paramList = "userId:'"+gUserId+"',presencestateId:'"+presenceStatus+"'";
		var conts = new Controller("setMyPresenceStatus",'PresenceManagementWidget',paramList);
		PresenceResult = conts.getResult();
		//checkStatus=false;
		document.getElementById('status_image').innerHTML=statusArr[presenceStatus]["image"];
		document.getElementById('status_text').innerHTML=statusArr[presenceStatus]["text"];

		//userPresenceStatus();
		
}


/**
* Function update User Presence Status
*/
function _update_User_Presence_Status(gUserId, strStatusText)
{
	
	var userID =  gUserId;
	//var statusTxt = document.getElementById("status").value;
	var paramList = "userId:'"+userID+"',presencestateId:'"+strStatusText+"'";
	//alert(paramList);
	var cont = new Controller("updateMyPresenceStatus",'PresenceManagementWidget',paramList);
	
}

/**
* Get the Presence status of the user from the database dynamically on the basis of UserID.
* This method will fist invoke the controller and fetch its mapping from there,
* then call the getCurrentPresenceStatus method of PresenceManagementWidget (JS API)
* @return
* @type
* @param PresenceStatus
*/
function get_Current_Presence_Status(userId)
{
		var paramList = "userId:'"+userId+"'";
		var cont = new Controller("getCurrentPresenceStatus", 'PresenceManagementWidget', paramList);
		var resultPresence = cont.getResult();
		if(resultPresence.length == 0){
			return "false";
		}else{
			return resultPresence[0].getPresenceStateId() + ":" + resultPresence[0].getStatus();
		}

		/*
		if(resultPresence.length == 0)
		{
			return "Available";
		}else
		{			
			//return resultPresence[0].getStatus();
			return resultPresence[0].getPresenceStateId();
		}*/
}


/**
* Load the Status of a number of user from the database dynamically on the basis of UserID.
* This method will fist invoke the controller and fetch its mapping from there,
* then call the getUsersPresenceStatus method of PresenceManagementWidget (JS API)
* @return
* @type
* @param UserId
*/
function _get_Users_Presence_Status(arrayUserId)
{

	 //var paramList = "userName:'newUser',userId:'"+arrayUserId+"'";
	 var paramList = "userId:'"+arrayUserId+"',callBackMethod:'displayCallback'";
	// alert("paramList"+paramList);
   //var conts = new Controller("getUsersPresenceStatus",'PresenceManagementWidget',paramList);
	 var conts = new Controller("getUsersPresenceStatus","PresenceManagementWidget",paramList,'presenceObj', true);
	 presence_Obj =  true;
}
function _stop_GetUsersPresenceStatus()
{	
	 var paramList = "userId:'1'";
 	 var conts = new Controller("stopGetUsersPresenceStatus","PresenceManagementWidget",paramList,'presenceObj');	
}

/**
* Functon change the Presence status of the user from the database dynamically on the basis of UserID.
* This method will fist invoke the controller and fetch its mapping from there,
* then call the updateMyPresenceStatus method of PresenceManagementWidget (JS API)
* @return
* @type
* @param PresenceStatus
*/
function _changePresenceStatus(presencestateid)
{
	var userID =  gUserId;
	//var statusTxt = document.getElementById("status").value;
	var paramList = "userId:'"+userID+"',presencestateId :'"+presencestateid +"'";
	var cont = new Controller("updateMyPresenceStatus",'PresenceManagementWidget',paramList);

	 //This method is used to publish user presence status and time.
	if (refreshPresence_Obj == true){	_stop_refresh_presence_status(); }
	 _refresh_presence_status(userID, presencestateid);


	/*Close the div used to ser the status*/
	//toggleEditStatusSelect();
	loginUserStatus = presencestateid ;
	//checkStatus=false;
	document.getElementById('status_image').innerHTML=statusArr[loginUserStatus]["image"];
	document.getElementById('status_text').innerHTML=statusArr[loginUserStatus]["text"];
	//userPresenceStatus();


}


function toggleEditStatusSelect()
{
	var RM_HTML = "";
	
	var returnPresenceArray = new Array();
	var paramList = "userId:'1'";
	var cont = new Controller('getPresenceDescriptions','PresenceManagementWidget',paramList);
	var returnPresenceArray = cont.getResult();
	var imageTag = "";

	RM_HTML = '<div id="edit_status_select" >';	
	
	//createStatusArr();
	for(var i=0; i<returnPresenceArray.length;i++)
	{	
		var presenceStatus = returnPresenceArray[i].getStatus();
		
		var presenceStatusId = returnPresenceArray[i].getPresenceStateId();
		
		imageTag = statusArr[presenceStatusId]["image"];
		
		RM_HTML = RM_HTML + '<a href="#" onclick="_changePresenceStatus(\''+presenceStatusId+'\');return false;">'+imageTag+'&nbsp;&nbsp;'+presenceStatus+'</a>';

	}
	
  
	RM_HTML += "</div>";


	//alert(RM_HTML)

	document.getElementById("RM").innerHTML = RM_HTML ;
	

	ToggelMenu.setup({'preventDefault':true, 'preventForms':false});
	ToggelMenu.attach('toggle', 'edit_status_select');
}



function displayUserName( userName )
{
	return "<div class='user_name_display'>"+userName+"</div>";
}

function displayUserStatus( userStatus )
{
	return "<span class='user_status_display'>"+userStatus+"</span>";
}

function displayFriendStatus( userStatus )
{
	return "<span class='user_status_display'>"+userStatus+"</span>";
}



/**
* Functon display the Presence status of the user.
* This method will fist invoke the controller and fetch its mapping from there,
*/
/*function userPresenceStatus()
{
			

		var ObjStatusDiv = document.getElementById("displayStatus");

		loggedInUser = _getUserInfo() ;
		isOnline='True';
		//alert('isOnline in user presence'+isOnline);

		var loginUserDisplay = '<table border="0" width="155" cellspacing="0" cellpadding="0" id="table2"><tr><td id="status_image">'+statusArr[loginUserStatus]["image"]+'</td><td class="member_txt" width="50px" align="center">'+displayUserName(_getUserInfo())+'</td><td class="toggle" align="left" width="30px"><a href="#" onclick="setMouseXY();toggleEditStatusSelect()"><img border="0" src="images/member_sts.gif" width="13" height="12"></a></td>';
		loginUserDisplay +="<td width='38' id='hideCamImage'></td>";
		loginUserDisplay +="<td width='38' id='cam_status' align='right'><img border='0' id='cam_image' src='images/webcam_deactivate.gif' width='21' height='24' onClick='if(!isCaptureStarted){	changeCamStatus(cuurentUserId(),isOnline); } else showAlertMessage(\"Can not start Self view as capture device busy\");' style='cursor:hand;' title='Show Self view'></td>";

		//else
		//	loginUserDisplay +='<td width="38"><img border="0" src="images/cam.gif" width="21" height="24" onClick="changeCamStatus(cuurentUserId(),isOnline);closeChatWindow("selfview");" style="cursor:hand;" title="Stop Self view"></td>';

		loginUserDisplay +='</tr><tr><td width="155" colspan="5" class="member_status" id="status_text">'+statusArr[loginUserStatus]["text"] +'</td></tr></table>';
		/*if(!checkStatus)
		{
	
		}
*/
/*		var statusHTMLstr ='';
		statusHTMLstr = loginUserDisplay;

		ObjStatusDiv.innerHTML = statusHTMLstr ;

}
*/
function userPresenceStatus()
{
			

		var ObjStatusDiv = document.getElementById("displayStatus");

		loggedInUser = _getUserInfo() ;
		isOnline='True';
		//alert('isOnline in user presence'+isOnline);

		var loginUserDisplay = "<table border='0' width='155' cellspacing='0' cellpadding='0' id='table2'><tr><td id='status_image'>"+statusArr[loginUserStatus]['image']+"</td><td class='member_txt' width='50px' align='left'>"+displayUserName(_getUserInfo())+"</td><td class='toggle' align='left' width='30px'><a href='#' onclick='setMouseXY();toggleEditStatusSelect()'><img border='0' src='images/member_sts.gif' width='13' height='12'></a></td></tr>";
		

		//else
		//	loginUserDisplay +='<td width="38"><img border="0" src="images/cam.gif" width="21" height="24" onClick="changeCamStatus(cuurentUserId(),isOnline);closeChatWindow("selfview");" style="cursor:hand;" title="Stop Self view"></td>';

		loginUserDisplay +="<tr><td class='member_status' id='status_text'>"+statusArr[loginUserStatus]['text']+"</td>" ;
		loginUserDisplay +="<td id='cam_status'><img border='0' id='cam_image' src='images/webcam_deactivate.gif' width='21' height='24' onClick='if(!isCaptureStarted){	changeCamStatus(cuurentUserId(),isOnline); } else showAlertMessage(\"Can not start Self view as capture device busy\");' style='cursor:hand;' title='Show Self view'></td>";
		loginUserDisplay +="<td id='hideCamImage'></td>";
		loginUserDisplay +="</tr></table>";
		
		/*if(!checkStatus)
		{
	
		}
*/
		var statusHTMLstr ='';
		statusHTMLstr = loginUserDisplay;

		ObjStatusDiv.innerHTML = statusHTMLstr ;

}



function updateStatuses( statusCallback )
{
	var newUpdates = Array();
	newUpdates = newStatusArray(statusCallback);

	for( x in  newUpdates  )
	{
			arrFriends[arrFriends.length] = x ;

			if(x=='contains' || x=='indexOf' )	continue;
				if(typeof(newUpdates[x]) != "undefined")
				{
					// var imgDiv	  	= document.getElementById("dvImg_"+x); 
					var imgDiv	  	= document.getElementById("status_"+x);
					var statusDiv	= document.getElementById("dvStatus_"+x);
					var camDiv		= document.getElementById("cam_div_"+x);
					var statusDiv   = document.getElementById("status_div_"+x);
					
					if(imgDiv == null ) continue ;

					//alert(newUpdates[x]);
					//alert(imgDiv +" === " +statusDiv);
					
					var callBackArray = new Array();
					var callBackArray = newUpdates[x].split("|");
					
					if(isUserIdAlreadyLogin(x))
					{
						var createText = displayFriendStatus(statusArr[callBackArray[0]]["text"]) ;
						var createSRC = statusArr[callBackArray[0]]["image"] ;
					}
					else
					{
						var createText = '-Offline' ;
						var createSRC = createImageTag('status_invisible.gif');
					}
					

					
					
					// var createSRC = statusArr[newUpdates[x]]["image"] ;
					//var createText = displayFriendStatus(statusArr[newUpdates[x]]["text"]) ;

					//alert( createSRC + " == " + createText );
					
					/*
					var userStatus = newUpdates[x];
					var userID = x; 
					var divID = "name_"+x;
					var userName = "";
					var currentUserId ="";
					//document.getElementById(divID).onmousedown = 
					displayRightMenu(divID, "'"+ userStatus + "'", userID, userName, '');
					*/

					//alert("call back array"+callBackArray[1]);
					var onCam = callBackArray[1];

					if(onCam == 'True')
					{
						//alert(onCam)
						camDiv.innerHTML = "&nbsp;<img src='images/webcam2.gif' title='View Live'>&nbsp;";
					}else if(onCam == 'False')
					{
						//alert(onCam)
						camDiv.innerHTML = "&nbsp;";
					}
				
					imgDiv.innerHTML = createSRC;
					statusDiv.innerHTML = createText;
					
					//statusDiv.innerHTML = createText ;
				}
	}
}


function displayCallback( statusCallback )
{
   //alert(ifTreeCreated);
   if(!ifTreeCreated)		
	  try{
	      
			createTree(statusResult,statusCallback)
		}
	  catch(e){
		  showAlertMessage(" the error is = " + e );
	  }

   else{

	   updateStatuses( statusCallback );
   }
}


function newStatusArray(statusCallback)
{
    var arrStatus = new Array();
	
	for( x =0; x < statusCallback.length ; x++ )
	{
		//arrStatus[statusCallback[x].getUserId()] = statusCallback[x].getStatus() ;
		arrStatus[statusCallback[x].getUserId()] = statusCallback[x].getPresenceStateId() +"|"+statusCallback[x].getIsCamAvailable() ;
		//arrStatus[statusCallback[x].getUserId()] = statusCallback[x].getPresenceStateId() ;

		//alert(statusCallback[x].getUserId() +" ===> "+arrStatus[statusCallback[x].getUserId()]+" ===> "+statusCallback[x].getIsCamAvailable());
		//alert(arrStatus[statusCallback[x].getPresenceStateId()] + "  cam status  " + statusCallback[x].getIsCamAvailable());



	}
	return arrStatus ;
}

function changeDivBgClass(objDiv) 
{
	 //this.background-color=#CCCCFF
	 objDiv.style.backgroundColor = "#CCCCFF";
}
/*
* function create tree
*/

function createTree(statusResult,statusCallback)
{
	var newArrStatus = new Array();
	newArrStatus = newStatusArray(statusCallback) ;
	//palmtree = new jktreeview("treeControl");

	
	loggedUserID = _getLoggedInUserID();
	
	var nodeArray=new Array();
	var indexNodeArray=0;
	var strHtml = "";
  	
    
    for(var cnt=0; cnt<statusResult.length; cnt++)
	{
	    var thisUserId		= statusResult[cnt].getUserId();
		var thisUserName	= statusResult[cnt].getUserLoginId() ;
		
		//alert(newArrStatus[thisUserId]);

		//alert(typeof(newArrStatus[thisUserId]));

		var cam_innerHTML = "";
		
		
		if( typeof(newArrStatus[thisUserId]) == "undefined")
		{	
			thisUserStatus = newArrStatus[thisUserId];
		}
		else
		{
		
		
			var newStatusCallBackArray = new Array();
				
			var newStatusCallBackArray = newArrStatus[thisUserId].split("|");

			var thisUserStatus	= newStatusCallBackArray[0];  
			
			var onCam = newStatusCallBackArray[1];
			
			if(onCam == 'True')
			{	cam_innerHTML = "<img src='images/webcam2.gif' title='View Live'>&nbsp;";
			}
					
		}			
	
		
		//alert("status   " + thisUserStatus + " cam status   " + statuscallBackArray[1]);
		
		if( typeof(thisUserStatus) == "undefined" )
		{			
			var thisStatusImage = createImageTag( "status_invisible.gif" );
		}else {
				
			var thisStatusImage = statusArr[thisUserStatus]["image"] ;
		}

		if( thisUserName == _getUserInfo()) continue;
		strHtml += "<table border='0'><tr><td class='membernormal' id='table_"+thisUserId+"' colspan=3><table border='0' width='145' cellspacing='0' cellpadding='0' id='table2'><tr><td width='30' id='status_"+thisUserId+"'>"+thisStatusImage+"</td><td width='65' id='name_"+thisUserId+"'><a class='member_txt' href='#' onmousedown=\"displayRightMenu(this.id, '"+thisUserStatus+"',"+thisUserId+",'"+thisUserName+"', "+loggedUserID+")\" >"+thisUserName+"</a></td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></table></td></tr><tr><td id='status_div_"+thisUserId+"' class='member_status'></td><td align='left' width='15px' id='balloon_div_"+thisUserId+"'>&nbsp;</td><td align='left' id='cam_div_"+thisUserId+"'>&nbsp;"+cam_innerHTML+"</td></tr><tr><td class='whiteline' colspan=3></td></tr></table>";
		//strHtml += "<table><tr><td class='membernormal' id='table_"+thisUserId+"'><table border='0' width='155' cellspacing='0' cellpadding='0' id='table2'><tr><td width='30' id='status_"+thisUserId+"'>"+thisStatusImage+"</td><td width='65' id='name_"+thisUserId+"'><a class='member_txt' href='#' onmousedown=\"displayRightMenu(this.id, '"+thisUserStatus+"',"+thisUserId+",'"+thisUserName+"', "+loggedUserID+")\" >"+thisUserName+"</a></td><td id='balloon_div_"+thisUserId+"'>&nbsp;</td><td id='cam_div_"+thisUserId+"'>&nbsp;"+cam_innerHTML+"</td><td>&nbsp;</td></tr></table></td></tr><tr><td id='status_div_"+thisUserId+"' class='member_status'></td></tr><tr><td class='whiteline'></td></tr></table>";
		//alert(strHtml);
	}
   document.getElementById("treeControl").innerHTML = strHtml ;
   ifTreeCreated = true;
 /*
	for(var cnt=0; cnt<statusResult.length; cnt++)
	{

		arrFriends[arrFriends.length] = statusResult[cnt].getUserId() ;
		var pendingUser = false ;

		//alert("loop counter -1  = " + cnt )	;
       	if( typeof(arrStatus[statusResult[cnt].getUserId()]) != "undefined" )
			{
				var currUserStatus  = arrStatus[statusResult[cnt].getUserId()];
				var currStatusImage = statusArr[currUserStatus]["image"];
				var currStatusText  = statusArr[currUserStatus]["text"];

				var displayName = "<table CELLPADDING=0 CELLSPACING=0 border=0><tr><td><div id='dvImg_"+statusResult[cnt].getUserId()+"'><img src='"+currStatusImage+"' border='0'/></div></td><td> <div class='container1' onclick='rightmenu("+statusResult[cnt].getUserId()+","+gUserId+");'>"+displayUserName(statusResult[cnt].getUserLoginId())+"</div></td><td nowrap><div id='dvStatus_"+statusResult[cnt].getUserId()+"'>"+ displayFriendStatus(currStatusText)+"</div></td></tr></table>" ;
			}
		else
		{
			pendingUser = true  ;
		}
	//alert("loop counter -2  = " + cnt )	;

		if(cnt == 0)
		{
			nodeArray[indexNodeArray] = palmtree.addItem(statusResult[cnt].getBuddyCategoryName()) //Parent

			arrGlobalTreeNodes[statusResult[cnt].getBuddyCategoryName()] = nodeArray[indexNodeArray] ;

			arrGlobalTreeChilds[statusResult[cnt].getUserId()] = palmtree.addItem(displayName,nodeArray[indexNodeArray],"#")  ; //child

		}else
		{
			//alert("loop counter -3  = " + cnt + " current group = " + statusResult[cnt].getBuddyCategoryName() + "previous group = "+ statusResult[cnt-1].getBuddyCategoryName())	;

				if(statusResult[cnt].getBuddyCategoryName() != statusResult[cnt-1].getBuddyCategoryName())
				{
					indexNodeArray++;
					nodeArray[indexNodeArray] = palmtree.addItem(statusResult[cnt].getBuddyCategoryName(),"","#");//parent

					arrGlobalTreeNodes[statusResult[cnt].getBuddyCategoryName()] = nodeArray[indexNodeArray] ;

				}

				if(pendingUser) //cnt > statusCallback.length
			     	{
			          		var pendingUser = "<table CELLPADDING=0 CELLSPACING=0 border=0><tr><td><div id='dvImg_"+statusResult[cnt].getUserId()+"'><img src='"+statusArr["Add request pending"]["image"]+"' border='0'/></div></td><td> <div class='container1' onmousedown='rightmenu("+statusResult[cnt].getUserId()+","+gUserId+")'>"+displayUserName(statusResult[cnt].getUserLoginId())+"</div></td><td nowrap><div id='dvStatus_"+statusResult[cnt].getUserId()+"'>"+ displayFriendStatus("&nbsp;-&nbsp;Add request pending")+"</div></td></tr></table>" ;

			          		arrGlobalTreeChilds[statusResult[cnt].getUserId()] = palmtree.addItem(pendingUser,nodeArray[indexNodeArray],"#"); //child
			    	 }
			    	else
				    {
				    	   arrGlobalTreeChilds[statusResult[cnt].getUserId()] = palmtree.addItem(displayName,nodeArray[indexNodeArray],"#");//child
				    }

		}
}
palmtree.treetop.draw();
palmtree.treetop.expandAll();
ifTreeCreated = true ;

var DHTMLWin = document.getElementById("UserPresence");
*/

//DHTMLWin.setAttribute("onclick", callme() );

}

/*
* Function used to display right menu while right click on any user in user list on index page
*
*/


function displayRightMenu(divID, userStatus, userID, userName, currentUserId)
{	
	
	var RM_HTML = "";
	
	RM_HTML = "<ul id='CM' class='SimpleContextMenu'>";
	
	//alert("user name: " + userID + "\n status: " + userStatus);

	//if(userStatus == 'Invisible')
	//{	RM_HTML += "<li><a href='#'>Offline</a></li>";
	//}	
	//else{
		
		if(typeof(chatUserArray[currentUserId]) == "object")
		{
			if(in_array(userID, chatUserArray[currentUserId]))
			{
				RM_HTML += "<li><a href='#' onclick='stop_chat("+userID+", "+currentUserId+");'>Stop Chat </a></li>";
			}else{
				RM_HTML += "<li><a href='#' onclick='start_chat("+userID+", "+currentUserId+",\""+userName+"\");'>Join "+userName+"</a></li>";
			}
		}else{
			RM_HTML += "<li><a href='#' onclick='start_chat("+userID+", "+currentUserId+",\""+userName+"\");'>Join "+userName+"</a></li>";
		}
//	}

	RM_HTML += '<li><a href="#" onclick="showRemoteView(\''+userName+'\');">View Live</a></li>';
    //RM_HTML += '<li><a href="#">Option2</a></li>';
	//RM_HTML += '<li><a href="#">Option3</a></li>';
	RM_HTML += '<li><a href="#" onclick="memberProfile('+userID+');">'+userName+'\'s Profile</a></li></ul>';


	document.getElementById("RM").innerHTML = RM_HTML ;
	
	// Define here user div id, original color and color to bechanged while right click
	
	var divBgChangeColor = "#c0c0c0";
	var divBgOrgColor = "#354254";

	if( divBgChanged != null)
	{
		if( document.getElementById(divBgChanged) != null )
		{
			document.getElementById(divBgChanged).style.background = divBgOrgColor;
		}
	}
	
	divBgChanged = "table_"+userID;
	
	
	SimpleContextMenu.setup({'preventDefault':true, 'preventForms':false, 'divbgorg':divBgOrgColor, 'divbgchange':divBgChanged, 'divbgcolor':divBgChangeColor});
	SimpleContextMenu.attach('member_txt', 'CM');
}



/*
* Function to check whether a value exists in array or not
*
*/
function in_array(value, array) 
{
	if(array.length > 0)
	{
		for(var i=0; i<array.length; i++)
		{
			if(array[i] == value)
			{
				return true;
			}
		}
	}
	return false;
}



/*
* function used to set the value of html element 
*
*/

function setHTMLFieldValue(filedName, fieldValue)
{
	document.getElementById(filedName).value = fieldValue;
}


function callme()
{
	//alert('hello');
}

function removeRightMenuDiv( userId )
{
	var objParent  = document.getElementById("UserPresence") ;
	var dvToRemove = document.getElementById( "dv_right_"+userId ) ;

	objParent.removeChild( dvToRemove ) ;
}

function removeAllRightMenuDivs()
{

	 var objParent = document.getElementById("UserPresence") ;

	 for( cntOp =0 ; cntOp < arrFriends.length ; cntOp ++ )
	 {
		var currDiv = document.getElementById("dv_right_"+arrFriends[cntOp]);

		if(currDiv)
		{
					objParent.removeChild( currDiv ) ;
		}

	 }

}

function rightmenu(userId, LoginUserId)
{

	 var objParent = document.getElementById("UserPresence") ;
		 //alert("parent.parent= "+ parent.parent);
		 //alert("parent Id= "+ parent.tag); ////.parent

	 removeAllRightMenuDivs() ;

	 setMouseXY();

	 var oDiv_Right = document.createElement("DIV") ;
	 str ='<div id="edit_status_select"><a href="#" onclick="_removeBuddy('+userId+','+LoginUserId+');return false;">Remove User</a><a href="#" onclick="_moveUser('+userId+'); return false;">Move User</a></div>';

	//oDiv2.id = "dv_right_"+userId ;

	oDiv_Right.setAttribute("id", "dv_right_"+userId );

	oDiv_Right.setAttribute("onmouseout", 'removeRightMenuDiv('+userId+')' );

	oDiv_Right.style.position = "absolute";

	oDiv_Right.style.overflow = "auto";

	oDiv_Right.style.width = "200px";

	oDiv_Right.style.height = "100px";

	parentX = objParent.style.left ;
	parentY = objParent.style.top ;
	parentX = parentX.replace(/px/gi,"");
	parentY = parentY.replace(/px/gi,"");

	oDiv_Right.style.left = (posX - parentX) + "px";

	oDiv_Right.style.top = (posY - parentY) + "px" ;


	oDiv_Right.style.zIndex = "100";

	oDiv_Right.style.background = "";

	oDiv_Right.innerHTML = str;
	//oDiv_Right.onmouseout = 'removeRightMenuDiv('+userId+')';

	objParent.appendChild(oDiv_Right);

	rightMouseClick = false ;
}




function setTreeToFalse()
{
	 ifTreeCreated = false ;
}






///////////////////////////           Common functions for all dropdowns               ////////////////////////////





  /*----------------------------------------------
  The Common function used for all dropdowns are:
  -----------------------------------------------
  -- function fnKeyDownHandler(getdropdown, e)
  -- function fnLeftToRight(getdropdown)
  -- function fnRightToLeft(getdropdown)
  -- function fnDelete(getdropdown)
  -- function FindKeyCode(e)
  -- function FindKeyChar(e)
  -- function fnSanityCheck(getdropdown)

  */

  function fnKeyDownHandler(getdropdown, e)
  {
    fnSanityCheck(getdropdown);

    // Press [ <- ] and [ -> ] arrow keys on the keyboard to change alignment/flow.
    // ...go to Start : Press  [ <- ] Arrow Key
    // ...go to End : Press [ -> ] Arrow Key
    // (this is useful when the edited-text content exceeds the ListBox-fixed-width)
    // This works best on Internet Explorer, and not on Netscape

    var vEventKeyCode = FindKeyCode(e);

    // Press left/right arrow keys
    if(vEventKeyCode == 37)
    {
    fnLeftToRight(getdropdown);
    }
    if(vEventKeyCode == 39)
    {
    fnRightToLeft(getdropdown);
    }

    // Delete key pressed
    if(vEventKeyCode == 46)
    {
    fnDelete(getdropdown);
    }

    // backspace key pressed
    if(vEventKeyCode == 8 || vEventKeyCode==127)
    {
    if(e.which) //Netscape
    {
      //e.which = ''; //this property has only a getter.
    }
    else //Internet Explorer
    {
      //To prevent backspace from activating the -Back- button of the browser
      e.keyCode = '';
      if(window.event.keyCode)
      {
      window.event.keyCode = '';
      }
    }
    return true;
    }

    // Tab key pressed, use code below to reorient to Left-To-Right flow, if needed
    //if(vEventKeyCode == 9)
    //{
    //  fnLeftToRight(getdropdown);
    //}
  }

  function fnLeftToRight(getdropdown)
  {
    getdropdown.style.direction = "ltr";
  }

  function fnRightToLeft(getdropdown)
  {
    getdropdown.style.direction = "rtl";
  }

  function fnDelete(getdropdown)
  {
    if(getdropdown.options.length != 0)
    // if dropdown is not empty
    {
    if (getdropdown.options.selectedIndex == vEditableOptionIndex_A)
    // if option the Editable field
    {
      getdropdown.options[getdropdown.options.selectedIndex].text = '';
      getdropdown.options[getdropdown.options.selectedIndex].value = '';
    }
    }
  }


  /*
  Since Internet Explorer and Netscape have different
  ways of returning the key code, displaying keys
  browser-independently is a bit harder.
  However, you can create a script that displays keys
  for either browser.
  The following function will display each key
  in the status line:

  The "FindKey.." function receives the "event" object
  from the event handler and stores it in the variable "e".
  It checks whether the "e.which" property exists (for Netscape),
  and stores it in the "keycode" variable if present.
  Otherwise, it assumes the browser is Internet Explorer
  and assigns to keycode the "e.keyCode" property.
  */

  function FindKeyCode(e)
  {
    if(e.which)
    {
    keycode=e.which;  //Netscape
    }
    else
    {
    keycode=e.keyCode; //Internet Explorer
    }

    //alert("FindKeyCode"+ keycode);
    return keycode;
  }

  function FindKeyChar(e)
  {
    keycode = FindKeyCode(e);
    if((keycode==8)||(keycode==127))
    {
    character="backspace"
    }
    else if((keycode==46))
    {
    character="delete"
    }
    else
    {
    character=String.fromCharCode(keycode);
    }
    //alert("FindKey"+ character);
    return character;
  }

  function fnSanityCheck(getdropdown)
  {
    if(vEditableOptionIndex_A>(getdropdown.options.length-1))
    {
    showAlertMessage("PROGRAMMING ERROR: The value of variable vEditableOptionIndex_... cannot be greater than (length of dropdown - 1)");
    return false;
    }
  }
 //Dropdown specific functions, which manipulate dropdown specific global variables

  /*----------------------------------------------
  Dropdown specific global variables are:
  -----------------------------------------------
  1) vEditableOptionIndex_A   --> this needs to be set by Programmer!! See explanation.
  2) vEditableOptionText_A    --> this needs to be set by Programmer!! See explanation.
  3) vPreviousSelectIndex_A
  4) vSelectIndex_A
  5) vSelectChange_A

  ---------------------------  */

  /*----------------------------------------------
  The dropdown specific functions
  (which manipulate dropdown specific global variables)
  used by all dropdowns are:
  -----------------------------------------------
  1) function fnChangeHandler_A(getdropdown)
  2) function fnKeyPressHandler_A(getdropdown, e)
  3) function fnKeyUpHandler_A(getdropdown, e)

  ---------------------------  */

  /*------------------------------------------------
  IMPORTANT: Global Variable required to be SET by programmer
  --------------------------   */

  var vEditableOptionIndex_A = 0;

  // Give Index of Editable option in the dropdown.
  // For eg.
  // if first option is editable then vEditableOptionIndex_A = 0;
  // if second option is editable then vEditableOptionIndex_A = 1;
  // if third option is editable then vEditableOptionIndex_A = 2;
  // if last option is editable then vEditableOptionIndex_A = (length of dropdown - 1).
  // Note: the value of vEditableOptionIndex_A cannot be greater than (length of dropdown - 1)

  var vEditableOptionText_A = "--?--";

  // Give the default text of the Editable option in the dropdown.
  // For eg.
  // if the editable option is <option ...>--?--</option>,
  // then set vEditableOptionText_A = "--?--";

  /*------------------------------------------------
  Global Variables required for
  fnChangeHandler_A(), fnKeyPressHandler_A() and fnKeyUpHandler_A()
  for Editable Dropdowns
  --------------------------  */

  var vPreviousSelectIndex_A = 0;
  // Contains the Previously Selected Index, set to 0 by default

  var vSelectIndex_A = 0;
  // Contains the Currently Selected Index, set to 0 by default

  var vSelectChange_A = 'MANUAL_CLICK';
  // Indicates whether Change in dropdown selected option
  // was due to a Manual Click
  // or due to System properties of dropdown.

  // vSelectChange_A = 'MANUAL_CLICK' indicates that
  // the jump to a non-editable option in the dropdown was due
  // to a Manual click (i.e.,changed on purpose by user).

  // vSelectChange_A = 'AUTO_SYSTEM' indicates that
  // the jump to a non-editable option was due to System properties of dropdown
  // (i.e.,user did not change the option in the dropdown;
  // instead an automatic jump happened due to inbuilt
  // dropdown properties of browser on typing of a character )

  /*------------------------------------------------
  Functions required for  Editable Dropdowns
  --------------------------  */

  function fnChangeHandler_A(getdropdown)
  {
    fnSanityCheck(getdropdown);

    vPreviousSelectIndex_A = vSelectIndex_A;
    // Contains the Previously Selected Index

    vSelectIndex_A = getdropdown.options.selectedIndex;
    // Contains the Currently Selected Index

    if ((vPreviousSelectIndex_A == (vEditableOptionIndex_A)) && (vSelectIndex_A != (vEditableOptionIndex_A))&&(vSelectChange_A != 'MANUAL_CLICK'))
    // To Set value of Index variables
    {
      getdropdown[(vEditableOptionIndex_A)].selected=true;
      vPreviousSelectIndex_A = vSelectIndex_A;
      vSelectIndex_A = getdropdown.options.selectedIndex;
      vSelectChange_A = 'MANUAL_CLICK';
      // Indicates that the Change in dropdown selected
      // option was due to a Manual Click
    }
  }

  function fnKeyPressHandler_A(getdropdown, e)
  {
    fnSanityCheck(getdropdown);

    keycode = FindKeyCode(e);
    keychar = FindKeyChar(e);
	

    // Check for allowable Characters
    // The various characters allowable for entry into Editable option..
    // may be customized by minor modifications in the code (if condition below)
    // (you need to know the keycode/ASCII value of the  character to be allowed/disallowed.


 if ((keycode>47 && keycode<59)||(keycode>62 && keycode<127) ||(keycode==32))
    {
      var vAllowableCharacter = "yes";
    }
    else
    {
      var vAllowableCharacter = "no";
    }

    //alert(window); alert(window.event);

    if(getdropdown.options.length != 0)
    // if dropdown is not empty
      if (getdropdown.options.selectedIndex == (vEditableOptionIndex_A))
      // if selected option the Editable option of the dropdown
      {

        var vEditString = getdropdown[vEditableOptionIndex_A].value;

        // make Editable option Null if it is being edited for the first time
        if((vAllowableCharacter == "yes")||(keychar=="backspace"))
        {
          if (vEditString == vEditableOptionText_A)
            vEditString = "";
        }
        if (keychar=="backspace")
        // To handle backspace
        {
          vEditString = vEditString.substring(0,vEditString.length-1);
          // Decrease length of string by one from right

          vSelectChange_A = 'MANUAL_CLICK';
          // Indicates that the Change in dropdown selected
          // option was due to a Manual Click

        }
        //alert("EditString2:"+vEditString);

        if (vAllowableCharacter == "yes")
        // To handle addition of a character
        {
          vEditString+=String.fromCharCode(keycode);
          // Concatenate Enter character to Editable string

          // The following portion handles the "automatic Jump" bug
          // The "automatic Jump" bug (Description):
          //   If a alphabet is entered (while editing)
          //   ...which is contained as a first character in one of the read-only options
          //   ..the focus automatically "jumps" to the read-only option
          //   (-- this is a common property of normal dropdowns
          //    ..but..is undesirable while editing).

          var i=0;
          var vEnteredChar = String.fromCharCode(keycode);
          var vUpperCaseEnteredChar = vEnteredChar;
          var vLowerCaseEnteredChar = vEnteredChar;


          if(((keycode)>=97)&&((keycode)<=122))
          // if vEnteredChar lowercase
            vUpperCaseEnteredChar = String.fromCharCode(keycode - 32);
            // This is UpperCase


          if(((keycode)>=65)&&((keycode)<=90))
          // if vEnteredChar is UpperCase
            vLowerCaseEnteredChar = String.fromCharCode(keycode + 32);
            // This is lowercase

          if(e.which) //For Netscape
          {
            // Compare the typed character (into the editable option)
            // with the first character of all the other
            // options (non-editable).

            // To note if the jump to the non-editable option was due
            // to a Manual click (i.e.,changed on purpose by user)
            // or due to System properties of dropdown
            // (i.e.,user did not change the option in the dropdown;
            // instead an automatic jump happened due to inbuilt
            // dropdown properties of browser on typing of a character )

            for (i=0;i<=(getdropdown.options.length-1);i++)
            {
              if(i!=vEditableOptionIndex_A)
              {
                var vReadOnlyString = getdropdown[i].value;
                var vFirstChar = vReadOnlyString.substring(0,1);
                if((vFirstChar == vUpperCaseEnteredChar)||(vFirstChar == vLowerCaseEnteredChar))
                {
                  vSelectChange_A = 'AUTO_SYSTEM';
                  // Indicates that the Change in dropdown selected
                  // option was due to System properties of dropdown
                  break;
                }
                else
                {
                  vSelectChange_A = 'MANUAL_CLICK';
                  // Indicates that the Change in dropdown selected
                  // option was due to a Manual Click
                }
              }
            }
          }
        }

        // Set the new edited string into the Editable option
        getdropdown.options[vEditableOptionIndex_A].text = vEditString;
        getdropdown.options[vEditableOptionIndex_A].value = vEditString;

        return false;
      }
    return true;
  }

  function fnKeyUpHandler_A(getdropdown, e)
  {
    fnSanityCheck(getdropdown);

    if(e.which) // Netscape
    {
      if(vSelectChange_A == 'AUTO_SYSTEM')
      {
        // if editable dropdown option jumped while editing
        // (due to typing of a character which is the first character of some other option)
        // then go back to the editable option.
        getdropdown[(vEditableOptionIndex_A)].selected=true;
      }

      var vEventKeyCode = FindKeyCode(e);
      // if [ <- ] or [ -> ] arrow keys are pressed, select the editable option
      if((vEventKeyCode == 37)||(vEventKeyCode == 39))
      {
        getdropdown[vEditableOptionIndex_A].selected=true;
      }
    }
  }

function closeDivIfOpened(e)
{
	if(statusDivOpened)
		{
			toggleEditStatusSelect()
		}
	//alert("clicked"+e) ;
}

function checkIfRightClick()
{
		   //alert('asdasd');

		   var event = window.event;

		   if (bNS && event.which > 1){
			   rightMouseClick = true ;
		   } else if (bIE && (event.button >1)) {
			 rightMouseClick = true ;
		   }

		/* document.onmousedown = nrc;
		if (document.layers) window.captureEvents(Event.MOUSEDOWN);
		if (bNS && bV<5) window.onmousedown = nrc;
		*/
}


//document.onmousemove = setMouseXY ;
/* document.onclick= chk; */

/**
 * Provide a new password to user in case of forgot password 
 * It will fist invoke the controller and fetch its mapping from there
 * @return
 * @type
 * @param userEmailId
 */
function _forgotPassword(){
		 try{
	 		
	 		var emailId =  document.getElementById("emailId").value; //"deepak.goel@rsystems.com";
			if( emailId == "" ) 
			 {
				 //alert("email="+emailId);
				 alert("Please enter your email address.");
				 return false;
			 }

			
	 		var paramList = "emailId:'"+emailId+"'";
	 		//alert("parameterList========"+paramList);
	 		var cont = new Controller("forgotPassword",'UserWidget',paramList); //"UserWidget",

     		var statusResult = cont.getResult();
			if(statusResult)
			{
				alert('Password has been retrieved and email successfully.');
				if(forgotPassword != null )
					forgotPassword.hide();
            }else
            {
				alert("Please check your email Id.");
			}
		    }
		    catch(e)
		    {
		    	
				showAlertMessage("Caught Exception while retreving password >> "+e.message);
		    }
}


function changeUserPassword(){
 try{
	var password = document.getElementById("currentPassword").value;
	var newPassword = document.getElementById("newPassword").value;
	var paramList = "password:'"+password+"',newPassword:'"+newPassword+"'";
	//alert("paramlist=="+paramList);
	var cont = new Controller("changePassword","UserWidget",paramList);
	//cont.executeAction("changePassword","UserWidget",paramList);
	var statusResult = cont.getResult();
	if(statusResult){
		password = '';
		newPassword = '';
		showAlertMessage('Password has been changed successfully.');
		document.getElementById("currentPassword").value='';
		document.getElementById("newPassword").value='';
		document.getElementById("cNewPassword").value='';
			
	}else{
		
		document.getElementById("currentPassword").value='';
		document.getElementById("newPassword").value='';
		document.getElementById("cNewPassword").value='';
		showAlertMessage("Please check your current password.");
	}
	}catch(e){
		showAlertMessage("Caught Exception while changing password >> "+e.message);
	}
}

function validatePass()
{
	newpasswd=document.getElementById("newPassword").value;
	cnewpasswd=document.getElementById("cNewPassword").value;
	if(newpasswd==cnewpasswd)
		changeUserPassword();
	else
		{
			document.getElementById("newPassword").value='';
			document.getElementById("cNewPassword").value='';
			showAlertMessage('New passwords does not match');
		}

}

function StateSuggestions() {
    
	//alert(arrayUserName[3]);
	this.states=arrayUserName;
	//alert(this.states.length);

}

/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                          bTypeAhead /*:boolean*/) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
    
    if (sTextboxValue.length > 0){
    
        //search for matching states
        for (var i=0; i < this.states.length; i++) { 
             if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) 
			 {
				aSuggestions.push(this.states[i]);
             } 
        }
    }

    //provide suggestions to the control
    oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
};

 function showSuggestion()
  		{
           var oTextbox = new AutoSuggestControl(document.getElementById("mtxtToAccount"), new StateSuggestions());        
            }
function showForwardSuggestion()
  		{
           var oTextbox = new AutoSuggestControl(document.getElementById("ftxtToAccount"), new StateSuggestions());        
            }

/*function changeCamStatus(userId)
{

	alert(userId);
	var userID = userId; //document.getElementById("UserIDTxt").value;
	var paramList = "userId:'"+userID+"'";
	var cont = new Controller("getWebcamStatus","PresenceManagementWidget",paramList);
	var statusResult = cont.getResult();
	//alert(cont.getResult());
	alert("current cam status of " + statusResult[0].getUserId()+" is "+statusResult[0].getIsCamAvailable());
	if(statusResult[0].getIsCamAvailable())
			var paramList = "userId:'"+userID+"',isCamAvailable:'"+statusTxt+"'";


}
*/
function isUserAlreadyLogin(userLoginId)
{
  
	var paramList = "userLoginId:'"+userLoginId+"'";
	
 	var cont = new Controller("checkForAlreadyLoginByUserLoginId","UserWidget",paramList);
	var statusResult = cont.getResult();
	//alert("statusResult=="+statusResult);
	
	return statusResult;
}








