// Navegador
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;
var objFrm;	// variable global que almacena el formulario con el que se está trabajando

var idIdioma;
var idi = new Array(20);
idi[1] = "El campo|O campo|The field";
idi[2] = "es obligatorio|é obrigatorio|cannot remain blank";
idi[3] = "no puede ser menor de|non pode ser menor de|must have at least";
idi[4] = "caracteres|caracteres|characters";
idi[5] = "no puede ser mayor de|non pode ser maior de|cannot contain more than";
idi[6] = "debe ser numérico [###.###,##]|debe ser numérico [###.###,##]|must be a numeric value [###.###,##]";
idi[7] = "debe ser DD/MM/AAAA|debe ser DD/MM/AAAA|must be DD/MM/YYYY";
idi[8] = "no puede elegir una fecha menor a la actual|non pode escoller unha data menor á actual|the selected date cannot be earlier than the current date";
idi[9] = "debe ser una dirección de correo válida|debe ser unha direción de correo válida|please enter a valid e-mail address";
idi[10]= "debe seleccionar un tipo de archivo válido|debe seleccionar un tipo de arquivo válido|please select a valid file format";
idi[11]= "No existen restricciones de tipo|Non hai restricións de tipo|There are no restrictions of type";
idi[12]= "debe ser DD/MM/AAAA hh:mm|debe ser DD/MM/AAAA hh:mm|must be DD/MM/YYYY hh:mm";
idi[13]= "Los campos fecha deben tener formato DD/MM/AAAA|Os campos de data deben ter formato DD/MM/AAAA|The date fields must have DD/MM/YYYY format";
idi[14]= "El día no es correcto|O día non é correcto|You have entered a wrong day";
idi[15]= "El mes no es correcto|O mes non é correcto|You have entered a wrong month";
idi[16]= "El año no es correcto|O ano non é correcto|You have entered a wrong year";
idi[17]= "Las contraseñas son distintas|Os contrasinais son distintos|Your passwords don't match";
idi[18]= "¿Desea borrar el registro seleccionado?|Desexa borrar o rexistro?|";
idi[19]= "Debe seleccionar por lo menos un registro|Debe seleccionar polo menos un rexistro";
idi[20]= "El campo \"buscar\" no puede estar vacio|O campo \"buscar\" non pode estar vacío";
idi[21]= "Las claves no coinciden|As chaves non coinciden";
idi[22]= "Los minutos no son correctos|";
idi[23]= "La hora no es correcta|";
idi[24]= "El texto ha sido modificado, si continua perderá los cambios, ¿desea continuar?|";
idi[25]= "debe ser numérico entero [###.###]|debe ser numérico entero [###.###]|must be a numeric integer value [###.###]";
idi[26]= "ya existe en la base de datos|xa existe na base de datos";
idi[27]= "El material no existe en el almacén|";
idi[28]= "La cantidad no puede ser mayor a la disponible";
idi[29]= "¿Desea eliminar el/los registros seleccionados?|Desexa eliminar o/os rexistros seleccionados?";
idi[30]= "debe ser hh:mm|debe ser hh:mm|must be hh:mm";
idi[31]= "En la base de datos ya existe un #campo# con ese nombre, desea guardarlo de todas formas?|";
idi[32] = "El campo D.N.I. es obligatorio para mayores de 18 años|O campo D.N.I. é obrigatorio para maiores de 18 anos|The field cannot remain blank";
idi[33] = "dígitos|díxitos|digits";
idi[34]= "debe ser numérico|debe ser numérico|must be a numeric";

// DEVUELVE un texto del array idi pasándole una posición y un idioma
// -----------------------------------------------------------------------------------------------
function mIdiJS(id){
	aux = idi[id].split("|");
	return aux[idIdioma-1];
}

// ACCIONES que se ejecutan al cargar la página
// -----------------------------------------------------------------------------------------------
function inicializa(idioma){
	idIdioma = idioma;
	colocaFoco();
}

