/************************************************************************ 
  Copyright 2011-2012, IceJS Team. All rights reserved.
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Update Freezer Team nor the names of its
        contributors may be used to endorse or promote products derived
        from this software without specific prior written permission.
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ***********************************************************************/
 
if (typeof(g_uiPage) == "undefined")
{
	g_uiPage = "MainUI.html";
	Include("Wrappers/Common.js");
	Include("Controllers/Controller.js");
}

g_executeInBatch = true;

Util.Locale.Load();
Util.Locale.OutputDependencies("UI");
Util.Locale.OutputDependencies("Common");
Util.Locale.OutputDependencies("UpdateFreezer");

Depends("Resources/UpdateFreezerLogo.png"); 
Depends("Resources/UpdateFreezerDesktopIcon.png"); 
Depends("UI/images/icons-18-black.png"); 
Depends("UI/images/icons-18-white.png"); 
Depends("UI/images/icons-36-black.png"); 
Depends("UI/images/icons-36-white.png");
Depends("UI/jScrollPane/image/ui-icons_222222_256x240.png");
Depends("UI/jScrollPane/image/ui-icons_888888_256x240.png");
Depends("UI/jScrollPane/image/ui-icons_cd0a0a_256x240.png");
Depends("UI/jScrollPane/script/jquery.jscrollpane.js");
Depends("UI/jScrollPane/script/jquery.mousewheel.js");
Depends("UI/jScrollPane/script/mwheelIntent.js");
Depends("UI/jScrollPane/style/jquery.jscrollpane.css");
Depends("UI/jScrollPane/style/jquery.jscrollpane.lozenge.css");

Depends("UI/BrowserNotSupported.html");
Depends("Bin/Util.Registry.dll");
Depends("Bin/Util.Scheduler.dll");
Depends("UpdateFreezer.cmd");
Depends("LICENSE");

if(typeof(g_scenarios)!="undefined")
{
	var scens = g_scenarios.split(";");
	for(var i in scens)
	{
		Include("Scenarios/"+scens[i]+".js");
	}
} 
else 
{
	Include("Scenarios/Google.Updater.js");
	Include("Scenarios/Default.Browser.js");
	Include("Scenarios/Check.vcredist.js");
	Include("Scenarios/Adobe.Updater.js");
	Include("Scenarios/Java.Updater.js");
	Include("Scenarios/Firefox.Updater.js");
	Include("Scenarios/Thunderbird.Updater.js");
	Include("Scenarios/Windows.Update.js");
	Include("Scenarios/Npp.Updater.js");
	Include("Scenarios/Opera.Updater.js");
}

if(typeof(_dependencies)!="undefined")
{
	_dependencies.MAINUIHTML = {name:"MainUI.html", path:Util.IO.GetCurrentDirectory()+"\\UI\\MainUI.html"};
	_dependencies.MAINUIJS = {name:"MainUI.js", path:Util.IO.GetCurrentDirectory()+"\\UI\\MainUI.js"};
	_dependencies.MAINUILOGJS = {name:"log4javascript.js", path:Util.IO.GetCurrentDirectory()+"\\UI\\log4javascript.js"};
	_dependencies.MAINUICSS = {name:"Main.css", path:Util.IO.GetCurrentDirectory()+"\\UI\\Main.css"};
	_dependencies.MAINICON = {name: "UpdateFreezer.ico", path:Util.IO.GetCurrentDirectory() + "\\Resources\\UpdateFreezer.ico"};
	_dependencies.JQUERY = {name: "jquery.min.js", path:Util.IO.GetCurrentDirectory()+"\\UI\\jquery.min.js"};
	_dependencies.JQUERYMOBILECSS = {name: "jquery.mobile.min.css", path:Util.IO.GetCurrentDirectory()+"\\UI\\jquery.mobile.min.css"};
	_dependencies.JQUERYMOBILE = {name: "jquery.mobile.min.js", path:Util.IO.GetCurrentDirectory()+"\\UI\\jquery.mobile.min.js"};
	_dependencies.startup=_dependencies.startup||{};
	_dependencies.startup.version=g_version;
	_dependencies.startup.scenarioName="UpdateFreezer";
	_dependencies.startup.shortcutText="Update Freezer";
	_dependencies.startup.icon="Bootstrapper/Icon/UpdateFreezer/UpdateFreezer3.ico";
	_dependencies.startup.entryPoint="Scenarios\\UpdateFreezer.js";
}


Log("Displaying Dialog");

var g_uiEntryPoint = Util.IO.GetCurrentDirectory()+"\\UI\\" + g_uiPage;
var g_browserNotSupported = Util.Shell.GetIEMajorVersion() < 7;
if (g_browserNotSupported)
{
	g_uiEntryPoint = Util.IO.GetCurrentDirectory()+"\\UI\\" + "BrowserNotSupported.html";
}

