/* 		An <img> gets converted to:
 *
 *  	<div id="uniqueid">
 *  		<img (original, now hidden)>
 *  		<img id="uniqueid_a">
 *  		<img id="uniqueid_b">
 *  	</div>
 */

/* Automatically search through HTML images for any images that we want to
 * rotate.  If we find them, schedule rotation events.
 */
//$(document).ready(function(){
$(window).bind('load', function() {
    $('img[rotate]').each(function() {
		/* Make sure every element has an ID */
		var img_id = $(this).attr('id');
		
		if(!img_id) {
			img_id = generateID();
			$(this).attr('id', img_id);
		}
		
		prepareImageSwap(img_id);
    });
});


function prepareImageSwap(img_id)
{
	var default_delay = 3; //seconds
	
	var wrapper_id = generateID();
	var frontimg_id = generateID();
	var backimg_id = generateID();
	
	/* Add our custom elements to the DOM */
	$('#' + img_id).wrap("<div id='" + wrapper_id + "'></div>");
	$('#' + wrapper_id).append("<img id='" + frontimg_id + "'>");
	$('#' + wrapper_id).append("<img id='" + backimg_id + "'>");
	
	var src = $('#' + img_id).attr('src');
	
	/* Check for a rotation delay.  If it does not exist, we'll use the default */
    var delay = parseInt($('#' + img_id).attr('delay'), 0);
    if(!delay || delay <= 0 || delay > 999) {
        delay = default_delay;
    }
	
	/* Configure our wrapper */
	$('#' + wrapper_id).height('100%');
	$('#' + wrapper_id).width('100%');
	$('#' + wrapper_id).css('position', 'relative');
	$('#' + wrapper_id).attr('frontimg_id', frontimg_id);
	$('#' + wrapper_id).attr('backimg_id', backimg_id);
	$('#' + wrapper_id).attr('counter', "0");
	$('#' + wrapper_id).attr('delay', delay);
	//$('#' + wrapper_id).css('border', '1px solid blue');
	$('#' + wrapper_id).css('margin', 'auto');
	$('#' + wrapper_id).attr('rotate', $('#' + img_id).attr('src') + ',' + $('#' + img_id).attr('rotate'));
	
	/* Configure our front image */
	$('#' + frontimg_id).attr('src', src);
	$('#' + frontimg_id).css('position', 'absolute');
	//$('#' + frontimg_id).css('border', '1px solid green');
	$('#' + frontimg_id).css('top', '0px');
	$('#' + frontimg_id).css('left', '0px');
	$('#' + frontimg_id).css('z-index', '0');

	
	/* Configure our back image */
	$('#' + backimg_id).attr('src', src);
	$('#' + backimg_id).css('position', 'absolute');
	//$('#' + backimg_id).css('border', '1px solid green');
	$('#' + backimg_id).css('top', '0px');
	$('#' + backimg_id).css('left', '0px');
	$('#' + backimg_id).css('z-index', '-1');
	
	$('#' + img_id).hide();
	$('#' + backimg_id).hide();
	
	/* Preload our images */
	preloadImages($('#' + img_id).attr('rotate'));
	
	window.setTimeout("performImageSwap('" + wrapper_id + "')", 0);
}

function performImageSwap(wrapper_id)
{
	/* Retrieve our element id's */
	var frontimg_id = $('#' + wrapper_id).attr('frontimg_id');
	var backimg_id = $('#' + wrapper_id).attr('backimg_id');
	
	/* Retrieve any other needed attributes */
	var delay = $('#' + wrapper_id).attr('delay');

	//$('#' + backimg_id).css('left', ($('#' + wrapper_id).width() - $('#' + backimg_id).width())/2);
	
	/* Perform the actual transition */
	//$('#' + frontimg_id).fadeOut('slow');
	$('#' + backimg_id).fadeIn('slow', function() {
		$('#' + frontimg_id).hide();
		
		/* Load the next image */
		var counter = parseInt($('#' + wrapper_id).attr('counter'));
		var img_array = parseCommaSeparatedArray($('#' + wrapper_id).attr('rotate'));
		
		if(++counter >= img_array.length) {
			counter = 0;
		}
		
		$('#' + frontimg_id).attr('src', img_array[counter]);
		//$('#' + frontimg_id).load(function() {
		//    $(this).unbind('load');
    	//   $('#' + frontimg_id).css('width', $(this).width());
    	//   $('#' + frontimg_id).css('height', $(this).height());
    	//});
		$('#' + wrapper_id).attr('counter', "" +  counter);
	});
	
	/* Swap the z-indices of the front and back images */
	$('#' + frontimg_id).css('z-index', '0');
	$('#' + backimg_id).css('z-index', '1');
	
	/* Swap the "pointers" in our wrapper */
	$('#' + wrapper_id).attr('frontimg_id', backimg_id);
	$('#' + wrapper_id).attr('backimg_id', frontimg_id);
	
	window.setTimeout("performImageSwap('" + wrapper_id + "')", delay * 1000);
}

/* Breaks a comma-separated list of items into a javascript array.
 * TODO: Removes any leading or trailing whitespace.
 */
function parseCommaSeparatedArray(str)
{
	return (str.split(','));
}

/* Preloads an image or a comma separated list of images */
function preloadImages(src_array)
{
	var img_array = parseCommaSeparatedArray(src_array);
	for(i = 0; i < img_array.length; i++) {
		var img = new Image;
		img.src = img_array[i];
	}
}

/* Function to (hopefully) generate a unique ID.  Makes sure that nothing
 * can inadvertently modify the ID variable being generated externally.
 */
var generateID = (function() {
    var lastID = 0;
    return function() {
        return ('uid_' + lastID++);
    }
})();
