$(document).ready(function(){

	gallery_stopped = false;

	$(".gallery .large").live('click',function(){
	   gallery_stop();
	});

	$(".gallery li:not(.last) a").colorbox({slideshow:true, slideshowSpeed:5000});

	$(".gallery").each(function(){
		gal = $(this);
		gallery_next = $("ul li.on", this);
		gallery_start($(this), $("ul li.on", this), false);
		$("li.last a", this).click(function(){
			$(this).toggleClass("pause");
			if($(this).is(".pause")) {
				gallery_stopped = true;
				gallery_stop();
			} else {
				gallery_stopped = false;
				gallery_stop();
				gallery_start(gal, gallery_next, false);
			}
			return false;
		});
		$(".gallery li:not(.last) img[height=34]", this).live('click',function(){
			gallery_stop();
			gallery_start(gal, $(this).closest("li"), 1);
			return false;
		})
	});

});

function gallery_load_img(source, destination, callback) {
	var path = source.attr('href').replace("large", "pic");
	var imgsrc = path;
	var newimg = new Image();
	newimg.src = imgsrc;
	newimg.onload = function() {
		$("a", destination).append('<span class="large"><img src="'+imgsrc+'" width="576" height="376" alt="Preview" style="display: none;" /></span>');
		$('.large img', destination).fadeIn();
		newimg.onload = function(){};
		if($.isFunction(callback)) {
			callback.call();
		}
	}
	newimg.src = imgsrc;
}

function gallery_start(gal, obj, first) {

	if(first == 1) {
		gallery_next = obj;
		gallery_load_img($("a", obj), obj, function(){
			$("li.on .large", gal).remove();
			$("li.on", gal).removeClass("on");
			obj.addClass("on");
		});
	}

	gallery_timeout = setTimeout(function() {
		gallery_next = (obj.next("li").is(".last")) ? $("li:first", gal) : obj.next("li");
		gallery_load_img($("a", gallery_next), gallery_next,function(){
			$(obj).removeClass("on");
			$(".large", obj).remove();
			gallery_next.addClass("on");
			gallery_start(gal, gallery_next, false);
		});
		
	},7000);

}

function gallery_stop() {
	clearTimeout(gallery_timeout);
}
