// ----------------------------------------------------------------
/// File: ItivaNodeDetect.js
/// Copyright (c) 2008 Itiva Development
// ----------------------------------------------------------------

// Use:
// itiva.nodeDetect.setOnDetect( callbackFunction );
// itiva.nodeDetect.init();
// itiva.nodeDetect.status(); // returns "nodeActive", "notDetected", "updateRequired" 

// set qmeshClientVersion to null when script loaded to be sure you aren't seeing old data
// qmeshClientVersion is set by the plugin when queried
var qmeshClientVersion = null;
var current_domain = null;
var targetElementName = "TargetElement";
var containerElementName = "container";
var ContainerCtrl = "QmeshCtrl";




// create itiva namespace if it doesn't exist
if( typeof itiva == 'undefined' )
	var itiva = new Object();

// ItivaNodeDetect object definition
itiva.nodeDetect =
{
	// Private Variables
	script_version: '1.0',
	page_script_id: 'ItivaNodeVersionQuery',
	// min_node_version - minimum version of node supported, in string format ( '2', '2.1', '2.01.0.00.123' ), default to '2'
	//min_node_version: '2',
	min_node_version: '2.4.0.3',
	
	// the domain the client needs to be in, default to blank
	required_domain: '',

	// Public params
	on_detect_callback: null,
	// states:  "nodeActive", "notDetected", "updateRequired", "wrongDomain" 
	state: null,

	int_timer: null,
	// depending whether you want to stop detecting when node is found or constantly test for node:
	stop_on_detect: true,
	use_refresh: false,
	
	// Private Functions
	cmpVersionNum: function( ver, minver )
	{
		// compares to version in form X.X.X.X to arbitrary length as long as X is number
		// returns true if ver is greater than or equal to minver
		// returns false if minver is greater than ver
		if( ver == null || minver == null )
			return false;

		ver = ver.split( '.' );
		minver = minver.split( '.' );
		
		
		var maxi = ( ver.length >= minver.length )? ver.length : minver.length;
		for( var i = 0; i < maxi; i++ )
		{
			if( i >= ver.length )
			{
				if( Number( minver[i] ) > 0 )
					return false;
			}
			else if ( i >= minver.length )
			{
				if( Number( ver[i] ) > 0 )
					return true;
			}
			else
			{
				if( Number( ver[i] ) > Number( minver[i] ) )
					return true;
				else if( Number( ver[i] ) < Number( minver[i] ) )
					return false;
			}
		}
		return true;
	},
	
	appendDetectScript: function()
	{
		// Adds a new script tag to the bottom of the page with the plugin as the source
		// if the plugin is installed, it will return 'var qmeshClientVersion = "X.X.X.XX";'
		// which sets qmeshClientVersion variable to the active qmesh version
		//var body = document.getElementsByTagName( 'body' )[ 0 ];
		var body = document.getElementById( ContainerCtrl );
		
		var script = document.getElementById( itiva.nodeDetect.page_script_id );
		var newScript = document.createElement( 'script' );
		
		if ( script ) { body.removeChild( script ); }
		
		// script tag format: <script id="ItivaNodeVersionQuery" language="javascript" rel="javascript" src="http://localhost:25111/info?rand=13579"></script>
		newScript.type = 'text/javascript';
		newScript.defer = true;
		newScript.src = 'http://localhost:25111/info?rand=' + String( Math.random() * 10000000 ) + '&reqdomain=' + itiva.nodeDetect.required_domain;
		newScript.id = itiva.nodeDetect.page_script_id;
		
		body.appendChild( newScript );
	},
	
	// Protected Functions
	checkVersion: function()
	{
		// states:  "nodeActive", "notDetected", "updateRequired", "wrongDomain" 
		if ( itiva.nodeDetect.cmpVersionNum( qmeshClientVersion, itiva.nodeDetect.min_node_version ) )
		{
			if ( (current_domain > '') && (current_domain != itiva.nodeDetect.required_domain) )
			{
				itiva.nodeDetect.state = 'wrongDomain';
			}
			else
			{
				itiva.nodeDetect.state = 'nodeActive';
				if( itiva.nodeDetect.stop_on_detect )
				{
					window.clearInterval( itiva.nodeDetect.int_timer );
				}
			}
		}
		else if ( qmeshClientVersion ) { 
			itiva.nodeDetect.state = 'updateRequired'; }
		else 
			{
			itiva.nodeDetect.state = 'notDetected';
			}
		
		
		if( itiva.nodeDetect.on_detect_callback ) {
			itiva.nodeDetect.on_detect_callback();
		}
		
		if( itiva.nodeDetect.use_refresh )
			window.location.reload(true);
		else
			itiva.nodeDetect.appendDetectScript();

		return false;
	},

	// Public Functions
	init: function( min_ver , req_domain)
	{
		// Check for DOM functions we use
		if( !document.getElementById || !document.getElementsByTagName ) {
			return false; }
			
		//if( min_ver ) {
		//	itiva.nodeDetect.min_node_version = min_ver; }
			
		if (req_domain) {
			itiva.nodeDetect.required_domain = req_domain; }

		itiva.nodeDetect.appendDetectScript();
		
		if( !itiva.nodeDetect.int_timer )
		{
			itiva.nodeDetect.int_timer = window.setInterval( itiva.nodeDetect.checkVersion, 2000 );
		}
		return true;
	},
	
	status: function()
	{
		return itiva.nodeDetect.state;
	},
	
	setOnDetect: function( callback )
	{
		itiva.nodeDetect.on_detect_callback = callback;
		return true;
	},
	
	useRefresh: function()
	{
		itiva.nodeDetect.use_refresh = !itiva.nodeDetect.use_refresh;
		return true;
	}
}

