///////////////////////////////////
//         ajax im v2.5          //
//    AJAX Instant Messenger     //
//   Copyright (c) 2006-2007     //
// unwieldy studios/Joshua Gross //
//  http://unwieldy.net/ajaxim/  //
//   Do not remove this notice   //
///////////////////////////////////

// Configurable Options //

// Notification //
var useBlinker    = true;           // Show new message in titlebar when window isn't active.
var blinkSpeed    = 1000;           // How fast to change between the titles when "blinking" (in milliseconds).
var pulsateTitles = true;           // Pulsate (blink) IM window titles on new IM when they are not the active window.
var audioNotify   = true;           // By default, play sounds upon getting an IM?

// Server //
var pingFrequency = 2500;           // How often to ping the server (in milliseconds). Best range between 2500 and 3500 ms.
//var pingTo        = '/newgpn/ajax_im.php';  // The file that is the "server".
var url = '/gpn_chat/gpnb_ajax_im.php';

// Windows //
var imWidth       = 310;            // Default IM window width
var imHeight      = 335;            // Default IM window height
var imHistory     = true;           // "Save" conversations with buddies throughout the session

var user='';
var userId='';
var pageId='';

// Other //
//var alertCSS      = 'alphacube';    // CSS file for alerts and login/add buddy/IM anyone windows
//var alertWidth    = 400;            // Alert window width (see above)
var windowCSS     = 'default';      // CSS file for all other windows (buddylist, IMs)
var buddyListLoc  = 1;              // Buddylist location: 0=left, 1=right

// End Configurable Options //

// Begin Code                                   //
// Note: Do not edit below this line unless you //
//       know what you are doing!               //

var pass='';
var isAway=0;
var awayMessage = '';
var curSelected='';
var loggedIn=false;
var IMWindows={};
var titlebarBlinker=false;
var defaultTitle=document.title;
var blinkerTimer;
var pingTimer;
var buddyList = {};
var fontListToWin;

var onlineUsers;
var country = [];
var speciality=[];
var refresh_duration=0;

window.onunload = function() {
   if(user.length > 0) var logout=1;
}

var buddyListWin;

