// Script bibliothèque de fonctions

function getElementsByClassName(className) { // Dommage qu'on ne puisse pas protoyper sur Element à cause d'IE
  var children = document.getElementsByTagName("*");
  var elements = new Array();
 
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var classNames = child.className.split(" ");
    for (var j in classNames) if (classNames[j] == className) {
      elements.push(child);
      break;
    }
  }
  return elements;
}

function in_array(a, v) { // Si on prototype on fait foirer tous les for-in du programme
  for (var i = 0; i < a.length; i++) if (a[i] == v) return true;
  return false;
}

function plugin_login_init() {
  if (document.getElementById("login_form")) document.getElementById("login").focus();
}

function plugin_ambiance_init() {
  document.getElementById("bgsound_switch").onclick = new Function("document.cookie = (document.getElementById('bgsound_switch').checked) ? 'bgsound=true' : 'bgsound=false';");
}

function plugin_harptos_init(htime) {
  var  now = new Date();
  var local = now.getTime();
  var diff = htime * 1000 - local;
  var clockloop = setInterval("plugin_harptos_update(" + diff + ")", 60000);
}

function plugin_harptos_update(diff) {  
  var now = new Date();
  var local = now.getTime();
  var htime = new Date(local + diff); 
  var years = [
    "Année de l'Entropie", 
    "Année des Dragons Renégats", 
    "Année des Tempêtes", 
    "Année de l'Ascension des Elfes", 
    "Année de la Lame Pliée", 
    "Année de la Hantise",
    "Année du Chaudron",
    "Année de la Forteresse Oubliée",
    "Année de la Main Enflammée"
  ];
  var months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  var bis = !(htime.getFullYear() % 4);
  
  var J = months[htime.getMonth()] + htime.getDate(); if (bis && (J > 214)) J--;
  var A = htime.getFullYear() -  630;
  var a = years[A - 1372];
  var H = htime.getHours(); 
  var MI = htime.getMinutes();  if (MI <= 9) MI = "0" + MI; 
  var m, M, F, f;
  
  if (J < 31) { m = "mois de Martel"; l = "coeur d'hiver"; M = 1; }
  else if (J == 31) { f = "Haut festival d'hiver"; F = "HfH"; }
  else if (J < 62) { m = "mois d'Alturiak"; l ="la griffe du froid"; M = 2; J -= 31; }
  else if (J < 92) { m = "mois de Ches"; l = "le couchant"; M = 3; J -= 61; }
  else if (J < 122) { m = "mois de Tarsakh"; l = "les tempêtes"; M = 4; J -= 91; }
  else if (J == 122) { f = "Herbeverte"; F = "Hrb"; }
  else if (J < 153) { m = "mois de Mirtul"; l = "la fonte"; M = 5; J -= 122; } 
  else if (J < 183) { m = "mois de Kythorn"; l = "le temps des fleurs"; M = 6; J -= 152; }
  else if (J < 213) { m = "mois de Flammerige"; l = "la marée estivale"; M = 7; J -= 182; }
  else if (J == 213) { f = "Haut festival d'été"; F = "HfÉ"; }
  else if (bis && (J == 214)) { f = "Rencontre des boucliers"; F = "RdB"; }
  else if (J < 244) { m = "mois d'Elesias"; l = "le haut soleil"; M = 8; J -= 213; } 
  else if (J < 274) { m = "mois d'Eleinte"; l = "la flétrissure"; M = 9; J -= 243; }
  else if (J < 275) { f = "Fête des moissons"; F = "FdM"; }
  else if (J < 305) { m = "mois de Marpenoth"; l = "la chute des feuilles"; M = 10; J -= 274; }
  else if (J < 335) { m = "mois d'Uktar"; l = "le pourrissement"; M = 11; J -= 304; } 
  else if (J == 335) { f = "Fête de la Lune"; F = "FdL"; }
  else { m = "mois de Noctur"; l = "le crépuscule"; M = 12; J -= 335;}
  
  D = Math.ceil(J / 10);
  d = (D == 1) ? '1ère décade' : D + 'ème décade';
  J = (J - 1) % 10 + 1; 
  j = (J == 1) ? '1er jour' : J + 'ème jour';
  
  document.getElementById("bigdate").firstChild.nodeValue = ((typeof(f) != "undefined") ? F : J + "/" + D + "/" + M) + "~" + A;
  document.getElementById("date").firstChild.nodeValue = (typeof(f) != "undefined") ? f : j + " de la " + d + " du " + m + " (" + l + ")";
  document.getElementById("year").firstChild.nodeValue = a;
  document.getElementById("clock").firstChild.nodeValue = "Il est actuellement " + H + "h" + MI;
  
  if (document.getElementById("bgsound_switch").checked) {
    var sound = document.getElementById("bgsound");
    if (MI == 0) plugin_harptos_ring(H);
    else if (MI == 30) plugin_harptos_ring(1);
    else if ((Math.random()*100 < 10) && ((H > 20) || (H < 5))) {sound.SetVariable("Request_args", "sounds/loup.mp3"); sound.SetVariable("Request_command", "PlayUrl");}
    else if ((Math.random()*100 > 90) && ((H > 20) || (H < 5))) {sound.SetVariable("Request_args", "sounds/chouette.mp3"); sound.SetVariable("Request_command", "PlayUrl");}
    else if ((H == 5) && (MI == 30)) {sound.SetVariable("Request_args", "sounds/cocorico.mp3"); sound.SetVariable("Request_command", "PlayUrl");}
  }
}

