/**
 * Validador de formularios
 *
 * Este es un validador de formularios que permite el uso
 * de atributos dentro de los tags del formulario (inputs y textareas)
 * para verificar la informacion antes de ser enviada al servidor.
 *
 * Funciona de manera simple. Ejemplo
 * <TAGFORMA name="xx" ... validate="[OPCIONES:=O1|O2|..|On]" msg="Mensaje de error" [ffocus="campo a foco"]>
 *
 * Opciones son:
 * R -> campo requerido.
 * E -> direccion de correo electronico
 * F -> real (positivo y negativo).
   P -> real (positivo)
 * I -> entero (positivo y negativo)
 * G -> GMT ((+-)H:MM o (+-)H)
 * A -> nn.nn.nn.nn.nn (numero de registro de partida arancelaria)
 * U -> nombre de usuario (letras y guion)
 * C -> GIF File
 * Z -> Archivo Windows Media
 * W -> verifica que un campo se identico a otro (validate="W=nombreCampo")
 * L -> verifica que un campo tenga al menos la longitud especificada (validate="L=8")
 * H -> Verifica antes de la validacion el valor de un campo. Ej: validate="H=campo&valor"
 *      Si desea que el campo NO tenga el valor use validate="H=campo&!valor"
 *      NOTA: uselo antes que cualquier otro parametro
 *
 */

