function MM_findObj(n, d) { //v4.01
    var p,i,x;

    if(!d) {
        d=document;
    }

    if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
    }

    if(!(x=d[n]) && d.all) {
        x=d.all[n];
    }

    for (i=0; !x && i<d.forms.length; i++) {
        x = d.forms[i][n];
    }

    for(i=0;!x&&d.layers&&i<d.layers.length;i++) {
        x = MM_findObj(n,d.layers[i].document);
    }

    if(!x && d.getElementById) {
        x=d.getElementById(n);
    }

    return x;
}

function MM_validateForm() { //v4.1rbf
    var i,p,q,nm,test,msg,num,min,max,errors='',args=MM_validateForm.arguments,error=false;
	//var mikExp = /[$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|\<\>]/;
	var mikExp = /[\^\{\}\`\|\<\>]/;
	var mikExpSinEspacios = /[$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|\<\>\s]/;
	
    for (i=0; i<(args.length-1); i+=3) {

        test=args[i+1];
        val=MM_findObj(args[i]);
		if (!error)
			val2=MM_findObj(args[i]);
		nm=args[i+2]; //El nombre del CAMPO manda el ALERT
		
        if (val) {
            //nm=val.name;
            //si es combo
            if (test.indexOf('isCombo')!=-1) {
        		if (val.options[val.selectedIndex].value == 0) {
        			errors+='- \"'+nm+'\" es obligatorio.\n';
        			error = true;
        		}
            } else if ((val=val.value)!="") {
				if (test.indexOf('isTextSinEspacios')!=-1) {
					if(val.search(mikExpSinEspacios) > -1) {
						errors+='- \"'+nm+'\" contiene caracteres invalidos (No se admiten espacios): ' + val + '.\n';
						error = true;
					}
                } else if (test.indexOf('isText')!=-1) {
					if(val.search(mikExp) > -1) {
						errors+='- \"'+nm+'\" contiene caracteres invalidos: ' + val + '.\n';
						error = true;
					}
                } else if (test.indexOf('isURL')!=-1) {
					if (!(/^(http:\/\/\w+(\.\w+)*\/)?(\w+)?(\/(\w+|\.\.|\.))*(\?\w+=\w+(&\w+=\w+)*)?$/.test(val))) {
						errors+='- \"'+nm+'\" debe contener un URL valido.\n';
						error = true;
					}
                } else if (test.indexOf('isPathToFile')!=-1) {
					//if (!(/^(([A-Za-z0-9_-\(\) ]+|\.\.|\.)\/)*[A-Za-z0-9_-\(\) ]+$/.test(val))) {
					if (!(/^(([A-Za-z0-9_\(\)]+|\.\.|\.)\/)*[A-Za-z0-9_\(\)]+$/.test(val))) {
						errors+='- \"'+nm+'\" debe contener una ruta valida a un archivo.\n';
						error = true;
					}
                } else if (test.indexOf('isEmail')!=-1) {
                    p=val.indexOf('@');
                    if (p<1 || p==(val.length-1)) {
                        errors+='- \"'+nm+'\" debe contener una direccion de correo electronico.\n';
						error = true;
                    //} else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(val))) {						
                    } else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)+$/.test(val))) {
						errors+='- \"'+nm+'\" contiene una direccion de correo invalida: ' + val + '.\n';
						error = true;
					}
                } else if (test.indexOf('isDate')!=-1) {

                    dia = val.substring(0,2);
                    s1  = val.substring(2,3);
                    mes = val.substring(3,5);
                    s2  = val.substring(5,6);
                    ano = val.substring(6,10);

                    if ( (val.length!=10) || // el formato de fecha es de 10 caracteres
                            (isNaN(dia)) || // verificar el dia
                            (isNaN(mes)) || // verificar el mes
                            (isNaN(ano)) || // verificar el anio
                            (s1!="/") || (s2!="/") ) { // verificar los separadores
                        errors+='- \"'+nm+'\" debe contener una fecha (dd/mm/aaaa).\n';
            			error = true;
           		    } else if ((ano < 1900) || (ano > 2079)) {
	           			errors+='- \"'+nm+'\" contiene una fecha invalida: ' + val + '.\n';
            			error = true;
                    } else if (!validaFecha(dia,mes,ano)) {
            			errors+='- \"'+nm+'\" contiene una fecha invalida: ' + val + '.\n';
            			error = true;            		
           		    }

                } else if (test.indexOf('isTime')!=-1) {

                    hora = val.substring(0,2);
                    sep  = val.substring(2,3);
                    min  = val.substring(3,5);

                    if ( (val.length!=5) ||  // el formato de horario es de 5 caracteres ##:##
                         (isNaN(hora)) ||  // verificar la hora
                         (isNaN(min)) || // verificar el minuto
                         (sep!=":")) {  // verificar el separador
                        errors+='- \"'+nm+'\" debe contener una hora (hh:mm de 00:00 a 23:59).\n';
						error = true;
		    		} else if ((hora < 0) || (hora > 23) || (min < 0) || (min > 59)) {
						errors+='- \"'+nm+'\" contiene una hora invalida: ' + val + '.\n';
						error = true;
                    }
                } else if (test!='R') {
                    num = parseFloat(val);

                    if (test.indexOf('isSignedNum') != -1 || test.indexOf('isNum') != -1) {
						if (!(/^[-+]?\d+$/.test(val))) {
							errors+='- \"'+nm+'\" debe contener un numero entero.\n';
							error = true;
							break;
						}
    	    	    }

                    if (test.indexOf('isUnsignedNum') != -1 || test.indexOf('isInteger') != -1) {
						if (!(/^\d+$/.test(val))) {
							errors+='- \"'+nm+'\" debe contener un número entero sin signo.\n';
							error = true;
							break;
						}
                    }

                    if (test.indexOf('isOnlyNumbers') != -1) {
						if (!(/^\d+$/.test(val))) {
							errors+='- \"'+nm+'\" solo acepta números.\n';
							error = true;
							break;
						}
                    }

                    if (test.indexOf('isCurrency') != -1) {
                        if (!(/^[-+]?\d*\.\d\d$/.test(val))) {
                        	errors+='- \"'+nm+'\" debe contener un numero con 2 decimales.\n';
							error = true;
                        }
                    }

                    if (test.indexOf('isFloat') != -1) {
                        if (!(/^[-+]?\d*\.?\d+$/.test(val))) {
                            errors+='- \"'+nm+'\" debe contener un numero.\n';
							error = true;
                        }
                    }

                    if (test.indexOf('isPorcent4_4') != -1) {
                        if (!(/^[-+]?\d\d\d\d\.\d\d\d\d$/.test(val))) {
                            errors+='- \"'+nm+'\" debe contener un numero con 4 enteros 4 decimales.\n';
							error = true;
                        }
                    }

                    if (test.indexOf('isPorcent1_1') != -1) {
                        if (!(/^[-+]?\d\.\d$/.test(val))) {
                            errors+='- \"'+nm+'\" debe contener un numero con 1 entero 1 decimal.\n';
							error = true;
                        }
                    }

                    if (test.indexOf('inRange') != -1) {
                        p=test.indexOf(':');
                        min=test.substring(8,p); max=test.substring(p+1);

                        if (num<min || max<num) {
                            errors+='- \"'+nm+'\" debe contener un numero entre '+min+' y '+max+'.\n';
							error = true;
                        }
                    }
                }
            } else if (test.charAt(0) == 'R') {
                errors += '- \"'+nm+'\" es obligatorio.\n';
				error = true;
            }
        }
    }

    if (errors) {
        alert('Ocurrieron los siguientes errores:\n'+errors);
		val2.focus();
    }

    document.MM_returnValue = (errors == '');
}

function validaFecha(myDayStr, myMonthStr, myYearStr) {

	if ((myDayStr > 31) || (myMonthStr > 12)) {
		return false;
	}
 
	var myDate = new Date(myYearStr, myMonthStr-1, myDayStr);

	/* Cuando una fecha es invalida, al convertirla a Date()
	   el mes (getMonth()) se recorre automaticamente, resultando
	   diferente de myMonthStr-1 */	
	return (parseInt(myDate.getMonth())) == parseInt(myMonthStr-1);
}

//Funcion para validar que el folio sea de 17 digitos      
function MM_validateFolio(folio) {  
 	var errors='',error=false;
  
    if (folio.value.length < 17){ 
		 errors+='- El Folio debe ser de 17 dígitos ' + '.\n';
		 error = true;
    }
   
	if (errors) {
        alert('Ocurrieron los siguientes errores:\n'+errors);
		
    }
 
    document.MM_returnValueFolio = (errors == '');
    
}      


	function TextoCorrecto(strCadena)
	{
		var nIndex = 0;
		
		if (strCadena.length > 0) {
			for (nIndex ; nIndex < strCadena.length; nIndex++)
			{
				if ((strCadena.charAt(nIndex) == "<") || (strCadena.charAt(nIndex) == ">")
					|| (strCadena.charAt(nIndex) == "&"))
					return false;
			}
		}
		return true;
	}

function formatCurrency( num ) {
        var isNegative = false;
        num = num.toString().replace(/\\$|\\,/g,'');
        if( isNaN( num ) ) {
          num = "0";
        }
        if ( num < 0 ) {
          num = Math.abs( num );
          isNegative = true;
        }
        cents = Math.floor( ( num * 100 + 0.5 ) % 100 );
        num = Math.floor( ( num * 100 + 0.5 ) / 100 ).toString();
        if ( cents < 10 ) {
          cents = "0" + cents;
        }
        for ( 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 ) );
        }

        var result = num + '.' + cents;
        if ( isNegative ) {
          result = "-" + result;
        }
        return result;
      }


// FUNCIONES GENERALES DE JAVA
// Este archivo <FuncionesJava.js> se debe encontrar en la carpeta _private

	// Trim.- Elimina los espacios de la derecha y de la izquierda de una "Cadena"
	function Trim(strCadena) // Debe ir en un archivo de Funciones
	{
		var strCadenaTmp;
		var nIndex, nIndex2;
		
		for (nIndex=0; nIndex < strCadena.length; nIndex++)
		{
			if (strCadena.charAt(nIndex) != " ") {
				break;
			}
			/*else
				if (strVar.charAt(nIndex) != " ")
					CadenaTmp=Concatenar(CadenaTmp, strVar.charAt(nIndex));*/
		}
		for (nIndex2 = strCadena.length-1; nIndex2 >= 0 && nIndex < strCadena.length; nIndex2--)
		{
			if (strCadena.charAt(nIndex2) != " ") {
				break;
			}
		}
		//Se concatenan CadenaTmp desde nIndex hasta nIndex2
		strCadenaTmp = ""
		if (nIndex <= nIndex2)
			strCadenaTmp = strCadena.substring(nIndex, nIndex2 + 1);
		return strCadenaTmp;
	}


	// NumeroCorrecto.- Valida que una Cadena sea un 'número entero' válido
	function NumeroCorrecto(strCadena)
	{
		var nIndex = 0;
		
		if (strCadena.length > 0) {
			for (nIndex ; nIndex < strCadena.length; nIndex++)
			{
				if ((strCadena.charAt(nIndex) < "0") || (strCadena.charAt(nIndex) > "9"))
					return false;
			}
		}
		return true;
	}

	// DecimalCorrecto.- Valida que una Cadena sea un 'número double' válido
	function DecimalCorrecto(strCadena)
	{
		var nIndex = 0;
		var numPuntos = 0;
		if (strCadena.length > 0) {
			for (nIndex ; nIndex < strCadena.length; nIndex++)
			{
				if ((strCadena.charAt(nIndex) < "0") || (strCadena.charAt(nIndex) > "9")){
					if(!(strCadena.charAt(nIndex) == '.' && ++numPuntos <= 1)){						
						return false;
					}
				}
			}
		}
		return true;
	}

	// TextoCorrecto.- Valida que una Cadena no contenga los simbolos < , > y &
	function TextoCorrecto(strCadena)
	{
		var nIndex = 0;
		
		if (strCadena.length > 0) {
			for (nIndex ; nIndex < strCadena.length; nIndex++)
			{
				if ((strCadena.charAt(nIndex) == "<") || (strCadena.charAt(nIndex) == ">")
					|| (strCadena.charAt(nIndex) == "&"))
					return false;
			}
		}
		return true;
	}

	//getParameter.- Regresa un parametro de una liga url
	function getParameter(liga,parametro){
		var posLiga, posParam = -1;
		var enCharEspecial = false;
		var enValor = false;
		var valor = "";
		parametro += "=";
		for (posLiga = 0 ;posLiga < liga.length; posLiga++){
		  if(liga.charAt(posLiga) == "?" || liga.charAt(posLiga) == "&"){
		    if(enValor){
		      return valor;
		    }else{
		      enCharEspecial = true;
		    }
		  }else{
		    if(enValor){
		      valor += liga.charAt(posLiga);
		    }else{
		      if(enCharEspecial){
		        if(liga.charAt(posLiga) == parametro.charAt(++posParam)){
		          if(posParam == parametro.length-1){
		            enValor = true
		          }
		        }else{
		          enCharEspecial = false;
		          posParam = -1;
		        }
		      }
		    }
		  }
		}
		return valor;
	}

	//validaFrames.- Si la pagina no esta dentro de frames manda a pagina de error
	function validaFrames(){
		var ns = navigator.appName == "Netscape";
		if(!ns){
			if(window.parent.document.all["body"]){
				document.location.href = "Error.jsp?"
				+ "funcion=No definido"
				+ "&error=" + "La página solicitada es inválida";
			}
		}
	}

	//comboValue.- Regresa el valor del objeto seleccionado
	function comboValue(combo){
		return combo.options[combo.selectedIndex].value;
	}

	//comboTexto.- Regresa el texto del objeto seleccionado
	function comboTexto(combo){
		return combo.options[combo.selectedIndex].text;
	}

	//radioValue.- Regresa el valor del radio boton señalado o cadena vacia si
	//ninguno esta señalado
	function radioValue(radio){
		for(i=0; i<radio.length; i++){
			if(radio[i].checked){
				return radio[i].value;
			}
		}
		return "";
	}

	//radioSelected.- Regresa true si un radio buton esta seleccionado, false 
	//en caso contrario
	function radioSelected(radio){
		for(i=0; i<radio.length; i++){
			if(radio[i].checked){
				return true;
			}
		}
		return false;
	}

	//wait.- Metodo para esperar cierto tiempo
	function wait(time){
		var t = 0;
		while (t < time){
			t = t+1;
		}
	}

	//checkboxValue.- Regresa S si esta seleccionado o N en otro caso
	function checkboxValue(checkb){
		if(checkb.checked == true){
			return "S";
		}
		return "N";
	}

	// MensajeInicioLoad.- Este mensaje muestra cada página cuando inicia su carga
	function MensajeInicioLoad() {
		statusBarMsg("Cargando página ...");
		return;
	}

	// MensajeFinLoad.- Este mensaje muestra cada página cuando termina su carga
	function MensajeFinLoad() {
		statusBarMsg("Listo");
		return;
	}
	
	//Obtiene los dias de diferencia entre una fecha y otra
	//Regresa un numero negativo si la 1er fecha es MAYOR a la 2da
	var SECOND = 1000; // el numero de milisegundos en un segundo
	var MINUTE = SECOND * 60; // el numero de milisegundos en un minuto
	var HOUR = MINUTE * 60; // el numero de milisegundos en una hora
	var DAY = HOUR * 24; // el numero de milisegundos en un dia
	var WEEK = DAY * 7; // el numero de milisegundos en una semana

	function daysBetween(fecha1, fecha2) {
		dia1 = fecha1.substring(0,2);
                mes1 = fecha1.substring(3,5);
                anio1 = fecha1.substring(6,10);
                dia2 = fecha2.substring(0,2);
                mes2 = fecha2.substring(3,5);
                anio2 = fecha2.substring(6,10);
		var nTime = Date.UTC(anio1, mes1 - 1, dia1); // especifica tiempo (UTC)
		var dTime = Date.UTC(anio2, mes2 - 1, dia2); // especifica tiempo (UTC)
		//var bTime = Math.abs(nTime - dTime)  // diferencia de tiempo
		var bTime = dTime - nTime;  // diferencia de tiempo
		return Math.round(bTime / DAY);
		//alert(Math.round(bTime / DAY));
	}
	
	function statusBarMsg(msg) {
		//alert(msg);
		window.status=msg;
		setTimeout("window.status=''",5000);
	}
	
	function MM_validatePassword() { //v4.1
    var i,p,q,nm,test,msg,num,min,max,errors='',args=MM_validatePassword.arguments,error=false;

	var mikExpNum = /[0\\1\\2\\3\\4\\5\\6\\7\\8\\9]/;
	var mikExpAlfa = /[a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k\\l\\m\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z\\A\\B\\C\\D\\E\\F\\G\\H\\I\\J\\K\\L\\M\\N\\O\\P\\Q\\R\\S\\T\\U\\V\\W\\X\\Y\\Z]/;

    for (i=0; i<(args.length-1); i+=3) {

        test=args[i+1]; // RisText (p.e)
        val=MM_findObj(args[i]); // us_respuesta (p.e.) Busca Objeto
		if (!error)
			val2=MM_findObj(args[i]);
			
		nm=args[i+2]; //El nombre del CAMPO manda el ALERT. (p.e. Pregunta)
		
        if (val) { // Si el campo existe
            if ( (val=val.value) != "" ) { // Si tiene algún valor el Objeto (el valor lo asigna a 'val')
                if (test.indexOf('isPassword')!=-1) {
                	if (val.length < 9 ) { // Valida que la longitud del Password sea de al menos 8 posiciones
						errors+='- \"'+nm+'\" debe contener 9 caracteres, corrija por favor ' + '.\n';
						error = true;
					}
                	if (val.length > 9 ) { // Valida que la longitud del Password sea de al menos 8 posiciones
						errors+='- \"'+nm+'\" debe contener 9 caracteres, corrija por favor ' + '.\n';
						error = true;
                	} else if(! (val.search(mikExpAlfa) > -1 )) { // En caso de que NO lo haya encontrado en los caracteres Alfabeticos manda un Error
						errors+='- \"'+nm+'\" debe contener letras y números, corrija por favor' +'.\n';
						error = true;
					} else 	if(! (val.search(mikExpNum) > -1 )) { // En caso de que NO lo haya encontrado en los caracteres Numéricos manda un Error
						errors+='- \"'+nm+'\" debe contener letras y números, corrija por favor' + '.\n';
						error = true;
					}
                } 
            } else if (test.charAt(0) == 'R') {
                errors += '- \"'+nm+'\" es obligatorio.\n';
				error = true;
            }
        }
    } // For para revisar los datos

    if (errors) {
        alert('Ocurrieron los siguientes errores:\n'+errors);
		val2.focus();
    }
    document.MM_returnValue = (errors == '');
}