$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: "images/flash/db/clouds.xml?v=5",
		dataType: "xml",
		success: function(xml) {
		// get children of xml weights
		var weights = $('weights', xml);
		var wxh = {};
		$(weights).find('weight').each(function(){
			var weight = $(this).attr('id');
			var size = {width: $(this).find('width').text(), height: $(this).find('height').text()};
			wxh[weight] = size;
			//console.log(weight + ": " + wxh[weight]);
		});
		
		// get children of xml items
		var itemsXML = $('items', xml);
		var items = [];
			$(itemsXML).find('item').each(function(){
				//var id = $(this).attr('id');
				var title = $(this).find('title').text();
				var weight = $(this).find('weight').attr('id');
				var width = wxh[weight].width;
				var height = wxh[weight].height;
				var thumb =  $(this).find('path').attr('src') + $(this).find('thumbnail').attr(weight);
				var url = $(this).find('url').attr('src');
				var item = {'title': title, 'weight':weight, 'thumb':thumb, 'url':url, 'width':width, 'height':height};
				//console.log("url: " + url + " thumb: " + thumb);
				items.push(item);
			});
			var inner = $('<div class="inner"/>');
			for(var i=0; i < slots.length; i++) {
				var slot = slots[i];
				// create a table for every slot container
				var table = $(template.Table());
				var tr = $(template.Row());
				$(table).append(tr);
				// assign weighted arrays to Anchor tags within a cell
				for (var row in slot) {
					
					var aSlot = slot[row];
					var td = $(template.Cell());
					
					for(var w=0; w < aSlot.length; w++) {
						//console.log("weighted slot: " + aSlot[w]);
						var splicedItem = getItemWithWeight(items, aSlot[w]);
						var a_img = $(template.A_IMG(splicedItem));
						var img = $(a_img).find('img');
						$(img).css({opacity:0});
						$(td).append( a_img);
						img.load(function() {
							$(this).animate({
								opacity: 1
							}, {duration: 1000 });
						
						});
						//console.log("td: " + td);
					}
					$(tr).append(td);
					//console.log("tr: "+ tr);
					
				}
				$(inner).append(table);
				
			}
			$('.image_cloud_html').append(inner);
			
		}
	});
});

function getItemWithWeight(items, weight) {
	for(var i=0; i < items.length; i++) {
		var item = items[i];
		if(item.weight == weight) {
			return items.splice(i, 1)[0];
		}
	}
}

var template = {
		
		Table : function() {
			return '<table valign="top"/>';
		},
		Row : function() {
			return '<tr valign="top"/>';
		},
		Cell : function() {
			return '<td/>';
		},
		A_IMG : function(item) {
			return '<a href="' + item.url + '" target="_blank"><img src="' + item.thumb + '" alt="' + item.title + '" width="' + item.width + '" height="' + item.height + '" /></a>';
		}
		
}

var slots = [{row1:["BIGGEST"], row2:["SMALL","SMALL"]}, {row1:["BIG","BIG"]}, {row1:["SMALL","SMALL","SMALL"]}, {row1:["MEDIUM","MEDIUM"]}];

