document.onselectstart=new Function ("return false");
document.oncontextmenu = new Function ("return false");

var argstr = location.search.substring(1,location.search.length);
var args = argstr.split("|");

var ftpHost;
var gameId = args[0];
var version = args[1];
var manifestDirective = args[2];
var strLanguage = args[3];
//alert("strLanguage:" + strLanguage);
//alert("manifestDirective:" + manifestDirective);

function getInstallFolder(path)
{
	var s = unescape(top.location.href);
	s = s.toLowerCase();
	var n = s.lastIndexOf(path.toLowerCase());
	s = s.substring(0,n);
	s = s.substring(8);
	//alert(s);
	return s;
}

function patch()
{
	//Ignore exception when cancel button is hit
	try
	{
		return patchHelper();
	}
	catch (e)
	{
		//alert("Exception caught in patch. ERROR:" + e.description);
	}
	return;
}
function patchHelper()
{
	divPatchCancel.style.display="block";
	divPatchComplete.style.display="none";
	document.all.divMF.innerHTML = ESTABLISHFTP;
	document.all.divErrors.innerHTML = "";
	//window.external.PumpMessages();

	var host_dir_arr = manifestDirective.split("::");
	ftpHost = host_dir_arr[0];
	var srcRoot = host_dir_arr[1];
	
	
	
	var mfFileName = "easo_patch_" + version + ".txt" 
	
	//alert("mfFileName=" + mfFileName);
	
	fso = new ActiveXObject("Scripting.FileSystemObject");
	if (!ftpManifestFile(srcRoot, mfFileName) )
		return;

	loadManifest( strInstallFolder +"/datatemp/"  + mfFileName  );
	
	if(!Patcher.openFTPConnection(ftpHost))
	{
		document.all.divErrors.innerHTML = FTPOPENFAILED + " " + PATCHABORTED;
		return;
	}

	var i=0;
	for(i=0;i<arrSource.length;i++)
	{
		var tempFolder = strInstallFolder + "datatemp/";
		
		//make sure folder exist
		var tempDestinationFolder = tempFolder  + arrDestination[i];
		
		makeSureFolderExists ( tempDestinationFolder )

		//divMF.innerHTML = "Downloading " +	 srcRoot + arrSource[i]  + " to " + tempFolder + arrDestination[i];
		document.all.divMF.innerHTML = DOWNLOADING +	 srcRoot + arrSource[i];
							
		if(Patcher.getFTPFile(  srcRoot + arrSource[i] ,tempFolder + arrDestination[i])==false)
		{
			
			//divErrors.innerHTML = "Error downloading file " + srcRoot + arrSource[i] + " to " +   tempFolder + arrDestination[i] + ". PATCH ABORTED";
			document.all.divErrors.innerHTML = ERROR + PATCHABORTED;
			return;
		}
		progressBar.style.width=( (i+1)/arrSource.length*100) + "%";
		//window.external.PumpMessages();
	}
	Patcher.closeFTPConnection();
		
	//Disable cancel button before local file copy
	divPatchCancel.style.display="none";

	for(i=0;i<arrSource.length;i++)
	{
		//make sure final folder exist
		var source = tempFolder + arrDestination[i];
		var destination = strInstallFolder + arrDestination[i];		

		makeSureFolderExists (destination);

		makeSurePermissionsAreCorrect(destination);
		
		//divMF.innerHTML = "Copying " +  source + " to " + destination ;
		document.all.divMF.innerHTML = COPYING + destination;
		//window.external.PumpMessages();

		try {
			fso.CopyFile (source, destination ,true)

			var file = fso.GetFile(source);
			file.Delete();

		} catch (e) { 
			//divErrors.innerHTML = "Copy from " + source + " to " + destination + "failed. ERROR: " + e.description + ". PATCH ABORTED";
			document.all.divErrors.innerHTML = ERROR + e.description + PATCHABORTED;
			divPatchCancel.style.display="block";
			return;
		}
	}
	
	divPatchComplete.style.display="block";
	document.all.divMF.innerHTML = "";
	divPatchCancel.style.display="none";
}

arrSource = new Array();
arrDestination = new Array();


function loadManifest(manifestFile)
{
	var s;
	var fso, f;
	var ForReading = 1, ForWriting = 2;
	fso = new ActiveXObject("Scripting.FileSystemObject");
	f = fso.OpenTextFile(manifestFile, ForReading,false);
	
	var n;
	var source;
	var destination;
	var count;
	count = 0;
	while (!f.AtEndOfStream)
	{
		s = f.ReadLine();
		source =s;
		n= s.indexOf("|");
		if(n>1)
		{
			source=s.substring(0,n);
			destination=s.substring(n+1,s.length);
		}
		if(source.length>5)
			{
				arrSource[count]=source;
				if  (destination )
					arrDestination[count]=destination;
				else // no destination given, use source..
					arrDestination[count]=source;
				//alert ("source" + arrSource[count] + "des" + arrDestination[count] );
				count++;
			}
    }
   	f.Close( );
}