itiva.platformDetect = {

	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	
	isSupported: function()
	{
		return ( ( this.OS == "win32" ) || ( this.OS=="osx-intel" ) || ( this.OS=="osx-ppc" ) );
	},
	
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.userAgent,
			subString: "Opera",
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "win32"
		},
		{
			string: navigator.platform,
			subString: "MacIntel",
			identity: "osx-intel"
		},
		{
			string: navigator.platform,
			subString: "MacPPC",
			identity: "osx-ppc"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "lin"
		}
	]

};


function SetPlayerVisibility( visibility )
{
	var container = document.getElementById( ContainerCtrl );
	if ( container != null )
	{
		if ( visibility )
		{
			container.style.visibility = "hidden";
			container.style.display = "none";			
		}
		else
		{
			container.style.visibility = "visibile";
			container.style.display = "block";		
		}
	}	
	var content = document.getElementById( containerElementName );
	if ( content != null )
	{
		if ( visibility )
		{
			content.style.visibility = "visible";
			content.style.display = "block";
		}
		else
		{
			content.style.visibility = "hidden";
			content.style.display = "none";		
		}
	}		
}

function setTarget(url)
{
	var target = document.getElementById( targetElementName );
	
	if (target != null)
	{
		target.src = url;
	}	
}

function prepareContainer()
{
	var container = document.getElementById( ContainerCtrl );
	var target = document.getElementById( targetElementName );
	
	if (container != null && target == null)
	{
		container.style.visibility = "visible";
		container.style.display = "block";
		container.innerHTML = '<iframe id="'+targetElementName+'" width="100%" height="100%" noscroll frameborder="0" border="0"></iframe>';
	}
	
	var content = document.getElementById( containerElementName );
	if ( content != null )
	{
		content.style.visibility = "hidden";
		content.style.display = "none";			
	}			
}

function processURL(url)
{
	var osParm = itiva.platformDetect.OS;
	if (qmeshClientVersion)
		url +="&qmver="+qmeshClientVersion;
	url += "&os="+osParm;
	return url;
}

function run( ver, domain )
{
	itiva.platformDetect.init();
	itiva.nodeDetect.setOnDetect( callback );
	itiva.nodeDetect.init( String( ver ), String(domain) );
}

function CheckState( domain, old_state )
{
	if ( activeLicense == undefined || activeLicense != '1' )
	{
		var error = "http://video." + domain + "/error_license.php";

		prepareContainer();
		setTarget( error );
	} 	

	var loc = false;
	var state = itiva.nodeDetect.status();
	var osParm = itiva.platformDetect.OS;

	var install = "http://video." + domain + "/install.php?os=" + osParm;
	var upgrade = "http://video." + domain + "/upgrade.php?os=" + osParm;
	var unsupported = "http://video." + domain + "/unsupported.php?os=" + osParm;
	var switchdomain = "http://video." + domain + "/switchdomain.php?os=" + osParm;

	if( !itiva.platformDetect.isSupported() && old_state != 'unsupported' )
	{
		old_state = 'unsupported';
		loc = unsupported;
		prepareContainer();
		setTarget( loc );
	}	
	else if( state == 'nodeActive' && old_state != 'nodeActive' && old_state != null )
	{
		SetPlayerVisibility( true );
		old_state = 'nodeActive';
		window.location.reload( true );
	}
	else if( state == 'notDetected' && old_state != 'notDetected' )
	{
		old_state = 'notDetected';
		loc = install;
		prepareContainer();
		setTarget( loc );
	}	
	else if( state == 'updateRequired' && old_state != 'updateRequired')
	{
		old_state = 'updateRequired';
		loc = upgrade;
		prepareContainer();
		setTarget( loc );
	}	
	else if ( state == 'wrongDomain' && old_state != 'wrongDomain' )
	{
		old_state = 'wrongDomain';
		loc = switchdomain;
		prepareContainer();
		setTarget( loc );			
	}
	return old_state;
}


