window.onload = ikaxpag ;

// Redirecciones.
// Si solo se recibe un parámetro sin valor, se entiende como redirección.
var args = URLvariables(location.href) ;
var arg1 = args[1] ;
if ((args.length==2) && arg1.indexOf('=')<0) {
  if(arg1.indexOf('.fex')>0) location.href = '/foc/fex?f=' + arg1 ;
  else location.href = '/red/' + arg1.toLowerCase() + '.html' ;
  window.onload = null ;
}

function ikaxpag() {
  if(URLvariable('js')=='no') {
    ikaxVis();
    return false;
  }

  // El elemento documento en un documento XHTML es siempre el elemento <html>
  // El elemento body es el segundo y último hijo del elemento html.
  var html_element  = document.documentElement;
  var body_element  = html_element.lastChild;

  var cabecera     = document.createElement('div') ;
  var cuerpo       = document.createElement('div') ;
  var indice       = document.createElement('div') ;
  var pie          = document.createElement('div') ;
  var track        = document.createElement('div') ;
  cabecera.id      = 'cabecera' ;
  cuerpo.id        = 'cuerpo' ;
  indice.id        = 'indice' ;
  pie.id           = 'pie' ;
  track.id         = 'track' ;

  var busquedas    =
    '  <!-- Búsquedas -->' +
    '    <form id="frmbus" action="" onsubmit="buscar();return false;" method="get">' +
    '      <span>' +
    '        <input id="clave" type="text" size="24" value="" onfocus="select()" tabindex="111" accesskey="B" />' +
    '        <select id="motor" tabindex="112" accesskey="E">' +
    '          <option value="google">Google</option>' +
    '          <option value="wikesp">Wikipedia español</option>' +
    '          <option value="wikeng">Wikipedia english</option>' +
    '          <option value="dicrae">Dic. Real Academia Española</option>' +
    '          <option value="ingesp">Inglés - Español</option>' +
    '          <option value="esping">Español - Inglés</option>' +
    '          <option value="rssnot">Noticias</option>' +
    '          <option value="expval">Javascript - Evaluar</option>' +
    (((location.href.indexOf('ibi')>=0)||(location.href.indexOf('foc')>=0)||(location.href.indexOf('web')>=0)||(URLvariable('ibi')=='si')) ? (
    '          <option value=""> </option>' +
    '          <option value="ibidoc">IBI Technical documentation</option>' +
    '          <option value="ibifor">IBI Forum</option>' +
    '          <option value="ibikbs">IBI Knowledge Base</option>' +
    '          <option value="ibisit">Information Builders</option>' +
    '          <option value="ifocus">Foro i.focus</option>'
    ) : '') +
    '        </select>' +
    '        <input type="submit" value="Buscar" tabindex="113" accesskey="S" />' +
    ((location.href.indexOf('mini=si')<0) ? '' :
    '        <a href="/" target="_blank"><img src="http://ikax.net/img/ikax-ico-16-borde.gif" style="padding-top: 1px;" /></a>'
    ) +
    '      </span>' +
    '    </form>' +
    '  <!-- Búsquedas - Fin -->' ;

  cabecera.innerHTML =
    '<!-- Cabecera de página -->' +
    '<div id="cabecera">' +
    '  <div id="logo">' +
    '    <a href="/"><img src="/img/ikax.png" width="192" height="29" alt="/lib/ikax.net" title="/lib/ikax.net" /></a>' +
    '  </div>' +
    '  <div id="conexion">' +
    '    <a href="/adm/contacto.php" title="contacto">Contacto</a> |' +
    '    <a href="#" onclick="alert(\'http://www.telefonodelaesperanza.org - 34.91.459.00.50 \');return false">Ayuda</a>' +
    '  </div">' +
    '</div>' +
    '<!-- Cabecera de página - Fin -->' ;

  cabecera.innerHTML +=
    '<!-- Pestañas -->' +
    '<div id="barra">' +
    '  <span id="busquedas">' +
    busquedas +
    '  </span>' +
    '<a href="/" id="pesinicio" class="pestana" title="Inicio">&nbsp;&nbsp;Inicio&nbsp;&nbsp;</a>' +
    '</div>' +
    '<!-- Pestañas - Final -->'

  pie.innerHTML =
    '<a href="http://validator.w3.org/check?uri='+window.location.href+'" class="botnar" title="Esta página esta diseñada conforme al estándar xthml 1.1">&nbsp;XHTML 1.1&nbsp;</a>' +
    '&nbsp;' +
    '<a href="http://jigsaw.w3.org/css-validator/validator?uri='+window.location.href+'" class="botnar" title="Esta página esta diseñada conforme al estándar xthml 1.1">&nbsp;W3C CSS&nbsp;</a>' +
    '&nbsp;' ;

  track.innerHTML =
    '<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">\n' +
    '</script>\n' +
    '<script type="text/javascript">\n' +
    '  _uacct = "UA-237759-2";\n' +
    '  urchinTracker();\n' +
    '</script>\n' ;

  // Adición de cabecera, cuerpo y pie.
  if(location.href.indexOf('mini=si')<0) {
    body_element.appendChild(cabecera);
    body_element.appendChild(cuerpo);
    body_element.appendChild(indice);
    body_element.appendChild(pie);
    body_element.appendChild(track);
  } else {
    cabecera.innerHTML = '<div id="mini">' + busquedas + '</div>' ;
    body_element.appendChild(cabecera);
    body_element.appendChild(cuerpo);
  }
  ikaxCuerpo();

  // Recuperación de claves.
  ikaxKey();

  // Visualización del cuerpo de la página.
  ikaxVis() ;

  // Foco por defecto en la página.
  ikaxFoc();

  // Menú
  // createTOC();
}

