var octoBrowserPlugin = null;
var octopv_swfname = null;


function octopvJS_setDebug(){
	var debug = document.getElementById('octopvDebugDiv');
	if(debug!=null){
		octopvDebugDiv = 'octopvDebugDiv';
		octopvDebugTopPost = true;
	}
}

function octopvJS_getFlashInstance() {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[octopv_swfname];
    } else {
        return document[octopv_swfname];
    }
}

function octopvJS_canHaveBrowserPlugin(){
	var text = navigator.userAgent.toLowerCase();
	if (text.indexOf("windows") >= 0 || text.indexOf("mac os x") >= 0 ) {
		return (text.indexOf("opera") == -1);
	} 
	return false;
}



function octopvJS_cabInstallComplete() {
	octopvJS_getFlashInstance().octopvAS_cabInstallCompleted();
}
function octopvJS_doCabInstall(div1) {
	octopv_doCabInstall(div1,octopvJS_cabInstallComplete);
}


function octopvJS_appletTestComplete(status) {
	octopvJS_getFlashInstance().octopvAS_appletTestCompleted(status);
}
function octopvJS_doAppletTest(div1) {
	octopv_doAppletTest(div1,octopvJS_appletTestComplete);
}

function octopvJS_debugWrite(message) {
	octopv_debug(message, arguments.callee);
}

function octopvJS_appletProgress(mess){
	octopvJS_getFlashInstance().octopvAS_appletProgress(mess);
}

function octopvJS_appletPreloadComplete() {
	octopv_debug('Applet preload complete.', arguments.callee);
	octopvJS_getFlashInstance().octopvAS_appletPreloadCompleted();
}

function octopvJS_doAppletPreload(indiv, onComplete){
	octopv_doAppletPreload(indiv,octopvJS_appletPreloadComplete);
}


function octopvJS_appletInstallComplete(status) {
	octopv_debug('Applet install complete from js: '+status, arguments.callee);
	octopvJS_getFlashInstance().octopvAS_appletInstallCompleted(status);
}

function octopvJS_doAppletInstall(div1, param, value) {
	octopv_debug('Doing applet install.', arguments.callee);
	octopv_setProgressFunction(octopvJS_appletProgress);
	octopv_debug('Doing applet install 2.', arguments.callee);
	octopv_doAppletInstall(div1, octopvJS_appletInstallComplete,param, value);
	octopv_debug('Doing applet install 3.', arguments.callee);
}


function octopvJS_canUseWMP() {
	// if windows and either IE or FX with wmp-plugin then ok
	var str =  window.navigator.userAgent.toLowerCase();
	if(str.indexOf("windows") != -1){
		if(str.indexOf("msie") != -1){
			return true;
		}else if (str.indexOf("firefox") != -1 && 
					(	str.indexOf("windows nt 6.0") != -1 || 
						str.indexOf("windows nt 5.1") != -1 || 
						str.indexOf("windows nt 5.2") != -1		)	){
			// The user has vista or xp and is using firefox.
			//  (the wmp-plugin requires xp or vista).
			if(navigator && navigator.mimeTypes && navigator.mimeTypes.length){
				var mime =  navigator.mimeTypes["application/x-ms-wmp"];
				if(mime && mime.enabledPlugin){
					return true;
				}
			}
		}
	}
	return false; 
}

function octopvJS_canUseSilverlight() {
	// according to http://msdn.microsoft.com/en-us/silverlight/bb419316.aspx
	var str =  window.navigator.userAgent.toLowerCase();
	if(str.indexOf("windows nt 6.0") != -1 || str.indexOf("windows nt 5.2") != -1 || str.indexOf("windows nt 5.1") != -1){
		return true;
	}
	if(str.indexOf("mac os x") != -1){
		return true;
	}
	return false;
}


function octopvJS_octoStartup(){
  	if(octoLowLevelCheck(octoBrowserPlugin)){
	  	var status = octoBrowserPlugin.getStatus(false);
	  	if(status==0 || status==1){
	  		status = octoLowLevelReady(octoBrowserPlugin, 
	  			function(){ octopvJS_getFlashInstance().octopvAS_finishedStartedUp(); },
  				function(){ octopvJS_getFlashInstance().octopvAS_progressStartingUp(); });
	  	}
		octopv_debug('Browser plugin status: '+status, arguments.callee);
		return status; 
  	}else{
  		// indicating that we are not installed.
		octopv_debug('Browser plugin not installed, returning -101 to actionscript.', arguments.callee);
  		return -101;
  	}
}

/** Void function. Initialises callbacks into flash. Can be called multiple times. */
function octopvJS_octoInit(swfName){
	octopv_swfname = swfName;
	octopv_debug('octopvJS_octoInit called.', arguments.callee);
}

function octopvJS_octoBPInstantiate(){
	octoBrowserPlugin = octoLowLevelGet();
	if(octoLowLevelCheck(octoBrowserPlugin)){
		return 0;
	}else{
		return -1;
	}
}

