// -----------------------------------------------------
// open remote control
// -----------------------------------------------------
	// variables
	var openWindows = new Array(1000);
	var loadNewMessagesWithAjax = true;
	
	// keep track when "Remote Control Chat, Main" window gets closed, because then we need to close the children aswell
		// interval object container
		var objRCCParent = '';
		
		// start interval
		function closeRCCChild()
		{
			objRCCParent = setInterval("checkRCCParent()", 500);
		}
		
		// the checker function
		function checkRCCParent()
		{
			// make sure opener exists (Remote Control Chat, Main)
			if(window.opener)
			{
				// check if it's closed
				if(window.opener.closed)
				{
					// "Remote Control Chat, Main" is closed, close child (private chat)
					clearInterval(objRCCParent);
					self.close();
				}
			}
			else
			{
				// "Remote Control Chat, Main" is closed, close child (private chat)
				clearInterval(objRCCParent);
				self.close();
			}
		}
	
	
	// open remote control window
	function openRemoteControl()
	{
		// get scrren size (to be able to determine position & size)
		var screen_w = parseInt(screen.width);
		var screen_h = parseInt(screen.height);
		
		// determine MAIN size
			// set default size (prefered)
			var rcc_w = '300';
			var rcc_h = '450';
			
			// check for low screen resolution
			if(screen_w <= '800' && screen_h <= '600')
			{
				// set new size
				rcc_w = '200';
				rcc_h = '350';
			}
		
		// determine MAIN position
			// set position
			var rcc_pos_x = (screen_w-rcc_w-40);
			var rcc_pos_y = (screen_h-(screen_h-70));
		
		var winURL 			= config['a_url'] + "remote_control/";			// url to load in the window
		var winName 		= "AmcmsRemoteControl";							// name of the window
		window.open(winURL, winName, "width="+rcc_w+",height="+rcc_h+",top="+rcc_pos_y+",left="+rcc_pos_x+",scrollbars=0,resizable=1,menubar=0,location=0,toolbar=0,status=1,directories=0");
	}
	
	// opens up a private chat window (child to AmcmsRemoteControl, that is, the main remote control window)
	function openPrivateChat(mid, oType, window_index)
	{
		// get scrren size (to be able to determine position & size)
		var screen_w = screen.width;
		var screen_h = screen.height;
		
		// determine "Remote Control Chat, Child" size
			// set default size (prefered)
			var rcc_w = '370';
			var rcc_h = '370';
			
			// check for low screen resolution
			if(screen_w <= '800' && screen_h <= '600')
			{
				// set new size
				rcc_w = '300';
				rcc_h = '300';
			}
		
		// determine MAIN position
			// set position
			var rcc_pos_x = (50 + (window_index*15));
			var rcc_pos_y = (100 + (window_index*10));
			
		oType							= oType != '' ? '&'+oType : '';
		
		var winURL 						= config['a_url'] + "remote_control_chat/?mid="+mid+oType;	// url to load in the window
		var winName 					= "AmcmsRemoteControlChat"+mid.trim();						// name of the window
		
		// check if window already is open
		if(openWindows && openWindows[winName] && !openWindows[winName].closed)
		{
			// window already open, load message from private chat iReceiver
			if(loadNewMessagesWithAjax || openWindows[winName].frames['iReceiver'])
			{
				// build url & querystring
				var url 		= config['a_url'] + 'receivers/remote_control_chat_append.php';
				var querystring = 'mid='+mid;
				
				// Whether to use ajax or regular iframe loading
				if(loadNewMessagesWithAjax)
				{
					// ajax
					if(openWindows[winName].mcmsAjax)
					{
						openWindows[winName].mcmsAjax.loadUrl(url, 'get', querystring, 'alert');
					}
					else
					{
						setTimeout("openWindows['"+winName+"'].mcmsAjax.loadUrl('"+url+"', 'get', '"+querystring+"', 'alert');", 2000);
					}
				}
				else
				{
					// iframe load
					openWindows[winName].frames['iReceiver'].document.location.href = config['a_url'] + "receivers/remote_control_chat_append.php?mid="+mid+"";
				}
			}
			
			// make window active
			//openWindows[winName].focus();
		}
		else
		{
			// window not open
			openWindows[winName] = window.open(winURL, winName, "width="+rcc_w+",height="+rcc_h+",top="+rcc_pos_y+",left="+rcc_pos_x+",scrollbars=0,resizable=1,menubar=0,location=0,toolbar=0,status=1,directories=0");
		}
		
		// start timer for reseting status message incase chat buddy decides to close chat window while typing (or else it would never stop showing "Richard is typing ...")
		if(oType == '&typing')
		{
			setTimeout("if(openWindows['"+winName+"'] && !openWindows['"+winName+"'].closed) openWindows['"+winName+"'].resetStatusText('"+global_usr_for_typing+"');", 120000);
		}
	}
	
	// open all remote control chat requests 
	// (a request is sent to user2 when user1 opens private chat window and user2 is 
	//  not online on remote control, but if user2 is online on remote control the private window will be 
	//  opened automaticaly and this function will never be loaded, this is only loaded onload="")
	function openRemoteControlChatRequests()
	{ 
		// make sure we got the request list
		if(window.opener && !window.opener.closed)
		{
			if(window.opener.remoteControlChatRequests)
			{
				// iterate all users in chat request list and open their window
				for(var i = 0; i < window.opener.remoteControlChatRequests.length; i++)
				{
					// make sure chat request mid is not empty
					if(window.opener.remoteControlChatRequests[i] != '')
					{
						// open private chat window (child to AmcmsRemoteControl, that is, the main remote control window)
						openPrivateChat(window.opener.remoteControlChatRequests[i], '', i);
						
						// decrease counter in "icon"
						// remote control chat
						if(window.opener.document.getElementById('blinkRemoteControlChat'))
						{
							// decrease blink counter
								// decrease number
								var val = parseInt(window.opener.document.getElementById('blinkRemoteControlChat').innerHTML);
								window.opener.document.getElementById('blinkRemoteControlChat').innerHTML = (val > 0) ? val-1 : 0;
					
								// stop icon from blinking
								if(window.opener.document.getElementById('blinkRemoteControlChatImg'))
								{
									window.opener.document.getElementById('blinkRemoteControlChatImg').src = config['a_url']+'inc/gfx/icon_header_remote_p.gif';;
								}
								
							// remove MID from request list
							window.opener.remoteControlChatRequests[i] = '';
						}
					}
				}
			}
		}
	}
	
	// when message has been sent:
	//  1. append message to own innerHTML.
	//  2. clear textarea.
	//  3. set focus on textarea
	function onMessageSubmit(receiver_mid)
	{
		// append message to history
		var msg = '';
		if(document.getElementById('remoteControlChatHistory'))
		{
			// get message
			var msg = document.getElementById('frmRCCMessage') ? document.getElementById('frmRCCMessage').value : '';
			
			// don't do anything unless a message was sent
			if(msg.length > 0)
			{
				// append message to textarea
				append_message(msg.htmlEntities(), sess_username, true, '', 'append');
				
				// scroll chat content
				scrollChatHistory();
				
				// set chat focus
				setChatFocus();
			}
		}
	}
	
	// count and limit message length
	function message_length()
	{
		// get message
		var msg = document.getElementById('frmRCCMessage') ? document.getElementById('frmRCCMessage').value : '';

		// get message length
		var msg_length = parseInt(msg.length);
		
		// show chars left to write
		if(document.getElementById('frmMsgLength')) document.getElementById('frmMsgLength').innerHTML = (2000-msg_length);
		
		// check length
		if(msg_length >= 2000) 
		{
			// fix length
			if(document.getElementById('frmRCCMessage'))
			{
				// cut text at the end
				document.getElementById('frmRCCMessage').value = document.getElementById('frmRCCMessage').value.substr(0, 2000);
			}
		}
	}
	
	// append message to textarea
	var printed_messages = new Array();
	function append_message(msg, username, nl2br, msg_type, rccId)
	{
		// declare rccId (the id which makes each message unique, and prevents them from beeing printed several times)
		rccId = (rccId != undefined && rccId != 'undefined') ? rccId : '';
		
		// make sure message has not already been printed
		if(printed_messages[rccId] == undefined || printed_messages[rccId] == 'undefined')
		{
			// declare this rccId as "printed"
			if(rccId != 'append') printed_messages[rccId] = true;
			
			// set nl2br default value
			nl2br = (nl2br == 'undefined' || nl2br == undefined) ? true : nl2br;
			
			// get message type [system] [notify]
			msg_type = (msg_type != 'undefined' && msg_type != undefined) ? msg_type : '';
			
			// replace \n & \r to <br/>
			msg = msg.replace(/\r/g, '');
			if(nl2br)
			{
				msg = msg.replace(/\n/g, '<br/>');
			}
			
			// fix tabs and nbsp
			msg = msg.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
			msg = msg.replace(/\ /g, '&nbsp;');
			
			// don't do anything unless a message was sent
			if(msg.length > 0)
			{
				if(document.getElementById('remoteControlChatHistory'))
				{
					// check message type
					if(msg_type == '') 
					{
						msg = msg.replace(/&nbsp;/g, ' ');
						
						document.getElementById('remoteControlChatHistory').innerHTML += "<b>"+username+"</b> s&auml;ger:<br/>"+msg+"<br/>";
					}
					else if(msg_type == 'notify')
					{
						document.getElementById('remoteControlChatHistory').innerHTML += "<br/><span style='color: gray;'><b>MEDDELANDE</b><br/>"+msg+"</span><br/>";
					}
				}
			}
		}
		else
		{
			//alert("DUBBEL: " + printed_messages[rccId]);
		}
	}
	
	// ----------------------------------
	// make chat window "blink"
	// ----------------------------------
		var toggle_mode = 0;
		var objInt = "";
		
		// blink
		function blink_window()
		{
			objInt = setInterval('toggle_title("'+toggle_mode+'")', 1000);
		}
		
		// stop blink
		function stop_blink()
		{
			clearInterval(objInt);
		}
		
		// toggle blink (the actual toggler)
		function toggle_title()
		{
			if(toggle_mode == 0)
			{
				// Updates the title of the frameset if possible (ns4 does not allow this)
			    if(typeof(parent.document) != 'undefined' && typeof(parent.document) != 'unknown' && typeof(parent.document.title) == 'string')
			    {
					parent.document.title = "[NYTT MEDDELANDE]";
					toggle_mode = 1;
			    }
			}
			else
			{
				if (typeof(parent.document) != 'undefined' && typeof(parent.document) != 'unknown' && typeof(parent.document.title) == 'string')
			    {
					document.title = "[-]";
					toggle_mode = 0;
			    }
			}
		}
	
	
	// scroll chat history
	function scrollChatHistory()
	{
		// scroll content
		if(document.getElementById('remoteControlChatHistory')) 
		{
			document.getElementById('remoteControlChatHistory').scrollTop = 10000000;
		}
	}
	
	// set focus on chat textarea
	function setChatFocus()
	{
		// set focus on chat textarea
		if(document.getElementById('frmRCCMessage')) document.getElementById('frmRCCMessage').focus();
	}
	
	// make sure content stays the same size as window (even after resize)
	var oldWidth 	= 0;
	var oldHeight 	= 0;
	function resizeContent()
	{
		// get window size
		if(document && document.documentElement && document.documentElement.clientWidth)
		{
			var winWidth = document.documentElement.clientWidth ? parseInt(document.documentElement.clientWidth) : 0;
			var winHeight = document.documentElement.clientHeight ? parseInt(document.documentElement.clientHeight) : 0;
		}
		else if(document && document.body && document.body.clientWidth)
		{
			var winWidth = document.body.clientWidth ? parseInt(document.body.clientWidth) : 0;
			var winHeight = document.body.clientHeight ? parseInt(document.body.clientHeight) : 0;
		}
		else
		{
			var winWidth = 0;
			var winHeight = 0;
		}
		
		// remove 3 pixels to keep the actual content within window size
			// remote only for REMOTE CONTROL, MAIN WINDOW
			if(!document.getElementById('remoteControlChatHistory'))
			{
				winWidth = winWidth-3;
				winHeight = winHeight-3;
			}
			else
			{
				winWidth = winWidth;
				winHeight = winHeight;
			}
			
		// check if size has changed since last check
		if(winWidth != oldWidth || winHeight != oldHeight)
		{
			// REMOTE CONTROL, MAIN WINDOW
			// set content size
			if(document.getElementById('remoteControlArea')) document.getElementById('remoteControlArea').style.width 	= winWidth + "px";
			if(document.getElementById('remoteControlArea')) document.getElementById('remoteControlArea').style.height 	= winHeight + "px";
				
				// set length of "personal message" field
				if(document.getElementById('frmPersonalMessage')) document.getElementById('frmPersonalMessage').style.width 	= ((winWidth-25) >= 0 ? (winWidth-25) : 0)-63 + "px";
				
				// set "friends list" content area
				if(document.getElementById('remoteControlFriendsList')) document.getElementById('remoteControlFriendsList').style.width 	= winWidth + "px";
				if(document.getElementById('remoteControlFriendsList')) document.getElementById('remoteControlFriendsList').style.height 	= ((winHeight-140) >= 0 ? (winHeight-140) : 0) + "px";
				
				if(document.getElementById('remoteControlFriendsList_content')) document.getElementById('remoteControlFriendsList_content').style.width 	= ((winWidth-25) >= 0 ? (winWidth-25) : 0) + "px";
				if(document.getElementById('remoteControlFriendsList_content')) document.getElementById('remoteControlFriendsList_content').style.height 	= ((winHeight-140) >= 0 ? (winHeight-140) : 0) + "px";
				
				// set width of footer advert
				if(document.getElementById('footerAd')) document.getElementById('footerAd').style.width 	= ((winWidth-25) >= 0 ? (winWidth-25) : 0)-13 + "px";
				
					
			// REMOTE CONTROL, PRIVATE CHAT WINDOW
			// set height of history field
			if(document.getElementById('remoteControlChatHistory') && document.getElementById('remoteControlChatHistoryParent')) 
			{
				// width
				document.getElementById('remoteControlChatHistory').style.width = ((winWidth-22) >= 0 ? (winWidth-22) : 0)-150 + "px";
				document.getElementById('remoteControlChatHistoryParent').style.width = ((winWidth-22) >= 0 ? (winWidth-22) : 0)-150 + "px";
				
				// height
					// this is the offset height of all other elements besides the history box
					var height_offset = 200;
					
					// set height
					document.getElementById('remoteControlChatHistory').style.height = ((winHeight - height_offset) >= 0 ? (winHeight - height_offset) : 0) + "px";
					document.getElementById('remoteControlChatHistoryParent').style.height = ((winHeight - height_offset) >= 0 ? (winHeight - height_offset) : 0) + "px";
					document.getElementById('rightColumnPictures').style.height = ((winHeight - height_offset) >= 0 ? (winHeight - height_offset + 20) : 0) + "px";
			}
			
			// set new size
			oldWidth 	= winWidth;
			oldHeight 	= winHeight;
			
			// scroll chat history
			scrollChatHistory();
			
			// scroll up inside window
			window.scroll(1000000, 0);
		}
	}
	
	// this is only used for checking which windows exist when linking from private chat window
	var windowRemoteControlMain = true;
	
	// open a href url from "Remote Control, Main" and "Remote Control, Private Chat"
	var objRemoteControlSpawnWindow = '';
	function openSite(href)
	{
		// check if site is already open
		if(window.opener && !window.opener.closed && window.opener.frames['appFrame'])
		{
			// load into already open browser
			window.opener.frames['appFrame'].document.location.href = href;
		}
		else if(objRemoteControlSpawnWindow != "" && !objRemoteControlSpawnWindow.closed)
		{
			// load into already opened remote control spawn
			objRemoteControlSpawnWindow.frames['appFrame'].document.location.href = href;
		}
		else
		{
			// open new window
			objRemoteControlSpawnWindow = window.open(config['a_url']+'?go='+href, 'remoteControlSpawn');
		}
	}
	
	
	// --------------------------------------------------
	// various functions
	// --------------------------------------------------
		// send "I am typing a message ..." or " I am not typing a message ..."
		var has_sent = false;
		function startTypingStatusCheck()
		{
			setInterval("send_typing_status(document.getElementById('frmRCCMessage'))", 500);
		}
		function send_typing_status(objThis)
		{
			// send "I am typing a message ..."
			if(objThis.value.length > 0 && !has_sent)
			{
				has_sent = true;
				var url	= '../sock__remote_control/typing_status_send.php';
				var querystring = 'mid='+receiver_mid+"&action=typing";
				
				mcmsAjax.loadUrl(url, 'GET', querystring, 'alert');
				//frames['iReceiver3'].document.location.href = url+"?"+querystring;
			}
			
			// send "I am NOT typing a message ..."
			if(objThis.value.length == 0 && has_sent)
			{
				has_sent = false;
				var url	= '../sock__remote_control/typing_status_send.php';
				var querystring = 'mid='+receiver_mid+"&action=not_typing";
				
				mcmsAjax.loadUrl(url, 'GET', querystring, 'alert');
				//frames['iReceiver3'].document.location.href = url+"?"+querystring;
			}
		}
	
		// function to reset "Richard is typing a message." status
		function resetStatusText(usr)
		{
			// make sure status bar exists
			if(document.getElementById('statusBar'))
			{
				// reset status text
				document.getElementById('statusBar').innerHTML = "["+objDate.getHours() + ":" + objDate.getMinutes() + ":" + objDate.getSeconds()+"] <b>" + usr + "</b> &auml;r online!";
			}
		}
		
		// set status "He/she is typing a message"
		var global_usr_for_typing = "";
		function set_typing_status(mid, usr, status)
		{
			var winName 					= "AmcmsRemoteControlChat"+mid.trim();						// name of the window
			
			// create/open window if it doesn't exist
			// - it might not be created (main window has been reloaded)
			// - it might exist, but be closed 
			if( openWindows && (!openWindows[winName] || (openWindows[winName] && openWindows[winName].closed)) )
			{
				// open window (physically create it, or re-open an already opened windows just to get the window object reference into openWindows[])
				// NOTE: send "status" ("typing" or "not_typing" as parameter so that it can set the correct value 
				// directly (or else it wont get the status because JS loads faster than the window object reference is made))
				if(status == 'typing')
				{
					global_usr_for_typing = usr;
					openPrivateChat(mid, status.replace(/_/g, ''), 1);
				}
			}
			
			// window SHOULD exist now, but let's check one more time just to be really sure
			if(openWindows && openWindows[winName] && !openWindows[winName].closed)
			{
				// get date object
				var objDate = new Date();
				
				// set status
				if(status == 'typing')
				{
					// "Richard is typing a message"
					if(openWindows[winName])
					{
						if(openWindows[winName].document.getElementById('statusBar'))
						{
							// set status "Richard is typing a message"
							openWindows[winName].document.getElementById('statusBar').innerHTML = "["+objDate.getHours() + ":" + objDate.getMinutes() + ":" + objDate.getSeconds()+"] <b>" + usr + "</b> skriver ett meddelande.";
							
							// start timer for reseting status message incase chat buddy decides to close chat window while typing (or else it would never stop showing "Richard is typing ...")
							if(eval("openWindows['"+winName+"'] != undefined && openWindows['"+winName+"'] != 'undefined'"))
							{
								if(eval("openWindows['"+winName+"'].resetStatusText != undefined && openWindows['"+winName+"'].resetStatusText != 'undefined'"))
								{
									setTimeout("if(openWindows['"+winName+"']) openWindows['"+winName+"'].resetStatusText('"+usr+"');", 120000);
								}
							}
						}
					}
				}	
				else if(status == 'not_typing')
				{
					// "Richard is NOT typing a message"
					if(openWindows[winName])
					{
						if(openWindows[winName].document.getElementById('statusBar'))
						{
							openWindows[winName].document.getElementById('statusBar').innerHTML = "["+objDate.getHours() + ":" + objDate.getMinutes() + ":" + objDate.getSeconds()+"] <b>" + usr + "</b> &auml;r online!";
						}
					}
				}
			}
		}
		
		
	// --------------------------------------------------
	// PRIVATE CHAT
	// keep track of key hits (hot keys)
	// - ENTER (submit)
	// - SHIFT + ENTER (new line)
	// - CTRL + W (close window)
	// --------------------------------------------------
		function KeyCheck(e)
		{
			var ev 					= e || window.event;
			var KeyID 				= (window.event) ? event.keyCode : e.keyCode;
			var is_shift_pressed 	= ev.shiftKey;
			
			if(ev.shiftKey && KeyID == 13)
			{
				// CTRL+ENTER (new line)
				if(document.getElementById('frmRCCMessage')) 
				{
					// NOT REQUIRED, THIS IS A BUILT IN BROWSER FEATURE
					//document.getElementById('frmRCCMessage').innerHTML += " BR ";
					//document.getElementById('frmRCCMessage').focus();
				}
			}
			else if(KeyID == 13)
			{
				// ENTER (submit)
				onMessageSubmit(receiver_mid);
				
				// submit form regular style
				document.forms['frmChatArea'].submit();
				
				// submit form ajax style
				//mcmsAjax.sendData(document.forms['frmChatArea'], 'alert');
				
				return false;
			}
		}
		
	// --------------------------------------------------
	// MAIN WINDOW
	// keep track of key hits (hot keys)
	// - F5 (we want to disable refresh)
	// --------------------------------------------------
		function KeyCheckMain(e)
		{
			var ev 					= e || window.event;
			var KeyID 				= (window.event) ? event.keyCode : e.keyCode;
			var is_shift_pressed 	= ev.shiftKey;
			
			if(KeyID == 116)
			{
				// DISABLE F5 (won't work in IE)
				//return false;
			}
		}
	
	// --------------------------------------------------
	// keep track of mouse move when resizing textarea
	// --------------------------------------------------
		// declare start pos var
		var start_pos_y = 0;
		var cur_pos_y 	= 0;
		var c_enabled	= false;
		var objDate 	= new Date();
		last_move		= objDate.getTime()*1000;
		
		// onload function to start event listeners
		function startEventListeners(fromWindow)
		{
			if(fromWindow == 'main')
			{
				document.onkeydown 		= KeyCheckMain;
			}
			else
			{
				document.onkeydown 		= KeyCheck;
				//document.onmousedown 	= resizeOnMouseDown;
				//document.onmousemove 	= resizeOnMouseMove;
				//document.onmouseup 	= resizeOnMouseUp;
			}
		}
		
		// onmousedown (grab start pos-y)
		function resizeOnMouseDown(eVent)
		{
			// set status "moving enabled"
			c_enabled = true;
			
			// make sure resizing is enabled
			if(c_enabled)
			{
				// get starting Y-pos
				if (!document.all) start_pos_y = parseInt(eVent.screenY); else start_pos_y = parseInt(event.clientY);
			}
		}
		
		// onmousemove
		function resizeOnMouseMove(eVent)
		{
			// make sure resizing is enabled
			if(c_enabled)
			{
				objDate 				= new Date();
				var current_move_time 	= objDate.getTime()*1000;
				
				if((current_move_time-last_move) > 1)
				{
					// get current mouse pos
					if (!document.all) cur_pos_y = parseInt(eVent.screenY); else cur_pos_y = parseInt(event.clientY)
					
					//append_message("CURR: "+cur_pos_y + " START:" + start_pos_y, 'DEBUG', true);
					//scrollChatHistory();
					
					// get element height
					var element_height = parseInt(document.getElementById('frmRCCMessage').style.height);
					
					// resize
					if(cur_pos_y < start_pos_y)
					{
						document.getElementById('frmRCCMessage').style.height = element_height - ((start_pos_y - cur_pos_y) / 100) + 'px';
					}
					else
					{
						document.getElementById('frmRCCMessage').style.height = element_height + ((cur_pos_y - start_pos_y) * 100) + 'px';
					}
					
					//append_message(document.getElementById('frmRCCMessage').style.height + " CURR: "+cur_pos_y + " START:" + start_pos_y, 'DEBUG', true);
					//scrollChatHistory();
				}
			}
		}
		
		// onmouseup
		function resizeOnMouseUp()
		{
			c_enabled = false;
		}
		
		