function fixBuddyList() {
   if(buddyListWin && buddyListWin.isVisible()) {
      buddyListWin.setSize(210, (browserHeight() - 50));
      buddyListWin.setLocation((((browserHeight()-40) / 2) - (buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (browserWidth() - buddyListWin.getSize()['width'] - 10)));
      sizeBuddyList();
   }
}
function open_online_window(uId, pId) {
	userId=uId;
	pageId=pId;
	//alert(uId+pId);
		window.onresize = fixBuddyList;
		if(!$('bl')) {
		   buddyListWin = new Window('bl', {className: "dialog", width: 210, height: (browserHeight() - 60), zIndex: 100, resizable: false,title: "Online Users/Help <img src='/gpn_images/arrow.gif' alt='pointer' />", draggable: true, closable: false, maximizable: false, minWidth: 205, minHeight: 150,showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
		}
		buddyListWin.getContent().innerHTML = '<div id="blTopToolbar"><div id="statusCountry"><a href="#" id="curStatusCountry" onclick="toggleStatusCountry();return false;">Please select Country</a></div><div id="statusSpeciality"><a href="#" id="curStatusSpeciality" onclick="toggleStatusSpeciality();return false;">Please select speciality</a></div></div><div id="ouContainer"><div id="olusers">No online users</div><div id="gpnb_buddy_title">Friend List</div><div id="gpnb_buddyList"></div></div>';

		buddyListWin.getContent().oncontextmenu = function() { return false; };
		sizeBuddyList();
		buddyListWin.setStatusBar("iGPnotebook buddy list");
		buddyListWin.showCenter(false, (((browserHeight()-40) / 2) - (buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (browserWidth() - buddyListWin.getSize()['width'] - 10)));
		buddyListWin.minimize();
		
		$('bl_minimize').removeClassName('dialog_minimize');
		$('bl_minimize').addClassName('dialog_maximize');
		
		//buddyListWin.setCookie('bl');

		online_users(uId,pageId);
		setTimeout(ping, 250);
		pingTimer = setInterval(ping, pingFrequency);
}
function online_users(uId,pageId){
	var pars = 'call=onlineusers&userId='+uId;
	var myAjax = new Ajax.Updater(
				'',
				'/gpn_chat/onlineusers.php', { 
					method: 'post',
					postBody:pars,
					onComplete: function (originalRequest){
							//alert(originalRequest.responseText);
								//var response = originalRequest.responseText;				
								var response = originalRequest.responseText.parseJSON();
								user=response.username;
								
								if($('countryList')){
									return;
								}
								
								if (response.num_user ==-1){
									onlineList.innerHTML='No online users.';
								}
	
								var x=document.createElement("div");
								x.id="countryList";
								x.className="itemList";
								document.body.appendChild(x);

								var x=document.createElement("div");
								x.id="specialityList";
								x.className="itemList";
								document.body.appendChild(x);

								onlineUsers = $A(response.array);
								
								//addCountry(response.country);
								//addSpeciality(response.speciality);

								onlineUsers.each(
												function(e){
													addCountry(e.country);
													addSpeciality(e.speciality);
													//alert(e.u_name+e.name+e.country+e.speciality);
												});
								country.sort();
								speciality.sort();
								populateCountries(country);
								populateSpecialities(speciality);

								$('curStatusCountry').innerHTML = response.country;
								$('curStatusSpeciality').innerHTML = response.speciality;
								
								onlinedropdown_change('coun');
								//$('ouContainer').innerHTML=originalRequest.responseText;
							}
					});
	buddylist(pageId);
	//setTimeout(ping, 250);
	//pingTimer = setInterval(online_users(userId,pageId), 5000);	
	
}
function populateCountries(arr){
	$('countryList').innerHTML='';
	var x = removeDuplicates(arr);
	for (var i = 0; i < x.length; i++) {
		//$('countryList').innerHTML+='<a href="#" onMouseout="setStatusCountry(1, \''+x[i]+'\');return false;">'+x[i]+'</a>';
		$('countryList').innerHTML+='<a href="#" onclick="setStatusCountry(1, \''+x[i]+'\');return false;">'+x[i]+'</a>';
	}
}
function populateSpecialities(arr){
	$('specialityList').innerHTML='';
	var y = removeDuplicates(arr);
	for (var i = 0; i < y.length; i++) {
		//$('specialityList').innerHTML+='<a href="#" onMouseOut="setStatusSpeciality(1, \''+y[i]+'\');return false;">'+y[i]+'</a>';
		$('specialityList').innerHTML+='<a href="#" onclick="setStatusSpeciality(1, \''+y[i]+'\');return false;">'+y[i]+'</a>';
	}
}
function ping() {
	if(!$('countryList')){
		//alert(userId+pageId);
		online_users(userId,pageId);
	}
	
	//alert(pageId);
	var pars = 'call=ping&userId='+userId;
 	var myAjax = new Ajax.Updater(
				'',
				url, { 
					method: 'post',
					postBody:pars,
					onComplete: function(originalRequest){
							//alert(originalRequest.responseText);
							if(trim(originalRequest.responseText).length == 0) return;
							var response = originalRequest.responseText.parseJSON();
							
							if(response.numMessages == 0) return;
							
							if(user=='') user=response.user;
							chatSession=response.messages[0].cs;
							
							var from, data;
							 for(i=0; i<response.numMessages; i++) {
								from = response.messages[i].sender;
								data = response.messages[i].message.replace(/&amp;#039;/g,'\'');
								data = data.replace(/&amp;lt;/g,'<').replace(/&amp;gt;/g,'>');
								if(!$(from + '_im')) {
								   chatIM(from,user,chatSession);
								} else {
								   if(!IMWindows[from].isVisible()) {
									  IMWindows[from].show();
									  setTimeout("scrollToBottom('" + from + "_rcvd')", 125);
								   }
								}

								var rcvdBox = $(from+"_rcvd");
								/*
								Stamp = new Date();
								var h = String(Stamp.getHours());
								var m = String(Stamp.getMinutes());
								var s = String(Stamp.getSeconds());
								h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;								
								*/

								if(data=='cap_request189'){
									//rcvdBox.innerHTML = rcvdBox.innerHTML + '<b class="sender">[' + h + ':' + m + '] ' + from + ':</b> <span style="color:#FF0000"><b>Capture Request : Accept or Reject</b></span><br>\n';
									rcvdBox.innerHTML = rcvdBox.innerHTML + '<b class="sender">'+ from + ':</b> <span style="color:#FF0000"><b>Creating Request : Yes or No</b></span><br>\n';
									scrollToBottom(from+'_rcvd');
									$(from + '_captureButton').style.display='none';
									$(from + '_acceptButton').style.display='block';
									$(from + '_acceptButton').innerHTML = 'Yes';
									$(from + '_rejectButton').style.display='block';
									$(from + '_rejectButton').style.left = (80) + 'px';
									$(from + '_rejectButton').innerHTML = 'No';
									$(from+"_sendBox").style.display='none';
									$(from+"_rcvd").focus();
									//alert('capture requested');
								}else if(data=='cap_accept189'){
									//alert('Capture Request : Accepted');
									$(from + '_captureButton').style.display='none';
									$(from + '_rejectButton').style.display='none';
									$(from + '_acceptButton').style.display='block';
									$(from + '_acceptButton').style.cursor = 'default';
									$(from + '_acceptButton').innerHTML = 'Created';
									$(from+"_sendBox").style.display='none';
									capture_complete(from);
								}else if(data=='cap_reject189'){
									//alert('Capture Request : rejected');
									$(from + '_captureButton').style.display='none';
									$(from + '_acceptButton').style.display='none';
									$(from + '_rejectButton').style.display='block';
									$(from + '_rejectButton').style.left = (0) + 'px';
									$(from + '_rejectButton').style.width = (90) + 'px';
									$(from + '_rejectButton').style.cursor = 'default';
									$(from + '_rejectButton').innerHTML = 'Not Created';							
									capture_complete(from);
								}else{
									//rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"sender\">[" + h + ":" + m + "] " + from + ":</b> <span style=\"color:#000000\">"+data +"</span><br>\n";
									rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"sender\">" + from + ":</b> <span style=\"color:#000000\">"+data +"</span><br>\n";
									
									rcvdBox.scrollTop = rcvdBox.scrollHeight - rcvdBox.clientHeight + 6;
									
									//scrollToBottom(from+'_rcvd');
									if ($(from+"_sendBox").style.display=='block')
										$(from+"_sendBox").focus();
								}

								if(Windows.getFocusedWindow().getId() != from + "_im" && pulsateTitles == true) {
								   new Effect.Pulsate(from + '_im_top');
								}
					
								if(titlebarBlinker == true && useBlinker == true) {
								   clearTimeout(blinkerTimer);
								   setTimeout("titlebarBlink('"+from+"', \""+data.replace(/\"/, '\"').replace(/<([^>]+)>/ig, '')+"\", 0)", blinkSpeed);
								}
							 }
					}
				});
}

function sendMessage(winName,chatSession) {
	//alert(chatSession);
	if(trim($(winName+"_sendBox").value).length > 0) {
		var sentText =$(winName+"_sendBox").value;
		var rcvdBox = $(winName+"_rcvd");
		/*
		Stamp = new Date();
		var h = String(Stamp.getHours());
		var m = String(Stamp.getMinutes());
		var s = String(Stamp.getSeconds());
		h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
		*/
		//rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"recipient\">[" + h + ":" + m + "] " + user + ":</b> <span style=\"color:#000000\">"+sentText +"</span><br>\n";
		rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"recipient\">" + user + ":</b> <span style=\"color:#000000\">"+sentText +"</span><br>\n";
		scrollToBottom(winName+'_rcvd');

		var pars = 'call=send&user='+user+'&recipient='+winName+'&msg='+encodeURIComponent(sentText.replace(/\'/g,'&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, "<amp>"))+'&cs='+chatSession;
		$(winName+"_sendBox").value = '';
		//alert(pars);
		var myAjax = new Ajax.Updater(
					'',
					url, { 
						method: 'post',
						postBody:pars,
						onComplete: function(originalRequest){
							//alert(originalRequest.responseText);
								var response = originalRequest.responseText.parseJSON();
								var recipient = response.recipient
								if(originalRequest.responseText == 'not_online') {
									var rcvdBox = $(recipient+"_rcvd");
									rcvdBox.innerHTML = rcvdBox.innerHTML + '<span style="color:#FF0000"><b>Error: Your last message could not be sent - the recipient is not logged in.</b></span><br>';
									scrollToBottom(recipient+'_rcvd');
								} else if(originalRequest.responseText == 'not_logged_in') {
									var logout=1;
								} else if(response.status != 'sent') {
									//alert(originalRequest.responseText);
									alert('An error occured while sending your message.');
								}							
							}
						});
		$(winName+"_sendBox").focus();
	}

}
 
function regExpEscape(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function newIMWindow() {
   if($('sendto').value.replace(/^\s*|\s*$/g,"").length > 0) {
      var toWhom = $('sendto').value;

      if(!$(toWhom + '_im')) {
         createIMWindow(toWhom, toWhom);
      } else {
         if(!IMWindows[toWhom].isVisible()) {
            IMWindows[toWhom].show();
            setTimeout("scrollToBottom('" + toWhom + "_rcvd')", 125);
         }
      }
      
      Dialog.closeInfo();
      IMWindows[toWhom].toFront();
      setTimeout("$('"+toWhom+"_sendBox').focus()", 125);
   } else {
      $('newim_error_msg').innerHTML = 'Please enter a proper username!';
      $('newim_error_msg').show(); 
      Dialog.win.updateHeight();
   }
}

function chatIM(recipientName,userName,chatSession) {
	if(!$(recipientName + '_im')){
	   //var imLeft = Math.round(Math.random()*(browserWidth()-360))+'px';
	   var imLeft = Math.round((browserWidth()/2))+'px';
	   //var imTop  = Math.round(Math.random()*(browserHeight()-400))+'px';
	   var imTop  = Math.round((browserHeight()-400))+'px';
	
	   IMWindows[recipientName] = new Window(recipientName + '_im', {className: "dialog", width: 310, height: 335, top: imTop, left: imLeft, zIndex: 200,resizable: false, title: recipientName, draggable: true, maximizable:false, minWidth: 150, minHeight: 75,
												   showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
	   
   IMWindows[recipientName].getContent().innerHTML = '<div class="rcvdMessages" id="' + recipientName + '_rcvd"></div>' + "\n" +
                                            '<div class="imToolbar" id="' + recipientName + '_toolbar"><div class="captureButton" id="'+recipientName+'_captureButton" onclick="capture(\''+recipientName+'\',\''+pageId+'\',\''+chatSession+'\');">ddfgdf</div><div class="acceptButton" id="'+recipientName+'_acceptButton" onclick="accept(\''+recipientName+'\',\''+pageId+'\',\''+chatSession+'\');"></div><div class="rejectButton" id="'+recipientName+'_rejectButton" onclick="reject(\''+recipientName+'\',\''+pageId+'\',\''+chatSession+'\');"></div>' +
                                            '</div>' +
                                            "\n" + '<input type="text" class="inputText" id="'+recipientName+'_sendBox" onfocus="blinkerOn(false);" onkeypress="keyHandler(event,\''+recipientName+'\',\''+chatSession+'\');" /><img  id="'+recipientName+'_enterKey" class="enterKey" src="/gpn_images/enter.gif" alt="enter" title="enter" onclick="mouseHandler(event,\''+recipientName+'\',\''+chatSession+'\');" />';


   $(recipientName + '_rcvd').style.height = (IMWindows[recipientName].getSize().height - 73) + 'px';
   $(recipientName + '_rcvd').style.width = (IMWindows[recipientName].getSize().width - 10) + 'px';
   
   $(recipientName + '_toolbar').style.top = (IMWindows[recipientName].getSize().height - 43) + 'px';
   $(recipientName + '_toolbar').style.width = (IMWindows[recipientName].getSize().width - 10) + 'px';
   

   $(recipientName + '_sendBox').style.top = (IMWindows[recipientName].getSize().height - 15) + 'px';
   $(recipientName + '_sendBox').style.left = '2px';
   $(recipientName + '_sendBox').style.width = (IMWindows[recipientName].getSize().width - 40) + 'px';
   $(recipientName + '_sendBox').style.fontWeight = '400';
   $(recipientName + '_sendBox').style.fontStyle = 'normal';
   $(recipientName + '_sendBox').style.textDecoration = 'none';
   $(recipientName + '_enterKey').style.left = (IMWindows[recipientName].getSize().width - 30) + 'px';
   $(recipientName + '_enterKey').style.top = (IMWindows[recipientName].getSize().height - 15) + 'px';
   
	$(recipientName + '_captureButton').style.display='block';
	$(recipientName + '_captureButton').innerHTML = 'Create iLog';

	   
   IMWindows[recipientName].setDestroyOnClose();
   IMWindows[recipientName].show();
   setTimeout("$('"+recipientName+"_sendBox').focus();", 250);

	}
}
function capture(recipient,pageId,chatSession){
	if ($(recipient + '_captureButton').innerHTML=='Creating...') return;
	//alert(recipient+pageId+chatSession);
	var pars = 'call=capture&user='+user+'&recipient='+recipient+'&pid='+pageId+'&cs='+chatSession;
	//alert(pars);
	var myAjax = new Ajax.Updater(
				'',
				url, { 
					method: 'post',
					postBody:pars,
					onComplete: function(originalRequest){
							//alert(originalRequest.responseText);
							var response = originalRequest.responseText;
							
							if (response=='csent'){
								var rcvdBox = $(recipient+"_rcvd");
								/*
								Stamp = new Date();
								var h = String(Stamp.getHours());
								var m = String(Stamp.getMinutes());
								var s = String(Stamp.getSeconds());
								h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
								*/
								//rcvdBox.innerHTML = rcvdBox.innerHTML + '<b class="recipient">[' + h + ':' + m + '] ' + user + ':</b> <span style="color:#FF0000">Capture request was send to <b>'+recipient+'</b></span><br>\n';
								rcvdBox.innerHTML = rcvdBox.innerHTML + '<b class="recipient">' + user + ':</b> <span style="color:#FF0000">Creating request was sent to <b>'+recipient+'</b></span><br>\n';
								scrollToBottom(recipient+'_rcvd');
								$(recipient + '_captureButton').style.cursor = 'default';
								$(recipient + '_captureButton').innerHTML='Creating...';
						
								$(recipient + '_sendBox').style.display='none';
								$(recipient + '_rcvd').focus();
								
							}						
						} 
					});						
}
function accept(recipient,pageId,chatSession){
	if($(recipient + '_acceptButton').innerHTML=='Created' || $(recipient + '_rejectButton').innerHTML=='Not Created') return;
	
	var pars = 'call=accept&user='+user+'&recipient='+recipient+'&pid='+pageId+'&cs='+chatSession;
	//alert(pars);
	var myAjax = new Ajax.Updater(
				'',
				url, { 
					method: 'post',
					postBody:pars,
					onComplete: function (originalRequest){
							//alert(originalRequest.responseText);
							var response = originalRequest.responseText;
							
							if (response=='accepted'){
								$(recipient + '_rejectButton').style.display='none';
								$(recipient + '_captureButton').style.display='none';
								$(recipient + '_acceptButton').style.display='block';
								$(recipient + '_acceptButton').style.cursor = 'default';
								$(recipient + '_acceptButton').innerHTML='Created';
								capture_complete(recipient);
							}						
						} 
					});
}
function reject(recipient,pageId,chatSession){
	if($(recipient + '_acceptButton').innerHTML=='Accepted' || $(recipient + '_rejectButton').innerHTML=='Rejected') return;
	
	var pars = 'call=reject&user='+user+'&recipient='+recipient+'&pid='+pageId+'&cs='+chatSession;
	//alert(pars);
	var myAjax = new Ajax.Updater(
				'',
				url, { 
					method: 'post',
					postBody:pars,
					onComplete: function (originalRequest){
							//alert(originalRequest.responseText);
							var response = originalRequest.responseText;
							if (response=='rejected'){
								$(recipient + '_acceptButton').style.display='none';
								$(recipient + '_captureButton').style.display='none';
								$(recipient + '_rejectButton').style.display='block';
								$(recipient + '_rejectButton').style.left = (0) + 'px';
								$(recipient + '_rejectButton').style.width = (90) + 'px';
								$(recipient + '_rejectButton').style.cursor = 'default';
								$(recipient + '_rejectButton').innerHTML='Not Created';
								capture_complete(recipient);
							}
						}
					});
}

function createIMWindow(name, imTitle) {
   var imLeft = Math.round(Math.random()*(browserWidth()-360))+'px';
   var imTop  = Math.round(Math.random()*(browserHeight()-400))+'px';

   IMWindows[name] = new Window(name + '_im', {className: "dialog", width: 310, height: 335, top: imTop, left: imLeft, zIndex: 200,
                                               resizable: true, title: imTitle, draggable: true, minWidth: 250, minHeight: 150,
                                               showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
   IMWindows[name].getContent().innerHTML = '<div class="rcvdMessages" id="' + name + '_rcvd"></div>' + "\n" +
                                            '<div class="imToolbar" id="' + name + '_toolbar">' +
                                            '</div>' +
                                            "\n" + '<input type="text" class="inputText" id="'+name+'_sendBox" onfocus="blinkerOn(\'false\');" onkeypress="keyHandler(event,'+"'"+name+"'"+');" />';
   $(name + '_rcvd').style.height = (IMWindows[name].getSize().height - 73) + 'px';
   $(name + '_rcvd').style.width = (IMWindows[name].getSize().width - 10) + 'px';
   
   $(name + '_toolbar').style.top = (IMWindows[name].getSize().height - 43) + 'px';
   $(name + '_toolbar').style.width = (IMWindows[name].getSize().width - 10) + 'px';
   

   $(name + '_sendBox').style.top = (IMWindows[name].getSize().height - 15) + 'px';
   $(name + '_sendBox').style.left = '2px';
   $(name + '_sendBox').style.width = (IMWindows[name].getSize().width - 16) + 'px';
   $(name + '_sendBox').style.fontWeight = '400';
   $(name + '_sendBox').style.fontStyle = 'normal';
   $(name + '_sendBox').style.textDecoration = 'none';
   
   IMWindows[name].show();
   setTimeout("$('"+name+"_rcvd').focus();", 250);
}
function mouseHandler(e, name) {
	if (e.type=='click' && $(name+'_sendBox').value!=''){
		sendMessage(name,chatSession);	
	}
	$(name+'_sendBox').focus()
}

function keyHandler(e, name) {
   var asc = document.all ? event.keyCode : e.which;
   if(asc == 13 && $(name+'_sendBox').value!=''){
      sendMessage(name,chatSession);
   }
   return asc != 13;
}
function loginHandler(e) {
   var asc = document.all ? event.keyCode : e.which;
   if(asc == 13) login();
   return asc != 13;
}

function destroyIMWindow(name) {
   var toKill = $(name);
   toKill.parentNode.removeChild(toKill);
}

function addBuddyToList(username, groupname) {
   if(!$(groupname.replace(/\s/, '_') + '_group')) addGroupToList(groupname);

   var groupList = $(groupname.replace(/\s/, '_') + '_group');

   groupList.innerHTML += '<li id="'+username+'_blItem" class="buddy" onmousedown="return false;" onselectstart="return false;" onmouseover="selectBuddy(this, \''+username+'\', true);" onmouseout="selectBuddy(this, \''+username+'\', false);" ondblclick="onBuddyDblClick();">&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/online.png" width="16" height="16" alt="" id="'+username+'_blImg">&nbsp;'+username+'</li>';
}

function moveBuddy(username, groupname) {
   if(groupname == null) return;
   if($(username+'_blItem').parentNode.id == $(groupname.replace(/\s/, '_') + '_group')) return;
   if(!$(groupname.replace(/\s/, '_') + '_group')) addGroupToList(groupname);
   
   $(groupname.replace(/\s/, '_') + '_group').insertBefore($(username+'_blItem'), null);
}

function addGroupToList(groupname) {
   var bList = $('buddylist');
   
   bList.innerHTML = (groupname=='Offline' ? bList.innerHTML : '') + '<li id="' + groupname.replace(/\s/, '_') + '_groupTop" class="groupTop" onmousedown="return false;" onselectstart="return false;"onclick=" toggleGroup(\'' + groupname + '\');">' + groupname + ' <img id="' + groupname.replace(/\s/, '_') + '_groupArrow" src="images/' + windowCSS + '/arrow.png" /></li>' + "\n" + '<ul id="' + groupname.replace(/\s/, '_') + '_group" class="group"></ul>' + (groupname!='Offline' ? bList.innerHTML : '');
}

function toggleGroup(groupname) {
   var groupList = $(groupname.replace(/\s/, '_') + '_group');
   var groupArrow = $(groupname.replace(/\s/, '_') + '_groupArrow');
   
   if(groupList.style.display != 'none') {
      groupList.style.display = 'none';
      groupArrow.src = 'images/' + windowCSS + '/arrow_up.png';
   } else {
      groupList.style.display = 'block';
      groupArrow.src = 'images/' + windowCSS + '/arrow.png';
   }
}

function selectBuddy(sel, username, selected) {
   if(selected === false) {
      sel.style.background = '#fff';
      sel.style.color = '#333';
      curSelected = '';
   } else {
      sel.style.background = '#e1ebf7';
      sel.style.color = '#000';
      curSelected = username;
   }
}

function onBuddyDblClick() {
   if(curSelected.length > 0) {
      if(!$(curSelected + '_im')) {
         createIMWindow(curSelected, curSelected);
      } else {
         if(!IMWindows[curSelected].isVisible()) {
            IMWindows[curSelected].show();
            setTimeout("scrollToBottom('" + curSelected + "_rcvd')", 125);
            setTimeout("$('" + curSelected + "_sendBox').focus();", 250);
         }
      }
   }
}

function scrollToBottom(id) {
   $(id).scrollTop = $(id).scrollHeight - $(id).clientHeight;
}
   
function trim(text) {
   if(text == null) return null;
   return text.replace(/^[ \t]+|[ \t]+$/g, "");
}

function saveBuddyList() {  
   var xhConn = new XHConn();
   xhConn.connect(pingTo, "POST", "call=save&from="+user+"&pwd="+pass+"&list="+encodeURIComponent(buddyList.toJSONString()), null);
}

function setStatusCountry(status, country) {
   if(status == 1) { // away
      //isAway = 1;
      //awayMessage = country;
      $('curStatusCountry').innerHTML = country;
   } else { // back
      //isAway = 0;
      //awayMessage = '';
      $('curStatusCountry').innerHTML = "Please Select Country";
   }
   $('countryList').style.display = 'none';
   onlinedropdown_change('coun');
}
function setStatusSpeciality(status, speciality) {
   if(status == 1) { // away
      //isAway = 1;
      //awayMessage =speciality;
      $('curStatusSpeciality').innerHTML = speciality;
   } else { // back
      //isAway = 0;
      //awayMessage = '';
      $('curStatusSpeciality').innerHTML = "Please Select speciality";
   }
   $('specialityList').style.display = 'none';
   
   onlinedropdown_change('spec');

}
function addCountry(name){
	country[country.length]=name;
	//alert(country[country.length-1]);
}

function addSpeciality(name){
	speciality[speciality.length]=name;
	//alert(speciality[speciality.length-1]);
}

function removeDuplicates(arr){
	var a=[],x=1,y=0;

	for (var i = 0; i < arr.length; i++) {
		if (arr[i]==arr[i+1])
			x++;
		else{
			a[a.length]=arr[i]+' ('+x+')';
			x=1;
		}
	}
	/*
	if (a[a.length-1]==arr[arr.length])
		a[a.length-1]=arr[arr.length]+' ('+x+')';
	else
		a[a.length]=arr[arr.length]+' ('+x+')';
	*/
	//alert(a);
	return a;
}

function onlinedropdown_change(type){
	$('olusers').innerHTML="Loading...";
	var x = $('curStatusSpeciality').innerHTML;
	var y= $('curStatusCountry').innerHTML;
	x=trim(x.replace(/\([\d]+\)/, ""));
	
	y=trim(y.replace(/\([\d]+\)/, ""));
	x=trim(x.replace('&amp;','&'));
   //$('olusers').innerHTML=x+' - '+y;
   
  /* 
	if (type=='coun'){ //Country
		speciality= speciality.clear();
		onlineUsers.each(
					function(e){
						//alert(e.u_name+e.name+e.country+e.speciality);
						if (e.country==y){
							addSpeciality(e.speciality);
						}
					});
		populateSpecialities(speciality);
		//$('curStatusCountry').innerHTML = response.country;
		//$('curStatusSpeciality').innerHTML = response.speciality;
		
		
	}else if (type=='spec'){ //speciality
		var countryCollection =[];
		onlineUsers.each(
					function(e){
						//alert(e.u_name+e.name+e.country+e.speciality);
						if (e.speciality==x)
							countryCollection[countryCollection.length]=e.country;
					});
		if(countryCollection.length>0){
			populateCountries(countryCollection);
		}else
			populateCountries(country);
		populateSpecialities(speciality);
	}
	
*/
	var u_name, name, userCollection='';
	onlineUsers.each(
					function(e){
						//alert(e.u_name+e.name+e.country+e.speciality);
						//alert(y+'-'+e.country);
						if (e.country==y && e.speciality==x)
							
							// request to change - 08-08-2007
							
							//userCollection+='<a href="#" onClick="initiating(\''+e.u_name+'\',\''+user+'\',\''+pageId+'\');">'+e.u_name+'</a> <a href="#" onclick="makeBuddy(\''+e.u_name+'\')"><img src="/gpn_images/buddy.gif" alt="Make my Buddy" title="Make my Buddy" border="0" /></a><br />';
							if(e.u_name=='OnlineHelp'){
								userCollection+='<a href="#" onClick="initiating(\''+e.u_name+'\',\''+user+'\',\''+pageId+'\');">'+e.u_name+'</a> <a href="#" onclick="makeBuddy(\''+e.u_name+'\')"><img src="/gpn_images/buddy.gif" alt="Make my Buddy" title="Make my Buddy" border="0" /></a><br />';
								
								
								}else {						
							userCollection+=e.u_name+'<a href="#" onclick="makeBuddy(\''+e.u_name+'\')"><img src="/gpn_images/buddy.gif" alt="Make my Buddy" title="Make my Buddy" border="0" /></a><br />';
								}
					});
	
	if (userCollection)
		$('olusers').innerHTML=userCollection;
	else
		$('olusers').innerHTML='No online users for this selection';	
}
function makeBuddy(uname){
	Dialog.confirm("Do you really want to make "+uname+" as your friend ?", 
              {windowParameters: {width:300}, okLabel: "Ok", 
               buttonClass: "myButtonClass",
               id: "gpnb_confirm",
               cancel:function() {Dialog.closeInfo();},
               ok:function() {
				   	//alert('ok');Dialog.closeInfo();
					var pars = 'call=makebuddy&uname='+uname+'&uId='+userId;
					var myAjax = new Ajax.Updater(
										'',
										'/gpn_chat/onlineusers.php', {
												method: 'post',
												postBody:pars,
												onComplete: function (originalRequest){	
													Dialog.closeInfo();
													if (originalRequest.responseText=='friend')
														alert(uname+' is already your friend');
													else if (originalRequest.responseText=='done')
														alert('Your friend should accept you first');
													else
														alert('An error occured while processing your request.');
											}
              			});
			   //open_online_window(userId, pageId);
			   }});
}

function customAway() {
   $('curStatus').style.display = 'none';
   $('customStatus').style.display = 'block';
   $('customStatus').focus();
}

function processCustomAway(e) {
   var asc = document.all ? event.keyCode : e.which;
   
   if(asc == 13) {
      isAway = 1;
      awayMessage = $('customStatus').value;
      $('curStatus').innerHTML = awayMessage.substring(0, 30) + (awayMessage.length > 30 ? '...' : '');
      $('curStatus').style.display = 'block';
      $('customStatus').style.display = 'none';      
   }
   return asc != 13;
}

function toggleAudio() {
   if(audioNotify == true) {
      audioNotify = false;
      $('toggleaudio').src = 'images/'+windowCSS+'/audio_off.png';
   } else {
      audioNotify = true;
      $('toggleaudio').src = 'images/'+windowCSS+'/audio_on.png';
   }
}

function toggleBold(name) {
   $(name + '_sendBox').style.display = 'none'; // horrah weird Opera 9 input refresh!
   if($(name + '_sendBox').style.fontWeight == '400') {
      $(name + '_bold').src = 'images/' + windowCSS + '/bold_on.png';
      $(name + '_sendBox').style.fontWeight = '700';
   } else {
      $(name + '_sendBox').style.fontWeight = '400';
      $(name + '_bold').src = 'images/' + windowCSS + '/bold_off.png';
   }
   $(name + '_sendBox').style.display = 'block'; // horrah weird Opera 9 input refresh!
   $(name + '_sendBox').focus();
}
   
function toggleItalic(name) {
   $(name + '_sendBox').style.display = 'none'; // horrah weird Opera 9 input refresh!
   if($(name + '_sendBox').style.fontStyle == 'normal') {
      $(name + '_sendBox').style.fontStyle = 'italic';
      $(name + '_italic').src = 'images/' + windowCSS + '/italic_on.png';
   } else {
      $(name + '_sendBox').style.fontStyle = 'normal';
      $(name + '_italic').src = 'images/' + windowCSS + '/italic_off.png';
   }
   $(name + '_sendBox').style.display = 'block'; // horrah weird Opera 9 input refresh!
   $(name + '_sendBox').focus();
} 

function toggleUnderline(name) {
   $(name + '_sendBox').style.display = 'none'; // horrah weird Opera 9 input refresh!
   if($(name + '_sendBox').style.textDecoration == 'none') {
      $(name + '_sendBox').style.textDecoration = 'underline';
      $(name + '_underline').src = 'images/' + windowCSS + '/underline_on.png';
   } else {
      $(name + '_sendBox').style.textDecoration = 'none';
      $(name + '_underline').src = 'images/' + windowCSS + '/underline_off.png';
   }
   $(name + '_sendBox').style.display = 'block'; // horrah weird Opera 9 input refresh!
   $(name + '_sendBox').focus();
}

function titlebarBlink(name, message, alter) {
   if(titlebarBlinker == false) {
      document.title = defaultTitle;
      return;
   }
   
   if(alter == 0) {
      document.title = name + '!';
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 1)", 1000);
   } else if(alter == 1) {
      document.title = '"' + message.substring(0, 10) + (message.length > 10 ? '...' : '') + '"';
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 2)", 1000);
   } else if(alter == 2) {
      document.title = defaultTitle;
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 0)", 1000);
   }
}

function blinkerOn(onoff) {
   if(onoff == true)
      titlebarBlinker = true;
   else
      titlebarBlinker = false;
}

function browserWidth() {
   if (self.innerWidth) {
      return self.innerWidth;
   } else if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientWidth;
   } else if (document.body) {
      return document.body.clientWidth;
   }
   return 630;
}

function browserHeight() {
   if (self.innerWidth) {
      return self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientHeight;
   } else if (document.body) {
      return document.body.clientHeight;
   }
   return 470;
}

function randomNumber(max) {
   return Math.round(Math.random()*max);
}
function getElementsByCondition(condition, container) {
   container = container||document;
   var all = container.all||container.getElementsByTagName('*');
   var arr = [];
   for(var k=0;k<all.length;k++) {
      var elm = all[k];
      if(condition(elm,k))
         arr[arr.length] = elm;
   }
   return arr;
}

function getElementsByClass(node, searchClass, tag) {
   var classElements = [];
   var els = node.getElementsByTagName(tag); // use "*" for all elements
   var elsLen = els.length;
   var pattern = new RegEx("\\b"+searchClass+"\\b");
   for (i = 0, j = 0; i < elsLen; i++) {
      if ( pattern.test(els[i].className) ) {
         classElements[j] = els[i];
         j++;
      }
   }
   return classElements;
}

function isDefined(variable) {
   return (typeof(variable) == "undefined") ? false : true;
}

function inArray(arr, value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
   var i;
   for (var group in arr) {
     // Matches identical (===), not just similar (==).
      for(i=0; i<arr[group].length; i++) {
         if(arr[group][i] === value)
            return true;
      }
   }
   return false;
};

function addOption(selectbox,text,value) {
   var optn = document.createElement("OPTION");
   optn.text = text;
   optn.value = value;
   selectbox.options.add(optn);
}

function removeItems(array, item) {
   var i = 0;
   while (i < array.length) {
      if (array[i] == item) {
         array.splice(i, 1);
      } else {
         i++;
      }
   }
   return array;
}

function removeAllOptions(selectbox) {
   var i;
   for(i=selectbox.options.length-1;i>=0;i--) {
      selectbox.remove(i);
   }
}

function removeOptions(selectbox, val) {
   var i;
   for(i=selectbox.options.length-1;i>=0;i--) {
      if(selectbox.options[i].value === val)
         selectbox.remove(i);
   }
}

String.prototype.isAlphaNumeric = function() {return /^[a-z0-9_\d]+$/.test (this)};

function Debug() { 
   this.create = function() {
      createIMWindow('Debug', 'Debug');
   }
   
   this.write = function(text) {
      $('Debug_rcvd').innerHTML += text + "<br>\n";
   }
}

function initiating (recipientName,userName,pageId){
	//alert(recipientName+userName+pageId);
	if($(recipientName + '_im')) return;
	
	Dialog.info("Chat window intializing. Please wait ...", 
					{windowParameters: {width:250, height:100}, showProgress: true}); 
	user=userName;
	var recipient=recipientName;
	var pars = 'call=initiate&user='+user+'&recipient='+recipient+'&pId='+pageId;
	//alert(pars);
	var myAjax = new Ajax.Updater(
				'',
				url, { 
					method: 'post',
					postBody:pars,
					onComplete: initiatedResponse
					});
}

function initiatedResponse(originalRequest){
	Dialog.closeInfo();
	//alert(userId+pageId);
	//alert(originalRequest.responseText);
	if (originalRequest.responseText=='not_online'){
		alert('You can\'t initiate the chat - the recipient is not logged in.'); 
		open_online_window(userId, pageId);
		return;
	}else if(originalRequest.responseText == 'not_logged_in') {
		//alert(refresh_duration);
		if (refresh_duration>3){
			location.reload(true);
			return;
		}else{
		   refresh_duration = refresh_duration+1;
		}
		alert('You can\'t initiate the chat.\n Please wait - refreshing the online list...'); 
		open_online_window(userId, pageId);
		return;
	}

	var response = originalRequest.responseText.parseJSON();
	//alert(response);
	if(response.status == 'initiated'){
		refresh_duration=0;
		chatSession = response.session;
		var recipient = response.recipient;
		chatIM(recipient,user,chatSession);
	}else if (response.status == 'chat_start'){
		chatSession = response.session;
		recipient = response.recipient;

	if (response.numMessages>0){
	 var from, to , data,chatfrom,ttime;
	 for(i=0; i<response.numMessages; i++) {
		 
		from = response.messages[i].sender;
		data = response.messages[i].message;
		
		data = data.replace(/&amp;lt;/g,'<').replace(/&amp;gt;/g,'>');
		//encodeURIComponent(sentText.replace(/\'/g,'&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, "<amp>")
		to = response.messages[i].to;
		//ttime=response.messages[i].ttime;
		
		if(from==user)
			chatfrom=to;
		if(to==user)
			chatfrom=from;
		if(!$(chatfrom + '_im'))
		   chatIM(chatfrom,user,chatSession);
		else {
		   if(!IMWindows[chatfrom].isVisible()) {
			  IMWindows[chatfrom].show();
			  setTimeout("scrollToBottom('" + chatfrom + "_rcvd')", 125);
		   }
		}
			var rcvdBox = $(chatfrom+"_rcvd");
			rcvdBox.innerHTML = rcvdBox.innerHTML + from + ":"+data +"<br>\n";
			
			scrollToBottom(chatfrom+'_rcvd');
	}
	}else
		chatIM(recipient,user,chatSession);
	
	$(recipient+"_sendBox").focus();
	}
}
function buddylist(pageId){
	//$('ouContainer').innerHTML+='<div id="gpnb_buddy_title">Buddy List</div><div id="gpnb_buddyList">Loading...</div>';
	var pars = 'call=buddylist&userId='+userId;
	var myAjax = new Ajax.Updater(
				'',
				'/gpn_chat/onlineusers.php', { 
					method: 'post',
					postBody:pars,
					onComplete: function(originalRequest){
						//alert(originalRequest.responseText);
						//$('ouContainer').innerHTML=originalRequest.responseText;
						var response = originalRequest.responseText;
						
						var buddylist = $('gpnb_buddyList');
						
						if (response =='no_buddy')
							buddylist.innerHTML='Buddy list is empty';
						else{
							buddylist.innerHTML='';
							var response = response.parseJSON();
							var uname, name;
							 for(i=0; i<response.num_online; i++) {
								uname = response.onusers[i].u_name;
								//name = response.onusers[i].name;
								//alert(name+uname);
								
								
								buddylist.innerHTML+='<img src="/gpn_images/friend.gif" alt="online" title="online" border="0" /><a href="#" onClick ="initiating(\''+uname+'\',\''+user+'\',\''+pageId+'\');">'+uname+'</a><br />';
								
							}
							 for(i=0; i<response.num_offline; i++) {
								uname = response.offusers[i].u_name;
								//alert(name+uname);
								buddylist.innerHTML+='<img src="/gpn_images/friend_off.gif" alt="offline" title="offline">'+uname+'<br />';
								
							}		
						}
						}
					});

}

function capture_complete(recipient) {
	$(recipient + '_sendBox').style.display='none';
	$(recipient + '_rcvd').focus();
}