var first_load = 1;
var prompt_callback_fct = null;
var alreadyEditing = 0;
var currentEditObj = null;
var currentEditContent = null;
var currentEditId = 0;
var chat_in_process = 0;
var refreshTimeout = null;
var warnTimeout = null;
var force_session_refresh = 0;
var isovermenuitem = 0;
var opened_menu = 0;
var pm_userid;
var addparam_to_callback = 1;
var chatids_array = new Array();
var last_scroll_height = 0;
var last_sticky_chatid = 0;
var temp_url = null;
var chat_username = null;

function mgc_cb_js_showpopup(message)
{
   fetch_object('mgc_cb_evo_input').disabled                = true;
   
   fetch_object('mgc_cb_evo_chat_popup_content').innerHTML  = message;
   fetch_object('mgc_cb_evo_close_button').style.display    = '';
   
   $.blockUI.defaults.fadeOut = 0; 
   $.blockUI({ message: $('#mgc_cb_evo_chat_popup'), css: { 
        border: 'none', 
        padding: '15px', 
        backgroundColor: '#000', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.8', 
        color: '#fff' 
    } }); }

function mgc_cb_js_hidepopup()
{
	$.unblockUI();
	
   fetch_object('mgc_cb_evo_input').disabled             = false;
 	fetch_object('mgc_cb_evo_close_button').style.display = 'none';
	
   chatbox_refresh('forced');
}

function mgc_cb_js_showprompt(message,inputval,prompt_callback,hideinput)
{
   prompt_callback_fct = prompt_callback;
   fetch_object('mgc_cb_evo_input').disabled                   = true;
   
   fetch_object('mgc_cb_evo_chat_popup_content').innerHTML     = message;
   fetch_object('mgc_cb_evo_prompt_input').value               = inputval;
   
   /* Enter key pushed */
   fetch_object('mgc_cb_evo_prompt_input').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_js_hideprompt(1);
       }
   };
   
   if (!hideinput)
   {
   	fetch_object('mgc_cb_evo_prompt_input_div').style.display   = '';
   }
   
   fetch_object('mgc_cb_evo_okcancel_buttons').style.display   = '';
   $.blockUI.defaults.fadeOut = 0; 
   $.blockUI({ message: $('#mgc_cb_evo_chat_popup'), css: { 
        border: 'none', 
        padding: '15px', 
        backgroundColor: '#000', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.8', 
        color: '#fff' 
    } });  
}

function mgc_cb_js_hideprompt(val)
{
	$.unblockUI(); 
	
   fetch_object('mgc_cb_evo_input').disabled               		= false;
   
   fetch_object('mgc_cb_evo_okcancel_buttons').style.display   = 'none';
   fetch_object('mgc_cb_evo_prompt_input_div').style.display   = 'none';
	
	/* Clicked on the ok button ? */
	if (val)
	{
		if (addparam_to_callback)
		{
      	eval(prompt_callback_fct + '("' + fetch_object('mgc_cb_evo_prompt_input').value + '");');
      }
      else
      {
      	eval(prompt_callback_fct + ';');
      }
   }
}


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 insert_enhanced_bbcode(select_item,tag)
{
	bbcode_option = select_item.options[select_item.selectedIndex].value;
	text_insert('[' + tag + '=' + bbcode_option + ']','[/' + tag + ']');
	select_item.selectedIndex = 0;
	return false;
}

function collapse_mgc_cb_evo()
{
   // Clear chats
   empty_chatids_array();
   $('#chats').empty();		
   $('#lchats').empty();		

   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)
{
   /* Reset inactive mode */
   if (chatbox_inactive)
   {
	  $('#chats').empty();
      chatbox_inactive = 0;
      idleTimeout = setTimeout("activate_idle_chatbox()", inactive_mode_delay);   
   }
   
	/* Forced refreshed, lets do it */
	if(auto_refresh || (type == 'forced'))
   {
      clearTimeout(refreshTimeout);			
		/* Type of refresh management */
		if (type == 'forced')
      {
			currentRefreshType = 'forced';
		}
      else
      {
			currentRefreshType = 'normal';
		}
		fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'visible';
    	refreshAjax = new vB_AJAX_Handler(true);
    	refreshAjax.onreadystatechange(wait_chatbox_refresh);
    	
    	var cids = chatids_array.join(',');

    	/* Chatbox is inactive, refresh forced => session update */
    	if (chatbox_inactive || force_session_refresh)
    	{ 
         refreshAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_refresh_chat&status=open&channel_id=' + channel_id + '&location=' + cb_location + '&first_load=1&chatids=' + cids + '&securitytoken=' + SECURITYTOKEN);
      }
      else
      {
         refreshAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_refresh_chat&status=open&channel_id=' + channel_id + '&location=' + cb_location + '&first_load=' + first_load + '&chatids=' + cids + '&securitytoken=' + SECURITYTOKEN);         
      }
      force_session_refresh = 0;
	}
   return false;
}

