/****************************************************/
/*
/* Biblioteca geral de variáveis e funções www.uma.pt
/* Leonel S. da Palma 28/02/2007
/* webmaster@uma.pt
/*
/****************************************************/

//Javascript Exteriores - Atenção à posição relativa
function include_dom(script_filename)         {var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); html_doc.appendChild(js); return false; }
//var external_js = new Array('../../javascript/hydra_js.js', '../../javascript/brwsniff_mini.js', '../../javascript/xml_charts_mini.js', '../../javascript/ieupdate.js', '../../javascript/expander_2009/animatedcollapse.js', '../../javascript/dtree/dtree.js');
//var external_js = new Array('../../javascript/hydra_js-min.js');
var external_js = new Array();
for (var jscript in external_js) {include_dom(external_js[jscript]);}

   //Componentes da Hydra -> Início
   //Variáveis Hydra
   var cor_zebra_1 = '#FFFFF0';
   var cor_zebra_2 = '#0AEEF2';
   var janela_maximizada = false;
   var template_anterior = "";
   //Tabuladores
   var JS_TPESQ_ACT = '';
   var JS_TPESQ_ANT = '';
   var JS_NV_TAB_ACT = '';
   var interface_de_tabuladores_corrente = '';
// Componentes da Hydra -> Fim




//Variáveis

var JS_NV_EAGR_ACT = '';

var largura = screen.width;
var lst_destaques_left_right = 0;
var imagem_aleatoria_activa;
var numero_de_imagens = 10;
var numero_total_de_imagens_de_canto = 5;
var SpecialWord = "mail"; SpecialUrl = "http://www.uma.pt/horde"; SpecialLetter = 0;

//
//Funções
//

 function hasClass(obj)                        {var result = false;if (obj.getAttributeNode("class") != null) {result = obj.getAttributeNode("class").value;} return result;}
 function coloriza(id, corImpar, corPar)       {var even = false; var table = id; if (! table) { return; } var tbodies = table.getElementsByTagName("tbody"); for (var h = 0; h < tbodies.length; h++) { var trs = tbodies[h].getElementsByTagName("tr"); for (var i = 0; i < trs.length; i++) { if (! hasClass(trs[i]) && ! trs[i].style.backgroundColor) { var tds = trs[i].getElementsByTagName("td"); for (var j = 0; j < tds.length; j++) { var mytd = tds[j]; if (! mytd.style.backgroundColor) { mytd.style.backgroundColor =even ? corPar : corImpar; } } } even =  ! even; }}}
 function coloriza_tabelas()                   {var classe_a_colorir = 'tbl_zebra'; var tabelas = document.getElementsByTagName('table'); for ( x = 0; x < tabelas.length ; x++) { if (hasClass(tabelas[x]) == classe_a_colorir) coloriza(tabelas[x], cor_zebra_1, cor_zebra_2); }}
 function FechaJanela()                        {self.opener = this; self.close() /* http://www.ssi-developer.net/htaccess/htaccess_logout.shtml */}

 // Torna visível a ampulheta
 function liga_ampulheta ()                    {document.getElementById('ampulheta').style.display = 'block'; if (document.all) for (var i=0;i < document.all.length; i++) document.all(i).style.cursor = 'wait';}
 function fecha_janela()                       {self.opener = this;self.close()}
 function st(texto)                            {status=texto;}

 // Para seleccionar as checkboxes de um form
 function selectAll(formObj, isInverse)        {for (var i=0;i < formObj.length;i++) {fldObj = formObj.elements[i];if (fldObj.type == 'checkbox')  {if(isInverse) fldObj.checked = (fldObj.checked) ? false : true; else fldObj.checked = true;}}}

 //Window
 function openCenteredWindow(url, name, width, height, status, scrollbars, moreProperties, openerName) {var x = 0;var y = 0;if (screen) x = (screen.availWidth - width) / 2;if (screen) y = (screen.availHeight - height) / 2;if (!status) status == '';if (!openerName) openerName == '';var reference = openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName);  return reference;}

//
// CSS
//
function setActiveStyleSheet(title)           {var i, a, main;for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {a.disabled = true;if(a.getAttribute("title") == title) a.disabled = false;}}}
function getActiveStyleSheet()                {var i, a;for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");}return null;}
function getPreferredStyleSheet()             {var i, a;for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {if(a.getAttribute("rel").indexOf("style") != -1&& a.getAttribute("rel").indexOf("alt") == -1&& a.getAttribute("title"))return a.getAttribute("title");}return null;}
function changeSheets(whichSheet)             {whichSheet=whichSheet-1;if(document.styleSheets){var c = document.styleSheets.length;for(var i=0;i<c;i++){if(i!=whichSheet){document.styleSheets[i].disabled=true;}else{document.styleSheets[i].disabled=false;}}}}

//
//Cookies
//
function createCookie(name,value,days)        {if (days){var date = new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires = "; expires="+date.toGMTString();}else var expires = "";document.cookie = name+"="+value+expires+"; path=/";}
function readCookie(name)                     {var nameEQ = name + "=";var ca = document.cookie.split(';');for(var i=0;i < ca.length;i++){var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length);if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);}return null;}
function eraseCookie(name)                    {createCookie(name,"",-1);}

