/*	unFocusFlashCommunicator, version 0.7 (alpha) (2005/09/13)
	Copyright: 2005, Kevin Newman (http://www.unfocus.com/)
	License: http://creativecommons.org/licenses/LGPL/2.1/ */
// set up function for IE to use to create the fscommand catcher
if (typeof ActiveXObject != 'undefined' && window.print)
	// unFocusFlashCommunicator.vbs
	document.write('<scr'+'ipt type="text/vbscript"\>Sub unFocusCreateFSCommand (n)\nExecuteGlobal "Sub " & n & ',
		'"_FSCommand(ByVal c, ByVal a):" & "call " & n & "_','DoFSCommand(c, a):" & "End Sub"\nEnd Sub</scr'+'ipt\>');


if (typeof com == 'undefined') var com = {};
if (!com.unFocus) com.unFocus = {};
if (!com.unFocus.Flash) com.unFocus.Flash = {};

com.unFocus.Flash.Communicator = function($id) {
	var $movieObj;
	/* provides reference for methods attatched to other objects 
	(like _CatchFSCommand) it will compress well too ;-) */
	var $self = this; 
	this.useFlashScripting = false; // for debugging
	var _comDiv;
	var _connId;
	//var _handlers = [];
	
	/**
	 * Tries to get a reference to the flash element
	 */
	function _GetFlashReference() {
		/* check embeds first, in case the regular html is used, in which case id would 
		return a reference to the object tag */
		if (document.embeds && document.embeds[$id])
			$movieObj = document.embeds[$id];
		if (!$movieObj && document.getElementById)
			$movieObj = document.getElementById($id);
		//return !!$movieObj; // return bool
	};
	
	/***********************************
	* Set up FSCommand catch functions *
	***********************************/
	/* catch, and route fscommand calls.
	:NOTE: "this" is scoped to window, so use the $self ref */
	function _RouteFSCommand($command, $arguments) {
		;;; trace('DoFSCommand called: ' + $command + ':' + $arguments);
		// do the command
		switch ($command) {
			case 'unFocusFlashTestFSCommand':
				/* get reference to the flash Object */
				if (!$movieObj) _GetFlashReference();
				// if we are here, then fscommand works!
				$self.SetVariable('unFocusCommunication','useFSCommand');
				break;
			case 'unFocusFlashSetConnID':
				_connId = $arguments;
				break;
			default:
				// call user's DoFSCommand
				//_DoFSCommand($command, $arguments);
				$self.DoFSCommand($command, $arguments);
		}
	};
	// these all route to _RouteFSCommand
	window[$id + '_'+'DoFSCommand'] = _RouteFSCommand;
	// catch function for IE
	if (typeof ActiveXObject != 'undefined' && window.print) unFocusCreateFSCommand($id);
	
	// to be overwritten by the user
	$self.DoFSCommand = new Function;
	
	/*function _DoFSCommand($command, $arguments) {
		for (var i = _handlers.length; -1 > --i;) {
			alert('success');
		}
		alert('end');
	};
	
	$self.AddFSCommandHandler = function($handler) {
		_handlers[_handlers.length] = $handler;
	};*/
	
	function trace($message) {
		var $elm = document.getElementById('unFocusFlashOutput');
		if ($elm) $elm.innerHTML = $message + '<br />' + $elm.innerHTML;
	};
	/************************************
	* Flash scripting emulation methods *
	************************************/
	// http://www.macromedia.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html
	/*
	//methods that return values will get call back functions instead (since it's asyncronous)
	GetVariable( varName )
	GotoFrame( frameNumber ) 
	IsPlaying()
	LoadMovie( layerNumber, url ) 
	Pan ( x, y, mode ) 
	PercentLoaded() 
	Play()
	Rewind()
	SetVariable( variableName, value )
	SetZoomRect ( left, top, right, bottom )
	StopPlay()
	TotalFrames()
	Zoom( percent )
	
	$self.TCallFrame( target, frameNumber )
	$self.TCallLabel( target, label )
	$self.TCurrentFrame( target )
	$self.TCurrentLabel( target )
	$self.TGetProperty( target, property )
	$self.TGetPropertyAsNumber ( target, property )
	$self.TGotoFrame( target, frameNumber )
	$self.TGotoLabel( target, label )
	$self.TPlay( target )
	$self.TSetProperty( target, property, value )
	$self.TStopPlay( target )
	
	
	*/
	
	$self.SetVariable = function($name, $value) {
		if (!$movieObj) _GetFlashReference();
		if (typeof $movieObj.SetVariable == 'function' || typeof ActiveXObject != 'undefined') {
			// overwrite the emulated (default) SetVariable function
			$self.SetVariable = function($name, $value) {
				;;; trace('SetVariable (native): '+$name+'='+$value);
				$movieObj.SetVariable($name, $value);
			};
			// first call
			$self.SetVariable($name, $value);
		// check _connId - if there is none, then the following will not work
		} else if (_connId) {
			///// do setup ...
			// create the div to hold the communication flash movie
			// :TODO: make sure this will not kill a page that hasn't finished loading yet
			if (!document.getElementById('unFocusFlashCommunicator')) { // in case user sets it up manually
				var _comDiv = document.createElement('div');
				_comDiv.id = 'unFocusFlashCommunicator';
				//_comDiv.style.position = 'absolute';
				//_comDiv.style.top = '-900px';
				//$historyFrame.runtimeStyle.display = 'none';
				document.body.appendChild(_comDiv);
			}
			
			// get swf file's url
			/*var $scripts = document.getElementsByTagName('script');
			
			for (var i = $scripts.length; i--;) {
				if ($scripts[i].src.indexOf('unFocusFlashCommunicator.js') != -1) {
					var $script = $scripts[i].src;
					var $swf = $script.slice(0, $script.lastIndexOf("/") + 1) + 'unFocusFlashCommunicator.swf';
					break;
				}
			}*/
			
			// set up the html object to reuse for sending in the data
			var $element = new unFocusFlashHTML();
			$element.SetSrc(this.communicatorSWF);
			$element.SetWidth(1);
			$element.SetHeight(1);
			$element.SetMajorVersion('6');
			$element.SetMinorVersion('29');
			$element.SetAllowscriptaccess('always');
			
			///// overwrite the original function:
			$self.SetVariable = function($name, $value) {
				// :NOTE: this cannot be used until the receiving flash movie passes out the connectionID
				// do localconnection thingy
				;;; trace('SetVariable (emulated): '+$name+'='+$value);
				
				$element.SetFlashvars('cid='+_connId+'&cmd=SetVariable&vName='+$name+'&vValue='+$value);
				
				_comDiv.innerHTML = $element;
			};
			// first call
			$self.SetVariable($name, $value);
		}/* else {
			// :TODO: either throw an exception, or add to a queue
		}*/
	};
};

// make sure the namespace is available before adding to it
if (!com.unFocus.util) com.unFocus.util = {};
/**
 * Gets the path of the script that is passed in, or of the last script in the array
 *
 * @param scriptObj - the script dom object ref
 */
com.unFocus.util.getScriptPath = function($scriptObj) {// still needs work...
	// if no scriptObj is passed in, get the last one from the bunch
	if (!scriptObj) {
		$scriptObj = document.getElementsByTagName('script');
		$scriptObj = $scriptObj[$scriptObj.length];
	}
	return $scriptObj.src.slice(0, $scriptObj.src.lastIndexOf("/") + 1);
};
com.unFocus.Flash.Communicator.prototype.communicatorSWF = com.unFocus.util.getScriptPath() + 'unFocusFlashCommunicator.swf';
