﻿var FK = FK || {};

$(function () {
    $("body").removeClass("nojs");

    $("#search input:submit").click(function () {
        $(this).blur();
    });

    new FK.TopMenu("#topNav", "h4.trigger", "div.panel");
    new FK.GroupLinks("#groupLinks");
    new FK.GMap("#gmap");

    $("#topNav .panel").each(function () {
        $(this).find(".grid_4:last").addClass("last");
    });

    $("#topNav .panel .news li").one("click", function () {
        window.location = $(this).find("a").attr("href");
    });

    $("select.custom").sexyCombo();

    $("#content.sub div.jumpLinks")
        .append($("<div/>").addClass("end").text(" "))
        .hover(
            function () {
                $(this).addClass("hover");
            },
            function () {
                $(this).removeClass("hover");
            }
        );


    if ($.browser.msie && $.browser.version == "6.0") {
        $("#leftNav div.section:first").addClass("first");

        $("#sectionIntro .intro").ifixpng();

        // add first, last class to every li element.
        $("ul").each(function () {
            $(this)
                .find("li")
                .first().addClass("first")
                .end()
                .last().addClass("last");
        });
    }


});


FK.GMap = function (containerSelector) {   /// <summary>Init Google Maps - Size is set by container class.</summary> 


    var maps = $(containerSelector);

    this.GMap = function () {
        var self = this;

        maps.each(function () {
            var container = $(this).find(".container");
            var size = $(this).attr("class");

            var map = new GMap2(container[0]);
            map.enableScrollWheelZoom();
            map.setCenter(new GLatLng(55.56473779089114, 9.754228591918945), 13);

            self.BindOptionsHandlers($(this).find("ul.options"));
        });
    }

    this.BindOptionsHandlers = function (optionsElement) {
        var trigger = optionsElement.find("li.filter > a");

        var toggleFilterPanel = function () {
            var panel = trigger.next("ul");

            var animateSettings = {};
            var complete = function () { };

            if (panel.is(":visible")) {
                animateSettings.top = "+" + panel.height();
                complete = function () {
                    $(this).hide();
                };
            }
            else {
                animateSettings.top = "-" + panel.height();
                panel.show();
            }

            panel.animate(animateSettings, 300, complete);

            return false;
        };


        // handle filter open/close
        trigger.click(toggleFilterPanel);

        // handle filter selection
        optionsElement.find("li.filter .filterList a").click(function () {
            alert("Filter GMap");

            toggleFilterPanel.apply(this);
        });
    }

    this.GMap();
}

FK.TopMenu = function (containerSelector, triggerSelector, panelSelector) {   /// <summary>Creates the top mega menu.</summary> 

    var container = $(containerSelector);
    if (!container.size())
        return;

    var triggers = container.find(triggerSelector).ensureMatches();
    var panels = triggers.nextAll(panelSelector).ensureMatches();

    this.TopMenu = function () {
        var self = this;

        triggers
            .parent().first().addClass("first")
            .end()
            .last().addClass("last");


        if ($.browser.msie && $.browser.version == "6.0") {
            triggers.each(function () {
                $(this).css("width", $(this).width());
            });
        }

        container.hover(
            function () { },
            self.ContainerUnhover
        );

        triggers
            .hover(self.MenuHover, function () { })
            .click(self.MenuHover)
            .hoverIntent(
            {
                over: self.MenuHover,
                out: function () { },
                timeout: 400
            });
    };

    this.ContainerUnhover = function () {
        var triggersParents = triggers.parent();
        var visibleMenus = panels.filter(":visible");

        visibleMenus.slideUp({ duration: 300, easing: "easeInOutQuint", complete: function () {
            triggersParents.removeClass("active beforeActive");
        }
        });
    };

    this.MenuHover = function (evt) {
        var hasVisiblePanels = panels.is(":visible") || panels.is(":animated");
        var currentPanel = $(this).next(panelSelector);

        if (panels.is(":animated"))
            panels.stop(false, true);

        var trigger = currentPanel.prevAll("h4");
        triggerParent = trigger.parent();

        triggerParent
            .addClass("active")
            .siblings()
            .not(triggerParent)
            .removeClass("active beforeActive");

        triggerParent.not(".first").prev().addClass("beforeActive");

        if (hasVisiblePanels) {
            panels
                .not(currentPanel)
                .hide();

            currentPanel.show();
        }
        else {
            currentPanel.slideDown({ duration: 300, easing: "easeInOutQuint" });
        }

        currentPanel.find(".grid_4").equalHeights().last().addClass("last");
    };

    this.MenuUnhover = function () {
        $(this).next(menuContentSelector).slideUp(300, function () {
            $(this).css("z-index", "1000");
        });
    };

    this.TopMenu();
};


