var weekdaystxt=["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
var meses=["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"]
var calendar1
var lastPageURL;
var loadstatustext="<img src='imgs/icons/loading.gif' /> Aguarde um momento..."; 
var iframeEl = null;
// ---------------------------------------------------------------------------------------
// Fun¦ºes do AutoComplete
// substitui a célula e destroi a lista
function selectTexto(linha){
var comboDivId = linha.parentNode.parentNode.parentNode.parentNode.id;
var objCell = linha.parentNode.parentNode.parentNode.parentNode.parentNode;  
var paramsTable = comboDivId.split('|');
  objCell.firstChild.value = linha.firstChild.nodeValue;
  document.getElementById(comboDivId).style.visibility = 'hidden';
  connect('sys/update.php?chave='+paramsTable[1]+'&tabela='+paramsTable[0]+'&campo='+paramsTable[2]+'&valor='+linha.id)
  objCell.removeChild(objCell.lastChild);  
}
// ---------------------------------------------------------------------------------------
// mostra a lista    
function makeLista(nodo,event,tabela,campos,filtro){  
  var comboDivId = nodo.parentNode.lastChild.id;
  if (event.type=='click'){
    if (document.getElementById(comboDivId).style.visibility=='visible'){
       document.getElementById(comboDivId).style.visibility='hidden'; 
    } else {
       document.getElementById(comboDivId).style.visibility='visible';
       nodo.parentNode.firstChild.select();    // input.select();
    }
  } else {
    document.getElementById(comboDivId).style.visibility='visible';
  }
  connect('utils/combobox.php?search='+nodo.value+'&table='+tabela+'&fields='+campos+'&filtro='+filtro,comboDivId,false);
  if (event.keyCode==27) {
     document.getElementById(comboDivId).style.visibility='hidden';
  }
}
function closeLista(nodo){
/*  var comboDivId = nodo.parentNode.lastChild.id;
    if (document.getElementById(comboDivId).style.visibility=='visible'){
       document.getElementById(comboDivId).style.visibility='hidden'; 
    } */ 
}
// ---------------------------------------------------------------------------------------
// Cria a lista quando ganha focus
function criaLista(nodo,tabela,chave){
  // cria o div dinamicamente
  var divList = document.createElement('div');
  var divId = tabela+'|'+chave+'|'+nodo.name;
   
  divList.setAttribute('id', divId);
  divList.style.width = nodo.parentNode.offsetWidth+'px'; 
  divList.className= 'lista';
  divList.style.position="absolute";       
  nodo.parentNode.appendChild(divList); 
}
// ---------------------------------------------------------------------------------------
// muda o tab seleccionado
mudaTab=function(tabSelected){
var parent = tabSelected.parentNode.parentNode.id;
var items=document.getElementById(parent).getElementsByTagName('li');
  for(var i=0; i<items.length ;i++) {
    items[i].firstChild.className='';
  }
  tabSelected.className='here';
}

// ---------------------------------------------------------------------------------------
// muda o tab seleccionado
mudaMenu=function(menuSelected){
//  menuSelected.parentNode.className='active';
var parent = menuSelected.parentNode.parentNode.id;
var items=document.getElementById(parent).getElementsByTagName('li');
  for(var i=0; i<items.length ;i++) {
    items[i].className='';
  }
  menuSelected.parentNode.className='active';
}

// ---------------------------------------------------------------------------------------
// edita uma c+lula da dbTable 
function editCell(celula){
// separa os campos do id : campos[0] = afields[], campos[1] = aKeyFields[], campos[2] = aLookupKey[], campos[3] = field type
var campos = celula.id.split('|');    
  if (campos[0]==campos[1]){
    if ( celula.firstChild.nodeValue != null) {
    oldvalue = celula.firstChild.nodeValue
    var input=document.createElement('input');
    input.type='text';
    input.className = 'cell';
    input.name = campos[0];       
    input.setAttribute('value', celula.firstChild.nodeValue);    
    input.onkeypress = function (evt){
                       if (evt.keyCode==13){ 
                          if (this.value!=oldvalue) {
                            if( confirm("Guarda alterações ?")) {
                              setCell(this.parentNode,this.value,oldvalue); 
                            } else {
                              setCell(this.parentNode,oldvalue,oldvalue);
                            }
                          } else {
                            setCell(this.parentNode,oldvalue,oldvalue);
                          }
                       }
                       if (evt.keyCode==27){
                          setCell(this.parentNode,oldvalue,oldvalue);
                       } 
                  };
    input.onblur  = function (evt) { 
                          if (this.value!=oldvalue) {
                            if( confirm("Guarda alterações ?")) {
                              setCell(this.parentNode,this.value,oldvalue); 
                            } else {
                              setCell(this.parentNode,oldvalue,oldvalue);
                            }
                        } else {
                          setCell(this.parentNode,oldvalue,oldvalue);
                        }
                    };
    input.onclick = function (evt) {
                      evt.cancelBubble = true;
                      if (evt.stopPropagation)
                      evt.stopPropagation();
                  };
    celula.replaceChild(input,celula.firstChild);
    input.focus();
    input.select();
    }
  } else {
    oldvalue = celula.firstChild.nodeValue              // texto apresentado
    var input=document.createElement('select');
    input.className = 'cell';
    tabela = campos[0].split(".");    
    // cria as op¦ºes do select
    s = getList('sys/listagem.php?tabela='+tabela[0]+'&campo1='+campos[2]+'&campo2='+campos[0]);
    s = s.substr(0,s.length-1);
    
    opcoes = s.split('|');
    for (i=0;i<(opcoes.length);i+=2){                   // cria as op¦ºes do select
      var option = document.createElement('option');
      option.value = opcoes[i];
      if (opcoes[i+1] == oldvalue){
        option.setAttribute('selected','true');  
      }
      option.appendChild(document.createTextNode(opcoes[i+1]));
      input.appendChild(option);
    }  
    input.onkeypress = function (evt){
                       if (evt.keyCode==13){ 
                          setCell(this.parentNode,this.value,oldvalue);
                       }
                       if (evt.keyCode==27){
                          setCell(this.parentNode,oldvalue,oldvalue);
                       } 
                  };        
    input.onblur = function (evt) { setCell(this.parentNode,this.value,oldvalue); };
    input.onclick = function (evt) {
                      evt.cancelBubble = true;
                      if (evt.stopPropagation) evt.stopPropagation();
                  };
    celula.replaceChild(input,celula.firstChild);       // muda o conteudo da c+lula pelo select
    input.focus();
  }
}
// ---------------------------------------------------------------------------------------
// substitui a inputbox text ou select pelo texto 
setCell=function(node,valor,olvalor){
var campos = node.id.split('|');
var tabela = campos[1].split(".");

  if (campos[0]==campos[1]){
    var cellText = document.createTextNode(valor);
  } else {
    var cellText = document.createTextNode(node.firstChild.options[node.firstChild.selectedIndex].text);
  }
  // muda o input pelo novo texto
  node.replaceChild(cellText,node.firstChild);
  // se houve altera¦Êo do valor do campo, actualiza na BD
  if (valor!=olvalor){
    connect('sys/update.php?chave='+node.parentNode.id+'&tabela='+tabela[0]+'&campo='+campos[1]+'&valor='+valor);
  } 
}
// ---------------------------------------------------------------------------------------
getList=function(pageurl){
	if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
		try {
		lista_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
			lista_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
		lista_request = new XMLHttpRequest()
	else
		return false
	
	lista_request.onreadystatechange=function(){	
    if (lista_request.readyState == 4 && (lista_request.status==200)){		            
       return lista_request.responseText;
    }
  }
  lista_request.open('GET', pageurl, false)  // pedido sincrono ao servidor
	lista_request.send(null)                   // nÊo envia nada ao servidor
	return lista_request.responseText;         // devolve o resultado 
}
// ---------------------------------------------------------------------------------------
// Apaga uma linha da DBTable
apagaLinha=function(node){    
  if ( confirm('Apaga a registo da tabela?')) {
    connect('sys/delete.php?chave='+node.parentNode.parentNode.id+'&table='+node.parentNode.id,false);
    connect(lastPageURL,node.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id,false);   // carrega a p¯gina j¯ com o registo apagado    
  }
}
// ---------------------------------------------------------------------------------------
// Adiciona uma linha
dbAdd = function(node,filtro){
  var s = "("; var f="(";    
  var filtros = new Array();  
  if (filtro){
    filtro = filtro.split(",");
    for (i=0;i<filtro.length;i++){
      filtros[i] = filtro[i].split("=");
    }
  }
  if (confirm('Adiciona um novo registo?')) {
//    alert(filtro)
    if (filtro!=null){
    // Adiciona os filtros ao valores a inserir
      for (j=0;j<filtros.length;j++){
        s += filtros[j][0]+",";
        f += "'"+filtros[j][1]+"',";       
      }
    }

    for(i=0; i<document.addForm.elements.length; i++){     
      // verifica se o campo existe na lista de campos do filtro
      existe=0;
      for (j=0;j<filtros.length;j++){
        if (document.addForm.elements[i].name == filtros[j][0]){
          existe = 1;
        }
      }
      if (!existe){
        // verifica se j¯ existe o campo    
        if (s.search(document.addForm.elements[i].name)<0){
          s += document.addForm.elements[i].name+",";
          if (document.addForm.elements[i].value==''){
            f += "null,";
          } else {
            f += "'"+document.addForm.elements[i].value+"',";
          }
        }
      }  
    }    
    s = s.substr(0,s.length-1)+")";
    f = f.substr(0,f.length-1)+")"; 
// alert('sys/adiciona.php?table='+node.parentNode.id+'&campos='+s+'&valores='+f)   
    connect('sys/adiciona.php?table='+node.parentNode.id+'&campos='+s+'&valores='+f,false);
// carrega a página já com o novo registo
    connect(lastPageURL,node.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id,false);   
  }
}

// ---------------------------------------------------------------------------------------
// Adiciona uma linha
dbPrint = function(node,filtro,header,widths){
//  alert(header);
  var s = "("; var f="(";    
  var filtros = new Array();  
  if (filtro){
    filtro = filtro.split(",");
    for (i=0;i<filtro.length;i++){
      filtros[i] = filtro[i].split("=");
    }
  }
  if (confirm('Imprimir dados?')) {
    //alert(filtro)
    if (filtro!=null){
    // Adiciona os filtros ao valores a inserir
      for (j=0;j<filtros.length;j++){
        s += filtros[j][0]+",";
        f += "'"+filtros[j][1]+"',";       
      }
    }

    for(i=0; i<document.addForm.elements.length; i++){     
      // verifica se o campo existe na lista de campos do filtro
      existe=0;
      for (j=0;j<filtros.length;j++){
        if (document.addForm.elements[i].name == filtros[j][0]){
          existe = 1;
        }
      }
      if (!existe){
        // verifica se já existe o campo    
        if (s.search(document.addForm.elements[i].name)<0){
          s += document.addForm.elements[i].name+",";
          if (document.addForm.elements[i].value==''){
            f += "null,";
          } else {
            f += "'"+document.addForm.elements[i].value+"',";
          }
        }
      }  
    }    
    s = s.substr(0,s.length-1)+")";
    f = f.substr(0,f.length-1)+")";
    window.open('utils/imprimir.php?id='+filtro+'&header='+header+'&widths='+widths); 
//alert('sys/adiciona.php?table='+node.parentNode.id+'&campos='+s+'&valores='+f)   
//    connect('sys/adiciona.php?table='+node.parentNode.id+'&campos='+s+'&valores='+f,false);
// carrega a página já com o novo registo
//    connect(lastPageURL,node.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id,false);   
  }
}

function naviGator(name,url,table,key,order,divId,id){           
// No caso de existir um naviGator, cria dois DIVs dinâmicamente
// resta saber como funciona com dois naviGators simultaneamente
      var newdiv = document.createElement('div');
      var contentDiv = document.createElement('div'); 
      newdiv.setAttribute('id',name);
      contentDiv.setAttribute('id',name+'_content');
      
      this.url    = url;
      this.currId = id;
      this.table  = table;
      this.key    = key;
      this.order  = order;
      this.divId  = divId;      
      this.navega = function(dir){                      
                      var urli = "sys/proxid.php?valor="+this.currId+"&key="+this.key+"&table="+this.table;
                      this.currId = getList(urli+"&sentido="+dir);
                      urli =  this.url+"?id="+this.currId;
                      connect(urli,document.getElementById(this.divId).getElementsByTagName('div')[1].id,false);  
                    }
      document.getElementById(this.divId).innerHTML = '';
      newdiv.innerHTML = "<a href='#' class='toolbotao' onclick='"+name+".navega( 0);'><img src='imgs/icons/prev.gif' border=0><img src='imgs/icons/prev.gif' border=0></a>"+
      "<a href='#' class='toolbotao' onclick='"+name+".navega(-1);'><img src='imgs/icons/prev.gif' border=0></a>"+
      "<a href='#' class='toolbotao' onclick='"+name+".navega( 1);'><img src='imgs/icons/next.gif' border=0></a>"+                    
      "<a href='#' class='toolbotao' onclick='"+name+".navega( 2);'><img src='imgs/icons/next.gif' border=0><img src='imgs/icons/next.gif' border=0></a>"
      document.getElementById(divId).appendChild(newdiv);
      document.getElementById(divId).appendChild(contentDiv);
}

// ---------------------------------------------------------------------------------------
// Mostra os registos anteriores da DBTable
dbFirst=function(node){    
    oldPageURL = lastPageURL.split("?");       // separa endere¦o dos parametros
    var s = oldPageURL[0]+"?"; 
    pageParams = oldPageURL[1].split("&")      // separa os v¯rios parametros
    for (i=0;i<pageParams.length;i++){
      if (pageParams[i].indexOf('inicial=')!=-1){
        campo = pageParams[i].split("="); 
        campo[1] = 0;
        if (campo[1]<0) {campo[1] = 0};            // protec¦Êo para nÊo passar do inicio do campo
        pageParams[i] = campo[0]+"="+campo[1];
        break;
      }      
    }
    for (i=0;i<pageParams.length;i++){
      s += pageParams[i]+"&";
    }
    s = s.substr(0,s.length-1);
    //alert(s);
    //alert(oldPageURL[0]+"="+oldPageURL[1])    
    connect(s,node.parentNode.id);// carrega a p¯gina com novos limites    
}
// ---------------------------------------------------------------------------------------
// Mostra os registos anteriores da DBTable
dbPrev=function(node){   
    oldPageURL = lastPageURL.split("?");       // separa endere¦o dos parametros
    var s = oldPageURL[0]+"?";     
    pageParams = oldPageURL[1].split("&")      // separa os v¯rios parametros
    for (i=0;i<pageParams.length;i++){      
      if (pageParams[i].indexOf('inicial=')!=-1){
        campo = pageParams[i].split("="); 
        campo[1] = parseInt(campo[1]) - 15;
        if (campo[1]<0) {campo[1] = 0};            // protec¦Êo para nÊo passar do inicio do campo
        pageParams[i] = campo[0]+"="+campo[1];
        break;
      }
    }
    for (i=0;i<pageParams.length;i++){
      s += pageParams[i]+"&";
    }
    s = s.substr(0,s.length-1);
//    alert(s);
//    alert(oldPageURL[0]+"="+oldPageURL[1])    
    connect(s,node.parentNode.id);// carrega a p¯gina com novos limites    
}
// ---------------------------------------------------------------------------------------
// Mostra os prÁximos registos do DBTable
dbProx=function(maximo,node){ 
    oldPageURL = lastPageURL.split("?");         // separa endere¦o dos parametros
    var s = oldPageURL[0]+"?"; 
    
    pageParams = oldPageURL[1].split("&")        // separa os v¯rios parametros
    for (i=0;i<pageParams.length;i++){
      if (pageParams[i].indexOf('inicial=')!=-1){
        campo = pageParams[i].split("="); 
        campo[1] = parseInt(campo[1]) + 15;
        if (campo[1]>maximo) { campo[1] -= 15};  // protec¦Êo para nÊo passar do inicio do campo
        pageParams[i] = campo[0]+"="+campo[1];
        break;
      }
    }
    for (i=0;i<pageParams.length;i++){
      s += pageParams[i]+"&";
    }
    s = s.substr(0,s.length-1);
//    alert(s);
//    alert(oldPageURL[0]+"="+oldPageURL[1])    
    connect(s,node.parentNode.id);// carrega a p¯gina com novos limites    
}
// ---------------------------------------------------------------------------------------
// Mostra os prÁximos registos do DBTable
dbLast=function(maximo,node){    
    oldPageURL = lastPageURL.split("?");       // separa endere¦o dos parametros
    var s = oldPageURL[0]+"?"; 
    pageParams = oldPageURL[1].split("&")      // separa os v¯rios parametros
    for (i=0;i<pageParams.length;i++){
      if (pageParams[i].indexOf('inicial=')!=-1){
        campo = pageParams[i].split("="); 
        campo[1] = 15*Math.floor(maximo/15);
        pageParams[i] = campo[0]+"="+campo[1];
        break;
      }      
    }
    for (i=0;i<pageParams.length;i++){
      s += pageParams[i]+"&";
    }
    s = s.substr(0,s.length-1);
    //alert(oldPageURL[0]+"="+oldPageURL[1]) 
//    alert(s);   
    connect(s,node.parentNode.id);// carrega a p¯gina com novos limites    
}
// ---------------------------------------------------------------------------------------
// Ordena a dbTable pelo registo seleccionado
ordenaCampo=function(node){
    oldPageURL = lastPageURL.split("?");       // separa endere¦o dos parametros
    var s = oldPageURL[0]+"?"; 
    pageParams = oldPageURL[1].split("&")      // separa os v¯rios parametros
    for (i=0;i<pageParams.length;i++){
      if (pageParams[i].indexOf('ordem=')!=-1){
        campo = pageParams[i].split("="); 
        campo[1] = node.id;
        pageParams[i] = campo[0]+"="+campo[1];
        break;
      }      
    }
    for (i=0;i<pageParams.length;i++){
      s += pageParams[i]+"&";
    }
    s = s.substr(0,s.length-1);        
    // carrega a p¯gina com novos limites
    connect(s,node.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id);    
}
// ----------------------------------------------------------------------------------------------------------------
// chamada da função AJAX
connect=function(pageurl,divId,sinc,novo){
  if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else
		return false  
	page_request.onreadystatechange=function(){	
    // imagem de LoadStatus sempre que se carrega uma página via AJAX
    if (divId){ document.getElementById(divId).innerHTML=loadstatustext; }
    if (page_request.readyState == 4 && (page_request.status==200)){		  
      if (divId){        
        if (novo){
          document.getElementById().innerHTML = ''; 
        }
        lastPageURL = pageurl;
        document.getElementById(divId).innerHTML=page_request.responseText;
        udf_init(pageurl,novo);     // user defined function para inicializar objectos javascript;
      }     
    }
  }
  // se não for especificada, a chamada é assincrona (true), senão é sincrona (false)
  if (sinc){ aSinc = sinc } else { aSinc = true }
  page_request.open('GET', pageurl, aSinc)
	page_request.send(null)
}
// ----------------------------------------------------------------------------------
// função definida pelo utilizador para inicialização dos objectos Javascript
// existentes na aplicação.
udf_init = function(texto,executa){
 
  // upload de fotografias
/*  if (document.getElementById('upload_target')){
    init();    
  } 
  if (document.getElementById('map_canvas')){
    initialize(document.getElementById('latitude').value, document.getElementById('longitude').value,"map_canvas");
//  initialize(40.605715,-7.765951, "map_canvas")
  }  */
  // inicialização do editor
/*  if (document.getElementById('elm2')){
    initTinyMCE();                    
  }
*/
  // inicialização do editor
  if (document.getElementById('area1')){
//new nicEditor({iconsPath : 'imgs/icons/nicEditorIcons.gif'}).panelInstance('area1');
new nicEditor({maxHeight : 220}).panelInstance('area1');
    //new nicEditor({iconsPath : 'imgs/icons/nicEditorIcons.gif'}).panelInstance('area1');                    
  }
  if (document.getElementById('db_upload_target')){
    init_db_upload();
  }
/*  if ((document.getElementById('leftcolumn')) && (executa)){
    makeTree("moduls/turmas.php?ordem=id_curso&inicial=0","leftcolumn",true);  
  }                                                                            */
  // inicialização do slider de fotos                
  if (document.getElementById('slider1')){                           
    initGlider();    
  }   
}
// ----------------------------------------------------------------------------------
// Carrega uma imagem e adiciona à base de dados
addImagem = function(idEntidade,divId){
  connect('sys/uploader.php?id='+idEntidade,divId,false);
}
// Inicialização do Glider
initGlider = function(){
featuredcontentslider.init({
	           id: "slider1",  //id of main slider DIV
	           contentsource: ["inline", ""],  //Valid values: ["inline", ""] or ["ajax", "path_to_file"]
	           toc: "#increment",  //Valid values: "#increment", "markup", ["label1", "label2", etc]
	           nextprev: ["Ant.", "Prox.","Eliminar"],  //labels for "prev" and "next" links. Set to "" to hide.
	           revealtype: "click", //Behavior of pagination links to reveal the slides: "click" or "mouseover"
	           enablefade: [true, 0.3],  //[true/false, fadedegree]
	           autorotate: [true, 5000],  //[true/false, pausetime]	           
	           onChange: function(previndex, curindex){  //event handler fired whenever script changes slide
		          //previndex holds index of last slide viewed b4 current (1=1st slide, 2nd=2nd etc)
		          //curindex holds index of currently shown slide (1=1st slide, 2nd=2nd etc)
	           }
          })
}
// ---------------------------------------------------------------------------------------
// Desenha uma treeView por Ajax
function makeTree(pageurl,divId,sinc){
    var newdiv = document.createElement('div');
    var b_contDiv = document.createElement('div'); 
    var contentDiv = document.createElement('div');
    newdiv.setAttribute('id','tree_lat');
    newdiv.setAttribute('class','tree_lat_class');    
    b_contDiv.setAttribute('id','grayBG');
    b_contDiv.setAttribute('class','grayBox');
    b_contDiv.setAttribute('style','display:none;');
    contentDiv.setAttribute('id','LightBox1');
    contentDiv.setAttribute('class','box_content');
    contentDiv.setAttribute('style','display:none;');   
 
	if (window.ActiveXObject){
		try { tree_request = new ActiveXObject("Msxml2.XMLHTTP") } 
		catch (e){
			try{ tree_request = new ActiveXObject("Microsoft.XMLHTTP")}
			catch (e){}
		}
	} else if (window.XMLHttpRequest)
		  tree_request = new XMLHttpRequest()
	  else return false

	tree_request.onreadystatechange=function(){	
    if (divId){ document.getElementById(divId).innerHTML=loadstatustext; }
    if (tree_request.readyState == 4 && (tree_request.status==200)){		  
      if (divId){
        s = '<h4>Mapa do Site</h4><div class="dtree" style="padding-left:20px;"><p><a href="javascript: d.openAll();">abrir</a> | <a href="javascript: d.closeAll();">fechar</a></p>';
        linhas = tree_request.responseText.split('<br>');
        d=new dTree('d');
        d.add(0,-1,'Menu');
        for (i=0;i<linhas.length;i++){
          valor = linhas[i].split('|');
//          d.add(valor[0],valor[1],valor[2],"javascript:connect('"+valor[3]+"','tree_lat_content',true)");
          d.add(valor[0],valor[1],valor[2],"javascript:connect('"+valor[3]+"','LightBox1',true);displayHideBox('1');");
        }  
        newdiv.innerHTML=s+d+'</div>'; 
        document.getElementById(divId).innerHTML = '<br>';
	      document.getElementById(divId).appendChild(newdiv);
        document.getElementById(divId).appendChild(b_contDiv);
        document.getElementById(divId).appendChild(contentDiv);        
//      document.getElementById(divId).innerHTML=tree_request.responseText+'</div>';
      }     
    }
  }
  if (sinc){ aSinc = sinc } else { aSinc = true }
  tree_request.open('GET', pageurl, aSinc)
	tree_request.send(null)

}
// ---------------------------------------------------------------------------------------
function formatField(num, isHour){
if (typeof isHour!="undefined"){ //if this is the hour field
//var hour=(num>12)? num-12 : num
var hour=num
return (hour==0)? 12 : hour
}
return (num<=9)? "0"+num : num//if this is minute or sec field
}
// ---------------------------------------------------------------------------------------
function checkform(form)
{
  // see http://www.thesitewizard.com/archive/validation.shtml
  // for an explanation of this script and how to use it on your
  // own website

  // ** START **
if (form.nome.value == "") {
    alert( "Introduza o seu Nome." );
    form.nome.focus();
    return false ;
  }
if (form.email.value == "") {
    alert( "Introduza o seu E-mail." );
    form.email.focus();
    return false ;
  } 
if (form.assunto.value == "") {
    alert( "Introduza o assunto." );
    form.assunto.focus();
    return false ;
  }  
if (form.texto.value == "") {
    alert( "Introduza o texto." );
    form.texto.focus();
    return false ;
  }  
  // ** END **
  return true ;
}
// ---------------------------------------------------------------------------------------
function setdiaActivo(nodo){ 
  document.getElementsByClassName('activo')[0].className = 'calend';
  nodo.className = 'activo';
}
// ---------------------------------------------------------------------------------------
// Inicializa o GoogleMaps
function initialize(x,y,map_area) {
  var myLatlng = new google.maps.LatLng(x,y);
  var myOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById(map_area), myOptions);

  var image = 'imgs/icons/beachflag.png';
  var myLatLng = new google.maps.LatLng(x, y);
  var beachMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
  });
}
//-----------------------------------------------------------------------------------------
// LightBox
function displayHideBox(boxNumber){
    if(document.getElementById("LightBox"+boxNumber).style.display=="none") {
        document.getElementById("LightBox"+boxNumber).style.display="block";
        document.getElementById("grayBG").style.display="block";
    } else {
        document.getElementById("LightBox"+boxNumber).style.display="none";
        document.getElementById("grayBG").style.display="none";
    }
}


