var error_code = 100;
var captcha_check_route;
var countChecks = 0;
var totalChecks = 0;
var error_list = {
					e_100:'Ok',
					e_1:'Edad no aceptada',
					e_2:'Email incorrecto',
					e_3:'La contraseña debe ser de 8 carácteres mínimo',
					e_4:'Código incorrecto',
					e_5:'Debes completar los campos',
					e_6:'El valor introducido debe ser un número',
					e_7:'Debes elegir una provincia',
					e_8:'Número de carácteres incorrecto',
					e_9:'Elige una opción',
					e_10:'Email no disponible',
					e_11:'Texto no adecuado para una url',
					e_12:'La hora debe estar entre 0 y 23',
					e_13:'El tiempo debe estar entre 0 y 59'
					}
var FormValidator = function(){
	
	this.captcha_check_route = function(value){
		captcha_check_route = value;
	}
	this.dispatchValid = function(){
		if(countChecks == totalChecks){
			$(this).trigger('checkValid');
		}
	}
	this.validar_formulario = function(form_id){
		countChecks = 0;
		totalChecks = 0;
		var papa = this;		
		error_code = 100;		
		
		//compruebo los selects
		$(form_id+" select").each(function(){
			//las pongo todas bien
			unmark_as_bad(this);
			
			//leo su valor
			var valor = this.value;
			
			if(valor == 0){
				mark_as_bad(this);
				error_code = 6;			
			}
		});
		
		//compruebo los inputs de texto
		$(form_id+" input").each(function(){
			//las pongo todas bien
			unmark_as_bad(this);
			var yo = this;
			var tipo = $(this).attr("type");
			if(tipo == "hidden")return;
			
			var comprobaciones = $(this).attr("validate");
			
			//leo su valor
			var valor = trim(this.value);
			if(comprobaciones != undefined){
				if(comprobaciones.search('cod_pos') == -1){
					valor = trimNumber(valor);
				}			
			}else{
				valor = trimNumber(valor);
			}
			
			if(comprobaciones != undefined){
				comprobaciones = comprobaciones.split(",");
				var opcional = (in_array('optional',comprobaciones) && valor == "");
				for(var it in comprobaciones){
					var split_data = comprobaciones[it].split(":");
					if(IsArray(split_data)){
						var nombre = split_data[0];
						var value = split_data[1];
					}else{
						var nombre = comprobaciones[it];
					}					
					switch(nombre){
						case "email":
							if(isValidEmail(valor) == false && !opcional){
								mark_as_bad(this);
								error_code = 5;
								continue;
							}
							break;
						case "min":
							if(valor.length < value && !opcional){
								mark_as_bad(this);
								error_code = 8;
								continue;
							}
							break;
						case "max":
							if(valor.length > value && !opcional){
								mark_as_bad(this);
								error_code = 8;
								continue;
							}
							break;
						case "number":
							if(IsNumeric(valor) == false && !opcional){
								mark_as_bad(this);
								error_code = 6;
								continue;
							}
							break;
						case "hora":
							if((IsNumeric(valor) == false || valor > 23 || valor < 0 )&& !opcional){
								mark_as_bad(this);
								error_code = 12;
								continue;
							}
							break;
						case "minuto":
							if((IsNumeric(valor) == false || valor > 59 || valor < 0) && !opcional){
								mark_as_bad(this);
								error_code = 13;
								continue;
							}
							break;
						case "web_string":
							var reWhiteSpace = new RegExp(/((\s|\n|{)|[^\x00-\x80]+)/i);
							if(reWhiteSpace.test(valor) == true && !opcional){
								mark_as_bad(this);
								error_code = 11;
								continue;
							}
							var reAlphaNumeric = new RegExp("[^a-zA-Z0-9 =.:/?#_-]");
							if(reAlphaNumeric.test(valor) == true && !opcional){
								mark_as_bad(this);
								error_code = 11;
								continue;
							}
							break;
						case "captcha":
							totalChecks++;
							$.getJSON(captcha_check_route+valor,function(data){
								if(data.status == "false"){
									mark_as_bad(yo);
									error_code = 4;
								}
								countChecks++;
								papa.dispatchValid();
							});
							break;
						case "bbdd_email":
							totalChecks++;
							$.get(AJAX_ROOT+"email_exists/"+valor,function(data){
								if(data == "true"){
									mark_as_bad(yo);
									error_code = 10;
								}
								countChecks++;
								papa.dispatchValid();
							});
							break;
						case "ignore":
							continue;
							break;
					}
				}						
			}else{
				//está vacío
				if(valor == ""){
					mark_as_bad(this);
					error_code = 5;
				}
			}
		});
		
		//compruebo los radio inputs
		var algun_radio_mal = false;
		var nombres_comprobados = Array();
		$(form_id+" input:radio").each(function(){
			if(in_array(this.name,nombres_comprobados) == false){
				//las pongo todas bien
				unmark_as_bad_span(this);
				
				//leo su valor
				var valor = this.checked;					
				if(valor == false){
					mark_as_bad_span(this);
					algun_radio_mal = true;	
				}else{
					nombres_comprobados.push(this.name);
					algun_radio_mal = false;
				}				
			}
		});
		if(algun_radio_mal){
			error_code = 9;
		}
		countChecks++;
		totalChecks++;
		this.dispatchValid();
	}
	this.get_error_code = function(){
		return error_code;
	}
	this.get_error_msg = function(){
		return "Error: "+error_code+" - "+error_list["e_"+error_code];
	}
	this.ok = function(){
		return (error_code == 100);
	}
}
function mark_as_bad(tag){
	$(tag).addClass("bad_tag");
}
function unmark_as_bad(tag){
	$(tag).removeClass("bad_tag");
}
function mark_as_bad_span(tag){
	$("span#"+tag.name).addClass("bad_tag");
}
function unmark_as_bad_span(tag){
	$("span#"+tag.name).removeClass("bad_tag");
}
//email validation
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}
function IsNumeric(input){
   return (input - 0) == input && input.length > 0;
}
function IsArray(input){
	return typeof(input)=='object'&&(input instanceof Array);
}
function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}