var g_uiLoaded = false;
var g_logEnabled = false;


Util.LightUI.ShowDialog("Main App Title", g_uiEntryPoint);

function OnMessageLogged(txt)
{
	// Don't use "Log" here. This will lead to infinite recursion!
	if( g_logEnabled )
	{
		Util.LightUI.SetElementInnerText("#tmplogbuff", txt);
		Util.LightUI.Eval('log_appendBuffer("#tmplogbuff");');
	}
}

function LightUIAction(act, data)
{
	if(act=="OnStatusTextChange") return false;

	if(act=="OnDocumentComplete")
	{
		if(!g_uiLoaded && (data.indexOf("MainUI.html")>0 || data.indexOf("BrowserNotSupported.html")>0))
		{
			InitializeUI();
		}
		Util.LightUI.SetTitle("Update Freezer " + g_version + " - www.updatefreezer.org");
	}
	
	if(act=="OnBeforeNavigate2"&&data.indexOf("uicmd://")==0)
	{
		Util.LightUI.WaitCursor();
		
		var cmd = data.substr(8);
		if(cmd == "close/")
		{
			ActionClose();
		}
		else if(cmd == "log/")
		{
			ActionEnableLog();
		}
		else if (cmd.indexOf("execute") == 0)
		{
			var params;
			eval("params = " + cmd.substr(9));
			ActionExecute(params);
		}
		else if (cmd == "restoreall/")
		{
			ActionRestoreAll();
		}
		else if (cmd == "disableall/")
		{
			ActionDisableAll();
		}		
		else if (cmd == "remove/")
		{
			ActionRemove();
		}
		else if (cmd == "license/")
		{
			ActionLicense();
		}
		else if (cmd.indexOf("info") == 0)
		{
			var params;
			eval("params = " + cmd.substr(6));
			ActionInfo(params);
		}
		else if (cmd == "status/")
		{
			ActionStatus();
		}
		else if (cmd == "openlog/")
		{
			ActionOpenLog();
		}
		else
		{
			Util.LightUI.Eval("alert('Unknown command: " + cmd + "');");
		}
		
		Util.LightUI.DefaultCursor();
		return true;
	}
	
	if (act =="OnBeforeNavigate2"&&data.indexOf("external://")==0)
	{
		var cmd = data.substr(11);
		Util.Shell.Execute(cmd);
		return true;
	}
	
	if (act =="OnBeforeNavigate2"&&data.indexOf("http://")==0)
	{
		Util.Shell.Execute(data);
		return true;
	}
	
	return false;
}

function InitializeUI()
{
	g_uiLoaded = true;
	g_logEnabled = true;
	Log("Log enabled");
	
	Util.LightUI.SetIcon("Resources\\UpdateFreezer.ico", 0);
	Util.LightUI.SetDialogSize(800, 500);
	Util.LightUI.CenterDialog();
	Util.LightUI.Eval("Util = {}; Util.Locale = " + JSON.stringify(Util.Locale));
	Util.LightUI.Eval("setLocale()");
	
	if (!g_browserNotSupported)
	{
		Util.LightUI.Eval("appendTopButtons()");
			
		for(var i in Scenario)
		{
			if (i == "currentScenario")
				continue;
			
			var scen = Scenario[i];
			var str = "";
			if (scen.GetScenarioInfo)
			{
				str ="appendScenario('" + JSON.stringify(scen.GetScenarioInfo()) + "')";
	
				Util.LightUI.Eval("appendScenarioRow('" + scen.name + "')");
				Util.LightUI.Eval(str);
			}
		}
		Util.LightUI.Eval("appendFeedbackRowToTable()");
	}
	Util.LightUI.Eval("appendBottomButtons()");
	
	Util.LightUI.HideConsoleWindow();
	Util.LightUI.BringToFront();

	// Shortcut	
	if (Util.LightUI.CreateDesktopShortcut())
	{
		Util.LightUI.Alert(S("UI.ShortcutInstalled"));	
	}
}

function ActionClose()
{
	g_logEnabled = false;
	Util.LightUI.Close();
}

function ActionEnableLog()
{
	g_logEnabled = true;
	Log("Log enabled");
}

