/*global document $*/
$(document).ready(function(){

var bg_pos = [0, 125, 250, 375, 500, 625];
var tour = $('#tour');
tour.html('<h3>Loading Tour...</h3>'); 
var window_width = $('#tour_window').width();
var url = "/ajax_tour";
var curr_page = 0;
var max_page;

function highlightCurrPage() {
    $('#tour_nav a').removeClass("activepage");
    $('#tour_nav #'+curr_page+'jump').addClass("activepage");
}

function moveTo(idx) {
    curr_page = idx;
    if( curr_page === 0 ) {
        $('#prev_link').hide();
        $('#next_link').show();
        $('#exit_links').hide();
    } else if( curr_page == max_page ) {
        $('#prev_link').show();
        $('#next_link').hide();
        $('#exit_links').fadeIn();
    } else {
        $('#prev_link').show();
        $('#next_link').show();
        $('#exit_links').hide();
    }
    // slide tour window
    var new_pos = 0 - parseInt($('#'+idx, tour).css("left"), 10);
    tour.animate({ left : new_pos }, 1000);
    // slide nav bg
    $('#tour_nav_inner').animate(
        { backgroundPosition : bg_pos[idx] }, 
        { duration: 1000, complete: highlightCurrPage }
    );
}

$.getJSON(url, function(data) {
    var num_pages = data.html.length;
    max_page = num_pages - 1; // as idx starts at 0
    tour.width(window_width*num_pages);
    tour.html(data.html.join(""));
    // give each div.tour_page an id
    $('div.tour_page', tour).each(function(i){
        $(this).attr("id", i)
            .css("position", "absolute")
            .css("left", i*window_width+"px");
    });
});

$('div#tour_nav a').click(function(){
    var jump_to = parseInt($(this).attr("id"), 10);
    moveTo(jump_to);
    return false;
});


$('#next_link').click(function(){
    var next_page = curr_page + 1;
    if( next_page > max_page ) {
        next_page = max_page;
    }
    moveTo(next_page);
    return false;
});

$('#prev_link').click(function(){
    var prev_page = curr_page - 1;
    if( prev_page < 0 ) {
        prev_page = 0;
    }
    moveTo(prev_page);
    return false;
});

highlightCurrPage();

});
