/** version: Update July 3, 2006. */

var	octo_embed_height, octo_embed_width;
var	octo_embed_wait_image, octo_embed_wait_height, octo_embed_wait_width;
var	octo_external_wait_popup, octo_external_wait_height, octo_external_wait_width;
var	octo_plugin_error, octo_plugin_missing;
var	octo_install_popup, octo_install_popup_features;
var octo_install_function;

var octo_player_div = 'dummy';
var octo_embed_has_been_called = false;
var octo_disabled = new Array();
var octo_startup_popup;

// if this is 999, then everything is normal.
// else we will use it to override the result variable in the play_rec function
var octoPrivate = 999;
var octo_group = "";	// default epsilon group


// If this returns false, octoshape is not installed, or not installed correctly
// Do not call this from the head section of a document, as the mime type function (used in firefox) adds a div to the body section
function octoOK(){
	if (octoUsingProtocol()){ return false; }
	return octopv_OK(octopv_get_octoclient());
}

function octoDisable(octoLink){
	octo_disabled[octo_disabled.length] = octoLink;
}

function octoUsingProtocol(){
	var text = navigator.userAgent.toLowerCase();
	if (text.indexOf("opera") >= 0 || text.indexOf("mac os x") >= 0) { 
		return true;
	}
	return false;
}


/***************************** PLAY FUNCTIONS *******************************/

// This will place an embedded media player in the div with the ID playerDIV_ID,
//  any previus content of the div will be discarded.
// Remember to place an install link on all pages where the play-link is, 
// since this function might show an alert asking the user to perform an install or re-install.
// The argument is the unique octolink you got from Octoshape
// player width and height are the video diplay area: there will be added 46 pixles to the height for the controls
// returns true if we start to play imidiatly or we are starting up and then we are going to play
//         false if: disabled or we are on the mac or there was some error with the plug-in.
function octoPlayEmbedded(arg_octolink, playerDIV_ID, arg_player_width, arg_player_height){
	if (octopv_disabled(arg_octolink)){return false;}

	if (octoUsingProtocol()){
		window.location.href='OCTOSHAPE'+octo_group+':'+arg_octolink;
		return false;
	}
	octo_player_div = playerDIV_ID;
	octo_embed_width=arg_player_width;
	octo_embed_height=arg_player_height;
	external_play = false;
	octoshapeclient=octopv_get_octoclient();
	octolink=arg_octolink;
	octo_embed_has_been_called=true;
	return octopv_play_rec();
}


// returns true if we start to play imidiatly or we are starting up and then we are going to play
//         false if: disabled or we are on the mac or there was some error with the plug-in.
function octoPlayExternal(OctoLink){
	if (octopv_disabled(OctoLink)){return false;}

	if (octoUsingProtocol()){
		window.location.href='OCTOSHAPE'+octo_group+':'+OctoLink;
		return false;
	}	
	external_play = true;
	octoshapeclient=octopv_get_octoclient();
	octolink=OctoLink;
	return octopv_play_rec();
}

// IE: 		stops player (can be started again via the controls below the viewing area)
// Firefox: removes the player object, leaving the PlayerDIV empty.
function octoStopEmbedded() {
	if(!octo_embed_has_been_called) { return; }
	
	try  { document.octoPlayerObjectID.stop(); } 
	catch (e) 	{ 
		try { document.getElementById(octo_player_div).innerHTML = ''; } 
		catch (e2) { /* if there was no divmplayer we do nothing */ }
	}
}

function octopv_stop_embedded(obj){
	try 				{ obj.stop(); return true; } 
	catch (exception) 	{ return false; }
}

/*********************** CUSTOMIZING FUNCTIONS *******************************/

function octoSetAlertTexts(noPlugInText, errorPlugInText){
	octo_plugin_missing = (noPlugInText==null)? 	octoConfig.OCTO_ST_PLUGIN_MISSING	: noPlugInText;
	octo_plugin_error 	= (errorPlugInText==null)? 	octoConfig.OCTO_ST_PLUGIN_ERROR		: errorPlugInText;
}