function wait_chatbox_refresh()
{
   if(refreshAjax.handler.readyState == 4 && refreshAjax.handler.status == 200 && refreshAjax.handler.responseXML)
   {   
   
   		var do_scrolling;
 		var jchats = fetch_tags(refreshAjax.handler.responseXML, 'chat');

		if (first_load)
		{
			$('#chats').empty();
		}

		// 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)
			{
				do_scrolling = 1;
			}
			else if (last_scroll_height == $('#chats_container').scrollTop())
			{
				// Scrollbar is at bottom we can scroll !
				do_scrolling = 1;
			}
			else
			{
				do_scrolling = 0;
			}
		}

		for (i=0;i<jchats.length;i++)
		{
         	var type 		= jchats[i].getAttribute('type');
         	var issticky 	= jchats[i].getAttribute('sticky');
         	var chatid 		= jchats[i].getAttribute('chatid');
         	
         	/* Whole page refresh requested */
			if (type == 2)
			{
				window.location.reload();      
			}
			/* Edit chat */
			else if (type == 1)
			{
				$('#chatrow_' + chatid).replaceWith(refreshAjax.fetch_data(jchats[i]));
			}
			/* Add chat */
			else if (type == 0)
			{
				chatids_array.push(chatid);
				/* Older at top */
				if (chats_order)
				{
					/* If no sticky chat yet -> append and check if first sticky chat received for recording */
					if (!last_sticky_chatid)
					{
						$('#chats').append(refreshAjax.fetch_data(jchats[i]));
						
						if (issticky == 1)
						{						
							last_sticky_chatid = chatid;						
						}
					}
					else
					{
						/* If sticky chat -> continue to append (first load) */
						if (issticky == 1)
						{
							$('#chats').append(refreshAjax.fetch_data(jchats[i]));						
						}
						/* Else, add before the first sticky chat */
						else
						{	
							$('#chatrow_' + last_sticky_chatid).before(refreshAjax.fetch_data(jchats[i]));	
						}
					}
				}
				/* Newer at top*/
				else
				{
					/* First load => always prepend and check if first sticky chat received for recording */
					if (first_load)
					{
						$('#chats').prepend(refreshAjax.fetch_data(jchats[i]));
						
						if (!last_sticky_chatid && issticky == 1)
						{
							last_sticky_chatid = chatid;
						}
					}
					else
					{
						/* If no sticky chat => prepend */
						if (!last_sticky_chatid)
						{
							$('#chats').prepend(refreshAjax.fetch_data(jchats[i]));
						}
						/* Add after the last sticky chat */
						else
						{
							$('#chatrow_' + last_sticky_chatid).after(refreshAjax.fetch_data(jchats[i]));							
						}
					}			
				}
			}
			/* Remove chat */
			else if (type == 3)
			{	
				if ($('#chatrow_' + chatid).length > 0)
				{
					$('#chatrow_' + chatid).remove();
				}
				remove_chatid_from_array(chatid);           	
			}
		}   

		/* First at bottom ? */
		if (do_scrolling)
		{
			$('#chats_container').scrollTop($('#chats').innerHeight());
			last_scroll_height = $('#chats_container').scrollTop();
		}
		
		refreshTimeout = setTimeout("chatbox_refresh()", val_timeout);
		
		if (first_load && warn_active)
		{
			check_new_messages();
		}
		
		first_load = 0;      
           
      /* Hide refresh */
      fetch_object('mgc_cb_evo_refresh_img').style.visibility = 'hidden';      
   }
}

