﻿jQuery.validator.addMethod("validarCIF", function(datosCif, element) {

	if(datosCif){
	
	var pares = 0;
    var impares = 0;
    var suma;
    var ultima;
    var unumero;
    var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
    var xxx;
    
    datosCif = datosCif.toUpperCase();

    var regular = new RegExp(/^[ABCDEFGJHKLMNPQRSUVW]\d\d\d\d\d\d\d[0-9,A-J]$/g);
     if (!regular.exec(datosCif)) return false;
        
     ultima = datosCif.substr(8,1);

     for (var cont = 1 ; cont < 7 ; cont ++){
         xxx = (2 * parseInt(datosCif.substr(cont++,1))).toString() + "0";
         impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
         pares += parseInt(datosCif.substr(cont,1));
     }
     xxx = (2 * parseInt(datosCif.substr(cont,1))).toString() + "0";
     impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
    
     suma = (pares + impares).toString();
     unumero = parseInt(suma.substr(suma.length - 1, 1));
     unumero = (10 - unumero).toString();
     if(unumero == 10) unumero = 0;
    
     if ((ultima == unumero) || (ultima == uletra[unumero]))
         return true;
     else
         return false;
	}
     else{
         return true;
	 }

}, '');
jQuery.validator.addMethod("IsNIF", function(YourNIF, element) {
	if(YourNIF){
		//alert(IsChar(YourNIF.substring(8, 9)))
	/*if (YourNIF.length != 9) return 0 //Si la longitud de "YourNIF" es menor que 9 devuelve falso
	else if (!IsUnsignedInteger(YourNIF.substring(0, 8))) return 0 //Si los ocho primeros digitos no forman un numero entero sin signo valido devuelve falso
	else if (!IsChar(YourNIF.substring(8, 9))) return 0 //Si el ultimo digito no es una letra valida devuelve falso
	else
	{*/ 
		var ControlValue = 0 //Control de calculos segun el criterio de correccion
		var NIFCharIndex = 0 //Almacenara la posicion de la letra correpondiente a la parte numerica del DNI con respecto al array "NIFChars"
		//El siguiente array "NIFChars" contiene las letras de DNI ordenadas segun el criterio de correccion
		var MaxLen = YourNIF.length
		var NIFChars = new Array('T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E')
		var FirstDigit = YourNIF.substring(0,1)//Almacenamos el primer digito para ver si es NIF o NIE
		FirstDigit = FirstDigit.toUpperCase() //Pasamos la letra del NIE a mayusculas por si acaso estaba en minusculas
		if(FirstDigit=='X'){
			var NIFNumber = '0'+(YourNIF.substring(1, MaxLen-1)) //Almacenanos la parte numerica del NIE en "NIFNumber"
		}
		else{
			if(FirstDigit=='Y'){
				var NIFNumber = '1'+(YourNIF.substring(1, MaxLen-1)) //Almacenanos la parte numerica del NIE en "NIFNumber"
			}else{
				var NIFNumber = YourNIF.substring(0, MaxLen-1) //Almacenanos la parte numerica del DNI en "NIFNumber"	
			}
		}
		var NIFChar = YourNIF.substring(MaxLen-1, MaxLen) //Almacenamos la letra del DNI en "NIFChar"
		NIFChar = NIFChar.toUpperCase() //Pasamos la letra del DNI a mayusculas por si acaso estaba en minusculas
		//Los siguientes 4 calculos sirven para calcular la posicion de la letra correspondiente al la parte numerica del DNI "NIFNumber" en en array "NIFChars"
		ControlValue = NIFNumber / NIFChars.length
		ControlValue = Math.floor(ControlValue);
		ControlValue = ControlValue * NIFChars.length
		NIFCharIndex = NIFNumber - ControlValue
		if (YourNIF.length > 9) return 0;
		return (NIFChar == NIFChars[NIFCharIndex]) ? 1 : 0//Si la letra coincide con la letra dada devuelve verdadero si no devuelve falso
	//}
	}
	else{
		return true;	
	}

}, '');
jQuery.validator.addMethod("EsMovil", function(value, element) {
	if(value){
		PMovilContacte_=value.slice(0,1);
		if (isNaN(value)) { 
			return false;
		} 	
		if(value.length!=9){
			return false;
		}
		if(PMovilContacte_!="6"){
			return false;
		}	
		else{
			 return true;
		}
	}
	else{
		 return true;
	}
}, '');
jQuery.validator.addMethod("EsTlf", function(value, element) {
	return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
}, '');
jQuery.validator.addMethod("codpostal", function (value) {
	return (value.match(/^(5[0-2]|[0-4][0-9])[0-9]{3}$/) || !(value));
}, 'Por favor introduzca un C&oacute;digo Postal v&aacute;lido.');
jQuery.validator.addMethod("codprovincia", function(value){	
	codprovincia_=document.getElementById('ProvinciaContacto').value;
	codpostal_=document.getElementById('CodigoPostalContacto').value.slice(0,2);
	if(codprovincia_ != codpostal_){
		return false;
	}
	else{
		return true;
	}
}, '');
jQuery.validator.addMethod("codprovinciacompra", function (value) {
    codprovincia_ = document.getElementById('ProvinciaCliente').value;
    codpostal_ = document.getElementById('CPostalCliente').value.slice(0, 2);
    if (codprovincia_ != codpostal_) {
        return false;
    }
    else {
        return true;
    }
}, '');
jQuery.validator.addMethod("escogecargo", function(value,element){
		if(value){		
			CargoPersonaAutorizada_=document.getElementById('CargoPersonaAutorizada').value;
			if (CargoPersonaAutorizada_=='Cargo') {
				return false;	
			}
			else{
				return true;	
			}
		}
		else{
			return true;
		}
},'');
jQuery.validator.addMethod("escogevia", function(value, element) {
	if(value){
		TipoViaContacto_=value;
		if (TipoViaContacto_=='Tipo de via') {
			return false;	
		}
		else{
			return true;	
		}
	}
	else{
		return true;
	}
},'');
jQuery.validator.addMethod("escogeprovincia", function(value, element) {
	if(value){
		ProvinciaContacto_=value;
		if (ProvinciaContacto_=='Provincia') {
			return false;	
		}
		else{
			return true;	
		}
	}else{
		return true;
	}
},'');
jQuery.validator.addMethod("numero", function(value, element) {
    return this.optional(element) || /^\d+$/.test(value);
}, 'Por favor introduzca un n&uacute;mero.');

