﻿iCM.RandomMedia = function() {
	// Store the master lists for rotating images
	var masterLists = {};

	// Populate a target with an image
	function PopulateItem(target, item) {
		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";
	}

	// Randomly choose a number between min and max
	function Random(min, max) {
		return Math.floor(Math.random()*(max-min))+min;
	}

	// For each target, pick an image to populate it with. Returns the list
	// of images without the chosen ones
	function ChangePanel(targets, items) {
		for (var i = 0; i < targets.length; i++) {
			PopulateItem(targets[i], items.splice(Random(0,items.length), 1)[0]);
		}
		return items;
	}

	return {
		// Randomly pick images for each of the targets. Set up a timer to do this
		// after a regular interval if a delay has been specified
		Initialise: function(id, list) {
			var newlist = ChangePanel(list.targets, list.images.slice());

			if (list.delay > 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.delay);
			}
		}
	};
}();