// jQuery inner-label plugin - Brian Lopez <seniorlopez@gmail.com>
// Based on the form-promt plugin
(function($) {
    $.fn.hasInnerLabel = function(text, options) {
        return $(this).each(function() {
            var input = $(this);

            if (input.hasClass('innerLabelApplied'))
              return;
            else
              input.addClass('innerLabelApplied');

            var innerLabelText = '';
            var settings = $.extend({
                className: 'inner-label-text',
                wrapperClassName: 'inner-label-wrapper'
            }, options);
            
            // If text is passed as a callback, evaluate it
            if ($.isFunction(text)) {
              innerLabelText = text.call(this);
            } else {
              innerLabelText = text == null ? input.attr('title') : text;
            }
            
            // Use native placeholder attribute in Safari/Chrome
            if ($.browser.webkit) {
                input.attr('placeholder', innerLabelText);
                return;
            }
            
            var inputPosition = input.position();
            var innerLabel = $("<div class='" + settings.className + " " + input.attr('data-size') + "'>" + innerLabelText + "</div>")
              .css({
                "position": "absolute",
                "left": inputPosition.left,
                "top": inputPosition.top,
                "z-index": 99999
              });
            input.after(innerLabel);
            
            if (input.val() != '') {
                innerLabel.hide();
            }
 
            var selectInput = function() {
                innerLabel.hide();
                input.focus();
            };
            input.bind('click keyup', selectInput);
            innerLabel.click(selectInput);
            input.focus(function() {
              innerLabel.hide();
            });
            
            input.blur(function() {
                if (input.val() == '') {
                    inputPosition = input.position();
                    innerLabel.css({top: inputPosition.top, left: inputPosition.left});
                    innerLabel.show();
                }
            });
        });
    };
    
    // Globally apply inner-labels to input fields with 'has-inner-label' class
    $.applyInnerLabels = function(selector) {
        $(selector || '.has-inner-label').hasInnerLabel();
    };
    
    // backward compatibility
    $.fn.form_prompt = $.fn.hasInnerLabel;
})(jQuery);
