/*
* funciones.js
*
* ==============================================================================
*
* License: Licencia de desarrollo de software.
*
* Copyright (c) 2004 iQual ingenieros S.L.L. All rights reserved.
*
* This file is part of the PAbierto Web application.
* (Cultural Heritage Management System)
*
* You should have received a copy of the License along with this program;
* if not, write to the iQual Ingenieros S.L.L.
*
* support@iqualingenieros.com
*
*/

function id2Obj(id) 
{
	return (document.getElementById) ? document.getElementById(id) : ((document.all) ? document.all[id] : document.layers[id]);
} // id2Obj

// Specify affected tags. Add or remove from list
var GENERAL_htmlZoom_ETIQS = new Array('div', 'td', 'tr', 'a', 'p', 'table', 'input', 'select', 'textarea');

/**
 * Tamaño de letra.
 *
 * @param   object   the table row
 * @param   object   the color to use for this row
 * @return  boolean  whether pointer is set or not
 */
function htmlZoom(id_etiq, zoom) 
{
	// DEBUG
	//alert('htmlZoom');

	var objX, iX, objTags, iTags;

	//
	if (!(objX = id2Obj(id_etiq))) 
	{
		objX = document.getElementsByTagName(id_etiq)[0];
	}

	objX.style.fontSize = zoom;

	for (iX = 0; iX < GENERAL_htmlZoom_ETIQS.length; iX++) 
	{

		objTags = objX.getElementsByTagName(GENERAL_htmlZoom_ETIQS[iX]);

		for (iTags = 0; iTags < objTags.length; iTags++) 
		{
			objTags[iTags].style.fontSize = zoom;
		} // for

	} // for

} // htmlZoom

function zoom(zoom) 
{
	//htmlZoom('TitleFrame', zoom);
	//htmlZoom('MenuBarFrame', zoom);
	//htmlZoom('ToolsBarFrame', zoom);
	//htmlZoom('Tipos', zoom);
	//htmlZoom('Zonas', zoom);
	//htmlZoom('FastSearch', zoom);
	//htmlZoom('MainMenu', zoom);
	//htmlZoom('NavegationBar', zoom);						
	
	htmlZoom('ContentFrame', zoom);
}

/**
 * Establece el color de una fila de una tabla.
 *
 * @param   object   the table row
 * @param   object   the color to use for this row
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, thePointerColor)
{
    if (thePointerColor == '' || typeof(theRow.style) == 'undefined') {
        return false;
    }
    if (typeof(document.getElementsByTagName) != 'undefined') {
        var theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        var theCells = theRow.cells;
    }
    else {
        return false;
    }

    var rowCellsCnt  = theCells.length;
    for (var c = 0; c < rowCellsCnt; c++) 
    {
        theCells[c].style.backgroundColor = thePointerColor;
    }

    return true;
} // end of the 'setPointer()' function

/**
 * Establece el color de una celda de una tabla.
 *
 * @param   object   the table cell
 * @param   object   the color to use for this cell
 * @return  boolean  whether pointer is set or not
 */
function setCellColor(theCell, thePointerColor)
{
    theCell.style.backgroundColor = thePointerColor;
    return true;
}

/**
 * Asigna un nuevo fichero fuente a una imagen.
 *
 * @param   object   the img object 
 * @param   string   the source img
 * @return  boolean  whether pointer is set or not
 */
function setImg(img, src)
{
	auxImage = new Image();
	auxImage.src = src;
    img.src = auxImage.src;
    return true;
}

/**
 * Establece el color de una fila de una tabla y el popup asociado.
 *
 * @param   object   the table row
 * @param	object 	 the popup info
 * @param   object   the color to use for this row
 * @return  boolean  whether pointer is set or not
**/

function fillRecord(theRow, theInfo, thePointerColor)
{
	setPointer (theRow, thePointerColor);
	overlib(theInfo);
    return true;
} // end of the 'setPointer()' function

/**
 * Obtiene de los inputs del formulario USERNAME, PASSWORD y CHALLENGE
 * la siguiente cadena:
 * md5(username:md5(password):challenge)
 * y la almacena en el input del formulario RESPONSE.
 *
 * Se usa en formulario de login de usuario de aplicación.
 *
 * @param   object   the form
 * @return  boolean  true
 */
function doChallengeResponse(form)
{
    str = form.elements['USERNAME'].value + ":" +
          MD5(form.elements['PASSWORD'].value) + ":" +
          form.elements['CHALLENGE'].value;
    form.elements['RESPONSE'].value = MD5(str);
    // TO-DO: quitar este comentario cuando se implemente
    //        en la función login del dominio el que se le pase
    //        la password encriptada.
    //form.elements['PASSWORD'].value = "";
    return true;
}

/**
 * Obtiene de los inputs del formulario USERNAME, PASSWORD y CHALLENGE
 * la siguiente cadena:
 * username:md5(password):challenge
 * y la almacena en el input del formulario RESPONSE.
 *
 * Se usa en formulario de login de administrador.
 *
 * @param   object   the form
 * @return  boolean  true
 */
