/**
*   flash.js writes flash and automatically detects flash version
*	Adapted from write_swf and plugins js
*   compatible: ns6+, ie4+
*	requires: no requirement but default page and 
*   default flash version should be set in settings.js
*	@author: David Burton
*	$Id: flash.js,v 1.0 2006/13/11 12:42:37 jonh Exp $
*/
var alerted=false;//variable to flag alert so that they only get one

function write_swf(){
	var version=CTAD_SETTINGS['minimum_flash_version'];
	if (!version)version=7; //default to version 7 if the variable is unset
	 var x = new pluginDetect(); 
 if (x.isPlugin("ShockwaveFlash.ShockwaveFlash."+version,"Shockwave Flash "+version)){		
		document.write(ObjectTag(write_swf.arguments[0],write_swf.arguments[1],write_swf.arguments[2],write_swf.arguments[3]));			// if we've detected an acceptable version
	} else {  
		var page=CTAD_SETTINGS['flash_download_page'];
		//default to web if variable is unset
		if(!page)page='https://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash';
		// flash is too old or we can't detect the plugin
		var msg="You need to install Flash Player to view some of the \ncontent on this page. \n\nWould you like to install it now? \n\nNOTE: Once Flash Player is installed you \nshould close all browser windows and start again."
		if(!alerted && confirm(msg)){
			window.open(page);
		}
		alerted=true;
			// Edit by Kris Harmer - If you need to explicitly set the path to "flashdownloadbutton.gif" you can set the variable "flashdownloadbuttonpath" in the relevant document; otherwise the default is used.
			if (undefined===window.flashdownloadbuttonpath) {
				document.write('<a href="'+page+'" target="_blank"><img src="../images/flashdownloadbutton.gif" border="0" alt="Download Flash player!"><\/a>');
			}else{
				document.write('<a href="'+page+'" target="_blank"><img src="'+flashdownloadbuttonpath+'" border="0" alt="Download Flash player!"><\/a>');
			}
	}	

};
function write_swf_ret(){
		return ObjectTag(write_swf_ret.arguments[0],write_swf_ret.arguments[1],write_swf_ret.arguments[2],write_swf_ret.arguments[3]);
};

function ObjectTag(){
	
	_a = ObjectTag.arguments;
	_b = new Array();
	_b['id'] = '';
	_b['width']= '100%';
	_b['height'] = '100%';
	_b['vspace'] = '';
	_b['hspace'] = '';
	_b['align']	= '';
	_b['id'] = '';
	_b['bgcolor'] = (document.bgColorFlash != null) ? document.bgColorFlash : "#8b80bc";
	_b['quality'] = 'high';
	
	if (!_a[3]){
		_b['wmode']='window';
	}
	
	_c = (_a[1]) ? _a[1].split(',') : new Array();
	
	for(i = 0; i< _c.length; i++){
		_d = _c[i].split('=');
		_b[_d[0].replace(' ','')] = _d[1].replace(' ','');
	}
	
	if(_a[2] ) {
		_e = _a[2].split('&');
		_e = _e.join('&',escape(_e));
	} else {
		_e = '';
	}
	//if it isn't a colour, look for a class with that name
	if(_b['bgcolor'].substr(0,1)!="#")_b['bgcolor']=flashColor(_b['bgcolor']);
	if(!_b['bgcolor'])_b['bgcolor']="#8b80bc";
	
	swf_tag = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+_b['width']+'" height="'+_b['height']+'" vspace="'+_b['vspace']+'" hspace="'+_b['hspace']+'" align="'+_b['align']+'" id="'+_b['id']+'"><param name="movie" value="'+_a[0]+'"><param name="AllowScriptAccess" value="true"><param name="quality" value="'+_b['quality']+'"><param name="menu" value="false"><param name="bgcolor" value="'+_b['bgcolor']+'"><param name="wmode" value="'+_b['wmode']+'"><param name="FlashVars" value="'+_e +'"><embed src="'+_a[0]+'" width="'+_b['width']+'" height="'+_b['height']+'" vspace="'+_b['vspace']+'" hspace="'+_b['hspace']+'" align="'+_b['align']+'" quality="'+_b['quality']+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"  name="'+_b['id']+'" bgcolor="'+_b['bgcolor']+'" wmode="'+_b['wmode']+'" flashvars="'+_e+'" AllowScriptAccess="true" menu="false" /></object>';
	
	return swf_tag; 
}
//function to read style from the stylesheet
function get_style(selector,style_attribute){

	if (!document.styleSheets){
		return (false);
	}
	for (var ss = 0; ss < document.styleSheets.length; ss++){
	     var tss = document.styleSheets[ss];
		if (!tss.cssRules){
			tss.cssRules = tss.rules;
		}	
	    for (var ru = 0; ru < tss.cssRules.length; ru++){
			if (typeof(tss.cssRules[ru].selectorText) != "undefined"){
				_match = new RegExp(selector,"gi"); 
				if (tss.cssRules[ru].selectorText.match(_match)) { 
					if (typeof(tss.cssRules[ru].style[style_attribute])!="undefined"){
						return (tss.cssRules[ru].style[style_attribute]);
					}	
				}				
			}		
		}
	}
	return(false);
}

