(function($) {
  
  function checkEmail(email) {
    var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var emailVal = $('#' + email).val();
    return pattern.test(emailVal);
  }
  
  // =============================
  // ===== WHEN DOM IS READY =====
  // =============================
  $(function() {
    // ===== jQuery Tools: Overlay =====
    // if the function argument is given to overlay, it is assumed to be the onBeforeLoad event listener
    $('a[rel=#overlogin], a[rel=#oversignup]').overlay(function() {
      // grab wrapper element inside content
      var wrap = this.getContent().find('div.wrap');
      // load only for the first time it is opened
      if (wrap.is(':empty'))
        wrap.load(this.getTrigger().attr('href'));
    });
  });
  
  
  // ==================================
  // ===== CAMPAIGN MONITOR FORMS =====
  // ==================================
  $('#invitation_form, #news_form').livequery('submit', function(event) {
    event.preventDefault();
    
    var form = $(this);
    var action = form.attr('action');
    var parameters = form.serialize();
    var query = parameters + '&action=' + action;
    
    // Hack together id for email field
    var pattern = /\/([^\/]+)\/$/;
    var matches = pattern.exec(action);
    var emailId = matches[1];
    emailId = emailId + '-' + emailId;

    // Validate email address with regex
    if (!checkEmail(emailId)) {
      var error_field = form.find('.error_message');
      error_field.html('Please enter a valid email address');
      error_field.slideDown('slow');
      return false;
    }

    // Submit the form via ajax
    $.ajax({
      url: 'proxy.php',
      type: 'POST',
      data: query,
      success: function(html) {
        form.find('.error_message, label, :input, :submit').hide(); // If successfully submitted hides the form
        var success_field = form.find('.success_message');
        success_field.html('Thanks for subscribing!');
        success_field.slideDown('slow');
      }
    });
    
    return false;
  });
  
})(jQuery);
