scriptid = 0;
ajasonfn = [ ];
userid   = null;
dbpath   = "Old_Site/public_html/";

//   filter:

function loadimg(name,url,w,h)
{
   if (navigator.appName.match(/icrosoft/) && (!navigator.appVersion.match(/MSIE 7/))) {
      loadimg = function (name,url,w,h) {
         var d, c;
         d = getelem(name);

         if (!d) {
            d     = document.createElement('IMG');
            d.src = dbpath + "img/blank.gif";
            d.id  = name;
            d.style.width  = w;
            d.style.height = h;
            d.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader("
                           + "src='" + url + "', sizingMethod='scale')";
            maindivs['imgload'].appendChild(d);
         }
         c    = d.cloneNode(false);
         c.id = '';
         return(c);
      };
   } else {
      loadimg = function (name,url) {
         var d, c;
         d = getelem(name);

         if (!d) {
            d     = document.createElement('IMG');
            d.src = url;
            d.id  = name;
            maindivs['imgload'].appendChild(d);
         }
         c    = d.cloneNode(false);
         c.id = '';
         return(c);
      };
   }
   return(loadimg(name,url,w,h));
}

function delete_elem(oid)
{
   var i, d, dl;
   d  = getelem(oid);
   dl = d.delete_level;
   for(i=0;i<dl;++i) {
      d = d.parentNode;
   }
   d.parentNode.removeChild(d);
}

function addEvent(obj, evt, func) {
  if (obj.attachEvent) {
    return obj.attachEvent(("on"+evt), function () { func(obj,window.event); });
  } else if (obj.addEventListener) {
    obj.addEventListener(evt, function (e) { func(obj,e); }, true);
    return true;
  }
  return false;
}

function ajason(url,func)
{
   this.xmlhttp = false;
   this.ie      = false;
   this.fn      = func;
   this.url     = url;
   var obj      = this;

   if (url.match(/http.*/)) {
      this.sslurl = url.replace("http:","https:");
   } else {
      this.sslurl = location.href.replace(/\/([^\/]*$)/,"").replace("http:","https:") + "/" + url
   }

    // returns string of only valid characters
    this._validChars = function (str) {

      // default legal character set is alphanumeric + symbols (note first char is a space)
      var validChars = " abcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+=[]{}\\|;:'\",.<>/?";

      //remove leading and trailing whitespace
      str = str.replace(/^\s+/g, '').replace(/\s+$/g, '');

      //convert carriage returns and newlines entered into textarea to spaces
      str = str.replace(/\r\n|\n/g, '%0a');

      var valid = "";
      for (var i=0; i < str.length; i++) {
        var c = str.charAt(i);
        var s = c.toLowerCase();
        if (validChars.indexOf(s) == -1) {
            valid += '%' + c.charCodeAt(0).toString(16);
//            alert(valid);
        } else {
           valid += c;
        }
      }

      // replace <, >, and &
      valid = valid.replace(/</g, "&lt;");
      valid = valid.replace(/>/g, "&gt;");
      valid = valid.replace(/&/g, "&amp;");

      return valid;
   }

   var recescape = function (o) {
      if (typeof(o)=="object") {
         var i;
         for(i in o) {
            o[i] = recescape(o[i]);
         }
         return(o);
      }
      if (typeof(o)=="string") {
         return(escape(escape(o)));
      }
      return(o);
   };

   var recunescape = function (o) {
      if (typeof(o)=="object") {
         var i;
         for(i in o) {
            o[i] = recunescape(o[i]);
         }
         return(o);
      }
      if (typeof(o)=="string") {
         return(unescape(o));
      }
      return(o);
   };

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
   try {
      this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      this.ie      = true;
   } catch (e) {
      try {
         this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         this.ie = true;
      } catch (E) {
         this.xmlhttp = false;
      }
   }
@end @*/
   if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
      try {
         this.xmlhttp = new XMLHttpRequest();
      } catch (e) {
         this.xmlhttp=false;
      }
   }
   if (!this.xmlhttp && window.createRequest) {
      try {
         this.xmlhttp = window.createRequest();
      } catch (e) {
         this.xmlhttp=false;
      }
   }

   this.send = function (data) {
      if (obj.xmlhttp) {
         obj.xmlhttp.open("POST", obj.url, true);
         obj.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         obj.xmlhttp.setRequestHeader("Accept","text/xml");
         obj.xmlhttp.onreadystatechange = function () {
            // only if req shows "complete"
            if (obj.xmlhttp.readyState == 4) {
               // only if "OK"
               if (obj.xmlhttp.status == 200) {
                  obj.fn(recunescape(obj.xmlhttp.responseText.parseJSON()));
               } else {
                  alert("Erro acessando o site:\n" + obj.xmlhttp.statusText);
               }
            }
         };
         obj.xmlhttp.send("data=" + _validChars(recescape(data).toJSONString()));
      }
   }

   this.syncsend = function (data) {
      if (obj.xmlhttp) {
         obj.xmlhttp.open("POST", obj.url, false);
         obj.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         obj.xmlhttp.setRequestHeader("Accept","text/xml");
         obj.xmlhttp.onreadystatechange = function () {
            // only if req shows "complete"
            if (obj.xmlhttp.readyState == 4) {
               // only if "OK"
               if (obj.xmlhttp.status == 200) {
                  obj.fn(recunescape(obj.xmlhttp.responseText.parseJSON()));
               } else {
                  alert("Erro acessando o site:\n" + obj.xmlhttp.statusText);
               }
            }
         };
         obj.xmlhttp.send("data=" + _validChars(recescape(data).toJSONString()));
      }
   }

   this.sslsend = function (data) {
      var sc       = document.createElement("SCRIPT");
      data["myid"] = scriptid++;
      sc.src       = obj.sslurl + "?data=" + _validChars(recescape(data).toJSONString())
      sc.defer     = true;
      sc.type      = "text/javascript";
      ajasonfn[data["myid"]] = function (d) {
         obj.fn(recunescape(d));
         document.getElementsByTagName("HEAD")[0].removeChild(sc);
         ajasonfn[data["myid"]] = null;
      };
      document.getElementsByTagName("HEAD")[0].appendChild(sc);
   }
}