function initTinyMCE(){ 
  tinyMCE.init({
		// General options
		mode : "exact",
		elements : "elm2",
		theme : "advanced",
		skin : "o2k7",
		plugins : "lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,autosave",

		// Theme options
		theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,

		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}
// NicEditor - exemplos
        // new nicEditor({iconsPath : 'imgs/nicEditorIcons.gif'}).panelInstance('area1');                    
        // bkLib.onDomLoaded(function() {
        //	new nicEditor().panelInstance('area1');
        //	new nicEditor({fullPanel : true}).panelInstance('area2');
        //	new nicEditor({iconsPath : '../nicEditorIcons.gif'}).panelInstance('area3');
        //	new nicEditor({buttonList : ['fontSize','bold','italic','underline','strikeThrough','subscript','superscript','html','image']}).panelInstance('area4');
        //	new nicEditor({maxHeight : 100}).panelInstance('area5');
        //});


//------------------------------------------------------------------------------
function menuAdd(id,parent){
  if (confirm('Adiciona novo registo ao \n menu '+parent+'?')==true){
    connect('moduls/menus_add.php?id='+id,'corpo',true);
    makeTree('moduls/menus_admin.php','corpo',true);
  }
}

function menuDel(id, hc){
  if (hc){
    alert('O menu tem sub-menus e não pode ser eliminado.\n'+
          'Elimine primeiro os sub-menus...');
  } else {
    if (confirm('Elimina o registo?')==true){
      connect('moduls/menus_del.php?id='+id,'corpo',true);
      makeTree('moduls/menus_admin.php','corpo',true);
    }
  }  
}
