/* 
 * Proyecto....: cima
 * Directorio..: /
 * Fichero.....: cima.js
 * Codificación: UTF-8
 * Fecha.......: 27-ene-2010 21:28:31
 * Modificado..: 11-abr-2010
 * Autor.......: Xavier Pastor
 * Descripción.: Funciones de JavaScript particulares de CIMA.
 */

/*** VARIABLES GLOBALES ***/

var inputJS;        // Input que sustituye a un texto.
var textJS;         // Textarea que sustituye a un texto.
var inputTabla;     // Tabla para grabar los datos de un input.
var inputClave;     // Clave primaria de la tabla.
var inputCampo;     // Campo en el que se grabarán los datos del input.
var textTabla;      // Tabla para grabar los datos de un textarea.
var textClave;      // Clave primaria de la tabla.
var textCampo;      // Campo en el que se grabarán los datos del textarea.

// Arrays
var aMeses   = new Array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
var aDiasSem = new Array ("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo");

/*** INCIO ***/

/**
 * Funciones que se realizan al cargarse la página.
 */
window.onload = function()
{
    //js_ponerLogoPie();
    js_PonerHora('divhora');
}

/**
 * Funciones que se realizan al cambiar el tamaño de la página.
 */
window.onresize = js_ponerLogoPie;

/*** EDITOR ***/

var barrasimple = [
    ['SelectAll','Cut','Copy','Paste','PasteText','PasteFromWord'],
    ['Undo','Redo'],
    ['Bold','Italic','Underline','TextColor'],
    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
    ['NumberedList','BulletedList','-','Outdent','Indent'],
    ['Table','HorizontalRule']
];

/*** REEMPLAZOS DE TEXTO ***/

/**
 * Reemplaza un texto por un INPUT o un TEXTAREA según el identificador del DIV
 * que contiene el texto:
 * - Si es del tipo: 'input_num' se reemplazará por un INPUT.
 * - Si es del tipo: 'text_num' se reemplazará por un TEXTAREA.
 * Siendo 'num' el número que identifica el texto en la tabla.
 * Los datos de la tabla, clave y campo se guardan en las variables globales y
 * serán reutilizados en las funciones que graban los datos.
 *
 * @param div Objeto DIV que contiene el texto.
 * @param tabla Nombre de la tabla que guardará los datos.
 * @param clave Nombre del campo que es la clave primaria de la tabla.
 * @param campo Nombre del campo que será modificado en la tabla.
 * @return Llama a la función apropiada para cambiar el texto.
 */
function js_reemplazaTexto( div, tabla, clave, campo )
{
    // Obtiene el ID del DIV y lo separa en el tipo y número.
    var sId = div.id;
    var aId = sId.split("_");
    var sTp = aId[0];
    sTp = sTp.toLowerCase();

    // Según el tipo de identificador se sustituirá el texto por un INPUT o un TEXTAREA.
    if ( sTp == "input")
    {
        // Guarda los datos en las variables globales.
        inputTabla = tabla;
        inputClave = clave;
        inputCampo = campo;
        js_reemplazarInput( div );
    }
    else if ( sTp == "text" )
    {
        // Guarda los datos en las variables globales.
        textTabla = tabla;
        textClave = clave;
        textCampo = campo;
        js_reemplazarTextarea( div );
    }
}

/**
 * Reemplaza el texto contenido en un DIV por un campo del tipo INPUT.
 * Si hay algún INPUT o TEXTAREA activos, los quita antes de crear el nuevo INPUT.
 *
 * @param div Objeto DIV que contiene el texto.
 * @return Nuevo INPUT con el valor el texto.
 */
