$(document).ready(function() {
	var pos = new Array();
	$('.templateGallery').each(function() {
		var id = $(this).attr('usergallery');

		// Show an edit link if admin
		if( $('#adminMenu').length > 0 ) {
			$("<div class='templateGalleryEdit rounded'><a href='/mod/gallery/view-gallery.php?gallery_id=" + id + "'>Edit</a></div>")
				.insertBefore($(this).find('img'));
		}

		if( typeof(tg) === 'undefined' || !tg[id] || tg[id].length <= 1 ) { return; } /* nothing to rotate */
		pos[id] = 1;
		if( !$(this).hasClass('nobg') )
			$(this).css('background','url("' + tg[id][1] + '")');
		setInterval(function() { tgRotate(id) }, secs[id]*1000);
	});	

	function tgRotate(id) {
		// Fade out the image to leave the background
		$('#tg'+id + ' IMG').animate({opacity: 0}, 2500,function() {
			// Then replace the image and show it...
			$(this).attr('src', tg[id][pos[id]]);
			$(this).animate({opacity:1},1000, function() {
				// ...and load a new background
				pos[id]++;
				if( pos[id] >= tg[id].length ) { pos[id] = 0; }
				if( !$(this).parent().hasClass('nobg') )
					$('#tg' + id).css('background','url("' + tg[id][pos[id]] + '")');
			});

		});
	}
});

