
//------------------------------------------------------------------------------
//  Encapsulates all kontiki UI related work
//------------------------------------------------------------------------------
function CliKontikiHosted(clientController, propositionInstance, profileName, authToken, authSignature ) {
   
    /* ----------------------------------------------- */
    /*           private static (class) members        */
    /* ----------------------------------------------- */
    var ROOT_FRAME_NAME = "root";
    var PLAYER_FRAME_NAME = "player";
	var SAMPLESTREAM_FRAME_NAME = "sampleStream";
    var PAGE_STYLE = 'class=browser,width=1024,height=768,position=1,resize=1,scrollbars=1,visible=1';
    var PLAYER_PAGE_STYLE = 'class=browser,width=625,height=585,position=1,resize=1,scrollbars=1,visible=1';
    var LIVETV_PLAYER_PAGE_STYLE = 'class=browser,width=680,height=404,position=1,resize=1,scrollbars=1,visible=1';
    var SAMPLESTREAM_PAGE_STYLE = 'class=browser,width=640,height=440,position=1,resize=1,scrollbars=1,visible=1';
    
    // The following pages are from the cache but we do not use the cache: prefix as they are all relative to the RootFrameset page
    var CACHED_EULA_PAGE = 'cache:EULA.htm';
    var CACHED_PCNAME_PAGE = 'cache:PCName.htm';
    var CACHED_LIBRARY_PAGE = 'cache:OfflineLibrary.htm';
    var CACHED_PLAYER_PAGE = 'cache:MediaPlayer.htm';
    var CACHED_MISSING_SETTINGS_PAGE = 'cache:MissingSettings.htm';
    var CACHED_NO_LICENSE_PAGE = 'cache:LicenseAcquisition.htm';
    var CACHED_START_PAGE = 'cache:StartPage.htm';
    var RELATIVE_CACHED_START_PAGE = "StartPage.htm";
    
    //TODO ensure these pages point to the correct pages online
    var ONLINE_HOME_PAGE = CliBuilOnlineUrl( "/page/home.do" );
    var ONLINE_HYBRID_STARTUP_PAGE = CliBuilOnlineUrl( "/page/hybridLaunch.do?requestedUrl=" );
    var ONLINE_LOGOUT_PAGE = CliBuilOnlineUrl( "/content/Home/Application-Navigation/Logout/content/logout.do" );

    
    var _clientController;
    var _propositionInstance;
    var _profileName;
    var _kdxApi;
    
    

    
    
    /* ----------------------------------------------- */
    /*           class constructor                     */
    /* ----------------------------------------------- */
    this.init = function CliKontikiHosted_initialize(clientController, propositionInstance, profileName, authToken, authSignature)
    {
        _clientController = clientController;
        _propositionInstance = propositionInstance;
        _profileName = profileName;
        
        try {
            _kdxApi = new ActiveXObject("KDX.SecureApi");
            _kdxApi.authorize(authToken, authSignature);
        }
        catch (e) {
            CliDebug('Unable to authorise kontiki: ' + e.message);
        }
 
    }
    
    
    /* ----------------------------------------------- */
    /*              private methods                    */
    /* ----------------------------------------------- */
    
    /*  accessor for the kdxapi  */
    CliKontikiHosted.prototype.getKdxApi = function() { return _kdxApi;}
    
    /*  launches a page in a new kdxsecureframe */
    function _launchPageInNewTemplate(page, style, kdxUrn, kdxFrameName)
    {
        if (kdxUrn==null) kdxUrn='';
        var kdxFrame = _kdxApi.launchTemplate( page, style, kdxUrn, kdxFrameName);
    }

    /*  launches a page in an existing kdxsecureframe if one exists.  if not, a new one is created  */
    function _launchPageReuseTemplateIfAvailable( page, style, kdxUrn, kdxFrameName )
    {
    
        if( kdxUrn == null ) kdxUrn = '';
        
        try
        {
            var kdxFrame = _kdxApi.getFrame( kdxUrn, kdxFrameName );
            
            if( kdxFrame == null )
                _launchPageInNewTemplate( page, style, kdxUrn, kdxFrameName );
            else
            {
                kdxFrame.navigate( page );
            }
        } 
        catch (e)
        {
            _launchPageInNewTemplate( page, style, kdxUrn, kdxFrameName );
        }
    }
    
    /////////////////////////////////////////////////////////////////////
    /* ------------------------------------------------- */
    /*        oem installation specific methods          */
    /* ------------------------------------------------- */
    
    /*  calls the proposition instance to determine if the oem installation has been finalised  */
    function _installIsFinalised () {
        return _propositionInstance.OemInstallation.OemInstallationComplete;
    }
    
    // if the oem setup has not been finalised, the finalisation flow is started
	function _ensureIsFinalised () {
	    if (_installIsFinalised())
	        return true;
	        
	    _startFinalisationInstallFlow();
	    return false;
	    
	}
	
	// start the install finalisation flow by displaying the EULA
	function _startFinalisationInstallFlow ()
	{
        _launchPageReuseTemplateIfAvailable(CACHED_EULA_PAGE, PAGE_STYLE, '', ROOT_FRAME_NAME);
	}
	
	// progress the flow
	CliKontikiHosted.prototype.agreeEulaFinalisationFlow = function()
	{
        _launchPageReuseTemplateIfAvailable(CACHED_PCNAME_PAGE, PAGE_STYLE, '', ROOT_FRAME_NAME);
	}
		
	// complete the install finalisation flow by displaying the Start page
	CliKontikiHosted.prototype.completeFinalisationFlow = function( pcName )
	{
	    try
	    {
	        _propositionInstance.OemInstallation.CompleteInstallation( pcName );
            document.location = RELATIVE_CACHED_START_PAGE;
        }
        catch( e )
        {
            CliDisplayError( CliErrorAction_SetPcName, e.number );
        }
	}
   //////////////////////////////////////////////////////////////////////////


    /* ----------------------------------------------- */
    /*              page related methods                     */
    /* ----------------------------------------------- */
    
        
    /*  launches a page inside kontiki if the client has the app installed  */
    CliKontikiHosted.prototype.launchInKontikiIfAvailable = function( destinationUrl ) {
        if (!_clientController.isInstalled())
            return false;
            
        if (!_ensureIsFinalised())
            return false;

        _launchPageReuseTemplateIfAvailable(destinationUrl, PAGE_STYLE, '', ROOT_FRAME_NAME);
        return true;
          
    }
    
    /*  performs a check for finalisation then launches a url in the kontiki root template  */
    function _launchPageInRootTemplateAndCheckFinalisation(url) {
        if (!_ensureIsFinalised()) 
            return false;
        _launchPageReuseTemplateIfAvailable(url, PAGE_STYLE, '', ROOT_FRAME_NAME);
    }

    /*  launches the media player for a specific urn inside a kontiki template */
    CliKontikiHosted.prototype.launchOfflineMediaPlayer = function (kdxUrn) {
        CliDebug('launchOfflineMediaPlayer kdxUrn: ' + kdxUrn );
        if (!_ensureIsFinalised()) {
            return false;
        }
        _launchPageInNewTemplate(CACHED_PLAYER_PAGE, PLAYER_PAGE_STYLE, kdxUrn, PLAYER_FRAME_NAME);
    }

    /*  launches the 'no license' message in a kontiki template */
    CliKontikiHosted.prototype.launchNoLicenseMessage = function () {
        _launchPageReuseTemplateIfAvailable(CACHED_NO_LICENSE_PAGE, PLAYER_PAGE_STYLE, '', PLAYER_FRAME_NAME);
    }

    /*  launches the media player for a specific urn inside a kontiki template */
    CliKontikiHosted.prototype.launchOnlineMediaPlayer = function (kdxUrn, onlineUrl) {
        CliDebug('launchOnlineMediaPlayer kdxUrn: ' + kdxUrn + '  onlineUrl: ' + onlineUrl);
        if (!_ensureIsFinalised()) 
            return false;
        
        if (kdxUrn==null) kdxUrn='';
        var kdxFrame = _kdxApi.launchTemplate( onlineUrl, PLAYER_PAGE_STYLE, kdxUrn, PLAYER_FRAME_NAME );
        //_launchPageInNewTemplate(onlineUrl, PLAYER_PAGE_STYLE, kdxUrn, PLAYER_FRAME_NAME);
    }

    /*  launches the media player for a specific urn inside a kontiki template */
    CliKontikiHosted.prototype.launchSilverLightPlayer = function (onlineUrl) {
        CliDebug('launchOnlineMediaPlayer onlineUrl: ' + onlineUrl);
        if (!_ensureIsFinalised()) 
            return false;
        
		
        var kdxFrame = _kdxApi.launchTemplate( onlineUrl, LIVETV_PLAYER_PAGE_STYLE , '', PLAYER_FRAME_NAME );
        //_launchPageInNewTemplate(onlineUrl, PLAYER_PAGE_STYLE, kdxUrn, PLAYER_FRAME_NAME);
    }

    /*  launches the streaming (servecast) media player for a specific stream inside a kontiki template */
    CliKontikiHosted.prototype.launchStreamingMediaPlayer = function (streamUrl) {
        CliDebug('launchStreamingMediaPlayer streamUrl: ' + streamUrl);
        if (!_ensureIsFinalised()) 
            return false; 
        
        var kdxFrame = _kdxApi.launchTemplate( streamUrl, PLAYER_PAGE_STYLE, '', PLAYER_FRAME_NAME );
    }

    /*  launches the sample stream inside a kontiki template */
    CliKontikiHosted.prototype.launchSampleStreamPlayer = function( streamUrl )
    {
        _launchPageReuseTemplateIfAvailable( streamUrl, SAMPLESTREAM_PAGE_STYLE, '', SAMPLESTREAM_FRAME_NAME );
    }

    /*  launches the offline library page */
    CliKontikiHosted.prototype.launchOfflineLibrary = function () {
        var hasSettings = _clientController._settingsPresent();  
        if (hasSettings)
            _launchPageInRootTemplateAndCheckFinalisation(CACHED_LIBRARY_PAGE);
        else
            this.launchMissingSettingsPage();
    }

    /*  launches the offline missing settings page */
    CliKontikiHosted.prototype.launchMissingSettingsPage = function () {
        _launchPageInRootTemplateAndCheckFinalisation(CACHED_MISSING_SETTINGS_PAGE);
    }

    /*  launches the online home page */
    CliKontikiHosted.prototype.launchOnlineHomePage = function () {
        _launchPageInRootTemplateAndCheckFinalisation(ONLINE_HOME_PAGE);
    }

    /*  launches the hybrid startup page.  if a requesturl is not passed into the function, the online home page is loaded
        after the hybrid startup page has been rendered.
    */
    CliKontikiHosted.prototype.launchOnlineHybridStartupPage = function (requestedUrl) {
        
        if (requestedUrl==null)
            requestedUrl = ONLINE_HOME_PAGE;
                  
        var pageToLaunch = ONLINE_HYBRID_STARTUP_PAGE + encodeURI(requestedUrl);
            
        _launchPageInRootTemplateAndCheckFinalisation(pageToLaunch);
    }
    
    /*  closes the app if launched in kontiki  */
    CliKontikiHosted.prototype.closeApp = function() {
        try {
            window.external.closeWindow();
        }
        catch (e){}
    }
    
    /*  naviagates to a specific link within the root kdxsecurefrane  */
    CliKontikiHosted.prototype.navigate = function( url, frameName )
    {
        if( frameName == null )
            frameName = ROOT_FRAME_NAME;

        _launchPageReuseTemplateIfAvailable( url, PAGE_STYLE, '', frameName );
    }
    
    /*  forces termination of the users session on closing the app by opening the logout page  */
    CliKontikiHosted.prototype.onClose = function( kdxFrame )
    {
        // ensure this only happens for the root template (not the play template)
        var rootFrame;
        try
        {
            rootFrame = _kdxApi.getFrame( '', ROOT_FRAME_NAME );
            if (kdxFrame != rootFrame) return;
        }
        catch( e )
        {
            return;
        }
        
        var xmlHttp;
        try
        {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch( e )
        {
            try
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch( E )
            {
                xmlHttp = false;
            }
        }
        
        if( xmlHttp )
        {
            var pageLoadCallback = function() 
            {
                if( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
                {
                    xmlHttp.abort();
                    kdxFrame.closeWindow();
                }
            }
        }     
        
        try
        {
            var logoutUrl = CliCoerceUrlScheme( ONLINE_LOGOUT_PAGE );
            xmlHttp.onreadystatechange = pageLoadCallback;
            xmlHttp.open( "HEAD", logoutUrl, true )
            xmlHttp.send( null )
        }
        catch( e )
        {
        }
    }
  
    /* ----------------------------------------------- */
    /*          invoke the constructor                 */
    /* ----------------------------------------------- */    
    /*  initialise  */
    this.init(clientController, propositionInstance, profileName, authToken, authSignature);
    return true;
}
