(function( $ ){
  $.fn.stcleanup = function( ) {
    if ( cleanme = this.find('img.orig') ) {
        cleanme.unwrap().siblings().removeClass('posimg');
        cleanme.remove();
    }
    return this;
  };
})( jQuery );

$( function () { 
	// slideshow
	var mainimg = $(".mainimg"),
		thumbimg = $(".thumbimg"),
		maxidx = thumbimg.size(),
		imgidx = 0,
		delay = 1600,
		hovered = false;
	function swapimg ($from, $to) {
        // stop and remove any preceding animations and clean up wrappers before starting a new one
		fref = $from.stop(true,true).stcleanup().find('img');
		tref = $to.stop(true,true).stcleanup().find('img');
		// Temporarily add relative-position div as a wrapper, so that adding the 2nd image doesn't displace the layout
		fref.addClass('orig posimg')
			.wrap('<div style="position: relative; margin: 0; padding: 0; width:' + fref.css('width') + '; height:' + fref.css('height') + ';" />')
			.parent().append('<img class="posimg" src="' + tref.attr('src') + '" width="' + fref.width() + '" height="' + fref.height() + '">');
		tref.addClass('orig posimg')
			.wrap('<div style="position: relative; margin: 0; padding: 0; width:' + tref.css('width') + '; height:' + tref.css('height') + ';" />')
			.parent().append('<img class="posimg" src="' + fref.attr('src') + '" width="' + tref.width() + '" height="' + tref.height() + '">');
		// fade out original image, and remove wrapper and positioning from new image
		fref.fadeOut(delay, function () { $from.stcleanup(); });
		tref.fadeOut(delay, function () { $to.stcleanup(); });
	}
	function startshow ( interval ) {
		interval = interval || delay; 
		$.doTimeout('slidetimer', interval , function () {
			swapimg(mainimg, thumbimg.eq(imgidx));
			imgidx++;
			if ( imgidx % maxidx == 0 ) { imgidx = 0; }
			if ( ! hovered ) { $.doTimeout('nexttimer', delay + delay, function () { startshow() }); } // wait a bit then do it again, unless being hovered
		});
	}
	startshow();
	$("#imageblock").hover(
		function () { $(this).attr({ title : "Paused"}); $.doTimeout('slidetimer'); $.doTimeout('nexttimer'); hovered = true; }, // stop all slidetimer timers, and prevent refiring if a transition is in progress
		function () { $(this).attr({ title: ""}); startshow(); hovered = false; }
	);
	$("#imageblock .thumbimg")
		.hover (
			function () { $(this).css({"cursor": "pointer"}); },
			function () { $(this).css({"cursor": "default"}); }
		)
		.click(
			function (e) {
				e.preventDefault();
				e.stopPropagation();
				swapimg(mainimg, $(this));
			}
		);
});

