/* $Id: komuna.js,v 1.1 2007/04/15 16:57:03 hoss Exp hoss $ */

/**************************** mallokaj variabloj ************************/

var _lingvoKodoj = ['eo', 'en'];
var _lingvoNomoj = ['Esperanto', 'English'];
var _lingvoRe = new RegExp(_lingvoKodoj.join('|'), 'i');
var _lingvoAktiva = 'eo'; // defaŭlto

/*************************** multlingviloj ******************************/

function sxangxuVideblecon() {
  var ie = (document.all) ? true : false;
  elementoj = (ie) ? document.all : document.getElementsByTagName('*');
  for (var i = 0; i < elementoj.length; i++) {
    var nodo = elementoj.item(i);
    var lingvo = nodo.getAttribute('lang');
    if (lingvo) { 
      var ago = (lingvo == _lingvoAktiva) ? 'forigu' : 'aldonu';
      _cssjs(ago, nodo, 'kasxita');
    }
  }
}

function montruNurAktivanLingvon() {
  sxangxuVideblecon();
  generuPiednotojn();
}

function sxangxuLingvon(kodo) {
  _lingvoAktiva = kodo;
  _kreuKuketon('lingvo', _lingvoAktiva, 365);
  montruNurAktivanLingvon();
}

function sercxuLingvoElekton() {
  var lingvo = null;
  // elekto = path_info || kuketo
  // se elekto, kreu kuketon
  // _kreuKuketon('lingvo', 'en', 365);
  var rez = document.URL.match(/\?(\w\w)$/i);
  if (rez) {
    if (_lingvoRe.test(rez[1])) {
      _kreuKuketon('lingvo', rez[1], 365);
      lingvo = rez[1];
    } 
  }
  if (!lingvo) {
    rez = _leguKuketon('lingvo');
    if (rez) {
      if (_lingvoRe.test(rez)) lingvo = rez;
    }
  }
  if (!lingvo) {
    lingvo = 'eo'; // defaŭlto
  }
  _lingvoAktiva = lingvo;
}

// kreu formulareton por elekti lingvon, kaj sercxu la lingvoelekton de
// la uzanto
function kreuLingvoElektilon() {
  sercxuLingvoElekton();
  var cxen = 'Lingvo/Language: ' +
  '<form id="lingvo-elektilo" method="post" action="">' +
  '<div><select name="lingvo" onchange="sxangxuLingvon(this.form.lingvo.value);">';
  for (var i = 0; i < _lingvoKodoj.length; i++) {
    var s = (_lingvoAktiva == _lingvoKodoj[i]) ? 'selected="selected"' : '';
    cxen += '<option ' + s + ' value="' + _lingvoKodoj[i] + 
      '">' + _lingvoNomoj[i] + ' (' + _lingvoKodoj[i] + ')</option>'
  }
  cxen += '</select></div></form>';
  document.write(cxen);
}

/****************************** Diversaj **********************************/

/* Kaŝu retpoŝtajn adresojn for de spamrobotoj.
 *
 * Ĉi tiu funkcio sxangxos:
 *   <span class="retposxtadreso">user cxe example punkto com</span>
 * al
 *   <a href="mailto:user@example.com">user@example.com</a>
 *
 * Bonvolu noti, ke:
 *  - "class" povas esti aŭ "retposxtadreso", "retpoŝtadreso",
 *    "retposhtadreso" aŭ eĉ "emailaddress"
 *  - per "@" anstataŭiĝas kaj "cxe" kaj "che" kaj "ĉe" kaj "at"
 *  - per "." anstataŭiĝas kaj "punkto" kaj "punkt" kaj "dot"
 */

