var gallery_pos = 1;
var curr_image = 0;
var gallery = images[2];
var stop_gallery = 0;
var max_items_per_page = 0;

function reset_buttons()
{
	$('.show_slideshow').css('background-position','0 0');
	$('.show_slideshow').each(function(){ 
		$(this).attr('title',$(this).attr('title').replace('stop','start'));
	});
}
function stop_image()
{
	var x = setTimeout('');
	for (var i = 0 ; i <= x ; i++) clearTimeout(i);
	reset_buttons();
	window.stop_gallery = 1;
}
function next_image()
{
	setTimeout('rotate_image()', 2000);
}
function rotate_image()
{
	if( !window.stop_gallery ) {
		var files = window.gallery.split(',');
		if( max_items_per_page ) {
			page = parseInt( (window.gallery_pos + 1) / max_items_per_page) + 1;
			id = basename(files[window.gallery_pos],'.jpg');
			if( window.gallery_pos == 0 ) prev_pos = files.length - 1;
			else prev_pos = window.gallery_pos - 1;
			if( window.gallery_pos == files.length - 1 ) next_pos = 0;
			else next_pos = window.gallery_pos + 1;
			$('#photo_prev').attr('href','item.php?id=' + basename(files[prev_pos],'.jpg') + '&page=' + page);
			$('#photo_next').attr('href','item.php?id=' + basename(files[next_pos],'.jpg') + '&page=' + page);
			$('#photo_back').attr('href','./?page=' + page);
			$('.show_slideshow').attr('href','item.php?id=' + id + '&page=' + page);
			$('#photo_id strong').html('Item ID: '+id);
		}
		var old_image = window.curr_image;
		window.curr_image = window.curr_image * -1 + 1;
		if( ++window.gallery_pos >= files.length ) window.gallery_pos = 0;
		$('#image_'+window.curr_image).fadeIn(1000)
		$('#image_'+old_image).fadeOut(1000, function() {
			if( max_items_per_page ) {
				$('#image_'+old_image).css('background-image','url("/_images_gallery/' + files[window.gallery_pos] + '")');
			} else {
				$('#image_'+old_image).attr('src','/_images_gallery/'+files[window.gallery_pos]);
			}
			next_image();
		});
	}
}

$(document).ready(function(){

	next_image();
	
	$('.show_slideshow').click(function(){
		if( !max_items_per_page ) {
			var pos = $(this).attr('title').search('start');							
			reset_buttons();
			if(pos == -1) {
				window.stop_gallery = 1;
			} else {
				$(this).attr('title',$(this).attr('title').replace('start','stop'));
				$(this).css('background-position','0 -26px');
				if(window.gallery != window.images[$(this).attr('rel')]) {
					window.curr_image = window.curr_image * -1 + 1;
					window.gallery_pos = -1;
					window.gallery = window.images[$(this).attr('rel')];
				}
				if( window.stop_gallery ) {
					window.stop_gallery = 0;
					rotate_image();
				}
			}
		}
	});
	
});

