(function($) {
    $.ui = $.ui || {};
    $.fn.sticky = function(options) {
        var opts = $.extend({}, $.sticky.defaults, options);
        return this.each(function() {
            var $this = $(this);
            if ($this.hasClass("sticky")) {
                return;
            }
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            $this.addClass("sticky");
            if (o.clazz) {
                $this.addClass(o.clazz+"");
            }
            $this.prepend('<div class="sticky-close"></div>');
            if (o.resizeable) {
                $this.resizable({handles:{se: '.ui-resizable-se'}});
            }
            var ondragstop = o.ondragstop;
            delete o.ondragstop;
            if (o.draggable) {
                $this.draggable({stop:ondragstop});
            }
            var onclosefn = o.onclose;
            delete o.onclose;
            $(".sticky-close",$this).click(function() {
                if (onclosefn) {
                    var r = onclosefn();
                    if (r!=undefined && !r) {
                        return;
                    }
                }
                return $this.remove();
            });
            if( o.draggable ) {
                $this.css({cursor:'move'});
            }
            $this.css(o);
            if (o.fade) {
                $this.fadeTo(o.fade_delay, o.fade_opacity);
            }
        });
    };

    // plugin defaults
    $.sticky = {
        defaults : {
            onclose: null,
            ondragstop: null,
            onresize: null,
            width: '150px',
            height: '100px',
            resizeable: false,
            draggable: true,
            backgroundColor: '#fefe81',
            fade:true,
            fade_delay: 1,
            fade_opacity:0.95
        },
        add : function(o,d) {
            d = d || window.document
            var e = d.createElement("div");
            e.id  = o.id;
            e.innerHTML = o.html;
            d.body.appendChild(e);
            jQuery(e).sticky(o);
        }
    };

})(jQuery);