jQuery.validator.addMethod("requerido", function(value, element, param) {
	// check if dependency is met
	if ( !this.depend(param, element) )
		return "dependency-mismatch";
	switch( element.nodeName.toLowerCase() ) {
	case 'select':
		// could be an array for select-multiple or a string, both are fine this way
		var val = $(element).val();
		return val && val.length > 0;
	case 'input':
		if ( this.checkable(element) )
			return this.getLength(value, element) > 0;
	default:
		return $.trim(value).length > 0;
	}
},'Este campo es obligatorio.');

jQuery.validator.addMethod("maxlongitud", function(value, element, param) {
	return this.optional(element) || this.getLength($.trim(value), element) <= param;
},'Por favor no introduzca m&aacute;s de {0} caracteres.');
jQuery.validator.addMethod("minlongitud", function(value, element, param) {
	return this.optional(element) || this.getLength($.trim(value), element) >= param;
},'Por favor introduzca al menos {0} caracteres.');
jQuery.validator.addMethod("numtienda", function(value) {
if(value){
	return value.match(/^[a-zA-Z]{2}\d{6}[a-zA-Z]$/);	
}
else{
	return true;
}
},'El n&uacute;mero introducido no es correcto (Ej: CL601000R).');
jQuery.validator.addMethod("escogetipo", function(value,element){
		TipoCliente_=document.getElementById('TipoCliente').value;	
		if(value){		
			TipoCliente_=document.getElementById('TipoCliente').value;
			if (TipoCliente_=='Ninguno') {
				return false;	
			}
			else{
				return true;	
			}
		}
		else{
			return true;
		}
},'Debe escoger el tipo de cliente.');
jQuery.validator.addMethod("numsim", function(value) {
if(value){
	return value.match(/^3456[0-9]{13}$/);	
}
else{
	return true;
}
}, '');



