﻿var wheel, highlight;

$(function() {
    wheel = $('.wheel');

    wheel.append('<img class="highlight" style="display:none" alt=""/>');
    highlight = wheel.find('.highlight');

    function showSegment(index) {
        $('.hovers li').hide();
        var id = segmentIds[index];
        $('.' + id).show();
        highlight.attr('src', '/images/' + id + (window.language === 'nl' ? '-nl' : '') + '.png').show();
    }
    wheel.mousemove(function(e) {
        var index = getSegmentIndex(e);
        showSegment(index);
    });
    wheel.click(function(e) {
        var index = getSegmentIndex(e);
        var id = segmentIds[index];
        wheel.animate(
            { left: 500, width: 150, height: 150 },
            { complete: function() { window.location = '/segment/' + id; } }
        );
    });

    $('.hovers li').hide();
    $('.hovers a').remove(); // links are only there for non-JS browsers.

    showSegment(0);

    $('.strip').css('margin-top', ($('.strip img').length - 1) * -100);
    setInterval(nextQuote, 10000);
    loadPhotos();
});

var segmentIds = ['gather-organise', 'identify', 'generate', 'decide', 'implement', 'evaluate', 'communicate', 'learn-from-experience'];

function getSegmentIndex(e) {
    var offset = wheel.offset();
    var x = e.clientX - offset.left - wheel.width() / 2;
    var y = e.clientY - offset.top - wheel.height() / 2 + scrollTop();
    var degrees = Math.atan2(x, y) * 180 / Math.PI;
    var index = Math.floor(degrees / -45) + 4;
    return index;
}

function loadPhotos() {
    var first = true;
    
    function loadNext() {
        if (window.photoUrls.length > 0) {
            var url = window.photoUrls.pop();
            var image = new Image();
            $(image).load(function() {
                $('.strip').append('<img src="' + url + '" alt=""/>');
                setTimeout(loadNext, 10);

                if (first) {
                    setInterval(nextPhoto, 5000);
                    first = false;
                }
            });
            image.src = url;
        }
    }

    loadNext();
}

function nextPhoto() {
    if (parseInt($('.strip').css('margin-top')) / 100 >= 0) {
        $('.strip').css('margin-top', ($('.strip img').length - 1) * -100);
    } else {
        $('.strip').animate({ marginTop: '+=100' }, 'slow', 'swing');
    }
}

function nextQuote() {
    var current = $('blockquote:visible');
    current.fadeOut('slow', function() {
        var next = current.next('blockquote');
        if (next.length == 0) next = $('blockquote:first');
        next.fadeIn('slow');
    });
}

function scrollTop() {
    var top = document.body.scrollTop;

    if (!top) {
        if (window.pageYOffset)
            top = window.pageYOffset;
        else
            top = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }
    return top;
}