function flashIsReady(arg) {
	aPlayers[arg].FLReady();
}

function flashToJavaScript (val) {
	if (val.func == "donePlaying") {
		if (currSng < aSongs.length-1) {
			currSng++;
		} else {
			currSng = 0;
		}
		
		loadSong(currSng);
	} else {
		aPlayers[val.shortName].FLToJavaScript(val);
	}
}

function quicktimeEventHandler(evt) {
// the plug-in has been loaded, so grab the ID of the element the browser used
//  (some use the <object> and some use the <embed>))
	var id = getTargetId(evt);
	var shortName = id.substr(0,id.indexOf('_'));
	if ((evt.type == 'qt_begin') && (!aPlayers[shortName].ready)) {	// If we're initializing for the first time
		aPlayers[shortName].QTReady(id);
	} else {
		aPlayers[shortName].QTEventHandler(evt);
	}
}

var Player = new Class({			// A Player should be inside <shortName>Player_div inside <shortName>_div

	FLVersion: false,
	QTVersion: false,
	WMVersion: false,
	dims:        { width: 1, height: 1 },
	playerDims:  { width: 1, height: 1 },
	detailsDims: { width: 1, height: 1 },
	aspectRatio: 640 / 360,
	controlBarHeight: 0,
	mode: 'x',
	retryFreq    : 100,	// milliseconds
	maxRetries   : 50,
	retryCounter : 0,
	failed       : false,
	visible: true,
	ready: false,

	initialize: function(args, flashVars, flashParams) {
		if (testMode) {
			this.dims        = { width: 300, height: 300 };
			this.playerDims  = { width: 200, height: 200 };
			this.detailsDims = { width: 200, height: 200 };
		}
		this.divId = args.divId;
		this.shortName = args.shortName;
		this.args = args;
		this.flashVars = flashVars;
		this.flashParams = flashParams;
		
		this.obj = 'x';
		this.QTTest();
		this.FLTest();
		if (testMode) {
			aObjs['dbgDiv']['main'].add ('Player shortName: ' + this.shortName + '<br /><br />' +
				   'FLVersion=' + this.FLVersion + '<br />' +
				   'QTVersion=' + this.QTVersion + '<br />' +
				   'WMVersion=' + this.WMVersion + '<br /><br />');
		}

		this.FLInit();
//		this.QTInit();
	},

	FLTest: function() {
		var ver = swfobject.getFlashPlayerVersion();
		this.FLVersion = ver.major + "." + ver.minor + "." + ver.release;
	
		if (parseInt(ver.major) >= 9) this.FLAvail = true;		// Make sure Flash player is new enough
	},
	
	FLInit: function() {
		$(this.divId).innerHTML = '<div id="noFlash' + this.shortName + '_div"><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></div>';
		
/*		alertObject (this.args);
		alertObject (this.flashVars);
		alertObject (this.flashParams);
*/		
		this.flashAttributes = { id : this.shortName + '_flash'};

		swfobject.embedSWF(this.args.flashPath,
						   "noFlash" + this.shortName + "_div",
						   this.args.flashWidth, this.args.flashHeight, this.args.flashMinVer,
						   "assets/flash/expressInstall.swf", this.flashVars, this.flashParams, this.flashAttributes);
	},
	
	FLReady: function() {
		this.obj = $(this.shortName + "_flash");		
		this.mode = 'f';
		this.controlBarHeight = 40;
		this.playerReady();
	},
	
	FLToJavaScript: function(val) {
		alert(val.func);
	},
	
	FLToActionScript: function(val) {
		this.obj.sendToActionScript(val);
	},
	
	QTTest: function () {
		if (navigator.plugins) {
			for (i=0; i < navigator.plugins.length; i++ ) {
				if (navigator.plugins[i].name.indexOf("QuickTime") >= 0) {
					this.QTAvail = true;
					this.QTVersion = navigator.plugins[i].name;
				}
			}
		}
 
		if ((navigator.appVersion.indexOf("Mac") > 0) && 
			(navigator.appName.substring(0,9) == "Microsoft") &&
			(parseInt(navigator.appVersion) < 5) ) { this.QTAvail = true; }

		this.QTTested = true;
	},
	
	QTInit: function () {
		QT_WriteOBJECT_XHTML('assets/audio/silence.mp3', '100%','100%',
							 '', 'obj#ID', this.shortName + '_qtObj', 'emb#ID', this.shortName + '_qtEmb',
							 'autoplay', 'false', 'postdomevents', 'true', 'kioskmode', 'true',
							 'scale', 'aspect');
		
		// register for events on the <object> element, our handler will be triggered even if
		//  the browser uses the <embed> because events pass through the parent element
		this.obj = $(this.shortName+'_qtObj');

		if ( null == this.obj ) {
			alert("QT plug-in not instantiated on <body> load event???");
			return;
		}

		myAddListener (this.obj, 'qt_begin',           quicktimeEventHandler, false);
		myAddListener (this.obj, 'qt_abort',           quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_canplay',         quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_canplaythrough',  quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_durationchange',  quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_ended',           quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_error',           quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_load',            quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_loadedfirstframe',quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_loadedmetadata',  quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_pause',           quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_play',            quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_progress',        quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_stalled',         quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_timechanged',     quicktimeEventHandler, false );
		myAddListener (this.obj, 'qt_volumechange',    quicktimeEventHandler, false );            
		myAddListener (this.obj, 'qt_waiting',         quicktimeEventHandler, false );
//		this.obj.addEvent('qt_play',  );
	},

	QTReady: function (id) {
		this.obj = $(id);
		this.obj.SetResetPropertiesOnReload(false);
		this.mode = 'q';
		this.controlBarHeight = 16;
		this.playerReady();
	},

	QTEventHandler: function (evt) {
		switch (evt.type) {
			case 'qt_load':
			$(this.shortName + 'DetailsStatus_div').innerHTML = 'Media has been loaded';
			break;
			
			case 'qt_pause':
			$(this.shortName + 'DetailsStatus_div').innerHTML = 'Pause';
			break;
			
			case 'qt_play':
			$(this.shortName + 'DetailsStatus_div').innerHTML = 'Play';
			break;
			
			case 'qt_timechanged':
			$(this.shortName + 'DetailsStatus_div').innerHTML = 'Time Changed';
			break;
			
			case 'qt_ended':
			$(this.shortName + 'DetailsStatus_div').innerHTML = 'End Of File Reached';
			break;
			
			default:
			$(this.shortName + 'DetailsStatus_div').innerHTML = evt.type;
			break;
		}
		
	},

	/*function callToActionscript(flashObj, str) {
		flashObj.sendToActionscript(str);
	}*/
	
	playerReady: function() {
		if (!this.ready) {
			switch (this.mode) {
				case 'f':
					aObjs['dbgDiv']['main'].add ('Flash Is Ready and id is ' + this.obj.id + '<br />');
					break;
				
				case 'q':
					aObjs['dbgDiv']['main'].add ('Quicktime is ready.  id is ' + this.obj.id +
						', this.shortName is ' + this.shortName + '<br />');
					break;
			}
//			this.hide();    SHOULD CHECK FOR A VARIABLE TO SEE IF WE SHOULD HIDE IT
			this.ready = true;
			
		} else {
			aObjs['dbgDiv']['main'].add (this.obj.id + ' was already ready.<br />');
		}
		
		if (this.args.autoHide) this.hide();
	},
	
	isReady: function(f) {
		if (this.ready) {
			this.retryCounter = 0;
			this.failed = false;
			return true;
		} else {
//			console.log(f + ': Not ready and this.retryCounter is ' + this.retryCounter);
			setTimeout ( function() {
				this.retryCounter++;
				if (this.retryCounter > this.maxRetries) {
					if (!this.failed) alert ('Player failed to load.\nPlease reload the page.');
					this.failed = true;
				} else {
					switch (f) {
						case 'load':	
							this.load (this.loadParams);
						break;
						
						case 'hide':
							this.hide();
						break;
						
						case 'show':
							this.show();
						break;
						
						default:
							alert ('Player.isReady got illegal function: ' + f);
						break;
					}
				}
			}.bind(this), this.retryFreq );
			return;
		}
	},
	
	hide: function () {
		if (this.isReady('hide')) {
			if (this.visible) {
				switch (this.mode) {
					case 'f':
	//					if (isSet(flashPlayerObj  )) flashPlayerObj.asPause();     // Remember to pause the player
	/*					$(this.shortName + 'Player_div').setStyles({'width' : '1px',				// First hide the player
																	'height' : '1px',
																	'overflow' : 'hidden' });
	*/					$(this.shortName + '_div').fade('hide');										// Then its wrapper
						break;
						
					case 'q':
						var n = this.shortName;
						setTimeout(function() {
							$(n + 'Player_div').setStyle('visibility', 'hidden');
							$(n +       '_div').setStyle('visibility', 'hidden');
						}, 100);
						break;
						
					default:
						alert ('Hiding invalid player mode: ' + this.mode);
				}
				this.visible = false;
			}
		}
	},
	
	show: function () {
		if (this.isReady('show')) {
			if (!this.visible) {
				switch (this.mode) {
					case 'f':
	/*					$(this.shortName + 'Player_div').setStyles( {'width'    : '100%',
																	 'height'   : '100%',
																	 'overflow' : 'hidden' });
	*/					$(this.shortName + '_div').fade('show');
						this.resize();
						break;
						
					case 'q':
						this.resize();
						$(this.shortName + 'Player_div').setStyle('visibility', 'visible');
						$(this.shortName +       '_div').setStyle('visibility', 'visible');
						break;
						
					default:
						alert ('Showing invalid player mode: ' + this.mode);
				}
				this.visible = true;
			}
		}
	},
	
	resize: function() {
		if (this.visible) {
			$(this.divId).setStyles (this.mainPaneDims);
		}
	},
	
	load: function(loadParams) {
		this.loadParams = loadParams;
		
		if (this.isReady('load')) {
			
	//		var newPath;
			switch (this.mode) {
				case 'f':
	//				newPath = (mediaType == 'v') ? escape('../../' + pathName + fileName) : escape(pathName + fileName);
	//				newPath = escape(pathName + fileName);
					
				setTimeout( function() {
					this.obj.asLoad (this.loadParams);
				 }.bind(this), 100 );
					
				break;
				
				case 'q':
					var newPath = escape('../../' + pathName + fileName);
		//			$('statusText_div').innerHTML += 'URL is ' + this.obj.GetURL() + '<br />';
		//			$('statusText_div').innerHTML += 'player id is ' + this.obj.id + '<br />';
		//			$('theaterDetails_div').set('html', 'GetURL: ' + this.obj.GetURL() + '<br />newPath: ' + newPath);
					this.obj.SetURL (newPath);
					break;
					
				default:
					alert ('Loading with invalid player mode: ' + this.mode);
			}
			
			aObjs['dbgDiv']['main'].add ('Loaded ' + newPath + '<br />');
		}
	},
	
	stop: function() {
		switch (this.mode) {
			case 'f':
				this.obj.asStop();
			break;
			
			case 'q':
			break;
			
			default:
		}
	},

	size_flash: function () {
		var width = Math.round(windowSize[0]/2);
		var height = Math.round(windowSize[1]/2);
		
		flashPlayer.width = width;
		flashPlayer.height = height;
		
		document.getElementById("flash_div").style.width = (width) + "px";
		document.getElementById("flash_div").style.height = (height) + "px";
		document.getElementById("apDivStatus").innerHTML = "The AP Div's dimensions are " + width + " x " + height;
	},
	
	playSong: function () {	// alertObject(nowPlaying);
		var topdir = '';
		if (useFlash) {
			setTimeout( function() {
				flashPlayerObj.asPlay(nowPlaying.songPath + nowPlaying.filename);
							 }, 100 );
		} else if (useQt) {
			if (nowPlaying.media == 'a') {
				qtPlayer.SetURL ('../../../../../' + nowPlaying.songPath + nowPlaying.filename);
				qtPlayer.SetKioskMode (true);
			} else {
				alert ('YouTube Video Playback Requires Flash');
			}
	//		qtPlayer.Play();
		}
	
	}
	
});
