new function() {
       // $.fn.validate = validate() {};
    $.fn.validate = {    
        init: function(o) {       
          if(o.name == 'sexo' || o.name == 'estadocivil') { this.selecciona(o) };
          if(o.name == 'hijos') { this.numero(o) };             
          if(o.name == 'nombre' || o.name == 'apellidos' || o.name == 'direccion' || o.name == 'tlf' || o.name == 'observaciones') { this.estalleno(o) };
          if(o.name == 'username') { this.username(o) };
          if(o.name == 'password') { this.password(o) };
          if(o.name == 'email') { this.email(o) };
          if(o.name == 'dob') { this.dob(o) };          
        },
        username: function(o) {
          var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(user)) {
             doValidate(o);
            } else {
             doError(o,'debe escribir numeros o letras');
            };
        },
        estalleno: function(o) {
          if (o.value.length > 3) {
            doSuccess(o);
          } else {
            doError(o,'debe escribir por lo menos 3 carácteres');
          }
        },
        selecciona: function(o) {          
          if (o.selectedIndex > 0) {
            doSuccess(o);
          } else {
            doError(o,'debe escoger una opción de la lista');
          }
        },
        numero: function(o) {
          if (!isNaN(o.value)) {
            doSuccess(o);
          } else {
            doError(o,'debe escribir un número');
          }
        },        
        password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(pass)) {
             //doValidate(o);
             variablecompta = $("#confirmpass").get(0).value;
             $('#confirmpass').val("");
             $('#confirmpass_img').html("");          
             $('#confirmpass_msg').html("");
             $('#confirmpass_li').removeClass("success");                                                    
             doSuccess(o);
            } else {
             doError(o,'debe escribir numeros o letras');
            };
        },
        email: function(o) {
          var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
           if (o.value.match(email)) {
              doSuccess(o);
            } else {
              doError(o,'dirección de correo electrónico incorrecta');
            };
        },
        dob: function(o) {
          //var dob  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
          var dob  = /(0[1-9]|[12][0-9]|3[01])+\/(0[1-9]|1[012])+\/(19|20)\d\d/;
            if (o.value.match(dob)) {
              doSuccess(o);
            } else {
              doError(o,'fecha no válida. Use el formato dd/mm/aaaa');
            };
        }
     };

     function doSuccess(o) {
              $('#' + o.id + '_img').html('<img src="imatges/accept.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').removeClass("error");
              $('#' + o.id + '_msg').html("");
              $('#' + o.id + '_li').addClass("success");
     }

     function doError(o,m) {
              $('#' + o.id + '_img').html('<img src="imatges/exclamation.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').addClass("error");
              $('#' + o.id + '_msg').html(m);
              $('#' + o.id + '_li').removeClass("success");
     }
     //private helper, validates each type after check
     function doValidate(o) {
        	$('#' + o.id + '_img').html('<img src="imatges/loading.gif" border="0" style="float:left;" />');
        	$.post('checkuser.php?'+Math.random(), { id: o.id, value: o.value }, function(json) {        	         
                  	eval("var args = " + json);
                    if (args.success == true)
                  	{
                  	  doSuccess(args);
                  	}
                  	else
                  	{
                      doError(args,args.msg);
                  	}
                  });
    };

};
$.fn.match = function(m) {  
	$('#' + this.get(0).id + '_img').html('<img src="imatges/loading.gif" border="0" style="float:left;" />');
	if ($(this).get(0).value == $(m.match).val()) {
          $('#' + this.get(0).id + '_img').html('<img src="imatges/accept.gif" border="0" style="float:left;" />');
          $(m.error).removeClass("error");
          $(m.error).addClass("success");
          $('#' + this.get(0).id + '_msg').html("");
        } else {
          $('#' + this.get(0).id + '_img').html('<img src="imatges/exclamation.gif" border="0" style="float:left;" />');
          $(m.error).addClass("error");
          $(m.error).removeClass("success");
          $('#' + this.get(0).id + '_msg').html("La contraseña no coincide con la confirmación.");
        };
};
$(document).ready(function()
{

  //$("//[@class=validated]/input").blur(function() {
  $("input[@class=validated]").blur(function() {                                        
          $(this).validate.init(this);
  });

  $("select[@class=validated]").blur(function() {                                        
          $(this).validate.init(this);
  }); 
  $("#confirmpass").blur(function() {
          $(this).match({match: '#password', error: '#confirmpass_li'});
  });

  $(".form li").mouseover(function() {
          $(this).addClass("selected");
  });
  $(".form li").mouseout(function() {
          $(this).removeClass("selected");
  });
  $("#submitform").click(function() {            
      $("#observaciones_li").addClass("success"); 
      $('#observaciones_img').html('<img src="imatges/accept.gif" border="0" style="float:left;" />');
      totalcamps=$('body').find(".validated").size();
      totalcamps=totalcamps/2;
      campsok=$('body').find(".success").size();
      campsko=$('body').find(".error").size();
      campsbuits=totalcamps-campsok-campsko;
      if (campsok < totalcamps) {
        if (campsko > 0) {
          alert("Se han encontrado errores, y no se puede enviar el formulario. Por favor, revise las advertencias");
        } else {
          alert("Algunos campos obligatorios del formulario no se rellenaron. Por favor, rellene los campos que faltan");
        }
      } else {                        
          $('#capaboto').html('<img src="imatges/loading.gif" border="0" style="float:left;" /> Comprobando los datos...');
          //$('#' + o.id + '_img').html('<img src="imatges/loading.gif" border="0" style="float:left;" />');
          // Canviar id:o.id, etc... per TOTS els camps!
        	//$.post('reguser.php?'+Math.random(), { usuari: $("#username").get(0).value, clau: $("#password").get(0).value, email: $("#email").get(0).value, nom: $("#nombre").get(0).value, cognoms: $("#apellidos").get(0).value, dataneix: $("#dob").get(0).value, sexe: $("#sexo").get(0).value, estatcivil: $("#estadocivil").get(0).value, fills: $("#hijos").get(0).value, adresa: $("#direccion").get(0).value, tlf: $("#tlf").get(0).value, observa: $("#observaciones").get(0).value }, function(json) {              
        	$.post('reguser.php?'+Math.random(), { usuari: $("#username").get(0).value, clau: $("#password").get(0).value, email: $("#email").get(0).value, nom: $("#nombre").get(0).value, cognoms: $("#apellidos").get(0).value, dataneix: $("#dob").get(0).value, fills: $("#hijos").get(0).value, adresa: $("#direccion").get(0).value, tlf: $("#tlf").get(0).value, observa: $("#observaciones").get(0).value }, function(json) {
                   eval("var args = " + json);
                   if (args.success == true)
                  	{                  	  
                      $("#capaform").fadeTo(3000,1,function () {
                        $("#capaform").html("<center>"+args.msg+"<br /><br /><a href='/portada'>Volver a la portada</a></center>");
                      });                              	                        
                  	}
                  	else
                  	{
                    	$('#' + args.id + '_img').html('<img src="imatges/exclamation.gif" border="0" style="float:left;" />');
                      $('#' + args.id + '_li').addClass("error");
                      $('#' + args.id + '_msg').html(args.msg);
                      $('#' + args.id + '_li').removeClass("success");
                      //$("input[@class=validated]").validate.doError(args,args.msg);
                  	}
                  });
                               
      }      
  });
  
});
