

/*
 * SilverlightController: controls a Silverlight video player
 */
function SilverlightController( pTheme )
{
	this.Format = Format.WindowsMediaVideo;
	
	this.includeCounter		= 1;
	this.internalController = null;
	this.hasStartedJSInstantation	= false;
	this.JSisInstantiated	= false;
	
	this.theme				= "http://watch.thecomedynetwork.ca/themes/Comedy/player/theme.aspx";

	SilverlightController.IsCrossDomainLoad = pTheme!=null && pTheme != 'undefined' && ( ( SilverlightController.DetermineDomain( pTheme ) != SilverlightController.DetermineDomain( this.theme ) ) || ( SilverlightController.DetermineDomain( this.theme ) != SilverlightController.DetermineDomain( document.location ) ) ); 
	
	if( pTheme )
	{
		this.theme = pTheme;
	}
	
	SilverlightController.__instance = this;
	
	
	this.LoadHtml( );
}

SilverlightController.DetermineDomain = function( url )
{
	return parseUri( url ).host;
}

SilverlightController.GetInstance = function()
{
	if( ! SilverlightController.__instance )
	{
		SilverlightController.__instance = new SilverlightController();
	}
	
	return SilverlightController.__instance;
}

SilverlightController.prototype.Destroy = function()
{
   this.internalController = null;
}


SilverlightController.prototype.Play = function( pVideo )
{
	var permalinkToPass = ( pVideo.IsAd || FlashController.IsOneClipPlayer ) ? pVideo.Permalink : "";
	var shouldWait = ! this.JSisInstantiated;

	if(	this.internalController == null )
	{
		var Me = this;

		if( shouldWait )
		{
			if(! this.hasStartedJSInstantation )
			{
				this.LoadHtml();
			}
		}
		else
		{
			shouldWait = SilverlightController.IsCrossDomainLoad && document.getElementById( "xamlContent" ) == null;
		}
		
		if( shouldWait )
		{
			Log("Silverlight Player is not yet instantiated, sleeping 100 milliseconds.");
			
			setTimeout( function() { Me.Play( pVideo ); }, 100 );
			return;
		}
		else
		{
			Log("Silverlight Player is ready to play");
		}
		
		var parentElement		= Interface.GetInstance().PlayerViewer;
		parentElement.innerHTML = "";
		
		var SceneFile = "http://watch.thecomedynetwork.ca/SilverlightPlayer/Scene.xml";

		
		try
		{
			this.internalController = new SilverlightPlayer( parentElement, SceneFile, this.theme, pVideo.Url, pVideo.IsAd, pVideo.BugUrl, pVideo.Title, permalinkToPass, null);
		}
		catch(e)
		{ 
			try
			{
				setTimeout( function() { Me.internalController = new SilverlightPlayer( parentElement, SceneFile, this.theme, pVideo.Url, pVideo.IsAd, pVideo.BugUrl, pVideo.Title, permalinkToPass, null); }, 350  ); 
			}
			catch(ee)
			{
				setTimeout( function() { Me.internalController = new SilverlightPlayer( parentElement, SceneFile, this.theme, pVideo.Url, pVideo.IsAd, pVideo.BugUrl, pVideo.Title, permalinkToPass, null ); }, 1000  ); 
			}
		}
	}
	else
	{
		this.internalController.PlayUrl( pVideo.Url, pVideo.IsAd, pVideo.BugUrl, pVideo.Title, permalinkToPass, null );
	}
}

SilverlightController.prototype.Wait = function()
{
	if( this.internalController )
	{
		this.internalController.Wait()
	}
}

SilverlightController.prototype.getTimelinePosition = function(  )
{

    var ob = this.internalController.GetTimelinePosition();

    return ob;

}

SilverlightController.prototype.Loading = function()
{
	if( this.internalController )
	{
		this.internalController.Loading();
	}
}

SilverlightController.IsInstalled = function()
{
	return Silverlight.isInstalled( SilverlightPlayer.SilverlightVersion );
}

SilverlightController.prototype.LoadHtml = function()
{
	this.hasStartedJSInstantation = true;
	
	var includes = [ "createSilverlight.js",
					 "HttpRequest.js",
					 "Scene.xaml.js",
					 "MovieSlider.js",
					 "VolumeSlider.js",
					 "XAMLfactory.aspx",
					 "XAMLdata.js",
					 "ConfigXamlMapper.js",
					 "VideoPlayer.js"
					];
	

	if( SilverlightController.IsCrossDomainLoad )
	{
		this.AddFirstSceneFile();
	}
	
	this.AddJSIncludes( includes );	
}

