var stop = false;
var current = false;
var regexp = /link(\d)/;
var slide_timeout = 6000;

var perm = true;

(function($)
 {
     var cache = new Array();
     $.preload_images = function(images) // images is array with full image path
     {
	 var img_num = images.length;
	 for (var i = img_num; i--;) {
	     var cacheImage = document.createElement('img');
	     cacheImage.src = images[i];
	     cache.push(cacheImage);
	 }
     };
 })(jQuery);

// Change slide div animation, accepts jquery object
function change_div(to)
{
    perm = false;

    current.children('div:first').children('img:first').fadeOut('fast', function ()
                {
                });
    to.children('div:first').children('img:first').fadeIn('slow');
    current.children('div:last').children('img:last').animate({ right: '0', opacity: 0 },250,function()
                {
                    current.children('div:last').children('img:last').hide();
                    to.children('div:last').children('img:last').show();

to.children('div:last').children('img:last').animate({ right: ((($("body").width())/2)-303), opacity: 100 },500,function()
                            {
                                //last callback
                                current = to;
                                perm = true;

                            });
                });
}

// Change link animation, accepts jquery object
function select_link(link)
{
    $('a.slider_link').each(function ()
			    {
				$(this).removeClass('slide_selected');
				link.addClass('slide_selected');
			    });
}

// Wrapper for select_link and change_div
function change_slide(next_link, next_div)
{
    select_link(next_link);
    change_div(next_div);
}

$(function ()
{
    // Preload images
    var images = new Array();
    $('div.slide').each(function () { images.push($(this).children('img').attr('src')); });
    $.preload_images(images);

    current = $('div.slide:first');
    $('a.slider_link').click(function ()
			     {
                     if (perm) {
                        var number = $(this).attr('class').match(regexp)[1]; //Match link num
                        var next = $('div.frame' + number); //Get next div
                        if (!stop)
                            stop = true;
                        $('div.slide').stop(true, true);
                        change_slide($(this), next);
                    };
                    return false;
			     });
    // Creating slideshow
    var items = $('div.slide');
    var links = $('a.slider_link');
    function animate(index)
    {
	if (!stop)
	{
	    if (index == items.length) //Full cycle
		index = 0;
            change_slide($(links[index]), $(items[index]));
    	    setTimeout(function () { animate(index + 1); }, slide_timeout);
	}
    }
    setTimeout(function () { animate(1); }, slide_timeout);

});