// BDL
function BDL() { var ua = navigator.userAgent.toLowerCase(); this.ua = ua; this.isGecko = (ua.indexOf('gecko') != -1); this.isMozilla = (this.isGecko && ua.indexOf("gecko/") + 14 == ua.length); this.isNS = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) ); this.isIE = ( (ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1) ); this.isOpera = (ua.indexOf("opera") != -1); this.isKonqueror = (ua.indexOf("konqueror") != -1);this.isIcab = (ua.indexOf("icab") != -1); this.isAol = (ua.indexOf("aol") != -1);this.isWebtv = (ua.indexOf("webtv") != -1);this.isOmniweb   = (ua.indexOf("omniweb") != -1);this.isDreamcast   = (ua.indexOf("dreamcast") != -1);this.isIECompatible = ( (ua.indexOf("msie") != -1) && !this.isIE);this.isNSCompatible = ( (ua.indexOf("mozilla") != -1) && !this.isNS && !this.isMozilla);this.versionMinor = parseFloat(navigator.appVersion);if (this.isNS && this.isGecko) {this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('/') + 1 ) );}else if (this.isIE && this.versionMinor >= 4) {this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );}else if (this.isOpera) {if (ua.indexOf('opera/') != -1) {this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera/') + 6 ) );}else {this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera ') + 6 ) );}}else if (this.isKonqueror) {this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );}else if (this.isIcab) {if (ua.indexOf('icab/') != -1) {this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab/') + 6 ) );}else {this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab ') + 6 ) );}}else if (this.isWebtv) {this.versionMinor = parseFloat( ua.substring( ua.indexOf('webtv/') + 6 ) );}this.versionMajor = parseInt(this.versionMinor);this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );this.isWin   = (ua.indexOf('win') != -1);this.isWin32 = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1) );this.isMac   = (ua.indexOf('mac') != -1);this.isUnix  = (ua.indexOf('unix') != -1 || ua.indexOf('linux') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1);this.isNS4x = (this.isNS && this.versionMajor == 4);this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);this.isNS4up = (this.isNS && this.versionMinor >= 4);this.isNS6x = (this.isNS && this.versionMajor == 6);this.isNS6up = (this.isNS && this.versionMajor >= 6);this.isIE4x = (this.isIE && this.versionMajor == 4);this.isIE4up = (this.isIE && this.versionMajor >= 4);this.isIE5x = (this.isIE && this.versionMajor == 5);this.isIE55 = (this.isIE && this.versionMinor == 5.5);this.isIE5up = (this.isIE && this.versionMajor >= 5);this.isIE6x = (this.isIE && this.versionMajor == 6);this.isIE6up = (this.isIE && this.versionMajor >= 6);this.isIE4xMac = (this.isIE4x && this.isMac);}
var browser = new BDL();
if ((browser.isIE55 || browser.isIE6up) && browser.isWin32) {var pngAlpha = true;var strExt = ".png";} else if ((browser.isGecko) || (browser.isIE5up && browser.isMac) || (browser.isOpera && browser.isWin && browser.versionMajor >= 6) || (browser.isOpera && browser.isUnix && browser.versionMajor >= 6) || (browser.isOpera && browser.isMac && browser.versionMajor >= 5) || (browser.isOmniweb && browser.versionMinor >= 3.1) || (browser.isIcab && browser.versionMinor >= 1.9) || (browser.isWebtv) || (browser.isDreamcast)) {var pngNormal = true;var strExt = ".png";} else {var strExt = ".gif";}var ns = (document.all)?false:true;var browserVersion = parseFloat(navigator.appVersion );

// Opacidade
function OpacityObject(divId, strPath) {  this.id = divId;  this.path = strPath;if (ns){if (browserVersion>=5) {this.layerObject = document.getElementById(divId).style;  } else { this.layerObject = eval("document."+divId);}} else {this.layerObject = eval(divId + ".style");}this.setBackground = od_object_setBackground;}
function od_object_setBackground() {if (pngAlpha) {this.layerObject.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.path+".png', sizingMethod='scale')";} else if (pngNormal) {this.layerObject.backgroundImage = 'url('+this.path+'.png)';} else {this.layerObject.backgroundImage = 'url('+this.path+'.gif)';}}
function od_displayImage(strId, strPath, intWidth, intHeight, strClass, strAlt) {  if (pngAlpha) {document.write('<div style="height:'+intHeight+'px ;width:'+intWidth+'px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+strPath+'.png\', sizingMethod=\'scale\')" id="'+strId+'" class="'+strClass+'"></div>');} else if (pngNormal) {document.write('<img src="'+strPath+'.png" width="'+intWidth+'" height="'+intHeight+'" name="'+strId+'" border="0" class="'+strClass+'" alt="'+strAlt+'" />');} else {document.write('<img src="'+strPath+'.gif" width="'+intWidth+'" height="'+intHeight+'" name="'+strId+'" border="0" class="'+strClass+'" alt="'+strAlt+'" />');}}
function od_rollOver(strId, strColor) {if (pngAlpha) {document.getElementById(strId).style.backgroundColor = strColor;} else {if (document.images && (flag == true)) {document[strId].src = eval(strId + "on.src");}}}
function od_rollOut(strId, strColor) {if (pngAlpha) {document.getElementById(strId).style.backgroundColor = strColor;} else {if (document.images) {document[strId].src = eval(strId + "off.src");}}}