function exec_collapse(item_id)
{
	obj = fetch_object('collapseobj_' + item_id);
	icon = fetch_object('icon_' + item_id);

	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 (obj.style.display == 'none')
   {
		get_online_users();
		icon_re = new RegExp("\\.gif$");
		icon.src = icon.src.replace(icon_re, '_collapsed.gif');
		fetch_object('chats').style.display = 'none';
	}
   else
   {
   	clearTimeout(whoisonlineTimeout);
		icon_re = new RegExp("_collapsed\\.gif$");
		icon.src = icon.src.replace(icon_re, '.gif');
		fetch_object('chats').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;
      chat_urlencoded = PHP.urlencode(fetch_object('mgc_cb_evo_input').value);		
      clear_chat_input();
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      /* Send the chat with the anonymous name if any */
      if (chatbox_ask_name)
      {
      	sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=' + channel_id + '&chat_name=' + chat_username + '&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
      }
      else
      {
      	sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=' + channel_id + '&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);      
      }
   	}
   	return false;
}


function wait_send_chat()
{
   if(sendAjax.handler.readyState == 4 && sendAjax.handler.status == 200 && sendAjax.handler.responseXML)
   {
      	/* Get xml answer content */
		var result_table = fetch_tags(sendAjax.handler.responseXML, 'sendchat_result');
		chatbox_result = sendAjax.fetch_data(result_table[0]);
           
      	chat_in_process = 0;
      
      	/* Execute ajax call return function */
      	eval(chatbox_result);
      	/* Clear timeout */
      	clearTimeout(refreshTimeout);
   }
}

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

function remove_bbcodes() {
	fetch_object('mgc_cb_evo_input').value = stripcode(fetch_object('mgc_cb_evo_input').value, false, false);
	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()
{
    getLastMsgAjax = new vB_AJAX_Handler(true);
    getLastMsgAjax.onreadystatechange(wait_last_chats);
    getLastMsgAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_refresh_chat&status=closed&channel_id=' + channel_id + '&securitytoken=' + SECURITYTOKEN);
}

function wait_last_chats()
{
	if(getLastMsgAjax.handler.readyState == 4 && getLastMsgAjax.handler.status == 200 && getLastMsgAjax.handler.responseXML)
	{
		var jchats = fetch_tags(getLastMsgAjax.handler.responseXML, 'chat');
				
		for (i=0;i<jchats.length;i++)
		{
	       	type = jchats[i].getAttribute('type');
        	/* First at bottom => append */
        	if (chats_order)
        	{
	        	$('#lchats').append(getLastMsgAjax.fetch_data(jchats[i]));
	      	}
	      	/* Else => prepend */
		  	else
	      	{
	        	$('#lchats').prepend(getLastMsgAjax.fetch_data(jchats[i]));
	      	}
      	}
    }
}

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;
	
	/* Clean chatbox and refresh */
	chatids_array = new Array();
	$('#chats').empty();
	chatbox_refresh('forced');
	
	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
		retrieveDataEditAjax = new vB_AJAX_Handler(true);
		retrieveDataEditAjax.onreadystatechange(wait_mgc_cb_evo_inline_edit);
      retrieveDataEditAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_edit_getchat&chatid=' + currentEditId + '&securitytoken=' + SECURITYTOKEN);
	}
   else
   {
		mgc_cb_js_showpopup(phrase_already_editing);
	}	
}

function wait_mgc_cb_evo_inline_edit()
{
   if(retrieveDataEditAjax.handler.readyState == 4 && retrieveDataEditAjax.handler.status == 200 && retrieveDataEditAjax.handler.responseXML)
   {
      /* Get xml answer content */
		var content_table = fetch_tags(retrieveDataEditAjax.handler.responseXML, 'chat_content');
		chat_content = retrieveDataEditAjax.fetch_data(content_table[0]);
      
      // 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)
   {
		/* No changes made ? */
	/*	if(fetch_object('chatedit').value == currentEditContent) 
      {
			alreadyEditing = 0;	
			currentEditObj.innerHTML = currentEditContent;
		}
      else
      {*/
			chat_urlencoded = PHP.urlencode(fetch_object('chatedit').value);		
			saveEditAjax = new vB_AJAX_Handler(true);
			saveEditAjax.onreadystatechange(wait_mgc_cb_evo_save_edit);
        	saveEditAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_save_edit&chatid=' + currentEditId + '&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);		
		//}
	}
}