FK.GroupLinks = function (containerSelector) {
    var container = $(containerSelector);

    if (!container.size())
        return;

    var groups = container.find(".group").ensureMatches();
    var cols = container.find(".col").ensureMatches();
    var linkContainer = null;
    groups.css("z-index", "0"); // fix from Tom to reset z-index

    this.AnimateTime = 500;

    this.GroupLinks = function () {
        this.BindEvents();

        linkContainer = $("<div/>", { id: "linkContainer" })
            .appendTo(container);

        // set group position for later use.
        cols.each(function (i) {
            $(this).find(".group").each(function (pos) {
                var group = $(this);
                var related = group.attr("title");

                // Dont use obj {} when setting data, bug in jQuery which overrides events data also.
                // Will throw null reference error
                group
                    .data("isTop", pos == 0)
                    .data("isLeft", group.parent().attr("id").indexOf("Left") > 0)
                    .data("related", related)
                    .attr("title", "");

                var links = group
                                .find("div.links")
                                .data("related", related)
                                .detach();

                links.appendTo(linkContainer);
            });
        });
    };

    this.GetLinksElementByName = function (name) {
        var match = null;

        linkContainer.find("div.links").each(function () {
            if ($(this).data("related") == name) {
                match = $(this);
                return false;
            }
        });

        return match;
    };

    this.BindEvents = function () {
        var self = this;

        groups.hoverIntent(
        {
            over: function () { self.GroupHover(this, self); },
            out: function () { },
            timeout: 300
        });

        container.hoverIntent(
        {
            over: function () { },
            out: function () { self.ContainerUnhover(this, self) },
            timeout: 300
        });

    };

    this.ContainerUnhover = function (sender, self) {
        self.RevertElemetsToDefault();
    };

    this.GroupHover = function (sender, self) {
        // test if a group already is open.
        if (groups.filter("[state=open]").size())
            return;

        var group = $(sender);
        var links = self.GetLinksElementByName(group.data("related"));
        var isTop = group.data("isTop");
        var isLeft = group.data("isLeft");

        group
            .css("z-index", 100)
            .find("h2")
            .fadeOut("fast");

        var groupAnimateSettings = {};
        if (isTop)
            groupAnimateSettings.height = '330px';
        else
            groupAnimateSettings.top = '0px';


        var linkAnimateSettings = {};
        if (isLeft) {
            links.css("left", "472px").show();
            linkAnimateSettings.left = "235px";
        }
        else {
            links.css("left", "-235px").show();
            linkAnimateSettings.left = "+=235px";
        }

        // animate group rollout
        group.data("animating", true);

        group.animate(groupAnimateSettings, this.AnimateTime, "easeInOutQuint", function () {
            $(this).data("state", "open");
        });

        // animate links rollout
        links.animate(linkAnimateSettings, this.AnimateTime, "easeInOutQuint", function () {
            $(this).data("state", "open");
        });

    };

    this.RevertElemetsToDefault = function () {

        var openGroup = groups.filter("[animating=true]");

        openGroup.removeData("animating");

        var openLinks = this.GetLinksElementByName(openGroup.data("related"));

        var groupAnimateSettings = {};

        if (openGroup.data("isTop"))
            groupAnimateSettings.height = "165px";
        else
            groupAnimateSettings.top = "165px";

        openGroup.animate(groupAnimateSettings, this.AnimateTime, "easeInOutQuint", function () {
            $(this)
                .removeData("state")
                .css("z-index", "0");

            openGroup.find("h2").fadeIn(75);
        });

        var linksAnimateSettings = {};

        if (openGroup.data("isLeft"))
            linksAnimateSettings.left = "472px";
        else
            linksAnimateSettings.left = "-=235px";

        try {
            openLinks.animate(linksAnimateSettings, this.AnimateTime, "easeInOutQuint", function () {
                $(this).removeData("state");
            });
        }
        catch (err) {
        }

    };

    this.GroupUnhover = function () {
    };

    this.GroupLinks();
};



// delay 
// delay(function() { }, 500);
var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();


jQuery.fn.log = function (msg) {
    if (!("console" in window) || !("firebug" in console)) {
        var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
        window.console = {};
        for (var i = 0; i < names.length; ++i) window.console[names[i]] = function () { };
    }

    console.log("%s: %o", msg || "", this);
    return this;
};

jQuery.fn.ensureMatches = function (errorMessage) {   /// <summary>Ensure jQuery array has one or more matches.</summary> 

    if (!jQuery(this).length) {
        var defaultText = "Selector: \"" + this.selector + "\" did not match any elements.";
        jQuery.error(errorMessage || defaultText);
    }

    return this;
};

// jQuery data selector filter
(function ($) {
    var _dataFn = $.fn.data;
    $.fn.data = function (key, val) {
        if (typeof val !== 'undefined') {
            $.expr.attrHandle[key] = function (elem) {
                return $(elem).attr(key) || $(elem).data(key);
            };
        }
        return _dataFn.apply(this, arguments);
    };
})(jQuery);