function octopvJS_octoBPStatus(){
	if(octoLowLevelCheck(octoBrowserPlugin)){
		var status = octoBrowserPlugin.getStatus(false);
		octopv_debug('Browser plugin status: '+status, arguments.callee);
		return status;
	}
	octopv_debug('Browser plugin not installed, returning -101 to actionscript.', arguments.callee);
	return -101;
}

function octopvJS_octoBPStartup(){
  	if(octoLowLevelCheck(octoBrowserPlugin)){
	  	octoBrowserPlugin.getStatus(true);
  	}
}

function octopvJS_octoTest(){
	octoBrowserPlugin = octoLowLevelGet();
	if(octoLowLevelCheck(octoBrowserPlugin)){
		var status = octoBrowserPlugin.getStatus(false);
		octopv_debug('Browser plugin status: '+status, arguments.callee);
		return status;
	}
	octopv_debug('Browser plugin not installed, returning -101 to actionscript.', arguments.callee);
	return -101;
}

// TODO: remove (get link from direct communication between octoshape and actionscript). Temporary test function 
function octopvJS_urlConvert(url){
	if(octoBrowserPlugin.getStatus(false) ==2){
		var result = octoBrowserPlugin.getLink(url, false);
		octopv_debug('Returning urlconverted string to actionscript: '+result, arguments.callee);
		return result;
	}else{
		return "";
	} 
}

function octopvJS_getXmlboundStr(){
	if(octoBrowserPlugin.getStatus(false)==2){
		var result = octoBrowserPlugin.getString('xmlbound'); 
		octopv_debug('Returning xmlbound string to actionscript: '+result, arguments.callee);
		return result;
	}else{
		octopv_debug('Could not return xmlbound string to actionscript since browser plugin status was: '+status, arguments.callee);
		return "";
	} 
}

function octopvJS_removeWMP(id){
	var divID = id;
	var newdiv = document.getElementById(divID);
	if(newdiv!=null){
		newdiv.innerHTML='';
	}
}

function octopvJS_insertWMP(id, src, x,y,width, height, showControls, zIndex){
	octopv_debug('Inserting WMP with src: '+src, arguments.callee);
	var divID = id;
	var playerID = id+'player';
  try {
	var theDiv = document.getElementById(divID);
	if(theDiv==null){
		alert('Coding error: add HTML div section with id: '+id);	
	}else{
		theDiv.style.position = 'absolute';
		theDiv.style.width = width+'px';
		theDiv.style.height = height+'px';
		theDiv.style.left = x+'px';
		theDiv.style.top = y+'px';
		if(zIndex!=0){
		 	theDiv.style.zIndex = zIndex+'';
		}
		if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){
			theDiv.innerHTML = octopvJS_wmpHTML_fx(playerID, src, width, height, showControls, zIndex<0);
		}else{
			theDiv.innerHTML = octopvJS_wmpHTML_ie(playerID, src, width, height, showControls, zIndex<0);
		}
	}
  }catch (e) {
	alert('insertWMP. e:'+e);
  }
}
/*
function octopvJS_changeZIndex(id, zIndex){
	var theDiv = document.getElementById(id);
	if(theDiv!=null){
 		theDiv.style.zIndex = zIndex+'';
 	}
}*/


function octopvJS_wmpHTML_ie(id, src, width, height, showControls, windowLess){
		var html  = '';
		var paramUiMode = '	<PARAM name="uimode" value="none" >';
		var paramWindowLess = '';
		var controls = 0;
		
		if(showControls){
			paramUiMode = '	<PARAM name="uimode" value="mini" >';
			controls += 45; 
		}
		if(windowLess){
			paramWindowLess += '   <param name="WindowlessVideo" value="True" />';
		}
		
		//octopv_debug('inserting. h:'+height+" cntrls: "+controls+" ", arguments.callee);
		html += '<OBJECT ID="'+id+'" ';
		html += 'height="'+(height + controls)+'" width="'+width+'" ';
		html += 'classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" ';
		// 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">';
		html += '>';
		html += '	<param name="rate" value="True" />';
		html += '	<param name="enableErrorDialogs" value="False" />';	
		html += '   <param name="autostart" value="True" />';
		html += '	<param name="URL" value="'+src+'" />';
		
		// StretchToFit will scale up the video if the player is larger than the content, 
		// 	but the aspect ratio will be preserved.
		// The matching shrinkToFit has default value true so it is not necessary to add it.
		html += '   <param name="ShrinkToFit" value="True" />';
		html += '   <param name="StretchToFit" value="True" />';

		html += paramUiMode;
		html += paramWindowLess;
		html += '</OBJECT>';
		return html;
}



