/*!
**********************************************************************
@file AhmbedGUIWorkflow.js

Copyright 2003-2006 Adobe Systems Incorporated.                     
All Rights Reserved.                                                
                                                                    
NOTICE: All information contained herein is the property of Adobe   
Systems Incorporated.                                                                                                                    

***********************************************************************
*/

////////////////////////////////////////////////////////////////////////////
// Page loading constants 
////////////////////////////////////////////////////////////////////////////
/** DIV ID of main page container into which all other pages are inserted */
var _k_mainPageContainerID = "container";

/** Flag indicating whether the workflow has started.  Prevents re-starting the
workflow when WebKit makes gratuitous calls. */
var gWorkflowStarted = false;
var gSession = null;
var gWizardControl = null;

/** 
Global method that's invoked from the generic onFrameLoad.js::DARKCallOnLoadHandler method
*/
function onPublisherRegistered()
{
	AhmbedGUIWorkflow();
}
				
/**
Once we've loaded all the supporting scripts, we need to create the order of pages with the attendant
string representation of the data.	This requires calling out to the container to load the page by name
and adding it to the page Array.  Toggling elements then becomes getting/setting the <div id="pageContent"> data with the 
body contents in the HTML page.	 The scripts in each page will be inserted into this dom's top level script node.
*/

// This method basically initializes the pages and creates a single
// DOM with div tags named with the pageName.  It also inserts the script
// for each page into the current DOM script element and makes those methods
// available for invocation.  

function getPageArray()
{
	var workflowMode=gSession.getWorkflowMode();
	var pageArray;
	if ( workflowMode == kWorkflowModeInstall )
	{
		pageArray = new Array("Welcome", "Eula", "Options", "Progress", "Register", "Finish");
	}
	else if(workflowMode==kWorkflowModeMaintenance)
	{
		pageArray = new Array("Options", "Progress", "Finish");
	}
	else if(workflowMode==kWorkflowModeUninstall)
	{
		pageArray = new Array("Options", "Progress", "Finish");
	}
	return pageArray;
}


function AhmbedGUIWorkflow()
{
	// Let the call stack unwind, then fire off the actual workflow.
	setTimeout(AhmbedGUIWorkflowReal, 1);
}

/* Enable a stylesheet based on a given title 
	Windows only								*/
function EnableStyleSheet(inTitle) 
{
	try 
	{
		for (var i = 0; i < document.styleSheets.length; i++) 
		{            
			if (document.styleSheets[i].title == inTitle)
				document.styleSheets[i].disabled = false;
		}
    }
    catch (ex)
    {
		
    }
}

/* Disable a stylesheet based on a given title 
	Windows only								*/
function DisableStyleSheet(inTitle) 
{
	try 
	{
        for (var i = 0; i < document.styleSheets.length; i++) 
		{            
            if (document.styleSheets[i].title == inTitle)
				document.styleSheets[i].disabled = true;
        }
    }
    catch (ex)
    {
    
    }
}