function kasxuRetposxtAdresojn() {
  var reClass  = /\b(retpo(sx|sh|s\^|\^s|s'|ŝ)t)?adreso?|email(address)?\b/i;
  var reCxe    = /(\w)\W+(cxe|che|c\^e|\^ce|c'e|ĉe|at|&amp;t)\W+(\w)/i;
  var rePunkto = /(\w)\W+(punkto?|dot|point)\W+(\w)/ig;
  var spanoj = document.getElementsByTagName('span');
  for (var i = 0; i < spanoj.length; i++) {
    var s = spanoj[i];
    if (reClass.test(s.className)) {
      var teksto = s.firstChild;
      var adreso = teksto.data.replace(reCxe, "$1@$3")
      adreso = adreso.replace(rePunkto, "$1.$3");
      adreso = adreso.replace(/\s*/g, ''); /* forigu spacojn */
      var ankro = document.createElement('a');
      ankro.appendChild(document.createTextNode(adreso));
      ankro.setAttribute('href', 'mailto:' + adreso);
      s.removeChild(teksto);
      s.appendChild(ankro);
    }
  }
}

/* De: http://validweb.nl/artikelen/javascript/better-zebra-tables */
function striu() {
  var tables = document.getElementsByTagName("table");  

  for(var x=0;x!=tables.length;x++){
    var table = tables[x];
    if (! table) { return; }
    
    var tbodies = table.getElementsByTagName("tbody");
    
    for (var h = 0; h < tbodies.length; h++) {
      var even = true;
      var trs = tbodies[h].getElementsByTagName("tr");
      
      for (var i = 0; i < trs.length; i++) {
        if(even)
          trs[i].className += " even";
        even = !even;
      }
    }
  }
}

/***************************** Eventoj, AJAX ******************************/

function _akiruCelElementon(evt) {
  var elem;
  if (evt && evt.target)
    elem = (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;
  else
    elem = evt.srcElement;
  return(elem)
}

function _akiruEventon(evt) {
  return((evt) ? evt : ((window.event) ? event : null))
}

/*
function eventTraktilo(evt) {
  evt = _akiruEventon(evt)
  var elem = _akiruCelElementon(evt)
  if (elem) {
    // faru ion
  }
}

// por uzi:
<a onclick="eventTraktilo(event)"></a>
*/

function aldonuEventon(obj, evTipo, fn) { 
  if (obj.addEventListener) { 
    obj.addEventListener(evTipo, fn, true); 
    return(true); 
  }
  if (obj.attachEvent) { 
    var r = obj.attachEvent("on"+evTipo, fn); 
    return(r); 
  }
  return(false); 
}

function XMLHttpReq() {
  req = false;
  // kreu brancxon por indigxena XMLHttpRequest-objekto
  if (window.XMLHttpRequest && !(window.ActiveXObject)) {
    try {
      req = new XMLHttpRequest();
    }
    catch(e) {
      req = false;
    }
  }
  else if (window.ActiveXObject) {
    // kreu brancxon por mikrosofta-acxajxo
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        req = false;
      }
    }
  }
  return req
}

function eltiruValutonElXMLArbo(req, nomo) {
  return req.responseXML.getElementsByTagName(nomo)[0].childNodes[0].nodeValue
}

/******************************** Kuketoj *********************************/

function _kreuKuketon(nomo, valuto, tagoj) {
  if (tagoj) {
    var dato = new Date();
    dato.setTime(dato.getTime()+(tagoj*24*60*60*1000));
    var senvalidigxos = "; expires="+dato.toGMTString();
  }
  else senvalidigxos = "";
  document.cookie = nomo+"="+valuto+senvalidigxos+"; path=/";
}

function _leguKuketon(nomo) {
  var ne = nomo + "=";
  var kuketoj  = document.cookie.split(';');
  for (var i=0; i < kuketoj.length; i++) {
    var k = kuketoj[i];
    while (k.charAt(0) == ' ') k = k.substring(1, k.length);
    if (k.indexOf(ne) == 0) return k.substring(ne.length, k.length);
  }
  return null;
}

/**************************************************************************/

/*
 * cssjs
 * written by Christian Heilmann (http://icant.co.uk)
 * eases the dynamic application of CSS classes via DOM
 * parameters: action a, object o and class names c1 and c2 (c2 optional)
 * actions: swap exchanges c1 and c2 in object o
 *      add adds class c1 to object o
 *      remove removes class c1 from object o
 *      check tests if class c1 is applied to object o
 * example: _cssjs('swap',document.getElementById('foo'),'bar','baz');
 */

function _cssjs(a,o,c1,c2) {
  switch (a){
    case 'swap':
    case 'permutu':
      if (!_cssjs('check',o,c1)) { o.className = o.className.replace(c2,c1); }
      else                      { o.className = o.ClassName.replace(c1,c2); }
      break;
    case 'add':
    case 'aldonu':
      if (!_cssjs('check',o,c1)) { o.className += o.className? ' '+c1 : c1; }
      break;
    case 'remove':
    case 'forigu':
      var rep = o.className.match(' '+c1) ? ' '+c1 : c1;
      o.className = o.className.replace(rep,'');
      break;
    case 'check':
    case 'estas':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
      break;
  }
}


/* El http://www.alistapart.com/stories/alternate */
function elektuStilaron(nomo) {
  var i, a;
  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") == nomo) a.disabled = false;
    }
  }
  return(true);
}

/******** navigilo *********/

// Donu vojon relative de la hejmpaĝo de tiu ĉi (sub)paĝaro.
// Por uzi, oni unue devas deklari window.vojbazo.
//
// Ekzemple, se nia hejmpaĝo situus ĉe 'http://example.com/retejo',
// ni asignus al window.vojbazo '/retejo/', kaj tiel
// _simpliguURLon('http://example.com/retejo/pri/kontakti.html') liverus
// 'pri/kontakti.html'.
//
// Kiel aparta kazo, ĝi forigas el la vojo "index.html", "index.php" ktp.

function _simpliguURLon(url) {
  if (typeof window.vojbazo == 'undefined') {
    alert('mankas window.vojbazo');
    return;
  }
  if (typeof window.urlbazoRe == 'undefined') {
    var urlbazo = window.location.protocol + '//' +
      window.location.hostname + window.vojbazo;
    window.urlbazoRe = new RegExp(urlbazo);
  }
  return url.replace(window.urlbazoRe,'').replace(/\/(index(\.[a-z]+)?)?$/,'');
}

