var target = '#new_animation';
var imagesArray = [], linksArray = [], counter = 0, current = -1;

$(document).ready(function() {
    init();
});

function init() {
    $(target).append($('<a href="#" style="border:none;" target="_blank"></a>').append($('<img id="animation-image" src="/" style="border:none; display:none; margin-top: 9px;"/>')));
    $.post("/default/getImages", {}, function(xml) {
        $("images",xml).each(function(id) {
            i_id = $('images',xml).get(id);
            var path = $("path", i_id).text();
            var link = $('text', i_id).text();
            
            imagesArray[counter] = path;
            linksArray[counter] = link;
            counter++;
        });        
        for(var i=0;i < counter; i++) {
            $('#anim-tags').append($('<div style="float:left;border:1px solid #989898;background-color:#232323;padding:3px;margin:2px;font-size:8pt;"></div>').append($('<a style="color:white;" href="#" class="show-count" rel="' + i + '">' + (i + 1) + '</a>')));
        }
        $('#anim-tags').append('<div style="clear:both;"></div>');
        beginAnimation();
        changeUp();
        $('.show-count').click(function(e) {
            forceChange($(this).attr('rel'));
        });
    });
}

function beginAnimation(images) {
    $('#animation-image').load(function() {
        $(this).fadeIn(1500, function() {
            $(this).delay(4000).fadeOut(1500, function() {
                changeUp();
            });
        });
    });
}

function forceChange(item) {
    if(item < 0 || item > counter)
        return;

    current = item;
    $('#animation-image').hide().unbind();
    $('#animation-image').attr('src', '/images/new_banner/' + imagesArray[item]);
    $('#animation-image').parent().attr('href', linksArray[item]);
    $('#animation-image').show();
    
    beginAnimation();
}

function changeUp() {
    if(current == (counter - 1)) { current = 0; } else { current++; }

    $('.showcount').css({'borderColor':'white'});
    $('.showcount[rel="' + current + '"]').css({'borderColor':'white'});

    $('#animation-image').attr('src', '/images/new_banner/' + imagesArray[current]);
    if(linksArray[current] != '')
        $('#animation-image').parent().attr('href',linksArray[current]);
    else
        $('#animation-image').parent().attr('href','#');
}