function ShowVideoSL( domain, assetGuid, assetFileName, width, height, autoplay, container, initOffset, mode )
{
	if ( assetGuid == "" )
		return;
		
	if ( height == null )
		height = 450;
		
	if ( width == null )
		width = 800;
		
	if ( autoplay == null )
		autoplay = false;
		
	if ( width == 0 || height == 0 )
		return;
		
	var videoHost = "http://video." + domain;
	var playerId = Math.floor( Math.random() * 100001 );
	var localhost = null;
	
	var os = navigator.userAgent.toLowerCase();
	if ( os.indexOf("mac") != -1 )
		localhost = "http://127.0.0.1:25111/";
	else
		localhost = "http://localhost:25111/";
		
	var mediaSrc = localhost + assetGuid + ", ";
	if ( assetFileName && assetFileName != null && assetFileName != "" )
		mediaSrc = localhost + assetGuid + "/" + assetFileName + ", ";
	

	var code = '';

	code +=( "<div id='errorLocation" + playerId + "' style='font-size: small; color: Gray;'>" );
	code +=( "</div>" );
	
	code +=( "<object id='svl" + playerId + "' width='" + width + "px' height='" + height + "px' data='data:application/x-silverlight-2,' type='application/x-silverlight-2'>" );
	
	code +=( "<param name='source' value='" + videoHost + "/OVP.xap' /> " );
	code +=( "<param name='minRuntimeVersion' value='2.0.30923.0' />" );
	code +=( "<param name='onerror' value='onSilverlightError" + playerId + "' />" );
	code +=( "<param name='background' value='black' />" );
	code +=( "<param name='MaxFrameRate' value='30' />" );
	code +=( "<param name='enablehtmlaccess' value='true'/>" );
	code +=( "<param name='initparams' value='muted=false, playlistoverlay=true, theme=" + videoHost + "/themes/SmoothHD.xaml, " );
	code +=( "	 plugins=" + videoHost + "/plugins/ItivaVPModes.xap!, stretchmode=Fit, stretchmodefullscreen=Fit" );
	code +=( "	 , autoplay=" + autoplay );			
	code +=( "	 , mediasource=" + mediaSrc + " itiva:buffertime=10 " );	
	
	if ( mode == "b" )
	{
		code +=( "	 , mode=broadcast" );	
	}
	
	if ( initOffset && initOffset != null && initOffset > 0 )
	{
		code +=( "	 , itiva:offset=" + initOffset );	
	}
	
	code +=( "'/>" );		
	code +=( "</object>" );
	
	code +=( "<script language='javascript'>");
	code +=( "function onSilverlightError" + playerId + "( sender, args )" );
	code +=( "{");
	code +=( "	onSilverlightError( 'onSilverlightError" + playerId + "', sender, args );" ); 
	code +=( "}");
	code +=( "<\/sc" + "ript>" );	

	
	if (container == null || container == ''){
		document.write(code);
	} else {
		jQuery("#"+container).html(code);
	}		
}

var initPosCalled = null;

