/* MGC Chatbox EVO created by MGC, Chatbox Functions Script, Copyright 2010 all rights reserved */
var first_load = 1;
var prompt_callback_fct = null;
var alreadyEditing = 0;
var alreadyRefreshing = 0;
var currentEditObj = null;
var currentEditContent = null;
var currentEditId = 0;
var currentReportId = 0;
var chat_in_process = 0;
var refreshTimeout = null;
var mgc_cb_evo_refreshPMtimeout = null;
var warnTimeout = null;
var force_session_refresh = 0;
var isovermenuitem = 0;
var opened_menu = 0;
var pm_userid;
var chatids_array = new Array();
var schatids_array = new Array();
var last_scroll_height = 0;
var last_scroll_sheight = 0;
var last_sticky_chatid = 0;
var temp_url = null;
var chat_username = null;
var channel_id = 0;
var in_archives = 0;
var force_scrolling = 0;
var chatprompt;
var enter_key_listener;
var chatprompt_kl = null;
var mgc_cb_evo_shift_key_pushed = 0;
var mgc_cb_evo_tabs = null;
var mgc_cb_evo_pmuserids_array = new Array();
var mgc_cb_evo_pmchatid_array = new Array();
var mgc_cb_evo_active_pmtab = 0;
var first_pm_load = 0;

/* Take care of the problem of vB 3.6 for geto ajax calls */
if (mgc_oldvb3 == 1)
{
	var vB_Default_Timeout = 15000;
	var SECURITYTOKEN = 0;

	if(!window.console||!console.firebug)
	{
		window.console={};
		var names=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"];
		for(var i=0;i<names.length;++i)
		{
			window.console[names[i]]=function(){}
		}
	}

	function vBulletin_AJAX_Error_Handler(objajax)
	{
		console.warn("AJAX Error: Status = %s: %s",objajax.status,objajax.statusText);
	}
}

function mgc_cb_evo_handle_enter_button()
{
	chatprompt.cancel();
	mgc_cb_js_showprompt_submit();
}

YAHOO.util.Event.onDOMReady(function()
{
	YAHOO.initChatbox=new function()
	{
		// Launch clock
		if (mgc_cb_evo_showtime)
		{
			mgc_cb_evo_clock();
		}
		
		// Define various event handlers for Dialog
		var handleSubmit = function() {
			this.cancel();
			mgc_cb_js_showprompt_submit();
		};
		var handleCancel = function() {
			this.cancel();
		};

		// Instantiate the Dialog
		chatprompt =
			new YAHOO.widget.Dialog("chatpopupinput",
					{ width : "30em",
					  fixedcenter : true,
					  visible : false,
					  constraintoviewport : true,
					  buttons : [ { text: phrase_save, handler:handleSubmit, isDefault:true },
							  { text: phrase_cancel, handler:handleCancel } ]
					});
		
		// Set the enter key as dialog 
		chatprompt_kl = new YAHOO.util.KeyListener(
							document,
							{ keys:13 },
							{
								fn:mgc_cb_evo_handle_enter_button,
								scope:chatprompt,
								correctScope:true 
							}
						);					
		chatprompt.cfg.queueProperty("keylisteners", chatprompt_kl);		

		// Render the Dialog
		chatprompt.render();

		// Overflow problem with some browsers
		if (is_opera || is_ns4)
		{
			fetch_object('chats').style.overflow = 'auto';
			if (mgc_cb_evo_notif_display > 1)
			{
				fetch_object('schats').style.overflow = 'auto';
			}
		}

		// Autocomplete if active
		if (mgc_cb_evo_autocomplete_on)
		{
			YAHOO.example.BasicLocal = function() {
				// Use a LocalDataSource
				var oDS = new YAHOO.util.LocalDataSource(chatAutocompletionarray);
				// Optional to define fields for single-dimensional array
				oDS.responseSchema = {fields : ["command"]};

				// Instantiate the AutoComplete
				var oAC = new YAHOO.widget.AutoComplete("mgc_cb_evo_input", "chatinputAutocompleteContainer", oDS);
				oAC.prehighlightClassName = "yui-ac-prehighlight";
				oAC.useShadow = true;

				return {
					oDS: oDS,
					oAC: oAC
				};
			}();
		}
		
		if (mgc_cb_evo_pm_tabs_on)
		{
			/* Tabs creatop, */
			mgc_cb_evo_tabs = new YAHOO.widget.TabView("tabs_mgc_cb_evo");
			mgc_cb_evo_tabs.addListener('activeTabChange', mgc_cb_evo_tabs_change);				
		}
		
		// Apply input style if active
		if (mgc_cb_evo_wysiwyg)
		{
			init_chatbox_input_style();
		}
		
		// Set default channel
		if (mgc_cb_evo_default_channel != 0)
		{
			display_channel(mgc_cb_evo_default_channel);
		}
		else
		{
			// Display general channel text
			if (typeof(channelNamesArray) != "undefined")
			{
				fetch_object('mgc_cb_evo_channel_name').innerHTML = channelNamesArray[0];
			}
		}

		// Last but not least : Chats refresh
		if (!in_archives)
		{

			fetch_object('mgc_cb_evo_opened').appendChild(getEvo());
			fetch_object('mgc_cb_evo_closed').appendChild(getEvo());

			// Chats retrieving loading when not in collapsed mode
			if (mgc_cb_evo_iscollapsed == 0)
			{
				if (mgc_cb_evo_initstate)
				{
					chatbox_refresh('forced');
				}
				else
				{
					// Show inactive message and refresh button (if refresh hidden option is set)
					fetch_object('chats').innerHTML = "<div align=\center\>" + phrase_inactive + "</div>";
					if (hide_refreshimg)
					{
						fetch_object('mgc_cb_evo_refresh_button').style.display = "";
					}
				}
			}
			else if (mgc_cb_evo_inistate)
			{
				// Chats retrieving loading when in collapsed mode
				mgc_cb_evo_get_last_chats();
			}
		}
	};
});

function mgc_cb_js_showpopup(message,callback_fct)
{
	var handleOK = function() {
		this.hide();
		if (callback_fct != '')
		{
			eval(callback_fct + '();');
		}
	};

	var chatpopup =
		new YAHOO.widget.SimpleDialog("chatpopup",
				 { width: "500px",
				   fixedcenter: true,
				   visible: false,
				   draggable: false,
				   close: false,
				   text: message,
				   icon: YAHOO.widget.SimpleDialog.ICON_WARN,
				   constraintoviewport: true,
				   buttons: [ { text: phrase_ok, handler:handleOK, isDefault:true }]
				 } );

	chatpopup.render("mgc_cb_evo_chat_popup");
	chatpopup.show();

	return false;
}

function mgc_cb_js_showpopup_yesno(message,callback_fct)
{
	var handleYes = function() {
		this.hide();
		eval(callback_fct + '();');
	};

	var handleNo = function() {
		this.hide();
	};

	var chatpopup =
		new YAHOO.widget.SimpleDialog("chatpopup",
				 { width: "500px",
				   fixedcenter: true,
				   visible: false,
				   draggable: false,
				   close: true,
				   text: message,
				   icon: YAHOO.widget.SimpleDialog.ICON_WARN,
				   constraintoviewport: true,
				   buttons: [ { text: phrase_yes, handler:handleYes, isDefault:true },
				   			  { text: phrase_no, handler:handleNo}]
				 } );

	chatpopup.render("mgc_cb_evo_chat_popup");
	chatpopup.show();

	return false;
}

function mgc_cb_js_showprompt(message,inputval,prompt_callback)
{
	prompt_callback_fct = prompt_callback;

	fetch_object('mgc_cb_evo_chat_popup_content').innerHTML	= message;
	fetch_object('id_mgc_cb_evo_prompt_input').value		= inputval;	
	chatprompt.show();
}

function mgc_cb_js_showprompt_submit()
{
	/* Escape data for pm */
	if (prompt_callback_fct == 'mgc_cb_evo_do_send_pm')
	{
		eval(prompt_callback_fct + '("' + escape(chatprompt.getData().mgc_cb_evo_prompt_input) + '");');
	}
	else
	{
		eval(prompt_callback_fct + '("' + chatprompt.getData().mgc_cb_evo_prompt_input + '");');
	}
}

function mgc_cb_evo_force_page_refresh()
{
	window.location.reload();
}

function add_smiley_to_input(smileytext)
{
	insert_at_cursor(fetch_object('mgc_cb_evo_input'),smileytext);
	return false;
}

function insert_at_cursor(myField, myValue)
{
	// Clear chat input if prompt still present
	if (chat_input_prompt)
	{
		clear_chat_prompt();
	}

	//IE support
	if (document.selection)
	{
		myField.focus();
		sel 		= document.selection.createRange();
		sel.text 	= myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == 0) {
		var startPos 	= myField.selectionStart;
		var endPos 		= myField.selectionEnd;
		myField.value 	= myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
	}
	else
	{
		myField.value += myValue;
	}
}

function text_insert(repdeb, repfin)
{
  	var input = fetch_object('mgc_cb_evo_input');
  	input.focus();
  	/* IE support */
	if(typeof document.selection != 'undefined')
	{
		/* Formatting code insert */
		var range = document.selection.createRange();
		var insText = range.text;
	    range.text = repdeb + insText + repfin;
	    /* Cursor position adjustment */
	    range = document.selection.createRange();
	    if (insText.length == 0)
		{
	      range.move('character', -repfin.length);
	    }
		else
		{
	      range.moveStart('character', repdeb.length + insText.length + repfin.length);
	    }
	    range.select();
  	}
  	/* Newer browsers based on Gecko*/
  	else
  	{
	    /* Insertion du code de formatage */
	    var start = input.selectionStart;
	    var end = input.selectionEnd;
	    var insText = input.value.substring(start, end);
	    input.value = input.value.substr(0, start) + repdeb + insText + repfin + input.value.substr(end);
	    /* Cursor position adjustment */
	    var pos;
	    if (insText.length == 0)
		{
	      pos = start + repdeb.length;
	    }
		else
		{
	      pos = start + repdeb.length + insText.length + repfin.length;
	    }
	    input.selectionStart = pos;
	    input.selectionEnd = pos;
  	}
  	return false;
}

