

function Interface()
{
	this.UpNextHolder = document.getElementById("UpNextTitle");
	this.NowPlaying = document.getElementById("Info");
	this.AlertMessage = document.getElementById("AlertMessages");
	this.PlayerViewer = document.getElementById("Viewer");
	this.UpNextThumbnail = document.getElementById("UpNextImage");
	this.UpNextTitle = document.getElementById("UpNextTitle");
	this.PermalinkClip = document.getElementById("LinkClip");
	this.PermalinkEpisode = document.getElementById("LinkEpisode");
	this.BigBoxHolder = document.getElementById("BigBoxAdFrame");
	this.CatalogContainer = document.getElementById("CatalogContainer");
	this.UpNextTextArea = document.getElementById( "UpNextTextArea" );
	this.BreadCrumbList	= document.getElementById("BreadcrumbArea");
	this.MetaDataList = document.getElementById( "MetaDataArea" );
	this.SearchField = document.getElementById( "SearchQuery" );
	this.SocialEpisodeContainer =  document.getElementById( "SocialEpisode" );
	this.SocialClipContainer =  document.getElementById( "SocialClip" );
	this.MainArtistContainer = document.getElementById( "PurchaseLinks" );
    
    this.NowPlayingTitle = document.getElementById("NowPlayingTitle");

    this.CurrentShowName = document.getElementById("CurrentShowName");

    this.CurrentShowTitle = document.getElementById("CurrentShowTitle");

	this.CatalogContainerCache = new Array();
	this.PanelCache = new Array();
	
	this.wrappingDivName = "EmptyWrapper";
	this.loadingDivName  = "EmptyLoadingWrapper";
	
	this.SearchCalloutText = "Search for videos here";
	
	this.LastBigBoxDisplayed = null;
	this.RotateBigBoxInterval = 150;
	this.AllowUrlRewriting = true;
	this.SupportBackButton = false;
	
	this.currentAsyncRequest  = null;
	
	this.setTitleInterval	  = null;
	this.backButtonInterval   = null;
	
	this.currentInfiniteScrollRequest = null;
	
	this.hasLoadedTab		  = true;

    this.showSearchResultsTab = true;
	
	this.DoSecurityAudit();
	
	this.InitSearch();
}

Interface.FeaturedBinId = 0;

Interface.PlayClipFromId = function( pClipId )
{
	Playlist.PlayClipFromId( pClipId );
	
	return false;
}

Interface.GetInstance = function()
{
	if( ! Interface.__instance )
	{
		Interface.__instance = new Interface();
	}
	
	return Interface.__instance;
}

Interface.prototype.DoSecurityAudit = function()
{
	var isInAnIFrame = parent && window && parent != window;
	if( isInAnIFrame )
	{
		top.document.location = "/";
	}
}

Interface.prototype.InitSearch = function()
{
	var _Search			= this.SearchField;
	
	if( _Search.value == "" )
	{
		_Search.value		= this.SearchCalloutText;
	}
	
	var handlerFunctionKeyPress	= function( event ) { if( ! event ) event = window.event; return Interface.Search( true, event ) };
	
	_Search.onkeypress	= handlerFunctionKeyPress;
	if( _Search.onkeypress == handlerFunctionKeyPress )
	{
		// DO NOTHING
	}
	else if( _Search.addEventListener )
	{
		_Search.addEventListener( "keypress", handlerFunctionKeyPress, false );
	}
	else if( _Search.attachEvent ) 
	{
		_Search.attachEvent( "onkeypress", handlerFunctionKeyPress );
	}
		
	var handlerFunctionBlur		= function() { if( _Search.value == ''){ _Search.value = Interface.GetInstance().SearchCalloutText; } };
	
	_Search.onblur		= handlerFunctionBlur;
	if( _Search.onblur == handlerFunctionBlur )
	{
		// DO NOTHING
	}
	else if( _Search.addEventListener )
	{
		_Search.addEventListener( "blur", handlerFunctionBlur, false );
	}
	else if( _Search.attachEvent ) 
	{
		_Search.attachEvent( "onblur", handlerFunctionBlur );
	}
	
	var handlerFunctionFocus		= function() { if( _Search.value == Interface.GetInstance().SearchCalloutText ) { _Search.value=''; } };
	
	_Search.onfocus		= handlerFunctionFocus;
	if( _Search.onfocus == handlerFunctionFocus )
	{
		// DO NOTHING
	}
	else if( _Search.addEventListener )
	{
		_Search.addEventListener( "focus", handlerFunctionFocus, false );
	}
	else if( _Search.attachEvent ) 
	{
		_Search.attachEvent( "onfocus", handlerFunctionFocus );
	}
}

Interface.PlayEpisode = function( pVideoId, dontReturn )
{
	 Playlist.GetInstance().PlayEpisode( pVideoId );
	 Interface.Play_Clicked();
	 
	 if( dontReturn != true )
	 {
		return false;
	 }
	 
}
Interface.Play_Clicked = function( pVideo )
{
    try
    {
		Interface.ScrollToVideo();
	}
	catch(e) {}
}


Interface.PermalinkClicked = function( pUrl )
{
    window.open( pUrl );
}

Interface.ScrollToVideo = function()
{
	Scroller.scroll( Interface.GetInstance().PlayerViewer );
}

Interface.PermalinkFieldFocus = function( pField )
{
    if( pField.select )
    {
        pField.select();
    }
    
    Metrics.InteractedWithElement( "Permalink" );
    
    return false;
}

Interface.SocialButtonClicked = function( pNetworkName )
{
    var _Playlist = Playlist.GetInstance();
    var CurrentVideo;
    
    if( ! _Playlist.Current.IsAd )
    {
        CurrentVideo = _Playlist.Current;
    }
    else
    {
        CurrentVideo = _Playlist.FindNext();
    }
    
    var VideoTitle = CurrentVideo.Title;
    
    var UrlLocation;
    if( pNetworkName.match( "Episode" ) != null )
    {
        UrlLocation = CurrentVideo.EpisodePermalink;
    }
    else
    {
        UrlLocation = CurrentVideo.Permalink;
    }
    
	if( pNetworkName.match( "Facebook" ) != null )
	{
	        u=UrlLocation;t=VideoTitle;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'social','toolbar=0,status=0,width=626,height=436');return false;        
	}
	else if( pNetworkName.match( "Digg" ) != null )
	{
	        window.open('http://digg.com/submit?phase=2&url='+encodeURIComponent(UrlLocation)+'&title='+encodeURIComponent(VideoTitle), 'social','toolbar=no,scrollbars=yes,width=950,height=600');
	}
	else if( pNetworkName.match( "Delicious" ) != null )
	{
	        window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+encodeURIComponent(UrlLocation)+'&title='+encodeURIComponent(VideoTitle), 'social','toolbar=no,width=700,height=400');
    }
    else if( pNetworkName.match( "StumbleUpon" ) != null )
    {
            window.open('http://www.stumbleupon.com/submit?url='+encodeURIComponent(UrlLocation)+'&title='+encodeURIComponent(VideoTitle), 'social','toolbar=no,scrollbars=yes,width=950,height=600');
    }
    else if( pNetworkName.match( "Reddit" ) != null )
    {
            window.open('http://reddit.com/submit?url='+encodeURIComponent(UrlLocation)+'&title='+encodeURIComponent(VideoTitle), 'social','toolbar=no,scrollbars=yes,width=950,height=600');
	}
    else if( pNetworkName.match( "Twitter" ) != null )
    {
            window.open('http://twitter.com/home?status='+encodeURIComponent(UrlLocation)+'&title='+encodeURIComponent(VideoTitle), 'social','toolbar=no,scrollbars=yes,width=950,height=600');
	}
	
	Metrics.InteractedWithElement( "SocialButton_" + pNetworkName );
	
	return false;
}