function plugin_harptos_ring(hhours) {
  var sound = document.getElementById("bgsound");
  sound.SetVariable("Request_args", "sounds/dong.mp3");
  sound.SetVariable("Request_command", "PlayUrl");
  if ((hhours - 1) % 12) setTimeout("plugin_harptos_ring(" + (hhours - 1) + ")", 2700);
}

function chat_init() {
  tracker_init(5000);
  if (document.getElementById("chat_form")) {
    aliases = [1];
    var alias = document.getElementById("alias");
    var message = document.getElementById("message");
    var presence = document.getElementById("presence");

    document.getElementById("chat_form").onsubmit = function () {
      if (message.value != "" && !message.disabled) {
        tracker_init(5000);
        trackercheck.postvars = "msg=" + encodeURIComponent(message.value);
        trackercheck.postvars += ((alias) ? "&alias=" + alias.options[alias.selectedIndex].value : "");
        trackercheck.getvars = "?nocache=" + Math.floor(Math.random() * 10000);
        trackercheck.request("sections/tracker.php", tracker_parse);
        message.value = "";
      }
      return false;
    }
    document.getElementById("message").onkeypress = function (e) {
      var targ;
      if (!e) var e = window.event
      if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement;
      if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which;

      if ((targ.value.length > 255) || (targ.value.length - targ.value.lastIndexOf(' ') > 30)) targ.value = targ.value.substr(0, Math.min(targ.value.length - 1, 255));
      if (code == 13) {document.getElementById("chat_form").onsubmit(); return false;}
    }
    document.getElementById("presence").onchange = function () {
      aliases[parseInt((alias) ? alias.options[alias.selectedIndex].value : 0)] = presence.checked;
      var a = ""; for(var n in aliases) if (aliases[n]) a += "," + n;
      tracker_init(5000);
      trackercheck.postvars += ((alias) ? "aliases=" + a : "");
      trackercheck.getvars = "?nocache=" + Math.floor(Math.random() * 10000);
      trackercheck.request("sections/tracker.php", tracker_parse);
      message.disabled = !presence.checked;
    }
    if (alias) document.getElementById("alias").onchange = function () {
      presence.checked = aliases[parseInt(alias.options[alias.selectedIndex].value)];
      presence.disabled = !parseInt(alias.options[alias.selectedIndex].value);
      message.disabled = !aliases[parseInt(alias.options[alias.selectedIndex].value)];
    }
  }
}

function chat_scroll() {
  var chatarea = document.getElementById("chatarea");
  if (chatarea.scrollTop < (chatarea.scrollHeight - chatarea.clientHeight)) chatarea.scrollTop++;
  else clearInterval(scrollloop);
}

function tracker_init(pace) {
  if (typeof trackercheck != 'undefined') clearInterval(trackerloop);
  else trackercheck = new ajaxobject();
  trackerloop = setInterval("trackercheck.request('sections/tracker.php', tracker_parse)", pace);
}

