(function(global, doc, $) {

global.gup = global.gup || {};

var oldInit = gup.init;

gup.init = function() {
    var navi = new gup.NaviManager();
    navi.init();

    var lightbox = new gup.Lightbox();

    if(oldInit) {
        oldInit();
    }
};


gup.NaviManager = function(options) {
    $.extend(this.settings, options || {});
    
    this.lists = $(this.settings.listSelector);
};
gup.NaviManager.prototype = {
    settings: {
        listSelector: ".navigation-list"
    },
    init: function() {
        var me = this;
        this.lists.find("li").each(function() {
            me.makeFlyout($(this));
        });
    },
    makeFlyout: function(listItem) {
        var subnav = listItem.children("ul"),
            me = this;
        if(subnav.length) {
            new gup.FlyoutNavi(listItem);

            subnav.find("li").each(function() {
                me.makeFlyout($(this));
            });
        }
    }
};

gup.FlyoutNavi = function(item) {
    this.item = item;
    this.subnav = this.item.children("ul");

    this.hideTimeout = null;

    this.attachListeners();
};
gup.FlyoutNavi.prototype = {
    attachListeners: function() {
        var me = this;
        this.item.hover(
            function() {
                me.showSubnav();
            },
            function() {
                me.hideSubnav();
            }
        );
    },
    showSubnav: function() {
        this.subnav.show();

        clearTimeout(this.hideTimeout);
    },
    hideSubnav: function() {
        var me = this;
        this.hideTimeout = setTimeout(function() {
            me.subnav.hide();
        }, 200);
        
    }
};



gup.Lightbox = function() {
    var self = this;

    this.box = $("#lightbox");
    this.overlay = $("#overlay");

    this.box.find("#lightbox-close").bind("click", function(e) {
        self.close();
    });
    this.overlay.bind("click", function(e) {
        self.close();
    });

    if(this.shouldOpen()) {
        this.open(false);
    }
};
gup.Lightbox.prototype = {
    animDuration: 500,
    shouldOpen: function() {
        return location.hash.indexOf("lightbox") != -1;
    },
    open: function(animated) {
        this.overlay.css({
            height: $(doc).height() + "px"
        });
        if(animated) {
            this.box.fadeIn(this.animDuration);
            this.overlay.fadeIn(this.animDuration);
        }
        else {
            this.box.css({
                display: "block"
            });
            this.overlay.css({
                display: "block"
            });
        }
    },
    close: function() {
        this.box.fadeOut(this.animDuration);
        this.overlay.fadeOut(this.animDuration);
    }
};


$(doc).ready(gup.init);

})(this, this.document, this.jQuery);