Interface.Search = function( IsKeyChangeTriggered, event, Query)
{   
    if( IsKeyChangeTriggered )
    {
        if( ! event ) event = window.event;

        if( event.keyCode ) keyCode = event.keyCode;
        else if( event.which ) keyCode = event.which;

        if( keyCode != 13 )
        {
            return true;
        }
    }
	
	if( Interface.GetInstance().SearchField.value == Interface.GetInstance().SearchCalloutText )
	{
		Interface.GetInstance().SearchField.value = '';
	}
    
    if( Query )
    {
        Interface.GetInstance().SearchField.value = Query;
    }
    
    Interface.OpenTab( "SearchResults", true );
    Interface.GetSearchResultsFrame( Interface.GetInstance().CatalogContainer );    
    
    return false;
}
//JM - added new param
Interface.OpenMainTab = function( pName, featureBinId )
{
	Interface.OpenTab( pName, featureBinId);
	
	return false;
}


Interface.OpenSocialTab = function( pName, dontLoad )
{
    Metrics.NavigatedTo( "Tab_" + pName );
    var _Interface = Interface.GetInstance();

    var Nav = document.getElementById("SocialTabs");
    var Tabs = Nav.getElementsByTagName("li");
    var PassedClassRegex = new RegExp( ".*" + pName + ".*" );

    //iterate through each of the tabs    
    for( var i = 0; i < Tabs.length; i++ )
    {
        //found a tab that is selected
        if( Tabs[i].className.match(/.*Selected$/) && Tabs[i].className.match(PassedClassRegex) )
        {
            //do nothing
        }
        else if( Tabs[i].className.match(/.* Selected$/) )
        {
            //found one that is selected
            Tabs[i].className = Tabs[i].className.replace(/ Selected/, "");
        }
        else if( Tabs[i].className.match(PassedClassRegex) )
        {
            Tabs[i].className += " Selected";
        }
    }
    
	if( document.getElementById( pName ) )
	{
	    switch( pName )
        {
	        case "Permalinks":
		        document.getElementById( "SocialBookmarks" ).style.display = "none";
	            break;
	        case "SocialBookmarks":
	           document.getElementById( "Permalinks" ).style.display = "none";
	           break;
        }
	
	    document.getElementById( pName ).style.display = "block";
	}
}
//JM - added new params
Interface.OpenTab = function( pName, featureBinId, dontLoad  )
{
    Metrics.NavigatedTo( "Tab_" + pName );

    dontLoad = dontLoad == true;

    var _Interface = Interface.GetInstance();

    var Nav = document.getElementById("Nav");

    var Tabs = Nav.getElementsByTagName("li");

    var PassedClassRegex = new RegExp( ".*" + pName + ".*" );
    
    var wantsToRefreshVideoLibrary  = false;
    var wantsToSearch				= false;

    for( var i = 0; i < Tabs.length; i++ )
    {      
        if( Tabs[i].className.match(/.*Selected$/) && Tabs[i].className.match(PassedClassRegex) )
        {
            if( pName != "VideoLibrary" && pName != "SearchResults" )
            {
				return;
			}
			else
			{
				wantsToSearch = pName == "SearchResults";
				wantsToRefreshVideoLibrary = pName == "VideoLibrary";
			}
        }
        else if( Tabs[i].className.match(/.* Selected$/) )
        {
            // The previously selected tab
            Tabs[i].className = Tabs[i].className.replace(/ Selected/, "");
            
            if( _Interface.hasLoadedTab ) //only cache the previously selected tab, if it's fully loaded
            {
				var loadingDivs = document.getElementsByClassName( _Interface.loadingDivName );
  
			    for( j=0; j < loadingDivs.length; j++ )
			    {
				   var loadingColumn = -1;
				   
				   if( Tabs[ i ].className.indexOf("VideoLibrary") > -1 )
				   {
					  var columnId = "" + loadingDivs[ j ].id;
					  
					  loadingColumn = parseInt( columnId.substring( columnId.length -1 ) );
					  var column = document.getElementById( "Level" + loadingColumn );
					  
					  if( column )
					  {
							var elements = column.getElementsByTagName("ul");
							if( elements.length && elements.length > 0 && elements[0].getElementsByTagName )
							{
								elements = elements[0].getElementsByTagName("li");
							}
							
							for( k=0; k < elements.length; k++ )
							{
								elements[ k ].className = elements[ k ].className.replace( "Selected", "" );
							}
					  }
				   }
				   
				   loadingDivs[ j ].parentNode.removeChild( loadingDivs[ j ] );
			    }
			    
				_Interface.CatalogContainerCache[ Tabs[i].className.trim() ] = _Interface.CatalogContainer.innerHTML;
			}
        }
        else if( Tabs[i].className.match(PassedClassRegex) )
        {
			if( Tabs[i].className.indexOf( "SearchResults" ) > -1 )
            {
				if (this.showSearchResultsTab != false)
                { 
                    Tabs[i].style.display = "inline";
                }
            }
            // A newly selected tab
            Tabs[i].className += " Selected";  
        }
        else if(Tabs[i].className.indexOf(featureBinId) > 0 )
        {

                // A newly selected tab
                Tabs[i].className += " Selected";  
        }
    }

    _Interface.hasLoadedTab = !wantsToSearch && ! wantsToRefreshVideoLibrary && _Interface.CatalogContainerCache[ pName ] != null;

    if( dontLoad || ! _Interface.hasLoadedTab )
    {
		_Interface.CatalogContainer.innerHTML	= "";
         var loadingDivs						= document.getElementsByClassName( _Interface.loadingDivName );
         var theLoadingDiv						= document.createElement( "div" );
	   
	     theLoadingDiv.id						= _Interface.loadingDivName + "0";
	     theLoadingDiv.className				= _Interface.loadingDivName;
	   
	     theLoadingDiv.innerHTML	= "<img src='/themes/Comedy/images/Nav/loading.gif' />";
	   
	     _Interface.CatalogContainer.appendChild( theLoadingDiv );
    }

    if( !dontLoad )
    {
		// We already have a cache of the tab
		if( _Interface.CatalogContainerCache[ pName ] && ! wantsToRefreshVideoLibrary && ! wantsToSearch )
		{
		    _Interface.CatalogContainer.innerHTML = _Interface.CatalogContainerCache[ pName ];
		
			// Update the content in the cache if we need to
			switch( pName )
			{
			    case "Playlist":
					Interface.UpdatePlaylist( Playlist.GetInstance(), true );
					break;
			} 
		}
		// We need to get the content for the tab for the first time
		else
		{

            var name = pName;

            if (name.indexOf('Featured') == 0)
            {
                name = 'Featured';
            }
			// For each tab, asynchronously get the content
			switch( name )
			{
				case "VideoLibrary":
					Interface.GetVideoLibrary( _Interface.CatalogContainer );
					break;
				case "Featured":
				   Interface.GetFeaturedFrame( _Interface.CatalogContainer, featureBinId );
					break;
				case "Channels":
					Interface.GetMoreChannelsFrame( _Interface.CatalogContainer );
					break;
				case "Playlist":
					Interface.GetPlaylistFrame( _Interface.CatalogContainer );
					break;
				case "SearchResults":
					Interface.GetSearchResultsFrame( _Interface.CatalogContainer );
					break;	
				default:
					break;
			}
	        
			return;
		}

		if( pName == "VideoLibrary" )
		{
			Interface.GetInstance().scrollVideoLibraryToSelected();
		}
	}
}

Interface.DisplaySilverlightChoice = function( )
{
	var _Interface = Interface.GetInstance();
	var _Player = Player.GetInstance();
	
	if( _Player.Controller && _Player.Controller.Destroy ) { _Player.Controller.Destroy(); }
	_Player.Controller = null;
	
	_Interface.PlayerViewer.innerHTML = ''
	    + '<div class="Error">'
	    + '<h3>Please install Silverlight</h3>'
	    + '<p>Silverlight is Microsoft\'s new way of displaying high-quality video in all the major browsers.  It\'s safe and easy to <a href="http://www.microsoft.com/silverlight/install.aspx" target="_blank">install</a>.</p>'
	    + '<ul><li><a href="http://blog.ctvdigital.net/index.php/video-player/video-player-faq/#Silverlight" target="_blank">What is Silverlight?</a></li><li><a href="javascript:Player.GetInstance().Play( Playlist.GetInstance().Current )" onclick="Player.GetInstance().RejectedSilverlight=true">Watch the video without Silverlight</a></li></ul>'
	    + '<a class="PlayNextVideo" href="javascript:Interface.DisplaySilverlightInstall()">Install and watch!</a>'
	    + '</div>';
	    
	Metrics.NavigatedTo( "Silverlight_Choice" );
}