// ABRE una ventana popup
// -----------------------------------------------------------------------------------------------
function abrePop(cual, nombre, alto, ancho, ajustable, scroll) {
	var ventana;
	var donde_x, donde_y;
	donde_x = (screen.width - ancho) / 2;
	donde_y = (screen.height - alto) / 2;

	if (ie) {
		ventana = window.open(cual, nombre, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars='+scroll+', resizable='+ajustable+', copyhistory=no, width='+ancho+', height='+alto+', top='+donde_y+', left='+donde_x+'');
	} else if (ns) {
		ventana = window.open(cual, nombre,'width='+ancho+', height='+alto+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+ scroll +',status=no');		
	} else {
		ventana = window.open(cual, nombre, 'left='+ donde_x +',top='+ donde_y +',width='+ ancho +',height='+(alto+5)+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+ scroll +',status=no');		
	}
	ventana.focus();
}

// formatea un texto para javascript
// -----------------------------------------------------------------------------------------------
function formatoJS(texto){
	texto = texto.replace("\n", "");	// nueva linea
	texto = texto.replace("\r", "");	// tabulador
	texto = texto.replace("\t", "");	// retorno de carro
	texto = texto.replace("\f", "");	// alimentacion de formulario
	texto = texto.replace("\b", "");	// retroceso de un espacio
	return texto;
}


// PIDE confirmación para realizar una accion con varios registros de un listado (dentro de un formulario)
// para usar esta funcion, el nombre de los checkbox que guardan los id de los registros a eliminar deberán ser:
//	chkId_*
//	substituir * por un nº que identifica el tipo de registro sobre el que se va a realizar una accion
//	ej: si queremos eliminar catalogos y categorias de una sola vez, los checkbox de los catalogos deberán llamarse
//		chkId_0 y los de categorias chkId_1 o viceversa, pero tienen que ser distintos.
// -----------------------------------------------------------------------------------------------
function confirma(frm, destino, pregunta){
	var qryStr;
	
	qryStr = dameQrystrIdsChk(frm);

	if(qryStr == ""){
		muestraAlerta(mIdiJS(19), "alert", "");
	}else{
		if(destino.indexOf("?")==-1){
			qryStr = "?" + qryStr;
		}else{
			qryStr = "&" + qryStr;
		}
		
		confirmaEnvio(destino + qryStr, pregunta);
	}
}

// REDIRIGE la página a un destino si se confirma la pregunta
// -----------------------------------------------------------------------------------------------
function confirmaEnvio(destino, pregunta){
	muestraAlerta(pregunta, "confirm", "window.location.href='"+destino+"';");
}



// PIDE confirmación para realizar una accion con varios registros de un listado (dentro de un formulario)
// para usar esta funcion, el nombre de los checkbox que guardan los id de los registros a eliminar deberán ser:
//	chkId_*
//	substituir * por un nº que identifica el tipo de registro sobre el que se va a realizar una accion
//	ej: si queremos eliminar catalogos y categorias de una sola vez, los checkbox de los catalogos deberán llamarse
//		chkId_0 y los de categorias chkId_1 o viceversa, pero tienen que ser distintos.
// -----------------------------------------------------------------------------------------------
function confirmaPop(frm, destino, pregunta){
	var qryStr;
	

	
	qryStr = dameQrystrIdsChk(frm);

	if(qryStr == ""){
		muestraAlerta(mIdiJS(19), "alert", "");
	}else{
		if(destino.indexOf("?")==-1){
			qryStr = "?" + qryStr;
		}else{
			qryStr = "&" + qryStr;
		}

		confirmaEnvioPop(destino + qryStr, pregunta);
	}
}

// REDIRIGE la página a un destino si se confirma la pregunta
// -----------------------------------------------------------------------------------------------
function confirmaEnvioPop(destino, pregunta){
	muestraAlerta(pregunta, "confirm", "abrePop('"+destino+"','pop',600,840,'yes','yes');");
}

// REDIRIGE la página a un destino si se confirma la pregunta
// -----------------------------------------------------------------------------------------------
function confirmaEnvioPopEtiquetas(destino, pregunta){
	muestraAlerta(pregunta, "confirm", "ocultaAlerta();abrePop('"+destino+"','pop',600,840,'yes','yes');");
}


// CREA un objeto para AJAX según disponibilidad del navegador
// -----------------------------------------------------------------------------------------------
function GetXmlHttpObject() {
	var objXMLHttp = null;
	if (window.XMLHttpRequest) {
		objXMLHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}

// EJECUTA un procedimiento con ajax y llama a la funcion correspondiente para tratar el resultado
// -----------------------------------------------------------------------------------------------
function ejecutaAjax(pagina, funcionJS) {
	var devolver, funcion;
	devolver = "";
	var xmlHttp = GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		//return;
	}
	xmlHttp.onreadystatechange = function(){
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			if (xmlHttp.responseText == -1000){ // id incorrecto
				devolver = "";
			}else{	// id correcto
				devolver = xmlHttp.responseText;
			}
			eval(funcionJS+"('"+formatoJS(devolver)+"');");
		}
	};
		
	xmlHttp.open("GET", pagina, true);
	xmlHttp.send(null);
}