function octoSetStartupPage(startupPage, startupWidth, startupHeight){
	octo_external_wait_popup 	= (startupPage==null)? 			octoConfig.OCTO_ST_EXTERNAL_WAIT_POPUP	: 	startupPage;
	octo_external_wait_height	= (startupHeight==null)?		octoConfig.OCTO_ST_EXTERNAL_WAIT_HEIGHT	: 	startupHeight;
	octo_external_wait_width	= (startupWidth==null)?			octoConfig.OCTO_ST_EXTERNAL_WAIT_WIDTH	:	startupWidth;

}

function octoSetStartupImage(startupImage, playerWidth, playerHeight){
	octo_embed_wait_image 	= (startupImage==null)? 		octoConfig.OCTO_ST_EMBED_WAIT_IMAGE		: startupImage;
	octo_embed_wait_height 	= (playerHeight==null)? 		octoConfig.OCTO_ST_EMBED_WAIT_HEIGHT	: playerHeight;
	octo_embed_wait_width 	= (playerWidth==null)? 			octoConfig.OCTO_ST_EMBED_WAIT_WIDTH		: playerWidth;
}


function octoSetInstallPopup(installPage, installPageFeatures){
	octo_install_popup 			= installPage;
	octo_install_popup_features = (installPageFeatures==null)? 	octoConfig.OCTO_ST_INSTALL_POPUP_FEATURES	: installPageFeatures;
}

function octoSetInstallFunction(javaScriptFunction){
	octo_install_function = (javaScriptFunction==null)? octoConfig.OCTO_ST_INSTALL_FUNCTION:javaScriptFunction;
}


function octoSetEmbedDisplay(show){
	octopv_set_param("showdisplay", show);
}


function octoSetEmbedStatusBar(show){
	octopv_set_param("showstatusbar", show);
}


function octoSetEmbedControls(play, audio){
	octopv_set_param("showcontrols", play);
	var aud = (typeof(audio) != "boolean")? play: audio;
	octopv_set_param("showaudiocontrols", aud);
}


/***************************************************************************************/
/********************************** PRIVATE FUNCTIONS *******************************/

var octopv_embed_params = new Object;
function octopv_set_param(paramname, value){
	if ((typeof(value))!="boolean"){ alert("The funtion octopv_set_param only accepts boolean values as second argument."); }
	else { octopv_embed_params[paramname.toLowerCase()] = value;  }
}

function ocvtopv_embed_calculate_height(){
	var ret = 0;
	if (octopv_embed_params["showcontrols"])	{ 
		ret += 26; 
		if (octopv_embed_params["showtracker"])	{ ret += 19; }
	}
	if (octopv_embed_params["showstatusbar"])	{ ret += 24; }
	
	if (octopv_embed_params["showgotobar"])		{ ret += 29; }
	if (octopv_embed_params["showdisplay"])		{ ret += 74; }
	if (octopv_embed_params["showcaptioning"])	{ ret += 89; }
	
	return ret;
}

function ocvtopv_embed_calculate_height_fx(){
	var ret = 0;
	if (octopv_embed_params["showcontrols"])	{ 
		ret += 27; 
		if (octopv_embed_params["showtracker"])	{ ret += 19; }
		if (octopv_embed_params["showstatusbar"]){ ret += 26; }
	} else if (octopv_embed_params["showstatusbar"]) { ret += 24; }
	
	if (octopv_embed_params["showgotobar"])		{ ret += 29; }
	if (octopv_embed_params["showdisplay"])		{ ret += 74; }
	if (octopv_embed_params["showcaptioning"])	{ ret += 89; }
	
	return ret;
}