SilverlightController.prototype.AddFirstSceneFile = function()
{
	var sceneId		= "xamlContent";
	
	if( ! document.getElementById( sceneId ) )
	{
		var body		= document.getElementsByTagName("body")[0];
		var newScript	= document.createElement("script");
		
		newScript.id	= sceneId;
		newScript.type	= "text/xaml";
		
		
		newScript.text = '<Canvas   xmlns="http://schemas.microsoft.com/client/2007"   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   Loaded="canvas_loaded"><Canvas.Resources><Storyboard Name="BufferingAnimation" Storyboard.TargetProperty="Angle" ><DoubleAnimation  From="0" To="360" Duration="0:0:2.16" RepeatBehavior="Forever" /></Storyboard><Storyboard Name="TextScrollAnimation" BeginTime="0:0:00" Storyboard.TargetProperty="(Canvas.Left)" ><DoubleAnimation Storyboard.TargetName="ScrollingText"   /><DoubleAnimation Storyboard.TargetName="ScrollingText2"  /><DoubleAnimation Storyboard.TargetName="ScrollingTextShadow"   /><DoubleAnimation Storyboard.TargetName="ScrollingText2Shadow"  /></Storyboard></Canvas.Resources><Canvas Name="PreloadImages" Opacity="0"></Canvas></Canvas>';

		body.appendChild( newScript );
		
		Log("Added the initial Silverlight scene to the page");
	}
	else
	{
		Log("Silverlight scene is already on the page");
	}
}

SilverlightController.prototype.AddJSIncludes = function( filePaths )
{
	this.includeCounter = filePaths.length;
	
	for( var i=0; i < filePaths.length; i++ )
	{
		var newID			= "SilverlightScript" + (i+1);
		
		var Me				= this;
		var fileName		= filePaths[ i ];
		var handlerFunction	= new function() { Me.JSisInstantiated = ( --Me.includeCounter <= 0 );  Log("INCLUDE ADDED:" + fileName + "  " + Me.includeCounter + " left"); };
			
		if( ! document.getElementById( newID ) )
		{
			var head		= document.getElementsByTagName("head")[0];
			var newScript	= document.createElement("script");
			
			newScript.type	= "text/javascript";
			newScript.src	= "http://watch.thecomedynetwork.ca/SilverlightPlayer/" + filePaths[ i ];
			newScript.id	= newID;
			
			newScript.onload = handlerFunction;
			if( newScript.onload == handlerFunction )
			{
				// DO NOTHING
			}
			else if( newScript.addEventListener )
			{
				newScript.addEventListener( "load", handlerFunction, false );
			}
			else if( newScript.attachEvent ) 
			{
				newScript.attachEvent( "onload", handlerFunction );
			}
			
			head.appendChild( newScript );
		}
		else
		{
			Log( fileName + " is already on the page." );
			this.JSisInstantiated = ( --this.includeCounter <= 0 );
		}
	}
}


///////////////////////////////////////////////////////////////////////////////
//
//  Silverlight.js   			version 2.0.30523.6
//
//  This file is provided by Microsoft as a helper file for websites that
//  incorporate Silverlight Objects. This file is provided under the Microsoft
//  Public License available at 
//  http://code.msdn.microsoft.com/silverlightjs/Project/License.aspx.  
//  You may not use or distribute this file or the code in this file except as 
//  expressly permitted under that license.
// 
//  Copyright (c) Microsoft Corporation. All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////

if (!window.Silverlight)
{
    window.Silverlight = { };
}

//////////////////////////////////////////////////////////////////
//
// _silverlightCount:
//
// Counter of globalized event handlers
//
//////////////////////////////////////////////////////////////////
Silverlight._silverlightCount = 0;

//////////////////////////////////////////////////////////////////
//
// fwlinkRoot:
//
// Prefix for fwlink URL's
//
//////////////////////////////////////////////////////////////////
Silverlight.fwlinkRoot='http://go2.microsoft.com/fwlink/?LinkID=';