// MARCA todos los check con al pulsar uno
// -----------------------------------------------------------------------------------------------
function marcaCheckbox(frm) {
  	if(document.forms[frm]){
	  	for(i=0;i<document.forms[frm].elements.length;i++){
			var obj = document.forms[frm].elements[i];
		 	if ((obj.name != 'marcaTodosCheckbox') && (obj.type=='checkbox') && (!obj.disabled)) {
				obj.checked = document.getElementById("marcaTodosCheckbox").checked;
			}
		}
	}
}

// MARCA todos los check con al pulsar uno siempre que empiecen por un texto
// -----------------------------------------------------------------------------------------------
function marcaCheckboxEdicion(frm, texto) {
  	if(document.forms[frm]){
	  	for(i=0;i<document.forms[frm].elements.length;i++){
			var obj = document.forms[frm].elements[i];
		 	if ((obj.name != 'marcaTodosCheckbox') && (obj.type=='checkbox') && (!obj.disabled) && (obj.name.indexOf(texto) == 0)) {
				obj.checked = document.getElementById("marcaTodosCheckbox").checked;
			}
		}
	}
}

// AÑADE un 0 a la izda de un nº de una cifra
// -----------------------------------------------------------------------------------------------
function numDosCifras(num){
	var aux = num;
	if (num < 10){
		aux = "0" + aux;
	}
	return aux;
}

// COLOCA el foco en el primer campo accesible de un formulario
// -----------------------------------------------------------------------------------------------
function colocaFoco(){
	var i = 0;
	if(window.document.forms.length > 0){
		for(i=0;i<window.document.forms[0].elements.length;i++){
			elemento = window.document.forms[0].elements[i];
			if(elemento.type != null && elemento.disabled != true  && elemento.readOnly != true && (elemento.type == "text" || elemento.type == "password")){
				try {
   	            	elemento.focus();
					return true;
            	} catch (e) {
					return false;		
				}
			}
		}
	}
}

// ABRE O CIERRA una capa, necesita prototype y effects
// -----------------------------------------------------------------------------------------------
function abreCierraCapa(capa){
	new Effect.toggle($(capa), "blind", {duration:0.3});
}

// CONTROLA EL menu desplegable
// -----------------------------------------------------------------------------------------------
function toggleMenu(el, over){

	var aA = el.getElementsByTagName("a");
	var aUL = el.getElementsByTagName("ul");
    if (over) {
		el.className=' over';
		WCH.Apply(aUL[0], aA[0]);	// en IE6 posicionamos los submenus por encima de los combos
   	}else {
		el.className='';
		WCH.Discard(aUL[0], aA[0]);
    }
}


// COMPRUEBA si un elemento ya existe en un array
// -----------------------------------------------------------------------------------------------
function enArray(elemento, coleccion){
	var i;
	for(i=0;i<coleccion.length;i++){
		if(coleccion[i] == elemento){
			return true;
		}
	}
	return false;
}

// MUESTRA mensajes de alerta
// -----------------------------------------------------------------------------------------------
function muestraAlerta(mensaje, tipo, accionAceptar){
	var contenidoAlerta = "";
	
	// bloqueamos el scroll del body
	document.body.scroll = "no";
		
	// mostramos la transparencia de fondo
	var cntAlerta = document.createElement("div");
	cntAlerta.id = "cntAlerta";
	document.body.appendChild(cntAlerta);
	var cntMsgAlerta = document.createElement("div");
	cntMsgAlerta.id = "cntMsgAlerta";
	document.body.appendChild(cntMsgAlerta);
	// mostramos la alerta
	with(document.getElementById("cntMsgAlerta")){
		contenidoAlerta = mensaje;
		contenidoAlerta += "<br /><br /><br />";
		switch(tipo){
		case "confirm":
			contenidoAlerta += "<input id=\"btnAlerta\" type=\"button\" class=\"boton\" onclick=\""+ accionAceptar +";\" value=\"Aceptar\" />";
			contenidoAlerta += "&nbsp;&nbsp;&nbsp;";
			contenidoAlerta += "<input type=\"button\" class=\"boton\" onclick=\"ocultaAlerta();\" value=\"Cancelar\" />";
			break;
		case "alert":
			contenidoAlerta += "<input type=\"button\" id=\"btnAlerta\" onblur=\"this.focus();\" class=\"boton\" onclick=\"ocultaAlerta();"+accionAceptar+"\" value=\"Aceptar\" />";
			break;
		case "pagina":
			break;
		}
		contenidoAlerta += "<div style=\"clear:both;\"></div>";
		innerHTML = contenidoAlerta;
	}
	WCH.Apply("cntAlerta");	// posiciona la capa por encima de elementos problematicos [combos, flash ...]
	document.getElementById("btnAlerta").focus();
}

