var debug;
var http_request;
var statoAlbero,gruppoCorrente,docCorrente,biscotti;

function init()
{
debug=document.getElementById("debug").firstChild;
 if(!document.getElementById || !document.getElementsByTagName) return;

 // Eventuale attivazione della toolbar
// attivaToolbar();

 // Attivazione dei tasti per l'albero gruppi
 try
 {
  var as=document.getElementById("gruppi").getElementsByTagName("h2").item(0).getElementsByTagName("a");
  for(var n=as.length-1; n>=0; n--)
   as.item(n).style.display="block";
 }
 catch(e) {}

 // Estrazione dai cookie dello stato dell'albero dei gruppi
 biscotti=new Array;
 var val,tmp=document.cookie.split("; ");
 for(var nome="",n=0; n<tmp.length; n++)
 {
  val=tmp[n].split("=");
  if(val.length==2)
  {
   val[1]=unescape(val[1]);
   switch(val[0])
   {
    case "expires": if(nome) biscotti[nome].expires=val[1]; break;
    case "path": if(nome) biscotti[nome].path=val[1]; break;
    case "domain": if(nome) biscotti[nome].domain=val[1]; break;
    default: nome=val[0]; biscotti[nome]=val[1]; break;
   }
  }
 }
 statoAlbero=new Array;
 if(biscotti["a"])
 {
  var nodo,albero=biscotti["a"].split(":");
  for(var n=0; n<albero.length; n++)
  {
   nodo=parseInt(albero[n],10);
   statoAlbero[nodo]=true;
  }
 }
 if(biscotti["g"]) gruppoCorrente=parseInt(biscotti["g"],10);
 if(biscotti["d"]) docCorrente=parseInt(biscotti["d"],10);

// try { generaAlbero(gruppoCorrente); } catch(e) { attivaGruppi(); }
 try { attivaGruppi(gruppoCorrente); } catch(e) {}
 try { attivaDocumenti(); } catch(e) {}
}

// Genera l'albero dei gruppi
function generaAlbero(gruppo)
{
 if(!nuovaRequest()) return false;
 http_request.onreadystatechange=function()
 {
  if(http_request.readyState==4)
  {
   if(http_request.status==200)
   {
    var xmldoc=http_request.responseXML;
    var gruppi;
    try { gruppi=xmldoc.getElementsByTagName("gruppi").item(0); } catch(e) {}
    if(gruppi)
    {
     var ul,div=document.getElementById("gruppi");
     try
     {
      ul=div.getElementsByTagName("ul").item(0);
      if(ul) removeElementDeep(ul);
     }
     catch(e) {}
     ul=document.createElement("ul");
     div.appendChild(ul);
     caricaGruppi(ul,gruppi);
     attivaGruppi(gruppo);
    }
    else stampaErrore("Nessun gruppo caricato");
   }
   else stampaErrore(http_request.status);
  }
  else return;
 };
 http_request.open("GET","gruppi.php",true);
 http_request.send(null);
}

function caricaGruppi(ul,gruppi)
{
 var li,a,strong,nome,id,nuovi,tot,figli;
 for(var g=gruppi.firstChild; g; g=g.nextSibling)
  if(g.nodeType==1)
  {
   id=g.getAttribute("id");
   nome=""; nuovi=tot=0; figlio=false;
   for(var e=g.firstChild; e; e=e.nextSibling)
    if(e.nodeType==1)
    {
     switch(e.nodeName.toLowerCase())
     {
      case "n": nome=e.firstChild.nodeValue; break;
      case "u": nuovi=parseInt(e.firstChild.nodeValue,10); break;
      case "t": tot=parseInt(e.firstChild.nodeValue,10); break;
      case "gr": figlio=e; break;
     }
    }
   li=document.createElement("li");
   a=document.createElement("a");
   a.href="index.php?g="+id;
   a.id="g"+id;
   a.appendChild(document.createTextNode(nome));
   li.appendChild(a);
   if(nuovi)
   {
    strong=document.createElement("strong");
    strong.appendChild(document.createTextNode(nuovi));
    li.appendChild(strong);
   }
   ul.appendChild(li);
   if(figlio)
   {
    var ul2=document.createElement("ul");
    li.appendChild(ul2);
    caricaGruppi(ul2,figlio);
   }
  }
}

