﻿/*
* Description (jQuery Plugin) v0.1.0
*
* Copyright 2010, de Groot Software
* Date: 11 september 2010
*
* Last update: 11 november 2010
*/

(function ($) {
    $.fn.description = function (options) {
        // build main options before element iteration
        var settings = $.extend({}, $.fn.description.defaults, options);

        // iterate and reformat each matched element
        return this.each(function () {
            var $this = $(this);

            // store the description in the input
            $this.data("description", settings.text);

            // set the first parent div to relative to calculate the position from
            $this.parents("div:first").css({ position: "relative" });

            // calculate position
            var marginTop = parseInt($this.css("margin-top"));
            var marginLeft = parseInt($this.css("margin-left"));
            var top = $this.position().top + ($this.outerHeight() - $this.height()) / 2 + (marginTop > 0 ? marginTop - 1 : 0);
            var left = $this.position().left + ($this.outerWidth() - $this.width()) / 2 + (marginLeft > 0 ? marginLeft - 1 : 0);

            // setup the div which is going to cover the input
            $("<div />").attr("id", $this.attr("id") + "-description")
                        .attr("class", "description")
                        .css({
                            position: "absolute",
                            top: top - 7,
                            left: left,
                            paddingTop: parseInt($this.css("padding-top")),
                            paddingRight: $this.css("padding-right"),
                            paddingBottom: $this.css("padding-bottom"),
                            paddingLeft: $this.css("padding-left"),
                            backgroundColor: "transparent",
                            display: "none"
                        })
                        .text($this.data("description"))
                        .insertAfter($this);


            var $description = $("#" + $this.attr("id") + "-description");

            // show the description if the input is empty
            if ($this.val() == "")
                $description.show();

            $description.click(function () {
                $description.hide();
                $this.focus();
            });

            $this.focus(function (e) {
                // in the case that the input "magically" got focus
                $description.hide();
            }).blur(function () {
                // fill the input with its description if its empty on blur
                if ($this.val() == "")
                    $description.show();
            });
        });
    };

    // defaults
    $.fn.description.defaults = {
        text: "No description entered ...",
        descriptionClass: "description"
    };
})(jQuery);
