//Dependencies - XMLUtils jQuery Plugin

$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: 4000,
		fadeDelay: 1000,
		repeat: true
	};
	var shelf = {};
	function init(){
		shelf.container = $j(config.CSS.container);
		shelf.target = $j(config.CSS.target,shelf.container);
		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);
				var i = 0;
				shelf.images = [];
				for(i=0;i<json.Image.length;i++){
					
					var valid = false;
					var filename = json.Image[i].Filename[0].Text;
					if(sanitizeFilename(filename) == true) { shelf.images.push(config.ImagePath + filename); }
				}
				start();
			}
		});
	};
	function sanitizeFilename(f){
		//Verify image filename is ok
		var valid = false;
		if(f == '' || f == undefined) { valid = false; } else { valid = true; }
		return valid;
	};
	function start(){
		//Start the image slideshow
		if(shelf.startTimer) { window.clearTimeout(shelf.startTimer); }
		shelf.imageCount = -1;
		shelf.startTimer = window.setTimeout(function(){ changeImage(); }, config.switchDelay);
	};
	function changeImage(){
		shelf.imageCount++;
		if(shelf.imageCount < (shelf.images.length)) {
			//Fade next image
			shelf.target.animate({opacity: 'hide'}, config.fadeDelay,function(){
				shelf.target[0].src = shelf.images[shelf.imageCount];
				shelf.target.animate({opacity: 'show'}, config.fadeDelay,function(){
					if(shelf.switchTimer) { window.clearTimeout(shelf.switchTimer); }
					shelf.switchTimer = window.setTimeout(function(){ changeImage(); }, config.switchDelay);
				});
			});
		} else {
			//If set to repeat, run repeat or stay on last slide.
			if(config.repeat == true){
				start();
			}
		}
		
	};
	return { config: config, init: init }
}();