// OCULTA mensajes de alerta
// -----------------------------------------------------------------------------------------------
function ocultaAlerta(){
	// eliminamos las capas
	WCH.Discard("cntAlerta");	// Elimina el efecto que muestra la capa por encima de elementos problematicos [combos, flash ...]
	var cntAlerta = document.getElementById("cntAlerta");
	cntAlerta.parentNode.removeChild(cntAlerta);
	var cntMsgAlerta = document.getElementById("cntMsgAlerta");
	cntMsgAlerta.parentNode.removeChild(cntMsgAlerta);
	
	// habilitamos el scroll del body
	document.body.scroll = "yes";
}

// ACTIVA los campos detalle de un formulario
// -----------------------------------------------------------------------------------------------
// 13 enter
// 46 punto
function noEnter(obj, e){
	var tecla;
	var posIni = getSelectionStart(obj); 
	var parte1 = obj.value.substr(0, posIni);
	var parte2 = obj.value.substr(posIni);

	if(window.event){ // IE
		tecla = event.keyCode;
	}else if(e.which){ // Netscape/Firefox/Opera
		tecla = e.which;
	} 		
	if(tecla == 13){
		return false;
	}else{
		if(obj.className == "numero" && tecla == 46){
//			alert(parte1 + " - " + parte2 );
			obj.value = parte1 + "," + parte2;
			setPosition(obj, posIni+1, posIni+1);
			return false;
		}else{
			return true;
		}
	}
}

// COLOCA el foco en la primera caja de la nueva linea de detalle
// -----------------------------------------------------------------------------------------------
function colocaFocoDetalle(id){
	var linea = document.getElementById("linea_"+id);
	var aCajas = linea.getElementsByTagName("input");
	for(i=0;i<aCajas.length;i++){
		if(aCajas[i].type == "text"){
			aCajas[i].focus();
			return true;
		}
	}
}

// REVISA el detalle, si hay alguna linea vacia la elimina
// -----------------------------------------------------------------------------------------------
function ajustarDetalle(){
	var detalle = document.getElementById("detalle");
	var aLineas = detalle.getElementsByTagName("li"); 

    if(aLineas.length > 1){	// debe haber mas de una linea de detalle (una corresponde a la cabecera)
		for(i=aLineas.length-1;i>=0;i--){	// OJO hay que comenzar a eliminar por el final !!!
			if(aLineas[i].id.substr(0,6) == "linea_"){
				var aCajas = $(aLineas[i].id).childElements();
				
				var vacio = true;
				for(j=0;j<aCajas.length;j++){
					if((aCajas[j].tagName.toLowerCase() == "input" && aCajas[j].type == "text" && aCajas[j].value != "" && aCajas[j].disabled == false) ||
					(aCajas[j].tagName.toLowerCase() == "select" && aCajas[j].value != "" && !aCajas[j].name.include("chk|iva"))){
//						(aCajas[j].tagName.toLowerCase() == "select" && aCajas[j].value != "")){
						vacio = false;
					}
				}
				if(vacio == true){
					detalle.removeChild(aLineas[i]);
				}
			}
		}
	}
}

// RECARGA el combo de la ventana padre
// -----------------------------------------------------------------------------------------------
function recargaOpcionesCombo(campo, opciones){
	var obj = window.opener.document.frmEdicion.elements[campo];
	var cadena = "<select name=\""+campo+"\" title=\""+obj.title+"\">"+unescape(opciones)+"</select>";
// innerHTML (aplicado a un select) solo funciona en firefox pero no en explorer
	if(window.opener.document.frmEdicion){
		if(window.opener.document.frmEdicion.elements[campo]){
			window.opener.document.frmEdicion.elements[campo].innerHTML = unescape(opciones);	// para firefox
			window.opener.document.frmEdicion.elements[campo].outerHTML = cadena;	// para explorer
		}
	}
}

// CAMBIA el valor de un campo seleccionado en la popup
// -----------------------------------------------------------------------------------------------
function cambiaValorCampo(campo, valor){

	if(window.opener.document.frmEdicion){
		if(window.opener.document.frmEdicion.elements[campo]){
			window.opener.document.frmEdicion.elements[campo].value = valor;
			window.opener.document.frmEdicion.elements[campo].focus();
			window.close();
		}
	}else if(window.opener.document.frmBusqueda){
		if(window.opener.document.frmBusqueda.elements[campo]){
			window.opener.document.frmBusqueda.elements[campo].value = valor;
			window.opener.document.frmBusqueda.elements[campo].focus();
			window.close();
		}
	}

}


