// hitolog Textbox Extends

(function($) {
  $.fn.hitologTextboxExtends = function(data, options) {
    return new HitologTexboxExtends(data, options);
  };

  $.fn.hitologTextboxExtends = function(options) {
    this.each(function() { new HitologTextboxExtends(this, options); });
  };

  // constructor
  function HitologTextboxExtends(obj, options) {
    var defaults = {
      label: "Enter text here",
      focusOnClass: "focusOn",
      focusOffClass: "focusOff",
      maxLength: 0,
      counterId: "textboxCounter",
      text: ""
    };
    var options = $.extend(defaults, options);

    this.oBaseElm = $(obj);
    this.options = options;
    this.initialize();
  }

  // class implementation
  HitologTextboxExtends.prototype = {
    initialize: function() {
      var self = this;

      // elements
      this.oBaseElm
      .focus(function() {
        self.setFocus(true);
      })
      .blur(function() {
        self.setFocus(false);
      });
      if (this.options.focusOffClass) {
        this.oBaseElm.addClass(this.options.focusOffClass);
      }
      this.oBaseElm.parents("form").submit(function() {
        if (self.oBaseElm.val() == self.options.label) {
          self.oBaseElm.val("");
        }
      });
      this.oCounter = $("#" + this.options.counterId);
      this.oBaseElm.keyup(function() { self.calcLength(); });
      this.oBaseElm.change(function() { self.calcLength(); });
      this.oBaseElm.val(this.options.text || this.options.label);
      this.calcLength();
      this.setFocus(false);
      $("body").focus();
    },
    setFocus: function(focus) {
      if (focus) {
        if (this.oBaseElm.val() == this.options.label) {
          this.oBaseElm.val("");
        }
      } else {
        if (this.oBaseElm.val() == "") {
          this.oBaseElm.val(this.options.label);
        }
      }
      if (this.oBaseElm.val() == this.options.label) {
        this.oBaseElm.removeClass(this.options.focusOnClass);
        this.oBaseElm.addClass(this.options.focusOffClass);
      } else {
        this.oBaseElm.addClass(this.options.focusOnClass);
        this.oBaseElm.removeClass(this.options.focusOffClass);
      }
    },
    calcLength: function() {
      if (this.options.maxLength > 0 && this.oCounter) {
        var text = this.oBaseElm.val() == this.options.label ? "" : this.oBaseElm.val();
        var limit = this.options.maxLength - text.length;
        limit = limit > 0 ? limit : 0;
        this.oCounter.text(limit);
      }
    }
  }

})(jQuery);