//////////////////////////////////////////////////////////////////
//  
// onGetSilverlight:
//
// Called by Silverlight.GetSilverlight to notify the page that a user
// has requested the Silverlight installer
//
//////////////////////////////////////////////////////////////////
Silverlight.onGetSilverlight = null;

//////////////////////////////////////////////////////////////////
//
// onSilverlightInstalled:
//
// Called by Silverlight.WaitForInstallCompletion when the page detects
// that Silverlight has been installed. The event handler is not called
// in upgrade scenarios.
//
//////////////////////////////////////////////////////////////////
Silverlight.onSilverlightInstalled = function () {window.location.reload(false);};

//////////////////////////////////////////////////////////////////
//
// isInstalled:
//
// Checks to see if the correct version is installed
//
//////////////////////////////////////////////////////////////////
Silverlight.isInstalled = function(version)
{
    var isVersionSupported=false;
    var container = null;
    
    try 
    {
        var control = null;
        
        try
        {
            control = new ActiveXObject('AgControl.AgControl');
            if ( version == null )
            {
                isVersionSupported = true;
            }
            else if ( control.IsVersionSupported(version) )
            {
                isVersionSupported = true;
            }
            control = null;
        }
        catch (e)
        {
            var plugin = navigator.plugins["Silverlight Plug-In"] ;
            if ( plugin )
            {
                if ( version === null )
                {
                    isVersionSupported = true;
                }
                else
                {
                    var actualVer = plugin.description;
                    if ( actualVer === "1.0.30226.2")
                        actualVer = "2.0.30226.2";
                    var actualVerArray =actualVer.split(".");
                    while ( actualVerArray.length > 3)
                    {
                        actualVerArray.pop();
                    }
                    while ( actualVerArray.length < 4)
                    {
                        actualVerArray.push(0);
                    }
                    var reqVerArray = version.split(".");
                    while ( reqVerArray.length > 4)
                    {
                        reqVerArray.pop();
                    }
                    
                    var requiredVersionPart ;
                    var actualVersionPart
                    var index = 0;
                    
                    
                    do
                    {
                        requiredVersionPart = parseInt(reqVerArray[index]);
                        actualVersionPart = parseInt(actualVerArray[index]);
                        index++;
                    }
                    while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
                    
                    if ( requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart) )
                    {
                        isVersionSupported = true;
                    }
                }
            }
        }
    }
    catch (e) 
    {
        isVersionSupported = false;
    }
    if (container) 
    {
        document.body.removeChild(container);
    }
    
    return isVersionSupported;
}
//////////////////////////////////////////////////////////////////
//
// WaitForInstallCompletion:
//
// Occasionally checks for Silverlight installation status. If it
// detects that Silverlight has been installed then it calls
// Silverlight.onSilverlightInstalled();. This is only supported
// if Silverlight was not previously installed on this computer.
//
//////////////////////////////////////////////////////////////////
Silverlight.WaitForInstallCompletion = function()
{
    if ( ! Silverlight.isBrowserRestartRequired && Silverlight.onSilverlightInstalled )
    {
        try
        {
            navigator.plugins.refresh();
        }
        catch(e)
        {
        }
        if ( Silverlight.isInstalled(null) )
        {
            Silverlight.onSilverlightInstalled();
        }
        else
        {
              setTimeout(Silverlight.WaitForInstallCompletion, 3000);
        }    
    }
}
//////////////////////////////////////////////////////////////////
//
// __startup:
//
// Performs startup tasks
//////////////////////////////////////////////////////////////////
Silverlight.__startup = function()
{
    Silverlight.isBrowserRestartRequired = Silverlight.isInstalled(null);
    if ( !Silverlight.isBrowserRestartRequired)
    {
        Silverlight.WaitForInstallCompletion();
    }
    if (window.removeEventListener) { 
       window.removeEventListener('load', Silverlight.__startup , false);
    }
    else { 
        window.detachEvent('onload', Silverlight.__startup );
    }
}

if (window.addEventListener) 
{
    window.addEventListener('load', Silverlight.__startup , false);
}
else 
{
    window.attachEvent('onload', Silverlight.__startup );
}

///////////////////////////////////////////////////////////////////////////////
// createObject:
//
// Inserts a Silverlight <object> tag or installation experience into the HTML
// DOM based on the current installed state of Silverlight. 
//
/////////////////////////////////////////////////////////////////////////////////

