var triggerCache = null;
var jsReady = false;
var swfReady = false;

/**
 * Send a new clip to the SWF for placement on the clipboard.
 * @param	clipTargetId	String DOM ID of clip container
 */
function getClipContents(clipTargetId)
{	
	clipEl = document.getElementById(clipTargetId);
	
	if (clipEl)
	{
		if(clipEl.type=='text'||clipEl.type=='hidden')
		{
			clipContents = clipEl.value;
		}
		else
		{
			clipContents = clipEl.innerHTML;
		}

		return clipContents;
	}
	else
	{
		//console.log('No DOM element with id '+clipTargetId+' found');
	}
}

/**
 * Handle errors thrown from SWF
 */
function swfError(msg)
{
	//alert(msg);
	//console.log('SWF Error: '+msg);
}

/**
 * Initialize clipStation functinality
 * Embeds SWF, adds event listeners on clipTriggers
 */
function clipstationInit()
{
	triggerCache = new Array();
	allAArr = document.getElementsByTagName('DIV');
	for(i=0;i<allAArr.length;i++)
	{
		currId = allAArr[i].id;
		if (currId.substring(0,12) == "clipTrigger_")
		{				
			triggerId = allAArr[i].id;
			clipTargetId = triggerId.substring(12, triggerId.length);
			decode = (allAArr[i].rel=='decode') ? 'true':'false';
			
			soId = "cs"+i;
			
			var soId = new SWFObject('flash/clipstation.swf','cs'+i,'112','16','9');

			soId.addParam('allowfullscreen','false');
			soId.addParam('allowscriptaccess','always');
			soId.addParam('wmode','opaque');
			soId.addParam('flashvars','clipId='+clipTargetId+'&decode='+decode);
			soId.write(allAArr[i].id);
		}
	}

	jsReady = true;
}

/**
 * Called by SWF, returns out init complete flag
 * @return jsReady flag
 */
function jsIsReady()
{
	return jsReady;
	//console.log('jsIsReady called');
}

/**
 * Called by SWF, sets SWF ready flag, calls function to enable clipTriggers
 */
function setSWFIsReady()
{
	swfReady = true;
	//console.log('setSWFIsReady called');
}

/**
 * Add an onload function to the document, keeps existing onLoad functions
 * @param fn Function reference to function to execute onLoad
 */
function addLoadEvent(fn)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = fn;
	} else {
		window.onload = function()
		{
			if (oldonload)
			{
				oldonload();
			}
			fn();
		}
	}
}

addLoadEvent(clipstationInit);