// cunstructor for the config object
function octopv_config(){
	// constants, dont change them.
	this.OCTO_ST_EMBED_HEIGHT			= octo_embed_height 			= 135;
	this.OCTO_ST_EMBED_WIDTH			= octo_embed_width				= 240;
	
	this.OCTO_ST_EMBED_WAIT_IMAGE 		= octo_embed_wait_image 		= "http://www.octoshape.com/images/upstart_16_9.GIF";
	this.OCTO_ST_EMBED_WAIT_HEIGHT		= octo_embed_wait_height		= 135;
	this.OCTO_ST_EMBED_WAIT_WIDTH		= octo_embed_wait_width			= 240;

	this.OCTO_ST_EXTERNAL_WAIT_POPUP 	= octo_external_wait_popup		= "http://www.octoshape.com/play/startup_popup.asp";
	this.OCTO_ST_EXTERNAL_WAIT_HEIGHT	= octo_external_wait_height		= 300;
	this.OCTO_ST_EXTERNAL_WAIT_WIDTH	= octo_external_wait_width		= 400; 

	this.OCTO_ST_PLUGIN_ERROR 			= octo_plugin_error				= "An error occured while trying to play an Octoshape stream. \nPlease re-install the plug-in. ";
	this.OCTO_ST_PLUGIN_MISSING 		= octo_plugin_missing 			= "Please get the Octoshape Plug-In to play.";

	//this.OCTO_ST_INSTALL_POPUP 		= ="http://www.octoshape.com/download/external_install.asp";
	this.OCTO_ST_INSTALL_POPUP 			= octo_install_popup			= null;
	this.OCTO_ST_INSTALL_POPUP_FEATURES	= octo_install_popup_features	= 'height=400,width=520';
	this.OCTO_ST_INSTALL_FUNCTION		= octo_install_function			= octoDummy;
	
	octopv_set_param("showcontrols", true);
	octopv_set_param("showaudiocontrols", true);
	octopv_set_param("ShowPositionControls", false);
	octopv_set_param("ShowTracker", false);
	octopv_set_param("showdisplay", false);
	octopv_set_param("showcaptioning", false);
	octopv_set_param("showgotobar", false);
	octopv_set_param("ShowStatusBar", true);
	octopv_set_param("stretchToFit", false);
	octopv_set_param("autosize", false);
}

function octoDummy(){}
var octoConfig = new octopv_config();



function octopv_disabled(octoLink){
	//	alert("testing: "+ octoLink);
	for (i=0;i<octo_disabled.length;i++){
		if (octoLink == octo_disabled[i]){
			alert("The stream is temporarily disabled.\n   Try again later.");
			return true;
		}
	}
	return false;
}

// JavaScript does has strange behavier when recursing with arguments, 
// to be on the safe side we have set the arguments as global variables before this call
// If the octoshape plug-in is running, we play the link,
// if not, we start up the plugin, display a wait message to the user, waits in 2 seconds, and then start over agian.
// The default setting in the plug-in is to start up when the computer starts up, so most likely it will be running.
//	The player URL is set in case 1 and 2.

// returns 	true if we play or we are starting up
// 			false if: force install
var octopv_oldStatus=999;
var octopv_numRecur=0;