function ajason2(url,func)
{
   this.xmlhttp = false;
   this.ie      = false;
   this.fn      = func;
   this.url     = url;
   var obj      = this;

   if (url.match(/http.*/)) {
      this.sslurl = url.replace("http:","https:");
   } else {
      this.sslurl = location.href.replace(/\/([^\/]*$)/,"").replace("http:","https:") + "/" + url
   }

    // returns string of only valid characters
    this._validChars = function (str) {

      // default legal character set is alphanumeric + symbols (note first char is a space)
      var validChars = " abcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+=[]{}\\|;:'\",.<>/?";

      //remove leading and trailing whitespace
      str = str.replace(/^\s+/g, '').replace(/\s+$/g, '');

      //convert carriage returns and newlines entered into textarea to spaces
      str = str.replace(/\r\n|\n/g, '%0a');

      var valid = "";
      for (var i=0; i < str.length; i++) {
        var c = str.charAt(i);
        var s = c.toLowerCase();
        if (validChars.indexOf(s) == -1) {
            valid += '%' + c.charCodeAt(0).toString(16);
//            alert(valid);
        } else {
           valid += c;
        }
      }

      // replace <, >, and &
      valid = valid.replace(/</g, "&lt;");
      valid = valid.replace(/>/g, "&gt;");
      valid = valid.replace(/&/g, "&amp;");

      return valid;
   }


/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
   try {
      this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      this.ie      = true;
   } catch (e) {
      try {
         this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         this.ie = true;
      } catch (E) {
         this.xmlhttp = false;
      }
   }
@end @*/
   if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
      try {
         this.xmlhttp = new XMLHttpRequest();
      } catch (e) {
         this.xmlhttp=false;
      }
   }
   if (!this.xmlhttp && window.createRequest) {
      try {
         this.xmlhttp = window.createRequest();
      } catch (e) {
         this.xmlhttp=false;
      }
   }

   this.send = function (data) {
      if (obj.xmlhttp) {
         obj.xmlhttp.open("POST", obj.url, true);
         obj.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         obj.xmlhttp.setRequestHeader("Accept","text/xml");
         obj.xmlhttp.onreadystatechange = function () {
            // only if req shows "complete"
            if (obj.xmlhttp.readyState == 4) {
               // only if "OK"
               if (obj.xmlhttp.status == 200) {
//                  alert(obj.xmlhttp.responseText);
                  obj.fn(obj.xmlhttp.responseText.parseJSON());
               } else {
                  alert("Erro acessando o site:\n" + obj.xmlhttp.statusText);
               }
            }
         };
         obj.xmlhttp.send("data=" + _validChars(data.toJSONString()));
      }
   }

   this.syncsend = function (data) {
      if (obj.xmlhttp) {
         obj.xmlhttp.open("POST", obj.url, false);
         obj.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         obj.xmlhttp.setRequestHeader("Accept","text/xml");
         obj.xmlhttp.onreadystatechange = function () {
            // only if req shows "complete"
            if (obj.xmlhttp.readyState == 4) {
               // only if "OK"
               if (obj.xmlhttp.status == 200) {
                  obj.fn(obj.xmlhttp.responseText.parseJSON());
               } else {
                  alert("Erro acessando o site:\n" + obj.xmlhttp.statusText);
               }
            }
         };
         obj.xmlhttp.send("data=" + _validChars(data.toJSONString()));
      }
   }

   this.sslsend = function (data) {
      var sc       = document.createElement("SCRIPT");
      data["myid"] = scriptid++;
      sc.src       = obj.sslurl + "?data=" + _validChars(data.toJSONString())
      sc.defer     = true;
      sc.type      = "text/javascript";
      ajasonfn[data["myid"]] = function (d) {
         obj.fn(d);
         document.getElementsByTagName("HEAD")[0].removeChild(sc);
         ajasonfn[data["myid"]] = null;
      };
      document.getElementsByTagName("HEAD")[0].appendChild(sc);
   }
}



function showchildren(o)
{
   var i;
   o.style.display = 'inline';
   for(i=0;i<o.childNodes.length;++i) {
      if (o.childNodes[i].style) {
         showchildren(o.childNodes[i]);
      }
   }
}

