function initPage() {
    linkTargetsLoadedWithAjax();
    mapClickEventsDelegatedToLinks();
    mapMouseOverAndOutHighlightsLinkImages();
    mainImageIsLinkToFrontPage();
    mapKuviaLink();
    initContentHeightListener();
    loadContentBasedOnAnchor();
    loadAnimatedGifAndReplaceMainImageWhenLoaded();
}

function loadContentBasedOnAnchor() {
    if (location.href.indexOf('#') > 0) {
        var linkIdSelector = parseEndFromAnchor(location.href);
        if (linkIdSelector.indexOf('_') > 0) linkIdSelector = linkIdSelector.substring(0, linkIdSelector.indexOf('_'));
        $('#content').load($(linkIdSelector + '-id').get(0).href);
    }
}

function initContentHeightListener() {
    $('#content').ajaxComplete(function(event, request, settings) {
        checkFooterHeight();
    });
}

function mapKuviaLink() {
    $('#kuvia_map').click(function() {
        $('#kuvia-id').click();
    });
}

function checkFooterHeight() {
    availableFooterSize = $(window).height() - $('.container:first').height();
    if (availableFooterSize > 0) $('#footer').height(availableFooterSize);
    else if (availableFooterSize != 0) $('#footer').height(0);
}

function initPictures() {
    $('a[rel^="lightbox"]').slimbox({counterText: '{x}/{y}'}, null, function(el) {
        return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
    });
}

function loadAnimatedGifAndReplaceMainImageWhenLoaded() {
    $.get('img/Kohtaus.gif', function() {
        $('#main_image').get(0).src = 'img/Kohtaus.gif';
    });
}

function mainImageIsLinkToFrontPage() {
    $('#main_image').click(function() {
        $('#etusivu-id').click();
    });
}

function mapMouseOverAndOutHighlightsLinkImages() {
    $('map[name="linkmap"] > area').hover(function() {
        $(parseEndFromAnchor(this.href) + '-id img:first-child').hide();
        $(parseEndFromAnchor(this.href) + '-id img:last-child').show();
    }, function() {
        $(parseEndFromAnchor(this.href) + '-id img:last-child').hide();
        $(parseEndFromAnchor(this.href) + '-id img:first-child').show();
    });
}

function mapClickEventsDelegatedToLinks() {
    $('map[name="linkmap"] > area').click(function(event) {
        $(parseEndFromAnchor(this.href) + '-id').click();
    });
}

function linkTargetsLoadedWithAjax() {
    $('a[id$="-id"]').click(function(event) {
        loading(true);
        $('#content').load(this.href, function() {
            loading(false);
        });
        event.preventDefault();
    });
}

function loading(isLoading) {
    $(isLoading ? '#loading' : '#content').show();
    $(isLoading ? '#content' : '#loading').hide();
    checkFooterHeight();
}

function parseEndFromAnchor(url) {
    return url.substring(url.indexOf('#'));
}