function octopv_play_rec(){
	var theOctoshapeClient;

	/*************************  PRIVATE FUNCTIONS  **************************/
	function insert_embedded_player(src, width, arg_height){
		var height = arg_height;
		if(height == null){
			octoSetEmbedStatusBar(false);
		} else if ((typeof height) != "number"){
			var num = parseInt(height, 10); 
			if (isNaN(num))	{ alert("The player height is not a number. \n\nPlayer height: " + height); }
			else 			{ height = num; }
		}
		var html  = "";
		
		html += "	<OBJECT ID=\"octoPlayerObjectID\" height=\""+(height + ocvtopv_embed_calculate_height())+"\" width=\""+width+"\"";
		html += "			classid=\"CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95\""
		html += "           STANDBY=\"Loading Octoshape plugin and client\"";
		html += "           pluginspage=\"http://microsoft.com/Windows/MediaPlayer/\" ";
		html += "			codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112\""; // checks if wmp is installed, if not it is installed automaticly 
		html += "           type=\"application/x-oleobject\">";
		
		for (var i in octopv_embed_params){ html += "<param name=\""+i+"\" value=\""+octopv_embed_params[i]+"\">"; }
		
		html += "           <param name=\"Loop\" value=\"0\">";
		html += "           <param name=\"Repeat\" value=\"false\">";
		html += "	        <param name=\"rate\" value=\"True\">";
		html += "	        <param name=\"defaultFrame\" value=\"\">";
		html += "	        <param name=\"playCount\" value=\"False\">";
		html += "	        <param name=\"mute\" value=\"False\">";
		html += "	        <param name=\"enableErrorDialogs\" value=\"False\">";	
		html += "           <param name=\"autostart\" value=\"true\">";
		html += "           <param name=\"PlayCount\" value=\"1\">";
		html += "           <param name=\"AutoRewind\" value=\"false\">";
		html += "	        <param name=\"URL\" value=\""+src+"\">";
		html += "	        <param name=\"src\" value=\""+src+"\">";

		html += "<embed "
		html += " 	type=\"application/x-mplayer2\" "
		html += " 	pluginspage=\"http://microsoft.com/Windows/MediaPlayer/\" "
		html += " 	filename=\""+src+"\" "
        html += " 	src=\""+src+"\" "
		html += "	name=\"octoPlayerObjectID\" "
		for (var i in octopv_embed_params){
			html += " "+i+"=";
			html += (octopv_embed_params[i])? "1 ": "0 "; 
		}
        html += "	width=" + width
        html += "	height="+(height + ocvtopv_embed_calculate_height_fx())+">"
    	html += "</embed>"
		html += "</OBJECT>";


  		var divmplayer = document.getElementById(octo_player_div);
		divmplayer.innerHTML = html;
	}

	function do_install(){
		if (octo_install_popup != null){
			window.open(octo_install_popup, "install_popup", octo_install_popup_features);
		}
		octo_install_function();
	}
	
	// from -4 to 2: answer from octoclient
	// -10: no octoclient present
	// This function might throw an exception (?)
	// OBS: IF octoPrivate < 100, this will overrule anything else
	function getStatus(){
		if (!octopv_OK(theOctoshapeClient)){ 
			theOctoshapeClient = octopv_get_octoclient();
		}
		if (octoPrivate < 100){ return octoPrivate; }
		if (!octopv_OK(theOctoshapeClient)){ return -10; }
	
		// We query the activeX object to se what status the octoshape program is in
		// The parameter indicates whether we want the octoshape program to begin starting up, if it is not already running ...
		var status = theOctoshapeClient.getStatus(true);

		// some users have experienced that when plugin installed but closed then:
		// pressing play the user gets 'octoshape is starting up' (status 1), 
		// but after a while the user gets 'please install' (status -10) and no musik is played. 
		// solution: if we get -10 after we have gotten 2, we wait a while to see if we get something other than -10
		if (octopv_oldStatus == 1 && status == -10) {
			octopv_numRecur++;
			if (octopv_numRecur < 4){ 
				return 1;
			}
		} else {
			octopv_numRecur=0;
		}
		return status;	
	}
	
	
	/*************************  END PRIVATE FUNCTIONS  **************************/

	try {
		var result = getStatus();	
		
		switch (result){
			case -100:	octoPrivate = 999; return false; 	// do nothing: for web integration pages
			case -10:	// no octoclient
				alert(octo_plugin_missing);
				window.location="./?listen";
				do_install();
				return false;	
 			// case 0 will not happen since we call getStatus with true
	 		case 1:
	 			// octoshape is starting up, so we show some message to the user while s/he waits
				if (external_play){

					if (octo_startup_popup == undefined){
						var features = "height="+octo_external_wait_height+",width="+octo_external_wait_width;
						octo_startup_popup = window.open(octo_external_wait_popup, "octo_popup", features);
					}
					
				} else {
					if (octopv_isFirefox()){
						var html = "<img src='"+octo_embed_wait_image+"' height='"+octo_embed_wait_height+"px' width='"+octo_embed_wait_width+"px'>";
						var divmplayer = document.getElementById(octo_player_div);
						divmplayer.innerHTML = html;
					}else{
						insert_embedded_player(octo_embed_wait_image, octo_embed_wait_width, octo_embed_wait_height);
					}
				}

				// we call our self again in 2000 milli-seconds
				setTimeout("octopv_play_rec();",2000);
	 			return true;
			case 2:
				// octoshape is already started up, so we just play the link
				
				// We get the link to play from the activeX object. The second parameter indicates whether we want to play in an external player.
				var playlink = 'OCTOSHAPE'+octo_group+':'+octolink;
				
				if (external_play){
					octoStopEmbedded();
					if (octo_startup_popup != undefined){
						if(!octo_startup_popup.closed){
							octo_startup_popup.close();
						}
						octo_startup_popup = undefined;
					}
					
					window.location.href=playlink;
				}else {
					//embeddedPlay(theOctoshapeClient.getLink(playlink,false));
					insert_embedded_player(theOctoshapeClient.getLink(playlink,false), octo_embed_width, octo_embed_height);
				}
				
	 			return true;
	 		default:
				// there was an error from the octoshape plug-in, we need to ask the user to re-install
	 			alert(octo_plugin_error + "\n\nError number: " + result);
				window.location="./?listen";
	 			do_install();
	 			
	 			return false;
		 }
	}
	catch (exception) {
		// This should really not happen, but just in case something went completely un-expectedly wrong, 
		// we must present the user with some form of crash recover help message.
		alert("An un-expected error occured while trying to start up the Octoshape plug-in. \n"+
			"Please try to shut down the plug-in and then press play again. \n" + 
			"To shut down: right click the system tray icon and choose exit. \n" + 
			"\n\n\nFunction getStatus response was: " + result + 
			"\nStartup link Exception:" + exception.description);
			do_install();
			return false;
	}
}