function octopvJS_wmpHTML_fx(id, src, width, height, showControls, windowLess){
		var paramUiMode = '	<PARAM name="uimode" value="none" >';
		var paramWindowLess = '';
		var controls = 0;
		if(showControls){
			paramUiMode = '	<PARAM name="uimode" value="mini" >';
			controls += 45; 
		}
		if(windowLess){
			paramWindowLess += '   <param name="WindowlessVideo" value="True" />';
		}
		
		//octopv_debug('inserting. h:'+height+" cntrls: "+controls+" ", arguments.callee);
		var html  = '';
		html += '	<OBJECT ID="'+id+'" ';
		html += '	height="'+(height + controls)+'" width="'+width+'" ';
        html += ' 	type="application/x-ms-wmp"'; 
		html += '   STANDBY="Loading Octoshape plugin and client" >';
		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 += '   <param name="WindowlessVideo" value="True" />';
		
		// StretchToFit will scale up the video if the player is larger than the content, 
		// 	but the aspect ratio will be preserved. 
		// There is no ShrinkToFit like for IE, the behavior is just always to shrink to fit. 
		html += '   	<param name="stretchToFit" value="1" />';
			
		html += paramUiMode;
		html += paramWindowLess;
		html += '</OBJECT>';
		return html;
}

/*************************** Silverlight **************************/

var octopvSilverObjects = new Object();
octopvSilverObjects.plugins = new Object();
octopvSilverObjects.canvas = new Object();
octopvSilverObjects.players = new Object();
octopvSilverObjects.widths = new Object();
octopvSilverObjects.heights = new Object();

// Set global variables for the plug-in and main Canvas objects.
function octopvSilverLoaded(plugin, userContext, sender){
	octopvSilverObjects.plugins[userContext] = plugin;
	octopvSilverObjects.canvas[userContext] = sender;
}

function octopvJS_hasSilver(){
	return Silverlight.isInstalled(null);
}


function octopvJS_insertSilver(id, x,y,w, h, zIndex){
	octopv_debug('Inserting Silver player '+id, arguments.callee);
	var divID = id;
	var playerID = id+'player';
  try {
	var theDiv = document.getElementById(divID);
	if(theDiv==null){
		alert('Coding error: add HTML div section with id: '+id);	
	}else{
		theDiv.style.position = 'absolute';
		theDiv.style.width = w+'px';
		theDiv.style.height = h+'px';
		theDiv.style.left = x+'px';
		theDiv.style.top = y+'px';
		if(zIndex!=0){
		 	theDiv.style.zIndex = zIndex+'';
		}
		
	   	//document.write('<div id="'+silverID+'PluginHost"></div>');
	 	//var parentElement = document.getElementById(silverID+"PluginHost");
	   	octopvSilverObjects.widths[playerID] = w;
	   	octopvSilverObjects.heights[playerID] = h;
   	
   		// This function creates the Silverlight plug-in.
		Silverlight.createObject(
		'#xaml',		                // Source property value.
		theDiv, 		                // DOM reference to hosting DIV tag.
		playerID,			         	// Unique plug-in ID value.
		{                               // Per-instance properties.
			width:''+w+'',              // Width of rectangular region of plug-in area in pixels.
	        height:''+h+'',             // Height of rectangular region of plug-in area in pixels.
            inplaceInstallPrompt:false, // Determines whether to display in-place install prompt if invalid version detected.
		   	background:'#D6D6D6',       // Background color of plug-in.
            isWindowless:'true',       // Determines whether to display plug-in in Windowless mode.
		    framerate:'24',             // MaxFrameRate property value.
            version:'1.0'               // Silverlight version to use.
        },
	    {
	    	onError:octopvSilverError, 	// OnError property value -- event handler function name.
	       	onLoad:octopvSilverLoaded   // OnLoad property value -- event handler function name.
	    },
        null, 		                    // InitParams property value set to null.  
		playerID);     				    // Unique context ID, a variable set before each page call.
	}
	
	octopv_debug('Ok done inserting Silver player '+id, arguments.callee);
			
  }catch (e) {
	alert('insertSilver. e:'+e);
  }
}


function octopvJS_playSilver(id, playlink){
	var silverID = id+'player';
	octopv_debug('Playing Silver player '+silverID+' with src: '+playlink, arguments.callee);

     var w = octopvSilverObjects.widths[silverID];
     var h = octopvSilverObjects.heights[silverID];

     // Determine whether the player is already playing.
    if (octopvSilverObjects.players[silverID] != null) {
    	// remove the existing silverplayer
        octopvSilverObjects.canvas[silverID].children.remove(octopvSilverObjects.players[silverID]);
    }
    // Define the XAML fragment.
    
    var xamlFragment = '<MediaElement Source="'+playlink+'" Width="'+w+'" Height="'+h+'" />';
    // Create the XAML fragment.
    
    var player = octopvSilverObjects.plugins[silverID].content.createFromXaml(xamlFragment, false);
	
    // Add the player to the Canvas object.
    octopvSilverObjects.canvas[silverID].children.add(player);
    octopvSilverObjects.players[silverID] = player;
}


function octopvSilverError(sender, errorArgs){
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";
    
    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";
    
    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0){
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

function octopvJS_stopSilver(id){
	var silverID = id+'player';
	
    // Determine whether the player is already playing.
    var player = octopvSilverObjects.players[silverID];
    var canvas = octopvSilverObjects.canvas[silverID];
    if (player != null) {
    	// remove the existing silverplayer
        canvas.children.remove(player);
    }
}