// Traslado de elementos originales de BODY a elemento "cuerpo".
function ikaxCuerpo() {
  var html_element = document.documentElement;
  var body_element = html_element.lastChild;
  var body_first = body_element.firstChild ;
  var cuerpo = document.getElementById('cuerpo');
  if(body_first) {
    if (body_first.id == 'cabecera') return ;
    cuerpo.appendChild(body_element.removeChild(body_first));
    ikaxCuerpo();
  }
}

function ikaxKey() {
  // Recuperación de claves.
  if(document.getElementsByName) {
    var clave = '' ;
    var metaArray = document.getElementsByName('keywords');
    for (var i=0; i<metaArray.length; i++)
      clave += metaArray[i].content.replace(/\,/gi, ' ');
    if(clave.indexOf('mikel')<0)
      document.getElementById('clave').value = clave ; // Antes document.title ;
  }
  document.title = ' ikax.net - ' + document.title ;
}

 // Visualización del cuerpo de la página.
function ikaxVis() {
  if(document.getElementsByTagName) {
    var bodies = document.getElementsByTagName('body');
    for (var i=0; i<bodies.length; i++) {
      bodies[i].style.display = 'block';
    }
  }
}

// Foco por defecto en la página.
function ikaxFoc() {
  //body_element.style.display = 'block' ;
  //cuerpo.firstChild.style.display = 'block' ;
  document.getElementById('clave').focus();
}