// Setta gli handler e le icone per l'albero dei gruppi
function attivaGruppi(gruppo)
{
 var ul=document.getElementById("gruppi").getElementsByTagName("ul").item(0);
 var as=document.getElementById("gruppi").getElementsByTagName("a");
 var subul,a,a2,li,img,id;
 for(var n=as.length-1; n>=0; n--)
 {
  a=as.item(n);
  if(a.addEventListener)
   a.addEventListener("click",apriGruppo,false);
  else if(a.attachEvent)
   a.attachEvent("onclick",apriGruppo);
  else
   a.onclick=apriGruppo;
  if(a.id) id=parseInt(a.id.substr(1),10);
  else
  {
   id=a.href.match(/([0-9]+)$/);
   if(id) id=parseInt(id[0],10);
   if(id) a.id="g"+id;
  }
  li=a.parentNode;
  if(id==gruppo) li.className="corrente";
  try
  {
   var subul=li.getElementsByTagName("ul").item(0);
   if(subul)
   {
    if(statoAlbero[id]) subul.className="on";
    else subul.className="off";
    img=document.createElement("img");
    if(statoAlbero[id]) img.src="img/aperto.gif";
    else img.src="img/chiuso.gif";
    img.alt="";
    a2=document.createElement("a");
    a2.className="freccia";
    a2.appendChild(img);
    if(a2.addEventListener)
     a2.addEventListener("click",apriChiudi,false);
    else if(a2.attachEvent)
     a2.attachEvent("onclick",apriChiudi);
    else
     a2.onclick=apriChiudi;
    li.insertBefore(a2,a);
   }
   else a.className="foglia";
  }
  catch(e) { a.className="foglia"; }
 }
}

