﻿(function($) {
    $.fn.labelize = function() {
        return this.each(function() {

            var $input = $(this);
            var $label = $('label[for=' + $input.attr('id') + ']');

            if (!$input.val()) {
                $input.val($label.text());
            }
            if ($input.val() == $label.text()) {
                $input.addClass('labelized');
            }

            //We need to know if input is of type password.
            if ($input.attr('type') == 'password') {
                $input = changeInputType($input, 'text');
                $input.addClass('password');
            }

            $input.focus(function() {
                if ($input.val() == $label.text()) {
                    $input.val('').removeClass('labelized');
                    if ($input.hasClass('password')) {
                        $input = changeInputType($input, 'password');
                        $input.focus();
                    }
                    
                }
            });
            $input.blur(function() {
                if (!$input.val()) {
                    $input.addClass('labelized');
                    $input.val($label.text());
                }
                else {
                    $input.removeClass('labelized');
                }
            });
            //}
        });
        function changeInputType($input, value) {
            //Manipulation of input type attribute is not allowed. Therefore we need to replace the input box.
            var $new = $('<input type="' + value + '" />')
            $new.val($input.val()).attr('class', $input.attr('class')).attr('id', $input.attr('id')).attr('name', $input.attr('name'));
            $input.replaceWith($new);
            return $new;
        }
    }
})(jQuery);
