﻿var sizingRatio;
var defaultTitle;

$(document).ready(function () {
    //init the scrollbar
    $("#scrollbar").tinyscrollbar();

    $("#backgroundImages img:first").show();

    defaultTitle = $("title").html();

    //every menu item click
    $("ul#menu li a").click(function () {
        var sectionUrl = $(this).attr("href");
        var section = $(this).data("section");

        showSection(sectionUrl, section);

        return false;
    });

    $("ul#menu li a").hover(function () {
        $(this).animate({
            paddingRight: "+=4px",
            paddingLeft: "+=3px"
        }, 70);
    }, function () {
        $(this).animate({
            paddingRight: "-=4px",
            paddingLeft: "-=3px"
        }, 70);
    });

    $("#closeContentWindow").click(function () {
        if ($(this).hasClass("active")) {
            hideSection();
        }
        else {
            $("ul#menu li:first a").click();
        }
    });

    $("#loadingMainContainer").stop().animate({ "width": "10%" }, "slow");

    var mainImagesLoadedCount = 0;

    //for each MainImage in the page
    $("#backgroundImages img").each(function (idx) {
        if (idx == 0) {
            //bind load event (when the image finished loading)
            $(this).load(function () {
                mainImagesLoadedCount++;

                var percentCompleted = (mainImagesLoadedCount / $("#backgroundImages img:first").length);
                var loadingWidth = 260 * percentCompleted; // 260 is the loading image full width

                $("#loadingMainContainer").stop().animate({ "width": loadingWidth + "px" }, function () {
                    //if all main images have been loaded
                    if (mainImagesLoadedCount == $("#backgroundImages img:first").length) {
                        //fit all content to the window
                        fitContentToWindow(false);

                        //show the main div
                        $("#loadingBlock").hide();
                        $("#main").show();

                        RotateImages();

                        ShowInitialSection();
                    }
                });
            });
        }

        //set the url source of the image
        var imageSrc = $(this).attr("data-src");
        $(this).attr("src", imageSrc);
    });

    $(window).resize(function () {
        fitContentToWindow(true);
    });

    //if the user click ESC
    $(document).keydown(function (event) {
        if (event.keyCode == 27) {
            if ($(".ui-dialog:visible").length == 0) {
                hideSection();
            }
            else {
                closeDialog();
            }
        }
    });

    $("#backgroundImages,#main #logo").click(function () {
        hideSection();
    });

    $("#youtubeLink").click(function () {
        window.open('http://www.youtube.com/user/tzilumpirsum1');
    });

    $("#facebookLink").click(function () {
        window.open('https://www.facebook.com/tzilumpirsum');
    });

    var backgroundImageIndex = 0;

    function RotateImages() {
        //rotate the main images
        window.setInterval(function () {
            if ($(".ui-dialog:visible").length == 0) {
                var currentVisibleMainImage = $("#backgroundImages img:visible");

                backgroundImageIndex++;
                if (backgroundImageIndex > $("#backgroundImages img").length - 1) {
                    backgroundImageIndex = 0;
                }

                $("#backgroundImages img:eq(" + backgroundImageIndex + ")").stop(true, true).fadeIn(1000);
                currentVisibleMainImage.stop(true, true).fadeOut(1000);
            }
        }, 10000);
    }
});

function ShowInitialSection() {
    //check if there is initial section specified in the QueryString
    var initialSectionUrl = getQuerystring("sec");
    if (initialSectionUrl != "") {
        var sectionItem = $("ul#menu a[href='" + initialSectionUrl + "']");
        if (sectionItem.length > 0) {
            var section = sectionItem.data("section");
            showSection(initialSectionUrl, section);
        }
    }
}

function setContentWidth() {
    //resize all the elements inside the ContentContainer with fixed width-height, according to the ratio
    $("#main #contentContainer [data-width], #main #contentContainer [data-height]").each(function () {
        if ($(this).attr("data-width") != "") {
            var width = parseInt($(this).attr("data-width"));
            $(this).css("width", (width * sizingRatio) + "px");
        }
        if ($(this).attr("data-height") != "") {
            var height = parseInt($(this).attr("data-height"));
            $(this).css("height", (height * sizingRatio) + "px");
        }

        if ($(this).attr("data-top") != "") {
            var top = parseInt($(this).attr("data-top"));
            $(this).css("top", (top * sizingRatio) + "px");
        }
        if ($(this).attr("data-left") != "") {
            var left = parseInt($(this).attr("data-left"));
            $(this).css("left", (left * sizingRatio) + "px");
        }
    });

    //resize all the elements inside the ContentContainer with fixed MAX width-height, according to the ratio
    $("#main #contentContainer [data-maxwidth], #main #contentContainer [data-maxheight]").each(function () {
        if ($(this).attr("data-maxwidth") != "") {
            var width = parseInt($(this).attr("data-maxwidth"));
            $(this).css("maxWidth", (width * sizingRatio) + "px");
        }

        if ($(this).attr("data-maxheight") != "") {
            var height = parseInt($(this).attr("data-maxheight"));
            $(this).css("maxHeight", (height * sizingRatio) + "px");
        }
    });

    //resize the font size (according to the sizing ratio)
    var newFontsize = (parseFloat(sizingRatio * 1.48).toFixed(2));
    $("#main #contentContainer #content").css("fontSize", newFontsize + "em");
}

