
jQuery(function($){

  $('#registro_id').parents('form').validate({
    rules: {
      
        'registro[id]': {
                      
        },
        'registro[nombre]': {
                      required: true, maxlength: 255
        },
        'registro[apellido]': {
                      required: true, maxlength: 255
        },
        'registro[tel1]': {
                      phoneEs: true, required: true
        },
        'registro[email]': {
                      email: true, required: true
        },
        'registro[direccion]': {
                      required: true, maxlength: 255
        },
        'registro[cp]': {
                      cp: true, required: true
        },
        'registro[localidad]': {
                      required: true, maxlength: 255
        },
        'registro[comentario]': {
                      maxlength: 1024
        },
        'registro[pais_id]': {
                      required: true
        },
        'registro[provincia_id]': {
                      provincia: true
        }    },
    messages: {
              'registro[id]': {
                      
        },
        'registro[nombre]': {
                      required: "Este campo es obligatorio.", maxlength: "Error en el nombre. M\u00e1ximo 255 caracteres."
        },
        'registro[apellido]': {
                      required: "Este campo es obligatorio.", maxlength: "Error en el apellido. M\u00e1ximo 255 caracteres."
        },
        'registro[tel1]': {
                      required: "Este campo es obligatorio."
        },
        'registro[email]': {
                      required: "Este campo es obligatorio."
        },
        'registro[direccion]': {
                      required: "Este campo es obligatorio.", maxlength: "Error en la direcci\u00f3n. M\u00e1ximo 255 caracteres."
        },
        'registro[cp]': {
                      required: "Este campo es obligatorio."
        },
        'registro[localidad]': {
                      required: "Este campo es obligatorio.", maxlength: "Error en la localidad. M\u00e1ximo 255 caracteres."
        },
        'registro[comentario]': {
                      maxlength: function(a, elem){ return "\"" + $(elem).val() + "\" is too long (1024 characters max)."; }
        },
        'registro[pais_id]': {
                      required: "Este campo es obligatorio."
        },
        'registro[provincia_id]': {
                      
        }
    },
    wrapper: 'ul class=error_list',
    errorElement: 'li',
    errorPlacement: function(error, element)
    {
     if(element.parents('.radio_list').is('*') || element.parents('.checkbox_list').is('*'))
     {
       error.prependTo( element.parent().parent().parent() );
     }
     else
     {
       error.prependTo( element.parent() );
     }
   },
   submitHandler: function(form) { popup(); }

  });

          
});

/* for some reason the jQuery Validate plugin does not incluce a generic regex method */
jQuery.validator.addMethod(
  "regex",
  function(value, element, regexp) {
      if (regexp.constructor != RegExp)
          regexp = new RegExp(regexp);
      else if (regexp.global)
          regexp.lastIndex = 0;
      return this.optional(element) || regexp.test(value);
  },
  "Inv&aacute;lido."
);



jQuery.validator.addMethod(
  "dni",
function valida_nif_cif_nie(value, element)
{
	var a = value;
	var temp=a.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
        
        var pais = $('#registro_pais_id').val();

        if(pais == '1')
        {
            if (temp!=='')
            {
                    //si no tiene un formato valido devuelve error
                    if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
                    {
                            return 0;
                    }

                    //comprobacion de NIFs estandar
                    if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
                    {
                            posicion = a.substring(8,0) % 23;
                            letra = cadenadni.charAt(posicion);
                            var letradni=temp.charAt(8);
                            if (letra == letradni)
                            {
                                    return 1;
                            }
                            else
                            {
                                    return -1;
                            }
                    }

                    //algoritmo para comprobacion de codigos tipo CIF
                    suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
                    for (i = 1; i < 8; i += 2)
                    {
                            temp1 = 2 * parseInt(a[i]);
                            temp1 += '';
                            temp1 = temp1.substring(0,1);
                            temp2 = 2 * parseInt(a[i]);
                            temp2 += '';
                            temp2 = temp2.substring(1,2);
                            if (temp2 == '')
                            {
                                    temp2 = '0';
                            }

                            suma += (parseInt(temp1) + parseInt(temp2));
                    }
                    suma += '';
                    n = 10 - parseInt(suma.substring(suma.length-1, suma.length));

                    //comprobacion de NIFs especiales (se calculan como CIFs)
                    if (/^[KLM]{1}/.test(temp))
                    {
                            if (a[8] == String.fromCharCode(64 + n))
                            {
                                    return 1;
                            }
                            else
                            {
                                    return -1;
                            }
                    }

                    //comprobacion de CIFs
                    if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
                    {
                            temp = n + '';
                            if (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
                            {
                                    return 2;
                            }
                            else
                            {
                                    return -2;
                            }
                    }

                    //comprobacion de NIEs
                    //T
                    if (/^[T]{1}/.test(temp))
                    {
                            if (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
                            {
                                    return 3;
                            }
                            else
                            {
                                    return -3;
                            }
                    }

                    //XYZ
                    if (/^[XYZ]{1}/.test(temp))
                    {
                            pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
                            if (a[8] == cadenadni.substring(pos, pos + 1))
                            {
                                    return 3;
                            }
                            else
                            {
                                    return -3;
                            }
                    }
            }
            return 0;
        }
        return 1;
	
},
  "Inv&aacute;lido DNI."
);

function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };

    return sa ? s : s[0];
}