Silverlight.createObject = function(source, parentElement, id, properties, events, initParams, userContext)
{
    var slPluginHelper = new Object();
    var slProperties = properties;
    var slEvents = events;
    
    slPluginHelper.version = slProperties.version;
    slProperties.source = source;    
    slPluginHelper.alt = slProperties.alt;
    
    //rename properties to their tag property names. For bacwards compatibility
    //with Silverlight.js version 1.0
    if ( initParams )
        slProperties.initParams = initParams;
    if ( slProperties.isWindowless && !slProperties.windowless)
        slProperties.windowless = slProperties.isWindowless;
    if ( slProperties.framerate && !slProperties.maxFramerate)
        slProperties.maxFramerate = slProperties.framerate;
    if ( id && !slProperties.id)
        slProperties.id = id;
    
    // remove elements which are not to be added to the instantiation tag
    delete slProperties.ignoreBrowserVer;
    delete slProperties.inplaceInstallPrompt;
    delete slProperties.version;
    delete slProperties.isWindowless;
    delete slProperties.framerate;
    delete slProperties.data;
    delete slProperties.src;
    delete slProperties.alt;


    // detect that the correct version of Silverlight is installed, else display install

    if (Silverlight.isInstalled(slPluginHelper.version))
    {
        //move unknown events to the slProperties array
        for (var name in slEvents)
        {
            if ( slEvents[name])
            {
                if ( name == "onLoad" && typeof slEvents[name] == "function" && slEvents[name].length != 1 )
                {
                    var onLoadHandler = slEvents[name];
                    slEvents[name]=function (sender){ return onLoadHandler(document.getElementById(id), userContext, sender)};
                }
                var handlerName = Silverlight.__getHandlerName(slEvents[name]);
                if ( handlerName != null )
                {
                    slProperties[name] = handlerName;
                    slEvents[name] = null;
                }
                else
                {
                    throw "typeof events."+name+" must be 'function' or 'string'";
                }
            }
        }
        slPluginHTML = Silverlight.buildHTML(slProperties);
    }
    //The control could not be instantiated. Show the installation prompt
    else 
    {
        slPluginHTML = Silverlight.buildPromptHTML(slPluginHelper);
    }

    // insert or return the HTML
    if(parentElement)
    {
        parentElement.innerHTML = slPluginHTML;
    }
    else
    {
        return slPluginHTML;
    }

}

///////////////////////////////////////////////////////////////////////////////
//
//  buildHTML:
//
//  create HTML that instantiates the control
//
///////////////////////////////////////////////////////////////////////////////
Silverlight.buildHTML = function( slProperties)
{
    var htmlBuilder = [];

    htmlBuilder.push('<object type=\"application/x-silverlight\" data="data:application/x-silverlight,"');
    if ( slProperties.id != null )
    {
        htmlBuilder.push(' id="' + slProperties.id + '"');
    }
    if ( slProperties.width != null )
    {
        htmlBuilder.push(' width="' + slProperties.width+ '"');
    }
    if ( slProperties.height != null )
    {
        htmlBuilder.push(' height="' + slProperties.height + '"');
    }
    htmlBuilder.push(' >');
    
    delete slProperties.id;
    delete slProperties.width;
    delete slProperties.height;
    
    for (var name in slProperties)
    {
        if (slProperties[name])
        {
            htmlBuilder.push('<param name="'+Silverlight.HtmlAttributeEncode(name)+'" value="'+Silverlight.HtmlAttributeEncode(slProperties[name])+'" />');
        }
    }
    htmlBuilder.push('<\/object>');
    return htmlBuilder.join('');
}



//////////////////////////////////////////////////////////////////
//
// createObjectEx:
//
// takes a single parameter of all createObject 
// parameters enclosed in {}
//
//////////////////////////////////////////////////////////////////