function AhmbedGUIWorkflowReal()
{
	if (gWorkflowStarted)
	{
		return;
	}

	try
	{
		var containerProxyTester = new ContainerProxy();
		
		// On Mac, we don't want to jump in when called from the main.html page
		if (containerProxyTester.UIHosted())
		{	
			gSession = new InstallerSession();
			var uidev = gSession.LoadFile(_concatPaths([gSession.GetResourcesPath(), kRadioStateEasy], gSession.properties["platform"])).data != undefined ? true : false;

			// On Mac (at least) we get called twice, once before window.external exists. Don't do anything in that case.
			if (gSession.UIHosted())
			{
				gSession.languagertl=false;
				gSession.reversedpage = new Object();
				gWorkflowStarted = true;
				gSession.LogInfo(""); 
				gSession.LogInfo("-------------------------------------------------------------");	
				gSession.LogInfo("---------------- BEGIN GUI Installer Session ----------------");
		
				var currentLang = getUserInterfaceLanguage(gSession);
				gSession.Rlanguage = currentLang;
				
				if (null != currentLang)
				{
					if (isLanguageRTL(currentLang)) 
					{
						gSession.languagertl=true;
					}
				}
				//gSession.languagertl=true;//MAKE TRUE FOR CODING ONLY
				// Locate the container element we need to customize
				var containerElement = document.getElementById(_k_mainPageContainerID);
				if (containerElement)
				{
					// Load the localization and localize this UI frame.
					var xmlPath = _concatPaths([gSession.GetResourcesPath(), 'main.xml'], gSession.properties["platform"]);
					gSession.localization = new Localization(gSession, xmlPath, gSession.properties, true);
					gSession.localization.LocalizeDOM(containerElement);					

					// Create the pool we can fish standard alerts from.
					var standardAlerts = new StandardAlert(gSession, gSession.localization);

					// Test for user credentials
					var bodyNode = document.getElementById('standardBody');
					var userCredentials = containerProxyTester.GetUserInfo();
					var isValid = (null != userCredentials);
					if (userCredentials && userCredentials.hasCredentials)
						isValid = (1 == userCredentials.hasCredentials) ? true : false;
				
					if (!isValid)
					{
						gSession.UIExitDialog(standardAlerts.InvalidUserCredentials());
						return;
					}
					
					// If there's another instance running, we can exit now
					var bootstrapLaunched = false;
					var args = containerProxyTester.GetCommandLineArguments();
					try
					{
						bootstrapLaunched = (null != args.Properties.BootstrappedLaunched);
					}
					catch (ex)
					{
						
					}
					containerProxyTester.LogDebug("Command line arguments");
					containerProxyTester.LogDebug(args);
					containerProxyTester.LogDebug("Bootstrapped launched: " + bootstrapLaunched);
					
					// Test for singleton
					if (!uidev && (containerProxyTester.IsSetupLocked() ||
						(!bootstrapLaunched && containerProxyTester.IsBootstrapperLocked()) ||
						!containerProxyTester.AcquireSetupLock()))
					{
						gSession.UIExitDialog(standardAlerts.SetupAlreadyRunning());
						return;
					}
					if (containerProxyTester.IsCAPSDBLocked()) {
						gSession.UIExitDialog(standardAlerts.CAPSDBLocked());
						return;
					}

					// See if we have a background image from the driver payload.
					var newImagePath = null;
					var driverPayload = gSession.GetDriverPayload();
					var validResults = null;
					var textColor = "#676767";  // default "background" color

					if (driverPayload)
					{
						validResults = gSession.GetStreamsForAdobeCode(driverPayload.AdobeCode);
					} 
				
					if (validResults && validResults["Streams"]) 
					{
						if (validResults["Streams"][0]) 
						{
							for (var i = 0; i < validResults["Streams"].length; i++) 
							{
								if (validResults["Streams"][i]["name"] == "InstallerBackground")
								{
									newImagePath = validResults["Streams"][i]["path"];
									textColor = validResults["Streams"][i]["meta"];
								}
								else if (validResults["Streams"][i]["name"] == "SIF")
								{
								    gSession.needsValidSerialization = true;
								}
							}
						}	
					}		

					// Set the background image if we found one, else use the default.
					if (newImagePath)
	                    var customBrandingBackground = new WizardImage1(newImagePath, "brandingBanner", "brandingBanner", document.getElementById("brandingBannerContainer"));
					else
	                    var defaultBrandingBackground = new WizardImage1(kImgDefaultBrandingBkgnd, "brandingBanner", "brandingBanner", document.getElementById("brandingBannerContainer"));

                    // Render the panel dividers
                    var hrTopLeft = new WizardImage1(kImgPanelDivider, "hrTopLeft", "hrMainDivider", document.getElementById("hrTopLeftContainer"));
                    var hrTopRight = new WizardImage1(kImgPanelDivider, "hrTopRight", "hrMainDivider", document.getElementById("hrTopRightContainer"));
                    var hrBottomLeft = new WizardImage1(kImgPanelDivider, "hrBottomLeft", "hrMainDivider", document.getElementById("hrBottomLeftContainer"));
                    var hrBottomRight = new WizardImage1(kImgPanelDivider, "hrBottomRight", "hrMainDivider", document.getElementById("hrBottomRightContainer"));

					// Update the visibility of the ProductName.  We don't show it if we have a background.
					var productNameElement = document.getElementById("brandingText");
					if (productNameElement)
					{
						productNameElement.style.visibility = (null == newImagePath) ? "visible" : "hidden";
					}

					// Now we have all UI ducks in a row, materialize on the user's display.
					containerElement.style.visibility = 'visible';
					gSession.UIResizeWindow(containerElement.clientWidth, containerElement.clientHeight);
					gSession.UISetWindowTitle(gSession.localization.GetString("locProductNameInstall", "[productName] Installer: [pageTitle]", { pageTitle: gSession.localization.GetString("locPageTitle", "Loading Setup") }));
					gSession.UIShowWindow(1);
					gSession.UISetCloseBoxEnabled(1);

					// Now look more closely at what we have...in a deferred function so
					// the UI on IE can catch up.
					function sessionSetup()
					{
						try
						{
							var uiCallbackObj = new UICallback();
							if (!gSession.CreatePayloadSession(uiCallbackObj))
							gSession.LogError("Failed to create payload session.");

							// Log the system info
							gSession.LogDebug("BEGIN GetSystemInfo");
							gSession.LogDebug(gSession.systemInfo)
							gSession.LogDebug("END GetSystemInfo");

							// If we are not bootstrapped, we can't really run.
							if (!uidev && !gSession.IsBootstrapped())
							{
								gSession.sessionErrorMessages.push(["sessionErrorInstallerDatabaseInvalid", "The installer database is invalid: please re-install the product from the original media."]);
							}

							// Finally, spin up the WizardControl to load all the pages and start the workflow.
							gWizardControl = new WizardControl(gSession, getPageArray(), textColor);
						}
						catch (ex)
						{
							OuterExceptionHandler(ex);
						}
					};							

					setTimeout(sessionSetup, 1);
				}
			}
		}
	}
	catch (ex)
	{
		OuterExceptionHandler(ex);
	}	
}


function OuterExceptionHandler(ex)
{
	if (gSession)
	{
		var errMsg = "Critical errors were found in setup";
		gSession.LogFatal(errMsg);

		if (gSession.sessionErrorMessages && gSession.sessionErrorMessages[0])
		{
			for (var i = 0; i < gSession.sessionErrorMessages.length; i++)
			{
				gSession.LogFatal(" - " + gSession.sessionErrorMessages[i][1]);
				errMsg += "\n - " + gSession.sessionErrorMessages[i][1];
			}
		}

		gSession.LogFatal(ex.name + ":" + ex.message);
		gSession.LogFatal("Please see the Setup log file for details.");
		errMsg += "\nPlease see the Setup log file for details.";

		alert(errMsg);
		gSession.UIExitDialog("4");
	}
	else
	{
		alert("Critical errors were found in setup. Please see the Setup log file for details."+ex.name+":"+ex.message);
	}
}