//
//Interface de Teclado
//
function getKey(keyStroke)                    {var which = keyStroke;if ( which == SpecialWord.charAt(SpecialLetter) ) {SpecialLetter++;if (SpecialLetter == SpecialWord.length){alterna_debug_output();SpecialLetter = 0;}} else SpecialLetter = 0;}
function onKeypress(evt)                      {var e = new xEvent(evt); return onKeyEvent(evt, e); }
function onKeyEvent(evt, xe)                  {getKey(String.fromCharCode(xe.keyCode)); }

//
//DEBUG Mode Switch
//
var SpecialWord = "debug"; SpecialLetter = 0;
function alterna_debug_output()               {var cook = readCookie("sem_debug");var stat = "";if (cook == 1) {cook=0;stat = "Debug";} else {cook=1;stat = "No Debug";}createCookie("sem_debug", cook, 365);alert('Hydra Framework\n\nSwitch to ' + stat + ' Mode');window.location.reload( false );}


// Específicas

function limpa(id, excepcao){
 if (document.getElementById(id) && document.getElementById(id).value == excepcao) document.getElementById(id).value = "";
}

function limpa_campo (id, texto_condicao){
  alvo = document.getElementById(id);
  if (alvo.value == texto_condicao) alvo.value = '';
}
                                                     
function carrega() {

}
function cookie_lang_create(){
  createCookie('jfcookie', 'pt', 365);
}
function aleat_css(){
 var numero_de_csss = -1;
 path_relativo_a_raiz = '../../css/chroma_spin/';

 //Final
 var cookie_css = readCookie("css_activo");
 var css_index_cookie = readCookie("css_activo_index");
 if ((cookie_css!=null) || (css_index_cookie!=null)) {
  string_css_final = "<link media='screen' href='" + path_relativo_a_raiz + "chroma_" + css_index_cookie +"/chroma.css' type=text/css rel='stylesheet' title='chroma_" + css_index_cookie + "'>";
  document.write(string_css_final);
  for(css_index=0; css_index<=numero_de_csss; css_index++){
    string_css = "<link media='screen' href='" + path_relativo_a_raiz + "chroma_" + css_index +"/chroma.css' type=text/css rel='stylesheet' title='chroma_" + css_index + "'>";
    document.write(string_css);
  }
 } else {
  css_index_cookie = 0;
  string_css_final = "<link media='screen' href='" + path_relativo_a_raiz + "chroma_" + css_index_cookie +"/chroma.css' type=text/css rel='stylesheet' title='chroma_" + css_index_cookie + "'>";
  document.write(string_css_final);
  createCookie('css_activo', "<link media='screen' href='../../css/chroma_spin/chroma_0/chroma.css' type=text/css rel='stylesheet' title='chroma_0'>", 365);
  createCookie('css_activo_index', 0, 365);
 }
 setActiveStyleSheet("chroma_" + css_index_cookie);
  cookie_lang_create();
}



function vars_GET(vars) {
 if (vars == undefined || '') return false;

 var url = location.href;
 var url_vars = url.split('?')[1];
 if(url_vars) {
  var gets = url_vars.split('&');

  for (var g = 0; g < gets.length; g++)
  {
   var vars_arr = gets[g].split('=');
   var vars_nme = vars_arr[0];
   var vars_val = vars_arr[1];
   vars_val = vars_val == undefined ? '' : vars_val;
   if (vars_nme == vars) return unescape(vars_val);
  }
 }
 return null;
}
/*window.onload = function()
{
var url = location.href;
var gets = url.split('?')[1];
var vars_each = gets.split('&');

for (var i = 0; i < vars_each.length; i++)
{
var vars = unescape(vars_each[i].split('=')[0]);
var vars_f = unescape(vars_each[i].split('=')[1]);

if (vars_each[i].indexOf('=') == -1)
{
eval(vars + '();');
}
else
{
eval (vars + '(\'' + vars_f + '\');');
}
}
}
*/
// After the page loads it would run the function you requested, example:
// <a href="?functionname">Link</a>
// Would start the JavaScript function: functionname(), and
// <a href="?functionname=text">Link</a>
// Would start the JavaScript function: functionname('text')


function act_css(css_index){
  if (imagem_aleatoria_activa) {
    proxima = imagem_aleatoria_activa.valueOf();
    proxima++;
    if (proxima>numero_total_de_imagens_de_canto) proxima = 0;
  } else {
    proxima = 0;
  }
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
  strCookie = proxima;
  createCookie('ultima_imagem_activa', strCookie, 365);

  path_relativo_a_raiz = '../../css/chroma_spin/';
  string_css = "<link media='screen' href='" + path_relativo_a_raiz + "chroma_" + css_index +"/chroma_mini.css' type=text/css rel='stylesheet' title='chroma_" + css_index + "'>";
  createCookie('css_activo', string_css, 365);
  createCookie('css_activo_index', css_index, 365);
  setActiveStyleSheet('chroma_' + css_index);
}

function cria_div_alterna_direita_esquerda(inicio_ou_fim) {
/*  if (inicio_ou_fim==1) {*/
  if (inicio_ou_fim==2) {
    switch (lst_destaques_left_right++%2) {
    case 0: document.write('<div class="float_right" style="clear:right;margin-left:10px;margin-bottom:10px;">'); break;
    case 1: document.write('<div class="float_left" style="clear:right;margin-right:10px;margin-bottom:10px;">'); break;
    }
/*  } else if (inicio_ou_fim==0){ */
  } else if (inicio_ou_fim==2){
    document.write("</div>");
  }
}

