﻿var headers = new Array();
var SCROLL_MARGIN = 70;
var MENU_MARGIN = 10;

function setupMenu() {
    setupMenu('linear');
}

function setupMenu(easing) {
    var menubg = $(".menubg");
    var item = $(".menu li");

    if (item.length == 0) return;

    menubg.width(item.outerWidth(false));
    menubg.height(item.outerHeight(false));
    headers = $(":not(.M):not(.N) > a[name*=menu]");

    scrollMenu();

    $("li:not(.static) > a[href*='#menu']").click(transferTo);
    $("a.slink").click(transferTo);
}

function transferTo(event) {
    event.preventDefault();
    $('html, body').animate({ scrollTop: $("a[name='" + $(this).attr("href").substring(1) + "']").offset().top - SCROLL_MARGIN + 5 }, 'slow', easing, null);
    $(this).blur();
}

function scrollMenu() {
    scrollMenu('linear');
}

function scrollMenu(easing) {
    var content = $(".content");
    var menu = $(".menu");
    var menubg = $(".menubg");

    if (menu.length == 0 || headers.length == 0) return;

    if ($(document).scrollTop() < content.offset().top && menu.position().top <= 10) return;

    var at = { index: 0, top: 0, bottom: 0 };
    headers.each(function (i) {
        if (at.index == i - 1) at.bottom = $(this).offset().top;
        if ($(document).scrollTop() >= $(this).offset().top - SCROLL_MARGIN) {
            at.index = i;
            at.top = $(this).position().top;
        }
    });

    var t = 10;
    if ($(document).scrollTop() > content.offset().top)
        t = $(document).scrollTop() - (content.offset().top - content.position().top) + 9;

    var height = $(".menu li").outerHeight(false);
    var bg = t + height * at.index;

    menu.stop(true, true);
    menubg.stop(true, true);

    menu.fadeTo('fast', 0.2, null);
    menubg.fadeTo('fast', 0.2, null);
    menu.animate({ 'top': t }, 'slow', easing, function () {
        menu.fadeTo('fast', 1.0, null);
    });
    menubg.animate({ top: bg }, 'slow', easing, function () {
        menubg.fadeTo('fast', 1.0, null);
    });
}