function doChallengeResponseAdmin(form)
{
    str = form.elements['USERNAME'].value + ":" +
          MD5(form.elements['PASSWORD'].value) + ":" +
          form.elements['CHALLENGE'].value;
    form.elements['RESPONSE'].value = MD5(str);
    form.elements['PASSWORD'].value = "";
    return true;
}

/**
 * Obtiene de los inputs del formulario USERNAME, PASSWORD y CHALLENGE
 * la siguiente cadena:
 * md5(username:challenge)
 * y la almacena en el input del formulario RESPONSE.
 * y además encripta la contraseña.
 *
 * Se usa en formulario de modificación/insercción de nuevos
 * usuarios adminitradores
 *
 * @param   object   the form
 * @return  boolean  true
 */
function encriptPass(form)
{
    str = form.elements['USERNAME'].value + ":" +
          form.elements['CHALLENGE'].value;
    form.elements['RESPONSE'].value = MD5(str);
    form.elements['PASSWORD'].value = MD5(form.elements['PASSWORD'].value);
    return true;
}

/**
 * Obtiene el input del formulario  CHALLENGE
 * y la almacena en el input del formulario RESPONSE.
 *
 * Se usa en algunos formularios de administración
 * para validar las respuestas que envían los clientes.
 * Se validad las respuestas que devuelven el mismo testigo (CHALLENGE)
 * que se les envió con el formulario.
 *
 * @param   object   the form
 * @return  boolean  true
 */
function sendResponse(form)
{
    form.elements['RESPONSE'].value = form.elements['CHALLENGE'].value;
    return true;
}

/**
 * Posiciona una capa en el pie de la Ventana
 *
 * @param   string		The layer id
 * @param   integer		Offset desde el pie	de ventana 
 * @return  boolean		true
 */
function moveLayerToBottom(layerID, offset)
{
	if (navigator.appName == "Netscape")
	{
		var layer = document.getElementById(layerID);
		//Falta obtener el PUTO ALTO de la capa
		//Falta restar el ancho de la barra de desplazamiento horizontal
		var layerheight = 20;
//		alert("Layer.left: " + layer.style.height + " Layer.top: " + layer.style.top);
		var layerpos = window.innerHeight - offset;
		layer.style.display = "block";
		layer.style.top = layerpos + "px";
		layer.style.width = window.dialogWidth + "px";
	}
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		var layer = document.getElementById(layerID);
		var layerheight = 20;
//		alert("Layer.left: " + layer.style.height + " Layer.top: " + layer.style.top);
		var layerpos = window.innerHeight - offset;
		layer.style.display = "block";
		layer.style.top = layerpos + "px";
		layer.style.width = window.dialogWidth + "px";
	}

	//alert(layer.style.top);
}

/**
 * Posiciona una capa en la Y indicada
 *
 * @param   string		The layer id
 * @param   integer		Offset desde el pie	de ventana 
 * @return  boolean		true
 */
function moveLayerTo(layerID, offset)
{
	if (navigator.appName == "Netscape")
	{
		var layer = document.getElementById(layerID);
		layer.style.display = "block";
		layer.style.top = offset + "px";
		layer.style.width = window.dialogWidth + "px";
	}
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		var layer = document.getElementById(layerID);
		layer.style.display = "block";
		layer.style.top = offset + "px";
		layer.style.width = window.dialogWidth + "px";
	}

	//alert(layer.style.top);
}

/**
 * Ejecuta el reset de un form
 *
 * @param   string   The form name
 * @return  void
 */
function resetForm(formName)
{
	if (navigator.appName == "Netscape")
	{
		var frm = document.forms.item(formName);
		frm.reset();
	}
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		var frm = document.forms.item(formName);
		frm.reset();
	}
}

function go(link)
{
  var ln = xGetElementById(link);
  var layer = xGetElementById("Content");  
  /*Ypos = ln.offsetTop;
  layer.style.top = -Ypos+'px';
  alert(Ypos+'px');*/
  //onScrollDn();
  layer.doScroll("scrollbarPageUp");
  return false;
}
  
function onScrollDn()
{
	var sc = xGetElementById('Content');
    var y = xTop(sc) - 100;
    if (y >= -(xHeight(sc) - xHeight('ContentFrame'))) 
    {
      xTop(sc, y);
    }
}  

function abrirImagen(ruta)
{
	// Para abrir la nueva ventana
	// del tamaño que ocupa la zona navegable del navegador.
	//var width = xClientWidth();
	//var height = xClientHeight();
	
	// Para abrir la nueva ventana maximizada.
	var width = screen.width;
	var height = screen.height;	

	winMap = window.open(ruta,'winImagen','width=' + width + 
							   ',height=' +  height +
	                           ',top=0' + 
	                           ',left=0' +
	                           ',menubar=no' + 
	                           ',toolbar=no' + 
	                           ',status=no' +
	                           ',resizable=yes' +
	                           ',scrollbars=no' +
	                           ',location=no');	
	                           
	winMap.focus();	                           
}