function ShowVideoFL( domain, assetGuid, assetFileName, width, height, autoplay, container, initOffset )
{
	if ( assetGuid == "" )
		return;
		
	if ( height == null )
		height = 450;
		
	if ( width == null )
		width = 800;
		
	if ( autoplay == null )
		autoplay = false;
		
	if ( width == 0 || height == 0 )
		return;
		
	var videoHost = "http://video." + domain;
	var playerId = Math.floor( Math.random() * 100001 );
	var localhost = null;
	var os = navigator.userAgent.toLowerCase();

	if ( os.indexOf("mac") != -1 )
		localhost = "http://127.0.0.1:25111/";
	else
		localhost = "http://localhost:25111/";

	var mediaSrc = localhost + assetGuid + "/" + assetFileName ;
	var code = '';

	code = ( "<a style='display:block; width:" + width + "px; height:" + height + "px; ' id='flv" + playerId + "'></a>" );

	code +=("<script language='javascript' type='text/javascript'>");
	code +=("var keys = {" );
	code +=("'climatetv.ca' : '#@9ceedcdf346d999eb40'," );
	code +=("'climatetv.tv' : '#@0ed59df4988c51b69be'," );
	code +=("'itiva.net' : '#@5a7e55673e93cbf1e3c'," );
	code +=("'xool.tv' : '#@60c0cc654e05d87077c'" );
	code +=("};" );

	code +=( "flowplayer('flv" + playerId + "', '" + videoHost + "/templates/flowplayer/flowplayer.commercial-3.1.5.swf', { " );
	code +=(" key : keys[location.host.replace('www.', '')] || keys[location.host.replace('video.', '')] || ''," );
	code +=( "	canvas:{backgroundColor:'#000000', backgroundGradient:'none'}, " );
	code +=( "	clip:  { " );
	code +=( "	url: '" + mediaSrc + "', " );
	code +=( "	autoPlay: " + autoplay + ", " ); 
	code +=( "	autoBuffering: true, " );
	code +=( "	scaling: 'fit', " );
	code +=( "	provider: 'seekto' " );

	if ( initOffset && initOffset != null && initOffset > 0 )		
	{
		if ( os.indexOf("mac") != -1 )
		{
			code +=( "	, onBufferFull: function(clip) { " );
			code +=( "      if (initPosCalled == null) " );
			code +=( "		{" );
			code +=( "			this.seek( " + initOffset + "); " ); 
			code +=( "			initPosCalled = 'yes'; " );
			code +=( "		}" );
			code +=( "	} " ); 
		}
		else
		{
			code +=( "	, onStart: function(clip) { " );
			code +=( "      if (initPosCalled == null) " );
			code +=( "		{" );
			code +=( "			this.seek( " + initOffset + "); " ); 
			code +=( "			initPosCalled = 'yes'; " );
			code +=( "		}" );
			code +=( "	} " ); 
		}	
	}		

	code +=( "	}," ); 

	code +=( "	plugins: {" );
	code +=( "	seekto: {" );
	code +=( "	url: '" + videoHost + "/templates/flowplayer/flowplayer.pseudostreaming-3.1.3.swf'" );
	code +=( "	}" );
	code +=( "}" );
	code +=( "});" );
	code +=( "<\/sc" + "ript>" );

	if ( container == null || container == '' ){
		document.write(code);
	} else {
		jQuery("#"+container).html(code);
	}
}


function ShowVideo( domain, assetGuid, assetFileName, width, height, autoplay, container, initOffset )
{
	var type = "wmv";
	if ( assetFileName && assetFileName != null )
	{
		var index = assetFileName.indexOf( '.flv' );
		if ( index != -1 && index == assetFileName.length - 4 )
			type = "flv";
		else
		{
			index = assetFileName.indexOf( '.mp4' );
			if ( index != -1 && index == assetFileName.length - 4 )
				type = "flv";		
			else
			{
				index = assetFileName.indexOf( '.f4v' );
				if ( index != -1 && index == assetFileName.length - 4 )
					type = "flv";			
			}						
		}	
	}		
		
	if ( type == "wmv" )
	{
		ShowVideoSL( domain, assetGuid, assetFileName, width, height, autoplay, container, initOffset );
	}
	else if ( type == "flv" )
	{
		ShowVideoFL( domain, assetGuid, assetFileName, width, height, autoplay, container, initOffset );
	}		
}


function onSilverlightError( errorLocationId, sender, args )
{
	var appSource = "";
	if (sender != null && sender != 0) {
		appSource = sender.getHost().Source;
	}
	var errorType = args.ErrorType;
	var iErrorCode = args.ErrorCode;

	var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";

	errMsg += "Code: " + iErrorCode + "    \n";
	errMsg += "Category: " + errorType + "       \n";
	errMsg += "Message: " + args.ErrorMessage + "     \n";

	if (errorType == "ParserError") {
		errMsg += "File: " + args.xamlFile + "     \n";
		errMsg += "Line: " + args.lineNumber + "     \n";
		errMsg += "Position: " + args.charPosition + "     \n";
	}
	else if (errorType == "RuntimeError") {
		if (args.lineNumber != 0) {
			errMsg += "Line: " + args.lineNumber + "     \n";
			errMsg += "Position: " + args.charPosition + "     \n";
		}
		errMsg += "MethodName: " + args.methodName + "     \n";
	}

	//document.getElementById(errorLocationId).innerHTML = errMsg;
	throw new Error(errMsg);
}