jQuery.validator.addMethod(
  "phoneEs",
  function(value, element) {

      value = value.replace(/-/g,'');
      value = value.replace(/ /g,'');

      var pais = $('#registro_pais_id').val();
      if(pais == '1')
      {
            regexp = /^([9|6|8])[0-9]{8}$/;
      }
      else
      {
        regexp = /.+/;
      }
      if (regexp.constructor != RegExp)
      {
      	regexp = new RegExp(regexp);
      }
      else if (regexp.global)
      {
      	regexp.lastIndex = 0;
      }

      if(this.optional(element) || regexp.test(value))
      {
        if(pais == '1')
        {
            var sub = value.substring(1);
            var char = sub[0];

            for(i=1; i<8; i++)
            {
                if(char != sub[i])
                {
                    return true;
                }
                char = sub[i];
            }
        }
        else
        {
            return true;
        }
    }
    return false;
  },
  "Tel&eacute;fono inv&aacute;lido. "
);

jQuery.validator.addMethod(
  "nivelEstudio",
  function(value, element) {

    if(value != '') {
        return true;
    }
    return false;
  },
  "Seleccione Nivel Estudio. "
);

jQuery.validator.addMethod(
  "nacionalidad",
  function(value, element) {

    if(value != '') {
        return true;
    }
    return false;
  },
  "Seleccione Nacionalidad. "
);

jQuery.validator.addMethod(
  "fNacimiento",
  function(value, element)
  {
    var rday = $('#registro_f_nacimiento_day').val();
    var rmonth = $('#registro_f_nacimiento_month').val();
    var ryear = $('#registro_f_nacimiento_year').val();
    var fecha = rday+'/'+rmonth+'/'+ryear;
    $('#registro_f_nacimiento').val(fecha);
    var min_age = 17;
    var max_age = 66;
    try
    {
        if(isDate(rmonth+'/'+rday+'/'+ryear)) {
            var dob = new Date(ryear, rmonth-1, rday);
            var today=new Date();
            var day=today.getDate();
            var month=today.getMonth()+1;
            var year=today.getFullYear();

            age=year-ryear;

            if(rmonth>month){
                age--;
            }
            else if(rmonth==month){
                if(rday>day){
                    age--;
                }
            }

            if((age<17) || (age>65)){
                return false;
            }
            else{
                return true;
            }
        }
        return false;
        
    }
    catch(err)
    {
        return false;
    }
    
    

  },
  "Debes tener entre 17 y 65 a&ntilde;os."
);

jQuery.validator.addMethod(
  "provincia",
  function(value, element)
  {
  	  var pais = $('#registro_pais_id').val();
  	  if(pais == '1')
  	  {
  	  	if(isEmpty(value) || value == '0' )
  	  	{
  	  		return false;
  	  	}
	  }
	  return true;
  },
  "Provincia inv&aacute;lida."
);