// Caricamento lista documenti
function caricaDocumenti(gruppo)
{
 if(!nuovaRequest()) return false;
 http_request.onreadystatechange=function()
 {
  if(http_request.readyState==4)
  {
   if(http_request.status==200)
   {
    var xmldoc=http_request.responseXML;
    var docs;
    try { docs=xmldoc.getElementsByTagName("documenti").item(0); } catch(e) {}
    if(docs)
    {
     var numDoc,tbody,table,div=document.getElementById("documenti");
     numDoc=0;
     try
     {
      table=div.getElementsByTagName("table").item(0);
      tbody=table.getElementsByTagName("tbody");
      for(var n=tbody.length-1; n>=0; n--)
       if(tbody[n]) removeElementDeep(tbody[n]);
     }
     catch(e)
     {
      table=document.createElement("table");
      var elem;
      elem=document.createElement("colgroup");
      elem.className="titolo";
      table.appendChild(elem);
      elem=document.createElement("colgroup");
      elem.className="data";
      table.appendChild(elem);
      elem=document.createElement("colgroup");
      elem.className="allegato";
      table.appendChild(elem);
      elem=document.createElement("thead");
      table.appendChild(elem);
      var tr=document.createElement("tr");
      var th;
      th=document.createElement("th");
      th.className="titolo";
      th.appendChild(document.createTextNode("Title"));
      tr.appendChild(th);
      th=document.createElement("th");
      th.className="data";
      th.appendChild(document.createTextNode("Date"));
      tr.appendChild(th);
      th=document.createElement("th");
      th.className="allegato";
      th=document.createElement("th");
      tr.appendChild(th);
      elem.appendChild(tr);
      div.appendChild(table);
     }
     tbody=document.createElement("tbody");
     table.appendChild(tbody);
     var td,tr,a,img,id,nome,data,allegato,nuovo;
     img=document.createElement("img");
     img.src="img/allegato.gif";
     for(var p="d",d=docs.firstChild; d; d=d.nextSibling)
      if(d.nodeType==1 && d.nodeName.toLowerCase()=="d")
      {
       id=d.getAttribute("id");
       nome=data=""; allegato=nuovo=false;
       for(var e=d.firstChild; e; e=e.nextSibling)
        if(e.nodeType==1)
         switch(e.nodeName.toLowerCase())
         {
          case "t": nome=e.firstChild.nodeValue; break;
          case "i": data=e.firstChild.nodeValue; break;
          case "a": allegato=true; break;
          case "n": nuovo=true; break;
         }
       tr=document.createElement("tr");
       tr.className=p;
       if(nuovo) tr.className+=" nuovo";
       if(id==docCorrente) tr.className+=" corrente";
       p=(p=="p")?"d":"p";
       td=document.createElement("td");
       a=document.createElement("a");
       a.id="d"+id;
       a.href="index.php?g="+gruppo+"&d="+id;
       a.appendChild(document.createTextNode(nome));
/*       if(a.addEventListener)
        a.addEventListener("click",apriDoc,false);
       else if(a.attachEvent)
        a.attachEvent("onclick",apriDoc);
       else
        a.onclick=apriDoc;*/
       td.appendChild(a);
       tr.appendChild(td);
       td=document.createElement("td");
       td.appendChild(document.createTextNode(data));
       tr.appendChild(td);
       td=document.createElement("td");
       if(allegato) td.appendChild(img.cloneNode(false));
       tr.appendChild(td);
       tbody.appendChild(tr);
       numDoc++;
      }
     if(!numDoc)
     {
      tr=document.createElement("tr");
      tr.id="nodocs";
      td=document.createElement("td");
      td.setAttribute("colspan","3");
      td.appendChild(document.createTextNode("No documents in this group."));
      tr.appendChild(td);
      tbody.appendChild(tr);
     }
     table.appendChild(tbody);
    }
    else stampaErrore("Nessun documento caricato");
   }
   else stampaErrore(http_request.status);
  }
  else return;
 };
 http_request.open("GET","documenti.php?g="+gruppo,true);
 http_request.send(null);
}

// Attiva l'elenco documenti
function attivaDocumenti()
{
 var id,a,as=null;
 try { as=document.getElementById("documenti").getElementsByTagName("a"); } catch(e) {}
 if(as)
 {
  for(var n=as.length-1; n>=0; n--)
  {
   a=as.item(n);
   if(!a.id)
   {
    id=a.href.match(/([0-9]+)$/);
    if(id) id=parseInt(id[0],10);
    if(id) a.id="d"+id;
   }
   if(a.addEventListener)
    a.addEventListener("click",apriDoc,false);
   else if(a.attachEvent)
    a.attachEvent("onclick",apriDoc);
   else
    a.onclick=apriDoc;
  }
 }
}

