
var __logDLM = new Log4Js.Logger("DownloadManager");


function RunGame(sku) {
  try 
  {		
	if ( isLaunchGameEnable )
	{				
		__logDLM.debug( "try running the game with sku: " + sku);
		isLaunchGameEnable = false;	
		var oGameObj = new ActiveXObject("Odyssey.OdysseyActiveX.1");
		oGameObj.launchGame(sku);
		oGameObj = null;			
		setTimeout('EnableLaunchGame();',2000);
	}
	else
	{
		__logDLM.debug( "launch game disabled" );
	}	
	
  }
  catch(ex)
  {
	__logDLM.error( Cookies.toJson( ex ) );
  }
  
}

function IsGameInstalled(sku) {
  try 
  {    
	__logDLM.debug( "Inside IsGameInstalled function" );
	var gamesList = getGamesListForChannel(110297473);
    if ( gamesList == null )
		return false;
		
	for ( i=0; i < gamesList.length; i++ )
	{
		if ( sku == gamesList[i][0] )
			return true;
	}	
   
  }
  catch(ex) {
	__logDLM.error( Cookies.toJson( ex ) );
  }
  return false;
}

function omDownloadOrPlay(url, sku, gameName, imgUrl) {  
  if (IsGameInstalled(sku)) {
	__logDLM.debug( "Game " + sku + " is installed. " + gameName );
    RunGame(sku);
  }
  else { 
    __logDLM.debug( "Game " + sku + " is not installed. " + gameName );
    var dlmExists = false;
    if (gameName != '' && imgUrl != '') {    
      dlmExists = downloadGame(gameName,url, imgUrl);
    } 
    
    if (!dlmExists) location.href = url;
  }
}

function omSkyDownloadOrPlay(url, sku, gameName, imgUrl, downloadEvents)
{  	
	if (IsGameInstalled(sku))
	{		
		__logDLM.debug( "Game " + sku + " is installed. " + gameName );
		RunGame(sku);		
	}
	else
	{ 
		 __logDLM.debug( "Game " + sku + " is not installed. " + gameName );
		var dlmExists = false;
		if (gameName != '' && imgUrl != '')
		{    
			dlmExists = downloadGame(gameName,url, imgUrl);
		} 

		if (!dlmExists) location.href = url;		
		eval(downloadEvents);
	}
}


function downloadGame(gameName,exeUrl,imgUrl)
{
	var host = "joinandplay.sky.com";
    var exeUrlDL = exeUrl;
    if (exeUrlDL.indexOf('http://') < 0) {
      exeUrlDL = 'http://' + host + exeUrl;
    }
    
    var imgUrlDL = imgUrl;
    if (imgUrlDL.indexOf('http://') < 0) {
      imgUrlDL = 'http://' + host + imgUrlDL;
    }    
    
    try 
    {        
        var Downloader = new ActiveXObject("OberonDownloader.Ax");
        Downloader.BrowserWindow = window;
        Downloader.BackColor = "303030";
		Downloader.TextColor = "333333" ;
		Downloader.ButtonTextColor = "EEEEEE";
		Downloader.ButtonTextHighColor = "FFEEDD";
		Downloader.ButtonTextDimColor = "a0a0a0";
		Downloader.DlgHeight = 500;
		//Downloader.DlgWidth = 700;
		Downloader.NewLayout = true;
		Downloader.RunParams = "/s";
		Downloader.Translate( "Download to", "Downloading to" );

        
        if (Downloader != null)
        {
          Downloader.AlwaysOnTop = false;
          Downloader.ChannelLogoUrl = 'http://' + host + '/graphics/sky/channelLogo.gif';
          Downloader.DownloadGame( gameName, exeUrlDL, imgUrlDL,Downloader.ChannelLogoUrl);          
		  Downloader = null;
          return true;
        }
        else {
		   __logDLM.error( "DLM is null" );
		  Downloader = null;
          return false;
        }        
    }
    catch (ex)
    {
      __logDLM.error( Cookies.toJson( ex ) );
      Downloader = null;
      return false;
    }
}

function getGamesListForChannel(channelID)
{	
	var oGameObj = new ActiveXObject("Odyssey.OdysseyActiveX.1");
	if (typeof(oGameObj) != 'object') 
	{
		__logDLM.debug( "could not initialize Odyssey.OdysseyActiveX.1");
		return null;
	}
		
	oGameObj.RefreshTree;
	var InstalledGames = new Array();
	var tempSku = oGameObj.FirstGameSKU;
	var gameProperties = new Array();
	
	var gameChannel = oGameObj.distributionChannel(tempSku);
	if (isEqual(gameChannel,channelID))
	{
		gameProperties.push(tempSku);
		gameProperties.push(oGameObj.availableUsageUnits(tempSku));
		gameProperties.push(oGameObj.isExpired(tempSku));
		gameProperties.push(oGameObj.isRegistered(tempSku));
		
		InstalledGames.push(gameProperties);
		__logDLM.debug( "existing installed sku: " + tempSku.toString() );
	}
	while(oGameObj.HasMoreGames)
	{
		
		tempSku = oGameObj.NextGameSKU;
		gameChannel = oGameObj.distributionChannel(tempSku);
		if (isNumeric(tempSku) == true && isEqual(gameChannel,channelID))
		{
			var gameProperties = new Array();
			gameProperties.push(tempSku);
			gameProperties.push(oGameObj.availableUsageUnits(tempSku));
			gameProperties.push(oGameObj.isExpired(tempSku));
			gameProperties.push(oGameObj.isRegistered(tempSku));
			
			InstalledGames.push(gameProperties);
			__logDLM.debug( "existing installed sku: " + tempSku.toString() );
		}
	}
	oGameObj = null;
	__logDLM.debug( "Total numbers of games installed: " + InstalledGames.length.toString() );
	return InstalledGames;	
}

// trim the same as in VB
function trim(str)
{
    if(str == null){
        return null;
    }
    
    switch(typeof(str)){
        case 'string':
            return str.replace(/^\s*|\s*$/g,'');
            break;
        default:
            return String(str);
    }
}

// Isnumeric - the same as VB
function isNumeric(s) {
  if(!/^-*[0-9\.]+$/.test(s)) {
   		return false
   }
   else {
		return true;
   }
}

// is Equal - true/false 
function isEqual(sku1, sku2)
{
    var sku1Trimed = trim(sku1);
    var sku2Trimed = trim(sku2);
    
	if(sku1Trimed == sku2Trimed)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// Enable lunch a game
var isLaunchGameEnable = true;
function EnableLaunchGame()
{
    isLaunchGameEnable = true;
}

function Play(code)
{
	if (typeof(TC) != 'object' || typeof(TC.SKUs) != 'object') 
		return;
	
	if ( TC.SKUs == null )
		return;
	
	if ( TC.SKUs[code] == null )
		return;
			
	omSkyDownloadOrPlay(TC.SKUs[code].downloadURL, TC.SKUs[code].sku, TC.SKUs[code].name, TC.SKUs[code].launcherImage, TC.SKUs[code].downloadEvents);
}

