(function ($) {
  $(function () {

    var form = $('#subscribe-form'),
        subscriber = $('.subscriber', form),
        button = $('.subscribe', form),
        options = null;
  
    form.each(function() {
      options = this.onclick instanceof Function ? this.onclick() : {};
      this.onclick = null;
      this.removeAttribute('onclick');
    });    
    
    function MadMini() {
      this.validateEmail = function(email) {
        var re = /^\w+([\.-]?\w+)*@(((([a-z0-9]{2,})|([a-z0-9][-][a-z0-9]+))[\.][a-z0-9])|([a-z0-9]+[-]?))+[a-z0-9]+\.([a-z]{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i;
        return re.test(email);
      }

      this.send = function(email) {
        $.ajax({
          url: options.path + '/ajax.handler.php',
          type: 'POST',
          dataTypeString: 'json',
          data: {email: email},
          beforeSend: function() {
            button.hide();
            $('.processing', form).removeClass('hidden');
          },
          success: function(data) {
            if (data.status) {
              form.html('<span class="subscribe-success">Спасибо, Вы подписаны на рассылку.</span>');
            } else {
              form.html('<span class="subscribe-error">' + data.data + '</span>');
            }
            console.log(data);
          },
          complete: function() {
            button.show();
            subscriber.val('');
            $('.processing', form).addClass('hidden');
          }
        });
      }

      this.subscribe = function() {
        var email = subscriber.val();
        
        if (!this.validateEmail(email)) {
          alert('Неправильный адрес электронной почты');
        } else {
          this.send(email);
        }  
      }      
    }

    var madmini = new MadMini();
    form.submit(function(e) {
      e.preventDefault();
      madmini.subscribe();
    });
    
  });

})(jQuery);