﻿//////////////////////////////////////attributes - début
var ChatRoomName, ChatUserId, ChatTimestamp, ChatFlags, ChatControl, ChatMode, ChatModeratorLevel;
var ChatDivDebug, ChatDivMessages, ChatDivPrivates, ChatULMessages, ChatDivUsers, ChatULUsers, ChatDivStatus, ChatSendDivStatus, ChatTextBox;
var ChatDivModo, ChatDivPopup, ChatDivPopupContent, ChatSelectUser, ChatDivOptions, ChatDivOptionsContent;
var ChatIndexMessage, ChatElapsedTimeForMessages, ChatElapsedTimeForPrivates, ChatElapsedTimeForUsers, ChatMessagesRetries, ChatUsersRetries, ChatUsersListMaxLength;
var ChatIgnoreList;
var ChatPopupFunction, ChatImagesPath;
//////////////////////////////////////attributes - fin


//////////////////////////////////////init - début
function ChatInit(roomName, userId, moderatorLevel, timestamp, flags, control, mode, ignoreList, srcImgs)
{
    ChatDivMessages = document.getElementById("ChatDivMessages");
    ChatDivPrivates = document.getElementById("ChatDivPrivates");
    ChatULMessages = document.getElementById("ChatULMessages");
    ChatDivUsers = document.getElementById("ChatDivUsers");
    ChatULUsers = document.getElementById("ChatULUsers");
    ChatDivStatus = document.getElementById("ChatDivStatus");
    ChatSendDivStatus = document.getElementById("ChatDivSendStatus");
    ChatTextBox = document.getElementById("ChatTextBox");
    ChatDivModo = document.getElementById("ChatDivModo");
    ChatDivPopup = document.getElementById("ChatDivPopup");
    ChatDivOptions = document.getElementById("ChatDivOptions");
    ChatDivOptionsContent = document.getElementById("ChatDivOptionsFull");
    ChatSelectUser = document.getElementById("ChatSelectUser");
    ChatDivDebug = document.getElementById("ChatDivDebug");

    //configuration du chat
    ChatRoomName = roomName;
    ChatUserId = userId;
    ChatModeratorLevel = moderatorLevel;
    ChatTimestamp = timestamp;
    ChatFlags = flags;
    ChatControl = control;
    ChatMode = mode;
    ChatImagesPath = srcImgs;
    
    //constantes et variables globales
    ChatIndexMessage = -1;
    ChatElapsedTimeForMessages = 2000;
    ChatElapsedTimeForPrivates = 10000;
    ChatElapsedTimeForUsers = 20000;
    ChatMessagesRetries = 0;
    ChatUsersRetries = 0;
    ChatUsersListMaxLength = 12;
    
    if (ChatMode == -1) return; //mode erreur => stop initialisation

    //initialisations diverses    
    InitIgnoreList(ignoreList);
    InitSpinners();
    SetSpinnerOn('Init');
    
    if (ChatMode == 0) { ChatTagsInit(); ChatPopupFunction = "ChatDisplayPopupN"; ChatDivPopupContent = document.getElementById("ChatDivPopupFull"); }
    else if (ChatMode == 1) { ChatPopupFunction = "ChatDisplayPopupC";  ChatDivPopupContent = document.getElementById("ChatDivPopupSimple"); }
    else { ChatPopupFunction == ""; }
    
    if (ChatModeratorLevel > 0) window.setTimeout("InitModeModo();", 2000);

    if (ChatDivOptions != null) document.oncontextmenu = ShowOptions;
}

function ChatStart()
{
    if (ChatMode == -1) return;
    
    if (ChatULUsers != null) ChatTimerForUsers();
    ChatTimerForMessages();
    SetSpinnerOff('Init');
    if (ChatSendDivStatus) ChatSendDivStatus.innerHTML = "Connecté";
}

function catchEnter(e)
{
    if (e == null) e == window.event;
    code = -1;
    for (prop in e)
        if(prop == 'which') code = e.which;
    if (code == -1) code = e.keyCode;

    if (code == 13)
    {
        ChatSendMessage();
        return false;
    }
    else
        return true;
}
//////////////////////////////////////init - fin


