/*
* Javascript Validation CakePHP Helper
* Copyright (c) 2008 Matt Curry
* www.PseudoCoder.com
* http://github.com/mcurry/cakephp/tree/master/helpers/validation
* http://sandbox2.pseudocoder.com/demo/validation
*
* @author mattc <matt@pseudocoder.com>
* @license MIT
*
*/

function validateForm(form, rules, options) {
  var errors = false;

  if (options['messageId'] && jQuery.trim(jQuery("#" + options['messageId']).html()) != "" ) {
    jQuery("#" + options['messageId']).slideUp().html("");
  }

  jQuery(".error-message").hide();
  jQuery("input").removeClass("form-error");
  jQuery("div").removeClass("error");

  //loop through the validation rules and check for errors
  jQuery.each(rules, function(field) {
    var val = jQuery.trim(jQuery("#" + field).val());

    jQuery.each(this, function() {
      //check if the input exists
      if (jQuery("#" + field).attr("id") != undefined) {
        var valid = true;

        if (this['allowEmpty'] && val == '') {
          //do nothing
        } else if (this['rule'].match(/^range/)) {
          var range = this['rule'].split('|');
          if (val < parseInt(range[1])) {
            valid = false;
          }
          if (val > parseInt(range[2])) {
            valid = false;
          }
        } else if (this['negate']) {
          if (val.match(eval(this['rule']))) {
            valid = false;
          }
        } else if (!val.match(eval(this['rule']))) {
          valid = false;
        }

        if (!valid) {
          errors = true;

          //add the error message
          if(options['messageId']) {
            jQuery("#" + options['messageId']).append("<p>" + this['message'] + "</p>");
          }

          //add the form-error class to the input
          jQuery("#" + field).addClass("form-error");
          jQuery("#" + field).parents("div:first").addClass("error");
          jQuery("#" + field).after('<div class="error-message">' + this['message'] + '</div>');

          if (this['last'] === true) {
            return false;
          }
        }
      }
    });
  });

  if(options['messageId']) {
    if(jQuery.trim(jQuery("#" + options['messageId']).html()) != "") {
      jQuery("#" + options['messageId']).wrapInner("<div class='error'></div>");
      jQuery("#" + options['messageId']).slideDown();
    }
  }

  if(errors) {
    return false;
  } else {
    return true;
  }
}