function mkbut(ico,fn)
{
   if (navigator.userAgent.match(/MSIE [1-6]/)) {
      return(
         "<a onmouseover='hibut(this)' onmouseout='unhibut(this)' href='javascript:" + fn + "()'>"
            + "<img src='" + dbpath + "img/blank.gif' "
               + "style=\"width: 51px; height: 67px; "
               + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader("
                  + "src='" + dbpath + "img/" + ico + "0.png', sizingMethod='scale');\" "
               + "border=0 />"
            + "<img src='" + dbpath + "img/blank.gif' "
               + "style=\"display: none; width: 51px; height: 67px; "
               + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader("
                  + "src='" + dbpath + "img/" + ico + "9.png', sizingMethod='scale');\" "
               + "border=0 />"
         + "</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
      );
   } else {
      return(
         "<a onmouseover='hibut(this)' onmouseout='unhibut(this)' href='javascript:" + fn + "()'>"
            + "<img src='" + dbpath + "img/" + ico + "0.png' "
               + "style='width: 51px; height: 67px;' "
               + "border='0' />"
            + "<img src='" + dbpath + "img/" + ico + "9.png' "
               + "style='display: none; width: 51px; height: 67px;' "
               + "border=0 />"
         + "</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
      );
   }


}

function showtropnet()
{
   var i;
   alert('Sistema em manutencao');
   return;
   for (i in maindivs) {
      if (i!="toJSONString") {
         maindivs[i].style.display = 'none';
      }
   }
   getelem("tonusr").value = "";
   getelem("tonpw").value = "";
   maindivs['forumviewer'].style.display = 'block';
//   showchildren(maindivs['forumviewer']);
   getelem('menu').style.display = 'none';
   getelem('tonusr').focus();
//   oContent = getelem('content');
//   oContent.className = 'bigcontent';
//   oContentData = getelem('contentdata');
//   oContentData.className = 'bigcontentdata';
   //loadXMLDoc('db.php');
}

function forumlogin(o)
{
   var d = {
      "usr" : getelem("tonusr").value,
      "pw"  : getelem("tonpw").value
   };

   if ((!d.usr) || (!d.pw)) {
      alert("Digite a identificação de usuário e a senha!");
   }

   forumloginrpc.send(d);
}

function basename(s)
{
   return(s.replace(/\/([^\/]*$)/,""))
}

function tonstart(data)
{
   var admbar;
   getelem('divtonpw').style.display       = 'none';
   admbar = getelem('forumcontent')
   admbar.style.display   = 'block';
   admbar = admbar.firstChild;
   admbar.innerHTML = "<br class=tiny />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                    + mkbut("sair","tonsair");
   if (data["cod"]=="0") {
      admbar.innerHTML += mkbut("cadsala","toncadsala")
                       +  mkbut("incluir","toncadempico")
                       +  mkbut("user","toncadusr");
//   } else {
//      alert(typeof(data["cod"]) + ": " + data["cod"]);
   }
   userid = data["cod"];

   admbar.innerHTML += mkbut("sala","tonsala");
}

function tonsair()
{
   forumlogoutrpc.send({});
}


forumloginrpc = new ajason("forum/login.php",function (data) {
   if (data["err"]) {
      if (data["err"]=="loginfailed") {
         alert("erro: nome ou senha errados");
      } else if (data["err"]=="notlogged") {
         alert("erro: logar no sistema primeiro!");
      }
   } else {
      tonstart(data);
   }
});

forumlogoutrpc = new ajason("forum/tonend.php",function (data) {
   var oContent, oContentData;
   var toncanvas;
   if (data["ok"]) {
      var toncanvas = getelem("ton");
      while (toncanvas.lastChild) {
         toncanvas.removeChild(toncanvas.lastChild);
      }
      oContent = getelem('content');
      oContent.className                      = 'smallcontent';
      oContentData                            = getelem('contentdata');
      oContentData.className                  = 'smallcontentdata';
      getelem('menu').style.display           = 'block';
      getelem('divtonpw').style.display       = 'block';
      getelem('forumcontent').style.display   = 'none';
      instit();
   }
});

function clearcanvas()
{
   var toncanvas = getelem("ton");
   while (toncanvas.lastChild) {
      toncanvas.removeChild(toncanvas.lastChild);
   }
   return(toncanvas);
}


function toncadsala()
{
   var qtsala;

   var tonaddsala = new ajason("forum/tonaddsala.php",function (data) {
      getelem("salanew").id = "sala" + data["cod"];
   });

   var tonupdsala = new ajason("forum/tonupdsala.php",function (data) {
      // getelem("salanew").lastChild.lastChild.id = data["id"];
   });

   function dbsala(o,e)
   {
      var _id = o.parentNode.id;
      if (_id=="salanew") {
//         tonaddsala.send({"nome" : escape(escape(o.value)) });
         tonaddsala.send({"nome" : o.value });
      } else {
//         tonupdsala.send({"cod" : _id.substr(4), "nome" : escape(escape(o.value)) });
         tonupdsala.send({"cod" : _id.substr(4), "nome" : o.value });
      }
   }

   function addsala()
   {
      var delbut;
      if (!getelem("salanew")) {
         tonlistsala.appendChild(mkrowaddsala(qtsala++));
         delbut = tonlistsala.lastChild;
         addEvent(delbut.firstChild,"change",dbsala);
         addEvent(delbut.firstChild.nextSibling,"mouseover",imghi);
         addEvent(delbut.lastChild,"mouseout",imgunhi);
         addEvent(delbut.lastChild,"click",delsala);
      }
   }

   var tondelsala = new ajason("forum/tondelsala.php",function (data) {
      if (data["err"]) {
         alert("Erro. Sala nao deletada.");
      } else {
         delete_elem("sala"+data["cod"]);
      }
   });

   function delsala(o,e)
   {
      var did = o.parentNode.id.substr(4);
      tondelsala.send({ "cod" : did });
   }


   var toncanvas = clearcanvas();

   toncanvas.appendChild(mkaddbutton(addsala));
   addEvent(toncanvas.lastChild.lastChild,"click",addsala);
   toncanvas.appendChild(document.createElement('DIV'));
   toncanvas.lastChild.style.overflow = 'scroll';
   toncanvas.lastChild.style.width    = '780px';
   toncanvas.lastChild.style.height   = '290px';
   var tonlistsala = toncanvas.lastChild;
   var tonlistedsala = new ajason("forum/tonlistedsala.php",function (data) {
      var delbut;
      for(qtsala=0;qtsala<data["tongrp"].length;++qtsala) {
         tonlistsala.appendChild(mkrowedsala(data["tongrp"],qtsala));
         delbut = tonlistsala.lastChild;
         addEvent(delbut.firstChild,"change",dbsala);
         addEvent(delbut.firstChild.nextSibling,"mouseover",imghi);
         addEvent(delbut.lastChild,"mouseout",imgunhi);
         addEvent(delbut.lastChild,"click",delsala);
      }
   });

   tonlistedsala.send({});
}

function mkrowedsala(d,i)
{
   var t;
   t               = document.createElement("DIV");
   t.id            = "sala" + d[i]["cod"];
   t.className     = "tabline" + (i&1);
   t.style.padding = '0px';
   t.style.margin  = '0px';
   t.onclick       = "edit_sala(this)";
   t.onmouseover   = "hi_sala(this)";
   t.onmouseout    = "unhi_sala(this)";
   t.innerHTML = "<input type='text' style='width: 720px;' autocomplete='off' class='inputnome' />";
//   t.lastChild.value = unescape(d[i]["nome"]);
   t.lastChild.value = d[i]["nome"];
   t.appendChild(loadimg('deletar',dbpath + 'img/deletar0.png',20,22));
   t.appendChild(loadimg('deletarhi',dbpath + 'img/deletar9.png',20,22));
   t.lastChild.style.display = 'none';
   t.delete_level = 0;
   return(t);
}

function mkrowaddsala(i)
{
   var t;
   t               = document.createElement("DIV");
   t.id            = "salanew";
   t.className     = "tabline" + (i%1);
   t.style.padding = '0px';
   t.onclick       = "edit_sala(this)";
   t.onmouseover   = "hi_sala(this)";
   t.onmouseout    = "unhi_sala(this)";
   t.innerHTML = "<input type='text' style='width: 720px;' autocomplete='off' class='inputnome' />";
   t.appendChild(loadimg('deletar',dbpath + 'img/deletar0.png',20,22));
   t.appendChild(loadimg('deletarhi',dbpath + 'img/deletar9.png',20,22));
   t.lastChild.style.display = 'none';
   t.delete_level = 0;
   return(t);
}

function toncadempico()
{
   var qtsala;

   var tonaddsala = new ajason("forum/tonaddsala.php",function (data) {
      getelem("salanew").id = "sala" + data["cod"];
   });

   var tonupdsala = new ajason("forum/tonupdsala.php",function (data) {
      // getelem("salanew").lastChild.lastChild.id = data["id"];
   });

   function dbsala(o,e)
   {
      var _id = o.parentNode.id;
      if (_id=="salanew") {
//         tonaddsala.send({"nome" : escape(escape(o.value)) });
         tonaddsala.send({"nome" : o.value });
      } else {
//         tonupdsala.send({"cod" : _id.substr(4), "nome" : escape(escape(o.value)) });
         tonupdsala.send({"cod" : _id.substr(4), "nome" : o.value });
      }
   }

   function addsala()
   {
      var delbut;
      if (!getelem("salanew")) {
         tonlistsala.appendChild(mkrowaddsala(qtsala++));
         delbut = tonlistsala.lastChild;
         addEvent(delbut.firstChild,"change",dbsala);
         addEvent(delbut.firstChild.nextSibling,"mouseover",imghi);
         addEvent(delbut.lastChild,"mouseout",imgunhi);
         addEvent(delbut.lastChild,"click",delsala);
      }
   }

   var tondelsala = new ajason("forum/tondelsala.php",function (data) {
      if (data["err"]) {
         alert("Erro. Sala nao deletada.");
      } else {
         delete_elem("sala"+data["cod"]);
      }
   });

   function delsala(o,e)
   {
      var did = o.parentNode.id.substr(4);
      tondelsala.send({ "cod" : did });
   }


   var toncanvas = clearcanvas();

   toncanvas.appendChild(mkaddbutton(addsala));
   addEvent(toncanvas.lastChild.lastChild,"click",addsala);
   toncanvas.appendChild(document.createElement('DIV'));
   toncanvas.lastChild.style.overflow = 'scroll';
   toncanvas.lastChild.style.width    = '780px';
   toncanvas.lastChild.style.height   = '290px';
   var tonlistsala = toncanvas.lastChild;
   var tonlistedsala = new ajason("forum/tonlistedsala.php",function (data) {
      var delbut;
      for(qtsala=0;qtsala<data["tongrp"].length;++qtsala) {
         tonlistsala.appendChild(mkrowedsala(data["tongrp"],qtsala));
         delbut = tonlistsala.lastChild;
         addEvent(delbut.firstChild,"change",dbsala);
         addEvent(delbut.firstChild.nextSibling,"mouseover",imghi);
         addEvent(delbut.lastChild,"mouseout",imgunhi);
         addEvent(delbut.lastChild,"click",delsala);
      }
   });

   tonlistedsala.send({});
}



function toncadusr()
{
   var qtusr, fnsel, emplist, salalist;

   var tonaddusr = new ajason("forum/tonaddusr.php",function (data) {
      if (data["err"]) {
         alert(data["err"]);
      } else {
         getelem("usrnew").id = "usr" + data["cod"];
         alert("Cadastrado");
      }
   });

   var tonupdusr = new ajason("forum/tonupdusr.php",function (data) {
      alert("Atualizado");
   });

   function dbusr(o,e)
   {
      var _id = o.parentNode.id, p, s, i;
      var nome, email, cargo, cod, pw, codemp, salas;
      if (userid=="0") {
         p      = o.parentNode.firstChild.nextSibling.nextSibling;
         nome   = p.lastChild;
         p      = p.nextSibling.nextSibling;
         email  = p.lastChild;
         p      = p.nextSibling.nextSibling;
         codemp = p;
         p      = p.nextSibling.nextSibling;
         pw     = p.lastChild;
         p      = p.nextSibling.nextSibling;
         cargo  = p.lastChild;
         p      = p.nextSibling.nextSibling;
         salas  = [];
         for(s=p.lastChild.options,i=0;i<s.length;++i) {
            if (s[i].selected) {
               salas[salas.length] = s[i].value;
            }
         }
         if (!email.value.match(/^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/)) {
            email.focus();
            alert("Email invalido");
            return;
         }
         if (codemp.selectedIndex==0) {
            alert("Selecione uma empresa");
            codemp.focus();
            return;
         }
         if (!nome.value.match(/[\w]{2,}( [\w]{2,})+/)) {
            alert("Digite um nome");
            nome.focus();
            return;
         }
         if (cargo.value=="") {
            alert("Digite um cargo");
            cargo.focus();
            return;
         }
         if (salas.length==0) {
            alert("Selecione pelo menos uma sala");
            p.lastChild.focus();
            return;
         }
      } else {
         pw     = o.previousSibling.previousSibling.lastChild;
      }
      cod    = _id.substr(3);
      if (cod=="new") {
         if (pw.value.length<8) {
            alert("Digite uma senha de no minimo 8 caracteres");
            pw.focus();
            return;
         }
         tonaddusr.send({
            "nome"      : nome.value,
            "email"     : email.value,
            "codemp"    : codemp.options[codemp.selectedIndex].value,
            "pw"        : pw.value,
            "cargo"     : cargo.value,
            "tonusrgrp" : salas
         });
      } else {
         if (userid=="0") {
            tonupdusr.send({
               "cod"       : cod,
               "nome"      : nome.value,
               "email"     : email.value,
               "codemp"    : codemp.options[codemp.selectedIndex].value,
               "pw"        : pw.value,
               "cargo"     : cargo.value,
               "tonusrgrp" : salas
            });
         } else {
            tonupdusr.send({
               "cod"    : cod,
               "pw"     : pw.value
            });
         }
      }
   }

   function addusr()
   {
      var delbut;
      if (!getelem("usrnew")) {
         tonlistusr.appendChild(mkrowaddusr(qtusr++,emplist,salalist));
         delbut = tonlistusr.lastChild;
         addEvent(delbut.lastChild,"click",dbusr);
         addEvent(delbut.firstChild,"mouseover",imghi);
         addEvent(delbut.firstChild.nextSibling,"mouseout",imgunhi);
         addEvent(delbut.firstChild.nextSibling,"click",delusr);
      }
   }

   var tondelusr = new ajason("forum/tondelusr.php",function (data) {
      if (data["err"]) {
         alert("Erro. Falha ao deletar.");
      } else {
         delete_elem("usr"+data["cod"]);
      }
   });

   function delusr(o,e)
   {
      var did = o.parentNode.id.substr(3);
      tondelusr.send({ "cod" : did });
   }

   fnemplist = new ajason("forum/tonlistemp.php",function (data) {
      emplist = data["empresa"];
   });

   fnsalalist = new ajason("forum/tonlistsala.php",function (data) {
      salalist = data["tongrp"];
      var i;
      for(i=0;i<salalist.length;++i) {
//         salalist[i]["nome"] = unescape(salalist[i]["nome"]);
         salalist[i]["nome"] = salalist[i]["nome"];
      }
   });

   var toncanvas = clearcanvas();

   toncanvas.appendChild(mkaddbutton(addusr));
   addEvent(toncanvas.lastChild.lastChild,"click",addusr);
   toncanvas.appendChild(document.createElement('DIV'));
   toncanvas.lastChild.style.overflow = 'scroll';
   toncanvas.lastChild.style.width    = '780px';
   toncanvas.lastChild.style.height   = '290px';
   var tonlistusr = toncanvas.lastChild;
   var tonlistedusr = new ajason("forum/tonlistedusr.php",function (data) {
      var delbut;
      fnemplist.syncsend({});
      fnsalalist.syncsend({});
      for(qtusr=0;qtusr<data["tonusr"].length;++qtusr) {
         tonlistusr.appendChild(mkrowedusr(data["tonusr"],qtusr,emplist,salalist));
         delbut = tonlistusr.lastChild;
         addEvent(delbut.lastChild,"click",dbusr);
         addEvent(delbut.firstChild,"mouseover",imghi);
         addEvent(delbut.firstChild.nextSibling,"mouseout",imgunhi);
         addEvent(delbut.firstChild.nextSibling,"click",delusr);
      }
   });

   tonlistedusr.send({});
}

function mkrowedusr(d,i,emplist,salalist)
{
   var t, obj, img, sel, fnsel, j, k;
   t                 = document.createElement("DIV");
   t.id              = "usr" + d[i]["cod"];
   t.className       = "tabline" + (i%2);
   t.style.padding   = '2px';
   t.style.textAlign = "left";
   if (userid=="0") {
      t.innerHTML     = "<label>Nome: <input type='text' style='width: 670px;' autocomplete='off' class='inputnome' /></label><br/>"
                      + "<label>E-mail: <input type='text' style='width: 320px;' autocomplete='off' class='inputnome' /></label>&nbsp;"
                      + "<select></select>"
                      + "<br /><label>Senha: <input type='password' style='width: 320px;' autocomplete='off' class='inputnome' /></label>"
                      + "<br /><label>Cargo: <input type='text' style='width: 670px;' autocomplete='off' class='inputnome' /></label>"
                      + "<br /><label>Salas: <select multiple size=4></select></label>"
                      + "<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button> Ok </button>"
                      ;
      obj = t.firstChild;
      obj.lastChild.value = d[i]["nome"];
      obj.nextSibling.nextSibling.lastChild.value = d[i]["email"];
      sel = obj.nextSibling.nextSibling.nextSibling.nextSibling;
      sel.nextSibling.nextSibling.nextSibling.nextSibling.lastChild.value = d[i]["cargo"];

      sel.options[0] = new Option("Empresa","");
      for(j=0;j<emplist.length;++j)  {
         sel.options[j+1] = new Option(emplist[j]["nome"],emplist[j]["cod"]);
         if (d[i]["codemp"]==emplist[j]["cod"]) {
            sel.options[j+1].selected = 1;
         }
      }

      sel = sel.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.lastChild;
      for(j=0;j<salalist.length;++j)  {
         sel.options[j] = new Option(salalist[j]["nome"],salalist[j]["cod"]);
         for (k=0;k<d[i]["tonusrgrp"].length;++k) {
            if (d[i]["tonusrgrp"][k]==salalist[j]["cod"]) {
               sel.options[j].selected = 1;
               d[i]["tonusrgrp"].splice(k,1);
               break;
            }
         }
      }

      t.insertBefore(img=loadimg('deletar',dbpath + 'img/deletar0.png',20,22),obj);
      img.style.cssFloat = "right";
      t.insertBefore(img=loadimg('deletarhi',dbpath + 'img/deletar9.png',20,22),obj);
      img.style.cssFloat = "right";
      img.style.display = 'none';
      img.delete_level = 0;

   } else {
      t.innerHTML     = "<label>Senha: <input type='password' style='width: 320px;' autocomplete='off' class='inputnome' /></label>"
                      + "&nbsp;<button> Ok </button>"
                      ;
   }
   return(t);
}

function mkrowaddusr(i,emplist,salalist)
{
   var t, obj, img, sel, fnsel;
   if (userid=="0") {
      t                 = document.createElement("DIV");
      t.id              = "usrnew";
      t.className       = "tabline" + (i%2);
      t.style.padding   = '2px';
      t.style.textAlign = "left";
//      t.onclick         = "edit_sala(this)";
//      t.onmouseover     = "hi_sala(this)";
//      t.onmouseout      = "unhi_sala(this)";
      t.innerHTML     = "<label>Nome: <input type='text' style='width: 670px;' autocomplete='off' class='inputnome' /></label><br/>"
                      + "<label>E-mail: <input type='text' style='width: 320px;' autocomplete='off' class='inputnome' /></label>&nbsp;"
                      + "<select></select>"
                      + "<br /><label>Senha: <input type='password' style='width: 320px;' autocomplete='off' class='inputnome' /></label>"
                      + "<br /><label>Cargo: <input type='text' style='width: 670px;' autocomplete='off' class='inputnome' /></label>"
                      + "<br /><label>Salas: <select multiple size=4></select></label>"
                      + "<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button> Ok </button>"
                      ;
      obj = t.firstChild;
      sel = obj.nextSibling.nextSibling.nextSibling.nextSibling;

      sel.options[0] = new Option("Empresa","");
      for(j=0;j<emplist.length;++j)  {
         sel.options[j+1] = new Option(emplist[j]["nome"],emplist[j]["cod"]);
      }

      sel = sel.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.lastChild;
      for(j=0;j<salalist.length;++j)  {
         sel.options[j] = new Option(salalist[j]["nome"],salalist[j]["cod"]);
      }

      t.insertBefore(img=loadimg('deletar',dbpath + 'img/deletar0.png',20,22),obj);
      img.style.cssFloat = "right";
      t.insertBefore(img=loadimg('deletarhi',dbpath + 'img/deletar9.png',20,22),obj);
      img.style.cssFloat = "right";
      img.style.display = 'none';
      img.delete_level = 0;

   }
   return(t);
}



function mkaddbutton(fn)
{
   if (typeof(fn)=="string") {
      return(
         "<div>"
         +   "<img src='" + dbpath + "/img/add.gif' "
         +        "onmouseover='imghi(this)' />"
         +   "<img style='display: none;' src='" + dbpath + "/img/add-o.gif' "
         +        "onmouseout='imgunhi(this)' "
         +        "onclick='" + fn + "(this)' />"
         + "</div>"
      );
   }

   var d = document.createElement('DIV');
   d.innerHTML = "<img src='" + dbpath + "/img/add.gif' onmouseover='imghi(this)' />"
               + "<img style='display: none;' src='" + dbpath + "/img/add-o.gif' "
               +        "onmouseout='imgunhi(this)' />";
   return(d);
}


function imghi(o)
{
   if (o.target) {
      o = this;
   }
   o.style.display='none';
   o.nextSibling.style.display='inline';
}

function imgunhi(o)
{
   if (o.target) {
      o = this;
   }
   o.style.display='none';
   o.previousSibling.style.display='inline';
}

function tonsala()
{
   var hdr, hdrde, hdrpara, hdrass, hdrdt, bdymsg;
   var nomesala = "", tdtmp, usrlist;

   var tonlistusr = new ajason("forum/tonlistusr.php",function (data) {
      var i, u;
      if (data["err"]) {
         alert(data["err"]);
      } else {
         u = getelem("tonew");
         if (userid!=0) {
            u.options[0] = new Option("Administrador Tr-Op.Net",0);
         }
         for(i=0;i<data["tonusr"].length;++i) {
            if (data["tonusr"][i]["cod"]!=userid) {
               u.options[u.options.length] = new Option(data["tonusr"][i]["nome"],data["tonusr"][i]["cod"]);
            }
         }
      }
   });

   var tonpostmsg = new ajason("forum/tonpostmsg.php",function (data) {
      var i, o, j, de, para, dt, ass, d, h, msg;

      if (data["err"]) {
         alert(data["err"]);
      } else {
         tonentersala(tonlistmsg.codsala)
      }
   });

   var tondelmsg = new ajason("forum/tondelmsg.php",function (data) {
      if (data["err"]) {
         alert("Erro. Mensagem nao deletada.");
      } else {
         delete_elem("msg" + data["cod"]);
      }
   });

   function delmsg(o,e)
   {
      if (o.target) {
         o = this;
      }
      tondelmsg.send({ "cod" : o.did });
   }

   var tonlistmsg = new ajason("forum/tonlistmsg.php",function (data) {
      var i, o, j, de, para, dt, ass, d, h, msg, img;

      var toncanvas = clearcanvas();
      hdr = document.createElement('TABLE');
      hdr.appendChild(document.createElement('TBODY'));

      hdrde = document.createElement('TR');
      hdrde.appendChild(document.createElement('TD'));
      hdrde.lastChild.innerHTML = "De: ";
      hdrde.lastChild.style.fontWeigth = 'bold';
      hdrde.lastChild.style.verticalAlign = 'top';
      hdrde.lastChild.style.textAlign = 'left';
      hdrde.appendChild(document.createElement('TD'));
      hdrde.lastChild.style.textAlign = 'left';

      hdrpara = document.createElement('TR');
      hdrpara.appendChild(document.createElement('TD'));
      hdrpara.lastChild.innerHTML = "Para: ";
      hdrpara.lastChild.style.fontWeigth = 'bold';
      hdrpara.lastChild.style.verticalAlign = 'top';
      hdrpara.lastChild.style.textAlign = 'left';
      hdrpara.appendChild(document.createElement('TD'));
      hdrpara.lastChild.style.textAlign = 'left';

      hdrass = document.createElement('TR');
      hdrass.appendChild(document.createElement('TD'));
      hdrass.lastChild.innerHTML = "Assunto: ";
      hdrass.lastChild.style.fontWeigth = 'bold';
      hdrass.lastChild.style.verticalAlign = 'top';
      hdrass.lastChild.style.textAlign = 'left';
      hdrass.appendChild(document.createElement('TD'));
      hdrass.lastChild.style.textAlign = 'left';

      hdrdt = document.createElement('TR');
      hdrdt.appendChild(document.createElement('TD'));
      hdrdt.lastChild.innerHTML = "Data: ";
      hdrdt.lastChild.style.fontWeigth = 'bold';
      hdrdt.lastChild.style.verticalAlign = 'top';
      hdrdt.lastChild.style.textAlign = 'left';
      hdrdt.appendChild(document.createElement('TD'));
      hdrdt.lastChild.style.textAlign = 'left';

      bdymsg = document.createElement('TR');
      tdtmp = document.createElement('TD');
      tdtmp.colSpan = 2;
      tdtmp.className = 'msgbdy';
      bdymsg.appendChild(tdtmp);

      o = document.createElement('DIV');
      o.innerHTML = "<div class='salatit'>" + nomesala + "<BR /></div>";

      for(i=0;i<data["tonmsg"].length;++i) {
         o.appendChild(document.createElement('DIV'));
         o.lastChild.className    = 'salacontent tabline' + (i&1);
         o.lastChild.codmsg       = data["tonmsg"][i]["cod"];
         o.lastChild.id           = "msg" + data["tonmsg"][i]["cod"];
         o.lastChild.delete_level = 0;

         // From:
         de = hdrde.cloneNode(true);
         de.lastChild.appendChild(mkuserid(
            data["tonmsg"][i]["codusr"],
            data["tonmsg"][i]["nome"],
            data["tonmsg"][i]["cargo"],
            data["tonmsg"][i]["email"],
            data["tonmsg"][i]["empresa"],
            data["tonmsg"][i]["codemp"]
         ));
         if (userid==0) {
            de.lastChild.insertBefore(img=loadimg('deletar',dbpath + 'img/deletar0.png',20,22),de.lastChild.firstChild);
            img.style.cssFloat     = "right";
            img.style.cssTextFLOAT = "right";
            img.style.styleFloat   = "right";
            addEvent(img,"mouseover",imghi);

            de.lastChild.insertBefore(img=loadimg('deletarhi',dbpath + 'img/deletar9.png',20,22),de.lastChild.firstChild.nextSibling);
            img.style.cssFloat     = "right";
            img.style.cssTextFLOAT = "right";
            img.style.styleFloat   = "right";
            img.style.display = 'none';
            img.delete_level = 0;
            img.did = data["tonmsg"][i]["cod"];
            addEvent(img,"mouseout",imgunhi);
            addEvent(img,"click",delmsg);
         }

         // To:
         para = hdrpara.cloneNode(true);
         for(j=0;j<data["tonmsg"][i]["tousr"].length;++j) {
            para.lastChild.appendChild(mkuserid(
               data["tonmsg"][i]["tousr"][j]["codusr"],
               data["tonmsg"][i]["tousr"][j]["nome"],
               data["tonmsg"][i]["tousr"][j]["cargo"],
               data["tonmsg"][i]["tousr"][j]["email"],
               data["tonmsg"][i]["tousr"][j]["empresa"],
               data["tonmsg"][i]["tousr"][j]["codemp"]
            ));
            para.lastChild.appendChild(document.createElement('BR'));
         }

         // Date:
         dt = hdrdt.cloneNode(true);
         dt.lastChild.appendChild(mkdt(data["tonmsg"][i]["dt"]));

         // Assunto:
         ass = hdrass.cloneNode(true);
         ass.lastChild.appendChild(mkass(data["tonmsg"][i]["assunto"]));

         // Msg:
         msg = bdymsg.cloneNode(true);
//         alert(data["tonmsg"][i]["msg"]);
//         alert(unescape(data["tonmsg"][i]["msg"]));
         msg.lastChild.innerHTML = unescape(unescape(data["tonmsg"][i]["msg"]));

         h = hdr.cloneNode(true);
         h.lastChild.appendChild(de);
         h.lastChild.appendChild(para);
         h.lastChild.appendChild(dt);
         h.lastChild.appendChild(ass);
         h.lastChild.appendChild(msg);

         o.lastChild.appendChild(h);
      }
      toncanvas.appendChild(o);
      toncanvas.appendChild(document.createElement('BR'));
      toncanvas.appendChild(document.createElement('DIV'));
      toncanvas.lastChild.className = "salacomment";
      toncanvas.lastChild.appendChild(document.createElement('P'));
      toncanvas.lastChild.lastChild.innerHTML = "Envie sua mensagem";
      toncanvas.lastChild.lastChild.style.textAlign = "center";
      toncanvas.lastChild.appendChild(document.createElement('BR'));
      toncanvas.lastChild.appendChild(document.createElement('SPAN'));
      toncanvas.lastChild.lastChild.innerHTML = "Para:&nbsp;";
      toncanvas.lastChild.appendChild(document.createElement('SELECT'));
      toncanvas.lastChild.lastChild.id           = 'tonew';
      toncanvas.lastChild.lastChild.setAttribute('MULTIPLE',true);
      tonlistusr.send({ "cod" : this.codsala });
      toncanvas.lastChild.appendChild(document.createElement('BR'));
      toncanvas.lastChild.appendChild(document.createElement('BR'));
      toncanvas.lastChild.appendChild(document.createElement('SPAN'));
      toncanvas.lastChild.lastChild.innerHTML = "Assunto:&nbsp;";
      toncanvas.lastChild.appendChild(document.createElement('INPUT'));
      toncanvas.lastChild.lastChild.id          = 'assnew';
      toncanvas.lastChild.lastChild.type        = 'TEXT';
      toncanvas.lastChild.lastChild.style.width = '600px';
      toncanvas.lastChild.appendChild(document.createElement('BR'));
      toncanvas.lastChild.appendChild(document.createElement('BR'));
      toncanvas.lastChild.appendChild(document.createElement('TEXTAREA'));
      toncanvas.lastChild.lastChild.id = 'msgnew';
      toncanvas.lastChild.appendChild(document.createElement('BUTTON'));
      toncanvas.lastChild.lastChild.innerHTML = " Enviar ";
      addEvent(toncanvas.lastChild.lastChild,"click",function(o,e) {
         var i, j, x, to, tolist, ass;
         var m = document.getElementById('msgnew').nextSibling.nextSibling.nextSibling;
         m = m.firstChild.firstChild.firstChild.firstChild.nextSibling;
         m = document.getElementById('wysiwygmsgnew');
         m = m.contentWindow.document.lastChild;

         m = m.innerHTML;
         m = m.replace(/\<BODY/g,"<DIV");
         m = m.replace(/\<\/BODY\>/g,"</DIV>");
         m = m.replace(/\<head.*\/head\>/g,"");
         m = m.replace(/\<body/g,"<DIV");
         m = m.replace(/\<\/body\>/g,"</DIV>");
         m = m.replace(/\"/g,"%22");
         m = escape(m);
         m = m.replace(/%3CHEAD.*HEAD%3E/g,"");
         ass = document.getElementById("assnew").value;
         to  = [];
         tolist = document.getElementById("tonew").options;
         for(i=j=0; i<tolist.length; ++i) {
            if (tolist[i].selected) {
               to[j++] = tolist[i].value;
            }
         }
         tonpostmsg.send({ "msg" : m, "ass" : ass, "to" : to, "cod" : tonlistmsg.codsala });
      });
      toncanvas.appendChild(document.createElement('BR'));
      generate_wysiwyg('msgnew');
   });

   function mkass(ass)
   {
      var u;
      u = document.createElement('SPAN');
      u.innerHTML = ass;
      return(u);
   }

   function mkdt(dt)
   {
      var u;
      u = document.createElement('SPAN');
      u.innerHTML = dt.substr(8,2) + "/"
                  + dt.substr(5,2) + "/"
                  + dt.substr(0,4)
                  + dt.substr(10);
      return(u);
   }

   function mkuserid(codusr,nome,cargo,email,empresa,codemp)
   {
      var u;
      u = document.createElement('TABLE');
      u.appendChild(document.createElement('TBODY'));
      u.lastChild.appendChild(document.createElement('TR'));
      u.lastChild.lastChild.appendChild(document.createElement('TD'));
      u.lastChild.lastChild.lastChild.setAttribute('ROWSPAN','2');
      u.lastChild.lastChild.lastChild.appendChild(loadimg("emp_" + codemp,dbpath + "img/empico/" + codemp + ".gif",50,50));
      u.lastChild.lastChild.appendChild(document.createElement('TD'));
      u.lastChild.lastChild.lastChild.innerHTML = nome;
      if (codusr==userid) {
         u.lastChild.lastChild.lastChild.style.color    = 'red';
      }
      u.lastChild.appendChild(document.createElement('TR'));
      u.lastChild.lastChild.appendChild(document.createElement('TD'));
      u.lastChild.lastChild.lastChild.style.color    = 'black';
      u.lastChild.lastChild.lastChild.style.fontSize = '12px';
      u.lastChild.lastChild.lastChild.innerHTML      = (cargo ? (cargo + "<BR />") : "");
      u.lastChild.lastChild.lastChild.innerHTML     += email + "<BR />";
      u.lastChild.lastChild.lastChild.innerHTML     += "&nbsp;" + empresa;

/*
      u = document.createElement('SPAN');
      u.innerHTML = nome;
      if (codusr==userid) {
         u.style.color    = 'red';
      }
      u.appendChild(document.createElement('BR'));
      u.appendChild(document.createElement('SPAN'));
      u.lastChild.style.color    = 'black';
      u.lastChild.style.fontSize = '12px';
      u.lastChild.innerHTML      = (cargo ? (cargo + "<BR />") : "");
      u.lastChild.appendChild(loadimg("emp_" + codemp,dbpath + "img/empico/" + codemp + ".gif",50,50));
      u.lastChild.innerHTML     += "&nbsp;" + empresa;
*/
      return(u);
   }

   function tonentersala(codsala)
   {
      var toncanvas  = clearcanvas();
      tonlistmsg.codsala = codsala;
      tonlistmsg.send({ "cod" : codsala });
   }

   var tonlistsala = new ajason("forum/tonlistedsala.php",function (data) {
      var i, o, fn;
      var toncanvas = clearcanvas();
      for(i=0;i<data["tongrp"].length;++i) {
         o = document.createElement('DIV');
         o.className = 'salalist tabline' + (i&1);
         o.innerHTML = data["tongrp"][i]["nome"];
         o.cod       = data["tongrp"][i]["cod"];
         toncanvas.appendChild(o);
         addEvent(o,"click",function (o,e) {
            nomesala = o.innerHTML;
            tonentersala(o.cod);
         });
         addEvent(o,"mouseover",function (o,e) {
            if (o.className.length==17) {
               o.className += " salalisthi";
            }
         });
         addEvent(o,"mouseout",function (o,e) {
            if (o.className.length>17) {
               o.className = o.className.substr(0,17);
            }
         });
      }
   });

   tonlistsala.send({});

}

