(function ($) {
  $.fn.liveCheck = function (options) {
    var defaults = { 'error' : 'error', 'image' : '', 'text' : 'validating...', 'ok' : 'ok', 'message' : 'message' };
    var settings = $.extend({}, options, defaults);
    return this.each(function () {
      var $$ = $(this);
      var t = this;
      
      var form = $$.parents('form:first');
      var url = form.attr('action');
      var type = form.attr('method');
      
      var infospan = $$.next();
      if (!infospan.is('span')) {
        infospan = $$.after(' <span></span>').next();
      }
        
      $$.keyup(function () {
        // prevent tabbing in to the field firing an ajax hit
        if (t.value == '' && (t.lastValue == undefined)) return true;
        
        if (t.value != t.lastValue) {
          if (this.timer) clearTimeout(this.timer);
          infospan.removeClass(settings.error).html((settings.image ? '<img src="' + settings.image + '" /> ' : '') + settings.text);
          this.timer = setTimeout(function () {
            $.ajax({
              url: url,
              type: type,
              data: t.name + '=' + t.value,
              dataType: 'json',
              success: function (j) {
                infospan.toggleClassIf(!j[settings.ok], settings.error).html(j[settings.message]);
              }
            });
          }, 200);
          t.lastValue = t.value;
        }
      });
    });
  };
  
  $.fn.toggleClassIf = function (v, c) {
    return v ? this.addClass(c) : this.removeClass(c);
  };
})(jQuery);