//////////////////////////////////////timers - début
function ChatRefreshMessages()
{
    SetSpinnerOn('Msgs');
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
    {
        WebSiteChat.ChatWebService.GetLastMessages(ChatIndexMessage, ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, ChatTimerForMessagesOK, ChatTimerForMessagesERR, ChatTimerForMessagesTO);
    }
    else
    {
        ChatMessagesRetries++;
    }
}
function ChatTimerForMessages()
{
    if (ChatMessagesRetries >= 3) { ChatDivStatus.innerHTML = "Connexion impossible ! <a href=\"javascript:window.location.reload();\">cliquez-ici</a> pour actualiser le chat"; return; }
    ChatRefreshMessages();
    setTimeout("ChatTimerForMessages()", ChatElapsedTimeForMessages);
}
function ChatTimerForMessagesOK(result)
{
    if (ChatDivDebug != null && result != null && result.length > 0) { ChatDivDebug.innerHTML = result;}
    ChatMessagesRetries = 0;
    if (result != null && result.length > 0)
    {
        for(var i=0; i<result.length; i++) AddNewMessage(result[i]);
        DisplayMessages();
    }
    SetSpinnerOff('Msgs');
}
function ChatTimerForMessagesERR(result) {}
function ChatTimerForMessagesTO(result) {}

//function ChatTimerForPrivates()
//{
//    SetSpinnerOn('Msgs');
//    if (typeof(WebSiteChat.ChatWebService) != "undefined")
//    {
//        WebSiteChat.ChatWebService.GetPrivateMessages(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, ChatTimerForPrivatesOK);
//        setTimeout("ChatTimerForPrivates()", ChatElapsedTimeForPrivates);
//    }
//}
//function ChatTimerForPrivatesOK(result)
//{
//    if (result != null && result.length > 0) DisplayPrivates(result);
//    SetSpinnerOff('Msgs');
//}

function ChatTimerForUsers()
{
    if (ChatUsersRetries >= 3) { ChatDivStatus.innerHTML = "Connexion impossible ! <a href=\"javascript:window.location.reload();\">Cliquez-ici</a> pour actualiser la page."; return; }

    SetSpinnerOn('Users');
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
    {
        WebSiteChat.ChatWebService.GetUsersList(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, ChatTimerForUsersOK, ChatTimerForUsersERR, ChatTimerForUsersTO);
    }
    else
    {
        ChatUsersRetries++;
        setTimeout("ChatTimerForUsers()", ChatElapsedTimeForUsers);
    }

}
function ChatTimerForUsersOK(result)
{
    ChatUsersRetries = 0;
    if (result != null && result.length > 0)
    {
        ChatTabUsers = result;
        DisplayUsers();
    }
    else
    {
        ChatULUsers.innerHTML = "";
    }
    SetSpinnerOff('Users');
    setTimeout("ChatTimerForUsers()", ChatElapsedTimeForUsers);
}
function ChatTimerForUsersERR(result)
{
    setTimeout("ChatTimerForUsers()", ChatElapsedTimeForUsers);
}
function ChatTimerForUsersTO(result)
{
    setTimeout("ChatTimerForUsers()", ChatElapsedTimeForUsers);
}
//////////////////////////////////////timers - fin


