﻿(function ($) {

    $.fn.userMenu = function (options) {

        var defaults = {};

        var options = $.extend(defaults, options);

        return this.each(function () {
            this.userMenu = new UserMenu(this, options);
        });
    };

    $.fn.extend({
        getUserMenu: function () {
            return this[0].userMenu;
        }
    });

    function UserMenu(element, options) {
        this.element = element;
        this.target = $(element);
        this.options = options;
        this.offset = options.offset;
        this.downSpeed = options.downSpeed;
        this.upSpeed = options.upSpeed;
        this.fadeSpeed = options.fadeSpeed;
        this.isOpened = false;
        setTimeout("$('#" + element.id + "').getUserMenu().init();", 25);
    }

    UserMenu.prototype.init = function () {
        var self = this;
        this.startTop = this.target.offset().top;
        this.startHeight = this.target.height();

        this.target.mouseover(function () {
            self.open();
        });

        this.target.mouseleave(function () {
            self.close();
        });

        /*
        $(window).scroll(function () {
            if ($(window).scrollTop() >= self.startTop + self.startHeight) {
                self.target.css("position", "fixed");
                self.target.css("top", -self.target.height());
            }
            else {
                self.target.css("position", "relative");
                self.target.css("top", -(self.target.height() + self.offset) + "px");
            }
        });
        */
    };

    UserMenu.prototype.open = function (callback) {
        if (this.isOpened) return;
        var self = this;
        var tab = $("#user-menu-tab", this.target);
        tab.stop();
        tab.animate({ opacity: 1 }, this.fadeSpeed);

        this.target.stop();
        this.target.animate({ top: 0 }, this.downSpeed, function () { self.isOpened = true; if (callback) callback(); });
    }

    UserMenu.prototype.close = function (callback) {
        if (!this.isOpened) return;
        var self = this;
        var tab = $("#user-menu-tab");
        tab.stop();
        tab.animate({ opacity: 0.85 }, this.fadeSpeed * 2);

        this.target.stop();
        this.target.delay(175).animate({ top: -this.target.height() - this.offset }, this.upSpeed, function () { self.isOpened = false; if (callback) callback(); });
    }

})(jQuery);

$(function() {
    $("#user-menu").userMenu({ offset: 5, downSpeed: 175, upSpeed: 350, fadeSpeed: 175});
});