function returnToEASO()
{
	document.location="../" + gameId + "/main/easoMain.html";
	var tmpDir = strInstallFolder + "datatemp/" ;
	removeTempFiles (tmpDir) ;
}

var rr = new ActiveXObject("MSXML2.XMLHTTP");

function getManifest()
{
	rr.open("GET", "http://www.google.com", true);
	rr.onreadystatechange = rrCallback;
	rr.send();

}

function rrCallback()
{
	if(rr.readyState==4)
	{
		alert(rr.responseText);
		alert("done load manifest now");
		patch();
	}
}

function ftpManifestFile ( srcRoot, file )
{
 	if (!Patcher.openFTPConnection(ftpHost ) ) 
	{
		//alert ("Failed to open connection to ftp server " + ftpHost );
		document.all.divErrors.innerHTML = FTPOPENFAILED + " " + PATCHABORTED;
		return false;
	}
	
	var destination= strInstallFolder + "datatemp/" + file;
	
	makeSureFolderExists(destination);
	//alert ("getting " +  "/"+ srcRoot + file  + " to "+ destination )
 	if( ! Patcher.getFTPFile( "/"+ srcRoot + file,  destination  ) )
	{
 		//alert ("Failed to download manifest file" + file + " /n Please ensure  you have permisions to install, and needed disk space available");
		//alert (MANIFESTDOWNLOADFAILED + file);
		document.all.divErrors.innerHTML = MANIFESTDOWNLOADFAILED + file;
		Patcher.closeFTPConnection();
		return false;
	}
 	Patcher.closeFTPConnection();
	return true;
}


function makeSureFolderExists(path)
{
	var destinationFolder
	var n = path.lastIndexOf("/");	
	if (n==0)
		return;
	
	var dirName  = path.substring(0,n);
	fso = new ActiveXObject("Scripting.FileSystemObject");
	//if folder already there, nothing to do.. 
	if ( fso.FolderExists( dirName ) ==false )
	{
		// Splits the various components of the folder name.
		aFolders = dirName.split("/")
		// Obtains the drive's root folder.
		newFolder = fso.BuildPath(aFolders[0], "/")
			
		// Scans each component in the array, and create the appropriate folder.
		for (i=1; i< aFolders.length ; i++ )
		{	 
			newFolder = fso.BuildPath(newFolder, aFolders[i])
			if ( fso.FolderExists(newFolder)== false )
				fso.CreateFolder(newFolder);
		}//for all subfolders..
	}
}

function removeTempFiles(path)
{
	var destinationFolder
	var n = path.lastIndexOf("/");	
	if (n==0)
		return;
	
	var dirName  = path.substring(0,n);
	fso = new ActiveXObject("Scripting.FileSystemObject");
	if ( (fso.FolderExists( dirName ) == true) && (dirName.toLowerCase().indexOf("/easo/datatemp")>0))
	{
		fso.DeleteFolder( dirName ) ;
	}
}

function makeSurePermissionsAreCorrect(path)
{
	fso = new ActiveXObject("Scripting.FileSystemObject");

	if ( fso.FileExists( path ) == true )
	{
		var file = fso.GetFile(path);
		file.attributes = 0;
	}
}

//Set up the audio call back for EA-TRAX because the game is crashing
//when it is called.

function GameAPI()
{
	this._gi = window.external.GameInterface;
}

GameAPI.prototype.setAudioCallback = function ( callback )
{
	if("AudioInterface" in this._gi) {
		this._gi.AudioInterface.SetEASOSongCallback( callback );
	} else if ("SetAudioCallback" in this._gi) { 
		this._gi.SetAudioCallback( callback);
	} else if ("SetBrowserCallback" in this._gi) {
		this._gi.SetBrowserCallback( callback );
	} 	
}

function getGameAPI()
{
	var gi = null ;
	var ei = window.external.GameInterface ;
	if (!ei)
	{
		alert("no game api available");
	}
	else
	{
		gi = new GameAPI();
	}
	return gi ;
}


function AudioCallback()
{
	
}

AudioCallback.prototype.ShowNewSong = function( trackStr  )
{
	//alert(trackStr);
}

var gCallback;
function prepareAudioCallback()
{
	gCallback = new AudioCallback();
	gapi.setAudioCallback ( gCallback ) ;
}

var gapi = getGameAPI();
prepareAudioCallback();