var chatEnCours = 0;
var refreshTimeout = null;
var editEnCours = 0;
var currentRefreshType = 'normal';
var currentEditObj = null;
var currentEditId = 0;
var currentEditContent = null;
var arSuppressionEnCours = 0;
var arSupprimerChatAjax = null;
var loading = 1;
var checkTeamAjax = null;
var checkTeamTimeout = null;
var isinactive = 0;
var getWolAjax = null;
var getWolEnCours = 0;
var avTeamMsg;

function myAlert(message) {
    var y=document.createElement('span');
    y.innerHTML=message;
    alert(y.innerHTML);
}

function vider_input_chat() {
    fetch_object('chatinput').value = '';
	return false;
}

function collaspe_chatbox() {
	if(fetch_object('chatbox_ouverte').style.display == '') {
        fetch_object('chatbox_ouverte').style.display = 'none';
        fetch_object('chatbox_titre_ouverte').style.display = 'none';
        fetch_object('chatbox_titre_fermee').style.display  = '';		
        clearTimeout(refreshTimeout);
		if(show_repliee) {
	        fetch_object('chatbox_fermee').style.display  = '';			
			fetch_object('chats_derniers').innerHTML = '';
			chatbox_get_derniers_msg();
		}
    } else {
        fetch_object('chatbox_ouverte').style.display = '';
        fetch_object('chatbox_fermee').style.display  = 'none';
        fetch_object('chatbox_titre_ouverte').style.display = '';
        fetch_object('chatbox_titre_fermee').style.display  = 'none';		
        chatbox_refresh('forced');
    }
};

function chatbox_refresh(type) {
	/* Rafraîchissement forcé => on le fait */
	if(auto_refresh || (type == 'forced')) {
        clearTimeout(refreshTimeout);		
		
		isinactive = 0;
		/* Gestion du type de refresh pour la mise à jour de la position du scroll */
		if (type == 'forced') {
			loading = 1;
			currentRefreshType = 'forced';
		} else {
			currentRefreshType = 'normal';
		}
		
		fetch_object('img_refresh').style.visibility = 'visible';
    	refreshAjax = new vB_AJAX_Handler(true);
    	refreshAjax.onreadystatechange(attente_refresh);		
    	refreshAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=ajax_refresh_chat&cb_status=open&chatbox_mode=' + chatbox_mode + '&canal=' + canal_actif + '&loading=' + loading + '&cb_location=' + cb_location);
		loading = 0;
	}
	return false;
};

function attente_refresh() {
    if(refreshAjax.handler.readyState == 4 && refreshAjax.handler.status == 200 && refreshAjax.handler.responseText) {
		fetch_object('img_refresh').style.visibility = 'hidden';
		if (refreshAjax.handler.responseText == "refresh_page") {
			window.location.reload();
		} else if (refreshAjax.handler.responseText == "idle") {
			fetch_object('chats').innerHTML = phrase_idle;
			isinactive = 1;
			fetch_object('chats').scrollTop = 0;
		} else {			
		   fetch_object('chats').innerHTML = refreshAjax.handler.responseText;
		   /* First at bottom ? */
		   if (chats_order) {	
			   fetch_object('chats').scrollTop = fetch_object('chats').scrollHeight;
		   }
		   
		   refreshTimeout = setTimeout("chatbox_refresh()", val_timeout);
		}
	}
}

function chatbox_get_derniers_msg() {
    getDerniersMsgAjax = new vB_AJAX_Handler(true);
    getDerniersMsgAjax.onreadystatechange(attente_derniers_msg);
    getDerniersMsgAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=ajax_refresh_chat&cb_status=fermee&chatbox_mode=' + chatbox_mode + '&canal=' + canal_actif);
}

function attente_derniers_msg() {
    if(getDerniersMsgAjax.handler.readyState == 4 && getDerniersMsgAjax.handler.status == 200 && getDerniersMsgAjax.handler.responseText) {
	   fetch_object('chats_derniers').innerHTML = getDerniersMsgAjax.handler.responseText;
    }
}

