/*
* 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
*
*/

/**
 * 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);
}

/**
 * Asigna la accion y ejecuta el submit
 *
 * @param   string   The form name
 * @param   string   The action
  * @return  void
 */
function submitFormAction(formName, action)
{
	if (navigator.appName == "Netscape")
	{
		var frm = document.forms.item(formName);
		frm.action = action;
		if (F_IETNO_JS__Validator(frm))
			frm.submit();
	}

	if (navigator.appName == "Microsoft Internet Explorer")
	{
		var frm = document.forms.item(formName);
		frm.action = action;
		if (F_IETNO_JS__Validator(frm))
			frm.submit();
	}
}

/**
 * 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 abrirMapa(ruta)
{
	//alert(ruta);

	// TO-DO: No la está haciendo se hace el enlace normal, ¿por qué?, a saber!
	// Lo solucioné poniendo un window.focus() al cargar la página del mapa.
	//winMap=window.open(anchor.href,"winMap", "status=yes,toolbar=no,menubar=no,location=yes");
	//return false;

	// 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,'winMap','width=' + width +
							   ',height=' +  height +
	                           ',top=0' +
	                           ',left=0' +
	                           ',menubar=no' +
	                           ',toolbar=no' +
	                           ',status=no' +
	                           ',resizable=yes' +
	                           ',scrollbars=no' +
	                           ',location=no');

	winMap.focus();
}

function abrirAplicacion(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;

	winMain = window.open(ruta,'winMain','width=' + width +
							   ',height=' +  height +
	                           ',top=0' +
	                           ',left=0' +
	                           ',menubar=yes' +
	                           ',toolbar=yes' +
	                           ',status=yes' +
	                           ',resizable=yes' +
	                           ',scrollbars=yes' +
	                           ',location=YES');
}

// 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 clientWidth;
}

// Nombre para el div de la página actual.
var ActiveContentFrameName1;
var ActiveContentFrameName2;
var ActiveContentFrameFunction;

// Fija el tamaño de la capa de contenido en función del tamaño disponible
// de la ventana del navegador. Se llama cuando cambia el tamaño de la
// ventana del navegador.
function fijaContenido()
{
	//alert(ActiveContentFrameFunction);

	// TO-DO: Hacer que el nombre de la función se coja de
	// la variable global ActiveContentFrameFunction, ó
	// llamar siempre a una misma función que tendrá en cuenta el
	// tipo de página.
	switch(ActiveContentFrameFunction)
	{
	case "fijaContenidoPage":
		return fijaContenidoPage(ActiveContentFrameName1);
		break;
	case "fijaContenidoTabPage":
		return fijaContenidoTabPage(ActiveContentFrameName1, ActiveContentFrameName2);
		break;
	case "fijaContenidoSimplePage":
		return fijaContenidoSimplePage(ActiveContentFrameName1);
		break;
	case "fijaContenidoLoginPage":
		return fijaContenidoLoginPage(ActiveContentFrameName1);
		break;
	}
}

function fijaContenidoPage(layerID)
{
	ActiveContentFrameName1 = layerID;
	ActiveContentFrameName2 = "";
	ActiveContentFrameFunction = "fijaContenidoPage";

	var layerT = document.getElementById("TitleFrame");
	var layerMB = document.getElementById("MenuBarFrame");
	var layerTB = document.getElementById("ToolsBarFrame");
	var layerAB = document.getElementById("SelectMunicipioFrame");
	var layerSB = document.getElementById("StatusBarFrame");
	var layerNB = document.getElementById("NavegationBarFrame");

	// Header
	var heightT = 25; //layerT.style.height;
	var heightMB = 22; //layerM.style.height;
	var heightTB = 56; //layerTB.style.height;
	var heightAB = 25; //layerAB.style.height;

	// Footer
	var heightNB = 28; //layerNB.style.height;
	var heightSB = 20; //layerSB.style.height;

	// Para obtener la posicion hay que sumar los padding (5 + 20) y marging
	var top = heightT + heightMB + heightTB + 5 + heightAB + 20;
	xMoveTo(layerID, 0, top);

	// Alto disponible para la página en el navegador
	var height = getWindowHeight();

	height = height - heightT - heightMB - heightTB - heightAB - heightSB - heightNB - 5 - 20;
	xHeight(layerID, height);

	xWidth(layerID, getWindowWidth());
}

function fijaContenidoTabPage(layerID, navegationBar)
{
	ActiveContentFrameName1 = layerID;
	ActiveContentFrameName2 = navegationBar;
	ActiveContentFrameFunction = "fijaContenidoTabPage";

	/*var layerT = document.getElementById("TitleFrame");
	var layerMB = document.getElementById("MenuBarFrame");
	var layerTB = document.getElementById("ToolsBarFrame");
	var layerAB = document.getElementById("AnchorBarFrame");
	var layerSB = document.getElementById("StatusBarFrame");*/

	// Header
	var heightT = 25; //layerT.style.height;
	var heightMB = 22; //layerM.style.height;
	var heightTB = 56; //layerTB.style.height;
	var heightAB = 25; //layerAB.style.height;

	// Footer
	if (navegationBar == true)
		var heightNB = 28; //layerSN.style.height;
	else
		var heightNB = 0; //layerSN.style.height;

	var heightSB = 20; //layerSB.style.height;

	// Para obtener la posicion hay que sumar los padding (5 + 20) y marging
	var top = heightT + heightMB + heightTB + 5 + heightAB + 20;
	xMoveTo(layerID, 0, top);

	// Alto disponible para la página en el navegador
	var height = getWindowHeight();

	height = height - heightT - heightMB - heightTB - heightAB - heightSB - heightNB - 5 - 20;
	xHeight(layerID, height);
}