function init_chatbox_input_style()
{
	if (mgc_cb_evo_ubbcode_b)
	{
		document.getElementById('mgc_cb_evo_input').style.fontWeight = "bold";
	}

	if (mgc_cb_evo_ubbcode_i)
	{
		document.getElementById('mgc_cb_evo_input').style.fontStyle = "italic";
	}

	if (mgc_cb_evo_ubbcode_u)
	{
		document.getElementById('mgc_cb_evo_input').style.textDecoration = "underline";
	}

	if (mgc_cb_evo_ubbcode_size != null  && mgc_cb_evo_ubbcode_size != 0)
	{
		var fontsizes = ['xx-small','x-small','small','medium','large','x-large','xx-large'];
		document.getElementById('mgc_cb_evo_input').style.fontSize = fontsizes[mgc_cb_evo_ubbcode_size - 1];
	}

	if (mgc_cb_evo_ubbcode_color != null && mgc_cb_evo_ubbcode_color != "#")
	{
		document.getElementById('mgc_cb_evo_input').style.color = mgc_cb_evo_ubbcode_color;
	}

	if (mgc_cb_evo_ubbcode_font != null)
	{
		document.getElementById('mgc_cb_evo_input').style.fontFamily = mgc_cb_evo_ubbcode_font;
	}
}

function configure_enhanced_format(select_item,tag)
{
	bbcode_option = select_item.options[select_item.selectedIndex].value;

	if (tag == 'size')
	{
		var fontsizes = ['xx-small','x-small','small','medium','large','x-large','xx-large'];
		mgc_cb_evo_ubbcode_size = bbcode_option;
		if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.fontSize = fontsizes[bbcode_option - 1];
	}

	if (tag == 'color')
	{
		mgc_cb_evo_ubbcode_color = bbcode_option;
		if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.color = bbcode_option;
	}

	if (tag == 'font')
	{
		mgc_cb_evo_ubbcode_font = bbcode_option;
		if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.fontFamily = bbcode_option;
	}

	return false;
}

function configure_simple_format(tag)
{
	var currentState = null;

	if (tag == 'b')
	{
		currentState = mgc_cb_evo_ubbcode_b;
		if (currentState)
		{
			mgc_cb_evo_ubbcode_b = 0;
			if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.fontWeight = "";
			document.getElementById('bbcode_image_b').src = imgdir_misc + '/mgc_cb_evo/mgc_cb_evo_b_off.gif';
		}
		else
		{
			mgc_cb_evo_ubbcode_b = 1;
			if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.fontWeight = "bold";
			document.getElementById('bbcode_image_b').src = imgdir_misc + '/mgc_cb_evo/mgc_cb_evo_b_on.gif';
		}
	}

	if (tag == 'i')
	{
		currentState = mgc_cb_evo_ubbcode_i;
		if (currentState)
		{
			mgc_cb_evo_ubbcode_i = 0;
			if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.fontStyle = "";
			document.getElementById('bbcode_image_i').src = imgdir_misc + '/mgc_cb_evo/mgc_cb_evo_i_off.gif';
		}
		else
		{
			mgc_cb_evo_ubbcode_i = 1;
			if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.fontStyle = "italic";
			document.getElementById('bbcode_image_i').src = imgdir_misc + '/mgc_cb_evo/mgc_cb_evo_i_on.gif';
		}
	}

	if (tag == 'u')
	{
		currentState = mgc_cb_evo_ubbcode_u;
		if (currentState)
		{
			mgc_cb_evo_ubbcode_u = 0;
			if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.textDecoration = "";
			document.getElementById('bbcode_image_u').src = imgdir_misc + '/mgc_cb_evo/mgc_cb_evo_u_off.gif';
		}
		else
		{
			mgc_cb_evo_ubbcode_u = 1;
			if (mgc_cb_evo_wysiwyg) document.getElementById('mgc_cb_evo_input').style.textDecoration = "underline";
			document.getElementById('bbcode_image_u').src = imgdir_misc + '/mgc_cb_evo/mgc_cb_evo_u_on.gif';
		}
	}
}

function collapse_mgc_cb_evo()
{
	/* Clear chats */
   	exec_chatbox_clear(0);

	/* Exec collapse */
   	if(fetch_object('mgc_cb_evo_opened').style.display == '')
   	{
    	fetch_object('mgc_cb_evo_opened').style.display       = 'none';
      	fetch_object('mgc_cb_evo_title_opened').style.display = 'none';
      	fetch_object('mgc_cb_evo_title_closed').style.display = '';
		clearTimeout(refreshTimeout);

     	if(chats_when_collapsed)
      	{
        	fetch_object('mgc_cb_evo_closed').style.display = '';
         	mgc_cb_evo_get_last_chats();
      	}
   	}
   	else
   	{
		fetch_object('mgc_cb_evo_opened').style.display       = '';
      	fetch_object('mgc_cb_evo_closed').style.display       = 'none';
      	fetch_object('mgc_cb_evo_title_opened').style.display = '';
      	fetch_object('mgc_cb_evo_title_closed').style.display = 'none';
    	chatbox_refresh('forced');
   	}
}

function exec_mgc_cb_evo_collapse()
{
   docollapse = toggle_collapse('mgc_cb_evo');
   collapse_mgc_cb_evo();
   return docollapse;
}

function open_help_window()
{
   window.open(bburl + "/mgc_cb_evo.php?" + SESSIONURL + "do=showhelp" , "showhelp", "toolbar=no,scrollbars=yes,resizable=yes,left=0 top=0,width=850,height=630");
   return false;
}

function chatbox_refresh(type)
{
	/* Not already refreshing */
	if ((auto_refresh || (type == 'forced')) && !alreadyRefreshing)
	{
		clearTimeout(refreshTimeout);
		alreadyRefreshing = 1;

		/* Type of refresh management */
		if (type == 'forced')
		{
			currentRefreshType = 'forced';
		}
		else
		{
			currentRefreshType = 'normal';
		}

		/* If chatbox is inactive and notification in sidebar : clear them before refresh as they were kept */
		if (chatbox_inactive && ((mgc_cb_evo_notif_display == 3) || (mgc_cb_evo_notif_display == 4)))
		{
			exec_notifs_clear();
		}

		fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'visible';

    	var cids = chatids_array.join(',');

    	if (mgc_cb_evo_notif_display > 1)
    	{
    		var scids = schatids_array.join(',');
    	}
    	else
    	{
    		var scids = '';
    	}

		// If leaving from inactive mode and refresh img hidden option is set : hide refresh button
		if (hide_refreshimg)
		{
			fetch_object('mgc_cb_evo_refresh_button').style.display = "none";
		}

    	/* Chatbox is inactive, refresh forced => session update */
    	if (chatbox_inactive || force_session_refresh)
    	{
			YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
				success: wait_chatbox_refresh,
				failure: vBulletin_AJAX_Error_Handler,
				timeout: vB_Default_Timeout
			}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_refresh_chat&status=open&channel_id=" + channel_id + "&location=" + cb_location + "&first_load=1&chatids=" + cids + "&schatids=" + scids);
		}
		else
		{
			YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
				success: wait_chatbox_refresh,
				failure: vBulletin_AJAX_Error_Handler,
				timeout: vB_Default_Timeout
			}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_refresh_chat&status=open&channel_id=" + channel_id + "&location=" + cb_location + "&first_load=" + first_load + "&chatids=" + cids + "&schatids=" + scids);
		}
	}
	return false;
}

