var bValidar = true;
// Mensajes
FIELD_EMPTY = 'Este campo es obligatorio';
FIELD_INT = 'Este campo debe ser numerico (enteros)';
FIELD_FLOAT = 'Este campo debe ser numerico';
FIELD_DATE = 'Este campo debe ser una fecha (Formato dd/mm/yyyy)';
FIELD_MAIL = 'Este campo debe ser un correo electronico';
FIELD_SELECT = 'Debe seleccionar una opcion';
FIELD_PASS = 'Los campos de contraseña deben ser iguales';
FIELD_PASS2 = 'Debe escribir la contraseña anterior';

/********************************************************/
// validar(oForm)                                          //
// Funcion generica para la validacion de formularios      //
// Segun el Id que tenga el elemento del formulario, se    // 
// mostrara determinado tipo de error                      //
/********************************************************/
function validar(oForm)
{


	if( bValidar )
	{
		var aElements = oForm.elements;
		// Recorre los campos

		for( var nElement = 0; nElement < aElements.length; nElement++ )
		{
			// Variables del Campo
			oElement = aElements[nElement];
			Value = oElement.value;
			Type = oElement.type;
			Name = oElement.name;
			// En el ID irian las declaraciones
			if(oElement.id)
			{
			aDeclarations = oElement.id.split('_'); // separador de declaraciones
				// Campo Vacio
				if( Value.replace(' ','').length == 0 )
				{
					// Campo Requerido
					if(aDeclarations[1])
					{
						// ...no puede ser vacio
						window.alert(FIELD_EMPTY);
						oElement.focus();
						return false;
					}
				}
				else
				{		
					// Tipos de Datos Especiales
					if(aDeclarations[2])
					{
						switch(aDeclarations[2])
						{							// Campo NUMERICO Entero
							case "int":
								if(isNaN(parseInt(Value)))
								{
									window.alert(FIELD_INT);
									oElement.select();
									oElement.focus();
									return false;
								}
								oElement.value = parseInt(Value);
							break;
							// Campo NUMERICO Flotante
							case "float":
								Value = Value.replace(',','.'); // Reemplaza la coma por el punto
								if(isNaN(parseFloat(Value)))
								{
									window.alert(FIELD_FLOAT);
									oElement.focus();
									oElement.select();
									return false;
								}
								oElement.value = parseFloat(Value);
							break;
							// Campo FECHA
							case "date":
								oDate = new RegExp("(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).([09][0-9]|[0-9]{4})");
								if(!Value.match(oDate))
								{
									window.alert(FIELD_DATE);
									oElement.focus();
									oElement.select();
									return false;
								}
							break;
							// Campo MAIL
							case "mail":
								oMail = new RegExp("[A-z0-9._%-]*@[A-z0-9._%-]*[\.][A-z0-9_-]*");
								if(!Value.match(oMail))
								{
									window.alert(FIELD_MAIL);
									oElement.focus();
									oElement.select();
									return false;
								}
							break;
							// Campo PASS
							case "pass":
								
								sPassRepeat = aDeclarations[0] + "__passrepeat";
								sPassRepeated = aDeclarations[0] + "__passrepeated";
								oPassRepeat = document.getElementById(sPassRepeat);
								oPassRepeated = document.getElementById(sPassRepeated);
								if( oPassRepeat.value != oPassRepeated.value )
								{
									window.alert(FIELD_PASS);
									oElement.focus();
									oPassRepeat.select();
									return false;
								}
								
							break;
							case "passrepeat":
								sPass = aDeclarations[0] + "__pass";
								oPass = document.getElementById(sPass);
								
								if(oPass.value.replace(' ','').length == 0)
								{
									window.alert(FIELD_PASS2);
									oElement.focus();
									oPass.select();
									return false;
								}

							break;
							case "select":
								if(Value =='0'){
								 	window.alert(FIELD_SELECT);
									oElement.focus();
									return false;	
							
								}
							break;
							}
						}
				}
			  	
			}
			// Dependiendo del Tipo
			switch(Type)
			{
				case 'select-one':
					if(Value.substr(0,3) == '___')
					{
						alert(Value.substr(3));
						return false;
					}
				break;
			}
		}
		return true;
	}
}

