//
// Ignacio Cougil Jares - Agosto/Septiembre 2004
// http://ignacio.cougil.com
// 

// Funciones JavaScript


// Validación de objetos de formulario
function CheckValue(obj, type, text, name, nofoco, tam, elForm) {

	if (arguments.length < 5) nofoco = false;
	if (obj == -1){
		alert ("objeto inexistente");
	 	return -1;
	}
	if (obj == null){
					return -1;
	}

	switch (type){
		case 0:
						// comprobar que tenga un valor numérico
						//alert(parseFloat(obj.value));
						//return -1;
						//if ( isNaN( obj.value ) || isNaN( parseInt(obj.value) ) ) {
						if ( !isNumber(obj.value) ) {
							//alert("Se requiere un entero en "+name);

							alert(text+" "+name);
			
							if (!nofoco) obj.focus();
							return -1;
						}
						/*
						else{
							obj.value = parseInt(obj.value);
						 	//alert("correcto "+name);
						}
						*/
						break;
			
		case 1:
						// comprobar que la opción seleccionada no sea una con valor 0
						var val = obj.options[obj.options.selectedIndex].value;
						// o no esté seleccionada ninguna opción
						var sel = obj.options.selectedIndex;
						if ( val == 0 || sel == -1 ){
							//alert("Selecciona un valor para "+name);
							alert(text+" "+name);
							if (!nofoco) obj.focus();
							return -1;
						}
			
						break;
			
		case 2:
						// comprobar que NO esté vacio
						if ( isEmpty(obj) ){
							//alert("Se requiere un valor para "+name);
							alert(text+" "+name);
							obj.value = "";
							if (!nofoco) obj.focus();
							return -1;
						}
						break;
			
		case 3:
						if (!validEmail(obj.value)){
							//alert("Dirección de E-mail incorrecta")
							alert(text+" "+name);
							if (!nofoco) obj.focus();
							return -1
						}
						break;
			
		case 4:
						var algun = false;
						// alert("Es necesario seleccionar un elemento")
						for (i=0;i<elForm.elements.length && !algun;i++) {
							var elem = elForm.elements[i];
							algun = ( (elem.type == "checkbox") && (elem.name.indexOf(name) != -1) && (elem.checked == true) );
						}
						if (!algun){
							alert(text);
							return (-1);
						}
						break;
			/*
		case 4:
						var sel;
						sel = obj.options[obj.options.selectedIndex];
						if (sel!=-1){
							//alert("valor: "+sel.value);
							if (!nofoco) obj.focus();
							return (-1);
						}
						break;
						*/
			
		case 5: if (!validLink(obj)) {
							//alert("Enlace incorrecto")
							alert(text+" "+name);
							if (!nofoco) obj.focus();
							return -1
						}
						break;
						
		case 6: // comprueba q el valor esté compuesto por un números y/o letras del alfabeto evitando los caracteres 'ç' y 'ñ'
						// re=/\W\/
						re = new RegExp("\\Wç?ñ?", "gi");
						OK = re.exec(obj.value);
						if (OK){
							alert(text+" "+name);
							if (!nofoco) obj.focus();
							  return -1;
							}
							break;
						
						/*	
		case 7:
						var sel;
						sel = obj.options.selectedIndex;
						if (sel==-1){
							alert(text+" "+name);
							if (!nofoco) obj.focus();
							return (-1);
						}
						break;
						*/
			
		case 8:
						if (!validDate(obj.value)){
							//alert("Fecha incorrecta")
							alert(text);
							if (!nofoco) obj.focus();
							return -1
						}
						break;

		case 9: // campo de longitud fija
						val = obj.value;
						if (val != null && val != "" && val.length < tam) {
								//alert("El campo xxxx tiene menos caracteres que los necesarios yyy...")
								prim = text.indexOf("*");
								sec = text.lastIndexOf("*");
								if (prim > -1 && sec > -1) {
									alert(text.substr(0,prim)+name+text.substr(prim+1,sec-prim-1)+text.substr(sec+1,text.length-sec+1)+" ("+tam+")");
								} 
								if (!nofoco) obj.focus();
								return -1;
						}
						break;

						/*
		case 9: // tamaño campo en caracteres
						val = obj.value;
						if (val != null && val != "") {
							if (val.length > tam) {
								//alert("El campo xxxx tiene mas caracteres que los permitidos yyy...")
								prim = text.indexOf("*");
								sec = text.lastIndexOf("*");
								//alert(prim+" "+sec+" ----- "+text);
								if (prim > -1 && sec > -1) {
									alert(text.substr(0,prim)+"("+val.length+")"+text.substr(prim+1,sec-prim-1)+"\""+name+"\""+text.substr(sec+1,text.length-sec+1)+" ("+tam+")");
								} else {
									alert(text+" ("+tam+")");
								}
								if (!nofoco) obj.focus();
								return -1;
							} else if (val.length < tam) {
								//alert("El campo xxx tiene menos caracteres de los necesarios yyy...");
							}
						}
						break;
						*/
						
		case 10: // horas: hh:mm
						val = obj.value;
						if (val != null && val != "") {
							if (val.length == 5) {
								//alert("Hora incorrecta")
								pos = val.indexOf(":");
								if (pos == 2) {
									h = val.substr(0,2);
									m = val.substr(3,2);
									if ((!isNaN(h)) && (!isNaN(m))) {
										if (((h > 23) || (h < 0)) || ((m > 59) || (m < 0) )) {
											alert(text);
											if (!nofoco) obj.focus();
											return -1;
										}
									} else {
										alert(text);
										if (!nofoco) obj.focus();
										return -1;
									}
								} else {
									alert(text);
									if (!nofoco) obj.focus();
									return -1;
								}
							} else {
								alert(text);
								if (!nofoco) obj.focus();
								return -1;
							}
						}
						break;
						
	 case 11: // hores: hh:mm per agenda -> 00:00 -- 24:00
					 val = obj.value;
					 if (val != null && val != "") {
							if (val.length == 5) {
							//alert("Hora incorrecta")
								pos = val.indexOf(":");
								if (pos == 2) {
									h = val.substr(0,2);
									m = val.substr(3,2);
									if ((!isNaN(h)) && (!isNaN(m))) {
										if (((h > 24) || (h < 0)) || (m < 0) ) {
											alert(text);
											if (!nofoco) obj.focus();
											return -1;
										}
									} else {
										alert(text);
										if (!nofoco) obj.focus();
										return -1;
									}
								} else {
									alert(text);
									if (!nofoco) obj.focus();
									return -1;
								}
							} else {
								alert(text);
								if (!nofoco) obj.focus();
								return -1;
							}
					 }
					 break;
		
		case 12:
							re = new RegExp("\\d", "gi");
							if (re.exec(obj.value)) {
								//alert("Números no permitidos")
								alert(text+" "+name);
								if (!nofoco) obj.focus();
								return -1
							}
							break;		
		
		case 13:  // campo de longitud excesiva
							val = obj.value;
							if (val != null && val != "" && val.length > tam) {
									//alert("El campo xxxx tiene mas caracteres que los admitidos yyy...")
									prim = text.indexOf("*");
									sig = text.indexOf("*",prim+1);
									sec = text.lastIndexOf("*");
									if (prim > -1 && sec > -1) {
										alert(text.substr(0,prim)+
										name+
										text.substr(prim+1,sig-prim-1)+
										" ("+val.length+") "+
										text.substr(sig+1,sec-sig-1)+
										text.substr(sec+1,text.length-sec+1)+" ("+tam+")");
										//alert(text.substr(0,prim)+name+text.substr(prim+1,sec-prim-1)+text.substr(sec+1,text.length-sec+1)+" ("+tam+")");
									} 
									if (!nofoco) obj.focus();
									return -1;
							}
							break;

	}

	return 1;
}

