(function ($) {

// Creates hint for password inputs
var createPassHint = function($input, hint) {
    var width = $input.width(),
        height = $input.height();
        
    // Don't create if not part of DOM
    if (width === 0 || height === 0) {
        return;
    }

    var $hint = $('<div id="' + $input.attr('id') + 'Hint" class="hint">' + hint + '</div>');
    $hint.width(width)
         .height(height)
         .appendTo('body')
         .click(function(e) {
            $hint.hide();
            $input.focus();
         });
};

$.fn.hint = function (blurClass) {

    if (!blurClass) { 
        blurClass = 'blur';
    }

    return this.each(function () {
        // get jQuery version of 'this'
        var input = this,
            $input = $(input),
            isPass = input.type === 'password' ? true : false,
            title = $input.attr('title'),
            $form = $(this.form),
            $win = $(window);

        if (isPass) {
            createPassHint($input, title);
        }

        function remove() {
            var $passHint = $('#' + $input.attr('id') + 'Hint');
      
            if (isPass && $passHint) { // Hide password hint while typing
                $passHint.hide();
            } else {
                if ($input.val() === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }
        }

        // 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 () {
                var $passHint = $('#' + $input.attr('id') + 'Hint'),
                    offset = $input.offset();

                if (this.value === '') {
                    if (isPass && $passHint) { // Show password hint
                        $passHint.css({
                            'top': offset.top - 5,
                            'left' : offset.left
                        })
                        $passHint.show();
                    } else {
                        $input.val(title).addClass(blurClass);
                        $input.css('color', '');  // clear error color (if any)
                    }
                }
            }).focus(remove).blur(); // now change all inputs to title

            // clear blurClass if exists
            if ($input.val() !== title) {
                $input.removeClass(blurClass);
            }

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

})(jQuery);
