﻿(function($) {
    // plugin definition
    $.fn.overlabel = function(options) {
        // build main options before element iteration
        var opts = $.extend({}, $.fn.overlabel.defaults, options);
        var selection = this.filter('label[for]').map(function() {
            var label = $(this);
            var id = label.attr('for');
            var field = document.getElementById(id);
            if (!field) return;

            // build element specific options
            var o = $.meta ? $.extend({}, opts, label.data()) : opts;

            label.addClass(o.label_class);

            var hide_label = function() { label.hide(); label._shown = 0; };
            var show_label = function() { if (!this.value && label._shown != 1) { label.fadeIn('fast'); label._shown = 1; } };

            // Set positioning and styling to match
            //label.height($(field).height());
            var p = $(field).position();
            label.css({ 'top': p.top + 'px', 'left': p.left + 'px',
                'padding-top': parseInt($(field).css("padding-top")) + 'px',
                'padding-left': (parseInt($(field).css("padding-left")) + 2) + 'px',
                'font-family': $(field).css("font-family"),
                'font-size': $(field).css("font-size") });
            // Attach events
            $(field).focus(hide_label).blur(show_label).each(hide_label).each(show_label);

            return this;

        });

        return opts.filter ? selection : selection.end();
    };

    // publicly accessible defaults
    $.fn.overlabel.defaults = {
        label_class: 'cms-label-dynamic',
        hide_css: { 'text-indent': '-10000px' },
    show_css: { 'text-indent': '0px', 'cursor': 'text' },
        filter: false
    };
})(jQuery);