/**
 * Looks for the HTML5 attribute 'placeholder' on input elements and
 * defines similar behaviour to set default text if the value is empty,
 * clear the text upon focus, and reset the placeholder on blur.
 */

(function($) {
    $.fn.placeholder = function(settings) {

        var config = {'attribute': 'placeholder'}
        if (settings) $.extend(config, settings);

        function set_placeholder()
        {
            var $this = $(this);
            var val = $this.val();
            var placeholder = $this.attr(config.attribute);
            if(!val) {
                $this.val(placeholder);
            }
        }

        function clear_placeholder()
        {
            var $this = $(this);
            var val = $(this).val();
            var placeholder = $this.attr(config.attribute);
            if(val == placeholder) {
                $(this).val('');
            }
        }

        function bind_placeholder()
        {
            set_placeholder.call(this);
            var $this = $(this);
            $this.click(clear_placeholder); 
            $this.blur(set_placeholder); 
        }
     
        this.each(function() {
            $(this).find('input['+config.attribute+']').each(function(){
                var $form = $(this).closest('form');
                var $input = $(this);
                if($form.length) {
                    $form.submit(function(){
                       // Clear any placeholder values that haven't been changed
                       if($input.val() == $input.attr(config.attribute))
                       {
                           $input.val('');
                       }
                    });
                }
                bind_placeholder.apply(this);
            });
        });

        return this;
     
    };      

})(jQuery);

