(function ($) {
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				if ( this.complete || this.readyState === 4 ) { hollaback.handler.apply(this); }
				else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) { $(this).trigger('error'); }
				// infinite loop crashes IE8: else { $(this).bind('load', hollaback.handler); }
			}
		}
	};
}(jQuery));

$(document).ready(function() {
	$('.tbType_gallery').each(function() {
		var $box = $(this);
		var metadata = $box.attr('metadata');
		$.get('/mod/gallery/export-json.php?gallery_id='+metadata, function(e) {
			var photos = eval(e);
			if( !photos ) { return; }

			tbRotateGallery($box, photos, 0);
		});
	});
});

function tbRotateGallery($box, photos, id) {
	id %= photos.length;
	var $old = $box.find('img');
	if( !photos[id] ) return;
	$('<img tbId="'+photos[id].id+'" src="'+photos[id].url+'">')
		.css('position','absolute')
		.hide()
		.css('cursor','pointer')
		.click(function() {
			document.location.href = '/mod/gallery/view-photo.php?photo_id='+$(this).attr('tbId');
		})
		.bind('load', function(e) { 
			e; // screw everything about this.
			$(this).appendTo($box)
				.fadeIn(function() { $old.detach(); })
		});
	if( photos.length > 1 ) { setTimeout(function() { tbRotateGallery($box, photos, id+1) }, 10000); }
}

