$(function () {
    // fix headlines
    var h = 0;
    $(".serviceCategory h2").each(function () {
        h = Math.max(h, $(this).height());
    }).height(h);

    // setup scrolling
    $(".partWindow").height($(".slider").height());
    
    // setup categories
    var categories = {};
    
    $(".part").each(function () {
        var id = this.id.replace('part', '');
        if (id == "default")
            return;
        
        categories[id] = {
            'part': $(this),
            'category': $("#category" + id),
            'activeIcon': $("#icons" + id + " .activeIcon"),
            'inactiveIcon': $("#icons" + id + " .inactiveIcon"),
            'smallIcon': $("#smallicon" + id),
            'chosen': false
        };
    });

    function pageload(hash) {
        var id = hash.replace(/^.*#/, '');
        if (id && !(id in categories))
            id = null;
        chooseCategory(id);
    }
    
    function makeCategoryActive(c) {
        var hideSmallWhenNull = false;
        for (var id in categories)
            if (categories[id].chosen)
                hideSmallWhenNull = true;
        
        for (var id in categories) {
            if (categories[id] == c || categories[id].chosen)
                continue;

            categories[id].activeIcon.hide();
            categories[id].inactiveIcon.show();
            if (c)
                categories[id].smallIcon.stop(true).animate({'opacity': 0}, 200);
            else {
                categories[id].smallIcon.stop(true).animate({'opacity': hideSmallWhenNull ? 0 : 1}, 200);
            }
        }

        if (c) {
            c.activeIcon.show();
            c.inactiveIcon.hide();
            c.smallIcon.stop(true).animate({'opacity': 1}, 200);
        }
    }

    function chooseCategory(id) {
        // set state
        for (var i in categories)
            categories[i].chosen = false;
        if (id)
            categories[id].chosen = true;

        // change icons
        makeCategoryActive(categories[id]);

        // show the part
        var l = $("#part" + (id || "default")).offset().left - $("#partdefault").offset().left;

        $(".slider").animate({'left': -l});
    }

    $(".service").tooltip({
        showURL: false,
        delay: 0,
	top: 0
    }).hover(
        function () {
            $(this).addClass('activeService');
        },
        function () {
            $(this).removeClass('activeService');
        });
    
    $(".serviceCategory").hover(function () {
        var id = this.id.replace('category', '');
        makeCategoryActive(categories[id]);
    }, function() {
        makeCategoryActive(null);
    }).click(function (e) {
        e.preventDefault();
        var links = $(this).find("a");
        links.blur();
        $.historyLoad(links.get(0).href.replace(/^.*#/, ''));
    });

    $.historyInit(pageload);
});
