$(function () {
	$("#logos").each(function () {
		$("#logos").html("<ul>"+(new Array(10).join("<li></li>"))+"</ul>")
		var available = []

		$.get("/informia_logoRotation.xml", function (xml) {
			$(xml).find("logo").each(function () {
				var img = $(this).attr("img"), href = $(this).attr("logoURL")
				if (img) {
					var html = '<img src="'+img+'" alt="" />'
					if (href) {
						html = '<a href="'+href+'">'+html+'</a>'
					} else {
						html = '<span>'+html+'</span>'
					}
					available.push(html)
				}
			});

			(function refresh() {
				var q = $("#logos")
				var notAvailable = []

				$("#logos li:not(:empty)").each(function () {
					var slot = $(this)
					q.queue("logos", function () {
						notAvailable.push(slot.html())
						slot.contents().fadeOut(300)
						q.dequeue("logos")
					})
					q.delay(200, "logos")
				})

				$("#logos li").each(function () {
					var slot = $(this)
					q.queue("logos", function () {
						if (available.length > 0) {
							var r = Math.floor(Math.random() * available.length)
							slot.html(available[r])
							slot.contents().hide().fadeIn(300)
							available.splice(r, 1)
						}
						q.dequeue("logos")
					})
					q.delay(200, "logos")
				})

				q.queue("logos", function () {
					available = available.concat(notAvailable)
					notAvailable = []
					setTimeout(refresh, 1000)
				})
				q.dequeue("logos")
			})();
		})
	})
});