function esconde_div_doc_gen(){ document.getElementById('div_doc_gen').style.display='none'; }
function mostrarlayer(nome_layer) {estilo = document.getElementById(nome_layer).style.display; estilo == "block" ? document.getElementById(nome_layer).style.display = "none" : document.getElementById(nome_layer).style.display = "block";}

function insere_objecto_flash(){

  path_relativo_a_raiz = '../../imagens/headers/intro1/';
  numero_de_imagens = 10;
  indice = Math.floor(Math.random()*numero_de_imagens);

  // Objecto que o Flash da Barra de Topo deverá carregar
  string_objecto_flash = path_relativo_a_raiz + "intro_" + indice + ".jpg";

  css_index = readCookie("css_activo_index");
  if (css_index) {
   switch (css_index)
   {
    case '0':
           string_objecto_flash = "../../flash/headers/agua.swf";
           string_objecto_flash = "../../flash/headers/header_20_anos_forced.swf";
           break;
           
    case '1':
           string_objecto_flash = "../../flash/headers/outono_2007.swf";
           break;
    case '2':
           string_objecto_flash = "../../flash/headers/outono_2007.swf";
           break;
    case '3':
           string_objecto_flash = "../../flash/headers/outono_2007.swf";
           break;
    case '4':
           string_objecto_flash = "../../flash/headers/agua.swf";
           break;
    case '5':
           string_objecto_flash = "../../flash/headers/agua.swf";
           break;
   }
  }
  
  //string_objecto_flash = "";

            // Modo com filem de pre-load e conteudo seleccionado pelo numero do CSS
            //  html_objecto ="<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='977' height='85' id='random_img' align='middle'><param name='allowScriptAccess' value='always' /><param name='movie' value='../../flash/random_img.swf?imagem_a_carregar=" + string_objecto_flash + "' /><param name='quality' value='high' /><param name='wmode' value='transparent' /><param name='bgcolor' value='#ffffec' /><embed src='../../flash/random_img.swf?imagem_a_carregar=" + string_objecto_flash + "' wmode='transparent' quality='high' bgcolor='#ffffec' width='977' height='85' name='random_img' align='middle' allowScriptAccess='always' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /><NOEMBED>Animação cosmética em Abode Flash</NOEMBED></object>";
            html_objecto ="<div style='position: absolute; z-index: 1000; margin-left: -977px;'><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' width='977' height='85' id='header_20_anos' align='middle'><param name='allowScriptAccess' value='sameDomain' /><param name='allowFullScreen' value='false' /><param name='movie' value='../../flash/headers/header_20_anos_forced.swf' /><param name='quality' value='high' /><param name='bgcolor' value='#1a8dbf' /><param name='wmode' value='tranparent' /> <embed src='../../flash/headers/header_20_anos_forced.swf' wmode='transparent' quality='high' bgcolor='#1a8dbf' width='977' height='85' name='header_20_anos' align='middle' allowScriptAccess='sameDomain' allowFullScreen='false' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /><noembed>Animação cosmética em Abode Flash</noembed> </object></div>";

  if (!browser.isUnix) {
   //document.write("<style>#imagens_topo{background: #1a8dbf;}</style>");
   document.write(html_objecto);
  } else {
//   document.write("<style>#imagens_topo{background: #1a8dbf;}</style>");
  }
}

function sem_presenca(){ window.alert("O Núcleo não tem neste momento presença na Internet, volte a tentar em breve... "); }

function switch_de_tabuladores(){
 if(JS_NV_EAGR_ACT)
 {
  switch (JS_NV_EAGR_ACT)
  {

  // Licenciaturas  

      case 'EAGR_CURSOLICENC':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabPlano');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabPlano');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabPlano');
             break;

      case 'EAGR_CURSO_ACESSO':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAcesso');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAcesso');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabAcesso');
             break;

      case 'EAGR_CURSO_MATRICULADOS':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMatriculados');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMatriculados');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabMatriculados');
             break;

      case 'EAGR_CURSO_DIPLOMADOS':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabDiplomados');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabDiplomados');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabDiplomados');
             break;

      case 'EAGR_CURSO_FUNCIONARIOS':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabFuncionarios');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabFuncionarios');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabFuncionarios');
             break;

      case 'EAGR_CURSO_MEIOS':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMeios');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMeios');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabMeios');
             break;

      case 'EAGR_CURSO_AVALIACAO':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');
             break;

  // Mestrados

      case 'EAGR_CURSOMEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabPlano');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabPlano');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabPlano');
             break;

      case 'EAGR_CURSO_ACESSO_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAcesso');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAcesso');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabAcesso');
             break;

      case 'EAGR_CURSO_MATRICULADOS_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMatriculados');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMatriculados');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabMatriculados');
             break;

      case 'EAGR_CURSO_DIPLOMADOS_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabDiplomados');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabDiplomados');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabDiplomados');
             break;

      case 'EAGR_CURSO_FUNCIONARIOS_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabFuncionarios');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabFuncionarios');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabFuncionarios');
             break;

      case 'EAGR_CURSO_MEIOS_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMeios');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMeios');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabMeios');
             break;

      case 'EAGR_CURSO_AVALIACAO_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');
             break;
  // Ciência e Tecnologia

      case 'EAGR_CENTROINFOGERAL':
             dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroInfoGeral');
             setTimeout("dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroInfoGeral');" , 1);
             nv_tab_act('FRM_TAB_CENTRO_LINKS_TabCentroInfoGeral');
             break;

      case 'EAGR_CENTROINVESTIGADORES':
             dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroInvestigadores');
             setTimeout("dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroInvestigadores');" , 1);
             nv_tab_act('FRM_TAB_CENTRO_LINKS_TabCentroInvestigadores');
             break;

      case 'EAGR_CENTROPUBLICACOES':
             dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroPublicacoes');
             setTimeout("dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroPublicacoes');" , 1);
             nv_tab_act('FRM_TAB_CENTRO_LINKS_TabCentroPublicacoes');
             break;

      case 'EAGR_CENTROPRESTSERVICOS':
             dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroPrestServicos');
             setTimeout("dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroPrestServicos');" , 1);
             nv_tab_act('FRM_TAB_CENTRO_LINKS_TabCentroPrestServicos');
             break;

      case 'EAGR_CENTRONOTICIAS':
             dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroNoticias');
             setTimeout("dhtml.cycleTab('tab_FRM_TAB_CENTRO_LINKS_TabCentroNoticias');" , 1);
             nv_tab_act('FRM_TAB_CENTRO_LINKS_TabCentroNoticias');
             break;

      case 'EAGR_CURSO_MEIOS_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMeios');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabMeios');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabMeios');
             break;

      case 'EAGR_CURSO_AVALIACAO_MEST':
             dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');
             setTimeout("dhtml.cycleTab('tab_FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');" , 1);
             nv_tab_act('FRM_CURSO_LINKS_AUTOAVAL_TabAvaliacao');
             break;

  }
 }
}