function ActionExecute(params, clearButtonStatus)
{
	var scen = Util.Scenario.GetScenarioForName(params.name);
	action = params.action;
	var actionLwc = action.toLowerCase();
	
	/*
	if (actionLwc == "disable" || actionLwc == "setdisabled" || actionLwc == "setnotset")
	{
		var res = Util.LightUI.Confirm(SF("UI.DisableUpdatesConfirm", [scen.displayName]));
		if (res == "no")
		{
			statusCommand = "setScenarioInfo('" + JSON.stringify(scen.GetScenarioInfo()) + "')";
			Util.LightUI.Eval(statusCommand);
			return;		
		}
	}*/
		
	var status = Execute(scen);
	
	var scenInfo = Scenario.currentScenario.GetScenarioInfo();
	if (actionLwc == "restore" || clearButtonStatus)
	{
		Util.LightUI.Eval("clearButtonStatus('" + JSON.stringify(scenInfo) + "')");
	}
	Util.LightUI.Eval("setScenarioInfo('" + JSON.stringify(scenInfo) + "')");
}

function ActionRestoreAll()
{
	for(var i in Scenario)
	{
		if (i == "currentScenario")
			continue;
			
		var scen = Scenario[i];	
		Scenario.currentScenario = scen;
		if (Util.Scenario.HasAction("restore"))
		{
			ActionExecute({name:scen.name, action:"restore"});
		}
	}
}

function ActionDisableAll()
{
	for(var i in Scenario)
	{
		if (i == "currentScenario")
			continue;
			
		var scen = Scenario[i];	
		Scenario.currentScenario = scen;
		if (Util.Scenario.HasAction("disable"))
		{
			ActionExecute({name:scen.name, action:"disable"}, true);
		}
	}
}

function ActionRemove()
{
	var info = Util.IO.ReadJsonFromFile("info.json");
	if (info)
	{
		var cmdFilePath = Util.IO.CombinePath(Util.Shell.GetLocalAppDataFolder(), "IceJS\\remove.cmd");
		var programInstallPath = Util.LightUI.GetInstallationPath(info);
		var lnkPath = Util.Shell.GetDesktopFolder() + "\\" + info.shortcutText + ".lnk";
		var cmdFileContents = 'rmdir "' + programInstallPath + '" /s/q';  
		cmdFileContents += '\r\ndel "' + lnkPath + '" /f/q';  
		//cmdFileContents += "\r\npause";
		Log("Uninstall script path: " + cmdFilePath);
		Log("Uninstall script contents: " + cmdFileContents);
		Log("Program install path: " + programInstallPath);
		var res = Util.LightUI.Confirm(SF("UI.UninstallConfirm", [cmdFileContents]));
		if (res == "yes")
		{
			Util.IO.CreateDirectory(Util.IO.CombinePath(Util.Shell.GetLocalAppDataFolder(), "IceJS"));
			Util.IO.DeleteFile(cmdFilePath);
			Util.IO.WriteFile(cmdFilePath, cmdFileContents);
			var d = new Date();
			if (Util.Shell.IsVistaOrLater())
				d.setTime(d.getTime() + 3000);
			else
				d.setTime(d.getTime() + 60000);
				
			Util.Scheduler.ScheduleTask("Remove UpdateFreezer", cmdFilePath, d);
			Util.LightUI.Close();
		}
		else
		{
			// nothing to do
		}
	}
	else
	{
		Util.LightUI.Alert("Can not remove development version");
	}
}

function ActionInfo(params)
{
	var subject = params.subject;
	var title = params.title;
	var fileName = Util.Locale.GetInfoFileName(subject);
	Util.LightUI.Eval("setInfoPanelContents(" + JSON.stringify(Util.IO.ReadFile(fileName)) + ")");
	Util.LightUI.Eval("setInfoPanelHeader(" + JSON.stringify(title) + ")");
}

function ActionStatus()
{
	var statusText = "";
	action = "query";
	for(var i in Scenario)
	{
		if (i == "currentScenario")
			continue;
			
		var scen = Scenario[i];	
		var statusObj = Execute(scen);
		statusText += "<h3>" + scen.displayName + "</h3>\r\n";
		for(var j = 0; j < statusObj.length; j++)
		{
			var s = statusObj[j];
			statusText += s.msg + "<br/>\r\n";		
		}
	}
	
	statusText+="<hr>";
	
	Log("--- Status Text ---");
	Log(statusText);
	Log("--- End Status Text ---");
	Util.LightUI.Eval("setInfoPanelHeader('UI.StatusInfo')");
	Util.LightUI.Eval("setInfoPanelContents(" + JSON.stringify(statusText) + ")");	
}

function ActionOpenLog()
{
	Util.Shell.Execute("notepad.exe", Util.IO.CombinePath(Util.IO.GetCurrentDirectory(), "../icejs.log"));
}

function ActionLicense()
{
	Util.Shell.Execute("notepad.exe", Util.IO.CombinePath(Util.IO.GetCurrentDirectory(), "LICENSE"));
}

Log("Done.");