﻿var TIMER_DELAY = 10000;
var FADE_DELAY = 800;

var linkcount;
var timer;
var active = 0;

var box_left_margin;
var box_range;
var bar_range;
var arrow_width;

function onTimeout() {
    var next = active + 1;
    if (next > linkcount) next = 1;

    changeImage(next);

    resetTimeout();
}

function resetTimeout() {
    if (timer)
        clearTimeout(timer);

    timer = setTimeout("onTimeout()", TIMER_DELAY);
    progress();
}

function progress() {
    $("div.bottomline > div.timeline > div.progress > img").animate({ height: 5 + "px" }, TIMER_DELAY, "linear");
    $("div.bottomline > div.timeline > div.progress > img").stop(true, true);
    $("div.bottomline > div.timeline > div.progress > img").css({ width: 0 + "px" });
    $("div.bottomline > div.timeline > div.progress > img").animate({ width: 222 + "px" }, TIMER_DELAY, "linear");


}

function changeImage(id) {

    // Change image
    var fadeOutItems = $("#pic" + active + ", div.box > div.text");
    var fadeInItems = $("#pic" + id + ", div.box > div.text");

    fadeOutItems.stop(false, true).fadeTo(0, 1);
    fadeOutItems.fadeOut(FADE_DELAY, function() {
        // Replace the text in the box
        //setBox(nextId);
        // Retrieve data
        var desc = $("#flash-" + id + " > div.text").text();
        var title = $("#flash-" + id + " > div.title").html();
        var link = $("#flash-" + id + " > div.link").text();

        // Set content of box
        $("div.box > div.text").text(desc);
        $("div.box > div.title").html(title);
        $("div.box > div.readmore a.link").attr("href", link);


        fadeInItems.fadeIn(FADE_DELAY);
    });


    // Set CSS classes
    $("#flash-" + active).removeClass("active");
    $("#flash-" + active).addClass("inactive");
    $("#flash-" + id).removeClass("inactive");
    $("#flash-" + id).addClass("active");


    active = id;
}

// Begin cycle
$(function() {
    linkcount = $("div.pic").size();

    // Hide background images
    $("div.pic").hide();

    // Add onClick triggers
    $(".item").click(function() {

        // Get the id value by parsing the element id
        var id = parseInt($(this).attr("id").split("-")[1]);
        changeImage(id);

        resetTimeout();
    });

    // Load positioning for box and items bar
    bar_range = $("div.photo").width();
    //arrow_width = $("div.photo div.box div.arrow").width();
    //box_left_margin = $("div.photo > div.box").offset().left;
    //box_range = (bar_range - (box_left_margin * 2)) - $("div.photo > div.box").width() + arrow_width;

    // Set background images from html
    for (i = 1; i <= linkcount; i++) {
        $("#pic" + i).css("background-image", "url(" + $("#flash-" + i + " > div.image").text() + ")");
    }

    // Start timeout
    changeImage(1);

    resetTimeout();
});