// CONVIERTE una cadena a valor numérico
// -----------------------------------------------------------------------------------------------
function cNumero(valor){
	numero = valor.replace(/[.]/g, "");
	numero = numero.replace(/[,]/g, ".");

	if(isNaN(numero) || valor == ""){
		return 0;
	}else{
//		return parseFloat(numero, 10);
		return redondea(numero);
	}
}

// FORMATEA un número 
// -----------------------------------------------------------------------------------------------
function formatoNumero(numero){
	numero = numero + ''; // lo convertimos a cadena
	var aux = numero.split('.');
	var parteEntera = aux[0];
	var parteDecimal = "00";
	if(aux.length > 1){
		parteDecimal = aux[1]+"00";
		parteDecimal = parteDecimal.substr(0, 2);
	}
	var regx = /(\d+)(\d{3})/;	// pone puntos de miles
	while (regx.test(parteEntera)) {
		parteEntera = parteEntera.replace(regx, '$1' + '.' + '$2');
	}
	return parteEntera + "," + parteDecimal;
}


// FORMATEA la entrada de una fecha en un input
//-------------------------------------------------------------------------------------------------
/*
	8	tecla retroceso
	39 	tecla cursor derecha
	37 	tecla cursor izquierda
	46 	tecla suprimir
	111	tecla '/'
*/
function formatearFecha(e, obj){
	var bool = true;
	var aFecha = obj.value.split("/");
	var sep = aFecha.length;
	var posIni = getSelectionStart(obj); 
	var posFin = getSelectionEnd(obj);
	var seleccion = obj.value.substr(posIni, posFin - posIni);
	
	if(window.event){ // IE
		code = event.keyCode;
	}else if(e.which){ // Netscape/Firefox/Opera
		code = e.which;
	}

	if 	(code != 8 && sep <= 2 &&
	  	((posIni == 2 && obj.value.length == 2) || (posIni == 5 && obj.value.length == 5))){
		obj.value = obj.value + "/";
	}

	if(code != 8 && code!= 39 && code != 37 && (posIni==2 || posIni == 5) && obj.value.substr(posIni, 1)=="/"){
		setPosition(obj, posIni+1, posFin+1);
	}
	
	if(code == 8 && obj.value.substr(posIni-1, 1)=="/" && posIni < obj.value.length){
		setPosition(obj, posIni-1, posFin-1);
		bool = false;
	}
	
	if(code == 46 && obj.value.substr(posIni, 1)=="/"){
		setPosition(obj, posIni+1, posFin+1);
		bool = false;
	}

	if(code == 111){
		bool = false;
	}
	
	if(seleccion.indexOf("/") != -1 && code !=37 && code != 39 && posFin < obj.value.length){
		bool = false;
	}

	return bool;
}

// FORMATEA la entrada de una hora en un input
//-------------------------------------------------------------------------------------------------
/*
	8	tecla retroceso
	39 	tecla cursor derecha
	37 	tecla cursor izquierda
	46 	tecla suprimir
	190	tecla ':'
*/
function formatearHora(e, obj){
	var bool = true;
	var aHora = obj.value.split(":");
	var sep = aHora.length;
	var posIni = getSelectionStart(obj); 
	var posFin = getSelectionEnd(obj);
	var seleccion = obj.value.substr(posIni, posFin - posIni);
	
	if(window.event){ // IE
		code = event.keyCode;
	}else if(e.which){ // Netscape/Firefox/Opera
		code = e.which;
	}

	if 	(code != 8 && sep <= 1 &&
	  	(posIni == 2 && obj.value.length == 2)){
		obj.value = obj.value + ":";
	}

	if(code != 8 && code!= 39 && code != 37 && posIni==2 && obj.value.substr(posIni, 1)==":"){
		setPosition(obj, posIni+1, posFin+1);
	}
	
	if(code == 8 && obj.value.substr(posIni-1, 1)==":" && posIni < obj.value.length){
		setPosition(obj, posIni-1, posFin-1);
		bool = false;
	}
	
	if(code == 46 && obj.value.substr(posIni, 1)==":"){
		setPosition(obj, posIni+1, posFin+1);
		bool = false;
	}

	if(code == 190 && sep > 1){
		bool = false;
	}
	
	if(seleccion.indexOf(":") != -1 && code !=37 && code != 39 && posFin < obj.value.length){
		bool = false;
	}

	return bool;
}

