﻿var imgSrcs = [];
var curSrc = 0;

var imgElems;
var curElem = 0;

var fadeSpeed;
var imageTimeout;

function img(src, alt){
this.src = src;
this.alt = alt;
}

jQuery.fn.bannerrotator = function(xmlFile, settings)
{
	var banner = this;
	settings = jQuery.extend({
		fade: 5000,
		timeout: 10000
	}, settings);

	fadeSpeed = settings.fade;
	imageTimeout = settings.timeout;

	// load image sources
	$.get(xmlFile, function(xml)
	{
		var i = 0;
		$(xml).find('image').each(function()
		{
			imgSrcs[i++] = new img($(this).attr('src'), $(this).attr('alt'));
		});

		// make sure there are at least 2 elements
		if (imgSrcs.length < 2) return;

		// only create element if it's not already there
		if (banner.length == 1) banner.append(document.createElement('img'));

		// get array of image elements to swap
		imgElems = $('img', banner);

		// start toggling!
		toggle();
	});
};
	
function toggle()
{
	// move to next image
	if (++curSrc >= imgSrcs.length) curSrc = 0;

	// grab ref to elements for updating
	var frontImg = imgElems[curElem];
	if (++curElem > 1) curElem = 0;
	var backImg = imgElems[curElem];
		
	// set current image to hide next
	frontImg.className = "";
	frontImg.removeAttribute('style');

	// prepare to swap image
	backImg.className = "show";
	backImg.src = imgSrcs[curSrc].src;
	backImg.alt = imgSrcs[curSrc].alt;

	// fade in next image and repeat
	setTimeout(function() { $('.show').fadeIn(fadeSpeed, toggle); }, imageTimeout);	
}
