/**
 * SWFEngine - Flash + Javascript Browser Integration Tool
 * 
 * Copyright 2008 by Factory Design Labs, All Rights Reserved.
 * <a href="http://www.factorylabs.com/">www.factorylabs.com</a>
 * 
 * @author Grant Davis
 * @version 1.0 :: May 28, 2008
 * @version 1.1 :: June 26, 2008
 * @version 1.2 :: August 25, 2008
 * @version 1.3 :: October 1, 2008
 */

/* Test Functions ......................................................................................*/

var pagesTracked = 0;
function trackPage( pagename )
{
//	alert( "Tracking: \n\t" + pagename );
	pagesTracked++;
}

/**
 * Testing method here for ensuring tracking calls or other
 * javascript calls are making it to the page.
 */
function test( arg1, arg2 )
{
	alert( "swfengine.js :: test() \n\t tracked pages: " + pagesTracked + "\n\t\targ1: " + arg1 + "\n\t\targ2: " + arg2 );
}

/* Object Definition ......................................................................................*/

/**
 * Creates a new SWFEngine object. 
 * 
 * @param url				String value of the location of the SWF to embed.
 * @param id				String value of the element ID on the HTML page to write the flash object to. 
 * @param w					Number value of the width of the embedded SWF.
 * @param h					Number value of the height of the embedded SWF.
 * @param version			String value of the minimum version required to view the SWF.
 * @param expressInstall	[Optional] String value of the url of the ExpressInstall SWF to seamlessly upgrade a user's Flash version.
 * @param varsObj			[Optional] Object containing name value pairs to send to the SWF object. aka FlashVars
 * @param paramObj			[Optional] Object containing name value pairs to apply to the embedded Flash object.
 * @param attObj			[Optional] Object containing name value pairs to define the attributes of the embedded Flash object.
 * @param swfFit			[Optional] Boolean flag which determines if SWFFit is used to size the Flash Object. Defaults to false.
 */
function SWFEngine( url, id, version, expressInstall, size, varsObj, paramObj, attObj, swfFit )
{
	this.swfUrl = url;
	this.elementId = id;
	this.swfVersion = version;
	this.dimensions = SWFEngine.checkObject( size );
	this.flashvarsObj = SWFEngine.checkObject( varsObj );
	this.parametersObj = SWFEngine.checkObject( paramObj );
	this.attributeObj = SWFEngine.checkObject( attObj );
	this.useSwfFit = ( swfFit == undefined ) ? false : swfFit;
	
	// Hook for Internet Explorer. 
	// This writes the "moviename_DoFScommand" javascript event to forward fscommand calls to a javascript handler function. 
	if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) 
	{
		document.write('<script type="text/javascript" event="FSCommand(command,args)" for="'+this.attributeObj.id+'"> \n');
		document.write('SWFEngine.handleFSCommand(command, args);');
		document.write('</script>');
	}
	
	/**
	 * 
	 */
	this.createSWF = function( url, id, version, expressInstall )
	{
		// don't proceed if the user doesn't have the version we want. 
		if ( !swfobject.hasFlashPlayerVersion( version )) return;
		
		// create a unique id for the new flash player object 
		var instanceId = SWFEngine.getRandomSeed();
		
		// store the instance ID in flash vars so Flash knows what instance of SWFEngine its associated with. 
		this.flashvarsObj[ "swfEngineId" ] = instanceId;
	
		// add url variables to the vars object.
		this.flashvarsObj = SWFEngine.addUrlVariables( this.flashvarsObj );
	
		// put instance id into local storage.
		SWFEngine.instances[ instanceId ] = this;
		
		// write the Flash object to the page
		swfobject.embedSWF( url, id, this.dimensions.maxWidth, this.dimensions.maxHeight, version, expressInstall, this.flashvarsObj, this.parametersObj, this.attributeObj );
	}
	
	/**
	 * 
	 */
	this.resizeSWF = function( minWidth, minHeight, maxWidth, maxHeight, center )
	{
		// don't resize this object if we're set to not use SWFFit. 
		if ( this.useSwfFit == false ) return;
		
		swffit( this.attributeObj.id, minWidth, minHeight, maxWidth, maxHeight, center );
	}
	
	/**
	 * 
	 */
	this.setBookmark = function( title, url )
	{
		if ( window.sidebar ) window.sidebar.addPanel( title, url, '' );
		else if( window.external ) window.external.AddFavorite( url, title);
		else if( window.opera && window.print ) return true;
		else prompt( 'Create a bookmark and use this URL', url);
	}
	
	/**
	 * Using the passed arugments in the "constructor", create the new flash object.
	 */
	this.createSWF( url, id, version, expressInstall );
}

/* Static Properties  ......................................................................................*/
/**
 * Flag which indicates if SWFEngine has been initialized.
 * Static property.
 */
SWFEngine.initialized = false;

/**
 * Object which stores a reference to all SWFEngines created.
 */
SWFEngine.instances = new Object();

/* Static Methods ......................................................................................*/

/**
 * @return The instance associated with the supplied id. 
 */
SWFEngine.getInstance = function( id )
{
	return SWFEngine.instances[ id ];
}

/**
 * Static initializer.
 */
SWFEngine.init = function()
{
	// don't init if we've already done so. 
	if ( SWFEngine.initialized == true ) return;
	SWFEngine.initialized = true;
	
	// include the scripts we need for the page.
//	this._includeScript( 'javascripts/swfaddress-optimizer.js' );  // this script seems to cause JS errors on pages. Not optimized enuff, or maybe too much!
	this.includeScript( 'site/javascripts/swfobject.js' );
//	this.includeScript( 'javascripts/swfaddress.js' );
//	this.includeScript( 'javascripts/swffit.js' );
//	this.includeScript( 'javascripts/swfmacmousewheel2.js' );
}

/**
 * Dynamically includes other required javascript files.
 * @see http://www.chapter31.com/2006/12/07/including-js-files-from-within-js-files/
 */
SWFEngine.includeScript = function( path )
{
	document.write( '<script type="text/javascript" src="' + path + '"></script>' );
}

/**
 * Utility method to see if an object is undefined. If so, returns a new object.
 */
SWFEngine.checkObject = function( obj )
{
	if ( obj == undefined ) return new Object();
	else return obj;
}

/**
 * Generates a unique seed for the SWFEngine instance. 
 * @return A unique number identifing the SWFEngine instance.
 */
SWFEngine.getRandomSeed = function()
{
	var seed = SWFEngine.generateSeed();
	while( SWFEngine.getInstance( seed ) != undefined )
	{
		seed = SWFEngine.generateSeed();
	}
	return seed;
}

/**
 * @return A random number between 0-100000.
 */
SWFEngine.generateSeed = function()
{
	return Math.round( Math.random() * 100000 );
}

/**
 * Adds any variables specified in the URL to flash vars. 
 */
SWFEngine.addUrlVariables = function( obj )
{
	var url = document.location.href;
	var values = url.substring( url.indexOf( "?" )+1, url.length ).split( "&" );
	
	for( var i=0; i < values.length; i++ )
	{
		var valuePair = values[ i ];
		var varName = valuePair.substring( 0, valuePair.indexOf( "=" ));
		var varValue = valuePair.substring( valuePair.indexOf( "=" )+1, valuePair.length );
		obj[ varName ] = varValue;
	}
	return obj
}

/**
 * Evalutes formatted functions calls sent using FSCommand from flash. 
 */
SWFEngine.handleFSCommand = function( command )
{
	eval( command );
}

/**
 * Initialize the engine.
 */
SWFEngine.init();


