/*
	File: weldfaith-imageRandomizer.js
	Author: Philip Siedow-Thompson
	Description: Selects a random set of pictures for the Weld Faith Templates
	Requires: jquery library (1.4.2+)
*/

//define a url to a json def file to make script run
var WELDFAITHRANDOMIZER_URL = 'randomizer-images.xml';

(function() {
	//redifine for a noConflict environment just in case...
	var j$ = jQuery.noConflict();
	
	//on window load (not on ready... we want to wait for assets to load)
	j$(window).load(function() {
	
		j$.ajax({
			url: WELDFAITHRANDOMIZER_URL,
			dataType: 'xml',
			success: function(data) {
				//define and fill the library
				var imageLibrary = [];
				j$(data).find('image').each(function(index, node) {
					imageLibrary.push(j$(node).text());
				});
				
				//load the images
				j$('.randomizer').each(function(index, node) {
					if(imageLibrary.length > 0) {
						//get a random index
						var libraryIndex 
							= Math.floor(Math.random() * imageLibrary.length);
							
						//add the load handler and set the href
						j$(node).load(function() {
							j$(this).css('opacity', 0);
							j$(this).animate({opacity: 1}, 1000);
						});
						j$(node).attr('src', imageLibrary[libraryIndex]);
						
						//remove the index from the library to avoid repeat
						imageLibrary.splice(libraryIndex, 1);
					}
				});
			}
		});
	});
	
})();