// Carica un documento
function caricaDocumento(documento)
{
 if(!nuovaRequest()) return false;
 http_request.onreadystatechange=function()
 {
  if(http_request.readyState==4)
  {
   if(http_request.status==200)
   {
    var xmldoc=http_request.responseXML;
    var doc;
    try { doc=xmldoc.getElementsByTagName("documento").item(0); } catch(e) {}
    if(doc)
    {
     var div=document.getElementById("documento");
     var diva,divl,divt,divc,titolo,data,dataagg,testo,allegati,link;
     diva=document.getElementById("allegati");
     divl=document.getElementById("link");
     azzeraDocumento();
     titolo=data=dataagg=testo="";
     divc=document.createElement("div");
     divc.id="testo";
     allegati=new Array; link=new Array;
     function Allegato(nome,url,dim) { this.nome=nome; this.url=url; this.dim=dim; }
     function Collegamento(nome,url) { this.nome=nome; this.url=url; }
     for(var n=doc.firstChild; n; n=n.nextSibling)
      if(n.nodeType==1)
       switch(n.nodeName.toLowerCase())
       {
        case "t": if(n.firstChild) titolo=n.firstChild.nodeValue; break;
        case "d": if(n.firstChild) data=n.firstChild.nodeValue; break;
        case "g": if(n.firstChild) dataagg=n.firstChild.nodeValue; break;
/*        case "c":
         for(var a=n.firstChild; a; a=a.nextSibling)
          if(a.nodeType==3) divc.appendChild(document.createTextNode(a.nodeValue));
          else if(a.nodeType==1 && a.nodeName.toLowerCase()=="br") divc.appendChild(document.createElement("br"));
         break;*/
        case "allegati":
         for(var a=n.firstChild; a; a=a.nextSibling)
          if(a.nodeType==1 && a.nodeName.toLowerCase()=="a")
           allegati[allegati.length]=new Allegato(a.firstChild.nodeValue,a.getAttribute("href"),a.getAttribute("d"));
         break;
        case "link":
         for(var a=n.firstChild; a; a=a.nextSibling)
          if(a.nodeType==1 && a.nodeName.toLowerCase()=="a")
           link[link.length]=new Collegamento(a.firstChild.nodeValue,a.getAttribute("href"));
         break;
       }
     divt=document.createElement("div");
     divt.id="intdoc";
     var h;
     h=document.createElement("h3");
     h.appendChild(document.createTextNode(titolo));
     divt.appendChild(h);
     h=document.createElement("h4");
     h.appendChild(document.createTextNode(data));
     divt.appendChild(h);
     if(dataagg)
     {
      h=document.createElement("h4");
      h.appendChild(document.createTextNode(dataagg));
      divt.appendChild(h);
     }
     if(allegati.length)
     {
      var ul,li,a;
      ul=document.createElement("ul");
      for(var i in allegati)
      {
       a=document.createElement("a");
       a.href=allegati[i].url;
       a.appendChild(document.createTextNode(allegati[i].nome));
       li=document.createElement("li");
       li.appendChild(a);
       if(allegati[i].dim) li.appendChild(document.createTextNode(" ("+allegati[i].dim+")"));
       ul.appendChild(li);
      }
      diva.appendChild(ul);
      diva.className="on";
     }
     if(link.length)
     {
      var ul,li,a;
      ul=document.createElement("ul");
      for(var i in link)
      {
       a=document.createElement("a");
       a.href=link[i].url;
       a.target="_blank";
       a.appendChild(document.createTextNode(link[i].nome));
       li=document.createElement("li");
       li.appendChild(a);
       ul.appendChild(li);
      }
      divl.appendChild(ul);
      divl.className="on";
     }
     h=document.createElement("br");
     h.className="clearr";
     divt.appendChild(h);
     div.appendChild(divt);
     div.appendChild(divc);
     caricaTestoDocumento(documento);
    }
    else stampaErrore("Nessun documento caricato");
   }
   else stampaErrore(http_request.status);
  }
  else return;
 };
 http_request.open("GET","documento.php?d="+documento,true);
 http_request.send(null);
}

function caricaTestoDocumento(documento)
{
 if(!nuovaRequest()) return false;
 http_request.onreadystatechange=function()
 {
  if(http_request.readyState==4)
  {
   if(http_request.status==200)
   {
    var divc=document.getElementById("testo");
    try { divc.innerHTML=http_request.responseText; } catch(e) {}
   }
   else stampaErrore(http_request.status);
  }
  else return;
 };
 http_request.open("GET","documentotesto.php?d="+documento,true);
 http_request.send(null);
}