function envoyer_chat() {
    if (chatEnCours) {
        myAlert(error_busy);
    } else {
		loading = 1;
        chatEnCours = 1;
        chat_urlencoded = PHP.urlencode(fetch_object('chatinput').value);		
        vider_input_chat();
		envoiAjax = new vB_AJAX_Handler(true);
		envoiAjax.onreadystatechange(attente_fin_envoi_chat);
        envoiAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=ajax_chat&canal=' + canal_actif + '&chat=' + chat_urlencoded);
    }
    return false;
}


function attente_fin_envoi_chat() {
    if(envoiAjax.handler.readyState == 4 && envoiAjax.handler.status == 200 && envoiAjax.handler.responseText) {
		chatEnCours = 0;
		if (envoiAjax.handler.responseText == 'do_showban')
		   window.open(bburl + "/mgc_chatbox.php?" + SESSIONURL + "do=showban" , "showban", "toolbar=no,scrollbars=no,resizable=yes,left=0 top=0,width=600,height=500");
		else if (envoiAjax.handler.responseText == 'do_showignore')
		   window.open(bburl + "/mgc_chatbox.php?" + SESSIONURL + "do=showignore" , "showignore", "toolbar=no,scrollbars=no,resizable=yes,left=0 top=0,width=375,height=500");		   
        else if(envoiAjax.handler.responseText != 'ok')
           myAlert(envoiAjax.handler.responseText);
        <!-- Clear du timeout pour lancer le refresh -->
        clearTimeout(refreshTimeout);
        chatbox_refresh('forced');
    }
}

function inline_chat_edit(obj,chatid) {
	if (editEnCours == 0) {
		// Préparation du contexte
		clearTimeout(refreshTimeout);
		editEnCours = 1;
		// infos utiles
		currentEditObj = obj;
		currentEditId = chatid;
		// envoi requete
		recupDataEditAjax = new vB_AJAX_Handler(true);
		recupDataEditAjax.onreadystatechange(attente_recup_data_edit);
        recupDataEditAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=ajax_edit_getchat&chatid=' + currentEditId);
	} else {
		myAlert(edit_encours);
	}	
}

function attente_recup_data_edit() {
    if(recupDataEditAjax.handler.readyState == 4 && recupDataEditAjax.handler.status == 200 && recupDataEditAjax.handler.responseText) {
        // Résultat ok ?
		if (recupDataEditAjax.handler.responseText != '') {
			currentEditContent = recupDataEditAjax.handler.responseText;
			show_edit_chat();
		}
		else
			myAlert(edit_interdit);
    }	
}

//Fonction de modification inline de l'élément double-cliqué
function show_edit_chat()
{
	if(editEnCours) {
		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 sortir()
		{		
			lancement_save_edit();			
		};

		//Appui sur la touche Entrée
		fetch_object('chatedit').onkeypress = function keyDown(event)
		{
        	if (!event&&window.event)
        	{
            	event = window.event;
        	}
			if(getKeyCode(event) == 13)
        	{
				lancement_save_edit();		
			}
		};
	}
}

function lancement_save_edit() {
	if(editEnCours) {
		/* Valeur validé identique à valeur précédente ? */
		if(fetch_object('chatedit').value == currentEditContent) {
			editEnCours = 0;	
			chatbox_refresh('forced');			
		} else {
			chat_urlencoded = PHP.urlencode(fetch_object('chatedit').value);		
			saveEditAjax = new vB_AJAX_Handler(true);
			saveEditAjax.onreadystatechange(attente_save_edit);
        	saveEditAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=ajax_save_edit&chatid=' + currentEditId + '&chat=' + chat_urlencoded);		
		}
	}
}

function attente_save_edit() {
    if(saveEditAjax.handler.readyState == 4 && saveEditAjax.handler.status == 200 && saveEditAjax.handler.responseText) {
		editEnCours = 0;
		if(saveEditAjax.handler.responseText  == 'erreur') {
			myAlert(edit_failed);
			refreshTimeout = setTimeout('chatbox_refresh("auto")', val_timeout);
		} else {
			chatbox_refresh('forced');
		}
	}	
}