function wait_chatbox_refresh(refreshAjax)
{
   	if(refreshAjax.responseXML)
   	{
   		var do_scrolling;
   		var do_sscrolling;
		var playsound = 0;

		var jchats = refreshAjax.responseXML.getElementsByTagName('chat');

		if (first_load || chatbox_inactive)
		{
			exec_chatbox_clear(0);
		}

		// Let's check if we should scroll at end of new shouts adding when in new shouts at bottom
		if (chats_order)
		{
			if (first_load || force_session_refresh || chatbox_inactive || force_scrolling)
			{
				do_scrolling = 1;
			}
			else if (last_scroll_height == document.getElementById('chats_container').scrollTop)
			{
				// Scrollbar is at bottom we can scroll !
				do_scrolling = 1;
			}
			else
			{
				do_scrolling = 0;
			}

			if (mgc_cb_evo_notif_display > 1)
			{
				if (first_load || force_session_refresh || chatbox_inactive)
				{
					do_sscrolling = 1;
				}
				else if (last_scroll_sheight == document.getElementById('schats_container').scrollTop)
				{
					// Scrollbar is at bottom we can scroll !
					do_sscrolling = 1;
				}
				else
				{
					do_sscrolling = 0;
				}
			}
		}

		/* Reset inactive mode */
		if (chatbox_inactive)
		{
			chatbox_inactive = 0;
			idleTimeout = setTimeout("activate_idle_chatbox()", inactive_mode_delay);
		}

		if (jchats.length)
		{
			/* Some var for chat add/edit manipulation */
			var chatrefreshel 	= document.getElementById('chats');
			var eledit 			= null;

			if (mgc_cb_evo_notif_display > 1)
			{
				var schatrefreshel = document.getElementById('schats');
			}

			/* Let's parse the ajax retrievals */
			for (i=0;i<jchats.length;i++)
			{
				var type 		= jchats[i].getElementsByTagName('type')[0].firstChild.nodeValue;
				var issticky 	= jchats[i].getElementsByTagName('sticky')[0].firstChild.nodeValue;
				var chatid 		= jchats[i].getElementsByTagName('chatid')[0].firstChild.nodeValue;
				var oldchat		= jchats[i].getElementsByTagName('oldchat')[0].firstChild.nodeValue;
				var specialchat	= jchats[i].getElementsByTagName('specialchat')[0].firstChild.nodeValue;

				if ((mgc_cb_evo_notif_display > 1) && (specialchat == 1))
				{
					/* Whole page refresh requested */
					if (type == 2)
					{
						window.location.reload();
					}
					/* Edit chat */
					else if (type == 1)
					{
						/* Create the new chat row */
						var newchat = create_chatrow(jchats[i],1);

						/* Do the replacement */
						schatrefreshel.replaceChild(newchat,document.getElementById('chatrow_' + chatid));
					}
					/* Add notification */
					else if (type == 0)
					{
						/* We have a chat or notification => can play sound */
						playsound = 1;

						/* Add chatid to chatids array */
						schatids_array.push(chatid);

						/* Create the new chat row */
						var newchat = create_chatrow(jchats[i],1);

						/* Older at top */
						if (chats_order == 1)
						{
							/* Add chat to the chatbox */
							schatrefreshel.appendChild(newchat)
						}
						/* Newer at top*/
						else
						{
							/* Older chat, append at the bottom */
							if (oldchat == 1)
							{
								schatrefreshel.appendChild(newchat);
							}
							/* First load => always prepend and check if first sticky chat received for recording */
							else if (first_load == 1)
							{
								if (schatrefreshel.hasChildNodes())
								{
									schatrefreshel.insertBefore(newchat,schatrefreshel.firstChild);
								}
								else
								{
									schatrefreshel.appendChild(newchat);
								}
							}
							else
							{
								schatrefreshel.insertBefore(newchat,schatrefreshel.firstChild);
							}
						}
					}
					/* Remove chat */
					else if (type == 3)
					{
						schatrefreshel.removeChild(document.getElementById('chatrow_' + chatid));
						remove_chatid_from_array(chatid,1);
					}
				}
				/* No separation between chats and notifications or normal chats management */
				else
				{
					/* Whole page refresh requested */
					if (type == 2)
					{
						window.location.reload();
					}
					/* Edit chat */
					else if (type == 1)
					{
						/* Create the new chat row */
						var newchat = create_chatrow(jchats[i],0);

						/* Do the replacement */

							chatrefreshel.replaceChild(newchat,document.getElementById('chatrow_' + chatid));
					}
					/* Add chat */
					else if (type == 0)
					{
						/* We have a chat or notification => can play sound */
						playsound = 1;

						/* Add chatid to chatids array */
						chatids_array.push(chatid);

						/* Create the new chat row */
						var newchat = create_chatrow(jchats[i],specialchat);

						/* Older at top */
						if (chats_order == 1)
						{
							/* Older chat, insert at the top */
							if (oldchat == 1)
							{
								chatrefreshel.appendChild(newchat);
							}
							/* If no sticky chat yet -> append and check if first sticky chat received for recording */
							else if (!last_sticky_chatid)
							{
								/* Add chat to the chatbox */
								chatrefreshel.appendChild(newchat)

								/* If sticky set as last sticky */
								if (issticky == 1)
								{
									last_sticky_chatid = chatid;
								}
							}
							else
							{
								/* If sticky chat -> continue to append (first load) */
								if (issticky == 1)
								{
									chatrefreshel.appendChild(newchat);
								}
								/* Else, add before the first sticky chat */
								else
								{
									chatrefreshel.insertBefore(newchat,document.getElementById('chatrow_' + last_sticky_chatid));
								}
							}
						}
						/* Newer at top*/
						else
						{
							/* Older chat, append at the bottom */
							if (oldchat == 1)
							{
								chatrefreshel.appendChild(newchat);
							}
							/* First load => always prepend and check if first sticky chat received for recording */
							else if (first_load == 1)
							{
								if (chatrefreshel.hasChildNodes())
								{
									chatrefreshel.insertBefore(newchat,chatrefreshel.firstChild);
								}
								else
								{
									chatrefreshel.appendChild(newchat);
								}


								if (!last_sticky_chatid && issticky == 1)
								{
									last_sticky_chatid = chatid;
								}
							}
							else
							{
								/* If no sticky chat => prepend */
								if (!last_sticky_chatid)
								{
									chatrefreshel.insertBefore(newchat,chatrefreshel.firstChild);
				
									if (!last_sticky_chatid && issticky == 1)
									{
										last_sticky_chatid = chatid;
									}									
								}
								/* Add after the last sticky chat */
								else
								{
									/* Insert after using insertBefore if next child, otherwise append */
									if (document.getElementById('chatrow_' + last_sticky_chatid).nextSibling)
									{
										chatrefreshel.insertBefore(newchat,document.getElementById('chatrow_' + last_sticky_chatid).nextSibling);
									}
									else
									{
										chatrefreshel.appendChild(newchat);
									}
								}
							}
						}
					}
					/* Remove chat */
					else if (type == 3)
					{
						chatrefreshel.removeChild(document.getElementById('chatrow_' + chatid));
						remove_chatid_from_array(chatid,0);
					}
				}
			}

			/* Scroll ? */
			if (do_scrolling)
			{
				document.getElementById('chats_container').scrollTop = document.getElementById('chats').offsetHeight;
				last_scroll_height = document.getElementById('chats_container').scrollTop;
			}

			if (mgc_cb_evo_notif_display > 1)
			{
				if (do_sscrolling)
				{
					document.getElementById('schats_container').scrollTop = document.getElementById('schats').offsetHeight;
					last_scroll_sheight = document.getElementById('schats_container').scrollTop;
				}
			}
		}

		/* Check for new messages if active */
		if (first_load && warn_active)
		{
			check_new_messages();
		}

		/* Hide refresh */
		fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'hidden';

		/* Update row alternate if requested */
      	if (cbaltcolors)
      	{
			update_row_color_alt(0);
		}
		else if (mgc_cb_evo_notif_display == 3 || mgc_cb_evo_notif_display == 4)
		{
			update_row_color_alt(1);
		}

		/* Numerically sort chatids array */
		chatids_array.sort(function(a,b){return b - a})
		if (mgc_cb_evo_notif_display > 1)
		{
			schatids_array.sort(function(a,b){return b - a})
		}

		/* At last play sound if needed and active */
		if (mgc_cb_evo_sound && playsound && !first_load)
		{
			fetch_object("mgc_cb_evo_sound_span").innerHTML= '<embed src="clientscript/mgc_cb_evo/sound/new_chat.swf" hidden="true" autostart="true" loop="false">';
		}

		first_load 				= 0;
		force_session_refresh 	= 0;
		force_scrolling 		= 0;
		alreadyRefreshing 		= 0;

		/* Relaunch timeout if active */
		if (mgc_cb_evo_autorefresh_on)
		{
			refreshTimeout = setTimeout("chatbox_refresh()", val_timeout);
		}
	}
}

function exec_collapse(item_id)
{
	var obj = fetch_object('collapseobj_' + item_id);
	var icon = fetch_object('icon_' + item_id);
	
	if (mgc_vb4)
	{
		// Object management
		if (obj.style.display == 'none')
	   	{
			icon_re 			= new RegExp("\\.gif$");
			icon.src 			= icon.src.replace(icon_re, '_collapsed.gif');
			obj.style.display 	= '';
			removeFromCookie	= 1;
		}
	   	else
	   	{
			icon_re 			= new RegExp("_collapsed\\.gif$");
			icon.src 			= icon.src.replace(icon_re, '.gif');
			obj.style.display 	= 'none';
			removeFromCookie	= 0;
		}	
	
		// Cookie save
		var vBCookie = fetch_cookie("vbulletin_collapse");
		var TableauCollapsed = new Array();
		if(vBCookie != null)
		{
			vBCookie = vBCookie.split("\n");
			for(var vBCookieElement in vBCookie)
			{
				if(YAHOO.lang.hasOwnProperty(vBCookie,vBCookieElement) && vBCookie[vBCookieElement] != item_id && vBCookie[vBCookieElement] != "")
				{
					TableauCollapsed[TableauCollapsed.length] = vBCookie[vBCookieElement];
				}
			}
		}
		
		if (removeFromCookie == 1) // Remove from collapsed
		{
			TableauCollapsed[TableauCollapsed.length] = item_id;
		}
		
		expires=new Date();
		expires.setTime(expires.getTime()+(1000*86400*365));
		set_cookie("vbulletin_collapse",TableauCollapsed.join("\n"),expires);
		return false;	
	}
	else
	{
		if (obj.style.display == 'none')
	   	{
			icon_re = new RegExp("\\.gif$");
			icon.src = icon.src.replace(icon_re, '_collapsed.gif');
		}
	   	else
	   	{
			icon_re = new RegExp("_collapsed\\.gif$");
			icon.src = icon.src.replace(icon_re, '.gif');
		}
		return toggle_collapse(item_id);
	}
}