Interface.DisplaySilverlightInstall = function()
{
    window.open('http://www.microsoft.com/silverlight/install.aspx', 'silverlight','toolbar=no,scrollbars=yes,width=950,height=600');

    var _Player = Player.GetInstance();
	
	if( _Player.Controller && _Player.Controller.Destroy ) { _Player.Controller.Destroy(); }
	_Player.Controller = null;
	
	Interface.GetInstance().PlayerViewer.innerHTML = ''
	    + '<div class="Error">'
	    + '<h3>Thanks for installing Silverlight</h3>'
	    + '<p>Silverlight is Microsoft\'s new way of displaying high-quality video in all the major browsers.  It\'s safe and easy to <a href="http://www.microsoft.com/silverlight/install.aspx" target="_blank">install</a>.</p>'
	    + '<ul><li><a href="http://blog.ctvdigital.net/index.php/video-player/video-player-faq/#Silverlight" target="_blank">What is Silverlight?</a></li></ul>'
	    + '<a class="PlayNextVideo" href="javascript:Player.GetInstance().Play( Playlist.GetInstance().Current );">Watch your video now!</a>'
	    + '</div>';
    
    Metrics.NavigatedTo( "Silverlight_Install" );
}


Interface.OpenVideoLibrary = function( pLocation )
{   
    
    
    Interface.OpenTab( "VideoLibrary", true );
    Interface.GetVideoLibrary( Interface.GetInstance().CatalogContainer, pLocation );
}

Interface.GetVideoLibrary = function( pContainer, pLocation )
{
    var url = "/AJAX/VideoLibraryWithFrame.aspx";
    
    if( pLocation )
    {
        url += "?" + pLocation;
    }
 
    var successCallBack     =   function( html ) 
                                {
								    var Nav = document.getElementById("Nav");
									var Tabs = Nav.getElementsByTagName("li");
									
									var canContinue = false;
									
									if( pLocation )
									{
										for( i=0; i < Tabs.length; i++ )
										{
											if(  Tabs[i].className.match(/.*VideoLibrary.*/) && Tabs[i].className.match(/.*Selected$/) )
											{
												canContinue = true;
											}
										}
									}
									else
									{
										canContinue = true;
									}
									
									//if the currently selected tab is NOT VideoLibrary, drop this response
									if( ! canContinue )
									{
										return;
									}
									
								    var panelNumber = -1;
									var panel		= null;
										
									var parentType	= null;
									var parentId	= -1;
									var panelCacheId = null;
										
								   if( pLocation )
								   {
										panelNumber = ( pLocation.split( "&" ).length ) + 1;
										parentType	= ( pLocation.indexOf( "EpisodeId" ) > -1 ) ?  "Episode" : ( pLocation.indexOf( "SeasonId" ) > -1 ) ? "Season" : ( pLocation.indexOf( "ShowId" ) > -1 ) ? "Show" : null;
										
										if( parentType )
										{
											var ParentIdRegex = new RegExp( parentType + "Id=([0-9]+)" );
											var results = ParentIdRegex.exec( pLocation );
											parentId = results.length > 0 ? results[1] : null;
											
											var url = '/AJAX/VideoLibraryContents.aspx?GetChildOnly=true&PanelID=' + panelNumber + '&' + parentType + 'ID=' + parentId;
											
											// this will disable the cache for now
											panelCacheId = null; //Interface.GetInstance().GetPanelKey( url );
										}
								   }
								   
								   pContainer.innerHTML = html;
                                   Interface.GetInstance().hasLoadedTab = true;
								   Interface.GetInstance().scrollVideoLibraryToSelected();
								   
								   panel = document.getElementById( "Level" + panelNumber );
								  
                                   var hasInfiniteScroll = html.indexOf( "<ul class=\"HasInfiniteScroll\">" ) > -1 && panel && parentType && parentId > -1;

                                   if( hasInfiniteScroll )
                                   {
										Interface.InitInfiniteScrollingListeners( panel, parentType, parentId, panelCacheId );
                                   }
                                   
                                };
    var failureCallBack     =   function( error )
                                {
                                     Log( url + " had error: " + error );
                                };

    Interface.GetInstance().DoAsyncRequest( url, successCallBack, failureCallBack, true );
    
    return false;
}

Interface.prototype.scrollVideoLibraryToSelected = function()
{
	var oldLevels =  document.getElementById('VideoLibraryFrame').getElementsByTagName("div");
        
    for( i=0; i < oldLevels.length; i++ )
    {
		var elements = oldLevels[ i ].getElementsByTagName("ul");
		if( elements.length && elements.length > 0 && elements[0].getElementsByTagName )
		{
			elements = elements[0].getElementsByTagName("li");
		}
		
		for( j=0; j < elements.length; j++ )
		{
			var theLi = elements[ j ];
			
			if( theLi.className.indexOf("Selected") > -1 )
			{
				var theDiv			= theLi.parentNode.parentNode;
				theDiv.scrollTop	= theLi.offsetTop - 3;
				
				break;
			}
		}
    }
}

Interface.GetPlaylistFrame = function( pContainer )
{
    var url                 = "/AJAX/PlaylistFrame.aspx";
 
    var successCallBack     =   function( html ) 
                                {
                                   pContainer.innerHTML = html;
                                   Interface.UpdatePlaylist( Playlist.GetInstance(), true );
                                   Interface.GetInstance().hasLoadedTab = true;
                                };
    var failureCallBack     =   function( error )
                                {
                                     Log( url + " had error: " + error );
                                };
    
    Interface.GetInstance().DoAsyncRequest( url, successCallBack, failureCallBack, true  );
    
    return false;
}

Interface.GetFeaturedFrame = function( pContainer, featureBinId )
{

    var strUrl                 = "/AJAX/FeaturedFrame.aspx";

    strUrl                = strUrl + "?" + "BinId=" + featureBinId;
 
    var successCallBack     =   function( html ) 
                                {
                                   pContainer.innerHTML = html;
                                   Interface.GetInstance().hasLoadedTab = true;
                                };
    var failureCallBack     =   function( error )
                                {
                                    Log( strUrl + " had error: " + error );
                                };
    
    Interface.GetInstance().DoAsyncRequest( strUrl, successCallBack, failureCallBack, true );
    
    return false;
}

Interface.GetSearchResultsFrame = function( pContainer, GetResults )
{
	var QueryText = "";
	
	if( GetResults == null )
	{
	    GetResults = true;
	}
	
	if( GetResults )
	{
	    if( Interface.GetInstance().SearchField != null )
	    { 
		    QueryText = Interface.GetInstance().SearchField.value;
	    }
    		
        var url                 = "/AJAX/SearchResults.aspx?query=" + QueryText;
     
        var successCallBack     =   function( html ) 
                                    {
                                       pContainer.innerHTML = html;
                                       if( document.getElementById( "SearchResultsJSToEval" ) )
                                       {
										eval( document.getElementById( "SearchResultsJSToEval" ).innerHTML );
                                       }
                                       Interface.GetInstance().hasLoadedTab = true;
                                    };
        var failureCallBack     =   function( error )
                                    {
                                         Log( url + " had error: " + error );
                                    };
        
        Interface.GetInstance().DoAsyncRequest( url, successCallBack, failureCallBack, true  );
    }
    
    return false;
}

Interface.GetMoreChannelsFrame = function( pContainer )
{
    var url                 = "/AJAX/MoreChannelsFrame.aspx";
 
    var successCallBack     =   function( html ) 
                                {
                                   pContainer.innerHTML = html;
                                   Interface.GetInstance().hasLoadedTab = true;
                                };
    var failureCallBack     =   function( error )
                                {
                                     Log( url + " had error: " + error );
                                };
    
    Interface.GetInstance().DoAsyncRequest( url, successCallBack, failureCallBack, true  );
    
    return false;
}

