﻿$(function() {
    var slide_timespan = 480;
    var slider_interval = 8000;
    var start_timeout = 8000;
    var items = $($(".headlines .headlines_items")[0]);
    var count = $("li", items).length;
    var enabled = true;
    _find(0).addClass("current");
    var slider_ref = setTimeout(function() { start_animate(); }, start_timeout);
    $(".headlines .arrows a").click(function() {
        if ($(this).hasClass("disabled") == true) return false;
        clearTimeout(slider_ref);
        enabled = false;
        animate(_current(), $(this).hasClass("prev") ? _next("", _index()) : _next("next", _index()), function() { slider_ref = next_animate(); });
        return false;
    });
    function animate(current, next, callback) {
        enabled = false;
        current.animate({ top: -20 }, slide_timespan, function() {
            current.removeClass("current");
            next.addClass("current");
            next.css("top", "20px");
            next.animate({ top: 0 }, slide_timespan, function() {
                enabled = true;
                $(".headlines .arrows a").each(function() { $(this).removeClass("disabled"); });
                if (_index() == 0) { $(".headlines .arrows a.prev").addClass("disabled"); }
                if (_index() + 1 == count) { $(".headlines .arrows a.next").addClass("disabled"); }
                if (callback != null)
                    callback();
            });
        });
    }
    function start_animate() {
        animate(_current(), _next("next", _index()), function() { slider_ref = next_animate(); });
    }
    function next_animate() {
        return enabled == true ? setTimeout(function() { start_animate() }, slider_interval) : setTimeout(function() { next_animate() }, 2000);
    }
    function _find(index_) {
        return $("li:eq(" + index_ + ")", items);
    }
    function _index() {
        return items.find(".current").index();
    }
    function _current() {
        return _find(_index());
    }
    function _next(dir, index_) {
        return dir === "next" ? _find(_next_index(index_)) : _find(_prev_index(index_));
    }
    function _prev_index(index_) {
        return index_ - 1 < 0 ? count - 1 : index_ - 1;
    }
    function _next_index(index_) {
        return index_ + 2 > count ? 0 : index_ + 1
    }
});