// FORMATEA una caja de texto para admitir numeros
// -----------------------------------------------------------------------------------------------
// 46 punto
function formatearNumero(obj, tecla){
	var tecla;
	var posIni = getSelectionStart(obj); 
	var parte1 = obj.value.substr(0, posIni);
	var parte2 = obj.value.substr(posIni);
		
	if(tecla == 46){
		obj.value = parte1 + "," + parte2;
		setPosition(obj, posIni+1, posIni+1);
		return false;
	}else{
		if((tecla >= 48 && tecla <= 57) || tecla == 44 || tecla == 0 || tecla == 8){
			return true;
		} else {
			return false;
		}
	}
}

// 	ABRE UNA popup como una capa
// -----------------------------------------------------------------------------------------------
function showWin(destino, titulo) {
	win = new Window({className: "dialog", title: titulo, width:600, height:200, destroyOnClose: true, recenterAuto:false}); 
	win.setAjaxContent(destino, "", true, false);
}

// FORMATEA los input de los formularios para que acepten los caracteres correspondientes
// -----------------------------------------------------------------------------------------------
function formatoInput(){
	var i = 0;
	if(window.document.forms.length > 0){
		for(i=0;i<window.document.forms[0].elements.length;i++){
			elemento = window.document.forms[0].elements[i];
			if(elemento.type != null && elemento.disabled != true  && elemento.readOnly != true && elemento.type == "text" && elemento.className=="numero" && !elemento.onkeypress){
				elemento.onkeypress = function pulsar(e){
					if (typeof window.event != 'undefined'){
						tecla = event.keyCode;
					}else{
						tecla = e.which;
					}
					if(tecla == 13){
						return true
					} else {
						return formatearNumero(this, tecla);
					}
				}
			}
		}
	}
}

// CARGA un calendario de javascript
// -----------------------------------------------------------------------------------------------
function seleccionCalendario(obj) {
	if (obj.dateClicked) {
		var fecha = numDosCifras(obj.date.getDate()) + "/" + numDosCifras(eval(obj.date.getMonth()+1)) + "/" + obj.date.getFullYear();
		obj.params.inputField.value = fecha;
		
		if($("horaInicio")){
			$("horaInicio").focus();
			$("horaInicio").select();
// --- en tareas al cambiar la fecha de inicio tambien cambiamos la de fin ( ojo! ya que esto sucedera en otros 
// 		sitios en donde se cumplan estas circunstacias [mismos campos] y a lo mejor no nos interesa )
			if($("fechaFin")){
				$("fechaFin").value = fecha;
			}
// --- 
		}
	}
};

// CARGA un calendario de javascript
// -----------------------------------------------------------------------------------------------
function cargaCalendario(idContenedor, idInput){
	
	var objFecha = convierteFecha($(idInput).value);

	if(objFecha == "Invalid Date"){
		objFecha = new Date();
	}
	
	Calendar.setup(
		{
			date			: objFecha,
			inputField     	: idInput,  			// id of the input field
	    	flat        	: idContenedor, 		// ID of the parent element
			flatCallback	: seleccionCalendario,	// our callback function
			step			: 1,          			// show all years in drop-down boxes (instead of every other year as default)
			weekNumbers    	: false,      			// Número de semana
			firstDay       	: 1,      				// Primer día el lunes
			showsTime	   	: false					// mostramos hora
		}
	);
	
}

// CARGA el tiny editor
// -----------------------------------------------------------------------------------------------
function cargaTinyMce(){
	if(typeof(tinyMCE) != "undefined"){
		tinyMCE.init({
			mode : "textareas",
			editor_selector : "tiny_mce",
			theme : "simple"
		});
	}
}

// redondeamos a 2 decimales
// -----------------------------------------------------------------------------------------------
function redondea(numero){
	numero = parseFloat(numero, 10);
	numero = Math.round(numero * 100) / 100;	// redondeamos a 2 decimales	
	return numero;
}

// GENERA un recibo
// -----------------------------------------------------------------------------------------------
function cargaPopupIdsChk(frm, destino){
	var qryStr;
	
	qryStr = dameQrystrIdsChk(frm);
	
	if(qryStr == ""){
		muestraAlerta(mIdiJS(19), "alert", "");
	}else{

		if(unescape(destino).indexOf("?")==-1){
			qryStr = "?"+qryStr;
		}else{
			qryStr = "&"+qryStr;
		}

		abrePop(unescape(destino)+qryStr, 'recibo', 600, 600, 'no', 'no');
	}
}

