﻿

$.fn.equalHeights = function (px) {
    $(this).each(function () {
        var currentTallest = 0;
        $(this).children().each(function (i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
        
        //if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};

function equalHeightStartColumns() {
    $(".column-wrapper").equalHeights();
    if ($(".column-wrapper").last().children().length > 1) {
        var calculatedHeight = $(".column-wrapper").first().height() - $(".column-wrapper").last().find(".column.half.first").height() - 60;
        $(".column-wrapper").last().find(".column.half.last").height(calculatedHeight);
    }
}

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

//after scroll event, based on SCROLL_DELAY
var afterScroll = (function () {
    // Configure
    var SCROLL_DELAY = 300;

    // Do not edit the following
    var  baseId = 0,
        scrollId = 0,
        currentlyScrolling = false,
        funcs = [];

    // --- Init ---
    addEvent(window, "onscroll", function (evt) {
                // update the scroll identifier
                scrollId = new Date().getTime();

                // parallax scroll
                scrollBackground($('.section'));

                if (!currentlyScrolling) { //Scroll has just started
                    // set the info
                    currentlyScrolling = true;

                    // Launch the watch process
                    setTimeout(function () {
                        if (scrollId == baseId) { // Scrolling has stopped

                            // set the info
                            currentlyScrolling = false;

                            // Execute the registered handlers
                            for (var ii = funcs.length; ii--; ) funcs[ii]();

                        } else { // Still scrolling
                            // set a milestone
                            baseId = scrollId;

                            // wait
                            setTimeout(arguments.callee,SCROLL_DELAY);
                        }
                    }, SCROLL_DELAY);
                } else {
                    // a process has already been launched
                    // and is waiting to be completed
                    // - Do nothing
                }

            }
            );

    // --- return the registering function ---
    return function (func) { funcs.push(func); }

    // --- Helpers ---
    function addEvent(obj, evt, func) {
        if (obj[evt]) {
            obj[evt] = (function (handler) {
                return function (evt) {
                    func.call(this, evt);
                    return handler.call(this, evt);
                }
            })(obj[evt]);
        } else {
            obj[evt] = func;
        }
    }
})();

//** auto run functions **/

var lastx = null;
var enableShowHideMenuWhileScrolling = true;
var topMenuSelectedItem = null;
var childMenuSelectedItem = null;

var agent = navigator.userAgent.toLowerCase();
var isIphone = agent.indexOf('iphone') > -1;
var isIpad = agent.indexOf('ipad') > -1;
var isAndroid = (agent.search('android') > -1);

var scrollFast = false;

var isSmartPhone = isIpad || isIphone || isAndroid;

var isPositionFixedSupported = !isSmartPhone;

if (agent.indexOf('iphone os 5') > -1) // position fixed works in ios5, hack. remove this when ios 6 comes.. ;)
    isPositionFixedSupported = true;

var seconds = 0;
var frames = 0;

function moveNext() {
    var currentVisiblePageElement = getNextPageElement();

    if (currentVisiblePageElement) {
        var nextLink = $(currentVisiblePageElement).find(".next a");

        if (nextLink.length > 0) {
            location.hash = nextLink.attr('href');
        }
        return false;
    }
}

function movePrevious() {
    var currentVisiblePageElement = getNextPageElement();
    if (currentVisiblePageElement) {
        var nextLink = $(currentVisiblePageElement).find(".prev a");

        if (nextLink.length > 0) {
            location.hash = nextLink.attr('href');
        }
        return false;
    }
}


function setMenuPositionForSmartPhones() {
    
    if (!isPositionFixedSupported)
    {
        $("#menu").css('position', 'absolute');
        $("#menu").css("left", $(window).scrollLeft() + 'px');
    }
}

function keyNavigation(e) {
    if (e.keyCode == 37) {
        movePrevious();
        return false;
    }
    if (e.keyCode == 39) {
        moveNext();
        return false;
    }
}
var lastscrollinglocationtogoto = null;
$(document).ready(function () {

    if ($.browser.mozilla) {
        $(document).keypress(keyNavigation);
    } else {
        $(document).keydown(keyNavigation);
    }

    $(window).hashchange(function () {
        var menuItemToGoTo = getMenuItemByLocationHash();
        goToMenuItem(menuItemToGoTo);
        selectMenuItem(menuItemToGoTo);

        setMenuPositionForSmartPhones();
    });

    //scrollto doesn't work for iphone, so # navigation is enabled instead
    if (isSmartPhone) {
        $(".section").css("-webkit-background-size", "2500px 1600px");
    }
    else
    {
        //replace the content Id's in order to prevent the browser to go there by #
        $(".clouds").each(function () {
            var newId = 'content_' + $(this).attr('id');
            $(this).attr('id', newId);
        });
    }

    $(window).scroll(function () {
        //show relevant submenu and select the menu item for the displayed content
        if (enableShowHideMenuWhileScrolling && !isIphone) {
            var currentVisiblePageElement = null;

            if ($(window).scrollLeft() - lastx < -100) {
                //vi scrollar vänster <--
                currentVisiblePageElement = getPreviousPageElement();
                scrollFast = true;
            }
            else if ($(window).scrollLeft() - lastx > 100) {
                //vi scrollar höger -->
                currentVisiblePageElement = getNextPageElement();
                scrollFast = true;
            }
            else {
                //vi scroll i y-led
            }

            if (currentVisiblePageElement != null) {
                //get menu element to navigate to by visible page content
                var menuItemToGoTo = $("#menu_" + $(currentVisiblePageElement).attr("id").replace('content_', ''));

                if (!menuItemToGoTo.hasClass("selected")) {
                    selectMenuItem(menuItemToGoTo, function () {
                        lastscrollinglocationtogoto = $(menuItemToGoTo).find("a").attr("href");
                    });
                }
            }

            //set lastx in order to keep track of the scroll direction
            lastx = $(window).scrollLeft();
        }

        //workaround to show menu for detected smartphones
        if (isSmartPhone) {
            setMenuPositionForSmartPhones();
        }
    });

    afterScroll(function () {
        if (lastscrollinglocationtogoto != null) {
            location.hash = lastscrollinglocationtogoto;
            lastscrollinglocationtogoto = null;
        }
    });

    //hover top menu
    $("#menu ul li").not("#menu ul li ul li").hover(function () {
        hoverMenuItem(this, topMenuSelectedItem);
    });

    //hover sub menu
    $("#menu ul li ul li").hover(function () {
        hoverMenuItem(this, childMenuSelectedItem);
    });

    //blur menu item
    $("#menu").find("a").focus(function () {
        $(this).blur();
    });

    //blur navigation button
    $(".horizontalNavigation").find("a").focus(function () {
        $(this).blur();
    });

    //make selection from hash
    if (location.hash != '') {
        var menuItemToGoTo = getMenuItemByLocationHash();
        goToMenuItem(menuItemToGoTo);
        selectMenuItem(menuItemToGoTo);
    }
    else {
        if (location.pathname.length > 1) {
            location.hash = location.pathname.substring(1).replace('/', '_');
            location.pathname = '';
        } else {
            location.hash = $("#menu .root").find("a").first().attr('href').substring(1);
        }
    }


    $(document).ready(function () {
        //set content height
        $(".content").equalHeights();
        //set the page sections to equal height
        $("#sections .section").equalHeights();

        //set equal height to sectionstart teaser elements
        $(".clouds").each(function () {
            $(this).find(".teaser .zone .element").equalHeights();
        });

        $('.zone.slideshow').each(function () {
            $(this).cycle(
            {
                height: $(this).height(),
                delay: -500,
                containerResize: true
            });
        });

        $("a:not(a.galleryImage)").each(function () {
            var currentUrl = this.href;
            if (this.hostname !== document.location.hostname || this.pathname.substring(0, 7) === '/files/' || this.pathname.substring(0, 6) === 'files/') {
                return;
            }
            if (this.hash && this.pathname === "/") {
                return;
            }

            var pathName = this.pathname;
            if (pathName.substring(0, 1) == '/') {
                pathName = pathName.substring(1);
            }

            var newHref = this.protocol + "//" + this.host + "/#" + pathName.replace("/", "_");

            //console.log("Href changed from '" + this.href + "' to '" + newHref + "'");
            $(this).attr("href", newHref.toLowerCase());
        });
    });

    //set the page section container to the correct width to contain all the sections horizontally
    var sectionContainerWidth = 0;
    $("#sections .section").each(function () {
        sectionContainerWidth += $(this).width();
    });
    $("#sections").width(sectionContainerWidth);
    $("#menu ul li ul").width(sectionContainerWidth);



    //add fancybox to element images
    $("a.galleryImage").fancybox();

});

function getMenuItemByLocationHash() {
    
    return $("#menu_" + location.hash.replace('#', ''));
}

function getPreviousPageElement() {
    var previousElement = null;
    $(".clouds").each(function () {
        var position = $(this).offset();
        if (position.left + ($(this).width() / 3) < $(window).scrollLeft() && (previousElement == null || position.left + ($(this).width() / 3) > $(previousElement).offset().left)) {
            previousElement = this;
        }
    });
    return previousElement;
}
function getNextPageElement() {
    var nextElement = null;
    $(".clouds").each(function () {
        var position = $(this).offset();
        if ((position.left + $(this).width() / 3) > $(window).scrollLeft() && (nextElement == null || (position.left + $(this).width() / 3) < $(nextElement).offset().left)) {
            nextElement = this;
        }
    });
    return nextElement;
}

//hover a menu item
function hoverMenuItem(menuItemToHover, currentSelectedMenuItem) {
    if ($(menuItemToHover).hasClass("selected") && $(currentSelectedMenuItem).attr('id') != $(menuItemToHover).attr('id')) {
        //only remove selection the menuitem if it's not the current selected list item
        $(menuItemToHover).removeClass("selected");

    }
    else {
        //make selection
        $(menuItemToHover).addClass("selected");
    }
}

//go to a menu item
function goToMenuItem(menuItemToGoTo) {
    //get content element by menu item
    if ($(menuItemToGoTo).length > 0) {
        var elementToDisplay = $("#content_" + $(menuItemToGoTo).attr('id').replace('menu_', ''));

        if (elementToDisplay.length > 0) {
            //scroll to content for clicked link
            scrollToElement(elementToDisplay);
        }
    }
}

//select a new menu item
function selectMenuItem(menuItemToSelect, callback) {
    var isTopMenu = $(menuItemToSelect).parent("ul.first").length > 0 || $(menuItemToSelect).attr('id') == "menu_start";

    $(menuItemToSelect).click();

    if (isTopMenu) {
        //unselect and hide menu for the old selected list item
        if (topMenuSelectedItem != null && topMenuSelectedItem != menuItemToSelect) {
            hideSubmenu(topMenuSelectedItem);
            $("ul.first li").removeClass("selected");
        }
        //unselect sub menu list item
        if (childMenuSelectedItem != null) {
            childMenuSelectedItem = null;
        }
        $("ul.second li").removeClass("selected");
        //select new list item
        $(menuItemToSelect).addClass("selected");
        topMenuSelectedItem = menuItemToSelect;
        showSubmenu(menuItemToSelect);
    }
    else {
        //if menu not visible, display it
        var parentMenuItem = $(menuItemToSelect).parent().parent();
        if (!parentMenuItem.hasClass("selected")) {
            $("ul.first li").removeClass("selected");
            parentMenuItem.addClass("selected");

            if (topMenuSelectedItem != null)
                hideSubmenu(topMenuSelectedItem);
            showSubmenu(parentMenuItem);
            topMenuSelectedItem = parentMenuItem;
        }

        //unselect the old selected list item
        if (childMenuSelectedItem != null && childMenuSelectedItem != menuItemToSelect) {
            $(childMenuSelectedItem).removeClass("selected");
            $("ul.second li").removeClass("selected");
        }

        //select new list item
        $(menuItemToSelect).addClass("selected");
        childMenuSelectedItem = menuItemToSelect;
    }
    if (callback != null)
        callback();

    if (typeof(onAfterMenuSelected) != "undefined")
        onAfterMenuSelected(menuItemToSelect);
}

// scroll to specific element
function scrollToElement(element, callback) {
    enableShowHideMenuWhileScrolling = false;
    $(window).stop();

    $.scrollTo(element, scrollFast ? 1500 : 3000, {
        easing: scrollFast ? 'easeOutExpo' : 'easeInOutQuint',
        stop: true,
        queue: true,
        axis: 'yx',
        onAfter: function () {
            lastx = null;
            enableShowHideMenuWhileScrolling = true;
            scrollFast = false;

            if (callback)
                callback();
        }
    });
    return false;
}

var depth = 8;

// set background position on specific element depending on the scroll position of the page
function scrollBackground(element) {


    if (!isSmartPhone) {
        var scroll = $(window).scrollLeft(); //  - element.position().left;
        // element.css("-webkit-transition:background-position", "20ms;");
        element.css("background-position", Math.round(-(scroll / depth)) + "px 0px");
    }
    $("#menu").css('top', (-$(window).scrollTop()) + "px ");
}

//fade in the submenu
function showSubmenu(menuItem) {
    $("ul").stop();
    $(menuItem).find("ul").fadeIn(1600);
}

//fade out the submenu
function hideSubmenu(menuItem) {
    $(menuItem).find("li").removeClass("selected");
    $(menuItem).find("ul").hide();
}

