/**
 * HTML5 placeholder support.
 *
 * @author Nikita Vershinin <me@endeveit.net>
 */
(function($) {
    $.html5Placeholder = function(settings) {
        settings = $.extend({
            // Class to be added when the placeholder text appears
            className: 'placeholded'
        }, settings || {});

        var
            inputSupport    = ('placeholder' in document.createElement('input')),
            textareaSupport = ('placeholder' in document.createElement('textarea'));

        if (!inputSupport || !textareaSupport) {
            $('input[placeholder], textarea[placeholder]').each(function () {
                var
                    placeholdText = $(this).attr('placeholder'),
                    currentText   = $(this).val();

                $(this).bind('focus', function() {
                    var o = $(this);
                    o.removeClass(settings.className);

                    if (o.val() == placeholdText) {
                        o.val('');
                    }
                }).bind('blur', function() {
                    var o = $(this);

                    if (o.val() == '' || o.val() == placeholdText) {
                        o.val(placeholdText).addClass(settings.className);
                    }
                }).addClass(settings.className);

                // Init field value
                $(this).val(
                    currentText == placeholdText || currentText == ''
                        ? placeholdText
                        : $(this).val()
                );

                // Process form submit
                $(this).parents('form:first').submit(function() {
                    $('input[placeholder], textarea[placeholder]', this).each(function() {
                        if ($(this).val() == $(this).attr('placeholder')) {
                            $(this).val('');
                        }
                    });

                    return true;
                });
            });
        }
    };
})(jQuery);