function exec_collaspe_online()
{
	obj = fetch_object('collapseobj_mgc_cb_evo_online');
	icon = fetch_object('icon_mgc_cb_evo_online');

	if (mgc_vb4)
	{
		if (obj.style.display == 'none')
		{
			get_online_users();
			icon_re = new RegExp("\\.gif$");
			icon.src = icon.src.replace(icon_re, '_collapsed.gif');
			fetch_object('chats_container').style.display = 'none';
			if (mgc_cb_evo_notif_display > 1)
			{
				fetch_object('schats_container').style.display = 'none';
				fetch_object('chatsmaincontainer').style.display = 'none';
			}
			obj.style.display = '';
		}
	   	else
	   	{
	   		clearTimeout(whoisonlineTimeout);
			icon_re = new RegExp("_collapsed\\.gif$");
			icon.src = icon.src.replace(icon_re, '.gif');
			fetch_object('chats_container').style.display = '';
			if (mgc_cb_evo_notif_display > 1)
			{
				fetch_object('schats_container').style.display = '';
				fetch_object('chatsmaincontainer').style.display = '';
			}
			obj.style.display = 'none';
		}
		
		return false;
	}
	else
	{
		if (obj.style.display == 'none')
		{
			get_online_users();
			icon_re = new RegExp("\\.gif$");
			icon.src = icon.src.replace(icon_re, '_collapsed.gif');
			fetch_object('chats_container').style.display = 'none';
			if (mgc_cb_evo_notif_display > 1)
			{
				fetch_object('schats_container').style.display = 'none';
			}
		}
	   	else
	   	{
	   		clearTimeout(whoisonlineTimeout);
			icon_re = new RegExp("_collapsed\\.gif$");
			icon.src = icon.src.replace(icon_re, '.gif');
			fetch_object('chats_container').style.display = '';
			if (mgc_cb_evo_notif_display > 1)
			{
				fetch_object('schats_container').style.display = '';
			}
		}
	
		return toggle_collapse('mgc_cb_evo_online');
	}
}

function set_name(username)
{
	if (username != null && PHP.trimusername != "")
   	{
   		/* Register username */
   		chat_username = PHP.urlencode(username);

   		/* Relaunch chat sending */
   		send_chat();
	}
	else
	{
		mgc_cb_js_showpopup(phrase_error_name,'');
	}
}

function send_chat()
{
	/* If ask name active and no name entered yet, ask for one before sending the chat */
	if (chatbox_ask_name && chat_username == null)
	{
		mgc_cb_js_showprompt(phrase_enter_name,"",'set_name',false);
		return false;
	}

	/* If trying to send prompt, clear prompt and do nothing */
   	if (chat_input_prompt)
   	{
    	clear_chat_prompt();
      	return false;
   	}

	/* If inactive mode is active in the chatbox, reset timeout */
	if (inactive_mode)
	{
		clearTimeout(idleTimeout)
   		idleTimeout = setTimeout("activate_idle_chatbox()", inactive_mode_delay);
	}

	if (chat_in_process)
	{
		mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
	}
	else
	{
		chat_in_process = 1;
		
		/* PM in tabs chat */
		if (mgc_cb_evo_pm_tabs_on && !mgc_cb_evo_tabs.get('tabs')[0].get('active'))
		{
			chat_urlencoded = PHP.urlencode('/pm uid ' + mgc_cb_evo_active_pmtab + ' ' + fetch_object('mgc_cb_evo_input').value);
		}
		else
		{
			chat_urlencoded = PHP.urlencode(fetch_object('mgc_cb_evo_input').value);
		}
		
		/* Send the chat with the anonymous name if any */
		if (chatbox_ask_name)
		{
			YAHOO.util.Connect.asyncRequest(
				"POST",
				mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php',
				{
					success: wait_send_chat,
					failure: vBulletin_AJAX_Error_Handler,
					timeout: vB_Default_Timeout
				},
				SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat_name=" + chat_username + "&chat=" + chat_urlencoded
				+ '&b=' + mgc_cb_evo_ubbcode_b + '&i=' + mgc_cb_evo_ubbcode_i + '&u=' + mgc_cb_evo_ubbcode_u
				+ '&font=' + PHP.urlencode(mgc_cb_evo_ubbcode_font) + '&color=' + mgc_cb_evo_ubbcode_color + '&size=' + mgc_cb_evo_ubbcode_size
			);
		}
		else
		{
			YAHOO.util.Connect.asyncRequest(
				"POST",
				mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php',
				{
					success: wait_send_chat,
					failure: vBulletin_AJAX_Error_Handler,
					timeout: vB_Default_Timeout
				},
				SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded
				+ '&b=' + mgc_cb_evo_ubbcode_b + '&i=' + mgc_cb_evo_ubbcode_i + '&u=' + mgc_cb_evo_ubbcode_u
				+ '&font=' + PHP.urlencode(mgc_cb_evo_ubbcode_font) + '&color=' + mgc_cb_evo_ubbcode_color + '&size=' + mgc_cb_evo_ubbcode_size
			);
 		}
   }
   return false;
}


function wait_send_chat(sendAjax)
{
   if(sendAjax.responseXML)
   {
      	/* Get xml answer content */
		chatbox_result = sendAjax.responseXML.getElementsByTagName('sendchat_result')[0].firstChild.nodeValue;

      	chat_in_process = 0;
      	
      	/* Clear chat input */
		clear_chat_input();

      	/* Execute ajax call return function */
      	if (mgc_cb_evo_pm_tabs_on && !mgc_cb_evo_tabs.get('tabs')[0].get('active') && chatbox_result == "chatbox_refresh('forced')")
      	{ 
      		chatbox_pm_refresh();
      	}
      	else
      	{
      		eval(chatbox_result);
		}
		
      	/* Clear timeout */
      	clearTimeout(refreshTimeout);
   }
}

function clear_chat_input() {
   fetch_object('mgc_cb_evo_input').value = '';
	return false;
}

function reset_bbcodes() {
	fetch_object('mgc_cb_evo_input').value = stripcode(fetch_object('mgc_cb_evo_input').value, false, false);

	if (mgc_cb_evo_ubbcode_b)
	{
		configure_simple_format('b');
	}
	if (mgc_cb_evo_ubbcode_i)
	{
		configure_simple_format('i');
	}
	if (mgc_cb_evo_ubbcode_u)
	{
		configure_simple_format('u');
	}

	mgc_cb_evo_ubbcode_size = 3;
	if (mgc_cb_evo_wysiwyg)
	{
		document.getElementById('mgc_cb_evo_input').style.fontSize = 'small';
	}
	document.getElementById('mgc_cb_evo_size').options[0].selected = "true";

	mgc_cb_evo_ubbcode_color = '#000000';
	if (mgc_cb_evo_wysiwyg)
	{
		document.getElementById('mgc_cb_evo_input').style.color = '#000000';
	}
	document.getElementById('mgc_cb_evo_color').options[0].selected = "true";

	mgc_cb_evo_ubbcode_font = 'Arial';
	if (mgc_cb_evo_wysiwyg)
	{	
		document.getElementById('mgc_cb_evo_input').style.fontFamily = 'Arial';
	}
	document.getElementById('mgc_cb_evo_font').options[0].selected = "true";

	return false;
}

function insert_bbcode_url()
{
	/* First get url */
   mgc_cb_js_showprompt(phrase_enter_url,"http://",'check_url',false);
}

function check_url(url)
{
	if (url != null && PHP.trim(url) != "")
   	{
   		/* URL ok, ask for an url text */
   		temp_url = url;
   		mgc_cb_js_showprompt(phrase_enter_urltext,"",'exec_insert_bbcode_url',false);
	}
}

function exec_insert_bbcode_url(urltext)
{
	if (urltext != null && PHP.trim(urltext))
	{
		insert_at_cursor(fetch_object('mgc_cb_evo_input'),"[url=" + temp_url + "]" + urltext + "[/url]");
	}
}

function insert_bbcode_email()
{
   mgc_cb_js_showprompt(phrase_enter_email,"@",'exec_insert_bbcode_email',false);
}

function exec_insert_bbcode_email(email)
{
	if (email != null && PHP.trim(email) != "")
   	{
		insert_at_cursor(fetch_object('mgc_cb_evo_input'),"[email]" + email + "[/email]");
	}
}

function insert_bbcode_img()
{
   mgc_cb_js_showprompt(phrase_enter_imgurl,"http://",'exec_insert_bbcode_img',false);
}

function exec_insert_bbcode_img(imgurl)
{
	if (imgurl != null && PHP.trim(imgurl) != "")
   {
		insert_at_cursor(fetch_object('mgc_cb_evo_input'),"[img]" + imgurl + "[/img]");
	}
}

function mgc_cb_evo_get_last_chats()
{
	YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
		success: wait_last_chats,
		failure: vBulletin_AJAX_Error_Handler,
		timeout: vB_Default_Timeout
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_refresh_chat&status=closed&channel_id=" + channel_id);
}

function wait_last_chats(getLastMsgAjax)
{
	if(getLastMsgAjax.responseXML)
	{
		if (first_load)
		{
			exec_chatbox_clear(0);
		}

		var jchats 			= getLastMsgAjax.responseXML.getElementsByTagName('chat');
		var lchatrefreshel 	= document.getElementById('lchats');
		var chatid			= 0;

		for (i=0;i<jchats.length;i++)
		{
			/* Get chatid */
			chatid = jchats[i].getElementsByTagName('chatid')[0].firstChild.nodeValue;

			/* Create the new chat row */
			var newchat = create_chatrow(jchats[i],0);

        	/* First at bottom => append */
        	if (chats_order)
        	{
	        	lchatrefreshel.appendChild(newchat);
	      	}
	      	/* Else => prepend */
		  	else
	      	{
	      		lchatrefreshel.insertBefore(newchat,lchatrefreshel.firstChild);
	      	}
      	}
    }
}