jQuery.validator.addMethod(
  "cp",
  function(value, element) {

        var provinciasCP =new Array();
        provinciasCP[7801] = '01'; //Álava 01
        provinciasCP[4257] = '02'; //Albacete 02
        provinciasCP[6302] = '03'; //Alicante/Alacant 03
        provinciasCP[3] = '04'; //Almería 04
        provinciasCP[8055] = '33'; //Asturias 33
        provinciasCP[1710] = '05'; //Ávila 05
        provinciasCP[6847] = '06'; //Badajoz 06
        provinciasCP[7553] = '07'; //Balears (Illes) 07
        provinciasCP[4893] = '08'; //Barcelona 08
        provinciasCP[1959] = '09'; //Burgos 09
        provinciasCP[7012] = '10'; //Cáceres 10
        provinciasCP[106] = '11'; //Cádiz 11
        provinciasCP[1606] = '39'; //Cantabria 39
        provinciasCP[6444] = '12'; //Castellón/Castelló 12
        provinciasCP[5844] = '51'; //Ceuta 51
        provinciasCP[4345] = '13'; //Ciudad Real 13
        provinciasCP[151] = '14'; //Córdoba 14
        provinciasCP[7233] = '15'; //Coruña (A) 15
        provinciasCP[4448] = '16'; //Cuenca 16
        provinciasCP[5205] = '17'; //Girona 17
        provinciasCP[227] = '18'; //Granada 18
        provinciasCP[2331] = '19'; //Guadalajara 19
        provinciasCP[7853] = '20'; //Guipúzcoa 20
        provinciasCP[396] = '21'; //Huelva 21
        provinciasCP[782] = '22'; //Huesca 22
        provinciasCP[476] = '23'; //Jaén 23
        provinciasCP[7622] = '26'; //La Rioja 26
        provinciasCP[2620] = '24'; //León 24
        provinciasCP[5427] = '25'; //Lleida 25
        provinciasCP[7328] = '27'; //Lugo 27
        provinciasCP[5847] = '28'; //Madrid 28
        provinciasCP[574] = '29'; //Málaga 29
        provinciasCP[7798] = '52'; //Melilla 52
        provinciasCP[8135] = '30'; //Murcia 30
        provinciasCP[6028] = '31'; //Navarra 31
        provinciasCP[7396] = '32'; //Ourense 32
        provinciasCP[2832] = '34'; //Palencia 34
        provinciasCP[1516] = '35'; //Palmas (Las) 35
        provinciasCP[7489] = '36'; //Pontevedra 36
        provinciasCP[3024] = '37'; //Salamanca 37
        provinciasCP[1551] = '38'; //Santa Cruz de Tenerife 38
        provinciasCP[3387] = '40'; //Segovia 40
        provinciasCP[675] = '41'; //Sevilla 41
        provinciasCP[3597] = '42'; //Soria 42
        provinciasCP[5659] = '43'; //Tarragona 43
        provinciasCP[985] = '44'; //Teruel 44
        provinciasCP[4687] = '45'; //Toledo 45
        provinciasCP[6580] = '46'; //Valencia/València 46
        provinciasCP[3781] = '47'; //Valladolid 47
        provinciasCP[7942] = '48'; //Vizcaya 48
        provinciasCP[4007] = '49'; //Zamora 49
        provinciasCP[1222] = '50'; //Zaragoza 50
          
        value = value.replace(/ /g,'');

        var pais = $('#registro_pais_id').val();

        if(pais == '1')
        {
            if(value.length != 5)
            {
                return false;
            }
            var regexp = /^[0-9]{5}$/;
            if (regexp.constructor != RegExp)
            {
                regexp = new RegExp(regexp);
            }
            else if (regexp.global)
            {
                regexp.lastIndex = 0;
            }

            if( regexp.test(value) )
            {
                var provincia = $('#registro_provincia_id').val();
                var sub = value.substring(0,2);
                if( provinciasCP[provincia] == sub)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        return true;
  },
  "C&oacute;digo Postal inv&aacute;lido."
);

function isEmpty( inputStr ) { if ( null == inputStr || "" == inputStr ) { return true; } return false; }

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
var dtCh= "/";
var today = new Date();
var minYear=today.getFullYear()-66;
var maxYear=today.getFullYear()-17;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year < minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}