function azzeraDocumento()
{
 var div=document.getElementById("documento");
 var diva,divl
 diva=document.getElementById("allegati");
 divl=document.getElementById("link");
 if(diva) diva.className="off";
 if(divl) divl.className="off";
 try
 {
  var ul=diva.getElementsByTagName("ul");
  for(var n=ul.length-1; n>=0; n--)
   if(ul[n]) removeElementDeep(ul[n]);
 }
 catch(e) {}
 try
 {
  var ul=divl.getElementsByTagName("ul");
  for(var n=ul.length-1; n>=0; n--)
   if(ul[n]) removeElementDeep(ul[n]);
 } catch(e) {}
 try
 {
  var br=div.getElementsByTagName("br");
  for(var n=br.length-1; n>=0; n--)
   if(br[n]) br[n].parentNode.removeChild(br[n]);
 } catch(e) {}
 try { removeElementDeep(document.getElementById("intdoc")); removeElementDeep(document.getElementById("intdoc")); } catch(e) {}
 try { removeElementDeep(document.getElementById("testo")); removeElementDeep(document.getElementById("testo")); } catch(e) {}
 cancellaTestiVuoti(div);
}

// Gestione albero gruppi
function apriChiudi(e)
{
 var node;
 if(!e) var e=window.event;
 if(e.target) node=e.target;
 else if(e.srcElement) node=e.srcElement;
 if(node.nodeType==3) node=n.parentNode;
 if(node.nodeType==1 && node.nodeName.toLowerCase()=="img")
 {
  try
  {
   var a=node.parentNode.nextSibling;
   var id=0;
   if(a && a.id) id=parseInt(a.id.substr(1),10);
   var ul=node.parentNode.parentNode.getElementsByTagName("ul").item(0);
   if(ul.className=="off")
   {
    if(node.addEventListener) ul.className="on";
    if(node.addEventListener) node.src="img/aperto.gif";
    if(id) statoAlbero[id]=true;
   }
   else
   {
    if(node.addEventListener) ul.className="off";
    if(node.addEventListener) node.src="img/chiuso.gif";
    if(id) statoAlbero[id]=false;
   }
   salvaAlbero();
  }
  catch(e) {}
 }
 if(e.preventDefault) e.preventDefault();
 if(e.stopPropagation) e.stopPropagation();
 else if(e.cancelBubble) e.cancelBubble=true;
 if(node.addEventListener) return false;
 else window.location.reload();
 return false;
}

// Gestione apertura gruppo
function apriGruppo(e)
{
 var node;

 if(!e) var e=window.event;
 if(e.target) node=e.target;
 else if(e.srcElement) node=e.srcElement;
 if(node.nodeType==3) node=n.parentNode;
 if(node.nodeType==1 && node.nodeName.toLowerCase()=="a")
 {
  try
  {
   gruppoCorrente=parseInt(node.id.substr(1),10);
   document.cookie="g="+gruppoCorrente;
   docCorrente=0;
   document.cookie="d="+docCorrente;
   caricaDocumenti(gruppoCorrente);
   azzeraDocumento();
   docCorrente=0;
   try
   {
    var li,liCorr=node.parentNode;
    li=document.getElementById("gruppi").getElementsByTagName("li");
    for(var n=0; n<li.length; n++)
     if(li.item(n).className && li.item(n).className=="corrente") li.item(n).className=li.item(n).className="";
    liCorr.className+="corrente";
   }
   catch(e) {}
  }
  catch(e) {}
 }
 if(e.preventDefault) e.preventDefault();
 if(e.stopPropagation) e.stopPropagation();
 else if(e.cancelBubble) e.cancelBubble=true;
 return false;
}

