qSessions = {
	domain: "http://qdepartment.com/",
	gallery_path: "sessions_gallery/",
	gallery_data: null,
	slideId: null,
	current_image: null,
	current_session: null,

	initGallery: function() {
		$("#session_window").html('');
		$("#session_image").remove();
		$("#session_info").html('');
		$("#contextnav").hide();
		qSessions.stopSlideshow();
	},

	loadSession: function(session_gallery) {
		if(qSessions.current_session == session_gallery) return;
		qSessions.current_session = session_gallery;
		qSessions.initGallery();
		$.getJSON(qSessions.domain+qSessions.gallery_path+session_gallery+'/', function(data) {
			
			qSessions.gallery_data = data.thumbs;

			for(i = 0; i < data.thumbs.length; i++) {
				image = data.thumbs[i];

				var thumb = new Image();
				$(thumb).load(function () {
					$(this).fadeIn('slow');
				}).error(function () {
					//alert(image.title);
				}).attr("src", image.thumb_url).attr("alt", i);
				$("#session_window").append(thumb);
			}
			$("#session_window > img").click(function() {
				var id = $(this).attr("alt");
				qSessions.loadImageN(id, false);
			});
			qSessions.loadSessionInfo(session_gallery);
			qSessions.loadImageN(0, true);
		});
	},	

	loadImageN: function(image_index, newLoad) {
		if(qSessions.current_image == image_index && !newLoad) return;

		var img = new Image();
		$(img).load(function () {
			qSessions.current_image = image_index;
			if( $('#session_image').length ) $("#session_window_2 #session_image").fadeOut('fast').remove();
			$("#session_window_2").append($(this)).fadeIn('fast');
			if(newLoad) $("#contextnav").show();
		}).error(function () {
			//alert("Could not find ");
		}).attr("src", qSessions.gallery_data[image_index].img_url).click(function() {qSessions.loadNextImage() }).attr("id", "session_image");
	},
	loadNextImage: function() {
		qSessions.checkSlideshow();
		qSessions.loadImageN((qSessions.current_image+1)%qSessions.gallery_data.length);
	},

	loadPreviousImage: function() {
		qSessions.checkSlideshow();
		var previous = qSessions.current_image-1;
		if(previous < 0) previous = qSessions.gallery_data.length - 1;
		qSessions.loadImageN(previous);
	},

	loadSessionInfo: function(session_gallery) {
		$.get("session_item.php", { session_gallery: session_gallery }, 
			function(data) {
				$("#session_info").html(data);
		});
	},

	startSlideshow: function() {
		$("#contextnav_play").hide();
		$("#contextnav_stop").show();
		qSessions.nextSlide();
	},

	nextSlide: function() {
		qSessions.loadImageN((qSessions.current_image+1)%qSessions.gallery_data.length);
		qSessions.slideId = setTimeout('qSessions.nextSlide()', 5000);
	},

	stopSlideshow: function() {
		clearTimeout(qSessions.slideId);
		qSessions.slideId = null;
		$("#contextnav_stop").hide();
		$("#contextnav_play").show();
	},

	checkSlideshow: function() {
		if(qSessions.slideId != null) qSessions.stopSlideshow();
	}
}