// DEVUELVE una query con los registros checkeados de un listado
// -----------------------------------------------------------------------------------------------
function dameQrystrIdsChk(frm){
	var obj;	// elementos
	var ids = new Array();
	var qryStr = "";
	var aux = "";

	obj = document.forms[frm].elements;
	
	for(i=0;i<obj.length;i++){
		if((obj[i].type == "checkbox") && (obj[i].checked == true) && (obj[i].name.substr(0,6) == "chkId_")){
			j = obj[i].name.substr(6);
			if(ids[j]){
				ids[j] = ids[j] + "," + obj[i].value;
			}else{
				ids[j] = obj[i].value;
			}
		}
	}

	for(i=0;i<ids.length;i++){
		if(ids[i]){
			qryStr = qryStr + aux + "ids_" + i + "=" + ids[i];
			aux="&";
		}
	}
	
	return qryStr;
}

// DEVUELVE una query con los registros checkeados de un listado
// -----------------------------------------------------------------------------------------------
function ocultaCampoUsuario(valor){
	if(valor == "-2"){
		document.getElementById("bsq_txtUsuarioContacto").style.display="block";
	}else{
		document.getElementById("bsq_txtUsuarioContacto").style.display="none";
		document.getElementById("bsq_txtUsuarioContacto").value = "";
	}
}

function ocultaCampoUsuarioResponsable(valor){
	if(valor == "-2"){
		document.getElementById("bsq_txtUsuarioResponsable").style.display="block";
	}else{
		document.getElementById("bsq_txtUsuarioResponsable").style.display="none";
		document.getElementById("bsq_txtUsuarioResponsable").value = "";
	}
}
function ocultaCampo(valor){
	if(valor == "llamada"){
		document.getElementById("campoLlamada").style.display="block";
		document.getElementById("campoDocumento").style.display="none";
		document.getElementById("otrasFormasSol").style.display="none";
	}else{
		document.getElementById("campoLlamada").style.display="none";
		document.getElementById("campoDocumento").style.display="block";
		document.getElementById("otrasFormasSol").style.display="none";
	}
	if(valor == "otros"){
		document.getElementById("campoLlamada").style.display="none";
		document.getElementById("campoDocumento").style.display="none";
		document.getElementById("otrasFormasSol").style.display="block";
	
	}
}


// OCULTA o MUESTRA el formulario de nuevo registro relacionado desde un combo
// -----------------------------------------------------------------------------------------------
function muestraFrmRelacionadoCombo(valor, frm){
	if (valor == '-1' && document.getElementById(frm).style.display == 'none'){
		abreCierraCapa(frm);
		document.getElementById(frm).focus();
	}
	if (valor != '-1' && document.getElementById(frm).style.display == ''){
		abreCierraCapa(frm);
	}
}

// carga combo provincias con AJAX
// -----------------------------------------------------------------------------------------------
function cargaProvincias(idPais, idProvinciaSel)
{
	new Ajax.Updater("comboProvincias","paginaAjax.php", {parameters:"accion=" +"actualizaComboProvincias" + "&idPais=" + idPais + "&idProvincia=" + idProvinciaSel});
}

// carga combo temporada con AJAX
// -----------------------------------------------------------------------------------------------
function cargaTemporada(idSocioAbonoTipo, idCategoria, idTemporada)
{
	var idSocio = $("idSocio").value;
	//var idTemporada = $("idTemporada").value;
	//alert(idSocio.value);
	new Ajax.Updater("comboTemporada","paginaAjax.php", {parameters:"accion=" +"actualizaComboTemporada" + "&idSocioAbonoTipo=" + idSocioAbonoTipo + "&idCategoria=" + idCategoria + "&idSocio=" + idSocio + "&idTemporada=" + idTemporada });
}


// carga combo sociosAbonosTipos con AJAX
// -----------------------------------------------------------------------------------------------
function cargaSociosAbonosTipos(idTemporada, idSocioAbonoTipoSel, idCategoria, numeroAbono)
{
	//var idSocio = $("idSocio").value;
	//alert(idSocio.value);
	new Ajax.Updater("comboSociosAbonosTipos" + numeroAbono,"paginaAjax.php", {parameters:"accion=" +"actualizaComboSociosAbonosTipos" + "&idTemporada=" + idTemporada + "&idSocioAbonoTipo=" + idSocioAbonoTipoSel + "&idCategoria=" + idCategoria});
}