Silverlight.createObjectEx = function(params)
{
    var parameters = params;
    var html = Silverlight.createObject(parameters.source, parameters.parentElement, parameters.id, parameters.properties, parameters.events, parameters.initParams, parameters.context);
    if (parameters.parentElement == null)
    {
        return html;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// buildPromptHTML
//
// Builds the HTML to prompt the user to download and install Silverlight
//
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.buildPromptHTML = function(slPluginHelper)
{
    var slPluginHTML = "";
    var urlRoot = Silverlight.fwlinkRoot;
    var shortVer = slPluginHelper.version ;
    if ( slPluginHelper.alt )
    {
        slPluginHTML = slPluginHelper.alt;
    }
    else
    {
        if (! shortVer )
        {
            shortVer="";
        }
        slPluginHTML = "<a href='javascript:Silverlight.getSilverlight(\"{1}\");' style='text-decoration: none;'><img src='{2}' alt='Get Microsoft Silverlight' style='border-style: none'/></a>";
        slPluginHTML = slPluginHTML.replace('{1}', shortVer );
        slPluginHTML = slPluginHTML.replace('{2}', urlRoot + '108181');
    }
    
    return slPluginHTML;
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// getSilverlight:
//
// Navigates the browser to the appropriate Silverlight installer
//
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.getSilverlight = function(version)
{
    if (Silverlight.onGetSilverlight )
    {
        Silverlight.onGetSilverlight();
    }
    
    var shortVer = "";
    var reqVerArray = String(version).split(".");
    if (reqVerArray.length > 1)
    {
        var majorNum = parseInt(reqVerArray[0] );
        if ( isNaN(majorNum) || majorNum < 2 )
        {
            shortVer = "1.0";
        }
        else
        {
            shortVer = reqVerArray[0]+'.'+reqVerArray[1];
        }
    }
    
    var verArg = "";
    
    if (shortVer.match(/^\d+\056\d+$/) )
    {
        verArg = "&v="+shortVer;
    }
    
    Silverlight.followFWLink("114576" + verArg);
}


///////////////////////////////////////////////////////////////////////////////////////////////
//
// followFWLink:
//
// Navigates to a url based on fwlinkid
//
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.followFWLink = function(linkid)
{
    top.location=Silverlight.fwlinkRoot+String(linkid);
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// HtmlAttributeEncode:
//
// Encodes special characters in input strings as charcodes
//
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.HtmlAttributeEncode = function( strInput )
{
      var c;
      var retVal = '';

    if(strInput == null)
      {
          return null;
    }
      
      for(var cnt = 0; cnt < strInput.length; cnt++)
      {
            c = strInput.charCodeAt(cnt);

            if (( ( c > 96 ) && ( c < 123 ) ) ||
                  ( ( c > 64 ) && ( c < 91 ) ) ||
                  ( ( c > 43 ) && ( c < 58 ) && (c!=47)) ||
                  ( c == 95 ))
            {
                  retVal = retVal + String.fromCharCode(c);
            }
            else
            {
                  retVal = retVal + '&#' + c + ';';
            }
      }
      
      return retVal;
}
///////////////////////////////////////////////////////////////////////////////
//
//  default_error_handler:
//
//  Default error handling function 
//
///////////////////////////////////////////////////////////////////////////////

Silverlight.default_error_handler = function (sender, args)
{
    var iErrorCode;
    var errorType = args.ErrorType;

    iErrorCode = args.ErrorCode;

    var errMsg = "\nSilverlight error message     \n" ;

    errMsg += "ErrorCode: "+ iErrorCode + "\n";


    errMsg += "ErrorType: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError")
    {
        errMsg += "XamlFile: " + 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";
    }
    alert (errMsg);
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// __cleanup:
//
// Releases event handler resources when the page is unloaded
//
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__cleanup = function ()
{
    for (var i = Silverlight._silverlightCount - 1; i >= 0; i--) {
        window['__slEvent' + i] = null;
    }
    Silverlight._silverlightCount = 0;
    if (window.removeEventListener) { 
       window.removeEventListener('unload', Silverlight.__cleanup , false);
    }
    else { 
        window.detachEvent('onunload', Silverlight.__cleanup );
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// __getHandlerName:
//
// Generates named event handlers for delegates.
//
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__getHandlerName = function (handler)
{
    var handlerName = "";
    if ( typeof handler == "string")
    {
        handlerName = handler;
    }
    else if ( typeof handler == "function" )
    {
        if (Silverlight._silverlightCount == 0)
        {
            if (window.addEventListener) 
            {
                window.addEventListener('onunload', Silverlight.__cleanup , false);
            }
            else 
            {
                window.attachEvent('onunload', Silverlight.__cleanup );
            }
        }
        var count = Silverlight._silverlightCount++;
        handlerName = "__slEvent"+count;
        
        window[handlerName]=handler;
    }
    else
    {
        handlerName = null;
    }
    return handlerName;
}







/*
	parseUri 1.2.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