//AWSTATS misc_tracker_url só para !msie

// if (!browser.isIE) include_dom('/portal/javascript/awstats_misc_tracker.js');

/*
*   propaga_alteracoes(formulario, id_elemento, selected_index);
*   Copia o selected_index de uma SELECT ou RADIO para todos os elementos de um formulário com o mesmo id_elemento
*
*   @param string formulario     - id do formulário que contém os campos para onde propagar as alterações
*   @param string id_elemento    - id dos vários elementos (deverá ser igual em todos os controlos)
*   @param int selected_index    - índice do item seleccionado (será sempre this.selectedIndex)
*
*/
function propaga_alteracoes(formulario, id_elemento, selected_index) {
  var s = document.forms[formulario].elements[id_elemento];
  for (var i = 0; i < s.length; i++) s[i].selectedIndex = selected_index;
}

/*
*   submete_formulario(id_formulario);
*
*   @param string id_formulario     - id do formulário a submeter
*   @param ar_resets                         - array com os id dos SELECT a colocar a zero
*
*/
function submete_formulario (id_formulario, ar_resets) {
  var delay_dos_submit=500;
  if (ar_resets){
      for (zen=0;zen<ar_resets.length;zen++){
        document.forms[id_formulario].elements[ar_resets[zen]].selectedIndex = 0;
      }
  }
  if (document.getElementById('ampulheta')) document.getElementById('ampulheta').style.display = 'block';
  if (document.getElementById('body')) document.getElementById('body').style.cursor="wait";
  s = document.forms[id_formulario];
  setTimeout ('s.submit();', delay_dos_submit);
}
/*
*   confirma_submissao_de_pauta();
*   exibe um aviso a pedir a confirmação da submissão da pauta
*   @var avisado    -
*   @var go_no_go   -
*/
var avisado = false;
var go_no_go = false;
function confirma_submissao_de_formulario(formulario, id_elemento, mensagem) {
  document.forms.target = '_self';
  if (avisado == false) {
  document.avisado = true;
    if (confirm(mensagem)) {
      go_no_go = true;
    } else {
      go_no_go = false;
      document.avisado = false;
    }
  }
  return go_no_go;
}

function esconde_resultados(id_elemento) {
  for (x=0; x < id_elemento.length;x++){
    if (document.getElementById(id_elemento[x])){
      document.getElementById(id_elemento[x]).style.display = "none";
      document.getElementById(id_elemento[x]).style.visibility = "hidden";
    }
  }
}

/*
*   Tabuladores e Breadcrumb();
*/

function mosDHTML() {
 this.activeTab = '';

 this.start_onTabStyle = 'tab_active_start';
 this.onTabStyle = 'tab_active_bg';
 this.end_onTabStyle = 'tab_active_end';

 this.start_offTabStyle = 'tab_inactive_start';
 this.offTabStyle = 'tab_inactive_bg';
 this.end_offTabStyle = 'tab_inactive_end';

 this.setElemStyle = function(elem,style) {
  if (document.getElementById(elem)) document.getElementById(elem).className = style;
 };
 this.showElem = function(id) {if (elem = document.getElementById(id)) {elem.style.visibility = 'visible';elem.style.display = 'block';} }
 this.hideElem = function(id) {if (elem = document.getElementById(id)) {elem.style.visibility = 'hidden';elem.style.display = 'none';} }
 this.cycleTab = function(name) {
  if (this.activeTab) {
   this.setElemStyle( this.activeTab, this.offTabStyle );
   this.setElemStyle( "start_" + this.activeTab, this.start_offTabStyle );
   this.setElemStyle( "end_" + this.activeTab, this.end_offTabStyle );
   page = this.activeTab.replace( 'tab', 'page' ); 
   this.hideElem(page);
  }
  this.setElemStyle( name, this.onTabStyle );
  this.setElemStyle( "start_" + name, this.start_onTabStyle );
  this.setElemStyle( "end_" + name, this.end_onTabStyle );
  this.activeTab = name;
  page = this.activeTab.replace( 'tab', 'page' );
  this.showElem(page);
 }
 return this;
}
var dhtml = new mosDHTML();