// carga combo categorias con AJAX
// -----------------------------------------------------------------------------------------------
function cargaCategorias(idSocioAbonoTipo, idTemporada, idCategoriaSel, numeroAbono)
{
	//var idSocio = $("idSocio").value;
	//alert(idSocio.value);
	new Ajax.Updater("comboCategorias" + numeroAbono,"paginaAjax.php", {parameters:"accion=" +"actualizaComboCategorias" + "&idTemporada=" + idTemporada + "&idSocioAbonoTipo=" + idSocioAbonoTipo +"&idCategoria=" +idCategoriaSel+"&numeroAbono=" +numeroAbono /*+ "&idSocio=" + idSocio*/});
}


// MUEVE los elementos de un combo a otro
// -----------------------------------------------------------------------------------------------
function traspasaElementosCombos(comboFuente, comboDestino){
	var nuevoElementoDestino;
	var arrayElementosTraspasados = new Array();
	var i;
	
	if (dameNumSel(comboFuente) == 0){
		// comprobamos si hay elementos seleccionados
		alert("Debe seleccionar por lo menos un registro");
		comboFuente.focus();
	}else{
		// movemos los seleccionamos
		for (i=0; i < comboFuente.options.length; i++){ 
			if (comboFuente.options[i].selected){
				nuevoElementoDestino = new Option(comboFuente.options[i].text, comboFuente.options[i].value);
				comboDestino.options[comboDestino.options.length] = nuevoElementoDestino;
				arrayElementosTraspasados[arrayElementosTraspasados.length] = i;
			}
		}
		// borramos los traspasados del combo fuente
		arrayElementosTraspasados.reverse(); // le damos la vuelta para borrar correctamente
		for (i=0; i < arrayElementosTraspasados.length; i++){
			comboFuente.options[arrayElementosTraspasados[i]] = null;
		}
	}
}

// VUELCA la información de un combo a un campo de texto
// -----------------------------------------------------------------------------------------------
function vuelcaElementosCombo(combo, campoIds){
	var aux = "";
	// almacenamos los menús seleccionados en el campo oculto
	if (combo) {
		for (i=0; i < combo.options.length; i++){
			if (aux != "") {
				aux += ",";
			}
			aux += combo.options[i].value;
		}
	}
	campoIds.value = aux;
}
// DEVUELVE el nº de elementos seleccionados en un combo
// -----------------------------------------------------------------------------------------------
function dameNumSel(objetoSelect){
	var seleccionadas = 0 ;
	for (var i=0; i < objetoSelect.options.length; i++){
		if (objetoSelect.options[i].selected){
			seleccionadas ++;
		}
	}
	return seleccionadas; 
}


// CAMBIA el numero de pagina por post
// -----------------------------------------------------------------------------------------------
function cambiaPaginaPost(idFormulario, valorPagina, nivelPagina) {
	if (window.document.getElementById("pag" + nivelPagina)) {
		window.document.getElementById("pag" + nivelPagina).value = valorPagina;
		window.document.getElementById(idFormulario).submit();
	}
}

// CAMBIA el numero de elementos por pagina por post
// -----------------------------------------------------------------------------------------------
function cambiaPagNumRsPost(idFormulario, numElementos, nivelPagina) {
	if (window.document.getElementById("pag" + nivelPagina)) {
		window.document.getElementById("pag" + nivelPagina).value = "1";
		window.document.getElementById(idFormulario).action = window.document.getElementById(idFormulario).action + "&pagNumRs" + nivelPagina + "=" + numElementos;
		window.document.getElementById(idFormulario).submit();
	}
}

// Recarga un combo de localidades por cp
// -----------------------------------------------------------------------------------------------
function recargaLocalidadesAjax(idCombo, cp, idTexto) {
	new Ajax.Request( "ajaxBusqueda.php", { 
		parameters:"accion=busquedaLocalidades&cp="+cp,
		onComplete:
			function (respuesta){
				var resultado = respuesta.responseText.split("#");
				
				var combo = window.document.getElementById(idCombo);
				
				combo.options.length = 1;
				
				if (resultado[0] != "") {
					if ((idTexto != '') && (window.document.getElementById(idTexto))) {
						window.document.getElementById(idCombo).style.display = "block";
						window.document.getElementById(idTexto).style.display = "none";
					}
					resultadosSplit = resultado[0].split("||");
					
					for (i = 0; i < resultadosSplit.length; i++) {
						resultadoSplit = (resultadosSplit[i]).split("|");
						
						opcion = new Option(resultadoSplit[1], resultadoSplit[0]);
						combo.options[combo.options.length] = opcion;
					}
				} else {
					if ((idTexto != '') && (window.document.getElementById(idTexto))) {
						window.document.getElementById(idCombo).style.display = "none";
						window.document.getElementById(idTexto).style.display = "block";
					}					
				}
			}
	});				
}