/*Funciones auxiliares para calcular el numero de cuetna*/
function obtenerDigito(valor) {
    valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
    control = 0;
    for (i = 0; i <= 9; i++)
        control += parseInt(valor.charAt(i)) * valores[i];
    control = 11 - (control % 11);
    if (control == 11) control = 0;
    else if (control == 10) control = 1;
    return control;
}

function numerico(valor) {
    cad = valor.toString();
    for (var i = 0; i < cad.length; i++) {
        var caracter = cad.charAt(i);
        if (caracter < "0" || caracter > "9")
            return false;
    }
    return true;
}
/*Fin de las funciones auxiliares*/


jQuery.validator.addMethod("CCC", function (value) { // Validar CCC: Cuetna bancaria
    entidad_=document.getElementById('EntidadDatosBancarios').value;
    oficina_=document.getElementById('SucursalDatosBancarios').value;
    dc_=document.getElementById('DCDatosBancarios').value;
    numCuenta_=document.getElementById('CuentaDatosBancarios').value;
   if (entidad_ == ""  || oficina_ == "" ||
      dc_ == "" || numCuenta_ == "")
      return false;
  else {
    if (entidad_.length != 4 || oficina_.length != 4 ||
        dc_.length != 2 || numCuenta_.length != 10)
      return false;
    else {
      if (!numerico(entidad_) || !numerico(oficina_) ||
          !numerico(dc_) || !numerico(numCuenta_))
        return false;
      else {
        if (!(obtenerDigito("00" + entidad_ + oficina_) ==
              parseInt(dc_.charAt(0))) || 
            !(obtenerDigito(numCuenta_) ==
              parseInt(dc_.charAt(1))))
          return false;
	    else
          return true;
      }
    }
  }
}, '');

/* Método para validar uno de los dos teléfonos que se piden en muchos formularios */
jQuery.validator.addMethod("ExisteTel", function(value) {
    // Si se ha seleccionado "ya soy cliente" o si se está en el área de clientes
    if ($("#PerfilClienteNo:checked").length > 0) {
        if ($("#MovilContactoPotencial").val() == '' && $("#TelefonoContactoPotencial").val() == '') {
            return false;
        } else {
            return true;
        }
    // Si se está en potenciales y se ha seleccionado "no soy cliente"
    } else {
        if ($("#MovilContactoCliente").val() == '' && $("#TelefonoContactoCliente").val() == '') {
            return false;
        } else {
            return true;
        }
    }
    return true;
}, 'Debes indicar al menos un n&uacute;mero de tel&eacute;fono.');

/* Método para validar que uno de los campos es igual a otro. Ideal para passwords */
jQuery.validator.addMethod ("igualQUE", function(value, element, param) {
    // bind to the blur event of the target in order to revalidate whenever the target field is updated
    // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
    var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
        $(element).valid();
    });
    return value == target.val();
}, 'El campo email es diferente.');

jQuery.validator.addMethod("existeEmail", function(value, element, param) {
 
	var Existence;
 
	$.ajax({
		url:'newsletter-comprueba-datos.asp?email=' + $(element).val(), 
		async:false, 
		success:function(data){ 
			if (trim(data)=="FALSE") {
				Existence = true;
			}else{
				Existence = false;
			}
		}
	});
	
	return Existence;

},'Lo sentimos, pero ya existe un usuario registrado con este email.');

jQuery.validator.addMethod("existeCuenta", function(value, element, param) {
	
	var Existence;

    var target = $(param).unbind(".validate-existeCuenta").bind("blur.validate-existeCuenta", function() {
        $(element).valid();
    });

    $.ajax({
		url:'newsletter-comprueba-datos.asp?contrasena=' + value +'&movil=' + target.val(), 
		async:false,
		success:function(data) {
			if (trim(data) == "TRUE") {
				Existence = true;
			} else {
				Existence = false;
			}
		}
    });
	
	return Existence;

}, 'El usuario introducido no existe.');