Interface.prototype.SetBookmarkingTool = function( title, url )
{
	addthis_url = url;
	addthis_title = title;
}

Interface.SetNowPlaying = function( pVideo ) 
{
    var _Interface = Interface.GetInstance();
	
	var NowPlaying = _Interface.NowPlaying;
	
	if( ! pVideo )
	{
	    return;
	}

	if( Playlist.GetInstance().Current != null && Playlist.GetInstance().Current.IsAd )
	{
	    Interface.ShowAdIsPlayingMessage( pVideo );
	}
	
	if( pVideo.Title != "" && document.title )
	{
	   var titleToUse	= pVideo.Title.replace(/&quot;/g,"\"").replace(/&#39;/g,"\""); 
	   document.title	= titleToUse;
                               
       var titleToBeTruncated;
       var len =  70;
               
       if (titleToUse.length > len)
       {
           titleToBeTruncated = titleToUse.substring(0, len) + "...";
           _Interface.NowPlayingTitle.innerHTML = titleToBeTruncated;
       }
       else
       {
            _Interface.NowPlayingTitle.innerHTML = titleToUse;
       }

       $(_Interface.NowPlayingTitle).attr("title", titleToUse);

	   /* This section attempts to fix the flash/ie bug documented in bug 5359 */ 
	   var isIE = BrowserDetect && BrowserDetect.browser && BrowserDetect.browser.indexOf("Explorer") > -1;
	   
	   if( isIE )
	   {
			if( _Interface.setTitleInterval != null )
			{
				clearInterval( _Interface.setTitleInterval );
				_Interface.setTitleInterval = null; 
			}
			
			var fixingFunction =	function() 
									{
										var fixed = false;
										try { if( document.title != titleToUse && document.title.length > 0 && document.title.substring(0,1) == "#" ) { document.title = titleToUse; fixed = true; } if( fixed && _Interface.setTitleInterval != null ) { clearInterval( _Interface.setTitleInterval ); _Interface.setTitleInterval = null; }  }
										catch(e) {} 
									};

			_Interface.setTitleInterval = setInterval( fixingFunction, 350 );

	   }
	   /* End Section to fix bug 5359 */
	}
	else
	{
	   //document.title = "Video";
	}

    var artistHTML = "";
    
    if ( pVideo.Artist == "" )
    {
            artistHTML = '';
    }
    else
    {
            artistHTML =	'<li><a href="http://shopmobile.muchmusic.com/search.aspx?query=' + pVideo.Artist + '" title="Buy ' + pVideo.Artist + ' Ringtones" target="_blank" class="Ringtones">Buy ' + pVideo.Artist + ' Ringtones</a></li>' +
							'<li><a href="http://shopmusic.muchmusic.com/catalog/browse.aspx?artistname=' + pVideo.Artist + '" title="Buy ' + pVideo.Artist + ' Mp3s" target="_blank" class="Mp3s">Buy ' + pVideo.Artist + ' Mp3s</a></li>' +
							'<li><a href="http://www.muchmusic.com/search/?query=' + pVideo.Artist + '" title="' + pVideo.Artist +' Info" target="_blank" class="ArtistInfo">More info about ' + pVideo.Artist + '</a></li>';
    }
    
    var theWrapper = _Interface.MainArtistContainer;
    if( theWrapper )
    {    
        theWrapper.innerHTML = artistHTML;
    }
    
    
    

	if( _Interface.AllowUrlRewriting && _Interface.SupportBackButton )
	{
		if( _Interface.backButtonInterval != null )
		{
			clearInterval( _Interface.backButtonInterval );
			_Interface.backButtonInterval = null; 
		}
		
		var _Playlist = Playlist.GetInstance();
		
		var backButtonFunction = function() { if( _Playlist.Current && _Playlist.Current.IsAd == false && _Playlist.Current.ClipId != Player.ParseClipIdFromAddress() ) {  Playlist.PlayClipFromId( Player.ParseClipIdFromAddress() ); clearInterval( _Interface.backButtonInterval ); _Interface.backButtonInterval = null;  } };
		_Interface.backButtonInterval = setInterval( backButtonFunction, 350 );
	}
	
	_Interface.SetBookmarkingTool( document.title, pVideo.Permalink );
	
    var Title = pVideo.Title;
    
    if( Title == "" )
    {
        Title = "*Clip Id " + pVideo.ClipId;
    }
    
    var ClipTextBox			= _Interface.PermalinkClip.getElementsByTagName("input")[0];
    var EpisodeTextBox		= _Interface.PermalinkEpisode.getElementsByTagName("input")[0];

    var ClipTextBox			= _Interface.PermalinkClip.getElementsByTagName("input")[0];
    var EpisodeTextBox		= _Interface.PermalinkEpisode.getElementsByTagName("input")[0];
    
    var breadcrumbList		= _Interface.BreadCrumbList;
    
    var metadataList		= _Interface.MetaDataList;
     
    if( pVideo.Permalink )
    {
		ClipTextBox.value		= pVideo.Permalink;
	}
	else
	{
		ClipTextBox.value = "";
	}
	
	if( pVideo.EpisodePermalink )
	{
		EpisodeTextBox.value	= pVideo.EpisodePermalink;
	}
	else
	{
		EpisodeTextBox.value	= "";
	}
}

Interface.HideShowInternals = function( pDomItem, show )
{
	var items = pDomItem.getElementsByTagName( "*" );

	for( i = 0; i < items.length; i++ )
	{
		items[ i ].style.visibility = show  ? "" : "hidden";
	}
}

Interface.OnNextButton = function()
{
    var _Playlist = Playlist.GetInstance();
    
    if( _Playlist.Current.IsAd )
    {
        // If an ad is playing, the next item is already on deck.  So don't touch the playlist.
        /*
        _Playlist.MovePlaylistForward();
        Interface.SetNowPlaying( _Playlist.FindNext() );
	    Interface.SetUpNext( _Playlist.FindNext( 1 ) );
	
	    Interface.UpdatePlaylist( _Playlist );
	    */
    }
    else
    {
        
        _Playlist.Next( false, false );
    }
    
     Interface.ScrollToVideo();
}

Interface.GetDescriptionText = function( pVideo ) 
{
	return pVideo.Title;
}

Interface.SetUpNext = function( pVideo, forceShow ) 
{
    forceShow = forceShow == true;
    
    var _Interface = Interface.GetInstance();
    
    var Title = pVideo.Title;
    
    if( Title == "" )
    {
        Title = "*Clip Id " + pVideo.ClipId;
    }
	

}

Interface.UpdatePlaylist = function( pPlaylist, pIsOnTabChange )
{
    var _Interface = Interface.GetInstance();
    
    var FirstDiv = _Interface.CatalogContainer.getElementsByTagName("div")[0];
    if( FirstDiv && ! FirstDiv.className.match(/.*Playlist.*/) )
    {
        return;
    }
    
    var Holder;
    if( _Interface.CatalogContainer )
    {
        Holder = _Interface.CatalogContainer.getElementsByTagName("ul")[0];
    }
    else
    {
        return;
    }
    
    
    if( ! Holder )
    {
        return;
    }
    
        
    
    var Html = "";
    
    var LastHistoricVideo = null;
    
    if( pPlaylist.History.length > 0 )
    {
        for( var i = 0; i < pPlaylist.History.length; i++ )
        {
            if( LastHistoricVideo != pPlaylist.History[i] )
            {
                var imageHTML		= pPlaylist.History[i] && pPlaylist.History[i].Thumbnail == '' ? '' : ' <dd class="Thumbnail"><a href="javascript:Interface.OnMovePlayhead(' + -1 * ( pPlaylist.History.length - i ) + ');" title="Play Now"><img src="' + pPlaylist.History[i].Thumbnail + '/33/25/jpg/Image.ashx" alt="" /><span>&nbsp;</span></a></dd>';
                var canadaImageHTML = pPlaylist.History[i] && pPlaylist.History[i].IsCanadaOnly ? '<a href="#" title="Canada Only"><img src="/images/Catalog/Canada.gif" alt="Canada Only" /></a>' : '';
                
                Html += ''
                + '    <li class="Played">'
                + '      <dl>'
                + '        <dt><a href="javascript:Interface.OnMovePlayhead(' + -1 * ( pPlaylist.History.length - i ) + ');" title="Play Now">' + pPlaylist.History[i].Title + '</a>' + canadaImageHTML + '</dt>'
                +        imageHTML 
                + '      </dl>'
                + '    </li>';
                
                LastHistoricVideo = pPlaylist.History[i];
            }
        }
    }
    
    var NextVideo = null;
    
    if( pPlaylist.Current && ! pPlaylist.Current.IsAd )
    {
        var imageHTML		= pPlaylist.Current.Thumbnail == '' ? '' : '<dd class="Thumbnail"><a href="#" title="Play Now"><img src="' + pPlaylist.Current.Thumbnail + '/33/25/jpg/Image.ashx" alt="" /><span>&nbsp;</span></a></dd>';
        var canadaImageHTML = pPlaylist.Current.IsCanadaOnly ? '<a href="#" title="Canada Only"><img src="/images/Catalog/Canada.gif" alt="Canada Only" /></a>' : '';  
        
        Html += ''
            + '    <li class="Playing">'
            + '      <dl>'
            + '        <dt><a href="#" title="Play Now">' + pPlaylist.Current.Title + '</a>' + canadaImageHTML + '</dt>'
            +         imageHTML
            + '      </dl>'
            + '    </li>';
    }
    else if(
        ! pPlaylist.Current
        || ( pPlaylist.Current && pPlaylist.Current.IsAd )
    )
    {
        NextVideo			= pPlaylist.FindNext();
        
        var imageHTML		= NextVideo.Thumbnail == '' ? '' : '<dd class="Thumbnail"><a href="#" title="Play Now"><img src="' + NextVideo.Thumbnail + '/33/25/jpg/Image.ashx" alt="" /><span>&nbsp;</span></a></dd>';
        var canadaImageHTML = NextVideo.IsCanadaOnly ? '<a href="#" title="Canada Only"><img src="/images/Catalog/Canada.gif" alt="Canada Only" /></a>' : '';  
        
        Html += ''
            + '    <li class="Playing">'
            + '      <dl>'
            + '        <dt><a href="#" title="Play Now">' + NextVideo.Title + '</a>' + canadaImageHTML + '</dt>'
            +         imageHTML
            + '      </dl>'
            + '    </li>';
    }
    
    if( pPlaylist.Upcoming.length > 0 )
    {
        for( var i = 0, j = 1 ; i < pPlaylist.Upcoming.length; i++ )
        {
            if( i > 0 || pPlaylist.Upcoming[0] != NextVideo )
            {
                var imageHTML		= pPlaylist.Upcoming[i].Thumbnail == '' ? '' : '<dd class="Thumbnail"><a href="javascript:Interface.OnMovePlayhead(' + j + ')" title="Play Now"><img src="' + pPlaylist.Upcoming[i].Thumbnail + '/33/25/jpg/Image.ashx" alt="" /><span>&nbsp;</span></a></dd>';
				var canadaImageHTML = pPlaylist.Upcoming[i].IsCanadaOnly ? '<a href="#" title="Canada Only"><img src="/images/Catalog/Canada.gif" alt="Canada Only" /></a>' : '';  
        
                Html += ''
                    + '    <li class="ComingUp">'
                    + '      <dl>'
                    + '        <dt><a href="javascript:Interface.OnMovePlayhead(' + j + ')" title="Play Now">' + pPlaylist.Upcoming[i].Title + '</a>' + canadaImageHTML + '</dt>'
                    +         imageHTML
                    + '      </dl>'
                    + '    </li>';
                    
                    j++;
            }
        }
    }
    
    Holder.innerHTML = Html;
    
    _Interface.CatalogContainer.getElementsByTagName("h4")[0].getElementsByTagName("a")[0].innerHTML = "Clip id " + pPlaylist.FindNext().ClipId;
    
    //Holder.scrollTop = Holder.scrollHeight;
    
    var upNextVideo		=  pPlaylist.FindNext();
	var UpNextTextArea	= document.getElementById("UpNextTextArea");
	
	if( UpNextTextArea )
	{
		var imageHTML = upNextVideo.Thumbnail == '' ? '' : '<a href="javascript:Interface.OnNextButton()" title="Play Now" class="UpNextPlay"><img src="' + upNextVideo.Thumbnail + '/120/90/jpg/Image.ashx" alt="" /><span>&nbsp;</span></a>';
        
		Html =  imageHTML
			+ '<h4><a href="javascript:Interface.OnNextButton()" title="Play Now">' + upNextVideo.Title+'</a></h4>'
			+ '<p class="MetaData"> &nbsp; </p>'
			+ '<p>' + upNextVideo.Description + '</p>';
			
		UpNextTextArea.innerHTML = Html;
	}
	
	var isOnTabChange	 = pIsOnTabChange == true;

	var currentlyPlaying = document.getElementsByClassName("Playing")[0];
	
	if( isOnTabChange && currentlyPlaying )
	{
		var wrappingDiv		= currentlyPlaying.parentNode.parentNode;
		var headerHeight	= 0;
		
		Holder.scrollTop	= headerHeight + currentlyPlaying.scrollTop +  ( (wrappingDiv.scrollHeight - currentlyPlaying.clientHeight ) / 2 );
	}
	
}

Interface.OnMovePlayhead = function( Offset )
{
    Playlist.GetInstance().MovePlayhead( Offset );
    Interface.ScrollToVideo();
}

Interface.OnClearPlaylist = function()
{
    Playlist.GetInstance().ClearHistory();
    Playlist.GetInstance().ClearUpcoming();
}

Interface.OnClearHistory = function()
{
    Playlist.GetInstance().ClearHistory();
}

Interface.DisplayFlashNeedsToBeManuallyUpgradedMessage = function()
{
	var errorMessageHTML = '<div class="Error">';
		
		errorMessageHTML +=    '          <h3>Flash Upgrade Required</h3>';
		errorMessageHTML +=    '          <h4>Adobe&#039;s Flash Player (v6.0.65 or greater) is required to view this content</h4>';
		errorMessageHTML +=    '          <ul>';
		errorMessageHTML +=    '            <li><a target="_blank" href="http://www.adobe.com/products/flashplayer/" title="Flash Player Information">Information about Adobe Flash Player</a></li>';
		errorMessageHTML +=    '            <li><a target="_blank" href="http://www.adobe.com/products/flashplayer/productinfo/faq/" title="Flash Player FAQ">Adobe Flash Player FAQ</a></li>';
		errorMessageHTML +=    '          </ul>';
		errorMessageHTML +=    '          <a target="_blank" href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW" title="Get Flash Player" class="PlayNextVideo">Click here to to download and install the plugin for your browser.</a> </div>';
		errorMessageHTML +=    '</div>';
		
	var _Interface = Interface.GetInstance();
	var _Player = Player.GetInstance();
	
	if( _Player.Controller && _Player.Controller.Destroy ) { _Player.Controller.Destroy(); }
	_Player.Controller = null;
	
	_Interface.PlayerViewer.innerHTML = errorMessageHTML;
}

Interface.DisplayPlayerControllerError = function( pTitle, pSubtitle, pDescription, pNextAnchor )
{
	var _Interface = Interface.GetInstance();
	var _Player = Player.GetInstance();
	
	if( _Player.Controller && _Player.Controller.Destroy ) { _Player.Controller.Destroy(); }
	_Player.Controller = null;
	
	var NextAnchorHtml = "";
	
	if( pNextAnchor != null )
	{
	    NextAnchorHtml = '<a class="PlayNextVideo" href="javascript:Playlist.GetInstance().Next(true)">Skip to next video</a>';
	}
	
	_Interface.PlayerViewer.innerHTML = ''
	    + '<div class="Error">'
	    + '<h3>' + pTitle + '</h3>'
	    + '<h4>' + pSubtitle + '</h4>'
	    + '<ul><li><a href="http://blog.ctvdigital.net/index.php/video-player/feedback/" target="_blank">Report this error</a></li></ul>'
	    + NextAnchorHtml
	    + '</div>';
}

Interface.DisplayViewerDiscretionIsAdvised = function( pVideo )
{
	var _Interface = Interface.GetInstance();
	
	var pSubtitle;
	var pDescription;
	
	if( pVideo.Rating == TVRating.ParentalGuidance )
	{
	    pSubtitle = "This video is rated PG";
	    pDescription = "";
	}
	else if( pVideo.Rating == TVRating.Over14 )
	{
	    pSubtitle = "This video is rated 14+";
	    ImageUrl = "/images/Warnings/14.gif";
	    pDescription = "This video may contain material that some viewers may find unsuitable for children under 14 years of age.";
	}
	
	else if( pVideo.Rating == TVRating.Adults )
	{
	    pSubtitle = "This video is rated 18+";
	    ImageUrl = "/images/Warnings/18.gif";
	    pDescription = "May contain mature themes and subject matter unsuitable for younger viewers.";
	}
	
	_Interface.PlayerViewer.innerHTML = ''
	    + '<div class="Error Warning">'
	    + '<h3>Viewer Discretion is Advised</h3>'
	    + '<img src="'+ ImageUrl + '" width="157" height="135" />'
	    + '<h4>' + pSubtitle + '</h4>'
	    + '<p>' + pDescription + '</p>'
	    + '<ul><li><a href="http://www.cbsc.ca/english/agvot/ratings.php" target="_blank">More information on Canada\'s rating system</a></li></ul>'
	    + '<a class="PlayNextVideo" href="javascript:Player.GetInstance().Play( Playlist.GetInstance().Current );">Play Now</a>'
	    + '</div>';
	

    Interface.DisplayViewerDiscretionIsAdvised_CurrentVideo = pVideo;

	setTimeout( "Interface.DisplayViewerDiscretionIsAdvised_AfterAdvisory()", 7000 );
}

Interface.DisplayViewerDiscretionIsAdvised_AfterAdvisory = function()
{
    
    if( Interface.DisplayViewerDiscretionIsAdvised_CurrentVideo == Playlist.GetInstance().Current )
    {
        Player.GetInstance().Play( Playlist.GetInstance().Current );
    }
    
    Interface.DisplayViewerDiscretionIsAdvised_CurrentVideo = null; 
}

Interface.SetBigBoxAd = function( pUrl )
{
    
	var _Interface = Interface.GetInstance();
	var full = Player.Fullscreen;
	if (!full){
	    //dont do bigbox in fullscreen
	    //console.log("fullscreen, not loading bigbox");
	    
//	    console.log("Not fullscreen, loading bigbox");
	    if( ! pUrl )
	    {
	        var AdCall = "";
	        try
	        {
                AdCall = Ad.DARTVideoTag( Playlist.GetInstance().Current );
            }
            catch( err )
            {}
    	
		    pUrl = "http://ad.ca.doubleclick.net/adj/" + Ad.DARTSite + "/" + AdCall + ";sz=300x250;ord=" + Math.round( 10000000 * Math.random() );
	    }
	    else
	    {
		    pUrl = pUrl.replace ("http://ad.ca.doubleclick.net/adi/", "http://ad.ca.doubleclick.net/adj/" );
	    }
    	
	    pUrl = "/BigBoxAd.aspx?DartCall=" + pUrl;
    	
	    //_Interface.BigBoxHolder.src = pUrl;
	    try
	    {
		    var iframeDoc = _Interface.BigBoxHolder.contentDocument ? _Interface.BigBoxHolder.contentDocument : ( _Interface.BigBoxHolder.contentWindow ? _Interface.BigBoxHolder.contentWindow.document : document.frames[ 0 ] );
		    iframeDoc.location.replace( pUrl );
	    }
	    catch(e)
	    {
		    try { _Interface.BigBoxHolder.src = pUrl; } catch(ee) {}
	    }
    	
	    _Interface.LastBigBoxDisplayed = new Date();
	}

	setTimeout( "Interface.RotateBigBoxAd()", _Interface.RotateBigBoxInterval * 1000 );
}

Interface.RotateBigBoxAd = function()
{
	var _Interface = Interface.GetInstance();
	
	var Now = new Date();

	if( _Interface.LastBigBoxDisplayed != null )
	{
		var SecondsSinceLastAd = ( Now  - _Interface.LastBigBoxDisplayed ) / 1000;
		
		if( Playlist.GetInstance().Current && ( ! Playlist.GetInstance().Current.IsAd && SecondsSinceLastAd > _Interface.RotateBigBoxInterval  ) )
		{
			Interface.SetBigBoxAd();
			_Interface.LastBigBoxDisplayed = Now;
		}
		else
		{
		    setTimeout( "Interface.RotateBigBoxAd()", _Interface.RotateBigBoxInterval * 1000 );
		}
		
	}
}
Interface.UnToggleOthers = function( theAnchor )
{
	var theColumnElements = theAnchor.parentNode.parentNode.getElementsByTagName("li");

    for( i = 0; i < theColumnElements.length; i++ )
    {
		theColumnElements[ i ].className = theColumnElements[ i ].className.replace( "Selected", "" );
		theColumnElements[ i ].className = theColumnElements[ i ].className.replace( "Expanded", "" );
	
		var theToggleArea = theColumnElements[ i ].getElementsByTagName( "dl" );
		if( theToggleArea && theToggleArea.length > 0 )
		{ 
			theToggleArea = theToggleArea[ 0 ];
			theToggleArea.style.display = "";    
		}
    }
}

Interface.ToggleMe = function( theAnchor, isPlayButton )
{
    var theLi = theAnchor.parentNode;
	var isExpanding = true;
	
    if( theLi )
    {
        var theColumnElements = theLi.parentNode.getElementsByTagName("li");
        for( i = 0; i < theColumnElements.length; i++ )
        {
			if( theColumnElements[ i ] != theLi )
			{
				theColumnElements[ i ].className = theColumnElements[ i ].className.replace( "Selected", "" );
				theColumnElements[ i ].className = theColumnElements[ i ].className.replace( "Expanded", "" );
			
				var theToggleArea = theColumnElements[ i ].getElementsByTagName( "dl" );
				if( theToggleArea && theToggleArea.length > 0 )
				{ 
					theToggleArea = theToggleArea[ 0 ];
					theToggleArea.style.display = "";    
				}
			}
        }
        
        var theToggleArea = theLi.getElementsByTagName( "dl" );
        if ( theToggleArea && theToggleArea.length > 0 )
        {
            theToggleArea = theToggleArea[ 0 ];
            
            newStyle					= theToggleArea.style.display == "" ? "block" :
                                          theToggleArea.style.display == "block" ? "" : "";

            if( newStyle == "" && isPlayButton == true )
            {
				return true;
            }
            
            theToggleArea.style.display = newStyle;    
           	
           	isExpanding = newStyle == "block";            
 
          	if( isExpanding )
			{
				var theDiv			= theLi.parentNode.parentNode;

				var theLibottom		= theLi.offsetTop + theLi.clientHeight;
				var theDivBottom	= theDiv.scrollTop + theDiv.clientHeight;
				
				var theLiTop		= theLi.offsetTop;
				var theDivTop		= theDiv.scrollTop;
			
				var padding			= 2;
				if( theLibottom > theDivBottom )
				{
					theDiv.scrollTop += ( theLibottom - theDivBottom ) + padding;
				}
				else if( theLiTop  < theDivTop )
				{
					theDiv.scrollTop -= ( theDivTop - theLiTop ) + padding;
				}
			}
			else
			{
				var videoLibraryFrame   = document.getElementById('VideoLibraryFrame');
				var panelNumber			= theLi.parentNode.parentNode.id;
				panelNumber				= parseInt( panelNumber.substring( panelNumber.length - 1 ) ) + 1;

				Interface.RemoveOldPanels( panelNumber, videoLibraryFrame, true );
				
				var _Interface = Interface.GetInstance();
				
				// if you're requesting the clips currently, cancel that request
				if( _Interface.currentAsyncRequest != null )
				{
					_Interface.currentAsyncRequest = null;
				}
			}
			
			theLi.className = theLi.className.replace( "Expanded", "" );
			theLi.className = theLi.className.replace( "Selected", "" );
			
            if( isExpanding )
            {
                 theLi.className += " Expanded";      
            }
        }
    }

    return isExpanding;
}

Interface.prototype.GetPanelKey = function( PanelUrl )
{
    return PanelUrl.replace( /[^A-Za-z0-9/]/g, "" );
}

Interface.ShowAdIsPlayingMessage = function( pVideo )
{
	var _Interface		= Interface.GetInstance();
	_Interface.ShowHideVideoInfo( false );


	
	if( pVideo && pVideo.Title )
	{
		Interface.SetUpNext( pVideo, true );
		

	}	
}
Interface.ShowEpisodeIsLoadingMessage = function()
{
	var _Playlist = Playlist.GetInstance();
	var _Player =  Player.GetInstance();
	if( ( ! _Playlist.Current || ! _Playlist.Current.IsAd ) && ( _Player.Controller && _Player.Controller.Loading ) )
	{
		_Player.Controller.Loading();
	}
	
	var _Interface		= Interface.GetInstance();
	_Interface.ShowHideVideoInfo( false );
	

	
	Interface.ShowLoadingAnimation( 'loadingAnimation' );
}

Interface.ShowLoadingAnimation = function( toAnimate, interval )
{
	var animationArea = document.getElementById( toAnimate );

	if( animationArea )
	{
		if( (! interval ) || interval == 'undefined' )
		{
			var thisInterval;
			thisInterval = setInterval( function() { Interface.ShowLoadingAnimation( toAnimate, thisInterval ) }, 750  );	
		}	
		else
		{
			if( animationArea.innerHTML.length == 4 )
			{
				animationArea.innerHTML = "";
			}
			else
			{
				animationArea.innerHTML+= ".";
			}
		}
	}
	else
	{
		clearInterval( interval );
	}
}

Interface.ClearAlertMessages = function()
{
	var _Interface = Interface.GetInstance();

	
	_Interface.ShowHideVideoInfo( true );
}


Interface.prototype.ShowHideVideoInfo = function( showMessage )
{

}

Interface.GetChildPanel = function( parentType, parentId, panelNumber, theAnchor )
{
    var url                 = '/AJAX/VideoLibraryContents.aspx?GetChildOnly=true&PanelID=' + panelNumber + '&' + parentType + 'ID=' + parentId;
	if( parentType.toLowerCase() == 'episode' || parentType.toLowerCase() == 'season' )
	{
		 var showId			= -1;
		 var showPanel		= document.getElementById( "Level1" );
		 if( showPanel )
		 {
			 var allLIs       = showPanel.getElementsByTagName("li");
			 for( i=0; i < allLIs.length; i++ )
			 {
				var isSelectedShow = allLIs[ i ].className.toLowerCase().indexOf("selected") > -1 
				if( isSelectedShow )
				{
					try
					{
						showId = parseInt( "" + allLIs[ i ].getElementsByTagName( "a" )[ 0 ].id );
					}
					catch(e) {}
				}
			 }
		 }
		 
		if( showId > -1 )
		{
			url+= '&ForceParentShowID=' + showId;
		}
	}

    var videoLibraryFrame   = document.getElementById('VideoLibraryFrame');
    
    var _Interface = Interface.GetInstance();
    
    var PanelId = _Interface.GetPanelKey( url );

    if( ! _Interface.PanelCache[PanelId] )
    {
        var theTimeout = null;//setTimeout( function() { Interface.RemoveOldPanels( panelNumber, videoLibraryFrame ); }, 50 );
		Interface.RemoveOldPanels( panelNumber, videoLibraryFrame ); 
		
        var successCallBack     =   function( html ) 
                                    {
                                        var _Interface = Interface.GetInstance();
                                        var hasInfiniteScroll = html.indexOf( "<ul class=\"HasInfiniteScroll\">" ) > -1;
      
                                        _Interface.PanelCache[ PanelId ] = html;
                                        _Interface.ReplacePanel( html, videoLibraryFrame, panelNumber, theTimeout, hasInfiniteScroll, parentType, parentId, PanelId );
                                        
                                        
                                    };
        var failureCallBack     =   function( error )
                                    {
                                        Log( url + " had error: " + error );
                                        
                                        var loadingDivs = document.getElementsByClassName( _Interface.loadingDivName );
  
									    for( i=0; i < loadingDivs.length; i++ )
									    {
										   loadingDivs[ i ].parentNode.removeChild( loadingDivs[ i ] );
									    }
                                    };
        
        _Interface.DoAsyncRequest( url, successCallBack, failureCallBack, true );
    }
    else
    {
        
        var html = _Interface.PanelCache[PanelId];
        var hasInfiniteScroll = html.indexOf( "<ul class=\"HasInfiniteScroll\">" ) > -1 || html.toLowerCase().indexOf( "<ul class=hasinfinitescroll>" ) > -1;

        _Interface.currentAsyncRequest = null;
        _Interface.ReplacePanel( html, videoLibraryFrame, panelNumber, null, hasInfiniteScroll, parentType, parentId, PanelId );
    }
    
     var clickedPanel   = document.getElementById( "Level" + ( panelNumber-1 ) );
   
     if( clickedPanel )
     {
	     var allLIs       = clickedPanel.getElementsByTagName("li");

	     for( i=0; i < allLIs.length; i++ )
	     {
		  	var thisLI = allLIs[ i ];
  
			thisLI.className = thisLI.className.replace("Selected", "");
	         
			var LIclicked = theAnchor.parentNode;
			if( thisLI == LIclicked )
			{    
				thisLI.className += " Selected";
			}
	     }
     }

    return false;
}

Interface.RemoveOldPanels = function( panelNumber, videoLibraryFrame, dontShowLoading )
{
   var oldMatchingPanel     = document.getElementById( "Level" + panelNumber );
   var isOldMatchingPanel   = oldMatchingPanel != null;
   var toRemove             = new Array();
   var usedWidth			= 0;	
   var _Interface			= Interface.GetInstance();
	
   if ( isOldMatchingPanel )
   {
        var oldLevels = videoLibraryFrame.getElementsByTagName("div");
        
        for( i=0; i < oldLevels.length; i++ )
        {
            var level = oldLevels[ i ].id;
            var oldLevelNumber = level.substring( level.length - 1 );

           if( parseInt( oldLevelNumber ) >= panelNumber )
           {
                toRemove.push( oldLevels[ i ] );
           }
        }     
   }

   for( i=0; i < toRemove.length; i ++ )
   {
		var parent = toRemove[i].parentNode;
		parent.removeChild( toRemove[i] );
		
		if( parent.className == _Interface.wrappingDivName )
		{
			parent.parentNode.removeChild( parent );
		}
   }
   

  var loadingDivs = document.getElementsByClassName( _Interface.loadingDivName );
  
   for( i=0; i < loadingDivs.length; i++ )
   {
	  loadingDivs[ i ].parentNode.removeChild( loadingDivs[ i ] );
   }

   dontShowLoading = dontShowLoading == true;

   if( ! dontShowLoading )
   {
	   var theLoadingDiv		= document.createElement( "div" );

	   theLoadingDiv.id			= _Interface.loadingDivName + (panelNumber-1);
	   theLoadingDiv.className	= _Interface.loadingDivName;
	   
	   theLoadingDiv.innerHTML	= "<img src='/themes/Comedy/images/Nav/loading.gif' />";
	   
	   videoLibraryFrame.appendChild( theLoadingDiv );   
   }
}

Interface.prototype.ReplacePanel = function( html, videoLibraryFrame, panelNumber, oldTimeout, hasInfiniteScroll, parentType, parentId, panelCacheId )
{   
   if( oldTimeout )
   {
	clearTimeout( oldTimeout );
   }
   
   Interface.RemoveOldPanels( panelNumber, videoLibraryFrame, true );
   
   var theWrappingDiv		= document.createElement( "div" );
   
   theWrappingDiv.className	= this.wrappingDivName;
   theWrappingDiv.innerHTML	= html;
   
   videoLibraryFrame.appendChild( theWrappingDiv );
	
   hasInfiniteScroll = hasInfiniteScroll == true;
   
   if( hasInfiniteScroll )
   {
		var panel = document.getElementById( "Level" + panelNumber );
		
		Interface.InitInfiniteScrollingListeners( panel, parentType, parentId, panelCacheId );
   }
}

Interface.InitInfiniteScroll = function( parentType, parentId )
{
	var listToScroll = document.getElementsByClassName( "HasInfiniteScroll" );
	
	if( listToScroll.length > 0 )
	{
		listToScroll = listToScroll[ 0 ];
		
		var panel = listToScroll.parentNode;
		
		Interface.InitInfiniteScrollingListeners( panel,parentType, parentId, null );
	}
}

Interface.InitInfiniteScrollingListeners = function ( panel, parentType, parentId, panelCacheId )
{
	if( panel )
	{
		var handlerFunction =	function() 
								{
									var innerHeight		= panel.clientHeight;
									var height	= panel.scrollHeight;
									var scrolled	= panel.scrollTop;
									
									var shouldGetMoreClips = height - innerHeight - scrolled  < ( height / 2 );
									
									if( shouldGetMoreClips && Interface.GetInstance().currentInfiniteScrollRequest == null )
									{
										Interface.DoInfiniteScroll( panel, parentType, parentId, panelCacheId );
									}
								};
		
		panel.onscroll = handlerFunction;
		if( panel.onscroll == handlerFunction )
		{
			// DO NOTHING
		}
		else if( panel.addEventListener )
		{
			panel.addEventListener( "scroll", handlerFunction, false );
		}
		else if( panel.attachEvent ) 
		{
			panel.attachEvent( "onscroll", handlerFunction );
		}
	}
}

Interface.DoInfiniteScroll = function( panel, parentType, parentId, panelCacheId )
{
	var _Interface = Interface.GetInstance();
	
	var url = "/AJAX/InfiniteScrollingContents.aspx";
    var theList = null;
    
    if( parentType && parentId && panel )
    {
        theList = panel.getElementsByTagName("ul");
        
        var offset = 0;
 
        if( theList.length > 0 )
        {
			theList = theList[ 0 ];
			offset = theList.getElementsByTagName("li").length + 1;
        }
        else
        {
			return;
        }
        
        url += "?" + parentType + "ID=" + parentId + "&NumberToGet=6&StartOffset=" + offset;
    }
    else
    {
		return;
    }
 
    var successCallBack     =   function( html ) 
                                {
                                   if( html.indexOf( "</li>" ) == -1 ) //didnt find atleast one valid list item
                                   {
										panel.onscroll = null;
										if( panel.onscroll != null )
										{
											// DO NOTHING
										}
										else if( panel.removeEventListener )
										{
											panel.removeEventListener( "scroll", panel.onscroll, false );
										}
										else if( panel.removeEvent ) 
										{
											panel.detachEvent( "onscroll",  panel.onscrol );
										}
								   }
                                   else
                                   {
										theList.innerHTML += html;
										if( panelCacheId != null && panel && panel.parentNode )
										{
											Interface.GetInstance().PanelCache[ panelCacheId ] = panel.parentNode.innerHTML;
										}
								   }
								   
								   setTimeout( function() { Interface.GetInstance().currentInfiniteScrollRequest = null; }, 100 );
                                };
    var failureCallBack     =   function( error )
                                {
                                    Log( url + " had error: " + error );
                                     
                                    panel.onscroll = null;
                                    
									if( panel.onscroll != null )
									{
										// DO NOTHING
									}
									else if( panel.removeEventListener )
									{
										try
										{
											panel.removeEventListener( "scroll" );
										}
										catch(e) {}
									}
									else if( panel.removeEvent ) 
									{
										panel.removeEvent( "onscroll" );
									}
									
									setTimeout( function() { Interface.GetInstance().currentInfiniteScrollRequest = null; }, 100 );
                                };

    _Interface.currentInfiniteScrollRequest = _Interface.DoAsyncRequest( url, successCallBack, failureCallBack, false );
}

Interface.prototype.DoAsyncRequest = function( url, callbackFunction, errorFunction, isPanelReplacement )
{
	var myCallback = function( req, interfaceInstance, url, isUIReplacement ) 
	{  
		if ( req.readyState == 4 && req.status == 200 ) 
		{
			if( req == interfaceInstance.currentAsyncRequest || ! isUIReplacement )
			{
				callbackFunction( req.responseText );
			}
			else
			{
				//drop this request, it's an old one coming back late
			}
		}
		else if( req.readyState == 4 ) 
		{
			errorFunction( "Server Error Code: " + req.status );	
		}
		
		//interfaceInstance.currentInfiniteScrollRequest = null;	
	};

	var http_request;
	
	if ( window.XMLHttpRequest ) 
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			http_request.overrideMimeType('text/xml');
		}
	}
	else if ( window.ActiveXObject )
	{ 
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}		
		}
	}
	
	if ( ! http_request ) 
	{
		errorFunction( "Cannot create request" );
		return;
	}
	
		
	this.currentAsyncRequest = http_request;
	var Me = this;
	
	var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
	var isReplacement = isPanelReplacement == true;
	
	http_request.onreadystatechange = function() { myCallback( http_request, Me, url, isReplacement  ); };
	
	http_request.open('GET', url, true);
	http_request.setRequestHeader("Content-Type", contentType);
    http_request.send( null );	
	return http_request;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