function js_reemplazarInput( div )
{
    if ( inputJS ) js_restauraInput( inputJS );     // Si hay un INPUT lo quita.
    if ( textJS ) js_restauraTextarea( textJS );    // Si hay un TEXTAREA lo quita.

    div.onclick = "";   // Elimina el onclick del DIV.

    // Crea un nuevo INPUT y lo sustituye por el texto.
    var inp = document.createElement("input");  // Nuevo INPUT.
    inp.setAttribute("type", "text");           // Tipo TEXT.
    inp.setAttribute("value", div.innerHTML);   // Valor el texto del DIV.
    inp.style.width = "100%";                   // Ancho del 100%.
    inp.className = "editable";                 // Clase 'editable'.
    inp.onblur = function() {js_restauraInput( this );};  // Al perder el foco restaura el texto.
    inp.onchange = function() {xajax_grabarDatosTexto( this.parentNode.id,inputTabla,inputClave,inputCampo,this.value );}; // Si cambia graba los datos.
    div.innerHTML = "";                         // Borra el texto del DIV.
    div.appendChild(inp);                       // Añade el nuevo input como hijo del DIV.
    inputJS = inp;                              // Guarda el INPUT.
}

/**
 * Reemplaza el texto contenido en un DIV por un campo del tipo TEXTAREA.
 * Si hay algún INPUT o TEXTAREA activos, los quita antes de crear el nuevo TEXTAREA.
 * Antes de mostrar el TEXTAREA, cambia los <br> del texto por \n.
 *
 * @param div Objeto DIV que contiene el texto.
 * @return Nuevo TEXTAREA con el valor el texto.
 */
function js_reemplazarTextarea( div )
{
    if ( inputJS ) js_restauraInput( inputJS );     // Si hay un INPUT lo quita.
    if ( textJS ) js_restauraTextarea( textJS );    // Si hay un TEXTAREA lo quita.

    div.onclick = "";   // Elimina el onclick del DIV.

    // Crea un nuevo TEXTAREA y lo sustituye por el texto.
    var text = document.createElement("textarea");  // Nuevo TEXTAREA.
    var dato = div.innerHTML.replace(/<br>/g,"\n"); // Cambia los <br> por \n
    var cont = document.createTextNode(dato);
    text.appendChild(cont);
    text.setAttribute("wrap", "physical");
    text.style.width = div.style.width;                      // Ancho del 100%.
    text.style.height = div.style.height;                    // Alto del Textarea
    text.className = "editable";                    // Clase 'editable'.
    text.onblur = function() {js_restauraTextarea( this );};  // Al perder el foco restaura el texto.
    text.onchange = function() {xajax_grabarDatosTexto( this.parentNode.id,textTabla,textClave,textCampo,this.value );}; // Si cambia graba los datos.
    div.innerHTML = "";                             // Borra el texto del DIV.
    div.appendChild(text);                          // Añade el nuevo textarea como hijo del DIV.
    textJS = text;
}

/**
 * Cambia un INPUT por el texto que contiene.
 *
 * @param inp Input que será cambiado por texto.
 * @return Quita el INPUT y deja el texto.
 */
function js_restauraInput( inp )
{
    var texto = inp.value;          // Contenido del INPUT.
    var padre = inp.parentNode;     // DIV que contiene el INPUT.
    padre.onclick = function() {js_reemplazaTexto( this, inputTabla, inputClave, inputCampo );}; // Carga la función onclick del DIV.
    padre.innerHTML = texto;        // Pone el texto en el DIV.
    inputJS = null;                 // Elimina la variable que guarda el INPUT.
}

/**
 * Cambia un TEXTAREA por el texto que contiene.
 * Antes de mostrar el texto cambia los \n por <br>.
 *
 * @param text Textarea que será cambiado por texto.
 * @return Quita el TEXTAREA y deja el texto.
 */
function js_restauraTextarea ( text )
{
    var texto = text.value.replace(/\n/g,"<br>");   // Cambia los \n por <br>
    var padre = text.parentNode;                    // DIV que contiene el TEXTAREA.
    padre.onclick = function() {js_reemplazaTexto( this, textTabla, textClave, textCampo );}; // Carga la función onclick del DIV.
    padre.innerHTML = texto;                        // Pone el texto en el DIV.
    textJS = null;                                  // Elimina la variable que guarda el INPUT.
}