// Búsquedas.
function buscar() {
  var motor = document.getElementById('motor').value ;
  var clave = document.getElementById('clave').value ;
  if(clave.substr(0,1)=='?') {
  //location.href = location.href.substr(0,location.href.indexOf('?')) + clave ;
    location.href = 'http://ikax.net' + clave ;
    return false;
  }
  if(clave.substr(0,1)=='>') {
    var dir = 'http://ikax.net?' + clave.substr(1, clave.length-1) ;
    var ven = window.open(dir) ;
    return false;
  }
  if (motor=='expval') { alert(calcEval(clave)); return false; }
  var url =
    (motor=='ibidoc') ? 'http://search.informationbuilders.com/docserv/query.html?qt=' :
    (motor=='ibifor') ? 'http://forums.informationbuilders.com/groupee/forums?a=search&reqWords=' :
    (motor=='ibikbs') ? 'http://techsupport.informationbuilders.com/completea?&UserRestriction=' :
    (motor=='ibisit') ? 'http://search.ibi.com/query.html?qt=' :
    (motor=='ifocus') ? 'http://groups.google.com/group/ifocus/search?hl=es&group=ifocus&q=' :
    (motor=='google') ? 'http://www.google.es/search?q=' :
    (motor=='rssnot') ? 'http://www.ikax.net/noticias/?num=10&q=' :
    (motor=='wikeng') ? 'http://en.wikipedia.org/wiki/' :
    (motor=='wikesp') ? 'http://es.wikipedia.org/wiki/' :
    (motor=='dicrae') ? 'http://buscon.rae.es/draeI/SrvltGUIBusUsual?TIPO_HTML=2&TIPO_BUS=3&LEMA=' :
    (motor=='ingesp') ? 'http://translate.google.com/translate_t?hl=es&langpair=en%7Ces&ie=UTF8&text=' :
    (motor=='esping') ? 'http://translate.google.com/translate_t?hl=es&langpair=es%7Cen&ie=UTF8&text=' :
    '' ;
  if(clave.substr(0,1)=='<') {
    var dir = codificar(url) + clave.substr(1,clave.length-1) ;
    var ajx = 'ajaxSend(\'http://ikax.net/lib/url.php?url='+dir+'\', ajaxShow)'
    setTimeout(ajx, 100);
  }
  else {
    var dir = url + ((motor=='rssnot') ? codificar(clave) : clave) ;
    var ven = window.open(dir) ;
  }
  return false
}

// Evaluación de expresiones.
function calcEval(expresion) {
  var salida = false ;
  try { salida = eval(expresion) ; }
  catch(er) { salida = er ; }
  return salida
}

// Codificación de caracteres.
function codificar(cadena) {
  var cadena = (cadena) ? cadena : '' ;
  cadena = escape(cadena);
  // escape no codifica el carácter '+'
  cadena = cadena.replace(/\+/g, '%2B') ;
  cadena = cadena.replace(/=/g, '%3D') ;
  return cadena
}

// Mostrar u ocultar objetos/capas.
function mostrar(nombreObjeto, estado) {
  var estado = (estado) ? estado : '' ;
  var objeto = document.getElementById(nombreObjeto) ;
  if(!objeto) return false;
  var actual = objeto.style.display ;
  estado     = (estado != '')       ?  estado  :
               (actual == '')       ? 'block'  :
               (actual == 'inline') ? 'none'   :
               (actual == 'block')  ? 'none'   :
                 'block' ;
  objeto.style.display = estado ;
  return true ;
}

function mostrarMenu(estado) {
  var estado = (estado) ? 'block' : 'none' ;
  var contraestado = (estado == 'block') ? 'none' : 'block' ;
  var cuerpo = (estado == 'block') ? '72%' : '92%' ;
  mostrar('menmostrar', contraestado) ;
  mostrar('menu', estado) ;
  document.getElementById('cuerpo').style.width = cuerpo ;
  document.getElementById('cuerpo').style.maxWidth = '800px' ;
}

function maximizar() {
  var estado = document.getElementById('btnmax1').value.charCodeAt(1) ;
  if (estado=='8593') {  // 8593: &uarr; - 8595: &darr;
    document.getElementById('cabecera').style.display = 'none' ;
    document.getElementById('pie').style.display      = 'none' ;
    document.getElementById('barra').style.display    = 'none' ;
    document.getElementById('btnmax1').value          = String.fromCharCode(32,8595,32);
    document.getElementById('btnmax2').value          = String.fromCharCode(32,8595,32);
    mostrarMenu(false);
  } else {
    document.getElementById('cabecera').style.display = 'block' ;
    document.getElementById('pie').style.display      = 'block' ;
    document.getElementById('barra').style.display    = 'block' ;
    document.getElementById('menu').style.display     = 'block' ;
    document.getElementById('btnmax1').value          = String.fromCharCode(32,8593,32);
    document.getElementById('btnmax2').value          = String.fromCharCode(32,8593,32);
    mostrarMenu(true);
  }
}

