jQuery(document).ready(function($){
  var rules = { 
    email : {
      check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; },
      msg : "please enter a valid e-mail address"
    },
    url : {
      check : function(value) { if(value) return testPattern(value,"([A-Za-z]+://)*[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+"); return true; },
      msg : "please enter a valid URL"
    },
    required : {
      check: function(value) { if(value) return true; else return false; },
      msg : "required"
    },
    human : {
      check: function(value) { if(value) return (value == 'hot' || value == 'Hot'); return true; },
      msg : "wrong answer"
    }
    
  }
  
  var testPattern = function(value, pattern) {
    var regExp = new RegExp("^"+pattern+"$","");
    return regExp.test(value);
  }

  $("#contactform #submit").click(function() { // run the function when contactform is submitted.
    var form = $("#contactform");
    var errors = false;
    
    // 1. cycle through each input and textarea form element:
    form.find("input[class], textarea[class]").each(function() {
      classes = $(this).attr("class").split(" ");
      inputelement = $(this);
     
      // 1.1 cycle through each class assigned to the element:
      var keepgoing = true;
      jQuery.each(classes, function(i, val) {  
           
        if(keepgoing && (rule = rules[val])) { // if a rule exists for the particular class
          var message_element = $(inputelement.prev("span"));        
          message_element = $(message_element[0]);
          if(!rule.check(inputelement.val())){ // if fail check
            message_element.hide(); 
            message_element.html(rule.msg).fadeIn("slow"); // enter the msg text into the inputs span sibling ...
            message_element.focus();
            keepgoing = false; // ... and don't check any more classes. 
          } 
          else {
            message_element.empty(); // remove the error message 
          }
        }
      });
      if (!keepgoing) { errors = true; }
    });
    var msg = $("#error_message"); 
    if (errors) {      
      msg.hide().text('Yikes, there something up. Please check the details you entered and try again.').addClass("vis").fadeIn("slow");
      return false;
    }
    else {
      if(msg.text()){ // if there was an error from before
        msg.fadeOut("slow", function(){msg.show(); msg.empty().removeClass("vis"); } );
      }
       
      // Do the client side processing - php script will figure out which part to execute from ajax header.
      $.ajax({
          data: form.serialize(),
          dataType: 'json',
          type: 'post',
          success: function (j) {
              if(j.ok){
                var canvas = $(".entry-content");
                canvas.fadeOut("fast", function(){canvas.html("<p>"+j.msg+"</p>");})
                canvas.fadeIn("slow");
                pageTracker._trackEvent("Forms", "Enquiry", "Receive Offers", $('input[name=offers]').is(':checked')+0); /* Register Google Analytics event. */
              }
              else{
                // put a message in the error box.
                msg.hide().text(j.msg).addClass("vis").fadeIn("slow");
              }
          }
      });
      return false;
    }
  });
}); // end of jQuery container.