/* Getting the activeX object */

function octopv_OK(octoobject){
	if (typeof(octoobject) == "undefined"){
		return false;
	}
	if (typeof(octoobject.getStatus) == "undefined") {
		return false;	
	}
	return true;
}


// Get the octoshape activeX object with this function
// If we fail and have Firefox, we refresh the plug-ins, and try once more
function octopv_get_octoclient(){
	// Do not call this directly, use octopv_get_octoclient()
	// Do not call this from the head section of a document.
	function octopv_get_octoclient_sub(){
	
		// Do not call this from the head section of a document.
		function octopv_get_octoclient_mimetype() {
			var octomime = "application/x-octoshapeplugin"+octo_group+"-client";

			if (navigator && navigator.mimeTypes && navigator.mimeTypes.length) {
				var mimetype = navigator.mimeTypes[octomime];

				if (mimetype) {
				var oDiv = document.createElement("DIV");
					document.body.appendChild(oDiv);
					oDiv.innerHTML = "<object id=octoshapeclientobject type=\""+octomime+"\" hidden=\"true\"></object>";
					var octoshape = document.getElementById('octoshapeclientobject');
					if (octopv_OK(octoshape)) {
						//alert("Client loaded using mimeTypes:" + octomime);
						return octoshape;
					}
				} 
			}
			return undefined;
		}

		try {
			if (window.ActiveXObject) {
				try {
					var octoshape = new ActiveXObject("octoshapeplugin"+octo_group+".client");
					if  (octopv_OK(octoshape)){ return octoshape; }
				} catch(exception) {}
			}
		
			if (window.GeckoActiveXObject) {
				try {
					var octoshape = new GeckoActiveXObject("octoshapeplugin"+octo_group+".client");
					if  (octopv_OK(octoshape)){ return octoshape; }
				} catch(exception) {}
			}

			// Crashes opera
			if (false && navigator && navigator.plugins && navigator.plugins.length) {
				var octoshape = navigator.plugins["application/x-octoshapeplugin"+octo_group+".client"];
				if  (octopv_OK(octoshape)){ return octoshape; }
			}		
		
			if (navigator && navigator.mimeTypes && navigator.mimeTypes.length) {
				var octoshape = octopv_get_octoclient_mimetype();
				if  (octopv_OK(octoshape)){ return octoshape; }
			}
	
			//alert(" Failed all together. ");
			return undefined;
		} catch (exception) {
			return octopv_get_octoclient_mimetype();
		}
	}


	var obj = octopv_get_octoclient_sub();
	if (octopv_OK(obj)){
		return obj;
	}
	else {
		if (octopv_isFirefox()){ 
			navigator.plugins.refresh(false);
			return (octopv_get_octoclient_sub());
		}
		return obj;
	}
}



function octopv_isOSX(){
	var text = navigator.userAgent.toLowerCase();
	if (text.indexOf("mac os x") > 0){ 
		//alert("hurra");
		return true;
	}
	//alert("no mac os x");
	return false;
}

function octopv_isFirefox(){
	var text = navigator.userAgent.toLowerCase();
	if (text.indexOf("firefox") > 0){ 
		return true;
	}
	return false;
}