$(function(){      
    var base_url = $("meta[name='DC.url']").attr('content');         
    /*
    $('#registro_veahi').click(function(e){
        e.preventDefault();
        $(document).scrollTo( '#registro_destino', 800, {
            onAfter: function(){
                $('#registro_destino p, #registro_destino li').flash('#CE7812', 1000);
            }
        });
    });        
    
    jQuery.fn.flash = function(color, duration) {
        var current = '#ffffff';
        this.animate({
            color: color
        }, duration);

        this.animate( {color: current}, duration);
    }
    */
    $('#registro_provincia_name_td').hide();
    
    $('#registro_condiciones').click(function() {
        if  ($('#registro_condiciones:checked').length > 0) {
              var cssObj = {
                'color' : '#7d7d7d',
                'font-weight' : ''
              }
              $("#registro_condiciones-label").css(cssObj);
        } else {                 
                var cssObj = {
                'color' : '#f00',
                'font-weight' : 'bold'
              }
              $("#registro_condiciones-label").css(cssObj);
        }
    });
    
    
    $('#registro_id_pais').change(function(){
        //España = 73;
        var id_pais_selected = $(this).val();
        
        if(id_pais_selected != '73')
        {
            $('#registro_provincia_id_td').hide();
            $('#registro_provincia_name_td').show();
            //$('#registro_provincia_name').attr('value', '');
            $('#registro_id_provincia').val(0);
        }
        else
        {
            $('#registro_provincia_id_td').show();
            $('#registro_provincia_name_td').hide();
            $('#registro_provincia_name').attr('value', '');
            $('#registro_id_provincia').val(0);
        }
    });
    
    
    $('#registro_fecha_completa').val($('#registro_mes').val()+'/'+$('#registro_dia').val()+'/'+$('#registro_anio').val());
    $('#registro_dia, #registro_mes, #registro_anio').change(function () {
        var full_date = $('#registro_mes').val()+'/'+$('#registro_dia').val()+'/'+$('#registro_anio').val();
        $('#registro_fecha_completa').val(full_date);
    });
    
    jQuery.validator.messages.required = "";
    jQuery.validator.messages.email = "";
    jQuery.validator.messages.dateISO ="";
    jQuery.validator.messages.samemail = "";
    jQuery.validator.messages.digits = "";
    jQuery.validator.messages.maxlength = "";
    jQuery.validator.messages.minlength = "";
    jQuery.validator.messages.fecha = "";
    
  
  var validator = $("#acceso_form").validate({
        errorElement: "span",
      rules: {
            registro_nombre: {
                required:true,
                lettersonly:true
                
            },
            registro_apellidos: {
                required:true,
                lettersonly:true
                
            },            
            registro_email: {
                required:true,
                email:true,
                remote: {
                    url: base_url + "acceso/compruebaemail",
                    type: 'post'                     
                        }, 
                equalTo: "#registro_email2"      
            },
            registro_password: {
                minlength: 8,
                required:true,
                equalTo: "#registro_password2"         
            },
            registro_cp: {
                required:true,
                cp: true,
                cp_provincia:true
                /*remote: {
                    type: "POST",
                    url: base_url+"acceso/compruebacp",             
                    //data: $('#registro_form').serialize()                     
                    data: "registro_cp="+$('#registro_cp').val()+"&registro_id_provincia="+$('#registro_id_provincia').val(),
                        },*/
                
            },
            registro_direccion: {
                required:true               
            },
            registro_localidad: {
                required:true,
                lettersonly: true
            },
            registro_id_provincia:{
                provincias: true
                
            },
            registro_provincia_name:{
                provincia_name: true
                
            },
            registro_id_pais:{
                paises: true
                
            },
            registro_telefono: {
                required:true,
                digits: true,
                maxlength: 9
            },
            registro_fecha_completa:{
                required:true,
                fecha:true          
            },
            registro_condiciones: {
                condiciones: true
            }            
        },
        
        invalidHandler: function(e, validator) {
                var errors = validator.numberOfInvalids();
                validator.hideErrors();
        },
        submitHandler: function(form) {enviarAjax(); }
  });
  



  
  jQuery.validator.addMethod(
  'provincias',
  function(a, element, param)
  {
        if($('#registro_id_provincia').val()  == '0' && $('#registro_id_pais').val() == '73')
        {
            return false;
        }
        else
        {
            return true;
        }
  }, ''); 
  
  
jQuery.validator.addMethod(
  'comprobaremail',
  function(a, element, param)
  {
        if($('#registro_id_provincia').val()  == '0' && $('#registro_id_pais').val() == '73')
        {
            return false;
        }
        else
        {
            return true;
        }
  }, '');
  
  jQuery.validator.addMethod(
  'cp_provincia',
  function(a, element, param)
  {
      if($('#registro_id_pais').val() != '73')
      {
          return true;
      }
      var resultado = false;
        $.ajax({
            type: "POST",
            async:false,
            url: base_url+"acceso/compruebacp",             
            data: "registro_cp="+$('#registro_cp').attr("value")+"&registro_id_provincia="+$('#registro_id_provincia').attr("value"),
            success: function(data){
                if (data == 'true') 
                {
                    resultado = true;
                }else
                {                       
                    resultado = false;                    
                }
            }                      
        });
        //console.log(resultado);
        return resultado;
        
  }, ''); 
    
     
     jQuery.validator.addMethod(
  'cp',
  function(a, element, param)
  {   
        if($('#registro_id_pais').val() == '73' && ($('#registro_cp').val().length < 4 || $('#registro_cp').val().length > 5 || isNaN(Number($('#registro_cp').val()))))
        {
            return false;
        }
        else
        {
            return true;
        }
  }, '');    
  
  jQuery.validator.addMethod(
  'provincia_name',
  function(a, element, param)
  {
        if($('#registro_provincia_name').val()  == '' && $('#registro_id_pais').val() != '73')
        {
            return false;
        }
        else
        {
            return true;
        }
  }, '');  
  
  jQuery.validator.addMethod(
  'paises',
  function(a, element, param)
  {
        if($('#registro_id_pais').val()  == '0')
        {
            return false;
        }
        else
        {
            return true;
        }
  }, '');
        
  jQuery.validator.addMethod(
  'condiciones', 
  function (a, element, param) {
      if($('#registro_condiciones:checked').length > 0){
          var cssObj = {
          'color' : '#7d7d7d',
          'font-weight' : 'normal'
          }
              
          $("#registro_condiciones-label").css(cssObj);
           $("#registro_condiciones-label a").css(cssObj);
          return true;
          
      }else{             
            var cssObj2 = {
            'color' : '#f00',
            'font-weight' : 'bold'
             }            
          $("#registro_condiciones-label").css(cssObj2);
          $("#registro_condiciones-label a").css(cssObj2);
          return false;
          
      }                  
  }, '');
  
  jQuery.validator.addMethod("lettersonly", function(value, element) {
  return this.optional(element) || /^[\á\é\í\ó\ú\ñ\Ñ\s a-z A-Z]+$/i.test(value);
  }, '');
  
    jQuery.validator.addMethod(
  'fecha',
  
  function(a, element, param){ 
    $('#registro_dia, #registro_mes, #registro_anio').addClass("error");

      
    var dateStr = $('#registro_mes').val()+'/'+$('#registro_dia').val()+'/'+$('#registro_anio').val(); 
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        return false;
    }

    month = matchArray[1]; // p@rse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        return false;
    }

    if (day < 1 || day > 31) {
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        return false;
    }

    if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day > 29 || (day==29 && !isleap)) {
        return false;
    }
    }
               
    $('#registro_dia, #registro_mes, #registro_anio').removeClass("error");
    return true; // date is valid

  }, '') 
    
    var input_recordar_usuario      =  $("#recordar_email").val();
    
    $("#recordar_email").focus(function() {if ($(this).val() == input_recordar_usuario) { $(this).val(''); }});
    $("#recordar_email").blur(function() {if (! $(this).val().length) { $(this).val(input_recordar_usuario); }});
    
    
    var input_login_usuario      =  $("#usuario").val();
    var input_login_password     =  $("#password").val();
    
    $("#usuario").focus(function() {if ($(this).val() == input_login_usuario) { $(this).val(''); }});
    $("#usuario").blur(function() {if (! $(this).val().length) { $(this).val(input_login_usuario); }});
    
    $("#password").focus(function() {if ($(this).val() == input_login_password) { $(this).val(''); }});
    $("#password").blur(function() {if (! $(this).val().length) { $(this).val(input_login_password); }});
    
    // valores por defecto de los campos
    var input_nombre        =  $("#registro_nombre").val();
    var input_apellidos     =  $("#registro_apellidos").val(); 
    var input_email         =  $("#registro_email").val();
    var input_telefono      =  $("#registro_telefono").val(); 
    var input_direccion     =  $("#registro_direccion").val();
    var input_localidad     =  $("#registro_localidad").val();
    var input_provincia     =  $("#registro_provincia_name").val();
    var input_cp            =  $("#registro_cp").val();    
    var input_email2        =  $("#registro_email2").val();    
    var input_password      =  $("#registro_password").val();
    var input_password2     =  $("#registro_password2").val();
    
     
    $("#registro_nombre").focus(function() {if ($(this).val() == input_nombre) { $(this).val(''); }});
    $("#registro_nombre").blur(function() {if (! $(this).val().length) { $(this).val(input_nombre); }});
         
    $("#registro_apellidos").focus(function() { if ( $(this).val() == input_apellidos) { $(this).val(''); }});
    $("#registro_apellidos").blur(function() {if (! $(this).val().length) { $(this).val(input_apellidos); }});
           
    $("#registro_email").focus(function() {if ($(this).val() == input_email) { $(this).val(''); }});
    $("#registro_email").blur(function() {if (! $(this).val().length) { $(this).val(input_email); }});
         
    $("#registro_telefono").focus(function() { if ( $(this).val() == input_telefono) { $(this).val(''); }});
    $("#registro_telefono").blur(function() {if (! $(this).val().length) { $(this).val(input_telefono); }});
           
    $("#registro_direccion").focus(function() {if ($(this).val() == input_direccion) { $(this).val(''); }});
    $("#registro_direccion").blur(function() {if (! $(this).val().length) { $(this).val(input_direccion); }});
    
    $("#registro_localidad").focus(function() {if ($(this).val() == input_localidad) { $(this).val(''); }});
    $("#registro_localidad").blur(function() {if (! $(this).val().length) { $(this).val(input_localidad); }});
         
    $("#registro_provincia_name").focus(function() { if ( $(this).val() == input_provincia) { $(this).val(''); }});
    //$("#registro_provincia_name").blur(function() {if (! $(this).val().length) { $(this).val(input_provincia); }});
         
    $("#registro_cp").focus(function() { if ( $(this).val() == input_cp) { $(this).val(''); }});
    $("#registro_cp").blur(function() {if (! $(this).val().length) { $(this).val(input_cp); }});
               
    $("#registro_email2").focus(function() {if ($(this).val() == input_email2) { $(this).val(''); }});
    $("#registro_email2").blur(function() {if (! $(this).val().length) { $(this).val(input_email2); }});
    
    $("#registro_password").focus(function() {if ($(this).val() == input_password) { $(this).val(''); }});
    $("#registro_password").blur(function() {if (! $(this).val().length) { $(this).val(input_password); }});
    
    $("#registro_password2").focus(function() {if ($(this).val() == input_password2) { $(this).val(''); }});
    $("#registro_password2").blur(function() {if (! $(this).val().length) { $(this).val(input_password2); }});
    

   
   
   // Registro 
    $('.buttons a:first').click(function (event) {        
        $('div#recordar').hide();
        $('div#registroOk').hide();  
        $('div#registroNoOk').hide();
        $('div#envioOk').hide();
        $('div#envioNoOk').hide();
        $('div#contenedor-formulario-registro').show();
        event.preventDefault();        
        $('div.registro').slideToggle('medium');
        event.stopPropagation();     
    });

    $('div.close').click(function (event) {                  
        $('div.registro').slideToggle('medium'); 
        event.stopPropagation();           
    });    
    
    $('.recordarme a:first').click(function (event) { 
        $('div#registroOk').hide();  
        $('div#registroNoOk').hide();
        $('div#envioOk').hide();
        $('div#envioNoOk').hide();      
        $('div#contenedor-formulario-registro').hide();
        $('div#recordar').show(); 
        event.preventDefault();        
        $('div.registro').slideToggle('medium');
        event.stopPropagation();     
    }); 
    
    $(document).click(function(event) {
        
        e = event || window.event;
        rightclick = "";
        if (e.which)
        rightclick = (e.which == 3);
        else if (e.button)
        rightclick = (e.button == 2);

        if(rightclick == "")
        { 
          if ($("div.registro").is(':visible')) {
              $("div.registro").hide();                 
              /*$(".nav-top").fadeIn(); 
              if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');*/    
          }
        }
    });
    
    $("div.registro").click(function(event) {
        event.stopPropagation();            
    });              
    
    function enviarAjax()
    {
    var dataString = 'registro_nombre='+ $("#registro_nombre").val() 
    + '&registro_apellidos=' + $("#registro_apellidos").val() 
    + '&registro_email=' + $("#registro_email").val()  
    + '&registro_telefono=' + $("#registro_telefono").val() 
    + '&registro_direccion=' + $("#registro_direccion").val() 
    + '&registro_localidad=' + $("#registro_localidad").val() 
    + '&registro_id_provincia=' + $("#registro_id_provincia").val()
    + '&registro_provincia_name=' + $("#registro_provincia_name").val() 
    + '&registro_cp=' + $("#registro_cp").val() 
    + '&registro_password=' + $("#registro_password").val()
    + '&registro_id_pais=' + $("#registro_id_pais").val()
    + '&registro_fecha_completa=' + $("#registro_fecha_completa").val()   
    + '&registro_dia=' + $("#registro_dia").val()
    + '&registro_mes=' + $("#registro_mes").val()
    + '&registro_anio=' + $("#registro_anio").val() 
    + '&registro_condiciones=' + $("#registro_condiciones").val()
    + '&registro_sexo=' + $('input[name=registro_sexo]:checked').val();
    
    
        
      //elimino el comportamiento por defecto del enlace
      //evento.preventDefault();         
      //Aquí pondría el código de la llamada a Ajax
       $('img.imagen-cargando').show();
       //var dataString = 'registro_nombre='+ $("input#registro_nombre").val();  
         //alert (dataString);return false;  
         $.ajax({  
           type: "POST",  
           url: base_url+"acceso/guardarFormulario",  
           data: dataString,  
           success: function(data) {   
               if(data == "true")
               {
                    $('div.registro').slideToggle('medium', function() {
                    $('img.imagen-cargando').hide();  
                    $('div#recordar').hide();   
                    $('div#contenedor-formulario-registro').hide(); 
                    $('div#registroOk').show();                                                             
                    $('div.registro').slideToggle('medium');                     
                 });
               }else{
                    $('div.registro').slideToggle('medium', function() {
                    $('img.imagen-cargando').hide();  
                    $('div#recordar').hide();   
                    $('div#contenedor-formulario-registro').hide(); 
                    $('div#registroNoOk').show();                                                             
                    $('div.registro').slideToggle('medium');                     
                 }); 
                    
                  
                                       
               }                              
           },
           error: function(XMLHttpRequest, textStatus, errorThrown) {  
               console.log(XMLHttpRequest);
               console.log(textStatus);
               console.log(errorThrown);                            
           }
           
         });     
      
   }                 
   $('#registro_button').click(function (event) {

       if($("#registro_nombre").val() == input_nombre)
       {
           $("#registro_nombre").val("");           
       }
       if($("#registro_apellidos").val() == input_apellidos)
       {
           $("#registro_apellidos").val("");           
       }
       if($("#registro_email").val() == input_email)
       {
           $("#registro_email").val("");           
       }
       if($("#registro_email2").val() == input_email2)
       {
           $("#registro_email2").val("");           
       }
       if($("#registro_password").val() == input_password)
       {
           $("#registro_password").val("");           
       }
       if($("#registro_password2").val() == input_password2)
       {
           $("#registro_password2").val("");           
       }
       if($("#registro_telefono").val() == input_telefono)
       {
           $("#registro_telefono").val("");           
       }
       if($("#registro_direccion").val() == input_direccion)
       {
           $("#registro_direccion").val("");           
       }
       if($("#registro_localidad").val() == input_localidad)
       {
           $("#registro_localidad").val("");           
       }
       if($("#registro_provincia_name").val() == input_provincia)
       {
           $("#registro_provincia_name").val("");           
       }
       if($("#registro_cp").val() == input_cp)
       {
           $("#registro_cp").val("");           
       }        
       
   }); 
   
   
   var validator = $("#recordar_form").validate({
        errorElement: "span",
      rules: {
            recordar_email: {
                required:true,
                email:true      
            }
        },
        
        invalidHandler: function(e, validator) {
                var errors = validator.numberOfInvalids();
                validator.hideErrors();
        },
        submitHandler: function(form) {enviarRecordar(); }
  }); 
  
  
  function enviarRecordar()
    {          
    var dataString = 'recordar_email='+ $("#recordar_email").val();
    
    
        
      //elimino el comportamiento por defecto del enlace
      //evento.preventDefault();         
      //Aquí pondría el código de la llamada a Ajax
       $('img.imagen-cargando').show();
       //var dataString = 'registro_nombre='+ $("input#registro_nombre").val();  
         //alert (dataString);return false;  
         $.ajax({  
           type: "POST",  
           url: base_url+"acceso/recordar_do",  
           data: dataString,  
           success: function(data) {   
               if(data == "true")
               {
                    $('div.registro').slideToggle('medium', function() {
                    $('img.imagen-cargando').hide();  
                    $('div#recordar').hide();   
                    $('div#contenedor-formulario-registro').hide(); 
                    $('div#envioOk').show();                                                             
                    $('div.registro').slideToggle('medium');                    
                 });
               }else{
                    $('div.registro').slideToggle('medium', function() {
                    $('img.imagen-cargando').hide();  
                    $('div#recordar').hide();   
                    $('div#contenedor-formulario-registro').hide(); 
                    $('div#envioNoOk').show();                                                             
                    $('div.registro').slideToggle('medium');                     
                 }); 
                                       
               }                              
           },
           error: function(XMLHttpRequest, textStatus, errorThrown) {  
               console.log(XMLHttpRequest);
               console.log(textStatus);
               console.log(errorThrown);                            
           }
           
         });     
      
   }
   
    function compruebacp()
    {
        var resultado = false;
        $.ajax({
            type: "POST",
            url: base_url+"acceso/compruebacp",
            //async:false, 
            data: $('#registro_form').serialize(),
            success: function(data){
                if (data == 'true') {
                    resultado = false;
                }else
                {                       
                    resultado = true;                    
                }
            }                      
        });
        return resultado;       
    } 
});