function apriDoc(e)
{
 var node;

 if(!e) var e=window.event;
 if(e.target) node=e.target;
 else if(e.srcElement) node=e.srcElement;
 if(node.nodeType==3) node=n.parentNode;
 if(node.nodeType==1 && node.nodeName.toLowerCase()=="a")
 {
  docCorrente=parseInt(node.id.substr(1),10);
  document.cookie="d="+docCorrente;
  caricaDocumento(docCorrente);
  try
  {
   var tr,trCorr=node.parentNode.parentNode;
   tr=document.getElementById("documenti").getElementsByTagName("tr");
   for(var n=0; n<tr.length; n++)
    if(tr.item(n).className.search(/ corrente/)>=0) tr.item(n).className=tr.item(n).className.replace(/ corrente/,"");
   trCorr.className+=" corrente";
   if(trCorr.className.search(/ nuovo/)>=0)
   {
    trCorr.className=trCorr.className.replace(/ nuovo/,"");
    var a=document.getElementById("g"+gruppoCorrente);
    if(a) try
    {
     var strong=a.parentNode.getElementsByTagName("strong").item(0);
     var nuovi=parseInt(strong.firstChild.nodeValue,10);
     if(nuovi>0) { nuovi--; strong.firstChild.nodeValue=nuovi; }
    }
    catch(e) {}
   }
  }
  catch(e) {}
 }
 if(e.preventDefault) e.preventDefault();
 if(e.stopPropagation) e.stopPropagation();
 else if(e.cancelBubble) e.cancelBubble=true;
 return false;
}

function salvaAlbero()
{
 var c="";
 for(var i in statoAlbero)
  if(statoAlbero[i]) c+=(c?":":"")+i;
 document.cookie="a="+escape(c);
}

function nuovaRequest()
{
 if(http_request) delete http_request;
 if(window.XMLHttpRequest)
 {
  http_request=new XMLHttpRequest();
  if(http_request.overrideMimeType) http_request.overrideMimeType("text/xml");
 }
 else if(window.ActiveXObject)
 {
  try { http_request=new ActiveXObject("Msxml2.XMLHTTP"); }
  catch(e)
  {
   try { http_request=new ActiveXObject("Microsoft.XMLHTTP"); }
   catch(e) { }
  }
 }
 return http_request;
}

function ricaricaGruppi()
{
 generaAlbero(gruppoCorrente);
}

function apriGruppi()
{
 var ul,li,a,img,id;
 try
 {
  ul=document.getElementById("gruppi").getElementsByTagName("ul").item(0);
  var a=ul.getElementsByTagName("a");
  for(var n=a.length-1; n>=0; n--)
  {
   li=a.item(n).parentNode;
   li.className="";
   img=li.firstChild.firstChild;
   if(img.nodeType==1 && img.nodeName.toLowerCase()=="img")
   {
    img.src="img/aperto.gif";
    li.getElementsByTagName("ul").item(0).className="on";
    if(a.item(n).id) statoAlbero[id]=true;
   }
  }
 }
 catch(e) {}
 salvaAlbero();
}

function chiudiGruppi()
{
 var ul,li,a,img,id;
 try
 {
  ul=document.getElementById("gruppi").getElementsByTagName("ul").item(0);
  var a=ul.getElementsByTagName("a");
  for(var n=a.length-1; n>=0; n--)
  {
   li=a.item(n).parentNode;
   li.className="";
   img=li.firstChild.firstChild;
   if(img.nodeType==1 && img.nodeName.toLowerCase()=="img")
   {
    img.src="img/chiuso.gif";
    li.getElementsByTagName("ul").item(0).className="off";
    if(a.item(n).id) statoAlbero[id]=false;
   }
  }
 }
 catch(e) {}
 salvaAlbero();
}

function stampaErrore(testo)
{
 alert(testo);
}

function removeElementDeep(e)
{
 if(!e) return;
 if(e.hasChildNodes())
  while(e.firstChild)
   removeElementDeep(e.firstChild);
 e.parentNode.removeChild(e);
 delete e;
}

function cancellaTestiVuoti(e)
{
 for(var n=e.firstChild; n; n=n.nextSibling)
  if(n.nodeType==3 && (!n.nodeValue || n.nodeValue.search(/^[\n\r\t ]*$/)>=0))
   e.removeChild(n);
}

//debug.nodeValue+="["+ul.getAttribute("style")+"]";