/********************************************************/
// validarCompra(thisform)                                 //
// Realiza una validacion del formulario de compra         //
/********************************************************/
function validarCompra(thisform){
    var error = false;
    var mensaje = 'Debe completar los siguiente datos:\n\n';
    var errores = "";
    with (thisform){
        if (uso.selectedIndex == 0){
            error = true;
            errores = errores + " - Seleccionar el uso de sus anteojos\n";
        }
        if (grosor.selectedIndex == 0){
            error = true;
            errores = errores + " - Seleccionar un tipo de grosor del lente\n";
        }
        if ((funda.item(0).checked==false) && (funda.item(1).checked==false) &&
            (funda.item(2).checked==false)){
            error=true;
            errores = errores + " - Seleccionar un tipo de funda\n\n";
        }

        if (error == true){
            alert(mensaje + errores);
            return false;
        }else{
            document.getElementById('antirreflejante').disabled = false;
            document.getElementById('opc').value = document.getElementById('opciones').innerHTML;
            document.getElementById('tot').value = document.getElementById('total').innerHTML;
            return true;
        }
    }
}

/********************************************************/
// validaReceta(thisform)                                  //
// Realiza una validacion del formulario de la receta      //
/********************************************************/
function validaReceta(thisform, grosor,condicion,tryAtHome){
  var MENSAJECOMPLEJO = "Lo sentimos, su receta incluye parámetros complejos. Póngase en contacto con nosotros en nuestro teléfono 902-734090, o en el email: info@opticadirecta.es";
  var MENSAJEFINO = "Su graduación supera los limites de cristales estándar. Debe seleccionar cristales de grosor reducido. Pulse 'paso anterior' y seleccione cristales finos o más finos";

    if (thisform.paso.value == "datos_personales"){
        var error = false;
        var mensaje;
        with (thisform){
            // CHEQUEAMOS QUE SE TILDO EL CERTIFICADO 
            if (chk_certificado.checked == false){
                mensaje = "Debe aceptar el certificado para continuar";
                error = true;
            }
            if (chk_condicion.checked == false){
                mensaje = "Debe aceptar la condición para continuar";
                error = true;
            }
            // CHEQUEAMOS QUE SE TILDO LAS CONDICIONES 
            /*if (chk_condiciones.checked == false){
                mensaje = "Debe aceptar las condiciones para continuar";
                error = true;
            }*/
            if (!tryAtHome){  // SI LA COMPRA NO ES TRY AT HOME... *
                // SI PONE EJE DERECHO, TIENE QUE PONER CILINDRO DERECHO *
                if ( (eje_der.selectedIndex != 0) && (cilindro_der.selectedIndex == 0) ){
                    mensaje = "Introduzca el valor del CILINDRO correspondiente con el EJE especificado";
                    cilindro_der.focus();
                    error = true;
                }
                // SI PONE EJE IZQUIERDO, TIENE QUE PONER CILINDRO IZQUIERDO *
                if ( (eje_izq.selectedIndex != 0) && (cilindro_izq.selectedIndex == 0) ){
                    mensaje = "Introduzca el valor del CILINDRO correspondiente con el EJE especificado";
                    cilindro_izq.focus();
                    error = true;
                }
                // SI PONE CILINDRO DERECHO, TIENE QUE PONER EJE DERECHO *
                if ( (cilindro_der.selectedIndex != 0) && (eje_der.selectedIndex == 0) ){
                    mensaje = "Introduzca el EJE correspondiente con el CILINDRO especificado";
                    eje_der.focus();
                    error = true;
                }
                // SI PONE CILINDRO IZQUIERDO, TIENE QUE PONER EJE IZQUIERDO *
                if ( (cilindro_izq.selectedIndex != 0) && (eje_izq.selectedIndex == 0) ){
                    mensaje = "Introduzca el EJE correspondiente con el CILINDRO especificado";
                    eje_izq.focus();
                    error = true;
                }
                //Si selecciona ver cerca u ordenador:
                //    Si valor absoluto(esfera cerca)+ valor absoluto(cilindro) =<4 es correcto
                //    Si valor absoluto(esfera cerca)+ valor absoluto(cilindro) >4 mensaje error
                //Si selecciona ver lejos:
                //    Si valor absoluto(esfera lejos)+ valor absoluto(cilindro) =<4 es correcto
                //    Si valor absoluto(esfera lejos)+ valor absoluto(cilindro) >4 mensaje error
                var suma = 0;
                var valorCilindroDer;
                var valorCilindroIzq;
				var esferaCercaDer = 0;
				var esferaLejosDer = 0;
				var esferaCercaIzq = 0;
				var esferaLejosIZq = 0;
                if(error !=true){
                  switch(condicion){
                    case(0):{
                      //cerca u ordenador
//BORJA DERECHO
					//SI FUE SELECCIONADO EL CILINDRO DERECHO
					if (cilindro_der.selectedIndex == 0) {
//CAMBIO: CILINDRO=0, pero error si se pasa de -6 o + 4 ERRO debe ir a finos
					  if ((cerca_der.selectedIndex != 0) && (grosor == 1)) {
					 	esferaCercaDer = parseFloat(cerca_der.options[cerca_der.selectedIndex].text);
						 if ((esferaLejosDer > 4)|| (esferaLejosDer < -6)) {
							 mensaje = MENSAJEFINO
							 error = true;
							 break;
						 }
					  }

					} else { //CILINDRO <> cero
						valorCilindroDer = Math.abs(parseFloat(cilindro_der.options[cilindro_der.selectedIndex].text));
             			//OBTENGO EL VALOR DE LA ESFERA CERCA DERECHA
						if (cerca_der.selectedIndex != 0) {
// CAMBIO                 esferaCercaDer = Math.abs(parseFloat(cerca_der.options[cerca_der.selectedIndex].text));
						  esferaCercaDer = parseFloat(cerca_der.options[cerca_der.selectedIndex].text);
						}
 //CAMBIO: VERIFICAMOS SI ES POSITIVO O NEGATIVO LA ESFERA (PREMISA: CILINDRO DISTINTO DE CERO)
						if (esferaCercaDer > 0){
							suma = valorCilindroDer + Math.abs(esferaCercaDer);
								if (suma > 6) {
									mensaje = MENSAJECOMPLEJO //"cil seleccionado y esferacercader seleccionadoy mayor que cero y  suma >6"
									error = true;
							 		break;
							 	}
							 	if ((suma > 4) && (suma <= 6) && (grosor == 1)) {
							 		mensaje = MENSAJEFINO //"cil seleccionado y esferacercader seleccionadoy mayor que cero y  suma entre 4 y 6 y grosor uno";
							 		error = true;
							 		break;
							 	}
						} else if (esferaCercaDer<0){
//CAMBIO: VERIFICAMOS CUANDO LA ESFERA ES NEGATIVA
							esferaCercaDer = Math.abs(parseFloat(cerca_der.options[cerca_der.selectedIndex].text));
							 	if ((esferaCercaDer > 4) && (valorCilindroDer > 2)) {
									mensaje = MENSAJECOMPLEJO //"ESF NEGATIVA esf mayor que 4 y cil mayor que 2 NORRRRRRRRRR"; 
									error = true;
									break;
							    }
								if (((esferaCercaDer > 6)|| (valorCilindroDer > 2))&& (grosor ==1)) {
									mensaje = MENSAJEFINO //"ESF NEGATIVA esfera mayor que 6 o cil mayor que 2 y grosor igual 1 FINOOOOO"; 
									error = true;
									break;
								}
						}
					}

//BORJA DERECHO
//BORJA IZQUIERDO
					//SI FUE SELECCIONADO EL CILINDRO IZQUIERDO
					if (cilindro_izq.selectedIndex == 0) {
					//CILINDRO=0, pero error si se pasa de -6 o + 4 ERRO debe ir a finos
					  if ((cerca_izq.selectedIndex != 0) && (grosor == 1)) {
					 	esferaCercaIzq = parseFloat(cerca_izq.options[cerca_izq.selectedIndex].text);
						 if ((esferaCercaIzq > 4)|| (esferaCercaIzq > 4)){
							 mensaje = MENSAJEFINO //"cil NO seleccionado y esfera dist cero y  grosor dist NORMAL y esferacercaizq mayor que 4";
							 error = true;
							 break;
						 }
					  }

					} else { //CILINDRO <> cero
						valorCilindroIzq = Math.abs(parseFloat(cilindro_izq.options[cilindro_izq.selectedIndex].text));
             			//OBTENGO EL VALOR DE LA ESFERA CERCA IECHA
						if (cerca_izq.selectedIndex != 0) {
						  esferaCercaIzq = parseFloat(cerca_izq.options[cerca_izq.selectedIndex].text);
						  
						}
						//VERIFICAMOS SI ES POSITIVO O NEGATIVO LA ESFERA (PREMISA: CILINDRO DISTINTO DE CERO)
						if (esferaCercaIzq > 0){
							suma = valorCilindroIzq + Math.abs(esferaCercaIzq);
								if (suma > 6) {
									mensaje = MENSAJECOMPLEJO //"cil seleccionado y esferacercaizq seleccionadoy mayor que cero y  suma >6"
									error = true;
							 		break;
							 	}
							 	if ((suma > 4) && (suma <= 6) && (grosor == 1)) {
							 		mensaje = MENSAJEFINO //"cil seleccionado y esferacercaizq seleccionadoy mayor que cero y  suma entre 4 y 6 y grosor uno";
							 		error = true;
							 		break;
							 	}
						} else if (esferaCercaIzq<0){
						//VERIFICAMOS CUANDO LA ESFERA ES NEGATIVA
							esferaCercaIzq = Math.abs(parseFloat(cerca_izq.options[cerca_izq.selectedIndex].text));
							 	if ((esferaCercaIzq > 4) && (valorCilindroIzq > 2)) {
									mensaje = MENSAJECOMPLEJO //"ESF NEGATIVA esf mayor que 4 y cil mayor que 2 NORRRRRRRRRR"; 
									error = true;
									break;
							    }
								if (((esferaCercaIzq > 6)|| (valorCilindroIzq > 2))&& (grosor ==1)) {
									mensaje = MENSAJEFINO //"ESF NEGATIVA esfera mayor que 6 o cil mayor que 2 y grosor igual 1 FINOOOOO"; 
									error = true;
									break;
								}
						}
					}
                      break;
                    }
//BORJA IZQUIERDO
                    case(1):{
                    //lejos
//BORJA DERECHO
					//SI FUE SELECCIONADO EL CILINDRO DERECHO
					if (cilindro_der.selectedIndex == 0) {
//CAMBIO: CILINDRO=0, pero error si se pasa de -6 o + 4 ERRO debe ir a finos
					  if ((lejos_der.selectedIndex != 0) && (grosor == 1)) {
					 	esferaLejosDer = parseFloat(lejos_der.options[lejos_der.selectedIndex].text);
						 if ((esferaLejosDer > 4)|| (esferaLejosDer < -6)) {
							 mensaje = MENSAJEFINO //"cil NO seleccionado y esfera dist cero y  grosor dist NORMAL y esferalejosder mayor que 4";
							 error = true;
							 break;
						 }
					  }

					} else { //CILINDRO <> cero
						valorCilindroDer = Math.abs(parseFloat(cilindro_der.options[cilindro_der.selectedIndex].text));
             			//OBTENGO EL VALOR DE LA ESFERA LEJOS DERECHA
						if (lejos_der.selectedIndex != 0) {
// CAMBIO                 esferaLejosDer = Math.abs(parseFloat(lejos_der.options[lejos_der.selectedIndex].text));
						  esferaLejosDer = parseFloat(lejos_der.options[lejos_der.selectedIndex].text);
						}
 //CAMBIO: VERIFICAMOS SI ES POSITIVO O NEGATIVO LA ESFERA (PREMISA: CILINDRO DISTINTO DE CERO)
						if (esferaLejosDer > 0){
							suma = valorCilindroDer + Math.abs(esferaLejosDer);
								if (suma > 6) {
									mensaje = MENSAJECOMPLEJO //"cil seleccionado y esferalejosder seleccionadoy mayor que cero y  suma >6"
									error = true;
							 		break;
							 	}
							 	if ((suma > 4) && (suma <= 6) && (grosor == 1)) {
							 		mensaje = MENSAJEFINO //"cil seleccionado y esferalejosder seleccionadoy mayor que cero y  suma entre 4 y 6 y grosor uno";
							 		error = true;
							 		break;
							 	}
						} else if (esferaLejosDer<0){
//CAMBIO: VERIFICAMOS CUANDO LA ESFERA ES NEGATIVA
							esferaLejosDer = Math.abs(parseFloat(lejos_der.options[lejos_der.selectedIndex].text));
							 	if ((esferaLejosDer > 4) && (valorCilindroDer > 2)) {
									mensaje = MENSAJECOMPLEJO //"ESF NEGATIVA esf mayor que 4 y cil mayor que 2 NORRRRRRRRRR"; 
									error = true;
									break;
							    }
								if (((esferaLejosDer > 6)|| (valorCilindroDer > 2))&& (grosor ==1)) {
									mensaje = MENSAJEFINO //"ESF NEGATIVA esfera mayor que 6 o cil mayor que 2 y grosor igual 1 FINOOOOO"; 
									error = true;
									break;
								}
						}
					}

//BORJA DERECHO
//BORJA IZQUIERDO
					//SI FUE SELECCIONADO EL CILINDRO IZQUIERDO
					if (cilindro_izq.selectedIndex == 0) {
					//CILINDRO=0, pero error si se pasa de -6 o + 4 ERRO debe ir a finos
					  if ((lejos_izq.selectedIndex != 0) && (grosor == 1)) {
					 	esferaLejosIzq = parseFloat(lejos_izq.options[lejos_izq.selectedIndex].text);
						 if ((esferaLejosIzq > 4)|| (esferaLejosIzq < -6)){
							 mensaje = MENSAJEFINO //"cil NO seleccionado y esfera dist cero y  grosor dist NORMAL y esferacercaizq mayor que 4";
							 error = true;
							 break;
						 }
					  }

					} else { //CILINDRO <> cero
						valorCilindroIzq = Math.abs(parseFloat(cilindro_izq.options[cilindro_izq.selectedIndex].text));
             			//OBTENGO EL VALOR DE LA ESFERA LEJOS IECHA
						if (lejos_izq.selectedIndex != 0) {
						  esferaLejosIzq = parseFloat(lejos_izq.options[lejos_izq.selectedIndex].text);

						}
						//VERIFICAMOS SI ES POSITIVO O NEGATIVO LA ESFERA (PREMISA: CILINDRO DISTINTO DE CERO)
						if (esferaLejosIzq > 0){
							suma = valorCilindroIzq + Math.abs(esferaLejosIzq);
								if (suma > 6) {
									mensaje = MENSAJECOMPLEJO //"cil seleccionado y esferacercaizq seleccionadoy mayor que cero y  suma >6"
									error = true;
							 		break;
							 	}
							 	if ((suma > 4) && (suma <= 6) && (grosor == 1)) {
							 		mensaje = MENSAJEFINO //"cil seleccionado y esferacercaizq seleccionadoy mayor que cero y  suma entre 4 y 6 y grosor uno";
							 		error = true;
							 		break;
							 	}
						} else if (esferaLejosIzq<0){
						//VERIFICAMOS CUANDO LA ESFERA ES NEGATIVA
							esferaLejosIzq = Math.abs(parseFloat(lejos_izq.options[lejos_izq.selectedIndex].text));
							 	if ((esferaLejosIzq > 4) && (valorCilindroIzq > 2)) {
									mensaje = MENSAJECOMPLEJO //"ESF NEGATIVA esf mayor que 4 y cil mayor que 2 NORRRRRRRRRR"; 
									error = true;
									break;
							    }
								if (((esferaLejosIzq > 6)|| (valorCilindroIzq > 2))&& (grosor ==1)) {
									mensaje = MENSAJEFINO //"ESF NEGATIVA esfera mayor que 6 o cil mayor que 2 y grosor igual 1 FINOOOOO"; 
									error = true;
									break;
								}
						}
					}
//BORJA IZQUIERDO
                      break;
                    }
                  }
                }
 
            }
        }
        if (error == true){
            alert (mensaje);
            return false;
        }else{
            return true;
        }
    }else{
        return true;
    }
}   