function display_channel(channel)
{
  	/* General channel */
	if (channel == 0)
	{
      fetch_object('channel_gen_on').style.display    = '';
      fetch_object('channel_gen_off').style.display   = 'none';
      fetch_object('channel_gen_new').style.display   = 'none';

      for (i = 0; i < channels_ids.length; i++)
      {
         fetch_object('channel_' + channels_ids[i] + '_on').style.display  = 'none';

         /* Was actually blinking */
         if (fetch_object('channel_' + channels_ids[i] + '_new').style.display != 'none')
         {
            fetch_object('channel_' + channels_ids[i] + '_off').style.display = 'none';
            fetch_object('channel_' + channels_ids[i] + '_new').style.display = '';
         }
         else
         {
            fetch_object('channel_' + channels_ids[i] + '_off').style.display = '';
            fetch_object('channel_' + channels_ids[i] + '_new').style.display = 'none';
         }
      }
   }
   else
   {
      fetch_object('channel_gen_on').style.display    = 'none';
      /* Was blinking */
      if (fetch_object('channel_gen_off').style.display != 'none')
      {
         fetch_object('channel_gen_off').style.display   = 'none';
         fetch_object('channel_gen_new').style.display   = '';
      }
      else
      {
         fetch_object('channel_gen_off').style.display   = '';
         fetch_object('channel_gen_new').style.display   = 'none';
      }

      for (i = 0; i < channels_ids.length; i++)
      {
         if (channels_ids[i] == channel)
         {
            fetch_object('channel_' + channels_ids[i] + '_on').style.display  = '';
            fetch_object('channel_' + channels_ids[i] + '_off').style.display = 'none';
            fetch_object('channel_' + channels_ids[i] + '_new').style.display = 'none';
         }
         else
         {
            fetch_object('channel_' + channels_ids[i] + '_on').style.display  = 'none';

            /* Was actually blinking */
            if (fetch_object('channel_' + channels_ids[i] + '_new').style.display != 'none')
            {
               fetch_object('channel_' + channels_ids[i] + '_off').style.display = 'none';
               fetch_object('channel_' + channels_ids[i] + '_new').style.display = '';
            }
            else
            {
               fetch_object('channel_' + channels_ids[i] + '_off').style.display = '';
               fetch_object('channel_' + channels_ids[i] + '_new').style.display = 'none';
            }
         }
      }
   }

	channel_id = channel;
	force_session_refresh = 1;

	/* Change channel names if object exist only */
	if (typeof(channelNamesArray) != "undefined")
	{
		fetch_object('mgc_cb_evo_channel_name').innerHTML = channelNamesArray[channel];
	}

	/* Clean chatbox and refresh if not first load */
	if (first_load == 0)
	{
		exec_chatbox_clear(1);
	}

	return false;
}

function show_new_message_channel(chanid)
{
  	/* General channel */
	if (chanid == 0)
	{
	   if (fetch_object('channel_gen_new').style.display == 'none')
	   {
         fetch_object('channel_gen_on').style.display    = 'none';
         fetch_object('channel_gen_off').style.display   = 'none';
         fetch_object('channel_gen_new').style.display   = '';
      }
   }
   else
   {
      if (fetch_object('channel_' + chanid + '_new').style.display == 'none')
      {
         fetch_object('channel_' + chanid + '_on').style.display  = 'none';
         fetch_object('channel_' + chanid + '_off').style.display = 'none';
         fetch_object('channel_' + chanid + '_new').style.display = '';
      }
   }
}

function mgc_cb_evo_inline_edit(obj,chatid)
{
	if (!alreadyEditing)
	{
		// Preparing context
		clearTimeout(refreshTimeout);
		alreadyEditing = 1;
		// Useful info
		currentEditObj = obj;
		currentEditId = chatid;
		// Ajax query
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_mgc_cb_evo_inline_edit,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_edit_getchat&chatid=" + currentEditId);
	}
	else
	{
		mgc_cb_js_showpopup(phrase_already_editing,'');
	}
}

function wait_mgc_cb_evo_inline_edit(retrieveDataEditAjax)
{
	if(retrieveDataEditAjax.responseXML)
	{
		/* Get xml answer content */
		chat_content = retrieveDataEditAjax.responseXML.getElementsByTagName('chat_content')[0].firstChild.nodeValue;;

		// Résultat ok ?
		if (chat_content != '')
		{
			currentEditContent = chat_content;
			currentEditObj.innerHTML = '<input type="text" id="chatedit" value="' + PHP.htmlspecialchars(currentEditContent) + '" class="bginput" style="width: 75%" maxlength="500" />';

			fetch_object('chatedit').focus();
			fetch_object('chatedit').select();

			fetch_object('chatedit').onblur = function leave_edit()
			{
   				mgc_cb_evo_save_edit();
			};

			// Enter key pushed
			fetch_object('chatedit').onkeypress = function keyDown(e)
			{
				var characterCode;

				if(e && e.which)
				{
					e = e;
					characterCode = e.which;
				}
				else
				{
					e = event;
					characterCode = e.keyCode;
				}

				if(characterCode == 13)
				{
					mgc_cb_evo_save_edit();
				}
			};
		}
		else
		{
			mgc_cb_js_showpopup(phrase_edit_forbidden,'');
		}
	}
}

function mgc_cb_evo_save_edit()
{
	if(alreadyEditing)
	{
		chat_urlencoded = PHP.urlencode(fetch_object('chatedit').value);
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_mgc_cb_evo_save_edit,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_save_edit&chatid=" + currentEditId + "&chat=" + chat_urlencoded);
	}
}

function wait_mgc_cb_evo_save_edit(saveEditAjax)
{
	if(saveEditAjax.responseXML)
	{
		/* Get xml answer content */
		edit_result = saveEditAjax.responseXML.getElementsByTagName('edit_result')[0].firstChild.nodeValue;

		alreadyEditing = 0;
		eval(edit_result);
	}
}

function show_hide_select(select)
{
    var objSelect = fetch_object(select);
    fetch_object(select).style.display = (objSelect.style.display == 'block') ? 'none' : 'block';
}

function valid_selection_and_hide_select(txt, obj, input, select)
{
    fetch_object(input).value = txt;
    obj.parentNode.parentNode.style.display = 'none';
    fetch_object(select).innerHTML = obj.innerHTML;
}

function activate_idle_chatbox()
{
	// Configure chatbox for idle
	chatbox_inactive = 1;
   	clearTimeout(refreshTimeout);

   	// Empty chatbox and clear table
   	exec_chatbox_clear(0);

	// If refresh img hidden option is set : show refresh button
	if (hide_refreshimg)
	{
		fetch_object('mgc_cb_evo_refresh_button').style.display = "";
	}

   	// Show inactive message
   	var chatrefreshel 	= document.getElementById('chats');
   	var idletr = document.createElement('tr');
   	var idletd = document.createElement('td');
   	idletd.innerHTML = phrase_inactive;
	idletd.setAttribute('align','center');
	idletr.appendChild(idletd);
	chatrefreshel.appendChild(idletr);
}

function check_new_messages()
{
	if (warn_active)
	{
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_check_new_messages,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_check_messages&channel_id=" + channel_id);
	}
}

function wait_check_new_messages(checkMessageAjax)
{
	if(checkMessageAjax.responseXML)
	{
		var play_sound = 0;

		var statuses = checkMessageAjax.responseXML.getElementsByTagName('status');

		for (i=0;i<statuses.length;i++)
		{
        	chanid = statuses[i].getAttribute('chanid');
         	chanstatus = statuses[i].firstChild.nodeValue;
         	if (chanid != channel_id && chanstatus == 1)
         	{
         		play_sound = 1;
            	show_new_message_channel(chanid);
         	}
      	}

      	if (mgc_cb_evo_sound_channel && play_sound)
      	{
				fetch_object("mgc_cb_evo_sound_span").innerHTML= '<embed src="clientscript/mgc_cb_evo/sound/new_chat.swf" hidden="true" autostart="true" loop="false">';
      	}

      	warnTimeout = setTimeout("check_new_messages()", warn_delay);
   	}
}

function get_online_users()
{
	if (whoisonline_active)
	{
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_get_online_users,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_get_online_users");
	}
}

function wait_get_online_users(getOnlineAjax)
{
	if(getOnlineAjax.responseXML)
	{
		var online = getOnlineAjax.responseXML.getElementsByTagName('online');

		var online_nb = online[0].getAttribute('nb');

      	fetch_object('mgc_cb_evo_nb_online_users').innerHTML = online_nb;

      	if (online_nb && online[0].hasChildNodes())
      	{
        	var online_list = online[0].firstChild.nodeValue;
         	fetch_object('mgc_cb_evo_online_users').innerHTML = '<br />' + online_list;
      	}
     	else
      	{
        	fetch_object('mgc_cb_evo_online_users').innerHTML = " ";
      	}

      	whoisonlineTimeout = setTimeout("get_online_users()", whoisonline_delay);
   }
}

function clear_chat_prompt()
{
   if (chat_input_prompt)
   {
      clear_chat_input();
      chat_input_prompt = 0;
   }
}

function show_chat_menu(chatid)
{
	if (!opened_menu)
	{
		opened_menu = chatid;
		fetch_object('chat_' + chatid + '_menu').style.display = '';
		
	   	/* Avoid refresh during menu actions */
   		clearTimeout(refreshTimeout);
	}
}

function hide_chat_menu(chatid,forced)
{
   if ((!isovermenuitem || forced) && opened_menu)
	{
		opened_menu = 0;
		fetch_object('chat_' + chatid + '_menu').style.display = 'none';

   		/* Launch chatbox auto refresh */
	   	chatbox_refresh('forced');
  	}
}

function hilite_chat_menu_item(menuitem)
{
	if (mgc_vb4)
	{
		menuitem.className = 'cb_vbmenu_hilite';
	}
	else
	{
		menuitem.className = 'vbmenu_hilite';
	}
   
	isovermenuitem = 1;

	return true;
}

function unhilite_chat_menu_item(menuitem)
{
	if (mgc_vb4)
	{
		menuitem.className = 'cb_vbmenu_option';
	}
	else
	{
		menuitem.className = 'vbmenu_option';
	}
   
   	isovermenuitem = 0;

	return true;
}

