﻿jQuery.fn.hint = function (options) {

   var defaults = {
      hintClass: 'txtbx-hint',
      blurClass: 'txtbx-blur'
    };

    var settings = $.extend(defaults, options);

    return this.each(function () {
    // get jQuery version of 'this'
    var $input = jQuery(this),

    // capture the rest of the variable to allow for reuse
    title = $input.attr('title'),
    $form = jQuery(this.form),
    $win = jQuery(window);

    function remove() {
        if ($input.val() === title && $input.hasClass(settings.blurClass)) {
            $input.val('').removeClass(settings.blurClass).addClass(settings.hintClass);
        }
    }

    function trim (s) {
        while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
        {
            s = s.substring(1,s.length);
        }
        while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
        {
            s = s.substring(0,s.length-1);
        }
        return s;
    }
    
    // only apply logic if the element has the attribute
    if (title) { 
        // on blur, set value to title attr if text is blank
        $input.blur(function () {
            if (trim(this.value) === '') {
              $input.val(title).addClass(settings.blurClass);
            }
        }).focus(remove).blur(); // now change all inputs to title

      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};