/**   
* gettabname(m_ar_tabs, idtab)
* Esta função verifica no array onde estão definidos os tabs qual a descrição e devolve o valor
**/
function gettabname(m_ar_tabs, idtab){
 var sDescTab;
// Retirado o "tab_" do início do idtab passado pelo cycleTab
 idtab = idtab.substr( 4, idtab.length);
 if (m_ar_tabs) {
  for(var iearg in m_ar_tabs){
   for(var itpesq in m_ar_tabs[iearg]){
    if (m_ar_tabs[iearg][itpesq][idtab]){
     sDescTab = m_ar_tabs[iearg][itpesq][idtab]['nome'];
     return (sDescTab);
    }
   }
  }
 }
}

/**   
* nv_tab_act(tab_id)
* Atribui à variável NV_TAB em todos os <form> o valor do tabulador corrente, de forma a que quando haja um SUBMIT, se saiba que tabulador estava activo
**/
function nv_tab_act(tab_id) {
 var f = document.forms;
 for (var i = 0; i < f.length; i++) {
  if (!f[i].TAB_CONF_DESTINO) {
   if (f[i].NV_TAB) { // Só para Espaços de Agregação
    f[i].NV_TAB.value = tab_id;
   }
  }
 } 
}

/**   
* breadcrumb(idtab)
* Preparada para receber a designacao do tab, quando recebe coloca no final ou na posicao definida como TAB no ARRAY de menus
**/
function breadcrumb(idtab){

 var separator = ' > ';
 var is_menu_tab = false; 
 var id_tab_ar_menus = 'tab';
 var nome_do_tab = 'nome';
 var id_do_breadcrumb = 'breadCrumb';
 var output = ''; var sTab ='';
 var titulo_do_documento ='';

if (window.ar_tabs.length >0)  {
  
  for(var i in ar_menus){
   //Se for um TAB procura no array de tabs caso esteja definido o array
   if (ar_menus[i][id_tab_ar_menus] && (idtab)){
    // Pesquisa o descrição para esta posição do array de tabs
       if (window.ar_tabs) sTab = gettabname (ar_tabs, idtab);    
    alert(typeof(sTab));
    if (typeof(sTab)!='undefined') output += sTab + separator;
       is_menu_tab = true;
   } else output += ar_menus[i][nome_do_tab] + separator;
  }
  
  // Caso não tenha sido encontrado, procura no array de tabs e coloca no final
  if (!(is_menu_tab) && (idtab)){
    // Pesquisa o descrição para esta posição do array de tabs
        if (window.ar_tabs) sTab = gettabname (ar_tabs, idtab);    
  //   if (typeof(sTab)!="undefined") output += sTab + separator;  
  }
  
  // Retirado o "separator" final
  if (div_objecto = document.getElementById(id_do_breadcrumb)) { 
   output = output.substr(0, output.length - separator.length);
   div_objecto.innerHTML = output;
  }



 } else if (window.ar_menus){
 
  for(var i in ar_menus){
   //Se for um TAB procura no array de tabs caso esteja definido o array
   if (ar_menus[i][id_tab_ar_menus] && (idtab)){
    // Pesquisa o descrição para esta posição do array de tabs
    if (window.ar_tabs) sTab = gettabname (ar_tabs, idtab); 
    if (typeof(sTab)!='undefined') output += sTab + separator;
    is_menu_tab = true;
   } else if (typeof(ar_menus[i][nome_do_tab])!='undefined') output += ar_menus[i][nome_do_tab] + separator;
  }
  
  
  // Retirado o "separator" final
  if (div_objecto = document.getElementById(id_do_breadcrumb)) { 
   output = output.substr(0, output.length - separator.length);
   div_objecto.innerHTML = output;
  }


 }
 //----------------------------------------------------------------------
 //
 // TITULO DO DOCUMENTO
 //
 //----------------------------------------------------------------------
   var stringArray = output.split(separator);
   var home_bcrumb = '<a href="/portal/modulos/noticia/index.php?NV_MOD=MODNOTICIA&NV_EAGR=EAGR_NOTICIABROWSER&TPESQ=PESQ_NOTICIA_DESTAQUES&IDM=PT" >Entrada<\/a>';
   var home_bcrumb_en = '<a href="/portal/modulos/noticia/index.php?NV_MOD=MODNOTICIA&NV_EAGR=EAGR_NOTICIABROWSER&TPESQ=PESQ_NOTICIA_DESTAQUES&IDM=EN" >Home<\/a>';
   
   if (stringArray[stringArray.length-1] == home_bcrumb){
     titulo_do_documento ='<h1>Seja Bem-vindo</h1>';
   } else if (stringArray[stringArray.length-1] == home_bcrumb_en){
     titulo_do_documento ='<h1>Welcome to Madeira University</h1>';
   } else {
     titulo_do_documento = '<h1>'+ stringArray[stringArray.length-1] + '</h1>';
   }
   document.getElementById('titulo_do_documento').innerHTML = titulo_do_documento;
}