// -----------------------------------------------------
// Remote Control, buddylist
// -----------------------------------------------------	
	// SETTINGS
		// set max number of allowed friends
		var max_friends2 = 1000;
	
		// declare username holder
		var hUsernames2 = new Array(max_friends2);
		var hUsernamesOffline2 = new Array(max_friends2);
		
		// declare mid holder
		var hMids2 = new Array(max_friends2);
		var hMidsOffline2 = new Array(max_friends2);
		
		// declare personal message holder
		var hPersonalMessage2 = new Array(max_friends2);
		var hPersonalMessageOffline2 = new Array(max_friends2);
	
	
	// initialize buddies (put friends into onlinelist (friends that where online on first load of page)
	function init_buddies2()
	{
		// only do this if buddies list is available
			// online buddies
				if(document.getElementById("polareOnlineList"))
				{
					var tmpUsers = str_friends.split(",");
					
					var strTMP = "";
					var tmpArr = Array();
					
					for(var x = 0; x < tmpUsers.length; x++)
					{
						// break out USERNAME and MEMBER_ID
						tmpArr = tmpUsers[x].split('|');
						
						// append buddy
						if(tmpArr[0] != '' && tmpArr[1] != '') append_buddy2(tmpArr[0], tmpArr[1], tmpArr[2], false);
					}
				}
			
			// offline buddies
				if(document.getElementById("polareOfflineList"))
				{
					var tmpUsers = str_friends_offline.split(",");
					
					var strTMP = "";
					var tmpArr = Array();
					
					for(var x = 0; x < tmpUsers.length; x++)
					{
						// break out USERNAME and MEMBER_ID
						tmpArr = tmpUsers[x].split('|');
						
						// append buddy
						if(tmpArr[0] != '' && tmpArr[1] != '') append_buddy2(tmpArr[0], tmpArr[1], tmpArr[2], true);
					}
				}
	}
	
	// ------------------------------------------------
	// generate html from arrays
	// ------------------------------------------------
		function refresh_buddies2()
		{
			// ONLINE
				var strTMP = "";
				var pm_online = "";
				var pm_offline = "";
				
				// build new buddy list
				for(var x = max_friends2; x > -1; x--)
				{
					// look for a free spot
					if(hUsernames2[x] != "" && hUsernames2[x] != "undefined" && hUsernames2[x] != undefined)
					{
						pm_online = ((hPersonalMessage2[x] != undefined && hPersonalMessage2[x] != 'undefined' && hPersonalMessage2[x] != '') ? '- '+(base64_decode(hPersonalMessage2[x])) : '');
						pm_online = htmlspecialchars(pm_online);
						
						strTMP += '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
						strTMP += '	<tr>';
						strTMP += '		<td valign="top" style="width: 16px;">';
						strTMP += '			<div style="padding-top: 3px;"><img src="'+config['a_url']+'inc/gfx/icon_remote_member.gif" style="width: 11px; height: 16px;" /></div>';
						strTMP += '		</td>';
						strTMP += '		<td valign="top" style="cursor: pointer; -moz-user-select: none;" onselectstart="return false;" ondblclick="openPrivateChat(\''+hMids2[x]+'\', \'request\', \''+x+'\');" onmouseover="this.style.backgroundColor=\'#e1e1e1\';" onmouseout="this.style.backgroundColor=\'white\';">';
						strTMP += '			<div style="padding: 3px 3px 3px 3px">';
						strTMP += '				'+hUsernames2[x]+' <font color="gray">'+pm_online+'</font>';
						strTMP += '			</div>';
						strTMP += '		</td>';
						strTMP += '	</tr>';
						strTMP += '</table>';
					}
				}
				
				document.getElementById("polareOnlineList").innerHTML = strTMP;
				
			// OFFLINE
				strTMP = "";
				
				// build new buddy list
				for(var x = max_friends2; x > -1; x--)
				{
					// look for a free spot
					if(hUsernamesOffline2[x] != "" && hUsernamesOffline2[x] != "undefined" && hUsernamesOffline2[x] != undefined)
					{
						pm_offline = ((hPersonalMessageOffline2[x] != undefined && hPersonalMessageOffline2[x] != 'undefined' && hPersonalMessageOffline2[x] != '') ? '- '+(base64_decode(hPersonalMessageOffline2[x])) : '');
						pm_offline = htmlspecialchars(pm_offline);
						
						strTMP += '<table cellspacing="0" cellpadding="0" border="0" width="100%">';
						strTMP += '	<tr>';
						strTMP += '		<td valign="top" style="width: 16px;">';
						strTMP += '			<div style="padding-top: 3px;"><img src="'+config['a_url']+'inc/gfx/icon_remote_member.gif" style="width: 11px; height: 16px;" /></div>';
						strTMP += '		</td>';
						strTMP += '		<td valign="top" style="cursor: pointer; -moz-user-select: none;" onselectstart="return false;" ondblclick="openPrivateChat(\''+hMidsOffline2[x]+'\', \'request\', \''+x+'\');" onmouseover="this.style.backgroundColor=\'#e1e1e1\';" onmouseout="this.style.backgroundColor=\'white\';">';
						strTMP += '			<div style="padding: 3px 3px 3px 3px">';
						strTMP += '				'+hUsernamesOffline2[x]+' <font color="gray"> '+pm_offline+'</font>';
						strTMP += '			</div>';
						strTMP += '		</td>';
						strTMP += '	</tr>';
						strTMP += '</table>';
					}
				}
				
				document.getElementById("polareOfflineList").innerHTML = strTMP;
			
			return false;
		}
	
	// ------------------------------------------------
	// append a buddy to the buddy list
	// @param string strBuddy the buddy to append
	// @param string strMid the buddy mid to append
	// ------------------------------------------------
		function append_buddy2(strBuddy, strMid, strPersonalMessage, appendToOffline)
		{
			// trim leading-/ending whitespace
			strPersonalMessage = strPersonalMessage.replace(/^\s+|\s+$/g, '');
			
			// allow empty values to be printed without the leading "-"
			strPersonalMessage = strPersonalMessage == 'IA==' ? '' : strPersonalMessage;
			
			// CHECK WHETHER TO APPEND TO ONLINE OR OFFLINE LIST
			if(appendToOffline != undefined && appendToOffline != 'undefined' && appendToOffline == true)
			{
				// grab a free index and put buddy into it
				for(var x = 0; x < max_friends2; x++)
				{
					// OFFLINE
						// check if free
						if(hUsernamesOffline2[x] == "" || hUsernamesOffline2[x] == "undefined" || hUsernamesOffline2[x] == undefined)
						{
							// index key is free, use it
							hUsernamesOffline2[x] = strBuddy;
							hMidsOffline2[x] = strMid;
							hPersonalMessageOffline2[x] = strPersonalMessage;
							break;
						}
				}
			}
			else
			{
				// grab a free index and put buddy into it
				for(var x = 0; x < max_friends2; x++)
				{
					// ONLINE
						// check if free
						if(hUsernames2[x] == "" || hUsernames2[x] == "undefined" || hUsernames2[x] == undefined)
						{
							// index key is free, use it
							hUsernames2[x] = strBuddy;
							hMids2[x] = strMid;
							hPersonalMessage2[x] = strPersonalMessage;
							break;
						}
				}
			}
			
			refresh_buddies2();
			
			return false;
		}
		
		
	// ------------------------------------------------
	// remove a buddy from the buddy list
	// @param string strBuddy the buddy to remove
	// ------------------------------------------------
		function remove_buddy2(strBuddy, strMid, removeFromOffline)
		{
			// CHECK WHETHER TO REMOVE FROM ONLINE OR OFFLINE LIST
			if(removeFromOffline != undefined && removeFromOffline != 'undefined' && removeFromOffline == true)
			{
				// OFFLINE
				for(var x = max_friends2; x > -1; x--)
				{
					if(hUsernamesOffline2[x] != "" && hUsernamesOffline2[x] != "undefined" && hUsernamesOffline2[x] != undefined)
					{
						if(hUsernamesOffline2[x].toLowerCase() == strBuddy.toLowerCase())
						{
							// remove from "offline" list
							hUsernamesOffline2[x] 			= '';
							hMidsOffline2[x] 				= '';
							hPersonalMessageOffline2[x] 	= '';
						}
					}
				}
			}
			else
			{
				// ONLINE
				for(var x = max_friends2; x > -1; x--)
				{
					if(hUsernames2[x] != "" && hUsernames2[x] != "undefined" && hUsernames2[x] != undefined)
					{
						if(hUsernames2[x].toLowerCase() == strBuddy.toLowerCase())
						{
							// remove from "online" list
							hUsernames2[x] 			= '';
							hMids2[x] 				= '';
							hPersonalMessage2[x] 	= '';
						}
					}
				}
			}
			
			refresh_buddies2();
			
			return false;
		}