function wait_mgc_cb_evo_save_edit()
{
   if(saveEditAjax.handler.readyState == 4 && saveEditAjax.handler.status == 200 && saveEditAjax.handler.responseXML)
   {
      /* Get xml answer content */
		var content_table = fetch_tags(saveEditAjax.handler.responseXML, 'edit_result');
		edit_result = saveEditAjax.fetch_data(content_table[0]);
		
		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
   	$('#chats').empty();
	empty_chatids_array();
   	
   	// Show inactive message
   	$('#chats').append("<div align=\"center\">" + phrase_inactive + "</div>");
}

function check_new_messages()
{
   if (warn_active)
   {
      checkMessageAjax = new vB_AJAX_Handler(true);
      checkMessageAjax.onreadystatechange(wait_check_new_messages);		
      checkMessageAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_check_messages&channel_id=' + channel_id + '&securitytoken=' + SECURITYTOKEN);
   }
}

function wait_check_new_messages()
{
   if(checkMessageAjax.handler.readyState == 4 && checkMessageAjax.handler.status == 200 && checkMessageAjax.handler.responseXML)
   {
		var statuses = fetch_tags(checkMessageAjax.handler.responseXML, 'status');

		for (i=0;i<statuses.length;i++)
		{
         chanid = statuses[i].getAttribute('chanid');
         chanstatus = checkMessageAjax.fetch_data(statuses[i]);
         if (chanid != channel_id && chanstatus == 1)
         {
            show_new_message_channel(chanid);          
         }
      }
      warnTimeout = setTimeout("check_new_messages()", warn_delay); 
   }
}   

function get_online_users()
{
   if (whoisonline_active)
   {
      getOnlineAjax = new vB_AJAX_Handler(true);
      getOnlineAjax.onreadystatechange(wait_get_online_users);		
      getOnlineAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_get_online_users&securitytoken=' + SECURITYTOKEN);
   }
}

function wait_get_online_users()
{
   if(getOnlineAjax.handler.readyState == 4 && getOnlineAjax.handler.status == 200 && getOnlineAjax.handler.responseXML)
   {
		var online = fetch_tags(getOnlineAjax.handler.responseXML, 'online');

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

      fetch_object('mgc_cb_evo_nb_online_users').innerHTML = online_nb;
      
      if (online_nb)
      {
         var online_list = getOnlineAjax.fetch_data(online[0]);
         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 = 1;
		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)
{
   menuitem.className = 'vbmenu_hilite';
   isovermenuitem = 1;
   
   return true;
}

function unhilite_chat_menu_item(menuitem)
{
   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,callback_has_param)
{
	addparam_to_callback = callback_has_param;
   	hide_chat_menu(chatid,1);
   
   	mgc_cb_js_showprompt(phrase_confirm,'',fct_callback,true);
}

function mgc_cb_evo_sticky_chat(chatid,status)
{	
	stickyAjax = new vB_AJAX_Handler(true);
	stickyAjax.onreadystatechange(waith_mgc_cb_evo_sticky);
   stickyAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_sticky_chat&chatid=' + chatid + '&status=' + status + '&securitytoken=' + SECURITYTOKEN);		
}

function waith_mgc_cb_evo_sticky()
{
   if(stickyAjax.handler.readyState == 4 && stickyAjax.handler.status == 200 && stickyAjax.handler.responseXML)
   {
      	/* Get xml answer content */
		var content_table = fetch_tags(stickyAjax.handler.responseXML, 'stiky_result');
		stiky_result = stickyAjax.fetch_data(content_table[0]);
		eval(stiky_result);
		mgc_cb_evo_force_page_refresh();
	}	
}

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 mgc_cb_evo_do_send_pm(message)
{
   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 + ' ' + message);		
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=0&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
   }
   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=375,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);		
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=0&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
   }
   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);		
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=0&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
   }
   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);		
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=0&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
   }
   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);		
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=0&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
   }
   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);		
      sendAjax = new vB_AJAX_Handler(true);
      sendAjax.onreadystatechange(wait_send_chat);
      sendAjax.send(mgc_cb_evo_jsloc + 'mgc_cb_evo_ajax.php', 'do=ajax_chat&channel_id=0&chat=' + chat_urlencoded + '&securitytoken=' + SECURITYTOKEN);
   }
   return false;   
}

function remove_chatid_from_array(id_chat)
{	
	var j;
	for(j=0;j<chatids_array.length;j++)
	{
		if (chatids_array[j] == id_chat)
		{
			chatids_array.splice(j,1);
			return;
		}
	}
}

function empty_chatids_array()
{
	while(chatids_array.length>0){
		chatids_array.pop();
	}
	last_sticky_chatid = 0;
}

function chatbox_full_reload()
{
	empty_chatids_array();
	$('#chats').empty();
	chatbox_refresh('forced');
}