//decimal to hexadecimal convertor for netscape
function decToHex(dec)
{
var hexStr = "0123456789ABCDEF";
var low = dec % 16;
var high = (dec - low)/16;
hex = "" + hexStr.charAt(high) + hexStr.charAt(low);
return hex;
}


//Function to return the background color of a class in a stylesheet
function flashColor(clas)
{
	var rgb=get_div_color(clas);
	if(!rgb)return false;
	//test for RGB or Hex
	if (rgb.substr(0, 3) == 'rgb'){
		rgb = rgb.replace(/rgb\(/g, "").replace(/\)/g, "");
		var rgbsplit=rgb.split(', ');
		return '#'+decToHex(rgbsplit[0])+decToHex(rgbsplit[1])+decToHex(rgbsplit[2]);
	}
	else return rgb;
}

//style from div itself
function get_div_color(clas){
		document.write('<div id="temp_flash" class="'+clas+'" style="display:none;">&nbsp;<\/div>');
		var temp_div=document.getElementById('temp_flash');
		var bgflash='';
		if(window.getComputedStyle)bgflash=window.getComputedStyle(temp_div, null).getPropertyValue("background-color");
		else if(temp_div.currentStyle)bgflash=temp_div.currentStyle.backgroundColor;
		else bgflash=get_style('.'+clas,'backgroundColor');
		temp_div.parentNode.removeChild(temp_div);
		return bgflash;
}

function FlashFix()
{
}

// fix flashy instances.. 
FlashFix.install = function() 
{ 
	var o = document.getElementsByTagName("object");
	
	for (var i = 0; i < o.length; i++) {
		var obj = o[i]; 
		
		// embed tag holds flashvars where as param doesn't 
		// see alert(obj.outerHTML)
		if (obj.outerHTML) {
			fv = obj.outerHTML.match(/flashvars="(.[^"]+)/i)[1]; 
			
			fv = fv.replace(/autoplay=1/i,"");
			
			//alert(fv); 
		
			// copy outer html on outerhtml 
			obj.outerHTML = obj.outerHTML.replace(/name="flashvars"\svalue=""/i,"NAME=\"FlashVars\" VALUE=\"" + fv+ "\""); 
		
		}
		

	}

}

/* uncomment this line to enable flashfixing */
//event_install(window,"onload", FlashFix.install); 




/** 
* Object which holds all the functions which are detecting plugins 
* 
* usage: 
* <pre>
* var x = new pluginDetect(); 
* 
* if (x.isPlugin("ShockwaveFlash.ShockwaveFlash.7","Shockwave Flash 7.0")) { 
* 	document.write("flash found.. flash developers are happy!\n"); 
* }
*
* if (x.isPlugin("MediaPlayer.MediaPlayer","Windows Media Player")) { 
*	document.write("media player found.. let's watch a movie?\n"); 
* }
* </pre>
* 
*/ 
function pluginDetect() { 
	this.IE =  (navigator.userAgent.toLowerCase().indexOf("msie") != -1) ? true : false; 
}


/** 
* Function which determines the browser client is using 
* and returns true if the plugin is installed (else false) 
* 
* @argument classsID  object name to look for (i.e. ShockwaveFlash.ShockwaveFlash.7) 
* @argument pluginName the name to look for in plugin list 
*
*/ 
pluginDetect.prototype.isPlugin = function(classID,pluginName) { 
	res = false;
	if (this.IE) { 
		return this.plugin_detectIE(classID); 
	} else {  
		if(pluginName.match(/ (\d+)/)[1])
		return this.plugin_detectMoV(pluginName.replace(pluginName.match(/ (\d+)/)[1],""),parseInt(pluginName.match(/ (\d+)/)[1])); 
		else return this.plugin_detectMoV(pluginName);
	}
}


/**
* Function for Plugin detection in IE 
* The function is trying to create an ActiveX object in VB 
* if the created object exists return true otherwise return false!
* 
* @argument ClassID object name to look for (i.e. ShockwaveFlash.ShockwaveFlash.7) 
*
*/ 
pluginDetect.prototype.plugin_detectIE = function (CLSID) { 
	// status 
	ret = false; 
	if (CLSID.match(/\$v\[(\d+),(\d+)\]/)) 
	{
		// if there is a start and end version specified 
		var vStartVersion = CLSID.match(/\$v\[(\d+),(\d+)\]/)[1]; 
		var vEndVersion = CLSID.match(/\$v\[(\d+),(\d+)\]/)[2]; 
		
		CLSID = CLSID.replace( CLSID.match(/\$v\[(\d+),(\d+)\]/)[0], ""); 

		for (var i = vEndVersion; i >= vStartVersion; i--) {
			document.write('<SCRIPT LANGUAGE=VBScript>\n'
			// resumes if an error is showed 
			+ 'on error resume next\n' 
			// try to create an object with given class name 
			// return true or false if the plugin is found 
			+ 'ret = IsObject(CreateObject("' + (CLSID  + i) + '"))\n' 
			+ '</SCRIPT>\n');		
			alert(i+":"+ret);
			if (ret) 
				return true; 
				

		}
		
		} else { 
			// look only for one version 

			document.write('<SCRIPT LANGUAGE=VBScript>\n'
			// resumes if an error is showed 
			+ 'on error resume next\n' 
			// try to create an object with given class name 
			// return true or false if the plugin is found 
			+ 'ret = Not IsNull(IsObject(CreateObject("' + CLSID + '")))\n' 
			+ '</SCRIPT>\n');
		}

	return ret;

}