function fijaContenidoSimplePage(layerID)
{
	ActiveContentFrameName1 = layerID;
	ActiveContentFrameName2 = "";
	ActiveContentFrameFunction = "fijaContenidoSimplePage";

	/*var layerT = document.getElementById("TitleFrame");
	var layerMB = document.getElementById("MenuBarFrame");
	var layerTB = document.getElementById("ToolsBarFrame");
	var layerAB = document.getElementById("AnchorBarFrame");
	var layerSB = document.getElementById("StatusBarFrame");*/

	// Header
	var heightT = 25; //layerT.style.height;
	var heightMB = 22; //layerM.style.height;
	var heightTB = 56; //layerTB.style.height;
	var heightAB = 0; //layerAB.style.height;
	var heightNB = 0; //layerSN.style.height;
	var heightSB = 20; //layerSB.style.height;

	// Para obtener la posicion hay que sumar los padding (5 + 0) y marging
	var top = heightT + heightMB + heightTB + 5 + heightAB + 0;
	xMoveTo(layerID, 0, top);

	// Alto disponible para la página en el navegador
	var height = getWindowHeight();

	height = height - heightT - heightMB - heightTB - heightAB - heightSB - heightNB - 5;
	xHeight(layerID, height);
}

function fijaContenidoLoginPage(layerID)
{
	ActiveContentFrameName1 = layerID;
	ActiveContentFrameName2 = "";
	ActiveContentFrameFunction = "fijaContenidoLoginPage";

	/*var layerT = document.getElementById("TitleFrame");
	var layerMB = document.getElementById("MenuBarFrame");
	var layerTB = document.getElementById("ToolsBarFrame");
	var layerAB = document.getElementById("AnchorBarFrame");
	var layerSB = document.getElementById("StatusBarFrame");*/

	// Header
	var heightT = 25; //layerT.style.height;
	var heightMB = 22; //layerM.style.height;
	var heightTB = 0; //layerTB.style.height;
	var heightAB = 0; //layerAB.style.height;
	var heightNB = 0; //layerSN.style.height;
	var heightSB = 20; //layerSB.style.height;

	// Para obtener la posicion hay que sumar los padding (5 + 0) y marging
	var top = heightT + heightMB + heightTB + 5 + heightAB + 0;
	xMoveTo(layerID, 0, top);

	// Alto disponible para la página en el navegador
	var height = getWindowHeight();

	height = height - heightT - heightMB - heightTB - heightAB - heightSB - heightNB - 5;
	xHeight(layerID, height);
}

// Cambia el tamaño del mapa para adaptarlo a la ventana
function resizeMap()
{
	//alert('resizeMap()');

	// Modifica el alto de la lista de marcadores y del mapa
	// El ancho se ajusta automaticamente con las hojas de estilo
	xHeight("MapBuilderMap", getWindowHeight() - 45);
	xHeight("map", getWindowHeight() - 45);
	xHeight("MapBuilderSideBar", getWindowHeight() - 45);

	// Indica a al mapa que comprueba el tamaño.
	// Esta llamada tiene que estar después se modificar su tamaño.
	map.checkResize();

}
//Comprueba que el formulario de búqueda simple contenga más de 3 caracteres
function ComprobarFormularioSimple(){
	if(document.getElementById('claves').value.length<3){
		alert("Los datos deben tener un mínimo de 3 caracteres");
		document.getElementById('claves').focus();
		return false;
	}else{
		return true;
	}
}
function ComprobarFormularioAvanzado(){
	if(document.getElementById('municipio').value == 'CUALQUIERA' &&
		(document.getElementById('actividad').value == 'CUALQUIERA' ||
		document.getElementById('actividad').value == 'AGRICULTURA' ||
		document.getElementById('actividad').value == 'HIDRÁULICA' ) &&
		document.getElementById('grupo').value == 'CUALQUIERA' &&
		document.getElementById('tipo').value == 'CUALQUIERA'){
		if(document.getElementById('claves').value == ''){
			if(confirm('Los criterios de búsqueda seleccionados generarán una gran cantidad de resultados y tardará algunos minutos en completarse. ¿Desea dividir el resultado en páginas?'))
				document.getElementById('paginacion').value = '1';
			else
				document.getElementById('paginacion').value = '0';
		}else if(document.getElementById('claves').value.length<3){
			alert("Los datos deben tener un mínimo de 3 caracteres");
			document.getElementById('claves').focus();
			return false;
		}
	}
	return true;
}

