﻿$(document).ready(function() {
    $("#FRAME_LOADING").hide();
    $.getJSON("script/Menu.json", onDataLoaded);
});
function onDataLoaded(data) {
    generateMenu(data);
    $(".menu-item").fadeIn(1500);
    selectUrlToLoad(data);
}
function selectUrlToLoad(data) {
    var hash = window.location.hash.split("#");
    if (hash[1]) {
        for (i = 0; i < data.MenuItems.length; i++) {
            if (data.MenuItems[i].Title.replace(" ", "--") == hash[1]) {
                loadUrl(data.MenuItems[i]);
            }
        }
    } else {
        loadUrl(data.MenuItems[0]);
    }
}
function generateMenu(data) {
    for (i = 1; i < data.MenuItems.length; i++) {
        createMenuItem(data.MenuItems[i]);
    }
}
function createMenuItem(jsonItem) {
    var item = $(document.createElement('a'));
    item.addClass("menu-item");
    item.text(jsonItem.Title);
    item.hide();
    $("#FRAME_MENU").append(item);
    createMenuItemLink(jsonItem, item);
}
function createMenuItemLink(jsonItem, item) {
    if (jsonItem.IncludeInPage) {
        item.attr("href", "#" + jsonItem.Title.replace(" ", "--"));
        item.click(function() {
            loadUrl(jsonItem);
        });
    } else {
        item.attr("href", jsonItem.Target);
    }
}
function loadUrl(jsonItem) {
    $("a.menu-item-selected").removeClass("menu-item-selected");
    $("a:[href$='" + jsonItem.Title.replace(" ", "--") + "']").addClass("menu-item-selected");

    $("#FRAME_CONTENT").empty().load(jsonItem.Target, function() {
        hideLoadingAnimation();
    });
    showLoadingAnimation();
}
function showLoadingAnimation() {
    var animation = $("#FRAME_LOADING");
    var loaderWidth = animation.width();
    var placeholder = $("#FRAME_CONTENT");
    var pos = placeholder.offset();
    var width = placeholder.width();
    animation.css({ "left": (pos.left + (width / 2) - (loaderWidth / 2)) + "px", "top": pos.top + 90 + "px" });
    animation.fadeIn();
}
function hideLoadingAnimation() {
    $("#FRAME_LOADING").fadeOut();
}
     