/*** FECHA Y HORA ***/

/**
 * Pone la fecha y hora actuales en el elemento con identificador 'id'.
 *
 * @param id Identificador del elemento.
 */
function js_PonerHora( id )
{
    if ( id )
    {
        var oFecha = new Date();
	var oSitio = document.getElementById(id);

	if (oSitio)
	{
            var sDia = aDiasSem[oFecha.getDay()];
            var iDia = oFecha.getDate();
            var sMes = aMeses[oFecha.getMonth()];
            var sAny = oFecha.getFullYear();
            var iHor = oFecha.getHours();
            var iMin = oFecha.getMinutes();
            var iSeg = oFecha.getSeconds();

            var sAhora = sDia + ", " + iDia + " de " + sMes.toLowerCase() + " de " + sAny + "<br />";
            sAhora += ((iHor < 10) ? "0" : "")   + iHor;
            sAhora += ((iMin < 10) ? ":0" : ":") + iMin;
            sAhora += ((iSeg < 10) ? ":0" : ":") + iSeg;

            oSitio.innerHTML = sAhora;
            eval(setTimeout("js_PonerHora('"+id+"')",1000));
	}
    }
}

/*** ENVIOS ***/

/**
 * Abre el cliente de correo electrónico para enviar un e-mail.
 * Asigna al atributo HREF la dirección de correo de CIMA.
 */
function js_enviarCorreo()
{
    var oMail = document.getElementById("idmail");
    oMail.setAttribute("href", "mailto:cima@ciudadanosmayores.org?subject=Correo desde la web de CIMA");
    return true
}

/*** PIE ***/

/**
 * Calcula el tamaño de la ventana del navegador y pone en la parte inferior
 * derecha el logotipo de CIMA.
 */
function js_ponerLogoPie()
{
    var oLogo = document.getElementById('logopieimg');
    var aTnav = js_tamanyoNavegador();
    var aTimg = js_tamanyoElemento('logopieimg');
    var iNav0 = aTnav[0];
    var iNav1 = aTnav[1];
    var iImg0 = aTimg[0];
    var iImg1 = aTimg[1];
    var iLeft = iNav0 - iImg0;
    var iTop  = iNav1 - iImg1;

    oLogo.style.left = iLeft + "px";
    oLogo.style.top  = iTop + "px";
}

/*** FUNCIONES PARA EL NAVEGADOR ***/

/**
 * Devuelve un array con el ancho y el alto del navegador.
 */
function js_tamanyoNavegador()
{
    var anchoBody = 0;
    var altoBody  = 0;

    if ( self.innerHeight )
    {
        // Todos los navegadores menos el Explorer.
        anchoBody = self.innerWidth;
        altoBody  = self.innerHeight;
    }
    else if ( document.documentElement && document.documentElement.clientHeight )
    {
        // Explorer 6
        anchoBody = document.documentElement.clientWidth;
        altoBody  = document.documentElement.clientHeight;
    }
    else if ( document.body )
    {
        // Otros Explorer
        anchoBody = document.body.clientWidth;
        altoBody  = document.body.clientHeight;
    }
    return [anchoBody,altoBody];
}

/**
 * Devuelve un array con el ancho y el alto del elemento 'id'
 */
function js_tamanyoElemento( id )
{
    var oElem  = document.getElementById(id);
    var iAncho = oElem.offsetWidth;
    var iAlto  = oElem.offsetHeight;

    if ( oElem.offsetHeight )
    {
        iAncho = oElem.offsetWidth;
        iAlto  = oElem.offsetHeight;
    }
    else if ( oElem.clientHeight )
    {
        iAncho = oElem.clientWidth;
        iAlto  = oElem.clientHeight;
    }
    return [iAncho,iAlto];
}