//////////////////////////////////////Get Messages - début
//tabMessages[i][0] = index
//tabMessages[i][1] = pseudo
//tabMessages[i][2] = message
var tabMessages = new Array();
var indexMaxMessages = 39;
var indexLastMessage = 0;
//msg[0] = index
//msg[1] = identifiant
//msg[2] = pseudo
//msg[3] = type message
//msg[4] = css
//msg[5] = message
function AddNewMessage(message)
{
    var msg = message.split("|");
    if (msg[3] == "1" || msg[3] == "5")
    {
        AddMessageToFile(msg);
    }
    else
    {
        var nb = parseInt(msg[0]);
        if (ChatIndexMessage < nb || ChatIndexMessage > nb + indexMaxMessages)
        {
            ChatIndexMessage = nb;
            AddMessageToFile(msg);
        }
    }
}
function AddMessageToFile(msg)
{
    if (indexLastMessage > indexMaxMessages) indexLastMessage = 0;

    var temp = new Array(3);
    temp[0] = msg[0];
    temp[1] = msg[2];
    
    switch (msg[3])
    {
        case "0": //normal
            if (ChatIgnoreList == null || ChatIgnoreList[msg[1]] == null || ChatIgnoreList[msg[1]] == false)
            {
                temp[2] = "<li class=\"cssChatUserMessage\"><span class=\"cssChatSender\">" + msg[2] + "&nbsp;&gt;&nbsp;</span><span class=\"cssChatMessage " + msg[4] + "\">" + PrepareMessageSmileys(msg[5]) + "</span>\n";
                tabMessages[indexLastMessage] = temp;
                indexLastMessage++;
            }
            break;
        case "1": //private
            if (ChatIgnoreList == null || ChatIgnoreList[msg[1]] == null || ChatIgnoreList[msg[1]] == false)
            {
                temp[2] = "<li class=\"cssChatPrivateMessage\"><span class=\"cssChatSender\">" + msg[2] + "&nbsp;chuchote :&nbsp;</span><span class=\"cssChatMessage " + msg[4] + "\">" + PrepareMessageSmileys(msg[5]) + "</span>\n";
                tabMessages[indexLastMessage] = temp;
                indexLastMessage++;
            }
            break;
        case "2": //admin
            temp[2] = "<li class=\"cssChatServerMessage\"><span class=\"ChatMessage " + msg[4] + "\">" + msg[5] + "</span>\n";
            tabMessages[indexLastMessage] = temp;
            indexLastMessage++;
            break;
        case "3": //modo
            temp[2] = "<li class=\"cssChatUserMessage\"><span class=\"cssChatSender\">" + msg[2] + "&nbsp;&gt;&nbsp;</span><span class=\"cssChatMessage " + msg[4] + "\">" + PrepareMessageSmileys(msg[5]) + "</span>\n";
            tabMessages[indexLastMessage] = temp;
            indexLastMessage++;
            break;
        case "4": //info
        case "5": //info private
            temp[2] = "<li class=\"cssChatInfoMessage\"><span class=\"ChatMessage " + msg[4] + "\">" + msg[5] + "</span>\n";
            tabMessages[indexLastMessage] = temp;
            indexLastMessage++;
            break;
        default: //erreur
            temp[2] = "<li class=\"cssChatServerMessage\">erreur</span>\n";
            tabMessages[indexLastMessage] = temp;
            indexLastMessage++;
    }
    
}
function DisplayMessages()
{
    var startIndex;
    var str = "";
    for (startIndex = indexLastMessage-1; startIndex>=0; startIndex--)
        str = tabMessages[startIndex][2] + str;
    for (startIndex = tabMessages.length-1; startIndex>=indexLastMessage; startIndex--)
        str = tabMessages[startIndex][2] + str;
    ChatULMessages.innerHTML = str; 
    ChatDivMessages.scrollTop = ChatULMessages.scrollHeight;    
}
var CharSmileysImages = new Array(  "happy","happy","sad","sad","slurp","veryHappy","sick","confused","eyes","cry");
var CharSmileysReplaces = new Array(":)",   ":-)",  ":(", ":-(",":p",   ":d",       "+o",  ":s",      "8-)", ":'(");
function PrepareMessageSmileys(msg)
{
    for(var i=0; i<CharSmileysReplaces.length; i++)
    {
        msg = msg.replace(CharSmileysReplaces[i], '<img src="' + ChatImagesPath + CharSmileysImages[i] + '.png" border="0"/>');
    }
    return msg;
}
//////////////////////////////////////Get Messages - fin


//////////////////////////////////////Send Messages - début
var ChatCanSend = true;
function ChatSendMessage()
{
    var msg = ChatTextBox.value;
    if (msg != "" && ChatCanSend)
    {
        SetSpinnerOn('Send');
        ChatCanSend = false;
        ChatSendDivStatus.innerHTML = "Patientez...";

        if (msg.indexOf("|") != -1)
        {
            ChatSendDivStatus.innerHTML = "refus&eacute;";
            setTimeout("ChatSendDivStatus.innerHTML = '&nbsp;';", 1500);
        }
        else {
            if (typeof(ChatSelectUser) != "undefined" && ChatSelectUser != null && ChatSelectUser.selectedIndex > 0)
            {
                var dest = ChatSelectUser.options[ChatSelectUser.selectedIndex].value;
                if (dest == "") { ChatSendDivStatus.innerHTML = "Pas de destinataire !"; SetSpinnerOff('Send'); ChatCanSend = true; return; }
                WebSiteChat.ChatWebService.SendMessagePrivate(dest, msg, ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, OnChatSendMessageComplete, OnChatSendMessageError, OnChatSendMessageTimeOut);
            }
            else
            {
                if (ChatCkbxModo != null && ChatCkbxModo.checked)
                    WebSiteChat.ChatWebService.SendMessageModeration(msg, ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, OnChatSendMessageComplete, OnChatSendMessageError, OnChatSendMessageTimeOut);
                else
                    WebSiteChat.ChatWebService.SendMessageFormatted(msg, ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, OnChatSendMessageComplete, OnChatSendMessageError, OnChatSendMessageTimeOut);
            }
            ChatTextBox.value = "";
        }
    }
    ChatTextBox.focus();
}
function OnChatSendMessageComplete(result)
{
    var r = "accept&eacute;";
    if (result == false) r = "<a href=\"MoutonGlouton.aspx\" target=\"_blank\">B&ecirc;&ecirc;&ecirc;&ecirc; ! Miam !</a>";
    ChatSendDivStatus.innerHTML = r;
    setTimeout("ChatCanSend = true; ChatSendDivStatus.innerHTML = 'Pr&ecirc;t'; SetSpinnerOff('Send');", 2000);
    ChatRefreshMessages();
}
function OnChatSendMessageError(result)
{
    ChatSendDivStatus.innerHTML = "Message pas envoy&eacute;";
    setTimeout("ChatCanSend = true; ChatSendDivStatus.innerHTML = 'Pr&ecirc;t'; SetSpinnerOff('Send');", 2000);
}
function OnChatSendMessageTimeOut(result)
{
    ChatSendDivStatus.innerHTML = "Message pas envoy&eacute;";
    setTimeout("ChatCanSend = true; ChatSendDivStatus.innerHTML = 'Pr&ecirc;t'; SetSpinnerOff('Send');", 2000);
}
//////////////////////////////////////Send Messages - fin