function esconde_resultados(id_elemento) {
 for (x=0; x < id_elemento.length;x++){
  if (document.getElementById(id_elemento[x])){
   document.getElementById(id_elemento[x]).style.display = "none";
   document.getElementById(id_elemento[x]).style.visibility = "hidden";
  }
 }
}

// Alterna entre layout fullscreen ou não e guarda as preferências num cookie
function alterna_max_min() {
    if (getActiveStyleSheet()=='Janela nao Maximizada') {
        setActiveStyleSheet('Janela Maximizada');
    } else {
        setActiveStyleSheet('Janela nao Maximizada');
    }
    janela_maximizada = !janela_maximizada;
    var title = getActiveStyleSheet();
    createCookie("style", title, 365);
}
// Alterna entre layout gráfico e numérico
function alterna_numerico_grafico() {
    if (getActiveStyleSheet()=='Janela nao Maximizada') {
        setActiveStyleSheet('Modo Grafico');
    } else {
        setActiveStyleSheet('Janela nao Maximizada');
    }
}

function limpa_campo_formulario (id_formulario, ar_campos)
{ if (ar_campos)
   { for (zen=0;zen<ar_campos.length;zen++)
      { document.forms[id_formulario].elements[ar_campos[zen]].value = ''; }
   }
}



/*--------------------------------------------------|
| dTree 2.05 | www.destroydrop.com/javascript/tree/ |
|---------------------------------------------------|
| Copyright (c) 2002-2003 Geir Landrö               |
|                                                   |
| This script can be used freely as long as all     |
| copyright messages are intact.                    |
|                                                   |
| Updated: 17.04.2003                               |
|--------------------------------------------------*/

// Node object
function Node(id, pid, name, url, title, target, icon, iconOpen, open, CampoExtra) {
    this.id = id;
    this.pid = pid;
    this.name = name;
    this.url = url;
    this.title = title;
    this.target = target;
    this.icon = icon;
    this.iconOpen = iconOpen;
    this._io = open || false;
    this._is = false;
    this._ls = false;
    this._hc = false;
    this._ai = 0;
    this._p;
   
   this.CampoExtra = CampoExtra;
};

// Tree object
function dTree(objName) {
    this.config = {
        target                    : null,
        folderLinks            : true,
        useSelection        : true,
        useCookies            : true,
        useLines                : true,
        useIcons                : true,
        useStatusText        : false,
        closeSameLevel    : false,
        inOrder                    : false
    }
    this.icon = {
        root                : '../../javascript/dtree/img/empty.gif',
    
       folder              : '../../javascript/dtree/img/empty.gif',
        folderOpen            : '../../javascript/dtree/img/empty.gif',
        node                : '../../javascript/dtree/img/empty.gif',
        empty                : '../../javascript/dtree/img/empty.gif',
        line                : '../../javascript/dtree/img/line.gif',
        join                : '../../javascript/dtree/img/join.gif',
        joinBottom            : '../../javascript/dtree/img/joinbottom.gif',
        plus                : '../../javascript/dtree/img/plus.gif',
        plusBottom            : '../../javascript/dtree/img/plusbottom.gif',
        minus                : '../../javascript/dtree/img/minus.gif',
        minusBottom            : '../../javascript/dtree/img/minusbottom.gif',
        nlPlus                : '../../javascript/dtree/img/nolines_plus.gif',
        nlMinus                : '../../javascript/dtree/img/nolines_minus.gif'
    };
    this.obj = objName;
    this.aNodes = [];
    this.aIndent = [];
    this.root = new Node(-1);
    this.selectedNode = null;
    this.selectedFound = false;
    this.completed = false;
};

// Adds a new node to the node array
dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open, CampoExtra) {
    this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open, CampoExtra);
};

// Open/close all nodes
dTree.prototype.openAll = function() {
    this.oAll(true);
};
dTree.prototype.closeAll = function() {
    this.oAll(false);
};

// Outputs the tree to the page
dTree.prototype.toString = function() {
    var str = '<div class="dtree">\n';
    if (document.getElementById) {
        if (this.config.useCookies) this.selectedNode = this.getSelected();
        str += this.addNode(this.root);
    } else str += 'Browser not supported.';
    str += '</div>';
    if (!this.selectedFound) this.selectedNode = null;
    this.completed = true;
    return str;
};

// Creates the tree structure
dTree.prototype.addNode = function(pNode) {
    var str = '';
    var n=0;
    if (this.config.inOrder) n = pNode._ai;
    for (n; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == pNode.id) {
            var cn = this.aNodes[n];
            cn._p = pNode;
            cn._ai = n;
            this.setCS(cn);
            if (!cn.target && this.config.target) cn.target = this.config.target;
            if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id);
            if (!this.config.folderLinks && cn._hc) cn.url = null;
            if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {
                    cn._is = true;
                    this.selectedNode = n;
                    this.selectedFound = true;
            }
            str += this.node(cn, n);
            if (cn._ls) break;
        }
    }
    return str;
};

