	
	//GLOBALES	
	var cambiarPagina = false;
	var PT = {
		mascara: null,
		validador: null,
		formateador: null,
		mensaje: null,
		
		crearMascara: function(args) {
			if(this.mascara == null)			
				this.mascara = new Mascara(args);
		},
		
		finalizarMascara: function() {
			this.mascara = null;
		},
		
		crearValidador: function(args) {
			if(this.validador == null)
				this.validador = new Validador(args);
		},
		
		finalizarValidador: function() {
			this.validador = null;
		},
		
		crearFormateador: function(args) {
			if(this.formateador == null)
				this.formateador = new Formateador(args);
		},
		
		finalizarFormateador: function() {
			this.formateador = null;
		},

		crearMensaje: function(args) {
			if(this.mensaje == null)
				this.mensaje = new Mensajes(args);
		},
		
		finalizarMensaje: function() {
			this.mensaje = null;
		},

		destroy: function() {
			this.mascara = null;
			this.validador = null;
			this.formateador = null;
			this.mensaje = null;			
			return null;
		}
	}

	/* Inicializa eventos y propiedades de la página.
	*	eventos:
	*		- oncontextmenu: desactiva el click derecho de la página 
	*		- onbeforeunload: según la metadata, si existen cambios en la pagina hace una pregunta de confirmacion antes de salir
	*		- onclick: según la metadata, cambio el valor de la global para avisar cambios en el documento.
	*/
	initPage();	
	function initPage() {
		try {
			// Inicializacion de variables		
			cambiarPagina = false;
	
			//document.onkeydown = lockKeyPress; //Bloqueo del F5 y Backpace.
			document.oncontextmenu = new Function("return false;"); // Bloqueo del menu contextual.

			// Evalua de la metadata para la programacion de eventos del documento.
			if(obtenerMetaData("cambioPagina")) {
				
				window.onbeforeunload = function() { //Pregunta por los cambio en el documento.
					var str = parent.document.getElementById("nombreOperacion").childNodes[0].innerText;
					if(str != undefined) {
						if(str.indexOf(":") != -1) {
							str = str.substring(0, str.indexOf(":"));
						}
					}
					str = str.replace("&gt;",">");
					if(cambiarPagina) return "Pueden haber ocurrido cambios en: \n - " + str; //document.title;
				};			
				
				document.onclick = function() { //Avisa de un cambio en el documento.
					cambiarPagina = true;					
				};
				
			}
			
			if(document.all) { //ie has to block in the key down
				document.onkeydown = onKeyPress;
			} else if (document.layers || document.getElementById) { //NS and mozilla have to block in the key press
				//document.onkeypress = onKeyPress;
			}
			
			function onKeyPress(evt) {				
				var oEvent = (window.event) ? window.event : evt;
				if(oEvent.keyCode == 122) {	//F11
					oEvent.returnValue = false;
					oEvent.cancelBubble = true;			
					if(document.all){ //IE
						oEvent.keyCode = 0;
					} else { //NS
						oEvent.preventDefault();
						oEvent.stopPropagation();
					}
				}
			};
						
			// seteo del estatus
			window.status = "Listo";
		} catch(e) {
			alert("Ha sucedido un error en la carga de esta página.\n" + e.message);
		}
	}	

	// Extiende el objeto Object el método inherit
	Object.inherit = function(padre, hijo) {
		for (var property in padre) {
			if(hijo[property] == undefined)
				hijo[property] = padre[property];
		}
		return hijo;
	}

	// Extiende el objeto String y agrega el método para remover el HTML de los textos.
	String.prototype.stripHTML = function() { 
		return this.replace(/<.*?>/g,"");
	}

	// Obtiene las coordenadas de un control HTML
	function buscarCoordenadas(element) {
		var coords = { x: 0, y: 0 };
		while(element) {
			coords.x += element.offsetLeft;
			coords.y += element.offsetTop;
			element = element.offsetParent;
		}
		return coords;
	}
	
	/* 
	* AJUSTA EL LAYOUT DEL LA TABLA PRINCIPAL DEL SISTEMA A LA RESOLUCIÓN DEL USUARIO.
    */
	function ajustarLayout(type) {		
		try {				
			// TODO: [Error]:Argumento no valido cuando la ventana es minimizada al maximo.
			var TAM_INTERNO;
			var BODYMARGIN_TOP_BOTTOM; 
			var HEADER_HEIGHT; 
			var FOOTER_HEIGHT; 
			var STATUS_BAR;
			
			if (window.innerHeight) TAM_INTERNO = window.innerHeight;
			else TAM_INTERNO = document.body.clientHeight;			
			
			if(type == 1) { // Redirect
				BODYMARGIN_TOP_BOTTOM = 0; 
				HEADER_HEIGHT = 0; 
				FOOTER_HEIGHT = 0; 
				STATUS_BAR = 0;
			} else if(type == 2) { // Modulos
				BODYMARGIN_TOP_BOTTOM = 0; 
				HEADER_HEIGHT = 127; 
				FOOTER_HEIGHT = 50; 
				STATUS_BAR = 0; 
			} else { // Index
				BODYMARGIN_TOP_BOTTOM = 0;
				HEADER_HEIGHT = 70;
				FOOTER_HEIGHT = 27;
				STATUS_BAR = 22;
			}
			var contenedor = document.getElementById("contenedorFrame");
			contenedor.height = TAM_INTERNO - HEADER_HEIGHT - FOOTER_HEIGHT - STATUS_BAR - BODYMARGIN_TOP_BOTTOM;
		} catch(e) {
			//alert(e.message);
		}
	}

	/* Establece el evento onkeydown de un document 
	*  para programar acciones segun las teclas presionadas
	*  en él.
	*  - params: 
	*        arr: array de objetos tecla
	*/
	function setTeclasPantalla(arr) {
		document.onkeydown = function(e) {			
			getKeyPress(arr, e);
		};
	}
	
	function eliminarContenidoBODY() {
		document.body.innerHTML = "";	
	}
	
    /* Asigna en la pantalla principal el nombre de la operación y las acciones en los span de la barra
     * de debajo del menú de acciones.
     * params:
     *     -strAcciones: HTML de acciones simples de pantalla.
     *     -strOperacion: Nombre de la operación.
     */
	function setBarraPantalla(/*String*/ strAcciones, /*String*/ strOperacion) {
		parent.document.getElementById("accionesPantalla").innerHTML = strAcciones;
		parent.document.getElementById("nombreOperacion").innerHTML = strOperacion;
	}

    /* Asigna en la pantalla principal el nombre de la operación y las acciones en los span de la barra
     * de debajo del menú de acciones.
     * params:
     * 	-acciones: Arreglo de objetos con los siguientes campos:
	 *		° String label: Etiqueta de la acción
	 *		° String src: URL de la imagen (icono) de la acción.
	 *		° String fn: Cadena de llamada a la función, incluyendo sus parametros reales (si los tiene)
	 *		Ej:
	 *		var arr = new Array(
	 *				{label: "Etiqueta de la acción", src: "imagenes/icono1.gif",	fn: "funcion1();"},
	 *				{label: "Otra accion", src: "imagenes/icono2.gif",	fn: "funcion2(a, 'msg', 54);"},
	 *			);
	 *
     *  -operacion: Nombre de la operación de la pantalla.
     */
	function setBarraPantalla2(/* Array */ acciones, /* String */ operacion) {
		try {
			var acc = parent.document.getElementById("accionesPantalla");
			var tmp;
			acc.innerHTML = "";
			if(acciones !=  null) {
				for(var i=0; i<acciones.length; i++) {
					tmp = (i==0) ? "" : " | ";
					acc.innerHTML +=  tmp + "<a style='cursor:hand;' onclick='body_layout." + acciones[i].fn + "'>" + 
					"<img src='" + acciones[i].src +"' align='absmiddle' /> " + acciones[i].label + "</a>";
				}
			}
			parent.document.getElementById("nombreOperacion").innerHTML = "<a onclick='recargarFrame();' style='cursor:hand' unselectable='on'>" + operacion + "</a>";
		} catch(e) {
			//Error: el elemento parent no existe.
		}
	}

	function recargarFrame() {
		if(body_layout.document.forms.length == 0) {
			body_layout.location.reload(true);	
		} else {
			//body_layout.location.replace(body_layout.location.href);
		}		
	}

    /* Oculta, aparece y redimensiona elementos de la vista.
     * 
     * params:
     *     -idObjetoVisible: id del objeto para asignar visible ó invisible.
     *     -idObjetoRedimension: id del objeto a redimensionar.
     *     -diferencial: valor diferencial para la redimensión del elemento.
     */
	function ajustarElementosPantalla(/*String*/ idObjetoVisible, /*String*/idObjetoRedimension, /*String*/idTagA, /*Int*/diferencial) {
		var objVisible = document.getElementById(idObjetoVisible);
		var objRedim = document.getElementById(idObjetoRedimension);
		var objEnlace = document.getElementById(idTagA);
		if(objVisible.style.display == 'none') {
			objVisible.style.display = 'block';
			objRedim.style.height = (parseInt(objRedim.style.height.substring(0, objRedim.style.height.length - 2)) - diferencial) + 'px';
			objEnlace.innerHTML = objEnlace.innerHTML.replace('Mostrar','Ocultar');
			objEnlace.innerHTML = objEnlace.innerHTML.replace('plus','minus');
		} else {
			objVisible.style.display = 'none';
			objRedim.style.height = (parseInt(objRedim.style.height.substring(0, objRedim.style.height.length - 2)) + diferencial) + 'px';
			objEnlace.innerHTML = objEnlace.innerHTML.replace('Ocultar','Mostrar');
			objEnlace.innerHTML = objEnlace.innerHTML.replace('minus','plus');
		}
	}
	
	function ajustarElementosPantalla3(/*String*/ idObjetoVisible, /*String*/idObjetoRedimension, /*String*/idTagA, /*Int*/diferencial) {
		var objVisible = document.getElementById(idObjetoVisible);
		var objRedim = null;
		if (typeof(idObjetoRedimension)=='string') objRedim = document.getElementById(idObjetoRedimension);
		else {
			objRedim = new Array();
			for (var i=0; i<idObjetoRedimension.length; i++) objRedim[i] = document.getElementById(idObjetoRedimension[i]);
		}
		var objEnlace = document.getElementById(idTagA);
		if(objVisible.style.display == 'none') {
			objVisible.style.display = 'block';
			if (typeof(objRedim)=='string') objRedim.style.height = (parseInt(objRedim.style.height.substring(0, objRedim.style.height.length - 2)) - diferencial) + 'px';
			else for (var i=0; i<objRedim.length; i++) objRedim[i].style.height = (parseInt(objRedim[i].style.height.substring(0, objRedim[i].style.height.length - 2)) - diferencial) + 'px';
			objEnlace.innerHTML = objEnlace.innerHTML.replace('Mostrar','Ocultar');
			objEnlace.innerHTML = objEnlace.innerHTML.replace('plus','minus');
		} else {
			objVisible.style.display = 'none';
			if (typeof(objRedim)=='string') objRedim.style.height = (parseInt(objRedim.style.height.substring(0, objRedim.style.height.length - 2)) + diferencial) + 'px';
			else for (var i=0; i<objRedim.length; i++) objRedim[i].style.height = (parseInt(objRedim[i].style.height.substring(0, objRedim[i].style.height.length - 2)) + diferencial) + 'px';
			objEnlace.innerHTML = objEnlace.innerHTML.replace('Ocultar','Mostrar');
			objEnlace.innerHTML = objEnlace.innerHTML.replace('minus','plus');
		}
	}	

    /* Oculta, aparece y redimensiona elementos de la vista.
     * 
     * params:
     *     -idObjetoVisible: id del objeto para asignar visible ó invisible.
     *     -idObjetoRedimension: id del objeto a redimensionar.
     *     -diferencial: valor diferencial para la redimensión del elemento.
	 * 	   -mostrar: true si abre el panel, false si lo pliegua
     */
	function ajustarElementosPantalla2(/*String*/ idObjetoVisible, /*String*/idObjetoRedimension, /*String*/idTagA, /*Int*/diferencial, /* boolean */ mostrar) {
		var objVisible = document.getElementById(idObjetoVisible);
		var objRedim = document.getElementById(idObjetoRedimension);
		var objEnlace = document.getElementById(idTagA);
		var h = parseInt(objRedim.style.height.substring(0, objRedim.style.height.length - 2));
		
		if(mostrar) {
			if(objVisible.style.display == 'none') {
				objVisible.style.display = 'block';
				objRedim.style.height = (h - diferencial) + 'px';
				objEnlace.innerHTML = objEnlace.innerHTML.replace('Mostrar','Ocultar');
				objEnlace.innerHTML = objEnlace.innerHTML.replace('plus','minus');
			}
		} else {
			if(objVisible.style.display != 'none') {
				objVisible.style.display = 'none';
				objRedim.style.height = (h + diferencial) + 'px';
				objEnlace.innerHTML = objEnlace.innerHTML.replace('Ocultar','Mostrar');
				objEnlace.innerHTML = objEnlace.innerHTML.replace('minus','plus');
			}
		}
	}	

	// Error de foto en del Empleado
	function errorFoto(obj) {
		obj.src = "/resources/imagenes/sin_foto.gif";
		//obj.title = "Sin foto";
	}

	function textAreaMaxlength(texts) {
		var ta;
		var etiqueta = "Remaining characters: ";
		for(var i=0;i<texts.length;i++) {
			ta = $(texts[i].id);
			ta.maxlength = texts[i].tamano;
			ta.div = texts[i].id + "$div";				
			ta.onkeyup = function() {
				check_length(this);
			}
			ta.onmouseover = function() {
				check_length(this);
			}
			$(ta.div).innerHTML = etiqueta + texts[i].tamano;
		}
		function check_length(textarea) {
			var div = $(textarea.div);
			var maxLen = textarea.maxlength;
			var tamano = textarea.value.length;
			if (tamano > maxLen) {
				textarea.value = textarea.value.substring(0, maxLen);
			}
			var total = maxLen - tamano;
			if(total < 0) total = 0;
			div.innerHTML = etiqueta + total;
		}
	}

	/* Agrega al combo box el valor "Seleccione:"
	 *
	 * params:
	 * 	-cbx: Referencia al combo box.
	 *	-indice: Indice donde se desea agregar el elemento
	 */
	function seleccione(/* El */ cbx, /* int */indice) {
		optionName = new Option("Seleccione:", -1);
		cbx.options[indice] = optionName;
	}	

	/* Agrega al combo box el valor "Todos:" o "Todas:"
	 *
	 * params:
	 * 	-cbx: Referencia al combo box
	 *	-indice: Indice donde se desea agregar el elemento
	 */
	function todos(/* El */ cbx, indice, sexo) {
		var str = "Todos";
		optionName = new Option(str, 0);
		cbx.options[indice] = optionName;
	}
	
	/* Obtiene el texto del un combo segun su atributo value */
	function getTextoCombo(/* El */ cbx, /*Int*/ value) {
		for(var i=0;i<cbx.length;i++) {
			if(cbx.options[i].value == value) {
					return cbx.options[i].text;
			}
		}
	}
	
	/* Establece un combo box en un valor especificado. Si el valor no existe, el combo 
	 * permanecerá en su valor inicial.
	 *
	 * params:
	 *	-cbx: Referencia al combo box
	 *	-valor: Valor a establecer
	 */
	function setValorCombo(/* El */ cbx, /* String */ valor) {
		for(var i=0;i<cbx.length;i++) {
			if(cbx.options[i].value == valor) {
					cbx.options[i].selected = true;
			}
		}
	}
	
	/* Obitiene el value del combo según el texto de parametro.
	 * params: 
	 *	-cbx: objecto combo
	 *  -text: texto a buscar
	 */
	function getValorCombo(/*Cbx*/ cbx, /*String*/ text) {
		for(var i=0;i<cbx.options.length;i++) {
			if(cbx.options[i].text == text)
				return cbx.options[i].value;
		}
	}
	
	/* Obitiene el valor clave de la opción seleccionada en un combo box.
	 * params:
	 *	-cbxName: Id del combo box
	 */
	function getCbxValue(/* String */ cbxName) {
		return $(cbxName).options[$(cbxName).selectedIndex].value;
	}
	
	/* Obitiene el text de la opción seleccionada en un combo box.
	 * params:
	 *	-cbxName: Id del combo box
	 */
	function getCbxText(/* String */ cbxName) {
		return $(cbxName).options[$(cbxName).selectedIndex].text;
	}	

	/* Cierra la ventana del navegador.
	 */
	function cerrarVentana() {
		window.close();
	}	
	
	/* Restringe la cantidad de caracteres que pueden tipearse o estar presentes en un elemento, 
	 * permitiendo la impresión de un mensaje indicando los caracteres restantes. Es de suma 
	 * utilidad para restringir la cantidad de caracteres tipeados dentro de un text area.
	 *
	 * params:
	 *	-elem: Elemento que contendrá los caracteres.
	 *	-limite: Catidad máxima de caracteres permitidos.
	 *	-divMsg: Elemento que contendrá el mensaje.
	 */
	function countChars(/* El */ elem, /* int */ limite, /* El */ divMsg) {
		var totalMensaje = elem.value.length;
		if (totalMensaje > limite) {
			elem.value = elem.value.substring(0, limite);
			totalMensaje = elem.value.length;
		}
		if(divMsg != undefined) divMsg.innerHTML = "Caracteres restantes: " + (limite-totalMensaje);
		return false;
	}
	
	/* Resetea las imagenes de una tabla de registro a seleccionar a transparentes (low)
	 *  y setea el registro seleccionado a oscuro (high).
	 * params:
	 *	-imagen: Nombre de la imagen.
	 *  -obj: Elemento imagen que se ha seleccionado
	 *  -usa: ultImgSelect
	 */	 
	 // TODO: Modificar para erutilizar en varios grids de una misma página.
	//var ultImgSelect = null; // Almacena la ultima imagen seleccionada del grid - FNC: setRegSeleccionado();
	function setRegSeleccionado(/* String */ imagen, /* Obj */ obj) {
		if(ultImgSelect != null)
			ultImgSelect.src = ultImgSelect.src.replace("high","low");
		obj.src = obj.src.replace("low","high");
		ultImgSelect = obj;
	}

	/* Resetea las imagenes de una tabla de registro a seleccionar a transparentes (low)
	 *  y setea el registro seleccionado a oscuro (high).
	 * params:
	 *	-imgGroup: Nombre del grupo de la imagenes.
	 *  -obj: Elemento imagen que se ha seleccionado
	 */	 
	function setImagenSelect(/* String */ imgGroup, /* Obj */ obj) {
		var imgs = document.getElementsByName(imgGroup);
		for(var i=0;i<imgs.length;i++) {
			imgs[i].src = imgs[i].src.replace("high","low");
		}
		if(obj != null)
			obj.src = obj.src.replace("low","high");
	}

	/*Devuelve un Objeto Date Javascript a partir de una cadena de la forma dd/mm/aaaa
	*
	*params:
	*idTexto: identificador del control que tiene la cadena de texto en formato fecha 
	*/
	function cadenaToFecha(idTexto)	{
        var cadena = new String();
        var dia;
        var mes;
        var anno;
      
        cadena = $(idTexto).value;
        dia = cadena.substring(0, 2);
        mes = cadena.substring(3, 5);
        mes = mes - 1; //Para ingresar en el constructor de Date
        anno = cadena.substring(6);
      
        var fecha = new Date(anno,mes,dia); //Objeto Fecha 
        return fecha;
     }
	  
	/*Elimina todas las filas de un grid.
	*
	*params:
	* -ojb: Objeto tabla al que se le va a elimiar las filas
	*/
	function eliminarFilasTabla(/* Obj */ tbl) {
		var ultFilas = tbl.rows.length-1;
		for(var i=0;i<ultFilas;i++)
			tbl.deleteRow(1);
    }
	
	/* Trunca una cadena a una longitud especificada.
	 *
	 * params:
	 *	-str: Cadena a truncar.
	 *	-len: Longitud que tendrá la cadena después de ser truncada.
	 */
	function truncar(/* String */ str, /* int */len) {
		var s = String(str);
		if(s.length>len) {
			return s.substring(0,len) + "...";
		} else {
			return s;
		}
	}	
	
	/* Muestra el mensaje de validación del proceso.
     * 
     * params:
     *     -tipo: tipo de mensaje 'err', 'msg' ó 'alr'. 
     *     -mensaje: mensaje a mostra.
     *     -idDisplay: id del elemento display donde se va a mostrar el mensaje.
     */
	function mostrarMensajeProceso(tipo, mensaje, idDisplay) {
		if(mensaje == "") {			
			document.getElementById(idDisplay).innerHTML = "";
			return;
		}		
		document.getElementById(idDisplay).innerHTML = "<table border='0' align='center' cellspacing='0' cellpadding='0' style='margin-top:8px;'><tr><td class='" +
		tipo + "_izq'></td><td class='" + tipo + "_cent'> " + mensaje + "</td><td class='" + tipo + 
		"_der'></td></tr></table>";
		window.setTimeout("mostrarMensajeProceso('blank', '', '" + idDisplay + "');", 4000);
	}
	
	/* Convierte una fecha numérica con formato aaaammdd al formato 
	 * dd/mm/aaaa en cadena
	 * params:
	 *	-fechaInt: fecha numérica con formato aaaammdd
	 */
	function convertirFechaAString(fechaInt) {
		var fechaStr = String(fechaInt);
		var ano;
		var mes;
		var dia;		
		if(fechaStr.length == 8) {
			ano = fechaStr.substr(0,4);
			mes = fechaStr.substr(4,2);
			dia = fechaStr.substr(6,2);
		} else {
			return "00/00/0000";	
		}
		return dia + "/" + mes + "/" + ano;
	}
	
	/* Convierte una fecha en cadena con formato dd/mm/aaaa al formato 
	 * aaaammdd en entero
	 * params:
	 *	-fechaStr: fecha en cadena con formato dd/mm/aaaa
	 */
	function convertirFechaAInt(fechaStr) {
		var dia = fechaStr.substr(0,2);
		var mes = fechaStr.substr(3,2);
		var ano = fechaStr.substr(6,4);
		return parseInt(ano +  mes +  dia);
	}
	
	/* Convierte una fecha en cadena con formato dd/mm/aaaa al formato 
	 * aaaammdd en entero y retorna 0 si el argumento no es un numero
	 * params:
	 *	-fechaStr: fecha en cadena con formato dd/mm/aaaa
	 */
	function convertirFechaAInt2(fechaStr) {
		var dia = fechaStr.substr(0,2);
		var mes = fechaStr.substr(3,2);
		var ano = fechaStr.substr(6,4);
		var f = ano + mes + dia;  
		return ((isNaN(f)||f.length==0) ? 0 : parseInt(f));
	}

	/*Funcion que determina si la fecha final es mayor o igual a la fecha inicial
	* returns true Si la fecha final es mayor o igual a la fecha inicial, false caso contrario	
	* requires function cadenaToFecha	
	*/
    function compararFechaFinal(/*String Nombre Ctrl F.Inicial*/ fInicial,/*String Nombre Ctrl F.Final*/fFinal){
      
      var fechaInicial = cadenaToFecha(fInicial); //Objeto Fecha Inicial
	  var fechaFinal = cadenaToFecha(fFinal);     //Objeto Fecha Final         
          
	  //Comparar las fechas
	  if (fechaFinal>=fechaInicial)
        return true;
      else
      	return false;	
       
	}

	// ALERTA: Cambio de funciones
	/* Convierte una fecha en cadena con formato dd/mm/aaaa al formato 
	 * mm/dd/aaaa para usar en Grids
	 * params:
	 *	-fechaStr: fecha en cadena con formato dd/mm/aaaa
	 */
	function monthDayYear(fechaStr) {
		return fechaStr;
		/*
		var dia = fechaStr.substr(0,2);
		var mes = fechaStr.substr(3,2);
		var ano = fechaStr.substr(6);		
		return  mes + "/" + dia + "/" + ano;
		*/
	}
	
	/* Selecciona y deselecciona todos los checks de una tabla segun el nombre del grupo de imagenes
	 * 
	 * params:
	 *	-chkGroupName: nombre del grupo.
	 *  -valor: valor booleano que activa y desactiva las opciones.
	 *  -oTagA: tag <a> en el que se hace el cambio de mostrar a ocultar y el + por -
	 */
	 // TODO: checkear si 
	function markAllChecks(/*String*/ chkGroupName, /*Bool*/ valor, /*Obj*/ oTagA) {
		
		var chks = document.getElementsByName(chkGroupName);		
		if(chks==null) return;
		for(var i=0;i<chks.length;i++) {
			chks[i].checked = valor;
		}
		if(oTagA.ontrigger!=undefined) {
			eval(oTagA.ontrigger);
		}
		oTagA.onclick = function() { markAllChecks(chkGroupName, !valor, oTagA) };
	}

	/* Deselecciona todos los checks de una tabla segun el nombre del grupo de imagenes
	 * 
	 * params:
	 *	-chkGroupName: nombre del grupo.
	 *  
	 */
	function desMarkChecks(/*String*/ chkGroupName) {
		var chks = document.getElementsByName(chkGroupName);		
		if(chks==null) return;
		for(var i=0;i<chks.length;i++) {
			chks[i].checked = false;
		}
	}

	/* Dedhabilita todos los checks de una tabla segun el nombre del grupo de imagenes
	 * 
	 * params:
	 *	-chkGroupName: nombre del grupo.
	 */
	function disabledAllChecks(/*String*/ chkGroupName) {
		
		var chks = document.getElementsByName(chkGroupName);		
		
		if(chks==null)
			return;	
				
		for(var i=0;i<chks.length;i++) {
						
			chks[i].disabled = true;
		}
	}	

	/* Retorna un arreglo de los valores de los checkboxes checked
	 * 
	 * params:
	 *	-chkGroupName: nombre del grupo.
	 *  -valor: valor booleano que activa y desactiva las opciones.
	 */
	function getChecksValues(/*String*/ chkGroupName) {
		var chks = document.all[chkGroupName];
		var values = new Array();
		var j = 0;
		if(chks!=null) {
			if(chks.length != undefined) {
				for(var i=0;i<chks.length;i++) {
					if(chks[i].checked)	{
						values[j] = parseInt(chks[i].value);
						j++;
					}
				}			 	
			} else if(document.all[chkGroupName].checked) { 
				values[j] = document.all[chkGroupName].value; 
			}
		}
		return values;
	}

	/** Oculta y aparece un elemento en pantalla
	* params: - obj objeto a manipular
	*/
	function mostrarElemento(/*Obj*/ obj) {
		if(obj.style.display == 'none')	{
			obj.style.display = 'block';
		} else {
			obj.style.display = 'none';
		}
	}	

	// Obtiene el evento evluando el caso de mozilla y IE
	function getEvent(e) {
		if(document.all) return event;
		else return e;
	}

	/* Retorna un mensaje de la excepcion devuelta por DWR
	 * 
	 * params:
	 *  -msg: Mensaje con la excepcion capturada.
	 *  TODO: El mensaje no debe desplegarse en un alert. Usar la ventana para mensajes que se defina
	 */
	function exception(msg) {
		//alert(msg); return;
		var w = new Ventana("about:blank");
		w.w = 530;
		w.h = 255;
		w.nombre = "";
		w.scrolls = "yes";
		w.reajustable = "yes";
		w.abrir();

		w.Ventana.document.open();
		w.Ventana.document.write('<html>');
		w.Ventana.document.write('<link rel="stylesheet" type="text/css" href="/resources/theme/estilos.css">');
		w.Ventana.document.write('<script type="text/javascript" src="/resources/javascript/commons.js"></script>');
		w.Ventana.document.write('<head><title>Error crítico en la aplicación</title>');
		
		w.Ventana.document.write('<style type="text/css">');
		w.Ventana.document.write('	html,body { height:100%;width:100%;margin:0px; }');
		w.Ventana.document.write('	a { font-size:10px;font-weight:normal; }');
		w.Ventana.document.write('</style></head>');
					
		w.Ventana.document.write('<body class=""popup_body>');
		
		w.Ventana.document.write('<table class="tabla_contenedor" cellpadding="0" cellspacing="0">');
		w.Ventana.document.write('	<tr>');
		w.Ventana.document.write('		<td valign="top" height="19" id="barra" class="estilo_error"></td>');
		w.Ventana.document.write('	</tr>');
		w.Ventana.document.write('	<tr>');
		w.Ventana.document.write('		<td valign="top">');
		w.Ventana.document.write('			<table border="0" cellspacing="6">');
		w.Ventana.document.write('				<td valign="top">');
		w.Ventana.document.write('					<img src="/resources/imagenes/error.gif" id="imagen" align="absmiddle" /> ');
		w.Ventana.document.write('				</td>');
		w.Ventana.document.write('				<td id="type" class="popup_texto" valign="top">');
		w.Ventana.document.write('					<span class="texto" id="texto">Ha ocurrido un error en la aplicaci&oacute;n, ');
		w.Ventana.document.write('					por favor comuniquese con el Departamento de Sistemas.<br/> Disculpe los inconvenientes causados.</span>');
		w.Ventana.document.write('					<br /><a onclick="mostrarElemento(document.getElementById(\'error\'));" class="a_click" id="link">- Ver detalle del problema</a>');
		w.Ventana.document.write('					<span id="error" class="popup_texto_error"><br /><pre>' + msg + '</pre></span>');
		w.Ventana.document.write('				</td>');
		w.Ventana.document.write('			</table>');
		w.Ventana.document.write('		</td>');
		w.Ventana.document.write('	</tr>');
		w.Ventana.document.write('	<tr height="21">');
		w.Ventana.document.write('		<td height="21" valign="bottom">');
		w.Ventana.document.write('		<table border="0" cellpadding="0" cellspacing="0" class="popup_tabla_botones">');
		w.Ventana.document.write('			<tr height="3"><td height="" class="popup_linea_error" id="linea"></td></tr>');
		w.Ventana.document.write('			<tr>');
		w.Ventana.document.write('				<td height="19" align="right" class="popup_barra_botones">');
		w.Ventana.document.write('					<input type="button" value="Imprimir" id="btnImprimir" class="boton" onclick="mostrarElemento(document.getElementById(\'error\'), true);window.print();" />');
		w.Ventana.document.write('					<input type="button" value="Cerrar" id="btnContinuar" class="boton" onclick="window.close();" />');
		w.Ventana.document.write('				</td>');
		w.Ventana.document.write('		    </tr>');
		w.Ventana.document.write('		</table>');
		w.Ventana.document.write('	</tr>');
		w.Ventana.document.write('</table>');

		w.Ventana.document.write('<script type="text/javascript">');
		w.Ventana.document.write('function mostrarElemento(obj, opt) {');
		w.Ventana.document.write('	if(obj.style.display == "none") { obj.style.display = "block"; document.getElementById("link").innerHTML = "- Ocultar detalle del problema";');
		w.Ventana.document.write('	} else { if(opt == undefined) { obj.style.display = "none"; document.getElementById("link").innerHTML = "- Ver detalle del problema"; } }');
		w.Ventana.document.write('}');
		w.Ventana.document.write('mostrarElemento(document.getElementById("error"));');
		w.Ventana.document.write('</script>');		
		
		w.Ventana.document.write("</body>");
		w.Ventana.document.write("</html>");
		w.Ventana.document.close();		
	}

	/* Borrar el contenido de un input del DOM y lo actualiza con el contenido de valor 
	 * 
	 * params:
	 *  -obj: Objeto input a borrar
	 *  -valor: valor a colocar en el control input
	 */
	function borrarTxtSeleccion(/*Obj*/ obj, /*Int*/ valor) {
		if(valor == -1) obj.value = "";
		else obj.value = valor;
	}

	 /* Permite validar la fecha en formato dd/mm/aaaa. 
	 *  Valida bisiestos y meses de 30 y 31 dias, asegurandose demás de que la fecha sea mayor de 1900 y menor a 2050. 
	 *  Estos valores pueden ser cambiados por el programador
	 * params:
	 *  -caja: Valor string de la fecha a validar
	 *  
	 */
	 function validarFecha(caja)
	 { 
		   if (caja)
		   {  
		      borrar = caja;
		      if ((caja.substr(2,1) == "/") && (caja.substr(5,1) == "/"))
		      {      
		         for (i=0; i<10; i++)
			     {	
		            if (((caja.substr(i,1)<"0") || (caja.substr(i,1)>"9")) && (i != 2) && (i != 5))
					{
		               borrar = '';
		               break;  
					}  
		         }
			     if (borrar)
			     { 
			        a = caja.substr(6,4);
				    m = caja.substr(3,2);
				    d = caja.substr(0,2);
				    if((a < 1900) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31))
				       borrar = '';
				    else
				    {
				       if((a%4 != 0) && (m == 2) && (d > 28))	   
				          borrar = ''; // Año no viciesto y es febrero y el dia es mayor a 28
					   else	
					   {
				          if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29)))
					         borrar = '';	      				  	 
					   }  // else
				    } // fin else
		         } // if (error)
		      } // if ((caja.substr(2,1) == \"/\") && (caja.substr(5,1) == \"/\"))			    			
			  else
			     borrar = '';
			  if (borrar == ''){
			    return false;
			  	
			  }else{
			  	return true;
			  }
			   
		   } // if (caja)
		   return false;
		      
	} // FUNCION
	
	/* Habilita o desabilita un txt desde un checkbox
	 * params:
	 *	-idChk: Id del elemento input checkbox
	 *	-idTxt: Id del elemento input text
	 */
	function habilitarTxt(/* String */ idChk, /* String */idTxt) {
		var chk = $(idChk);
		var txt = $(idTxt);
		if(chk.checked) {
			txt.style.backgroundColor = "#FFFFFF";
			txt.readOnly = false;
			txt.focus();
		} else {
			txt.style.backgroundColor = "#F5F4EA";
			txt.value = "";
			txt.readOnly = true;
		}
	}
	
	/* Formatea un número de la forma ##########.00 a #.###.###.###,00
	 * params:
	 *	-num: numero a formatear
	 *	-format: true para formatear de ##########.00 a #.###.###.###,00.
	 *	 false para formatear de #.###.###.###,00 a ##########.00.
	 */
	function formatCurrency(num, format) {
		var _num = num;
		if(format) {
			if(isNaN(num)) return _num;
			num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num))
				num = "0";
			
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			
			if(cents<10)
				cents = "0" + cents;
			
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
				num = num.substring(0,num.length-(4*i+3))+'.'+
			
			num.substring(num.length-(4*i+3));
			
			return (((sign)?'':'-') +  num + ',' + cents);
		} else {
			var strArr = String(num).split(',');
			var ent = strArr[0].split('.');
			var dec = strArr[1];
			
			num = "";
			for(var i=0; i<ent.length; i++) {
				num += ent[i];
			}
			num += "." + dec;
			
			if(isNaN(num)) return _num;
			
			return Math.round(parseFloat(num)*100)/100;
		}
	}	
	
	function formatearCampoMoneda(/* El */ txt, /* boolean */ format) {
		if(txt.value.length>0) {
			txt.value = formatCurrency(txt.value, format);
		}
	}	
	
	/** Retorna el numero de dias del mes y año seleccionado */ 
	function obtenerDiasMes(mes, ano) {
		var diasMes = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		if (((0 == (ano%4)) && ( (0 != (ano%100)) || (0 == (ano%400)))) && mes == 1) {
			return 29;
		} else {
			return diasMes[mes];
		}
	}
	
	/*Imprime en formato dd de mes de aaaa*/
	function stringDeFecha()
	{
	    var Meses = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
	    var Semanas= new Array ("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado", "Domingo");
	    var NumeroFecha = new Date();
	    var NumeroDia = NumeroFecha.getDate();
	    var NumeroMes = NumeroFecha.getMonth();
	    var NumeroAno = NumeroFecha.getYear();
	    if (NumeroAno <100) NumeroAno ="19"+NumeroAno ;
	    if (navigator.appName=="Netscape") NumeroAno =2001+Math.abs(NumeroAno -100);
	    StringDeFecha=NumeroDia+" de "+ Meses[NumeroMes]+" de "+NumeroAno;
	    return StringDeFecha;
	 }
	
	/* Coloca una fila en al tabla con el mensaje pasado por argumento
	* params: 
	*  - tabla: el objeto tabla al que se le colocara el mensaje.
	*  - msg: mensaje.
	*/
	function setTablaSinRegistros(/*Obj*/ tabla, /*String*/ msg) {
		eliminarFilasTabla(tabla);
		var x = tabla.insertRow(1);
		var fila = x.insertCell();
		var head = tabla.rows[0].cells;
		fila.colSpan = head.length;
		fila.className = "txt_sin_registros";
		fila.innerHTML = msg;
	}
	
	/* Muestra el mensaje de seleccionar un registro
	*  params: -url url de la pagina
	*/
	function sinRegistroSeleccionado(/*String*/ url) {
		erroresValidacion = [];
		erroresValidacion.push({ nombreControl: "", error: "Debe seleccionar al menos un registro." });
		var w = new Ventana(url);
		w.w = 380;
		w.h = 180;
		w.abrir();
	}
	
	/* Impresion de error en pantalla
	* params: 
	*  - msg: mensaje.
	*  - url: página donde se encuentra el error.
	*  - l: línea donde se encuentra el error.
	*/
	function getErrorPagina(/*String*/ msg, /*String*/ url, /*String*/ l) {
		var txt = "Ha ocurrido un error en la página:\n\n";
		txt += "Error: " + msg + "\n";
		txt += "URL: " + url + "\n";
		txt += "Línea: " + l + "\n\n";
		txt += "Por favor cierre la ventana e intente nuevamente.\n\n";
		alert(txt);
		return true;
	}	

	/* Captura el evento keypress
	* params: 
	*  - arr: Array de key presionada y funcion a ejecutar.
	*/
	function getKeyPress(/*Array*/ arr, e) {
		var e = (window.event) ? window.event : e;
		if(e) {
			var keyPress = e.keyCode;
			
			if(e.srcElement && e.srcElement.tagName == "INPUT" && e.srcElement.className == "pt-autocompletar_input") return false;
			
			for(var i=0;i<arr.length;i++) {				
				if(keyPress == arr[i].tecla) {
					if(arr[i].shift) {
						if(e.shiftKey) eval(arr[i].funcion);
					} else if(arr[i].ctrl) {
						if(e.ctrlKey) eval(arr[i].funcion);
					} else if(arr[i].alt) {
						if(e.altKey) eval(arr[i].funcion);						
					} else {
						eval(arr[i].funcion);
					}
					//if(keyPress == 113)
					return false;
				}
			}
		}		
	}
	
	/*Validador de fecha*/
	function valFecha(ctrl){
		if (ctrl.value!= ""){
			if (!validarFecha(ctrl.value)){
			   //ctrl.value="";
			   //ctrl.blur();
			   ctrl.focus();
			   // TODO por definir el mostrar el mensaje de validación.
			   alert("Fecha Errónea.\n"+
			         "Ingrese una fecha en formato dd/mm/aaaa");			   
			   return;	
			}
		}
	}
	
	function lockKeyPress() {
		var msg = 'Funcionalidad Restringida';
		var asciiBack       = 8;
		var asciiTab        = 9;
		var asciiSHIFT      = 16;
		var asciiCTRL       = 17;
		var asciiALT        = 18;
		var asciiHome       = 36;
		var asciiLeftArrow  = 37;
		var asciiRightArrow = 39;
		var asciiMS         = 92;
		var asciiView       = 93;
		var asciiF1         = 112;
		var asciiF2         = 113;
		var asciiF3         = 114;
		var asciiF4         = 115;
		var asciiF5         = 116;
		var asciiF6         = 117;
		var asciiF11        = 122;
		var asciiF12        = 123;
		
		if(document.all) { //ie has to block in the key down
			document.onkeydown = onKeyPress;
		}else if (document.layers || document.getElementById){ //NS and mozilla have to block in the key press
			document.onkeypress = onKeyPress;
		}
		
		function onKeyPress(evt) {
			//window.status = '';
			//get the event object
			var oEvent = (window.event) ? window.event : evt;
			
			//hmmm in mozilla this is jacked, so i have to record these seperate
			//what key was pressed
			var nKeyCode =  oEvent.keyCode ? oEvent.keyCode :
							oEvent.which ? oEvent.which : 
							void 0;
			
			var bIsFunctionKey = false;
		
			//hmmm in mozilla the keycode would contain a function key ONLY IF the charcode IS 0    
			//else key code and charcode read funny, the charcode for 't' 
			//returns 116, which is the same as the ascii for F5
			//SOOO,... to check if a the keycode is truly a function key, 
			//ONLY check when the charcode is null OR 0, IE returns null, mozilla returns 0 
			if(oEvent.charCode == null || oEvent.charCode == 0)
			{ 
				bIsFunctionKey = (nKeyCode >= asciiF2 && nKeyCode <= asciiF12) || (nKeyCode == asciiALT || nKeyCode == asciiMS || nKeyCode == asciiView || nKeyCode == asciiHome || nKeyCode == asciiBack)
			}
			
			//convert the key to a character, makes for more readable code  
			var sChar = String.fromCharCode(nKeyCode).toUpperCase();
		
			//get the active tag that has the focus on the page, and its tag type
			var oTarget = (oEvent.target) ? oEvent.target : oEvent.srcElement;
			var sTag = oTarget.tagName.toLowerCase();
			var sTagType = oTarget.getAttribute("type");
			
			var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
			var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
			var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
			//var bMetaPressed = (oEvent.metaKey) ? oEvent.metaKey : oEvent.modifiers & 8 > 0;
		
			var bRet = true; //assume true as that will be the case most times
			//alert (nKeyCode + ' ' + sChar + ' ' + sTag + ' ' + sTagType + ' ' + bShiftPressed + ' ' + bCtrlPressed + ' ' + bAltPressed);
		
			if(sTagType != null){sTagType = sTagType.toLowerCase();}
		
			//allow these keys inside a text box
			if  (sTag == "textarea" || (sTag == "input" && (sTagType == "text" || sTagType == "password")) &&  (nKeyCode == asciiBack || nKeyCode == asciiSHIFT || nKeyCode == asciiHome || bShiftPressed ||  (bCtrlPressed && (nKeyCode == asciiLeftArrow || nKeyCode == asciiRightArrow)))){
				return true;
			}else if(bAltPressed && (nKeyCode == asciiLeftArrow || nKeyCode == asciiRightArrow)){ // block alt + left or right arrow
				bRet = false;
			}else if(bCtrlPressed && (sChar == 'A' || sChar == 'C' || sChar == 'V' || sChar == 'X')){ // ALLOW cut, copy and paste, and SELECT ALL
				bRet = true;
			}else if(bShiftPressed && nKeyCode == asciiTab){//allow shift + tab
				bRet = true;
			}else if(bIsFunctionKey){ // Capture and stop these keys
				bRet = false;
			}else if(bCtrlPressed || bShiftPressed || bAltPressed){ //block ALL other sequences, includes CTRL+O, CTRL+P, CTRL+N, etc....
				bRet = false;
			}
			
			if(!bRet){
				try{
					oEvent.returnValue = false;
					oEvent.cancelBubble = true;
		
					if(document.all){ //IE
						oEvent.keyCode = 0;
					}else{ //NS
						oEvent.preventDefault();
						oEvent.stopPropagation();
					}
					//alert(msg); 
				}catch(ex){
					//alert(ex);
				}
			}
			return bRet;
		}
	}
	
	/* Obtiene una fecha dado un numero de dias a partir de la fecha actual
	 * params:
	 *	-numeroDias: Numero de dias
	 * return String de fecha
	 */
	 function obtenerFechaAutomatica(/*int*/ numeroDias){
		var fechaActual = new Date();
		
		datDate1 = Date.parse(fechaActual.toUTCString());
		datDate2 = (numeroDias*24*60*60*1000)+ datDate1;
			
		var d = new Date();
		d.setTime(datDate2);
		
		dia = (d.getDate()<10) ? "0" + d.getDate() : d.getDate();
		mes = parseInt(d.getMonth()) + 1;
		mes = (mes <10) ? "0" + mes : mes;
		anno = d.getYear();
			
		fechaGenerada = dia + "/" + mes + "/" + anno;
		return fechaGenerada;		
	
	}
		
	/* Determina  la metadata existe en el DOM
	 * params:
	 *	name: Nombre de la Metadata
	 * return true si existe, false si no existe
	 */
	function obtenerMetaData(name) {
		var metaArray = document.getElementsByTagName("meta"); 
		for(var i=0; metaArray[i]; i++) {
			if(metaArray[i].getAttribute(name) != null) {
				return true;
			}
		}
		return false;
	}
	
	/*Funcion que deshabilita/habilita controles
	  true: Deshabilita
	  false: Habilita	
	*/	
	function deshabilitarFormulario(arrControles, bool) {
		if (bool) {
			for(i=0; i<arrControles.length; i++) {
				$(arrControles[i]).disabled = true;			
			}
		} else {
			for(i=0; i<arrControles.length; i++) {
				$(arrControles[i]).disabled = false;			
			}
		}
	}
	
	/* 
	* OBJETOS GENERALES 
	*/
	
	/* objeto tecla la captura de los keypress */
	function Tecla(/*Int*/ tecla, /*Fnc*/ funcion) {
		this.tecla = tecla;
		this.funcion = funcion;
		this.shift = false;
		this.ctrl = false;
		this.alt = false; 
	}
	
	/* objeto ventana para la manipulacion de los popups */
	function Ventana() {
		
		this.url = "";
		this.w = 420;
		this.h = 200;
		this.estatus = true;
		this.reajustable = false;
		this.scrolls = false;
		this.menu = false;
		this.nombre = "popup";
		this.Ventana = null;
		
		if(arguments.length > 1) {
			this.setAtributos(arguments);
		} else {
			this.url = (arguments[0]==undefined)?"":arguments[0];
		}

		this.abrir = function () {
			if(arguments.length > 1) this.setAtributos(arguments);
			var x = (screen.width - this.w) / 2;
			var y = (screen.height - this.h) / 2;
			var sc = (this.scrolls)?"yes":"no";
			var ra = (this.reajustable)?"yes":"no";
			var et = (this.estatus)?"yes":"no";
			this.h += 27;
			var featu = 'width=' + (this.w - 10) + ', height=' + (this.h - 59) + ', screenX=' + x + ', screenY=' + y + 
			', top=' + y + ', left=' + x + ', scrollbars=' + sc + ', status=' + et + 
			', resizable=' + ra + ', menubar=no';
			
			var wind = window.open(this.url, this.nombre, featu);
			
			if(esBloqueado(wind)) return;
			
			wind.resizeTo(this.w, this.h);
			wind.moveTo(x, y);
			wind.focus();
			this.Ventana = wind;
		};
		
		this.abrirResolucion = function() {
			var w = (screen.width);
			var h = (screen.height);
			var x = (screen.width - w) / 2;
			var y = (screen.height - h) / 2;
			var sc = (this.scrolls)?"yes":"no";
			var ra = (this.reajustable)?"yes":"no";
			var et = (this.estatus)?"yes":"no";
			var mn = (this.menu)?"yes":"no";					
			var featu = 'width=' + (w - 12) + ', height=' + (h - 90) + ', screenX=' + x + ', screenY=' + y + 
			', top=' + y + ', left=' + x + ', scrollbars=' + sc + ', status=' + et + ', resizable=' + ra + 
			', menubar=' + mn;
			
			var wind = window.open(this.url, this.nombre, featu);
			
			if(esBloqueado(wind)) return;
			
			wind.focus();
			this.Ventana = wind;
		};

		this.setAtributos = function (a) {			
			this.url = a[0];
			this.w = a[1];
			this.h = a[2];
		};
		
		function esBloqueado(w) {
			if (w == null) {
				alert("No es posible abrir esta ventana.\nDebe deshabilitar el bloqueo de ventanas emergentes\npara continuar.\n\nPor favor comunicarse con Soporte."); 
				return true; 			
			}
			return false;
		};
		
		this.cerrar = function() {
			if(this.Ventana != null)
				this.Ventana.close();
		};
		
		this.destroy = function() {
			//this.cerrar();
			this.Ventana = null;
			return null;
		};
		
	}
	
	/* Objeto para la manipulación del MultiTask Panel
	 *	params:
	 *		-String nombre: Nombre (id) del panel multitask
	 *		-
	 */
	function MultiTask(/* String */ nombre) {
	
		if(arguments.length==0) return;
		var tags = $(nombre).getElementsByTagName('a');
		
		for(var i=0; i<tags.length; i++) {
			tags[i].trigger = tags[i].onclick;
			tags[i].enabled = true;
			
			tags[i].onclick = function() {
				if(this.enabled) {
					this.trigger();
				}
			};
		}
	
		this.habilitar = function(/* int */ i, /* boolean */ habilitado) {
			tags[i].enabled = habilitado;
			var img = tags[i].getElementsByTagName('img');
			if(habilitado) {
				tags[i].className = "a_click";
				img[0].src = img[0].src.replace("low","high");
			} else {
				tags[i].className = "";
				img[0].src = img[0].src.replace("high","low");			
			}
		};
		
		var chkCount=0;
		this.chkEvent = function(/* El */ chk) {
			if(chk.checked) {
				chkCount++;
			} else {
				chkCount--;
			}
			if(chkCount>1) {
				for(var i=0; i<tags.length; i++) {
					if(tags[i].multi!=undefined&&tags[i].multi=="false") {
						this.habilitar(i,false);
					}
				}
			} else {
				for(var i=0; i<tags.length; i++) {
					if(tags[i].multi!=undefined&&tags[i].multi=="false") {
						this.habilitar(i,true);
					}
				}
			}
		};
	}

	function Boton(/* String */ id) {
		var btn = document.getElementById(id);
		btn.enabled = true;
		btn.trigger = btn.onclick;

		btn.onclick = function() {
			if(this.enabled) {
				this.trigger();
			}
		};
		
		btn.enable = function(/* boolean */ _enable) {
			this.enabled = _enable;
			var img = this.getElementsByTagName('img');
			if(_enable) {
				this.className = "a_click";
				this.src = this.src.replace("low","high");
				//img[0].src = img[0].src.replace("low","high");
			} else {
				this.className = "";
				this.src = this.src.replace("high","low");			
				//img[0].src = img[0].src.replace("high","low");			
			}
		};
		
		return btn;
	}
	//calcular la edad de una persona
	//recibe la fecha como un string en formato español
	//devuelve un entero con la edad. Devuelve false en caso de que la fecha sea incorrecta o mayor que el dia actual
	function calcularEdad(fecha){
	
	    //calculo la fecha de hoy
	    hoy=new Date()
	    //alert(hoy)
	
	    //calculo la fecha que recibo
	    //La descompongo en un array
	    var array_fecha = fecha.split("/")
	    //si el array no tiene tres partes, la fecha es incorrecta
	    if (array_fecha.length!=3)
	       return false
	
	    //compruebo que los ano, mes, dia son correctos
	    var ano
	    ano = parseInt(array_fecha[2]);
	    if (isNaN(ano))
	       return false
	
	    var mes
	    mes = parseInt(array_fecha[1]);
	    if (isNaN(mes))
	       return false
	
	    var dia
	    dia = parseInt(array_fecha[0]);
	    if (isNaN(dia))
	       return false
	
	
	    //si el año de la fecha que recibo solo tiene 2 cifras hay que cambiarlo a 4
	    if (ano<=99)
	       ano +=1900
	
	    //resto los años de las dos fechas
	    edad=hoy.getYear()- ano - 1; //-1 porque no se si ha cumplido años ya este año
	
	    //si resto los meses y me da menor que 0 entonces no ha cumplido años. Si da mayor si ha cumplido
	    if (hoy.getMonth() + 1 - mes < 0) //+ 1 porque los meses empiezan en 0
	       return edad
	    if (hoy.getMonth() + 1 - mes > 0)
	       return edad+1
	
	    //entonces es que eran iguales. miro los dias
	    //si resto los dias y me da menor que 0 entonces no ha cumplido años. Si da mayor o igual si ha cumplido
	    if (hoy.getUTCDate() - dia >= 0)
	       return edad + 1
	
	    return edad
	}
	
	/* ejecuta fnc cuando el iframe finaliza su carga, cada "ms" milisegundos se ejecuta fnc2*/
	function esperar(iframe, fnc, fnc2, ms) {
		if (iframe.document.readyState == "complete") {
			fnc();
		} else {
			setTimeout(function() { esperar(iframe, fnc, fnc2) }, ms);
			if (fnc2!=null) fnc2();
		}
	}
	
	/* imprime el reporte que se encuentra dentro del iframe */
	function imprimirReporte(iframe) {
		iframe.CrystalViewerCrystalEvent('CrystalViewer', 'tb=crprint');
	}
	
	function imprimirElemento(contenedor, titulo) {
		try {
			contenedor = $(contenedor);
			var nombreFrame = contenedor.id + "__iFramePrint";
			if($(nombreFrame) == undefined) {
				var iframe = document.createElement("IFRAME");
				iframe.width = "500";
				iframe.height = "500";
				iframe.frameBorder = "1";
				iframe.id = nombreFrame;
				iframe.name = nombreFrame;
				document.body.appendChild(iframe);
			}
			if(!titulo) titulo = "";
			document.frames[nombreFrame].document.open();
			document.frames[nombreFrame].document.write("<html>");
			document.frames[nombreFrame].document.write("<body>");
			document.frames[nombreFrame].document.write("<style> body, table { font-family:Arial, Verdana; font-size: 12px; } " +
								 "th { background-color:#ccc; } table, td, th, tr { border:0px solid #ccc; } </style>");
			document.frames[nombreFrame].document.write("<h2>" + titulo + "</h2>");
			document.frames[nombreFrame].document.write("<table cellspacing='0' cellpadding='1' width='100%'><tr><td>" + contenedor.innerHTML + "</td></tr></table>");
			document.frames[nombreFrame].document.write("<hr /><br />Fecha de Impresión: <script>document.write(new Date().toLocaleString());</script>");
			document.frames[nombreFrame].document.write("</body>");
			document.frames[nombreFrame].document.write("</html>");
			document.frames[nombreFrame].document.close();

			//alert(document.frames[nombreFrame].document.body.innerHTML);

			window.frames[nombreFrame].focus();
			window.frames[nombreFrame].print();

		} catch(e) {
			alert("No es posible imprimir este objeto.\nError: " + e.message);	
		}
	}

	/*Redondea un numero. Debe ser usada en las sumatorias de numeros*/
	function redondeo(num){
		
		var _num = num;

		if(isNaN(num)) return _num;
			num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num))
				num = "0";
			
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			
			if(cents<10)
				cents = "0" + cents;
			
			
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
				num = num.substring(0,num.length-(4*i+3)) +
			
			
			num.substring(num.length-(4*i+3));
			
			return (((sign)?'':'-') +  num + '.' + cents);

	}
	
	/* Devuelve un arreglo de Objetos Json con los meses del anno para ser usado en ComboBox.*/
	function llenarDataMeses(){
	
		var temp = [];
		var meses = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
		var i;
	
		for(i=0;i<meses.length;i++){
		    temp[i] = {descripcion: meses[i], valor: i+1};
		}
		
		return temp;
	}
	
	
	/*Devuelve un arreglo de Objetos Json con un rango de años  -2 Año Actual, Año Actual, +2 Año Actual

	*/
	function llenarDataAnnos(){
	
			
		var annos = [];
		var annoFinal;
		var i;
	
		var d = new Date()
		annoActual = d.getFullYear();
	
		annoInicial = annoActual - 2;
		//annoFinal = annoActual + 2;
		
		//cantidadAnnos = annoFinal - annoInicial + 1;
					
		for(i=0;i<5;i++){
		    annos[i] = {descripcion: annoInicial, valor: annoInicial};
			annoInicial++;
		}
		
		return annos;
	
	}
	
	var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
	function LZ(x) {return(x<0||x>9?"":"0")+x}
	function formatDate(date,format) {
		format=format+"";
		var result="";
		var i_format=0;
		var c="";
		var token="";
		var y=date.getYear()+"";
		var M=date.getMonth()+1;
		var d=date.getDate();
		var E=date.getDay();
		var H=date.getHours();
		var m=date.getMinutes();
		var s=date.getSeconds();
		var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
		// Convert real date parts into formatted versions
		var value=new Object();
		if (y.length < 4) {y=""+(y-0+1900);}
		value["y"]=""+y;
		value["yyyy"]=y;
		value["yy"]=y.substring(2,4);
		value["M"]=M;
		value["MM"]=LZ(M);
		value["MMM"]=MONTH_NAMES[M-1];
		value["NNN"]=MONTH_NAMES[M+11];
		value["d"]=d;
		value["dd"]=LZ(d);
		value["E"]=DAY_NAMES[E+7];
		value["EE"]=DAY_NAMES[E];
		value["H"]=H;
		value["HH"]=LZ(H);
		if (H==0){value["h"]=12;}
		else if (H>12){value["h"]=H-12;}
		else {value["h"]=H;}
		value["hh"]=LZ(value["h"]);
		if (H>11){value["K"]=H-12;} else {value["K"]=H;}
		value["k"]=H+1;
		value["KK"]=LZ(value["K"]);
		value["kk"]=LZ(value["k"]);
		if (H > 11) { value["a"]="PM"; }
		else { value["a"]="AM"; }
		value["m"]=m;
		value["mm"]=LZ(m);
		value["s"]=s;
		value["ss"]=LZ(s);
		while (i_format < format.length) {
			c=format.charAt(i_format);
			token="";
			while ((format.charAt(i_format)==c) && (i_format < format.length)) {
				token += format.charAt(i_format++);
				}
			if (value[token] != null) { result=result + value[token]; }
			else { result=result + token; }
			}
		return result;
	}
	
	