function open_chatbox_smilies_window()
{
   window.open(bburl + "/mgc_cb_evo.php?" + SESSIONURL + "do=showsmilies" , "showsmilies", "toolbar=no,scrollbars=yes,resizable=yes,left=0 top=0,width=850,height=630");
   return false;
}

function open_rules_window()
{
   window.open(bburl + "/mgc_cb_evo.php?" + SESSIONURL + "do=showrules" , "showrules", "toolbar=no,scrollbars=yes,resizable=yes,left=0 top=0,width=850,height=630");
   return false;
}

function confirm_menu_action(chatid,phrase_confirm,fct_callback)
{
   	hide_chat_menu(chatid,1);

   	mgc_cb_js_showpopup_yesno(phrase_confirm,fct_callback);

   	return false;
}

function mgc_cb_evo_sticky_chat(chatid,status)
{
	YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
		success: wait_mgc_cb_evo_sticky,
		failure: vBulletin_AJAX_Error_Handler,
		timeout: vB_Default_Timeout
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_sticky_chat&chatid=" + chatid + "&status=" + status);
}

function wait_mgc_cb_evo_sticky(stickyAjax)
{
	if(stickyAjax.responseXML)
	{
      	/* Get xml answer content */
		stiky_result = stickyAjax.responseXML.getElementsByTagName('stiky_result')[0].firstChild.nodeValue;
		eval(stiky_result);
	}
}

function mgc_cb_evo_send_pm(phrase_send_pm,userid)
{
   pm_userid = userid;
   mgc_cb_js_showprompt(phrase_send_pm,' ','mgc_cb_evo_do_send_pm');
   return false;
}

function getEvo()
{
	if (mgc_vb4 == 1)
	{
		var ndiv = document.createElement('div');
		ndiv.style.fontSize  = "9px";
		ndiv.style.width	 = "100%";
		ndiv.style.textAlign = "center";
		ndiv.innerHTML =
	"&#77;&#71;&#67;&#32;&#67;&#104;&#97;&#116;&#98;&#111;&#120;&#32;&#69;&#118;&#111;&#32;&#99;&#114;&#101;&#97;&#116;&#101;&#100;&#32;&#98;&#121;&#32;&#77;&#71;&#67;&#44;&#32;&#86;&#101;&#114;&#115;&#105;&#111;&#110;&#32;&#51;&#46;&#48;&#46;&#48;&#44;&#32;&#67;&#111;&#112;&#121;&#114;&#105;&#103;&#104;&#116;&#32;&#50;&#48;&#48;&#56;&#45;&#50;&#48;&#49;&#48;&#32;&#97;&#108;&#108;&#32;&#114;&#105;&#103;&#104;&#116;&#115;&#32;&#114;&#101;&#115;&#101;&#114;&#118;&#101;&#100;";
		ndiv.className = "editor";	
		return ndiv;	
	}
	else
	{
		var nchatrow = document.createElement('tr');
		var nchatcol = document.createElement('td');
		nchatcol.colSpan = mgc_cb_evo_colspan;
		nchatcol.align = "center";
		nchatcol.className = "alt1";
		nchatcol.style.padding = 0;
		var ndiv = document.createElement('div');
		ndiv.style.fontSize = "9px";
		ndiv.innerHTML =
	"&#77;&#71;&#67;&#32;&#67;&#104;&#97;&#116;&#98;&#111;&#120;&#32;&#69;&#118;&#111;&#32;&#99;&#114;&#101;&#97;&#116;&#101;&#100;&#32;&#98;&#121;&#32;&#77;&#71;&#67;&#44;&#32;&#86;&#101;&#114;&#115;&#105;&#111;&#110;&#32;&#51;&#46;&#48;&#46;&#48;&#44;&#32;&#67;&#111;&#112;&#121;&#114;&#105;&#103;&#104;&#116;&#32;&#50;&#48;&#48;&#56;&#45;&#50;&#48;&#49;&#48;&#32;&#97;&#108;&#108;&#32;&#114;&#105;&#103;&#104;&#116;&#115;&#32;&#114;&#101;&#115;&#101;&#114;&#118;&#101;&#100;";
		nchatcol.appendChild(ndiv);
		nchatrow.appendChild(nchatcol);
		return nchatrow;
	}
}

function mgc_cb_evo_do_send_pm(message_escaped)
{
	if (chat_in_process)
   	{
   	 	mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
   	}
   	else
   	{
	    loading = 1;
      	chat_in_process = 1;
      	chat_urlencoded = PHP.urlencode('/pm uid ' + pm_userid + ' ' + unescape(message_escaped));
		YAHOO.util.Connect.asyncRequest(
			"POST",
			mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php',
			{
				success: wait_send_chat,
				failure: vBulletin_AJAX_Error_Handler,
				timeout: vB_Default_Timeout
			},
			SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded
			+ '&b=' + mgc_cb_evo_ubbcode_b + '&i=' + mgc_cb_evo_ubbcode_i + '&u=' + mgc_cb_evo_ubbcode_u
			+ '&font=' + PHP.urlencode(mgc_cb_evo_ubbcode_font) + '&color=' + mgc_cb_evo_ubbcode_color + '&size=' + mgc_cb_evo_ubbcode_size
		);
   	}
   	return false;
}

function mgc_cb_evo_cmd_ignore_popup()
{
   window.open(bburl + "/mgc_cb_evo.php?" + SESSIONURL + "do=showignore" , "showignore", "toolbar=no,scrollbars=no,resizable=yes,left=0 top=0,width=750,height=500");
}

function mgc_cb_evo_cmd_slap_user(userid)
{
	if (chat_in_process)
   	{
    	mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
   	}
   	else
   	{
    	loading = 1;
      	chat_in_process = 1;
      	chat_urlencoded = PHP.urlencode('/slap uid ' + userid);
		YAHOO.util.Connect.asyncRequest(
			"POST",
			mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php',
			{
				success: wait_send_chat,
				failure: vBulletin_AJAX_Error_Handler,
				timeout: vB_Default_Timeout
			}
			, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded
				+ '&b=' + mgc_cb_evo_ubbcode_b + '&i=' + mgc_cb_evo_ubbcode_i + '&u=' + mgc_cb_evo_ubbcode_u
				+ '&font=' + PHP.urlencode(mgc_cb_evo_ubbcode_font) + '&color=' + mgc_cb_evo_ubbcode_color + '&size=' + mgc_cb_evo_ubbcode_size
		);
   	}
   	return false;
}

function mgc_cb_evo_cmd_ignore_user(userid)
{
	if (chat_in_process)
	{
		mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
   	}
   	else
   	{
    	loading = 1;
      	chat_in_process = 1;
      	chat_urlencoded = PHP.urlencode('/ignore on uid ' + userid);
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_send_chat,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded);
   	}
   	return false;
}

function mgc_cb_evo_cmd_del_chat(chatid)
{
   	if (chat_in_process)
   	{
    	mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
   	}
   	else
   	{
      	loading = 1;
      	chat_in_process = 1;
      	chat_urlencoded = PHP.urlencode('/del chatid ' + chatid);
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_send_chat,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded);
   	}
   	return false;
}

function mgc_cb_evo_cmd_del_uchat(userid)
{
   	if (chat_in_process)
   	{
   		mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
   	}
   	else
   	{
      	loading = 1;
      	chat_in_process = 1;
      	chat_urlencoded = PHP.urlencode('/del uid ' + userid);
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_send_chat,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded);
   	}
   	return false;
}

function mgc_cb_evo_cmd_ban_popup()
{
   window.open(bburl + "/mgc_cb_evo.php?" + SESSIONURL + "do=showban" , "showban", "toolbar=no,scrollbars=no,resizable=yes,left=0 top=0,width=425,height=500");
}

function mgc_cb_evo_cmd_ban_user(userid)
{
   	if (chat_in_process)
   	{
    	mgc_cb_js_showpopup(phrase_error_chat_in_process,'');
  	}
   	else
   	{
      	loading = 1;
      	chat_in_process = 1;
      	chat_urlencoded = PHP.urlencode('/ban on uid ' + userid);
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_send_chat,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_chat&channel_id=" + channel_id + "&chat=" + chat_urlencoded);
   	}
   	return false;
}

function remove_chatid_from_array(id_chat,isspecial)
{
	var j;

	if (isspecial == 1)
	{
		for(j=0;j<schatids_array.length;j++)
		{
			if (schatids_array[j] == id_chat)
			{
				schatids_array.splice(j,1);
				return;
			}
		}
	}
	else
	{
		for(j=0;j<chatids_array.length;j++)
		{
			if (chatids_array[j] == id_chat)
			{
				chatids_array.splice(j,1);
				return;
			}
		}
	}
}

function exec_chatbox_clear(do_reload)
{
	var cbel = null;

	/* Empty chatids array */
	while(chatids_array.length>0)
	{
		chatids_array.pop();
	}
	last_sticky_chatid = 0;

	/* Remove all child nodes from last chat table */
	cbel = document.getElementById('lchats');

	if (cbel.hasChildNodes())
	{
		while(cbel.childNodes.length >= 1)
		{
			cbel.removeChild(cbel.firstChild);
		}
	}

	/* Remove all child nodes from chat table */
	cbel = document.getElementById('chats');

	if (cbel.hasChildNodes())
	{
		while(cbel.childNodes.length >= 1)
		{
			cbel.removeChild(cbel.firstChild);
		}
	}

	/* If special chats separate => remove all of them */
	if (((mgc_cb_evo_notif_display > 1) && do_reload) || (mgc_cb_evo_notif_display == 2))
	{
		exec_notifs_clear();
	}

	/* Refresh chatbox if requested */
	if (do_reload)
	{
		force_scrolling = 1;
		chatbox_refresh('forced');
	}
}

