(function() {
	var scripts = document.getElementsByTagName("script"),
		scriptsCt = scripts.length,
		script = null,
		src = null,
		completed = false,
		loaded = false,
		containerClass = 'cnn_evm_container_ident'
		containerClassPattern = new RegExp(containerClass, "i"),
		containerID = 'cnn_evm_container',
		playerAreaID = 'cnn_evm_playerarea',
		availableListeners = [],
		availablePollInterval = 20,
		availableInterval = null,
		availableAttempts = 0,
		availableRetries = 500,
		id = 'cnn_evm-' + Math.random();
		debug = false;
	
	log('\nexecuting...' + scriptsCt);
	for (var i=0; i < scriptsCt; i++)
	{
		script = scripts[i];
		src = script.src;
		log(src);
		if (/cnn_evm.js\?/.test(src)) {
			// only allow one player per page for now
			if (!completed && typeof TURNERPLAYER == 'undefined')
			{
				// only add the load event if there's a possibility of writing the swf to the page
				addLoadEvent(function() {
					loaded = true;
					log('page loaded...');
				});
	
				var domId = getQueryParam(src, 'domID') || containerID;
				onAvailable(domId, function(container) 
				{	
					log('onAvailable');
					if (container && !containerClassPattern.test(container.className))
					{
						log('embedding swf...');
						// add a custom class to the container so it will only be written to once
						container.className = containerClass;
						
						// append the JS used to embed and interact with the player
						addScript('http://i.cdn.turner.com/cnn/video/evm/turnerplayer-evm.js');
						// add the element to write the swf to, handle the no flash scenario
						addPlayerMarkup(container);
						
						var context = getQueryParam(src, 'context') || '';
						var size = getQueryParam(src, 'size') || '1';
						var site = getQueryParam(src, 'site') || '';
						embedSwf(context, size, site);
					}	
				}, null);
				
			}
		
			// for when we support more than one player per page...remove the script node just acted upon
			var next = script.nextSibling;
			if (next && next.nodeType == 1
				&& next.nodeName.toLowerCase() == 'noscript')
			{
				// If this script tag is immediately followed by a noscript tag, remove the noscript tag as well
				next.parentNode.removeChild(next);
				next = null;
			}
			script.parentNode.removeChild(script);
			script = null;
			log('removed script tag');
			
			// only process the first script found...let each script tag process itself
			break;
		}
	}
	
	function getQueryParam(str, param)
	{
		var a = str.substr(str.indexOf('?') + 1);
		if (a != '')
		{
			var b = a.split('&');
			for (var i=0; i < b.length; i++)
			{
				var c = b[i].split('=');	
				if (c.length && c[0] == param)
				{
					return c.length==2 ? c[1] : '';	
				}
			}
		}
		return null;
	}
	
	function addScript(src)
	{
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = src;
		var head = document.getElementsByTagName('head')[0];
		if (!head)
			return;
		// appending to the head to avoid a possible op aborted error in IE
		head.appendChild(script);
	}
	function addPlayerMarkup(container)
	{
		var markup = [
			'<div id="' + playerAreaID + '">',
				'<span id="cnn_evm_playerarea_noflash" style="display:none;">',
					'<img src="http://i.cdn.turner.com/cnn/video/evm/no.flash.graphic.gif" usemap="#cnn_evm_map" border="0"/><map name="cnn_evm_map"><area coords="80,230,240,265" href="http://get.adobe.com/flashplayer/" target="_blank"/></map>',
				'</span>',
			'</div>',
			'<img src="http://gdyn.cnn.com/1.1/1.gif" width="1" height="1"/>'
		];
		container.innerHTML = markup.join('');	
	}
	
	function embedSwf(context, size, site)
	{
		if (typeof TURNERPLAYER == 'undefined' || document.getElementById(playerAreaID) == null)
		{
			setTimeout(function() { embedSwf(context, size, site) }, 100);
			return;	
		}
		
		// If the user does not have flash installed, show the no flash message inside the div
		if (TURNERPLAYER.swfobject.getFlashPlayerVersion().major == 0)
		{
			// writing a css rule to avoid having to either wait for the DOM to be ready, or to	write the <div> string in this method
			TURNERPLAYER.swfobject.createCSS('#cnn_evm_playerarea_noflash', 'display:inline !important');
		}
		
		var width = 0,
			height = 0;
		if (size == 1)
		{
			width = '336';
			height = '391';
		}
		else
		{
			width = '320';
			height = '385';
		}
		
		var flashvars = {}; 
		flashvars.player = context;
		flashvars.site = site;

		var params = {};
		params.quality = "high";
		params.bgcolor = "#ffffff";
		params.allowFullScreen = "true"; 
		params.allowScriptAccess = "always";
		
		TURNERPLAYER.embedSWF("http://i.cdn.turner.com/cnn/video/evm/cnn_evm.swf", "cnn_evm_playerarea", width, height, "http://i.cdn.turner.com/v5cache/turnerplayer/flash/expressInstall.swf", flashvars, params);
	}
	
	function addLoadEvent(func)
	{
		var oldonload = window.onload;
		if (typeof window.onload != 'function')
		{
			window.onload = func;
		}
		else
		{
			window.onload = function()
			{
				if (oldonload)
				{
					oldonload();
				}
				func();
			}
		}
	}
	
	function onAvailable(id, cb, context)
	{
		availableListeners.push({
			id : id,
			callback : cb,
			context : context
		});
		startPolling();
		
		function startPolling()
		{
			if (availableInterval)
				return;
			availableAttempts = 0;
			availableInterval = setInterval(checkAvailability, availablePollInterval);	
			log('started polling...');
		}
		
		function stopPolling()
		{
			if (!availableInterval)
				return;
			clearInterval(availableInterval);
			availableInterval = null;
			log('stopped polling...');
		}
		
		function checkAvailability()
		{
			log('checkAvailability...')
			var el = null,
				listener = null;
				
			for (var i = 0; i < availableListeners.length; i++)
			{
				listener = availableListeners[i];
				try {
					el = document.getElementById(listener.id);
				} catch(e) {
					el = null;
				}
				
				if (el) 
				{
					listener.callback.call(listener.context, el);
					availableListeners.splice(i, 1);
					--i;
				}
			}
			
			availableAttempts++;
			if (availableListeners.length == 0
				|| loaded == true
				|| availableAttempts >= availableRetries)
				stopPolling();
		}
	}
	
	function log(s)
	{
		if (debug
			&& typeof window.console != 'undefined'
			&& window.console.log)
				console.log(id + ': ' + s);
	}
})();