//Dependencies - XMLUtils jQuery Plugin

/* for preloading images*/
jQuery.preloadImages = function() {
	var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
	for(var i = a.length -1; i >= 0; i--) {
		jQuery("<img>").attr("src", a[i]);
	}
}

$j(document).ready(function(){
	stage.init();
});

stage = function() {
	var config = {
		CSS: { container: '#FlashStage', target: 'img' },
		//XMLPath: '_Client/XML/Images.xml',
		XMLPath: '_Client/XML/Images.php',
		ImagePath: '_Client/Images/Stage/',
		switchDelay: 5000,
		fadeDelay: 1500,
		repeat: true
	};
	
	var shelf = {};
	function init(){
		shelf.container = $j(config.CSS.container);
		shelf.target = $j(config.CSS.target, shelf.container);
		shelf.images = [];
		shelf.timerFirstRun = true;
		shelf.imageCount = 0;
		
		loadImages();
	};
	
	function loadImages(){
		//Load image filenames from xml file
		$j.ajax({
		  type: "GET",
		  url: config.XMLPath,
		  dataType: "xml",
			complete: function(data){
				var json = $j.xmlToJSON(data.responseXML);
				
				for(i = 0; i < json.Image.length; i++){
					var filename = json.Image[i].Filename[0].Text;
					
					if(sanitizeFilename(filename))
						shelf.images.push(config.ImagePath + filename);
				}
				
				$j.preloadImages(shelf.images);
				
				start();
			}
		});
	};
	
	function sanitizeFilename(f){
		//Verify image filename is ok	
		return (f == '' || f == undefined) ? false : true;
	};
	
	function start(){
		//Start the image slideshow
		shelf.timer = window.setInterval(function() {
			changeImage();
		}, config.switchDelay);
	};
	
	function changeImage(){
		window.clearInterval(shelf.timer);
		
		shelf.target.fadeOut(config.fadeDelay, function()
		{
			var src = shelf.images[shelf.imageCount];
			
			var loader = new Image();
			loader.onload = function() {
				shelf.target.attr("src", src);
				
				if (shelf.imageCount < shelf.images.length - 1)
				shelf.imageCount++;
				else
					shelf.imageCount = 0;
					
				shelf.target.fadeIn(config.fadeDelay, function()
				{
					start();	
				});
			}
			
			loader.src = src;
			
		});
	};
	
	return { config: config, init: init }
	
}();
