function scroller_resize(image) {
    var h = image.height;
    var w = image.width;
    if ( w > 120 )
    {
        shrink = 120/w;
        w *= shrink;
        h *= shrink;
    }
    if ( h > 90 )
    {
        shrink = 90/h;
        w *= shrink;
        h *= shrink;
}
    scroller_queue('<img src="'+image.src+'" width="'+w+'" height="'+h+'">');
}

function scroller_pick_image() {
    if ( scroller_files_unused.length == 0 )
        scroller_files_unused = scroller_files.slice();
    index = Math.floor(Math.random()*scroller_files_unused.length);
    if ( index > scroller_files_unused.length-1 )
        index = scroller_files_unused.length-1;
    ret = scroller_files_unused[index];
    scroller_files_unused.splice(index, 1);
    return ret;
}

function scroller_request(count) {
    if ( count <= 0 || scroller.queue.length >= 10 )
        return;
    var preloader = new Image();
    preloader.onload=function() {
        scroller_resize(this);
    };
    preloader.src=scroller_pick_image();
    scroller_request(count-1);
}

function scroller_queue(html) {
    scroller.queue.push(html);
    $('#scroller_floater').triggerHandler('enqueued');
}

function scroller_dequeue()
{
    if ( scroller.queue.length > 0 )
    {
        scroller_request(1);
        return scroller.queue.shift();
    }
    else
        return false;
}

function scroller_step() {
    $('#scroller_floater').unbind('enqueued', scroller_step);
    // load an image
    var img = scroller_dequeue();
    if ( !img )
    {   
        $('#scroller_floater').bind('enqueued', scroller_step);
        return;
    }
    if ( scroller.images <= scroller.max_images ) {
        scroller.images++;
    } else {
        // unload an image first
        $('#scroller_floater').children(':last').remove();
    }
    $('#scroller_floater').css('top', '0px');
    $('#scroller_floater').prepend('<div class="scroller_image">'+img+'</div>');
    $('#scroller_floater').children(':first').hide().fadeIn(1500);
    $('#scroller_floater').animate({'top': '+=100px'}, 4000, 'linear', scroller_step);
}

$(document).ready(function() {
    scroller = new Object();
    scroller.max_images = (Math.floor($('#scroller_container').height()/100))-1;
    scroller.queue = new Array();
    scroller_files_unused = scroller_files.slice();
    scroller_request(scroller.max_images);
    $('#scroller_floater').css('top','0px');
    scroller.images = 0;
    scroller_step();
});