function ponerAtributo(objeto, nombre, valor) {
  if(nombre=='className') objeto.className = valor ;
  else
    if(nombre.substr(0,2)!='on') objeto.setAttribute(nombre, valor);
  else
    if(!document.all)
      objeto.setAttribute(nombre, valor);
    else
      objeto[nombre] = new Function(valor);
}

function createTOC() {
  var cuerpo = document.getElementById('cuerpo').childNodes ;

  var toc = document.createElement('div');
  var toBeTOCced = new Array();
  for (var i=0; i<cuerpo.length; i++) {
    if (cuerpo[i].nodeName.indexOf('H') != -1)
      toBeTOCced.push(cuerpo[i])
  }
  if (toBeTOCced.length <= 1) return;
  for (var i=0; i<toBeTOCced.length; i++) {
    var tmp = document.createElement('div');
    var tmp2 = document.createElement('a');
    tmp2.id = 'link' + i;
    var niv =
      (toBeTOCced[i].nodeName == 'H1') ? '&rArr;&nbsp;' :
      (toBeTOCced[i].nodeName == 'H2') ? '&nbsp;&nbsp;&sect;&nbsp;' :
      (toBeTOCced[i].nodeName == 'H3') ? '&nbsp;&nbsp;&nbsp;&nbsp;&loz;&nbsp;' :
      (toBeTOCced[i].nodeName == 'H4') ? '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&raquo;&nbsp;' :
        ' ' ;
    tmp.innerHTML   = niv + toBeTOCced[i].innerHTML + '&nbsp;&nbsp;' ;
    ponerAtributo(tmp, 'className'  , 'menopcnor');
    ponerAtributo(tmp, 'onmouseover', 'this.className=\'menopchov\'');
    ponerAtributo(tmp, 'onmouseout' , 'this.className=\'menopcnor\'');
    ponerAtributo(tmp, 'onclick'    , 'location.href=\'#link' + i + '\'');
    toBeTOCced[i].parentNode.insertBefore(tmp2,toBeTOCced[i]);
    toc.appendChild(tmp);
  }
  var indice = document.getElementById('indice');
  if(indice) indice.appendChild(toc);
}

// Matriz con variables URL.
function URLvariables(url) {
  var url = (url) ? 'host=' + url.replace('?', '&') : '' ;
  return url.split('&');
}

// Obtención de variable de URL determinada por nombre.
function URLvariable(nombre, url) {
  var url = (url) ? url : location.href ;
  var vars = URLvariables(url);
  for (var i=0; i<vars.length; i++) {
    vals = vars[i].split('=');
    if (vals[0]==nombre) return vals[1]
  }
  return ''
}


// threadsafe asynchronous XMLHTTPRequest code
function ajaxSend(url, callback){
// we use a javascript feature here called "inner functions"
// using these means the local variables retain their values after the outer function
// has returned. this is useful for thread safety, so
// reassigning the onreadystatechange function doesn't stomp over earlier requests.

  function ajaxBindCallback(){
    if (ajaxRequest.readyState == 4) {
      if (ajaxRequest.status == 200) {
        if (ajaxCallback){
          ajaxCallback(ajaxRequest);
        } else {
          alert('no callback defined');
        }
      } else {
        alert("There was a problem retrieving the xml data:\n" + ajaxRequest.status + ":\t" + ajaxRequest.statusText + "\n" + ajaxRequest.responseText);
      }
    }
  }

  // use a local variable to hold our request and callback until the inner function is called...
  var ajaxRequest = null;
  var ajaxCallback = callback;

  // bind our callback then hit the server...
  if (window.XMLHttpRequest) {
  // moz et al
    ajaxRequest = new XMLHttpRequest();
    ajaxRequest.onreadystatechange = ajaxBindCallback;
    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null);
  } else if (window.ActiveXObject) {
  // ie
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    if (ajaxRequest) {
      ajaxRequest.onreadystatechange = ajaxBindCallback;
      ajaxRequest.open("GET", url, true);
      ajaxRequest.send();
    }
  }

}

function ajaxShow(request) {
  var cuerpo = document.getElementById('cuerpo') ;
  cuerpo.innerHTML = request.responseText ;
}