// Creates the node icon, url and text
dTree.prototype.node = function(node, nodeId) {
    var str = '<div class="dTreeNode">' + this.indent(node, nodeId);
    if (this.config.useIcons) {
        if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
        if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
        if (this.root.id == node.pid) {
            node.icon = this.icon.root;
            node.iconOpen = this.icon.root;
        }
        str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
    }
    if (node.url) {
    str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"';
    if (node.title) str += ' title="' + node.title + '"';
    if (node.target) str += ' target="' + node.target + '"';
    if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';
    if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))
        str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';
    str += '>';
    }
    else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)
        str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';
    str += node.name;
    if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>';
   
   if (node.CampoExtra) str += '<span class="dtree_link">' + node.CampoExtra + '</span>';
    str += '</div>';
    if (node._hc) {
        str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
        str += this.addNode(node);
        str += '</div>';
    }
    this.aIndent.pop();
    return str;
};

// Adds the empty and line icons
dTree.prototype.indent = function(node, nodeId) {
    var str = '';
    if (this.root.id != node.pid) {
        for (var n=0; n<this.aIndent.length; n++)
            str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
        (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
        if (node._hc) {
            str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
            if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
            else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );
            str += '" alt="" /></a>';
        } else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
    }
    return str;
};

// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function(node) {
    var lastId;
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node.id) node._hc = true;
        if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
    }
    if (lastId==node.id) node._ls = true;
};

// Returns the selected node
dTree.prototype.getSelected = function() {
    var sn = this.getCookie('cs' + this.obj);
    return (sn) ? sn : null;
};

// Highlights the selected node
dTree.prototype.s = function(id) {
    if (!this.config.useSelection) return;
    var cn = this.aNodes[id];
    if (cn._hc && !this.config.folderLinks) return;
    if (this.selectedNode != id) {
        if (this.selectedNode || this.selectedNode==0) {
            eOld = document.getElementById("s" + this.obj + this.selectedNode);
            eOld.className = "node";
        }
        eNew = document.getElementById("s" + this.obj + id);
        eNew.className = "nodeSel";
        this.selectedNode = id;
        if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id);
    }
};

// Toggle Open or close
dTree.prototype.o = function(id) {
    var cn = this.aNodes[id];
    this.nodeStatus(!cn._io, id, cn._ls);
    cn._io = !cn._io;
    if (this.config.closeSameLevel) this.closeLevel(cn);
    if (this.config.useCookies) this.updateCookie();
};

// Open or close all nodes
dTree.prototype.oAll = function(status) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
            this.nodeStatus(status, n, this.aNodes[n]._ls)
            this.aNodes[n]._io = status;
        }
    }
    if (this.config.useCookies) this.updateCookie();
};

// Opens the tree to a specific node
dTree.prototype.openTo = function(nId, bSelect, bFirst) {
    if (!bFirst) {
        for (var n=0; n<this.aNodes.length; n++) {
            if (this.aNodes[n].id == nId) {
                nId=n;
                break;
            }
        }
    }
    var cn=this.aNodes[nId];
    if (cn.pid==this.root.id || !cn._p) return;
    cn._io = true;
    cn._is = bSelect;
    if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls);
    if (this.completed && bSelect) this.s(cn._ai);
    else if (bSelect) this._sn=cn._ai;
    this.openTo(cn._p._ai, false, true);
};

// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function(node) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
            this.nodeStatus(false, n, this.aNodes[n]._ls);
            this.aNodes[n]._io = false;
            this.closeAllChildren(this.aNodes[n]);
        }
    }
}

// Closes all children of a node
dTree.prototype.closeAllChildren = function(node) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
            if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);
            this.aNodes[n]._io = false;
            this.closeAllChildren(this.aNodes[n]);        
        }
    }
}

// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function(status, id, bottom) {
    eDiv    = document.getElementById('d' + this.obj + id);
    eJoin    = document.getElementById('j' + this.obj + id);
    if (this.config.useIcons) {
        eIcon    = document.getElementById('i' + this.obj + id);
        eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
    }
    eJoin.src = (this.config.useLines)?
    ((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):
    ((status)?this.icon.nlMinus:this.icon.nlPlus);
    eDiv.style.display = (status) ? 'block': 'none';
};


// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function() {
    var now = new Date();
    var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
    this.setCookie('co'+this.obj, 'cookieValue', yesterday);
    this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};

// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
    document.cookie =
        escape(cookieName) + '=' + escape(cookieValue)
        + (expires ? '; expires=' + expires.toGMTString() : '')
        + (path ? '; path=' + path : '')
        + (domain ? '; domain=' + domain : '')
        + (secure ? '; secure' : '');
};

// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function(cookieName) {
    var cookieValue = '';
    var posName = document.cookie.indexOf(escape(cookieName) + '=');
    if (posName != -1) {
        var posValue = posName + (escape(cookieName) + '=').length;
        var endPos = document.cookie.indexOf(';', posValue);
        if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
        else cookieValue = unescape(document.cookie.substring(posValue));
    }
    return (cookieValue);
};

// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function() {
    var str = '';
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
            if (str) str += '.';
            str += this.aNodes[n].id;
        }
    }
    this.setCookie('co' + this.obj, str);
};

// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function(id) {
    var aOpen = this.getCookie('co' + this.obj).split('.');
    for (var n=0; n<aOpen.length; n++)
        if (aOpen[n] == id) return true;
    return false;
};

// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
    Array.prototype.push = function array_push() {
        for(var i=0;i<arguments.length;i++)
            this[this.length]=arguments[i];
        return this.length;
    }
};
if (!Array.prototype.pop) {
    Array.prototype.pop = function array_pop() {
        lastElement = this[this.length-1];
        this.length = Math.max(this.length-1,0);
        return lastElement;
    }
};









