//hold current position
var current_tb = null;

function animateTb()
{
    //if start or last tb then use first one
    if (!$chk(current_tb) || !$chk(current_tb.getNext()))
    {
        current_tb = $('thumbnails').getFirst();
        //empty large image container
        $('large_img').empty();
    }else{
        current_tb = current_tb.getNext();
    }
    
    //create active element
    var active = new Element('div', {'class': 'active'});
    
    //hide it to the left
    active.setStyle('margin-left', -105);
    
    //insert it into thumbnail
    active.inject(current_tb);
    
    //insert large image
    var large_img = new Element('div', {'class': 'large_img'});
    large_img.inject($('large_img'));
    large_img.setStyles(
    {
        'background-image': 'url(' + current_tb.getFirst().value + ')',
        'background-repeat': 'no-repeat',
        'opacity': 0
    });
    var imgFx = new Fx.Tween(large_img,
    {
        property: 'opacity'
    }).start(1);
    
    //start animation
    var activeFx = new Fx.Tween(active,
    {
        duration: 'long',
        onComplete: function()
        {
            var fx = function()
            {
                //now slide active to the right
                var activeFx2 = new Fx.Tween(active,
                {
                    duration: 'long',
                    onComplete: function()
                    {
                        active.destroy();
                    }
                }).start('margin-left', 105);
                
                animateTb();
            };
            fx.delay(1500);
        }
    }).start('margin-left', 0);
}

window.addEvent('domready', function()
{
    //add preloader
	var progress = new Element('div', {'id': 'progress'}).inject($('large_img')).setStyles({'height': 0, 'position': 'absolute'});
	
	//progress fx
	var progressFx = new Fx.Tween(progress, {property: 'height'});
	
	//preload images
	var images = [];
	$('thumbnails').getElements('.collage_tb').each(function(tb)
	{
		//add thumbnail link
		tb.addEvent('click', function(e)
		{
			e = new Event(e);
			e.stop();
			window.location = tb.getElement('.link').value;
		});
		images.include(tb.getFirst().value);
	});
	
	new Asset.images(images,
	{
		onProgress: function(counter, index)
		{
			progressFx.start(counter * 425 / images.length);
		},
		onComplete: function()
		{
			animateTb();
		}
	});
});
