// Some utility functions

String.prototype.trimLeft = function(s) {
  if (!s) s = this;
  return s.charAt(0).isSpace() && s.length > 0 ? this.trimLeft(s.slice(1)) : s;
}

String.prototype.trimRight = function(s) {
  if (!s) s = this;
  return s.charAt(s.length - 1).isSpace() && s.length > 0 ? this.trimRight(s.slice(0, s.length - 1)) : s;
}

String.prototype.trim = function() {
  return this.trimLeft().trimRight();
}

String.prototype.isSpace = function() {
  var spaceChars = [" ", "\n", "\t"];

  for (var i = 0; i < spaceChars.length; i++) {
    if (this.charAt(0) == spaceChars[i]) return true;
  }
}

// You can only validate one form per page with this object.

Validator = {

  "cleanup" : null,

  "setCleanup" : function(cleanupFunc) {
    this.cleanup = cleanupFunc;
  },

  "rules" : [],

  "addRule" : function(ruleFunc, messageOnError) {
    this.rules.push({
      "rule"    : ruleFunc,
      "error"   : messageOnError});
  },

  "check" : function() {
    var isOK = true;
    var errorMessage = "Error: \n\n";
  
    for (var i = 0; i < this.rules.length; i++) {
      if (!this.rules[i].rule()) {
        isOK = false;
        errorMessage += " - " + this.rules[i].error + "\n";
      }
    }

    if (isOK) {
      return true;
    }
    else {
      alert(errorMessage);
      this.cleanup();
      return false;
    }
  }
}

// Some sitewide behaviours

var siteRules = {
  "input.back_button" : function(el) {
    el.onclick = function() {
      history.go(-1);
    }
  }
};

Behaviour.register(siteRules);