var validators = new Array();
validators['G'] = /^(\+|-)?\d(:[012345][\d])?$/;
validators['F'] = /^(((\+|-)?\d+(\.\d*)?)|((\+|-)?(\d*\.)?\d+))$/;
validators['P'] = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
validators['I'] = /^((\+)?\d+)$/;
validators['E'] = /^([\w_\-]+)(\.[\w_\-]+)*@((\[[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.)|(([\w\-]+\.)+))([a-zA-Z]{2,4}|[\d]{1,3})(\]?)$/;
validators['A'] = /^(\d){2}(\.(\d){2}){4}$/;
validators['U'] = /^([A-Za-z])+(-)*([A-Za-z])*$/;
validators['J'] = /\.(jpg|JPG)$/;
validators['D'] = /\.(pdf|PDF)$/;
validators['C'] = /\.(gif|GIF)$/;
validators['K'] = /\.(jpg|gif|pdf|doc|xls|ppt)$/;
validators['Z'] = /\.(wmv)$/;

function validateVidaNavegantes (form) {
    ocultarMensajes();
	for(i = 0; i < form.length; i++) {
		if(form.elements[i].getAttribute('validate')) {
			var i;
			var field;
			if (form == null) {
				mensajeError ('Intenta validar una forma invalida');
				return false;
			}

			for (i = 0; i < form.elements.length; i++) {
				field = form.elements[i];
				if (!validateField (field, form)) {
					if (!field.getAttribute('msg')) {
						mensajeError ('El campo no ha sido diligenciado correctamente');
					}
					else {
						mensajeError (field.getAttribute('msg'));
					}
					if (!field.getAttribute('ffocus')) {
						if (field.type == 'text' || field.type == 'password') {
							field.focus();
							field.select();
						}
						if (field.type != 'hidden') {
							field.focus();
						}
					}
					else {
						if (field.type == 'text' || field.type == 'password') {
							form.elements[field.getAttribute('ffocus')].focus();
							form.elements[field.getAttribute('ffocus')].select();
						}
						else {
							form.elements[field.getAttribute('ffocus')].focus();
						}
					}
					return false;
				}
			}

                        if(document.getElementById('actualStep').value == 1){

                            if (eval(document.getElementById('telefono').value.length) !=  7){
                                mensajeError("El Número telefónico no es valido");
                                document.getElementById('telefono').focus();
                                document.getElementById('telefono').select();
                                return false;
                            }
                            if(document.Paso1.DNIaux.value == ""){

                                    if(document.getElementById('indProspecto').value != 1)
                                    {

                                            document.Paso1.iOperacion.value = 97; //grabar prospecto

                                    }else{
                                        document.Paso1.iOperacion.value = 99; //grabar datos y avanzar  //////////ultima modificacion, pendiente revisar
                                    }

                            }else{
                                document.Paso1.iOperacion.value = 98; //verifica si los datos fueron modificados,  y cambia de pagina
                            }
                        }else{
                            /*if(document.getElementById('actualStep').value == 2){
                                if(document.getElementById('placa')!=null){
                                    if (eval(document.getElementById('placa').value.length) !=  6){
                                        alert("La placa no es valida");
                                        document.getElementById('placa').focus();
                                        document.getElementById('placa').select();
                                        return false;
                                    }
                                }
                                if(document.getElementById("valorSugerido").value != "" && document.getElementById("valorSugerido").value != "0")
                                {
                                    if(document.getElementById("valorAsegurado").value > (document.getElementById("valorSugerido").value * 1.1)  || document.getElementById("valorAsegurado").value < (document.getElementById("valorSugerido").value * 0.9))
                                    {
                                        alert("El valor asegurado difiere significativamente del valor sugerido. Por favor verifique");
                                        document.getElementById('valorAsegurado').value = "";
                                        document.getElementById('valorAsegurado').focus();
                                        document.getElementById('valorAsegurado').select();
                                        return false;
                                    }
                                }
                                document.Paso2.iOperacion.value = 2;
                                document.Paso2.action = document.getElementById('ruta').value;
                            }*/

                        }

                        if(document.Paso1.cdDepPer.value == '-1'){
                            mensajeError("Debe seleccionar un departamento.");
                            return false;
                        }

                        if(document.Paso1.cdCiudadPer_COMBO.value == null || document.Paso1.cdCiudadPer_COMBO.value == "" || document.Paso1.cdCiudadPer_COMBO.value == "-1"){
                            mensajeError("Debe seleccionar un municipio.");
                            return false;
                        }

//                        document.Paso1.cdDepPer_Tmp.value = document.Paso1.cdDepPer.value;

			form.submit();
			return true;
		}
	}
}


function validate (form) {
    ocultarMensajes();
	//alert(form);
        var enviarform = true;
	for(i = 0; i < form.length; i++) {
		if(form.elements[i].getAttribute('validate')) {
			var i;
			var field;
			if (form == null) {
				mensajeError ('Intenta validar una forma invalida');
				return false;
			}

			for (i = 0; i < form.elements.length; i++) {
				field = form.elements[i];
				if (!validateField (field, form)) {
					if (!field.getAttribute('msg')) {
						mensajeError ('El campo no ha sido diligenciado correctamente');
					}
					else {
						mensajeError(field.getAttribute('msg'));
					}
					if (!field.getAttribute('ffocus')) {
						if (field.type == 'text' || field.type == 'password') {
							field.focus();
							field.select();
						}
						if (field.type != 'hidden') {
							field.focus();
						}
					}
					else {
						if (field.type == 'text' || field.type == 'password') {
							form.elements[field.getAttribute('ffocus')].focus();
							form.elements[field.getAttribute('ffocus')].select();
						}
						else {
							form.elements[field.getAttribute('ffocus')].focus();
						}
					}
					return false;
				}
			}
                        if(document.getElementById('actualStep').value == 1){
                            if (eval(document.getElementById('telefono').value.length) !=  7){
                                mensajeError("El Número telefónico no es valido");
                                document.getElementById('telefono').focus();
                                document.getElementById('telefono').select();
                                return false;
                            }
                            if(document.Paso1.DNIaux.value == ""){
                                //if(document.getElementById('cdtipoDni').value != 'J' && document.getElementById('cdtipoDni').value != 'O'){
                                //    if(document.getElementById('indProspecto').value != 1)
                                //    {
                                        if(document.getElementById('dni').value == "")
                                        {
                                            mensajeError("Ingrese un número de identificación");
                                            document.getElementById('dni').focus();
                                            document.getElementById('dni').select();
                                            return false;
                                        }else{
                                            document.Paso1.iOperacion.value = 99; //grabar datos y avanzar
                                        }
                                   // }else{
                                   //     document.Paso1.iOperacion.value = 99; //grabar datos y avanzar
                                 //   }
                                //}
                                /*else{
                                    if(document.getElementById('indProspecto').value != 1)
                                    {
                                        if(document.getElementById('dni').value != "")
                                        {
                                            alert("No debe ingresar identificación");
                                            document.getElementById('dni').focus();
                                            document.getElementById('dni').select();
                                            return false;
                                        }else{
                                            document.Paso1.iOperacion.value = 97; //grabar prospecto
                                        }
                                    }else{
                                        document.Paso1.iOperacion.value = 99; //grabar datos y avanzar  //////////ultima modificacion, pendiente revisar
                                    }
                                }*/
                            }else{
                                document.Paso1.iOperacion.value = 98; //verifica si los datos fueron modificados,  y cambia de pagina
                            }
                        }else{
                            if(document.getElementById('actualStep').value == 2){
                                if (validarPaso2Autos() == false){
                                    return false;
                                }
                                //validarPaso2Autos();
                                if(document.Paso2.iOperacion.value!="98" && document.Paso2.iOperacion.value!="3"){
                                    document.Paso2.iOperacion.value = 2;
                                    document.Paso2.action = document.getElementById('ruta').value;
                                }
                            }
                        }
                        if(document.Paso2 != null){
                            if(document.Paso2.iOperacion.value!="98"){
                                form.submit();
                            }
                        }else{
                            form.submit();
                        }
			return true;
		}
	}
}

function validarPaso2Autos(){
    ocultarMensajes();
    if (eval(document.getElementById('placa').value.length) !=  6){
        mensajeError("La placa no es valida");
        document.getElementById('placa').focus();
        document.getElementById('placa').select();
        return false;
    }
    if(document.getElementById("valorSugerido").value != "" && document.getElementById("valorSugerido").value != "0")
    {
        if(document.getElementById("valorAsegurado").value > (document.getElementById("valorSugerido").value * 1.1)  || document.getElementById("valorAsegurado").value < (document.getElementById("valorSugerido").value * 0.9))
        {
            mensajeError("El valor asegurado difiere significativamente del valor sugerido. Por favor verifique");
            document.getElementById('valorAseguradoMascara').value = "";
            document.getElementById('valorAseguradoMascara').focus();
            document.getElementById('valorAseguradoMascara').select();
            return false;
        }
    }
}


function validateField (field, form) {
	var properties;
	var property;
	if (field.getAttribute('validate') != null) {
		properties = field.getAttribute('validate').split('|');
		for (i = 0; i < properties.length; i++) {
			property = properties[i];
			if (property.length > 1) {
			  if (!validateComplexProperty (property, field, form)) {
					return (property.substr(0, 1) == 'H');
				}
			}
			else {
                                //alert(property + " - " + field.name + ": " + field.value);
				if (property == 'R' && field.value.length == 0) {
					return false;
				}

				if (property != 'R' && field.value.length > 0) {
					if (!validators[property].test(field.value)) {
						return false;
					}
				}
			}
		}
	}
	return true;
}

function validateComplexProperty (paramStr, field, form) {
	var params;
	var property;
	var temp;
	var field;

	temp = paramStr.split('=');
	property = temp [0];
	if (temp.length > 1) {
		params = temp[1].split('&');
	}
	else {
		mensajeError ('El parametro ' + property + ' del validador ha sido utilizado incorrectamente');
		return false;
	}

	if (property == 'W') {
		return (field.value == (form.elements[params[0]]).value);

	}
	if (property == 'L') {
		return (field.value.length>=params[0]);
	}

	if (property == 'H') {
		field = form.elements[params[0]];
		// Botones Radio
		if (field.length > 0) {
			for (var i = 0; i < field.length; i ++) {
				if (field[i].checked) {
					if (params[1].substr(0, 1) == '!') {
						return (field[i].value != params[1].substr(1));
					}
					return (field[i].value == params[1]);
				}
			}
		}
		else {
			if (params[1].substr(0, 1) == '!') {
				return (field.value != params[1].substr(1));
			}
			return (field.value == params[1]);
		}
	}

	return false;
}
function handleEnter (field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) {
            var i;
            for (i = 0; i < field.form.elements.length; i++)
                    if (field == field.form.elements[i])
                            break;
            i = (i + 1) % field.form.elements.length;
            return false;
    }
    else
    return true;
}

function mensajeError(mensaje){
    document.getElementById("cuadroError").style.display = "block";
    document.getElementById("cuadroError").innerHTML = mensaje;
}
function mensajeAdvertencia(mensaje){
    document.getElementById("cuadroAdvertencia").style.display = "block";
    document.getElementById("cuadroAdvertencia").innerHTML = mensaje;
}
function mensajeInformacion(mensaje){
    document.getElementById("cuadroInformacion").style.display = "block";
    document.getElementById("cuadroInformacion").innerHTML = mensaje;
}

function ocultarMensajes(){
    document.getElementById("cuadroError").style.display = "none";
    document.getElementById("cuadroError").innerHTML = "";
    document.getElementById("cuadroAdvertencia").style.display = "none";
    document.getElementById("cuadroAdvertencia").innerHTML = "";
    document.getElementById("cuadroInformacion").style.display = "none";
    document.getElementById("cuadroInformacion").innerHTML = "";
}

