jQuery(document).ready(function($) {
	var $tagcloud = $('#tagcloud'),
		bodySize = parseInt($('body').css('font-size'), 10),
		RGBtoHex = function(R,G,B) {
			return toHex(R)+toHex(G)+toHex(B);
		},
		toHex = function(N) {
			if (N == null) return "00";
			N = parseInt(N, 10);
			if (N == 0 || isNaN(N)) return "00";
			N = Math.max(0,N); N = Math.min(N,255); N = Math.round(N);
			return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
		},
		getRGB = function(color) {
			var result;

			// Check if we're already dealing with an array of colors
			if ( color && color.constructor == Array && color.length == 3 )
				return color;

			// Look for rgb(num,num,num)
			if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
				return [parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10)];

			// Look for rgb(num%,num%,num%)
			if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
				return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

			// Look for #a0b1c2
			if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
				return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

			// Look for #fff
			if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
				return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

			// Otherwise, we're most likely dealing with a named color
			return colors[jQuery.trim(color).toLowerCase()];
		};
		
	if ($tagcloud.length) {
		var $tags = $('<tags></tags>'),
			attributes = {
				id: 'tagcloud'
			},
			params = {
				allowfullscreen: 'true',
				allowScriptAccess: 'always',
				menu: 'false'
			},
			flashvars = {
				distr: true,
				mode: 'tags',
				tcolor: '0x000000',
				tspeed: '50',
				hicolor: '0x000000',
				tagcloud: ''
			};
		
		$tagcloud.find('li a').each(function(index) {
			var $this = $(this),
				text = $this.text(),
				href = $this.attr('href'),
				fontSize,
				color;
			
			fontSize = parseInt($this.css('font-size'), 10) / bodySize * 10;
			
			color = getRGB($this.css('color'));
			color = '0x' + RGBtoHex(color[0], color[1], color[2]);
			
			$this.attr({
				target: '_blank',
				color: color,
				hicolor: color
			}).css({
				fontSize: fontSize,
				color: null
			});
			
			flashvars.tagcloud += "<a href='" + href + "' target='_blank' color='" + color + "' hicolor='" + color + "' style='font-size: " + fontSize + "px;'>" + text + "</a>";
			
		});
			
		flashvars.tagcloud = ("<tags>" + flashvars.tagcloud + "</tags>");
			
		swfobject.embedSWF("lib/wp-cumulus/tagcloud.swf", "tagcloud", "100%", "100%", "9.0.0","lib/swfobject/expressInstall.swf", flashvars, params, attributes);

	};
	
});

