﻿iCM.ImageRotator = function() {
	// Store the master lists for rotating images
	var masterLists = {};

	// Populate a target with an image
	function PopulateItem(target, item) {
		try {		
			Ext.get(target.image).dom.src = item.image;
			Ext.get(target.image).dom.alt = item.altText;
			Ext.get(target.imageLink).dom.href = item.link;
			Ext.get(target.text).dom.innerHTML = item.description;
			Ext.get(target.textLink).dom.href = item.link;
			if (Ext.get(target.wrap))
				Ext.get(target.wrap).dom.style.width = item.width + "px";
		}
		catch(err) {
		}
	}

	// For each target, pick an image to populate it with. Returns the list
	// of images without the chosen ones
	function ChangePanel(targets, items) {
		var i = 0;
		while (i < targets.length) {
			PopulateItem(targets[i], items.splice(i, 1)[0]);
			i++;	
		}
		return items;
	}

	return {
		// Randomly pick images for each of the targets. Set up a timer to do this
		// after if a regular interval has been specified
		Initialise: function(id, list) {
			var newlist = ChangePanel(list.targets, list.images.slice());

			if (list.interval > 0 && list.images >= list.targets) {
				masterLists[list.targets] = list.images.slice();

				var callback = function() {
				    //If there's not enough images, refresh the list with the master list
					if (newlist.length < list.targets.length) {
						newlist = masterLists[list.targets].slice();
					}
					newlist = ChangePanel(list.targets, newlist);
				}
				window.setInterval(callback, list.interval);
			}
		}
	};
}();