function validEmail(str) {
		  //var field = form.email; // email field
		  //var str = field.value; // email string
		  var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		  var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/; // valid
		  if (!reg1.test(str) && reg2.test(str)) { // if syntax is valid
		    return true;
		  }
		  //field.focus();
		  //field.select();
		  return false;
}

function validLink(fld) {
	var siOno = false;
  if (!isEmpty(fld)) {
		/*
			var re = new RegExp("(\\W)|ç?|ñ?", "gi");
			if (!re.exec(fld.value)) { 
		*/
			siOno = true;
			var v = fld.value+"";
			if ( (v.toUpperCase()).substring(0,7) != "HTTP://"  && (v.toUpperCase()).substring(0,8) != "HTTPS://" ) {
				fld.value="http://"+fld.value;
			}
		/* }		 */
	}
	return siOno;
}

function isEmpty(obj) {
	return ( trim(obj.value) == "" );
}

function trim (str) {
  while (str.charAt(0) == ' ')
    str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
    str = str.substring(0, str.length - 1);
  return str;
}

function noblanks(str) {
  str = trim(str);
  for (i=0;i<str.length;i++) {
    if (str.charAt(i) == ' ') {
      str = str.substring(0,i) + str.substring(i+1, str.length );
    }
  }
  return str;
}

/* Validar fechas */