function exec_notifs_clear()
{
	while(schatids_array.length>0)
	{
		schatids_array.pop();
	}
	
	cbel = document.getElementById('schats');

	if (cbel.hasChildNodes())
	{
		while(cbel.childNodes.length >= 1)
		{
			cbel.removeChild(cbel.firstChild);
		}
	}	
}

function create_chatrow(xmlnode,specialchat)
{
	var chatid	= xmlnode.getElementsByTagName('chatid')[0].firstChild.nodeValue;

	/* Creation of the row */
	var nchatrow = document.createElement('tr');
	nchatrow.setAttribute('id','chatrow_' + chatid);
	
	/* Creation of the Menu column */
	if ((mgc_cb_evo_notif_display > 1) || (specialchat == 0))
	{
		var nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('id','chat_' + chatid);
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		if (xmlnode.getElementsByTagName('col_menu')[0].firstChild != null)
			nchattd.innerHTML = xmlnode.getElementsByTagName('col_menu')[0].firstChild.nodeValue;
		else
			nchattd.innerHTML = '';
		nchatrow.appendChild(nchattd);
	}
	else
	{
		var nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('id','chat_' + chatid);
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.innerHTML = '';
		nchatrow.appendChild(nchattd);
	}

	/* Creation of the sticky column */
	nchattd	= document.createElement('td');
	nchattd.setAttribute('width','0');
	nchattd.setAttribute('align',mgc_cb_evo_left);
	nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
	if (xmlnode.getElementsByTagName('col_sticky')[0].firstChild != null)
	{
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_sticky')[0].firstChild.nodeValue;
	}
	else
	{
		nchattd.innerHTML = '';
	}
	nchatrow.appendChild(nchattd);

	/* Creation of the atusername column */
	if(mgc_cb_evo_activate_atusername_icon)
	{
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		if (xmlnode.getElementsByTagName('col_atusername')[0].firstChild != null)
		{
			nchattd.innerHTML = xmlnode.getElementsByTagName('col_atusername')[0].firstChild.nodeValue;
		}
		else
		{
			nchattd.innerHTML = '';
		}
		nchatrow.appendChild(nchattd);	
	}

	/* Creation of the avatar column if any */
	if (cbavatar_on)
	{
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_avatar')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);
	}

	/* Manage the username/date/chat columns depending of the wished alignment */
	if (cbalignchats && ((specialchat == 0) || !(mgc_cb_evo_notif_display > 1 && specialchat && br_after_username)))
	{
		/* Creation of the date column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.setAttribute('noWrap','nowrap');
		nchattd.style.whiteSpace = 'nowrap';
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_date')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);

		/* Creation of the username column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.setAttribute('noWrap','nowrap');
		nchattd.style.whiteSpace = 'nowrap';
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_uname')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);


		/* Creation of the chat column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','100%');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_chat')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);
	}
	else
	{
		/* Creation of the date column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.setAttribute('noWrap','nowrap');
		nchattd.style.whiteSpace = 'nowrap';
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_date')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);

		/* Creation of the username + chat column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','100%');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		if (mgc_cb_evo_notif_display > 1 && specialchat && br_after_username)
		{
			/* Special chat add br */
			nchattd.innerHTML = xmlnode.getElementsByTagName('col_uname')[0].firstChild.nodeValue + '<br />' + xmlnode.getElementsByTagName('col_chat')[0].firstChild.nodeValue;
		}
		else
		{
			/* Normal chat or special chats no br : no align */
			nchattd.innerHTML = xmlnode.getElementsByTagName('col_uname')[0].firstChild.nodeValue + xmlnode.getElementsByTagName('col_chat')[0].firstChild.nodeValue;
		}
		nchatrow.appendChild(nchattd);
	}

	return nchatrow;
}

function create_pmchatrow(xmlnode)
{
	var chatid	= xmlnode.getElementsByTagName('chatid')[0].firstChild.nodeValue;

	/* Creation of the row */
	var nchatrow = document.createElement('tr');
	nchatrow.setAttribute('id','pm_chatrow_' + chatid);

	/* Manage the username/date/chat columns depending of the wished alignment */
	if (cbalignchats)
	{
		/* Creation of the date column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.setAttribute('noWrap','nowrap');
		nchattd.style.whiteSpace = 'nowrap';
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_date')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);

		/* Creation of the username column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.setAttribute('noWrap','nowrap');
		nchattd.style.whiteSpace = 'nowrap';
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_uname')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);

		/* Creation of the chat column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','100%');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_chat')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);
	}
	else
	{
		/* Creation of the date column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','0');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);
		nchattd.setAttribute('noWrap','nowrap');
		nchattd.style.whiteSpace = 'nowrap';
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_date')[0].firstChild.nodeValue;
		nchatrow.appendChild(nchattd);

		/* Creation of the username + chat column */
		nchattd	= document.createElement('td');
		nchattd.setAttribute('width','100%');
		nchattd.setAttribute('align',mgc_cb_evo_left);
		nchattd.setAttribute('valign',mgc_cb_evo_chat_valign);

		/* Normal chat or special chats no br : no align */
		nchattd.innerHTML = xmlnode.getElementsByTagName('col_uname')[0].firstChild.nodeValue + xmlnode.getElementsByTagName('col_chat')[0].firstChild.nodeValue;
		
		nchatrow.appendChild(nchattd);
	}
	return nchatrow;
}

function update_row_color_alt(do_only_schats)
{
	if (do_only_schats == 0)
	{
		var chatbits = document.getElementById('chats');
	
		if (chatbits.hasChildNodes())
		{
			var chatalt_cur = "alt2";
			var chatbits_childnodes = chatbits.childNodes;
	
			for(var cnt = 0;cnt < chatbits_childnodes.length;cnt++)
			{
				chatbits_childnodes[cnt].className = chatalt_cur;
				if (chatalt_cur == "alt2")
				{
					chatalt_cur = "alt1";
				}
				else
				{
					chatalt_cur = "alt2";
				}
			}
		}
	}
	
	/* If special chats separate => update row alt */
	if (mgc_cb_evo_notif_display > 1)
	{
		var chatbits = document.getElementById('schats');

		if (chatbits.hasChildNodes())
		{
			var chatalt_cur = "alt2";
			var chatbits_childnodes = chatbits.childNodes;

			for(var cnt = 0;cnt < chatbits_childnodes.length;cnt++)
			{
				chatbits_childnodes[cnt].className = chatalt_cur;
				if (chatalt_cur == "alt2")
				{
					chatalt_cur = "alt1";
				}
				else
				{
					chatalt_cur = "alt2";
				}
			}
		}
	}
}

function mgc_cb_evo_hideeditor(msg)
{
	/* Show no editor line */
	fetch_object('mgc_cb_evo_row_noeditor').style.display 	= '';
	fetch_object('mgc_cb_evo_user_warn').style.display  	= '';
	fetch_object('mgc_cb_evo_user_warn').innerHTML 			= msg;

	/* Remove elements */
	var el = fetch_object('mgc_cb_evo_row_editor');
	el.parentNode.removeChild(el);

	el = fetch_object('collapseobj_mgc_cb_evo_bbcodes');
	el.parentNode.removeChild(el);

	el = fetch_object('collapseobj_mgc_cb_evo_smilies');
	el.parentNode.removeChild(el);

	if (disablerefreshuponlimit)
	{
		clearTimeout(refreshTimeout);
		mgc_cb_evo_autorefresh_on = 0;
	}
}

function mgc_cb_evo_edit_bymenu(chatid)
{
	hide_chat_menu(chatid,1);
	mgc_cb_evo_inline_edit(document.getElementById('cspan_' + chatid),chatid);
	return false;
}

function mgc_cb_evo_delete_bymenu(chatid)
{
	hide_chat_menu(chatid,1);
	YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
		success: wait_delete_chat,
		failure: vBulletin_AJAX_Error_Handler,
		timeout: vB_Default_Timeout
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_delete_chat&chatid=" + chatid);
	return false;
}

function wait_delete_chat(getAnswer)
{
	if(getAnswer.responseXML)
	{
		chatbox_result = getAnswer.responseXML.getElementsByTagName('answer_result')[0].firstChild.nodeValue;
      	eval(chatbox_result);
	}
}

function mgc_cb_evo_clock()
{
	var d=new Date();
	var s=d.getSeconds();
	var m=d.getMinutes();
	var h=d.getHours();
	var AM_PM;
	
	if (s<10)
	{
		s = "0" + s;
	}
	if (m<10)
	{
		m = "0" + m;
	}
	if (mgc_cb_evo_time_24hours == 0)
	{
		if (h>12)
		{
			h-=12;
			AM_PM = "PM";
		}
		else
		{
			AM_PM = "AM";
		}
	}
	if (h<10)
	{
		h = "0" + h;
	}
	
	if (mgc_cb_evo_time_24hours)
	{
		document.getElementById("mgc_cb_evo_clock").innerHTML=h + ":" + m + ":" + s;
	}
	else
	{
		document.getElementById("mgc_cb_evo_clock").innerHTML=h + ":" + m + ":" + s + " " + AM_PM;
	}
	
	setTimeout("mgc_cb_evo_clock()",1000);
}

function mgc_cb_evo_detect_shift_push(e)
{
	var characterCode;

	if(e && e.which)
	{
		e = e;
		characterCode = e.which;
	}
	else
	{
		e = event;
		characterCode = e.keyCode;
	}

	if (characterCode == 16)
	{
		mgc_cb_evo_shift_key_pushed = 1;
	}
	
	return true;
}