/**
* Function for Plugin detection in Non IE browsers 
* Usualy Non IE browsers have a special object called navigator.plugins which contains 
* all the plugins supported by browser. The function loops through the object and 
* searches for the specific plugin 
*
* @argument pluginName the name to look for in plugin list 
*/ 
pluginDetect.prototype.plugin_detectMo = function (pluginName) {
	// plugin which contains all the objects
	var pluginObj = navigator.plugins; 
	// make a loop through the object
	for (i = 0; i < pluginObj.length;i++)  { 
		// search the plugin 
		if (pluginObj.item(i).name.search(pluginName) >= 0 || pluginObj.item(i).description.search(pluginName) >= 0) 
			return true; 
	}
	
	return false; 
	
}

/**
* Extension of detectMo: detects the plugin and then retrieves the version number.
* if it is above or equal to the version argument returns true, otherwise false
*
* @argument pluginName the name to look for in plugin list 
* @argument minVersion the version required of flash
*/
pluginDetect.prototype.plugin_detectMoV = function (pluginName,minVersion) {
	var pluginObj = navigator.plugins; 
	// make a loop through the object
	for (i = 0; i < pluginObj.length;i++)  { 
		// search the plugin 
		p = pluginObj.item(i); 
		//found plugin
		if (p.name.search(pluginName) >= 0 || p.description.search(pluginName) >= 0 ) {
			//detect version
			var version  = p.description.match(new RegExp(pluginName + "\s?(\\d+)"))[1]; 
			if (typeof minVersion != "undefined" && version >= minVersion) { 
				return true; 
			} else if (typeof minVersion != "undefined") { 
				// min version defined but smaller 
				return false; 
			}
			
			return false; 
		}
	}
	
	return false; 
	
}

/* ************************* FlashObject *************************
*
* This object is to make JS > Flash calls
* You need to pass Flash object ID in the HTML page in the constructor
*
*/

FlashObject = function(domID){
	
	this.domID = domID;
	this.param_token = "__[@]__";
	this.param_glue = "___";
	this.watchedVar = "jsCall";
	this.htmlObject = window.document[this.domID];
	
}

FlashObject.prototype.makeCall = function(func,params){
	
	var call_string = func;
	if(params){ call_string += this.param_token + params.join(this.param_token); }
	this.htmlObject.SetVariable(this.watchedVar,call_string);
	
}

FlashObject.prototype.updateVideo = function(videoPath,autoplay,subtitlesXML){
	this.makeCall("evUpdateVideo",["videoPath" + this.param_glue + videoPath,"autoPlay" + this.param_glue + autoplay,"subtitlesXMLPath" + this.param_glue + subtitlesXML]);
}

FlashObject.prototype.playCurrentVideo = function(){
	this.makeCall("evVideoPlay");
}

FlashObject.prototype.stopAllSounds = function(){
	this.makeCall("evStopAllSounds");
}

FlashObject.prototype.changeSound = function(soundPath,autoPlay){
	this.makeCall("evChangeSound",["soundPath" + this.param_glue + soundPath,"autoPlay" + this.param_glue + autoPlay]);
}

/* ************************* FlashAPI *************************
*
* This object is to receive Flash > JS calls
* There *MUST* be a "flashAPI" object in all pages
* Some of the methods are empty but need to be there anyway
*
*/

FlashAPI = function(){}
FlashAPI.prototype.evSoundStarted = function(element,soundPath,fromFlash){}
FlashAPI.prototype.evSoundStopped = function(element,soundPath,fromFlash){}
FlashAPI.prototype.evVideoStarted = function(element,videoPath){}
FlashAPI.prototype.evVideoStopped = function(element,videoPath){}
FlashAPI.prototype.evAppReady = function(element){}
FlashAPI.prototype.evAboutBox = function(element){}

// This function is used for the flash templates Scanning and WhatNext (it could perhaps belong elsewhere)
FlashAPI.prototype.evSetInstructionText = function(element,order)
{

	var instructions = instruction_text[qnum]; //passed from template (q number to get data from qdata)
		
	var brokenstring = instructions.split("^");
	
	var displayText = document.getElementById("instruction_text");
	
	if (!displayText){
		return; 
	}

	displayText.innerHTML = brokenstring[order]; 
	displayText = null; 
	
}


this.flashAPI = new FlashAPI();