/**
* funcion para comprobar si un año es bisiesto
* argumento anyo > año extraido de la fecha introducida por el usuario
*/
function anyoBisiesto(anyo) {
    /**
    * si el año introducido es de dos cifras lo pasamos al periodo de 1900. Ejemplo: 25 > 1925
    */
    if (anyo < 100)
        var fin = anyo + 1900;
    else
        var fin = anyo ;

    /*
    * primera condicion: si el resto de dividir el año entre 4 no es cero > el año no es bisiesto
    * es decir, obtenemos año modulo 4, teniendo que cumplirse anyo mod(4)=0 para bisiesto
    */
    if (fin % 4 != 0) return false;
    else {
        if (fin % 100 == 0) {
            /**
            * si el año es divisible por 4 y por 100 y divisible por 400 > es bisiesto
            */
            if (fin % 400 == 0) {
                return true;
            }
            /**
            * si es divisible por 4 y por 100 pero no lo es por 400 > no es bisiesto
            */
            else {
                return false;
            }
        }
        /**
        * si es divisible por 4 y no es divisible por 100 > el año es bisiesto
        */
        else {
            return true;
        }
    }
}

/**
* Funcion principal de validacion de la fecha
* argumento fecha > cadena de texto de la fecha introducida por el usuario
*/
function validDate(a) {
   /**
   * obtenemos la fecha introducida y la separamos en dia, mes y año
   a=document.forms[0].fecha.value;
   */
  if (a != "") {
    var aaux = a.split("/");
    if (aaux.length == 3) {
      dia=a.split("/")[0];
      mes=a.split("/")[1];
      anyo=a.split("/")[2];
      if ( ( !isNaN(dia) && !isNaN(mes) && !isNaN(anyo) ) &&
         ( !isNaN( parseInt(dia) ) && !isNaN( parseInt(mes) ) && !isNaN( parseInt(anyo) ) ) ) {
        if(anyoBisiesto(anyo)) febrero=29;
        else febrero=28;
        /**
         * si el mes introducido es negativo, 0 o mayor que 12
         */
        if ((mes<1) || (mes>12)) {
          /* alert("El mes introducido no es valido. Por favor, introduzca un mes correcto");
          document.forms[0].fecha.focus();
          document.forms[0].fecha.select();
          return; */
          return false;
        }
        /**
         * si el mes introducido es febrero y el dia es mayor que el correspondiente
         * al año introducido > alertamos y detenemos ejecucion
         */
        if ((mes==2) && ((dia<1) || (dia>febrero))) {
          /* alert("El dia introducido no es valido. Por favor, introduzca un dia correcto");
          document.forms[0].fecha.focus();
          document.forms[0].fecha.select(); */
          return false;
        }
        /**
         * si el mes introducido es de 31 dias y el dia introducido es mayor de 31 > alertamos y detenemos ejecucion
         */
        if (((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && ((dia<1) || (dia>31))) {
          /* alert("El dia introducido no es valido. Por favor, introduzca un dia correcto");
          document.forms[0].fecha.focus();
          document.forms[0].fecha.select(); */
          return false;
        }
        /**
         * si el mes introducido es de 30 dias y el dia introducido es mayor de 30 > alertamos y detenemos ejecucion
         */
        if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30))) {
          /* alert("El dia introducido no es valido. Por favor, introduzca un dia correcto");
          document.forms[0].fecha.focus();
          document.forms[0].fecha.select(); */
          return false;
        }
        /**
         * si el mes año introducido es menor que 1900 o mayor que 2010 > alertamos y detenemos ejecucion
         * NOTA: estos valores son a eleccion vuestra, y no constituyen por si solos fecha erronea
         */
        if ((anyo<1950) || (anyo>2100)) {
          /* alert("El año introducido no es valido. Por favor, introduzca un año entre 1900 y 2010");
          document.forms[0].fecha.focus();
          document.forms[0].fecha.select(); */
          return false;
        }
        /**
         * en caso de que todo sea correcto > enviamos los datos del formulario
         * para ello debeis descomentar la ultima sentencia
         */
        /* else {
         alert("La fecha introducida es correcta. Gracias por su colaboración");
         document.forms[0].submit();
         }
        */
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  return true;
}

function deselectTheOthers(f, obj) {
	 for (i=0;i<f.elements.length;i++) {
	 		if (f.elements[i].type == "checkbox" && f.elements[i] != obj && obj.checked) f.elements[i].checked=false;
	 }
}

function showError(obj,type,text,moreInfo,nofoco) {
	var nofoco = true;
	if (arguments.length < 5) nofoco = false;
	if (arguments.length < 4) moreInfo = "";
	switch(type) {
		case 0:
						// No se ha realizado la operación X sobre el campo Y
						alert(text+moreInfo);
						if (!nofoco && obj!=null) obj.focus();
						break;
	}
}

function displayStatus(msg) {
	window.status = msg;
	document.weNeedToReturn = true;
}

function isNumber(str) {
	var aux;
	aux = (str + "");
	//aux = (str + "").replace(".",",");
	return ( ! ( isNaN(aux) || isNaN(parseInt(aux)) ) );
}