document.getElementsByClassName = function(clsName)
{
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for (var i = 0; i < elements.length; i++)
    {
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

Interface.StripCounter = 0;
Interface.StripIndex = 0;

Interface.StripElementOverflow = function( elementHandle )
{
	var leaveFunction = Interface.StripCounter >= 40 || 
					( elementHandle.scrollHeight <= elementHandle.parentNode.scrollHeight );
	
	if ( !leaveFunction )
	{
		var data = elementHandle.innerHTML;
		data = data.replace(/[...]/g, "");
		
		Interface.StripIndex = Math.floor( data.length / 2 );
				
		var tempdata = data.substring( 0, ( Interface.StripIndex - Interface.StripCounter ) ) + "..." + data.substring( ( Interface.StripIndex + Interface.StripCounter +1 ) )
		elementHandle.innerHTML = tempdata;

		Interface.StripCounter++;
		Interface.StripElementOverflow( elementHandle ); //recursion	
	}
	else
	{
		Interface.StripCounter = 0;
		Interface.StripIndex = 0;
	}
}

/*--------------------------------------------------------------------------
 *  Smooth Scroller Script, version 1.0.1
 *  (c) 2007 Dezinerfolio Inc. <midart@gmail.com>
 *
 *  For details, please check the website : http://dezinerfolio.com/
 *
/*--------------------------------------------------------------------------*/

Scroller = {
	// control the speed of the scroller.
	// dont change it here directly, please use Scroller.speed=50;
	speed:0.5,

	// returns the Y position of the div
	gy: function (d) {
		gy = d.offsetTop
		if (d.offsetParent) while (d = d.offsetParent) gy += d.offsetTop
		return gy
	},

	// returns the current scroll position
	scrollTop: function (){
		body=document.body
	    d=document.documentElement
	    if (body && body.scrollTop) return body.scrollTop
	    if (d && d.scrollTop) return d.scrollTop
	    if (window.pageYOffset) return window.pageYOffset
	    return 0
	},

	// move the scroll bar to the particular div.
	scroll: function(d){
		i = window.innerHeight || document.documentElement.clientHeight;
		h=document.body.scrollHeight;

		a = Scroller.scrollTop()
		if(d<a)
			if(h-d>i)
				a+=Math.floor((d-a)/Scroller.speed)
			else
				a+=Math.floor((d-a-(h-d))/Scroller.speed)
		else
			a = a+(d-a)/Scroller.speed;
			
		window.scrollTo(0,a)
	  	if(a==d || Scroller.offsetTop==a)clearInterval(Scroller.interval)
	  	Scroller.offsetTop=a
	}
}
