var navItems,
    navBreakItem,
    navBreakOffset,
    contentItems,
    prevItem = -1,
    scrollable,
    pageWidth,
    pageHeight,
    contentWidth,
    contentMargin,
    navSlideDelay,
    autoSlideTimeout,
    autoSlideInterval = 6000;

// Replace navigation links with cufon font
Cufon.replace('.menu-item a', {
    fontFamily: 'Gotham Medium',
    hover: true
});

// Initialize stuff after document has loaded
$(document).ready(function () {
    // Check which element is scrollable in current browser
    scrollable = $('html,body').scrollable();
    pageHeight = $(window).height();

    initSlideshows();
    initResize();
    initNews();
});

// Initialize stuff after Cufon has been applied
$(window).load(function () {
    initScrollNavigation();
    initFixedHeader();

    // Load map iframe after everything else
    $('#IMSMap').attr('src', 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=IMS+Talent+oy+Urho+Kekkosen+katu+5+C+00100+Helsinki&aq=&sll=59.040555,30.322266&sspn=37.321762,113.818359&ie=UTF8&hq=IMS+Talent+oy&hnear=Urho+Kekkonens+gata,+00100+Helsingfors,+Finland&cid=3204708555145803291&ll=60.174306,24.936819&spn=0.018143,0.037251&z=14&iwloc=A&output=embed');
});

function initFixedHeader ()
{
    if (($.browser.msie && $.browser.version == '6.0') ||
        navigator.platform.indexOf('iPad') != -1 ||
        navigator.platform.indexOf('iPhone') != -1 ||
        navigator.platform.indexOf('iPod') != -1) {

        $('#viiva').css('position', 'absolute');

        // Attach smooth scrolling and fixed header events
        $('.menu-item a,#logo,#etusivugradient .more-link,.nappi').smoothScroll({
            afterScroll: handleFixedHeader
        });
        $(window).scroll(handleFixedHeader);
        handleFixedHeader();
    } else {
        $('.menu-item a,#logo,#etusivugradient .more-link,.nappi').smoothScroll();
    }
}

// Calculate fixed header position for ie6 and mobile browsers
function handleFixedHeader ()
{
    if (navSlideDelay)
        clearTimeout(navSlideDelay);
        
    navSlideDelay = setTimeout(animateFixedHeader, 100);
}

function animateFixedHeader ()
{
    navSlideDelay = null;
    $('#viiva').animate({ top: scrollable.scrollTop() }, 'normal');
    handleScrollNavigation();
}

function initSlideshows ()
{
    // Initialize slideshows
    pageWidth = $('.slidecontainer').width();
    contentWidth = $('.slidecontainer .pagewrapper').outerWidth();
    contentMargin = Math.max(0, Math.floor((pageWidth - contentWidth) / 2));
    $('.slidecontainer').each(initSlideshow);

    // Handle read more links in slideshows
    $('.summary').click(function (e) {
        e.preventDefault();
        $('#goto-' + this.id.split('-')[1]).click();
    });

    // Make navigation go to specific slide
    $('.menu-item a,#etusivugradient .more-link,.nappi').click(function (e) {
        e.preventDefault();
        var hash = this.href.split('#')[1],
            path = hash.split(','),
            page = path[0],
            slide = path[1] ? parseInt(path[1], 10) : 0;

        if(slide)
            $('#' + page + ' #goto-' + slide).click();
        else
            $('#' + page + ' .gotoslide:first').click();
    });

    // Start automatic slideshows, if any
    if ($('.autoslide').length) {
        autoSlideTimeout = setTimeout(autoSlide, autoSlideInterval);
    }
}

// Advance automatic slideshows
function autoSlide ()
{
    autoSlideTimeout = null;
    $('.autoslide .nextslide').click();
    autoSlideTimeout = setTimeout(autoSlide, autoSlideInterval);
}

// Initialize slideshows
function initSlideshow ()
{
    var container = $(this),
        buttons = container.find('.prevslide,.nextslide,.gotoslide'),
        gotoButtons = buttons.filter('.gotoslide'),
        nextButtons = buttons.filter('.prevslide,.nextslide'),
        slides = container.find('.pagewrapper'),
        clone = $(slides).first().clone(),
        holder,
        index = 0,
        previous = 0,
        hideNextButtons = buttons.is('.gotoslide');

    // Wrap slides with holder
    slides.wrapAll('<div />');
    holder = slides.parent();
    //holder.append('<div class="clear"></div>');

    // Duplicate first slide for never-ending loop
    if (nextButtons.length) {
        holder.append(clone);
        slides = slides.add(clone);
    }

    // Modify slide styles
    slides.css({
        'display': 'inline',
        'float': 'left',
        'marginLeft': contentMargin,
        'marginRight': contentMargin
    });
    holder.css({ 'position': 'absolute', 'width': pageWidth * slides.length + 'px' });

    buttons.click(function (e) {
        e.preventDefault();

        // Prevent automatic slideshows from advancing for a while
        if (autoSlideTimeout && container.hasClass('autoslide')) {
            clearTimeout(autoSlideTimeout);
            autoSlideTimeout = setTimeout(autoSlide, autoSlideInterval * 3);
        }
                      
        // Change slide
        if ($(this).hasClass('prevslide')) {
            index--;
        } else if ($(this).hasClass('nextslide')) {
            index++;
        } else {
            index = parseInt(this.href.split('#')[1], 10);
        }

        // Check bounds
        if (index < 0) {
            holder.css({ left: '-' + ((slides.length - 1) * pageWidth - 5) + 'px' });
            index = slides.length - 2;
        } else if (index >= slides.length) {
            holder.css({ left: '-5px' });
            index = 1;
        }

        // Hide next buttons on first slide
        var trueIndex = index % (slides.length - 1);
        if (hideNextButtons && trueIndex == 0) {
            nextButtons.fadeOut('fast');
        } else {
            nextButtons.fadeIn('fast');
        }

        // Activate button
        gotoButtons.removeClass('current-menu-item');
        gotoButtons.eq(trueIndex).addClass('current-menu-item');

        // Animate
        holder.animate({ left: '-' + (index * pageWidth) + 'px' }, 'normal', function () {
            if (index == slides.length - 1) {
                holder.css({ left: '0px' });
                index = 0;
            }
        });

        container.data('index', index);
        previous = index;
    });
}

function initResize ()
{
    // Attach resize events
    $(window).resize(handleResize);
    handleResize();
}

// Update slideshow margins
function handleResize ()
{
    pageWidth = $('.slidecontainer').width();
    pageHeight = $(window).height();
    contentMargin = Math.max(0, Math.floor((pageWidth - contentWidth) / 2));

    if (contentItems) {
        var contentLast = $('.page:last');
        contentLast.height(pageHeight - 114);
    }

    // Modify slide styles
    $('.slidecontainer .pagewrapper').css({
        'marginLeft': contentMargin,
        'marginRight': contentMargin
    });

    // Calculate container width and position
    $('.slidecontainer').each(function () {
        var slides = $(this).find('.pagewrapper'),
            holder = slides.parent();
        holder.css({
            width: pageWidth * slides.length + 'px',
            left: '-' + ($(this).data('index') * pageWidth) + 'px'
        });
    });
}

function initNews ()
{
    $('.post span').each(function () {
        if (this.id.split('-')[0] != 'more')
            return;

        var readmore = $('<a href="#" class="more-link">Lue lisää</a>'),
            postmore;

        $(this).parent().before(readmore).remove();
        readmore.nextAll().wrapAll('<div class="postmore"></div>');
        postmore = readmore.next('.postmore');

        readmore.click(function (e) {
            e.preventDefault();
            readmore.fadeOut('fast', function () {
                postmore.slideDown('fast');
            });
        });
    });

    $('.postlist a').click(function (e) {
        e.preventDefault();

        var id = '#' + this.href.split('#')[1];
        if ($(id).is(':visible'))
            return;

        $('.post:visible').fadeOut('fast', function () {
            $('.more-link').show();
            $('.postmore').hide();
            $(id).fadeIn('fast');
        });
    });
}

function initScrollNavigation ()
{
    var navOffset = $('#navigaatio li:first').offset().left + 2,
        barOffset = navOffset - $('#navigaatio-wrapper').offset().left,
        navLast = $('#navigaatio li:last'),
        navLeftLast = $('#navigaatio-left li:last'),
        contentLast = $('.page:last');

    $('#progress-bar-left').css('left', barOffset + 'px');

    // Calculate navigation offsets
    navItems = $('#navigaatio li').map(function (i) {
        return $(this).offset().left - navOffset;
    }).get();
    navItems.push(navLast.offset().left + navLast.width() - navOffset);

    navBreakItem = $('#navigaatio-left li').length - 1;
    navBreakOffset = navLeftLast.offset().left + navLeftLast.width() - navOffset;

    // Calculate content offsets
    contentItems = $('.page').map(function (i) {
        return $(this).offset().top;
    }).get();
    contentLast.height(pageHeight - 114);
    contentItems.push(contentLast.offset().top + contentLast.outerHeight(true));

    // Attach scroll event
    $(window).scroll(handleScrollNavigation);
    handleScrollNavigation();
}

// Update navigation according to scroll position
function handleScrollNavigation ()
{
    var scroll = scrollable.scrollTop() + 1,
        progress = 0,
        percent = 0,
        activeItem;

    // Determine current content
    for (var n = 0; n < contentItems.length - 1 && scroll > contentItems[n]; n++);

    // Calculate scoll percentage in current content
    if (n && n < contentItems.length - 1) {
        percent = (scroll - contentItems[n - 1]) / (contentItems[n] - contentItems[n - 1]);
        if (n == navBreakItem)
            progress = Math.round((navBreakOffset - navItems[n]) * percent);
        else
            progress = Math.round((navItems[n + 1] - navItems[n]) * percent);
    }

    // Update progress bar
    if (n > navBreakItem)
        $('#progress-bar-right').width(navItems[n] - navItems[navBreakItem + 1] + progress - 2);
    else
        $('#progress-bar-left').width(navItems[n] + progress - 2);

    if (n > navBreakItem)
        $('#progress-bar-left').width(navBreakOffset);
    else
        $('#progress-bar-right').width(0);

    // Update navigation according to visible content
    if (contentItems[n] + pageHeight / 2 < scroll + pageHeight) {
        activeItem = n;
    } else {
        activeItem = n - 1;
    }

    if (activeItem != prevItem) {
        $('#navigaatio li').removeClass('current-menu-item');
        $('#navigaatio li:eq(' + activeItem + ')').addClass('current-menu-item');
        Cufon.refresh();
        prevItem = activeItem;
    }
}

