$(function()
{
   (function($)
   {
      $.fn.clearDefault = function()
      {
         return this.each(function()
         {
            var default_value = $(this).val();
            $(this).data('dv', default_value);
            $(this).focus(function()
            {
               if ($(this).val() == default_value) $(this).val("");
            });
            $(this).blur(function()
            {
               if ($(this).val() == "") $(this).val(default_value);
            });
         });
      };
   })(jQuery);

   jqFormNL = $("#frmNL");
   jqFormNL.wrapInner('<div id="frmNL-inner" />');
   jqFormNL.append('<div id="frmNL-msg"></div>')
   jqFormNLInner = $("#frmNL-inner", jqFormNL);
   jqFormNLMsg = $("#frmNL-msg", jqFormNL);
   txtEmail = $('#txtNLmail', jqFormNL);
   txtEmail.clearDefault();

  /**
   * Proceso el newsletter
   */
   $('#btnNlSubmit').click(function()
   {
      var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      
      if (txtEmail.val() == '')
      {
         alert('Escribe aquí tu dirección de email antes');
      }
      else if (regEmail.test(txtEmail.val()) == false)
      {
         alert('Esta dirección de email no parece válida. Revísala por favor');
      }
      else
      {
         $.ajax(
         {
            url : '/newsletter/ajax/suscribe',
            type: 'POST',        
            data : {email : txtEmail.val()},
            dataType : 'json',
            beforeSend : function()
            {
               jqFormNLInner.hide();
               jqFormNLMsg.html('Suscribiéndote al newsletter... Aguarda unos segundos').addClass('sending');
            },
            error : function(XMLHttpRequest, textStatus, errorThrown)
            {
               alert('ERROR: ' + XMLHttpRequest + ' : ' + textStatus + ' : ' + errorThrown); 
            },                   
            success: function(oR)
            {
               if (oR.r == true)
               {
                  jqFormNLMsg.html('Gracias por suscribirte!!!. Te enviaremos todas las novedades.').removeClass('sending').addClass('success');                                             
               }
               else
               {
                  alert(oR.e.m);
                  jqFormNLMsg.hide();
                  jqFormNLInner.show();
               }
            }
         });
      }
      return false;
   });
});