// TO-DO: separar las funciones que son genéricas de las que son especificas
//        de la aplicación y comentarlas.

/**
 * Obtiene el alto de la ventana disponible para visualizar la página
 * en el navegador.
 *
 * @return  integer
 */
function getWindowHeight() 
{
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number') 
	{
		windowHeight = window.innerHeight;
	}
	else 
	{
		if (document.documentElement&&
	        document.documentElement.clientHeight) 
	    {
			windowHeight = document.documentElement.clientHeight;
		}
		else 
		{
			if (document.body&&document.body.clientHeight) 
			{
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

/**
 * Obtiene el ancho de la ventana disponible para visualizar la página
 * en el navegador.
 *
 * @return  integer
 */
function getWindowWidth() 
{
	var windowWidth=0;
	if (typeof(window.innerWidth)=='number') 
	{
		windowWidth = window.innerWidth;
	}
	else 
	{
		if (document.documentElement&&
	        document.documentElement.clientWidth) 
	    {
			windowWidth = document.documentElement.clientWidth;
		}
		else 
		{
			if (document.body&&document.body.clientWidth) 
			{
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}

/*
function replaces extended characters of 'text' with its character
entities.
call the function by default with output = false. if you switch it
to true
it will format the source code for output in a textarea.
*/
function replaceExtChars(text, output) 
{
	text = text.replace(eval('/&/g'), '&amp;');
	
	fromTo = new Array(
		'&AElig;','Æ',
		'&Aacute;','Á',
		'&Acirc;','Â',
		'&Agrave;','À',
		'&Aring;','Å',
		'&Atilde;', 'Ã',
		'&Auml;','Ä',
		'&Ccedil;','Ç',
		'&ETH;','Ð',
		'&Eacute;','É',
		'&Ecirc;','Ê',
		'&Egrave;','È ',
		'&Euml;','Ë',
		'&Iacute;','Í',
		'&Icirc;','Î',
		'&Igrave;','Ì',
		'&Iuml;','Ï',
		'&Ntilde;','Ñ',
		'&Oacute;','Ó',
		'&Ocirc;','Ô',
		'&Ograve;','Ò',
		'&Oslash;','Ø',
		'&Otilde;','Õ',
		'&Ouml;','Ö',
		'&THORN; ','Þ',
		'&Uacute;','Ú',
		'&Ucirc;','Û',
		'&Ugrave;','Ù',
		'&Uuml;','Ü',
		'&Yacute;','Ý',
		'&aacute;', 'á',
		'&acirc;','â',
		'&aelig;','æ',
		'&agrave;','à',
		'&aring;','å',
		'&atilde;','ã',
		'&auml;','ä ',
		'&brvbar;','¦',
		'&ccedil;','ç',
		'&cent;','¢',
		'&copy;','©',
		'&deg;','°',
		'&eacute;','é',
		'&ecirc;','ê',
		'&egrave;','è',
		'&eth;','ð',
		'&euml;','ë',
		'&frac12;','½',
		'&frac14;','¼',
		'&frac34; ','¾',
		'&gt;','>',
		'&gt','>',
		'&iacute;','í',
		'&icirc;','î',
		'&iexcl;','¡',
		'&igrave;','ì',
		'&iquest;','¿',
		'&iuml;','ï', 
		'&laquo;','«',
		'&lt;','<',
		'&lt','<',
		'&mdash;','?',
		'&micro;','µ',
		'&middot;','·',
		'&ndash;','?',
		'&not;','¬',
		'&ntilde;','ñ', 
		'&oacute;','ó',
		'&ocirc;','ô',
		'&ograve;','ò',
		'&oslash;','ø',
		'&otilde;','õ',
		'&ouml;','ö',
		'&para;','¶',
		'&plusmn;','±',
		'&pound;',' £',
		'&quot;','\"',
		'&raquo;','»',
		'&reg;','®',
		'&sect;','§',
		'&shy;','*',
		'&sup1;','¹',
		'&sup2;','²', 
		'&sup3;','³',
		'&szlig;','ß',
		'&thorn;','þ',
		'&tilde;','?',
		'&trade;','?',
		'&uacute;','ú',
		'&ucirc; ','û',
		'&ugrave;','ù',
		'&uuml;','ü',
		'&yacute;','ý',
		'&yen;','¥',
		'&yuml;','ÿ');
	
	if (output) 
	{
		fromTo[fromTo.length] = '&amp;';
		fromTo[fromTo.length] = '&';
	}
	
	for (i=0; i < fromTo.length; i=i+2)
		text = text.replace(eval('/'+fromTo[i+1]+'/g'), fromTo[i]);
	
	return (text);
}