function ajout_smilie(smilietext) {
	insertAtCursor(fetch_object('chatinput'),smilietext);
	return false;
}

function insertAtCursor(myField, myValue) {
	//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 insertion(repdeb, repfin) {
  var input = fetch_object('chatinput');
  input.focus();
  /* pour l'Explorer Internet */
  if(typeof document.selection != 'undefined') {
    /* Insertion du code de formatage */
    var range = document.selection.createRange();
    var insText = range.text;
    range.text = repdeb + insText + repfin;
    /* Ajustement de la position du curseur */
    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();
  }
  /* pour navigateurs plus récents basés sur 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);
    /* Ajustement de la position du curseur */
    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 insertionEnhancedBBcode(selectItem,balise) {
	enhancedOption = selectItem.options[selectItem.selectedIndex].value;
	insertion('[' + balise + '=' + enhancedOption + ']','[/' + balise + ']');
	selectItem.selectedIndex = 0;
	return false;
}

function supprimerBBcode() {
	fetch_object('chatinput').value = stripcode(fetch_object('chatinput').value, false, false);
	return false;
}

function inserer_bbcode_url() {
	var url = prompt(phrase_enter_url,"http://");
	// Url entrée ?
	if (url != null && PHP.trim(url) != "") {
		insertAtCursor(fetch_object('chatinput'),"[url]" + url + "[/url]");
	}
}

function inserer_bbcode_img() {
	var imgurl = prompt(phrase_enter_imgurl,"http://");
	// Url entrée ?
	if (imgurl != null && PHP.trim(imgurl) != "") {
		insertAtCursor(fetch_object('chatinput'),"[img]" + imgurl + "[/img]");
	}
}

function aff_canal(canal) {
	loading = 1;
	switch(canal) {
		case 0:
			fetch_object('canal_gen_on').style.display = '';
			fetch_object('canal_gen_off').style.display = 'none';
			
			if (can_team && chatbox_mode) {				
				fetch_object('canal_team_on').style.display = 'none';
				if (!avTeamMsg) {
					fetch_object('canal_team_off').style.display = '';
					fetch_object('canal_team_new').style.display = 'none';
				} else {
					fetch_object('canal_team_off').style.display = 'none';
					fetch_object('canal_team_new').style.display = '';					
				}
			}
			
			if (can_wol) {
				fetch_object('canal_wol_on').style.display = 'none';
				fetch_object('canal_wol_off').style.display = '';				
			}
			
			if (can_pm) {
				fetch_object('canal_pm_on').style.display = 'none';
				fetch_object('canal_pm_off').style.display = '';				
			}
			
			canal_actif = 0;
			break;
		case 1:
			fetch_object('canal_gen_on').style.display = 'none';
			fetch_object('canal_gen_off').style.display = '';
				
			if (can_team && chatbox_mode) {
				fetch_object('canal_team_on').style.display = '';
				fetch_object('canal_team_new').style.display = 'none';
				fetch_object('canal_team_off').style.display = 'none';
			}
			
			if (can_wol) {
				fetch_object('canal_wol_on').style.display = 'none';
				fetch_object('canal_wol_off').style.display = '';				
			}
			
			if (can_pm) {
				fetch_object('canal_pm_on').style.display = 'none';
				fetch_object('canal_pm_off').style.display = '';				
			}			
			
			avTeamMsg = 0;
			canal_actif = 1;
			break;
		case 2 :
			fetch_object('canal_gen_on').style.display = 'none';
			fetch_object('canal_gen_off').style.display = '';
			
			if (can_team && chatbox_mode) {
				fetch_object('canal_team_on').style.display = 'none';
				if (!avTeamMsg) {
					fetch_object('canal_team_off').style.display = '';
					fetch_object('canal_team_new').style.display = 'none';
				} else {
					fetch_object('canal_team_off').style.display = 'none';
					fetch_object('canal_team_new').style.display = '';					
				}
			}
			
			if (can_wol) {
				fetch_object('canal_wol_on').style.display = 'none';
				fetch_object('canal_wol_off').style.display = '';			
			}
			
			if (can_pm) {
				fetch_object('canal_pm_on').style.display = '';
				fetch_object('canal_pm_off').style.display = 'none';				
			}		
			
			canal_actif = 2;
			break;
		case 3 :
			fetch_object('canal_gen_on').style.display = 'none';
			fetch_object('canal_gen_off').style.display = '';
			
			if (can_team && chatbox_mode) {
				fetch_object('canal_team_on').style.display = 'none';
				if (!avTeamMsg) {
					fetch_object('canal_team_off').style.display = '';
					fetch_object('canal_team_new').style.display = 'none';
				} else {
					fetch_object('canal_team_off').style.display = 'none';
					fetch_object('canal_team_new').style.display = '';					
				}
			}
			
			if (can_wol) {
				fetch_object('canal_wol_on').style.display = '';
				fetch_object('canal_wol_off').style.display = 'none';			
			}
			
			if (can_pm) {
				fetch_object('canal_pm_on').style.display = 'none';
				fetch_object('canal_pm_off').style.display = '';				
			}			
			
			canal_actif = 3;
			break;						
		default:
			break;
	}

	if (canal_actif == 3) {
        clearTimeout(refreshTimeout);		
		get_wol_list();
	} else {
		chatbox_refresh('forced');
	}
	
	return false;
}

function supprimer_chat(chatid) {
	if (!arSuppressionEnCours) {
		arSuppressionEnCours = 1;
    	arSupprimerChatAjax = new vB_AJAX_Handler(true);
    	arSupprimerChatAjax.onreadystatechange(attente_suppression);
    	arSupprimerChatAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=ajax_suppr_chat&chatid=' + chatid);
	} else {
		myAlert(suppr_encours);
	}	
}

function attente_suppression() {
    if(arSupprimerChatAjax.handler.readyState == 4 && arSupprimerChatAjax.handler.status == 200 && arSupprimerChatAjax.handler.responseText) {
		arSuppressionEnCours = 0;
		chatbox_refresh('forced');
	}
}

function check_team_msg() {
	/* Chat is not inactive ? */
	if (!isinactive) {
		/* Check only if the canal is not active, otherwise it's skipped */
		if (canal_actif != 1) {
			checkTeamAjax = new vB_AJAX_Handler(true);
			checkTeamAjax.onreadystatechange(attente_check_team_msg);
			checkTeamAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=check_team');
		} else {
			checkTeamTimeout = setTimeout('check_team_msg()', val_checkTeamTimeout * 60000);		
		}
	}
}

function attente_check_team_msg() {
    if(checkTeamAjax.handler.readyState == 4 && checkTeamAjax.handler.status == 200 && checkTeamAjax.handler.responseText) {
		if (checkTeamAjax.handler.responseText == "ok") {
			avTeamMsg = 1;
			fetch_object('canal_team_off').style.display = 'none';
			fetch_object('canal_team_new').style.display = '';
			checkTeamTimeout = setTimeout('check_team_msg()', val_checkTeamTimeout * 60000);
		} else {
			avTeamMsg = 0;			
		}

	}
}

function get_wol_list() {
	getWolAjax = new vB_AJAX_Handler(true);
	getWolAjax.onreadystatechange(attente_get_wol_list);
	getWolAjax.send(mgc_cb_jsloc + '/mgc_chatbox.php', 'do=getWol');
}

function attente_get_wol_list() {
    if(getWolAjax.handler.readyState == 4 && getWolAjax.handler.status == 200 && getWolAjax.handler.responseText) {
		fetch_object('chats').innerHTML = getWolAjax.handler.responseText;
	}
}

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 do_private_shout(username) {
	fetch_object('chatinput').value = '/mp "' + username + '" ';
	return false;
}