$(function() {

    var carousel   = $('#news_carousel');
    var news       = carousel.find('ul.news');
    var controls   = null; // Will hold the ul with the controls
    var timer      = null; // Will hold the timer div
    var wait       = 5000; // Milliseconds to wait for auto-switching
    var widths     = [];   // Will hold the widths of each image
    var title     = [];   // Will hold the widths of each image
    var items_size = news.find('li').length;
    var initialized = false;
    var timeInterval = null;
    var pause = false;

    if (!items_size) {
        return;
    }

    news.find('div.newstitle a').each(function(i, e) {
        title[i+1] = $(e).text();
    });

    // Controls html to append
    var controls_str = '<ul class="controls">';
    for ( var i = 1; i <= items_size; i++ ) {
        controls_str += '<li><a href="#">' + i + '. '+title[i]+'</a></li>';
    }
    controls_str += '<li class="clear"></li></ul>';

    // Cache the controls list
    controls = carousel.append(controls_str).find('ul.controls');

    // Make the first button in controls active
    controls.find('li:first a').addClass('active');

    // Hook to the controls' click events
    controls.find('li a').click(function() {
        move_news( $(this) );
        return false;
    });

    var play_pause = carousel.find('#play_pause');
    play_pause.click(function() {
        if(pause) {
            pause = false;
            play_pause.find('#pause_btn').show();
            play_pause.find('#play_btn').hide();
        } else {
            pause = true;
            play_pause.find('#pause_btn').hide();
            play_pause.find('#play_btn').show();
        }
        handlePause();
    });

    // Append the timer and cache it
    timer = carousel.append('<div class="timer"></div>').find('div.timer');

    // Store each item's width and calculate the total width
    news.find('li img')
    .each(function(i, e) {
        //widths[i] = $(e).width();     //ovako je originalno pisalo, ali je problem kada se ne ucitaju slike do kraja
        widths[i] = news.width();
        if ( all_images_loaded() ) {
//            alert('init_carousel_each');
            init_carousel();
        }
    })
    .load(function(e) {
        var i = news.find('li img').index(this);
        widths[i] = $(this).width();
        if ( all_images_loaded() ) {
//            alert('init_carousel_load');
            init_carousel();
        }
    });


    function all_images_loaded() {
        return (items_size == widths.length) && (jQuery.inArray(0, widths) < 0);
    }

    function animate_timer() {
        timer.stop().css({width: '100px'}).animate({width: '1px'}, wait);
    }

    function move_news( new_active ) {

        // Move unless it is already moving
        if ( $('#news_carousel ul.news:animated').length > 1 ) {
            return false;
        }

        var current_active = controls.find('li a.active');

        if (new_active == 'next') {
            var next = current_active.parent().next().find('a');

            if ( !next.length ) {
                next = controls.find('li:first a');
            }

            new_active = next;
        }

        var current_index = parseInt(current_active.text(), 10) - 1;
        var new_index     = parseInt(new_active.text(), 10) - 1;
        var move_to       = new_index - current_index;


        if (!move_to) {
            return false;
        }

        var direction = (move_to > 0)? '-=': '+=';
        var duration   = 500;
        var move   = 0;
        var bottom = Math.min(current_index, new_index);
        var top    = Math.max(current_index, new_index);

        while (bottom < top) {
            move += widths[bottom];
            bottom++;
        }

        if(move_to < 0)
            duration   = 2;
            
        news.animate({marginLeft: direction + move}, duration);
        new_active.addClass('active');
        current_active.removeClass('active');
        clearInterval(timeInterval);
        if(!pause)
            timeInterval = setInterval(function() {move_news('next');}, wait);
//        animate_timer();
        return true;
    }

    // Initializer, called when all images are loaded
    function init_carousel() {
        if (initialized) {
            return false;
        }

        // Set the news ul total width
        var width = 0;
        for( var i = 0; i < widths.length; i++) {
            width += widths[i];
        }
        news.width(width);

        // Make the news change every X seconds
        start();

        initialized = true;
    }

    function stopTimerAnimation() {
        timer.stop();
    }
    function start() {
        timeInterval = setInterval(function() {move_news('next');}, wait+2000);
//        animate_timer();
    }
    function handlePause() {
        if(pause) {
            clearInterval(timeInterval);
        }
        else {
            start();
        }
    }
});