function _lasuPaneron(nodo) {
  // se ne ekzistas malloka variablo por paneroj, unue kreu ĝin
  if (typeof _PANEROJ == 'undefined') {
      _PANEROJ = document.getElementById('paneroj');
      _PANEROJ.innerHTML = '';
  }
  if (_PANEROJ.childNodes.length > 0)
    _PANEROJ.innerHTML += ' &gt; ';
  _PANEROJ.appendChild(nodo.cloneNode(true));
}

// Se la paĝo havas elementon kun id "mesagxo", malkaŝu ĝin kaj
// aldonu m. Ĉi tiu funkcio povas multe helpi la programiston dum senerarigo!
function _mesagxu(m) {
  if ((e = document.getElementById('mesagxo')) == null) return;
  e.style.display = 'block';
  e.innerHTML += m + '<br/>';
}

function _tramarsxu(ul, pagxvojo) {
  // document.write(ul.tagName + '<br/>');
  if (ul.tagName != 'UL') return;
  var ulidoj = ul.childNodes;
  for (var i = 0; i < ulidoj.length; i++) {
    if (ulidoj[i].nodeType != 1) continue;
    var li = ulidoj[i];
    if (li.tagName != 'LI') break;
    var liidoj = li.childNodes;
    var aktiva = false;
    for (var j = 0; j < liidoj.length; j++) {
      if (liidoj[j].nodeType != 1) continue;
      if (liidoj[j].tagName == 'A') {
        vojo = _simpliguURLon(liidoj[j].href);
        if (aktiva = (pagxvojo.match(vojo))) {
          if (vojo != '')   // ne flagu la hejmpaĝon 'aktiva'
            liidoj[j].className += ' lauxvoja';
          if (pagxvojo == vojo)
            liidoj[j].className += ' vi-estas-cxi-tie';
          _lasuPaneron(liidoj[j]);
        }
      }
      else {
        if (liidoj[j].tagName == 'UL') {
          if (aktiva) {
            // _mesagxu('aktiva: ' + vojo + '<br/>');
            liidoj[j].style.display = 'block';
            _tramarsxu(liidoj[j], pagxvojo);
          }
          else {
            // liidoj[j].style.display = 'none';
          }
        }
      }
    }
  }
}

/********** hiperligoj/piednotoj **********/

function generuPiednotojn() {
  var m = document.getElementById('mesagxo');
  if (m == null) return;
  // e.innerHTML += m + '<br/>';
  ankroj = document.getElementById('enhavo').getElementsByTagName('a');  
  var numero = 0;
  for (var i = 0; i < ankroj.length; i++) {
    var a = ankroj[i];
    // var lingvo = a.getAttribute('lang');
    // _mesagxu(lingvo);
    if (a.hasAttribute('href')) {
      numero++;
      a.parentNode.insertBefore(document.createTextNode(numero), a.nextSibling);
      _mesagxu(numero + ': ' + a.href);
       // ankro.appendChild(document.createTextNode(adreso));
       // ankro.setAttribute('href', 'mailto:' + adreso);
       // s.removeChild(teksto);
       //s.appendChild(ankro);
    }
  } 
}

function _tramarsxu_kaj_aldonu_piednotojn(nodo, numero) {
  var lingvo = nodo.getAttribute('lang');
  if (lingvo && (lingvo != _lingvoAktiva)) return 0; // ne sekvu kasxitajn nodojn
  var idoj = nodo.childNodes;
  var no_ligoj = 0;
  for (var i = 0; i < idoj.length; i++) {
    if (idoj[i].nodeType != 1) continue;
    if (idoj[i].tagName == 'A') {
      var ankro = idoj[i];
      if (ankro.hasAttribute('href')) {
        no_ligoj++;
        /*
          ankro.parentNode.insertBefore(
            document.createTextNode(no_ligoj+numero), ankro.nextSibling);
        */
        ankro.setAttribute('numero', no_ligoj + numero);
        var noto = numero + no_ligoj + ': ' + ankro.href + '<br />';
        document.getElementById('piednotoj').innerHTML += noto;
      }
    }
    else {
      no_ligoj += _tramarsxu_kaj_aldonu_piednotojn(idoj[i], numero+no_ligoj);
    }
  }
  return no_ligoj;
}

function generuPiednotojn() {
  var p = document.getElementById('piednotoj');
  if (p == null) return;
  p.innerHTML = '';
  _tramarsxu_kaj_aldonu_piednotojn(document.getElementById('enhavo'), 0);
}
 
function generuNavigilojn() {
  var pagxvojo = _simpliguURLon(window.location.href);
  pagxvojo = pagxvojo.replace(/^\/+/, ''); /* forigu komencaj / */
  pagxvojo = pagxvojo.replace(/\/+$/, ''); /* forigu finaj / */
  pagxvojo = pagxvojo.replace(/\/\/+/g, '/');
  // _mesagxu('paĝvojo = ' + pagxvojo + '<br/>');
  var root = document.getElementById('navigilo').getElementsByTagName('ul')[0];
  _tramarsxu(root, pagxvojo);
}


// aldonuEventon(window, "load", striu)
aldonuEventon(window, "load", kasxuRetposxtAdresojn)
aldonuEventon(window, "load", montruNurAktivanLingvon)