function showSection(url, section) {
    $("#main #contentContainer").attr("data-section", section);

    var windowWidth = $(window).width();
    var contentContainerWidth = 0.33 * windowWidth;

    $("#main #contentContainer").show();
    $("#main #contentContainer").animate({ width: contentContainerWidth + "px" }, 200, function () {
        $("#main #scrollbarContent").html("<div class='loadingImage'></div>");

        $("#menuContainer #closeContentWindow").addClass("active");
        $("#menuContainer #closeContentWindow img").attr("src", pathPrefix + "Content/images/closeIcon.png");

        //Invoke AJAX method to get this selected page from server
        $.get(url, null, function (result) {
            $("#main #scrollbarContent").html(result);

            fitContentToWindow(false);

            window.setTimeout(function () {
                $("#scrollbar").tinyscrollbar_update();
            }, 100);

            //define relevant page title
            var stateTitle = defaultTitle;
            if (stateTitle.indexOf(" -") >= 0) {
                stateTitle = stateTitle.substring(0, stateTitle.indexOf(" -"));
            }
            var sectionItem = $("ul#menu a[href='" + url + "']");
            if (sectionItem != null) {
                var sectionTitle = sectionItem.html();
                if (sectionTitle != "") {
                    stateTitle += " - " + sectionTitle;
                }
            }

            //push this state to history
            History.pushState({ "section": section, "url": url }, stateTitle, "?sec=" + url);
        }, "html");
    });

    //highlight the relevant menu item
    $("ul#menu li a.selected").removeClass("selected");
    $("ul#menu li a[href='" + url + "']").addClass("selected");
}

function hideSection() {
    if ($("#main #contentContainer:visible").length == 1) {
        $("#main #scrollbarContent").html("");
        $("#main #contentContainer").animate({ width: "0px" }, function () { $(this).hide(); });
        $("#main #contentContainer").attr("data-section", "");

        $("#menuContainer #closeContentWindow").removeClass("active");
        $("#menuContainer #closeContentWindow img").attr("src", pathPrefix + "Content/images/openIcon.png");

        //un highlight the relevant menu item
        $("ul#menu li a.selected").removeClass("selected");

        //push blank state to history
        window.setTimeout(function () {
            History.pushState({ "section": null, "url": null }, defaultTitle, pathPrefix);
        }, 100);
    }
}

function fitContentToWindow(resizing) {
    var windowHeight = $(this).height();
    var windowWidth = $(this).width();
    var imageHeight = 1280;
    var imageWidth = 1920;

    //calculate the difference in width and height
    var heightDiff = parseFloat(windowHeight) / parseFloat(imageHeight);
    var widthDiff = parseFloat(windowWidth) / parseFloat(imageWidth);

    var marginLeft = 0;
    var marginTop = 0;

    //check what is the max (width or height)
    if (heightDiff > widthDiff) {
        sizingRatio = heightDiff;
    }
    else {
        sizingRatio = widthDiff;
    }

    imageHeight = imageHeight * sizingRatio;
    imageWidth = imageWidth * sizingRatio;

    marginLeft = (imageWidth - windowWidth) / 2;
    marginTop = (imageHeight - windowHeight) / 2;

    if ((imageWidth > 1024 && imageHeight > 768) || resizing == false) {
        var mainImages = $("#backgroundImages img");
        mainImages.css("width", imageWidth + "px").css("height", imageHeight + "px");
        mainImages.css("marginTop", "-" + marginTop + "px");
        mainImages.css("marginLeft", "-" + marginLeft + "px");

        //resize the logo according to the sizingRatio
        $("#main #logo,#main #facebookLink,#main #youtubeLink").each(function () {
            var logoWidth = parseInt($(this).attr("data-width"));
            var logoHeight = parseInt($(this).attr("data-height"));
            $(this).css("width", (logoWidth * sizingRatio) + "px");
            $(this).css("height", (logoHeight * sizingRatio) + "px");
        });

        setContentWidth();
    }

    //set the window height to MainElements
    $("#mainElements").css("height", windowHeight + "px");

    if ((imageWidth > 1024 && imageHeight > 768)) {
        $("body").css("overflow", "hidden");
    }
    else {
        $("body").css("overflow", "auto");
    }
}

/* History Handler
-------------------*/

(function (window, undefined) {
    // Prepare
    var History = window.History; // Note: We are using a capital H instead of a lower h
    if (!History.enabled) {
        // History.js is disabled for this browser.
        // This is because we can optionally choose to support HTML4 browsers or not.
        return false;
    }

    // Bind to StateChange Event
    History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
        var State = History.getState(); // Note: We are using History.getState() instead of event.state
        //History.log(State.data, State.title, State.url);

        var section = State.data.section;
        var url = State.data.url;
        var currentSection = $("#main #contentContainer").attr("data-section");

        if (section == null) {
            hideSection();
        }
        else if (section != currentSection) {
            showSection(url, section);
        }
    });
})(window);

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