//////////////////////////////////////Send Alerts - début
var ChatCanAlert = true;
function ChatSendAlert()
{
    if (!ChatCanAlert) return;
    if (typeof(WebSiteChat) == 'undefined') return;
    if (!confirm('Attention, tout abus sera puni !\nSouhaitez-vous vraiment alerter un modérateur ?')) return;
    WebSiteChat.ChatWebService.SendAlert(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, OnSendAlertOK, OnSendAlertError, OnSendAlertTimeout);
    ChatCanAlert = false;
    setTimeout("ChatCanAlert = true;", 1000*60*5); // 5 minutes
}
function OnSendAlertOK(result)
{
    if (result)
        ChatSendDivStatus.innerHTML = "alerte envoy&eacute;e";
    else
        ChatSendDivStatus.innerHTML = "alerte refus&eacute;e";
}
function OnSendAlertError(result) {}
function OnSendAlertTimeout() {}
//////////////////////////////////////Send Alerts - fin


//////////////////////////////////////Users List - début
//ChatTabUsers[i][0] = identifiant
//ChatTabUsers[i][1] = displayName
//ChatTabUsers[i][2] = type (anonyme / user / modo)
//ChatTabUsers[i][3] = classement
var ChatTabUsers;
function DisplayUsers()
{
    var userList = new Array();
    var anoList = new Array();
    
    for (var i=0; i<ChatTabUsers.length; i++)
    {
        var u = ChatTabUsers[i].split("|");
        if (u[2]=='A') anoList[anoList.length] = u;
        else userList[userList.length] = u;
    }
    
    userList = QuickSort(userList, 0, userList.length - 1);
    anoList = QuickSort(anoList, 0, anoList.length - 1);

	var strRet = "";
	for(var i = 0; i < userList.length; i++) strRet += AddNewUser(userList[i]);
	for(var i = 0; i < anoList.length; i++) strRet += AddNewUser(anoList[i]);
	ChatULUsers.innerHTML = strRet;

    if (ChatSelectUser != null)
    {
        var oldindex = ChatSelectUser.selectedIndex;
        var oldValue = "";
        if (oldindex >= 0) oldValue = ChatSelectUser.options[oldindex].value;
        var newindex = 0;
        
        ChatSelectUser.options.length = 0;
        
        var i=0;
        ChatSelectUser.options[i] = new Option("à tout le monde", "-1");
	    ChatSelectUser.options[i].style.color = "red";
	    ChatSelectUser.options[i].style.fontWeight = "bold";
        if (oldValue == "-1") newindex = i;
        i++;
        
	    for(var j = 0; j < userList.length; j++)
	    {
	        if (userList[j][0] != ChatUserId)
	        {
	            ChatSelectUser.options[i] = new Option("à " + userList[j][1], userList[j][0]);
	            ChatSelectUser.options[i].style.color = "Blue";
	            ChatSelectUser.options[i].style.fontWeight = "bold";
	            if (userList[j][0] == oldValue) newindex = i;
	            i++;
	        }
	    }
	    
        ChatSelectUser.options[i] = new Option("Choisir un destinataire", "");
	    if (newindex == 0 && oldindex > 0) newindex = i;
	    ChatSelectUser.selectedIndex = newindex;
	    if (newindex==0)
	    {
	        ChatSelectUser.style.color = "Red";
	        ChatSelectUser.style.fontWeight = "bold";
	    }
	    else
	    {
	        ChatSelectUser.style.color = "Blue";
	        ChatSelectUser.style.fontWeight = "bold";
	    }
	    ChatSelectUser.style.display = '';
	}
}
function ChatSelectUserChanged(sender)
{
    if (sender.selectedIndex == 0)
    {
        sender.style.color = "Red";
        sender.style.fontWeight = "bold";
    }
    else
    {
        sender.style.color = "Blue";
        sender.style.fontWeight = "bold";
    }
}
function AddNewUser(user)
{
    //icones
    var icnIgn = "";
    if (ChatIgnoreList != null && ChatIgnoreList[user[0]] != null &&  ChatIgnoreList[user[0]] == true)
        icnIgn = "<img src=\"" + ChatImagesPath + "ign.gif\" border=\"0\" title=\"ignoré\" />&nbsp;";
    var css = "cssChatUser" + user[2];
    //classement
    if (user[3] != null)
    {
        if (user[3] < 750) css += " cssClassementBB";
        else if (user[3] < 950) css += " cssClassementBM";
        else if (user[3] < 1050) css += " cssClassementMM";
        else if (user[3] < 1250) css += " cssClassementMH";
        else css += " cssClassementHH";
    }
    
    //build li for user
    var pseu = user[1]; if (pseu.length>ChatUsersListMaxLength) pseu = user[1].substr(0, ChatUsersListMaxLength-1) + "...";
    if (ChatPopupFunction == "")
        return "<li>" + icnIgn + pseu + "</li>"; // (" + user[2] + "," + user[3] + ")
    else
        return "<li>" + icnIgn + "<a href=\"javascript:" + ChatPopupFunction + "('" + user[0] + "', '" + user[1] + "');\" title=\"" + user[1] + "\" class=\"" + css + "\">" + pseu + "</a></li>"; // (" + user[2] + "," + user[3] + ")
}
//////////////////////////////////////Users List - fin


