﻿/**
 * Quick/dirty polyfill for placeholder attribute
 */
BF.placeholder = (function () {

    // private methods
    var isSupported = function () {
        return 'placeholder' in document.createElement('input');
    };

    return {

        init: function (target, options) {
            this.target = $(target);
            this.form = this.target.parent('form');
            this.options = $.extend({
                focusClass: 'focus', // CSS class to set on target on focus
                force: false, // force the input field to use fallback solution? Useful for testing
                placeholderClass: 'placeholder' // CSS class for default (placeholder) styling
            }, options || {});

            // check if we need to fallback from placeholder attribute
            if (!isSupported() || this.options.force === true) {
                // if so call fallback method
                this.fallback();
            }

        },

        fallback: function () {
            var self = this; // scope alias
            // read placeholder attribute, if it exists set the value of the input
            var placeholder = this.target.attr('placeholder');
            if (placeholder) {
                this.target.val(placeholder);
                /**
                * events
                */
                this.target.bind('focus', function (e) {
                    self.setFocus($(this), placeholder);
                });

                this.target.bind('blur', function (e) {
                    self.setBlur($(this), placeholder);
                });

//                this.form.bind('submit', function (e) {
//                    var val = $.trim(self.target.val());
//                    if (val === placeholder) {
//                        self.target.val('');
//                    }
//                });
            }
        },

        // do things on focus
        setFocus: function (el, placeholder) {
            el.addClass(this.options.focusClass);
            if (el.val() === placeholder) {
                el.removeClass(this.options.placeholderClass);
                el.val('');
            }
        },

        // do stuff on blur
        setBlur: function (el, placeholder) {
            var val = el.val();
            el.removeClass(this.options.focusClass);
            if (val === '') {
                el.addClass(this.options.placeholderClass);
                el.val(placeholder);
            }
        }

    };


})();