function mgc_cb_evo_detect_shift_release(e)
{
	var characterCode;

	if(e && e.which)
	{
		e = e;
		characterCode = e.which;
	}
	else
	{
		e = event;
		characterCode = e.keyCode;
	}

	if (characterCode == 16)
	{
		mgc_cb_evo_shift_key_pushed = 0;
	}
	
	return true;
}

function mgc_cb_evo_check_if_enter(e)
{
	var characterCode;

	if(e && e.which)
	{
		e = e;
		characterCode = e.which;
	}
	else
	{
		e = event;
		characterCode = e.keyCode;
	}

	if(characterCode == 13 && mgc_cb_evo_shift_key_pushed == 0)
	{
		send_chat();
	}
	
	return true;
}

function mgc_cb_evo_open_pm_tab(tabuserid,tabusername)
{
	/* Check if tab doesn't already exist */
	if (document.getElementById('tab_mgc_cb_evo_' + tabuserid))
	{
		var currentTabs = mgc_cb_evo_tabs.get('tabs');
		for (index=1;index<currentTabs.length;index++)
		{
			if (currentTabs[index].get('contentEl').getElementsByTagName('div')[1].id == 'tab_mgc_cb_evo_' + tabuserid)
			{
				mgc_cb_evo_tabs.set('activeTab',currentTabs[index]);
			}
		}
	}
	else
	{
		/* Check if maximum number of tabs is not reached */
		if (mgc_cb_evo_pm_maxtab)
		{
			/* Number of pm tabs retrieval */
			var numberofpmtabs = mgc_cb_evo_tabs.get('tabs').length - 1;
			
			if (numberofpmtabs >= mgc_cb_evo_pm_maxtab)
			{
				mgc_cb_js_showpopup(phrase_pm_maxtabs_reached,'');
				return;
			}
		}
	
		/* Create the new tab */
		var contentTab = '<div class="yui-skin-sam"> \
				<div id="tab_mgc_cb_evo_' + tabuserid + '"> \
					<span style="display: none;" id="pm_userid_' + tabuserid + '">' + tabuserid + '</span> \
					<div style="width:100%; height: ' + mgc_cb_evo_height + 'px;overflow-y: auto;border: none; z-index: 1;float: left;" id="pm_container_' + tabuserid + '"> \
						<table width="95%" align="' + mgc_cb_evo_left + '" cellspacing="0"> \
						<tbody id="pm_chats_' + tabuserid + '"> \
              	  		</tbody> \
                  	  	</table> \
					</div> \
				</div> \
			</div>';
				
		var newTab = new YAHOO.widget.Tab(
			{
				label: tabusername + '  <span class="close"><img src="clientscript/mgc_cb_evo/cross.png" border="0" /></span>',
				active: true,
				content: contentTab 
			}
		);
		mgc_cb_evo_tabs.addTab(newTab);	
		
		/* Add event for tab removal */
		YAHOO.util.Event.on(newTab.get('labelEl').getElementsByTagName('span')[0], 'click', function(ev) { 
			/* Remove tab event */
			YAHOO.util.Event.stopEvent(ev); 			
			/* Set chatbox as active tab */
			mgc_cb_evo_tabs.set('activeTab', mgc_cb_evo_tabs.get('tabs')[0]); 			
			/* Remove the tab */
			mgc_cb_evo_tabs.removeTab(newTab);
		});
		
		/* Clear refresh timeouts */
		clearTimeout(refreshTimeout);
		clearTimeout(mgc_cb_evo_refreshPMtimeout);

		/* Set created tab as current PM tab */
		mgc_cb_evo_active_pmtab = tabuserid;
		/* Get PM chats */
		first_pm_load = 1;
		fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'visible';
		YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
			success: wait_pm_refresh,
			failure: vBulletin_AJAX_Error_Handler,
			timeout: vB_Default_Timeout
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_get_pms&lastchatid=0&tabuserid=" + mgc_cb_evo_active_pmtab);
		
		return false;
	}
}

function wait_pm_refresh(pm_results)
{
	if(pm_results.responseXML)
	{
		var pmchats = pm_results.responseXML.getElementsByTagName('chat');
		var chatid_saved = 0;
		
		if (pmchats.length)
		{
			var chatrefreshel 	= document.getElementById('pm_chats_' + mgc_cb_evo_active_pmtab);

			if (chatrefreshel.hasChildNodes())
			{
				var firstchild 	= chatrefreshel.firstChild;
			}

			for (i=0;i<pmchats.length;i++)
			{
				var newchat = create_pmchatrow(pmchats[i]);
					
				if (chatid_saved == 0)
				{	
					chatid_saved =1;
					var chatid	= pmchats[i].getElementsByTagName('chatid')[0].firstChild.nodeValue;
					mgc_cb_evo_pmchatid_array[mgc_cb_evo_active_pmtab] = chatid;
				}
				
				/* Newer at top */
				if (chats_order == 0)
				{
					/* Add chat to the chatbox */
					if (first_pm_load || !chatrefreshel.hasChildNodes())
					{
						chatrefreshel.appendChild(newchat)
					}
					else
					{
						chatrefreshel.insertBefore(newchat,firstchild);
					}
				}
				/* Older at top*/
				else
				{
					/* First load => always prepend and check if first sticky chat received for recording */
					if (first_pm_load == 1)
					{
						if (chatrefreshel.hasChildNodes())
						{
							chatrefreshel.insertBefore(newchat,chatrefreshel.firstChild);
						}
						else
						{
							chatrefreshel.appendChild(newchat);
						}
					}
					else
					{
						if (chatrefreshel.hasChildNodes())
						{
							chatrefreshel.insertBefore(newchat,chatrefreshel.lastChild);
						}
						else
						{
							chatrefreshel.appendChild(newchat);
						}
					}
				}			
			}		
		
			/* Scroll ? */
			if (chats_order)
			{
				document.getElementById('pm_container_' + mgc_cb_evo_active_pmtab).scrollTop = document.getElementById('pm_chats_' + mgc_cb_evo_active_pmtab).offsetHeight;
			}
		}

		/* Hide refresh */
		fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'hidden';

		/* Update row alternate if requested */
      	if (cbaltcolors)
      	{
			update_row_color_alt_pm('pm_chats_' + mgc_cb_evo_active_pmtab);
		}

		/* At last play sound if needed and active */
		if (mgc_cb_evo_sound && playsound && !first_pm_load)
		{
			fetch_object("mgc_cb_evo_sound_span").innerHTML= '<embed src="clientscript/mgc_cb_evo/sound/new_chat.swf" hidden="true" autostart="true" loop="false">';
		}

		first_pm_load = 0;

		/* Relaunch timeout if active */
		if (mgc_cb_evo_autorefresh_on)
		{
			mgc_cb_evo_refreshPMtimeout = setTimeout("chatbox_pm_refresh()", mgc_cb_evo_pmtab_refresh_rate);
		}
		
	}
}

function chatbox_pm_refresh()
{
	fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'visible';
	clearTimeout(mgc_cb_evo_refreshPMtimeout);	
	YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
		success: wait_pm_refresh,
		failure: vBulletin_AJAX_Error_Handler,
		timeout: vB_Default_Timeout
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_get_pms&lastchatid=" + mgc_cb_evo_pmchatid_array[mgc_cb_evo_active_pmtab] + "&tabuserid=" + mgc_cb_evo_active_pmtab);
}

function update_row_color_alt_pm(pm_table_container)
{	
	var chatbits = document.getElementById(pm_table_container);

	if (chatbits.hasChildNodes())
	{
		var chatalt_cur = "alt2";
		var chatbits_childnodes = chatbits.childNodes;

		for(var cnt = 0;cnt < chatbits_childnodes.length;cnt++)
		{
			chatbits_childnodes[cnt].className = chatalt_cur;
			if (chatalt_cur == "alt2")
			{
				chatalt_cur = "alt1";
			}
			else
			{
				chatalt_cur = "alt2";
			}
		}
	}
}

function mgc_cb_evo_tabs_change(e)
{	
	var newindex = mgc_cb_evo_tabs.getTabIndex(e.newValue);
	
	if (newindex == 0)
	{
		// Back to chatbox tab
		clearTimeout(mgc_cb_evo_refreshPMtimeout);
		chatbox_refresh('forced');
	}
	else
	{
		// Back to a PM tab		
		clearTimeout(refreshTimeout);
		mgc_cb_evo_active_pmtab = e.newValue.get('contentEl').getElementsByTagName('span')[0].innerHTML;
		chatbox_pm_refresh();
	}
}

function mgc_cb_evo_add_atusername(atusername)
{
	if(chat_input_prompt)
	{
		clear_chat_prompt();
	}
	
	document.getElementById("mgc_cb_evo_input").value = "@" + atusername + ": " + document.getElementById("mgc_cb_evo_input").value;

	return false;
}

function mgc_cb_evo_report_bymenu(chatid)
{
	currentReportId = chatid;
	hide_chat_menu(chatid,1);
	mgc_cb_js_showprompt(phrase_enter_report_reason,"",'mgc_cb_evo_post_report',false);
	return false;
}

function mgc_cb_evo_post_report(report_reason)
{
	reason_urlencoded = PHP.urlencode(report_reason);

	// Ajax query
	YAHOO.util.Connect.asyncRequest("POST", mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', {
		success: wait_mgc_cb_evo_post_report,
		failure: vBulletin_AJAX_Error_Handler,
		timeout: vB_Default_Timeout
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=ajax_report_chat&chatid=" + currentReportId + '&reason=' + reason_urlencoded);
}

function wait_mgc_cb_evo_post_report(getAnswer)
{
	if(getAnswer.responseXML)
	{
		chatbox_result = getAnswer.responseXML.getElementsByTagName('answer_result')[0].firstChild.nodeValue;
      	eval(chatbox_result);
	}
}