//////////////////////////////////////Popup Compact - début
function ChatDisplayPopupC(idUser, userName)
{
    var str = "";
    str += "<div style=\"float:left;margin:5px;font-weight:bold;\">" + userName + "</div>";
    str += "<div style=\"float:right;margin:5px;font-weight:bold;\">";
    str += "<a href=\"javascript:CloseTag();\" class=\"ChatLink\">Fermer</a>";
    str += "</div>";
    str += "<div style=\"clear:both;text-align:left;margin:5px;font-weight:bold;\">"
    var ign = "Ignorer";
    if (ChatIgnoreList[idUser] == 1) ign = "Ne pas ignorer";
    if (ChatModeratorLevel >= 0) str += "<a class=\"ChatIgnore ChatLink\" href=\"\" onclick=\"ChatIgnore(this, '" + idUser + "'); return false;\">" + ign + "</a><br/>";
    if (ChatModeratorLevel >= 1 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(15, '" + idUser + "'); return false;\">Bannir 15 mins</a><br/>";
    if (ChatModeratorLevel >= 2 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(1440, '" + idUser + "'); return false;\">Bannir 1 jour</a><br/>";
    if (ChatModeratorLevel >= 3 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(-1, '" + idUser + "'); return false;\">Bannir &agrave; vie</a><br/>";
    if (ChatModeratorLevel >= 4 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(-10, '" + idUser + "'); return false;\">Bannir l'IP</a><br/>";
    str += "</div>";

    document.getElementById("ChatDivPopupSimpleContent").innerHTML = str;

    ChatDivPopup.className = "ModePopupOn";
    ChatDivPopupContent.style.display = "block";
    ChatDivPopup.style.display = "block";
}
//////////////////////////////////////Popup Compact - fin


//////////////////////////////////////Popup Normal - début
var ChatListTags = null;
function ChatTagsInit()
{
    SetSpinnerOn('Tags');
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
        WebSiteChat.ChatWebService.GetListTags(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, OnChatTagsInitOk, OnChatTagsInitError, OnChatTagsInitTimeout);
    else
        setTimeout("ChatTagsInit();", 1000);
}
function OnChatTagsInitOk(result)
{
    if (result == null) setTimeout("ChatTagsInit();", 1000);
    else SetSpinnerOff('Tags');
    ChatListTags = result;
}
function OnChatTagsInitError(result)
{
    alert("erreur OnChatTagsInitError : " + result);
}
function OnChatTagsInitTimeout()
{
    alert("erreur OnChatTagsInitTimeout");
}
function ChatDisplayPopupN(idUser, userName)
{
    SetSpinnerOn('Tags');
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
        WebSiteChat.ChatWebService.GetFicheUtilisateur(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, idUser, OnGetFicheOk, OnGetFicheError, OnGetFicheTimeout);
}
function OnGetFicheOk(result)
{
    if (result == null)
    {
        document.getElementById("ChatDivTagsFiche").innerHTML = "";
        ChatDivPopup.style.display = "none";
        ChatDivPopupContent.style.display = "none";
        return;
    }

    var str = "";
    str += "<div id=\"divTagIdTagged\" style=\"visibility:hidden;width:0px;height:0px;\">" + result.Identifiant + "</div><br/>";
    str += "<div style=\"float:left;width:105px;height:105px;margin:5px;\">"
    str += "<img src=\"" + result.Avatar + "\" border=\"2px solid black\"><br/>";
    str += "</div>";
    str += "<div style=\"float:left;width:auto;height:auto;margin:5px;font-weight:bold;\">"
    str += "" + result.DisplayName + "<br/><br/>";
    var ign = "Ignorer";
    if (ChatIgnoreList[result.Identifiant] == 1) ign = "Ne pas ignorer";
    if (ChatModeratorLevel >= 0) str += "<a class=\"ChatIgnore ChatLink\" href=\"\" onclick=\"ChatIgnore(this, '" + result.Identifiant + "'); return false;\">" + ign + "</a><br/>";
    if (ChatModeratorLevel >= 1 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(15, '" + result.Identifiant + "'); return false;\">Bannir 15 mins</a><br/>";
    if (ChatModeratorLevel >= 2 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(1440, '" + result.Identifiant + "'); return false;\">Bannir 1 jour</a><br/>";
    if (ChatModeratorLevel >= 3 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(-1, '" + result.Identifiant + "'); return false;\">Bannir &agrave; vie</a><br/>";
    if (ChatModeratorLevel >= 4 && ChatCkbxModo != null && ChatCkbxModo.checked) str += "<a class=\"ChatSanction ChatLink\" href=\"\" onclick=\"ChatBan(-10, '" + result.Identifiant + "'); return false;\">Bannir l'IP</a><br/>";
    str += "</div>";
    str += "<div style=\"float:right;width:50px;height:auto;margin:5px;font-weight:bold;\">"
    str += "<a href=\"javascript:CloseTag();\" class=\"ChatLink\">Fermer</a>";
    str += "</div>";
    str += "<div style=\"clear:both;width:1px;\"></div>"
    document.getElementById("ChatDivTagsFiche").innerHTML = str;
    
    BuildListTags();

    //ListTagsAppliedByTagger[i][0] : "T" ou "V"
    //ListTagsAppliedByTagger[i][1] : IdTag ou IdTagValue
    //ListTagsAppliedByTagger[i][2] : TagName ou TagValue
    //ListTagsAppliedByTagger[i][3] : IdTag si "V"
    if (result.ListTagsAppliedByTagger != null)
    {
        for(var i=0; i<result.ListTagsAppliedByTagger.length; i++)
        {
            var idckbx = "ckbxTag_" + result.ListTagsAppliedByTagger[i][0] + "_" + result.ListTagsAppliedByTagger[i][1];
            if (result.ListTagsAppliedByTagger[i][0] == "V") idckbx += "_" + result.ListTagsAppliedByTagger[i][3];

            var ckbx = document.getElementById(idckbx);
            if (ckbx != null) ckbx.checked = true;
        }
    }

    ChatDivPopup.style.display = 'block';
    ChatDivPopupContent.style.display = 'block';
    SetSpinnerOff('Tags');
}
function OnGetFicheError(result)
{
    alert("erreur OnGetFicheError : " + result);
    SetSpinnerOff('Tags');
}
function OnGetFicheTimeout()
{
    alert("erreur OnGetFicheTimeout");
    SetSpinnerOff('Tags');
}
function BuildListTags()
{
    if (ChatListTags == null || ChatListTags.length == 0)
    {
        document.getElementById("ChatDivTagsList").innerHTML = "";
        return;
    }
    //ChatListTags[i][0] : "T" ou "V"
    //ChatListTags[i][1] : IdTag ou IdTagValue
    //ChatListTags[i][2] : TagName ou TagValue
    //ChatListTags[i][3] : IdTag si "V"
    var str = "Quels adjectifs qualifient le mieux ce joueur ?<br/><table border=\"0\"><tr>";
    for(var i=0; i<ChatListTags.length; i++)
    {
        var idckbx = "ckbxTag_" + ChatListTags[i][0] + "_" + ChatListTags[i][1];
        if (ChatListTags[i][0] == "V") idckbx += "_" + ChatListTags[i][3];
        if (i==ChatListTags.length-1 && i%2==0)
        {
            str += "<td colspan=\"2\"><input type=\"checkbox\" onclick=\"javascript:TagChanged(this);\" id=\"" + idckbx + "\">";
        }
        else
        {
            str += "<td><input type=\"checkbox\" onclick=\"javascript:TagChanged(this);\" id=\"" + idckbx + "\">";
        }
        str += ChatListTags[i][2];
        str += "</td>";
        if ((i+1)%2==0) str += "</tr><tr>";
    }
    str += "</tr></table>";
    document.getElementById("ChatDivTagsList").innerHTML = str;
    document.getElementById("ChatDivTagsList").style.margin = "5px";
}

function CloseTag()
{
    ChatDivPopup.style.display = "none";
    ChatDivPopupContent.style.display = "none";
}
function TagChanged(sender)
{
    SetSpinnerOn('Tags');
    if (typeof(WebSiteChat.ChatWebService) == "undefined")
    {
        alert("Erreur de communication avec le serveur");
        sender.checked = !sender.checked;
        return false;
    }

    var divIdTagged = document.getElementById("divTagIdTagged");
    if (divIdTagged == null)
    {
        sender.checked = !sender.checked;
        return false;
    }

    var idTagged = divIdTagged.innerHTML;
    var tab = sender.id.split(new RegExp("_", "g"));
    var tagtype = tab[1];
    var tagid = tab[2];
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
    {
        if (sender.checked)
        {
            WebSiteChat.ChatWebService.AddTag(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, idTagged, tagtype, tagid, OnAddTagOk, OnAddTagError, OnAddTagTimeout);
        }
        else
        {
            WebSiteChat.ChatWebService.RemoveTag(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, idTagged, tagtype, tagid, OnRemoveTagOk, OnAddTagError, OnAddTagTimeout);
        }
    }
    return true;
}

function OnAddTagOk(result)
{
    if (ChatListTags == null || ChatListTags.length == 0) return;
    if (result == null) return;
    for(var i=0; i<ChatListTags.length; i++)
    {
        if (ChatListTags[i][0] == "V" && ChatListTags[i][3] == result.IdTag && ChatListTags[i][1] != result.IdTagValue)
        {
            var idckbx = "ckbxTag_" + ChatListTags[i][0] + "_" + ChatListTags[i][1] + "_" + ChatListTags[i][3];
            var ckbx = document.getElementById(idckbx);
            if (ckbx != null) ckbx.checked = false;
        }
    }
    SetSpinnerOff('Tags');
}
function OnAddTagError(result) {SetSpinnerOff('Tags');}
function OnAddTagTimeout() {SetSpinnerOff('Tags');}
function OnRemoveTagOk(result) {SetSpinnerOff('Tags');}
//////////////////////////////////////Popup Normal - fin


//////////////////////////////////////IgnoreList - début
function InitIgnoreList(ignoreList)
{
    ChatIgnoreList = new Array();
    
    if (ignoreList==null || ignoreList == "") return;
    
    var tmp = ignoreList.split("|");
    for(var i=0; i<tmp.length; i++)
    {
        if (tmp[i] != "") ChatIgnoreList[tmp[i]] = true;
    }
}
function ChatIgnore(object, userKey)
{
    if (ChatIgnoreList[userKey] == null || ChatIgnoreList[userKey] == false) ChatIgnoreList[userKey] = true;
    else ChatIgnoreList[userKey] = false;
    
    var ign = "Ignorer";
    if (ChatIgnoreList[userKey] == true) ign = "Ne pas ignorer";
    object.innerHTML = ign;
    
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
    {
        WebSiteChat.ChatWebService.SetIgnore(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, userKey, ChatIgnoreList[userKey], OnSetIgnoreOk, OnSetIgnoreError, OnSetIgnoreTimeout);
    }
}
function OnSetIgnoreOk(result) { DisplayUsers(); }
function OnSetIgnoreError(result) {}
function OnSetIgnoreTimeout() {}
//////////////////////////////////////IgnoreList - fin


//////////////////////////////////////Moderation - début
var ChatCkbxModo;
function InitModeModo()
{
    if (!ChatDivModo) return;
    var str = "Modo:<input type=\"checkbox\" id=\"ChatCheckBoxModo\" onclick=\"javascript:ChangeModeModo(this);\" />";
    ChatDivModo.innerHTML = str;
    ChatCkbxModo = document.getElementById("ChatCheckBoxModo");
    GetModeModo();
}
function GetModeModo()
{
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
    {
        WebSiteChat.ChatWebService.GetModeModo(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, OnGetModeModoOk, OnModerationErr, OnModerationTimeout);
    }
}
function OnGetModeModoOk(result)
{
    if (result==null || result == false) ChatCkbxModo.checked = false;
    else ChatCkbxModo.checked = true;
}
function OnModerationErr(result) { alert(result); }
function OnModerationTimeout() {}

function ChangeModeModo(ckbx)
{
    if (typeof(WebSiteChat.ChatWebService) != "undefined")
    {
        WebSiteChat.ChatWebService.SetModeModo(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, ckbx.checked, OnSetModeModoOk, OnModerationErr, OnModerationTimeout);
    }
}
function OnSetModeModoOk(result) { if (result==null || result==false) { ChatCkbxModo.checked = !ChatCkbxModo.checked; alert("Votre demande n'a pas été prise en compte"); } }

function ChatBan(duree, user)
{
    if (typeof(WebSiteChat.ChatWebService) != "undefined" && confirm("Etes-vous sûr de vouloir sanctionner ?"))
    {
        WebSiteChat.ChatWebService.AddSanction(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, duree, user, OnAddSanctionOk, OnModerationErr, OnModerationTimeout);
    }
}
function OnAddSanctionOk(result)
{
    if (result==null || result==false) alert("Erreur ! La sanction n'a pas été appliquée.");
    else alert("Sanction appliquée !");
}
//////////////////////////////////////Moderation - fin

//////////////////////////////////////Options - début
function ShowOptions() { ChatDivOptions.style.display = 'block'; ChatDivOptionsContent.style.display = 'block'; return false; }
function HideOptions() { ChatDivOptions.style.display = 'none'; ChatDivOptionsContent.style.display = 'none'; }
function ChangeColor(rblID)
{
    var rbl = document.getElementsByName(rblID);
    var color = "";
    for(var i=0; i<rbl.length; i++) if (rbl[i].checked) color = rbl[i].value;
    WebSiteChat.ChatWebService.ChangeColor(ChatUserId, ChatRoomName, ChatTimestamp, ChatFlags, ChatControl, color, OnChangeColorOk, OnChangeColorErr, OnChangeColorTimeout);
}
function OnChangeColorOk(result) { if (result==false) alert('Votre demande n\'est pas acceptée');}
function OnChangeColorErr(result) {alert('Une erreur s\'est produite');}
function OnChangeColorTimeout() {alert('timeout');}
//////////////////////////////////////Options - fin

//////////////////////////////////////Divers - début
function InitSpinners()
{
    var str = "";
    str += "<img id=\"spinInit\" src=\"images/spinner.gif\" border=\"0\"/ style=\"visibility:hidden;\">&nbsp;";
    str += "<img id=\"spinMsgs\" src=\"images/spinner.gif\" border=\"0\"/ style=\"visibility:hidden;\">&nbsp;";
    str += "<img id=\"spinSend\" src=\"images/spinner.gif\" border=\"0\"/ style=\"visibility:hidden;\">&nbsp;";
    str += "<img id=\"spinUsers\" src=\"images/spinner.gif\" border=\"0\"/ style=\"visibility:hidden;\">&nbsp;";
    str += "<img id=\"spinTags\" src=\"images/spinner.gif\" border=\"0\"/ style=\"visibility:hidden;\">&nbsp;";
    ChatDivStatus.innerHTML = str;
}
function SetSpinnerOn(index) {document.getElementById("spin"+index).style.visibility="";}
function SetSpinnerOff(index) {document.getElementById("spin"+index).style.visibility="hidden";}

function CompareUsers(user1, user2)
{
    return (user1[1] > user2[1]);
}
function CompareUsers2(user1, user2)
{
    return (user1[1] <= user2[1]);
}
function QuickSort(arr, low, high)
{
	if(low < high)
	{
		var i = low;
		var j = high;
		var pivot = arr[i];
		while(i<j) 
		{
			while(i<j && CompareUsers(arr[j],pivot)) j--;
			if(i<j) arr[i++] = arr[j];
			while(i<j && CompareUsers2(arr[i],pivot)) i++;
			if(i<j) arr[j--] = arr[i];
		}
		arr[i] = pivot;
		var pivotpos = i;
		QuickSort(arr, low, pivotpos-1);
		QuickSort(arr, pivotpos+1, high);
	} 
	else
	   return arr;
	return arr;
}
//////////////////////////////////////Divers - fin