function tracker_parse() {
  if ((trackercheck.channel.readyState == 4) && (trackercheck.channel.status == 200)) {
    cdqueryadd(4);
    var data = eval('(' + trackercheck.channel.responseText + ')');

    if (document.getElementById("plugin_messenger")) {
      if (data.newmps) {
        var html = data.newmps + ((data.newmps > 1) ? " nouveaux messages" : " nouveau message");
        document.getElementById("mpnotifyarea").style.textDecoration = "blink";
      }
      else var html = "Pas de nouveau message";
      document.getElementById("mpnotifyarea").firstChild.nodeValue = html;
    }

    if (document.getElementById("plugin_online")) {
      document.getElementById("onlineusers").firstChild.nodeValue = (data.online.length) ? data.online.length + " personne" + ((data.online.length > 1) ? "s" : "")  : "Personne";
      var ul = document.getElementById("onlineuserslist"); while (ul.hasChildNodes()) ul.removeChild(ul.firstChild);
      for (var n in data.online) {
        var li = document.createElement("li");
        var a = document.createElement("a"); a.setAttribute("href", "index.php?section=2&uid=" + data.online[n].id);
        var name = document.createTextNode(data.online[n].name);
        if (data.online[n].id) li.appendChild(a).appendChild(name); else li.appendChild(name);
        document.getElementById("plugin_online").getElementsByTagName("ul")[0].appendChild(li);
      }
    }

    if (document.getElementById("chatarea")) {
      var userlist = document.getElementById("userlist");
      while (userlist.getElementsByTagName("li")[1]) userlist.removeChild(userlist.getElementsByTagName("li")[1]);
      for (var n in data.online) {
        var li = userlist.getElementsByTagName("li")[0].cloneNode(true);
        li.firstChild.setAttribute("href", "index.php?section=2&uid=" + data.online[n].id); li.firstChild.setAttribute("target", "_blank");
        li.firstChild.firstChild.setAttribute("src", "upload/avatars/"+ ((data.online[n].id) ? "avatar" + data.online[n].id : "default") + ".jpg"); li.firstChild.firstChild.setAttribute("alt", data.online[n].name + " (Code: " + data.online[n].id + ")"); li.firstChild.firstChild.setAttribute("title", data.online[n].name + " (Code: " + data.online[n].id + ")");
        if (document.getElementById("message") && (n > 0)) li.firstChild.firstChild.onclick = new Function("codeinsert('[mp=' + data.online[n].id + ']', '[/mp]');");
        if (data.online[n].location == 10 && data.online[n].delay < 15) userlist.appendChild(li);
      }
      var chatarea = document.getElementById("chatarea");
      var scroll1 = (chatarea.scrollTop == (chatarea.scrollHeight - chatarea.clientHeight));
      for (var n in data.chat) {
        var li = chatarea.getElementsByTagName("li")[0].cloneNode(true);
        li.firstChild.setAttribute("src", "upload/avatars/avatar" + data.chat[n].id + ".jpg"); li.firstChild.setAttribute("alt", data.chat[n].name + " (Code: " + data.chat[n].id + ")"); li.firstChild.setAttribute("title", data.chat[n].name + " (Code: " + data.chat[n].id + ")");
        var gid = ((data.chat[n].id == 0) ? 4 : 2); for (var m in data.online) if (data.online[m].id == data.chat[n].id) gid = data.online[m].gid;
        li.lastChild.className = "gid" + gid + " msg";
        if ((data.chat[n].message) && (data.chat[n].message != '')) {li.lastChild.innerHTML = data.chat[n].message; chatarea.appendChild(li);}
      }
      var scroll2 = (chatarea.scrollTop < (chatarea.scrollHeight - chatarea.clientHeight));
      if (scroll1 && scroll2) scrollloop = setInterval(chat_scroll, 10);
    }

    trackercheck.getvars = "?nocache=" + Math.floor(Math.random() * 10000);
  }
}

function wakeup() {
  if (inactivitytime > 0) {
    inactivitytime = 0;
    if (document.getElementById("plugin_messenger")) plugin_messenger_init();
    if (document.getElementById("plugin_online")) plugin_online_init();
  }
  inactivitytime = 0;
  if (typeof activityloop != 'undefined') clearInterval(activityloop);
  activityloop = setInterval("hibernate();", 300000);
}

function hibernate() {
  inactivitytime += 300000;
  if (typeof onlineloop != 'undefined') {clearInterval(onlineloop); plugin_online_init();}
  if (typeof mploop != 'undefined') {clearInterval(mploop); plugin_messenger_init();}  
}

function cdqueryadd(n) {
  document.getElementById('numdqueries').firstChild.nodeValue = parseInt(document.getElementById('numdqueries').firstChild.nodeValue) + n;
}

function queryvalue(s) {
  var query = window.location.search.substring(1)
  var pos1 = query.indexOf(s); if (pos1 < 0) return;
  var pos2 = query.indexOf("&", pos1); if (pos2 <0) pos2 = query.length;
  return query.substring(pos1 + s.length + 1, pos2);    
}
  
function ajaxobject() {
  function getxhrobject() {
    if (window.XMLHttpRequest) return new XMLHttpRequest();
    else if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }
  this.channel = getxhrobject();
  
  this.getvars = "";
  
  this.postvars = "";
  
  this.request = function(url, callback) {
    if (!(this.channel.readyState % 4)) {
      this.channel.open((this.postvars) ? "POST" : "GET", url + this.getvars, true);
      this.channel.onreadystatechange = callback; // IE impose d'avoir le onreadystatechange entre le open et le send
      this.channel.setRequestHeader("Content-Type",(this.postvars) ? "application/x-www-form-urlencoded" : "text/plain");
      this.channel.setRequestHeader("Cache-Control","no-cache");
      this.channel.send((this.postvars) ? this.postvars : null);
      this.getvars = "";
      this.postvars = "";
    }
  }
}

