﻿
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2010 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
*
* $DateTime: 2008/04/10 13:35:00 $
*
* Adobe Output Module 4.0
*
* MediaGallery Originally Written by Quality Process Incorporated, Enhanced by
* Adobe System China. Contact Sheet written by Adobe System China.
* 
*
**************************************************************************/

/*
@@@START_XML@@@
    <?xml version="1.0" encoding="UTF-8"?>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en_US">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Enables the Output Panel for PDF creation and web galleries.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="cs_CZ">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Povoluje Output Panel, ve kterém můžete vytvářet soubory PDF a webové galerie.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="da_DK">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Aktiverer panelet Output til oprettelse af PDF-filer og webgallerier.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="de_DE">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Aktiviert im Ausgabebedienfeld die Option zur Erstellung von PDF-Dateien und Webgalerien.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="es_ES">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Activa el Panel de salida para la creación de archivos PDF y galerías Web.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fi_FI">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Ottaa käyttöön tulostusikkunan, jossa voi luoda PDF-asiakirjoja ja web-gallerioita.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fr_FR">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Active le panneau Sortie pour la création de fichiers PDF et les galeries Web.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fr_XM">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Active le panneau Sortie pour la création de fichiers PDF et les galeries Web.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="hu_HU">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Engedélyezi a Kimenet panel használatát a PDF-fájlok létrehozása és a webes fotógalériák számára.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="it_IT">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Attiva il pannello Output per la creazione di file PDF e gallerie per Web.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="ja_JP">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>PDF 作成および Web ギャラリー用に出力パネルを有効にします。</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="ko_KR">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>PDF 만들기 및 웹 갤러리를 위한 출력 패널 사용.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="nb_NO">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Aktiverer utdatapanelet for PDF-opprettelse og webgallerier.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="nl_NL">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Hiermee schakelt u het deelvenster Uitvoer in voor het maken van PDF-bestanden en webgalerieën.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="pl_PL">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Włącza panel wyjścia na potrzeby tworzenia plików PDF i galerii internetowych.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="pt_BR">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Ativa o painel Saída para criação de PDF e galerias da web.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="ru_RU">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Включает панель вывода для создания PDF и web-галерей.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="sv_SE">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Aktiverar utdatapanelen för PDF-skapande och webbgallerier.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="tr_TR">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>PDF oluşturma ve web galerileri için Çıktı Paneli'ni etkinleştirir.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="uk_UA">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>Вмикає панель виводу для створення PDF і веб-галерей.</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="zh_CN">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>启用用于 PDF 创建和 Web 画廊的输出面板。</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="zh_TW">
		 <dc:title>Adobe Output Module</dc:title>
		 <dc:description>啟動用於建立 PDF 以及網路收藏館的輸出面板。</dc:description>
	</ScriptInfo>
@@@END_XML@@@
*/

function AOM() {}

AOM.requiredBridgeVersion = "5";
AOM.CS_VERSION = "CS6";

if (BridgeTalk.appName != "bridge")
{
	alert("Adobe Output Module requires Bridge\n\n(BridgeTalk.appName is " + BridgeTalk.appName + ")");
}
else if (app.version < AOM.requiredBridgeVersion) 
{
	alert("Adobe Output Module requires Bridge " + AOM.requiredBridgeVersion + ".\n\n(version is " + app.version + ")");
}
else // we are good to go
{

AOM.StartupTimes = function() {}

AOM.StartupTimes.isCollectOff = true;

AOM.StartupTimes.start = function(elementId, parentElement) {
	if (AOM.StartupTimes.isCollectOff) {
		return;
	}

	if (AOM.StartupTimes.root == undefined) {
		AOM.StartupTimes.root = new XML("<Root>");
	}

	if (parentElement == undefined) {
		parentElement = AOM.StartupTimes.root;
	}
	
	var element = new XML("<" + elementId + ">");
	parentElement.appendChild(element);
	element.@startTime = new Date().getTime();
	return element;
}

AOM.StartupTimes.end = function(elementId, parentElement) {
	if (AOM.StartupTimes.isCollectOff) {
		return;
	}

	var element;
	if (elementId instanceof Object) {
		element = elementId;
	} else {
		if (parentElement == undefined) {
			element = AOM.StartupTimes.root[elementId];
		} else {
			element = parentElement[elementId];
		}
	}
	element.@endTime = new Date().getTime();
	element.@timeDiff = Number(element.@endTime) - Number(element.@startTime);
	
	var children = element.children();
	var childrenLen = children.length();
	if (childrenLen > 0) {
		var timeDiffCount = 0;
		for (var i = 0; i < childrenLen; ++i) {
			timeDiffCount += Number(children[i].@timeDiff);
		}
		element.@childrenTotalTimeDiff = timeDiffCount;
	} else {
		element.@childrenTotalTimeDiff = 0;
	}
}

AOM.StartupTimes.dump = function() {
	if (AOM.StartupTimes.isCollectOff) {
		return;
	}

	$.writeln("\nBridge LaunchTime is : " + app.launchTime);
	$.writeln("=======================================");
	$.writeln(AOM.StartupTimes.toString());
}

AOM.StartupTimes.toString = function() {
	if (AOM.StartupTimes.isCollectOff) {
		return;
	}

	return AOM.StartupTimes.traversalXMLDatas(AOM.StartupTimes.root, "");
}


AOM.StartupTimes.traversalXMLDatas = function(parent, indent) {
	var outputBuffer = indent + "[" + parent.name() + "]  " + parent.@timeDiff;
	if (Number(parent.@childrenTotalTimeDiff) > 0 && 
		Number(parent.@childrenTotalTimeDiff) != Number(parent.@timeDiff)) {
		outputBuffer += " / [sum_childrens=" + parent.@childrenTotalTimeDiff + "]";
	}
	outputBuffer += "\n";
		
	var children = parent.children();
	if (children != undefined) {
		var childLen = children.length();
		var childIndent = indent + "\t";
		for (var i = 0; i < childLen; ++i) {
			outputBuffer += this.traversalXMLDatas(children[i], childIndent); 
		}
	}
	return outputBuffer;
}

AOM.StartupTimes.findElement = function(elementPath) { 
	if (AOM.StartupTimes.isCollectOff) {
		return;
	}

	return eval("AOM.StartupTimes.root." + elementPath);
}

AOM.StartupTimes.start("ScriptLoading");

AOM.build = "Adobe Output Module 4.0";
AOM.version = "4.0.1";
AOM.persistFileVersion = "4.0.1";
AOM.jsonHeaderLength = 113;

AOM.Paths = function() {};
AOM.Paths.base = Folder.commonFiles.fullName + "/Adobe/Bridge " + AOM.CS_VERSION + " Extensions";
AOM.Paths.project = AOM.Paths.base + "/Adobe Output Module";
AOM.Paths.images = AOM.Paths.project + "/resources/images";
AOM.Paths.userData = Folder.userData + "/Adobe/Bridge " + AOM.CS_VERSION + "/Adobe Output Module"; 
AOM.Paths.workspace = Folder.userData + "/Adobe/Bridge " + AOM.CS_VERSION + "/Workspaces";
AOM.Paths.absoluteBaseOnWin = Folder.commonFiles.fsName + "\\Adobe\\Bridge " + AOM.CS_VERSION + " Extensions";
AOM.Paths.absoluteBaseOnMac = Folder.commonFiles.fsName + "/Adobe/Bridge " + AOM.CS_VERSION + " Extensions";
AOM.Paths.absoluteProjectOnWin = AOM.Paths.absoluteBaseOnWin + "\\Adobe Output Module";
AOM.Paths.absoluteProjectOnMac = AOM.Paths.absoluteBaseOnMac + "/Adobe Output Module";
AOM.latestDocumentId = -1;


AOM.localize = function(s)
{
	return localize(s);
}

AOM.localizeEsc = function(s)
{
	var str = AOM.localize(s);
	return str.replace("'", "\\'");
}

AOM.localizeWithArgs = function(zstring, args) {
	var localizedStr = AOM.localize(zstring);
	
	if (args != undefined) {
		if (args instanceof Array) {
			for (var i = 0; i < args.length; i++) {
				if (args[i] != undefined) {
					var regex = new RegExp("\\(" + (i + 1) + "\\)", "g");
					localizedStr = localizedStr.replace(regex, AOM.localize(args[i]));
				}
			}
		} else {
			//default is string
			localizedStr = localizedStr.replace(/\(1\)/g, AOM.localize(args));
		}
	}
	
	return localizedStr;
}

AOM.alert = function(message) {
	alert(message);
}

AOM.confirm = function(message, noAsDefault) {
	return confirm(message, noAsDefault);
}

/**
 * This class used to store "aomJsFuncs" property value of each document object.
 * It's a workaround for app.document, which can not save any custom propert value.
 *
 */
AOM.documents = function(){};

AOM.documents.setAOMJsFuncs = function(documentId, prop) {
	if (AOM.documents.docMap == undefined) {
		AOM.documents.docMap = new Object();
	}
	AOM.documents.docMap[documentId] = prop;
}

AOM.documents.getAOMJsFuncs = function(documentId) {
	if (AOM.documents.docMap == undefined) {
		return {};
	}
	var aomJsFuncs = AOM.documents.docMap[documentId];
	if (!aomJsFuncs) {
		return {};
	} else {
		return aomJsFuncs;
	}
}

AOM.documents.getAOMJsFuncsFromDoc = function(document) {
	if (document == undefined) {
		AOM.alert("Undeterminable document: " + $.stack);
        document = app.document;
	}

	return AOM.documents.getAOMJsFuncs(document.id);
}

AOM.tabbedPalette = function(document)
{
	return AOM.documents.getAOMJsFuncsFromDoc(document).outputPalette;
}

AOM.csDesignWindow = function(document) {
	return AOM.documents.getAOMJsFuncsFromDoc(document).csDesignWindow();
}

AOM.previewPalette = function(document)
{
	return AOM.documents.getAOMJsFuncsFromDoc(document).previewPalette;
}

AOM.userInput = function(document)
{
    return AOM.documents.getAOMJsFuncsFromDoc(document).csUserInput;
}

AOM.theme = function(document)
{
    return AOM.documents.getAOMJsFuncsFromDoc(document).gsTheme;
}

AOM.workspaceLoaded = function(document)
{
    return AOM.documents.getAOMJsFuncsFromDoc(document).workspaceLoaded;
}


AOM.eventHandler = function(event) {

	if(event.type == "launchComplete") {
		AOM.StartupTimes.dump();
	}
	
	if(event.type == "workspacesPreLoad" && event.object instanceof Document && event.object.id != undefined) {
		AOM.latestDocumentId = event.object.id;
		if(!AOM.StartupTimes.isCollectOff)
			app.logging = 1;
		
		AOM.StartupTimes.start("WorkspacePreload");
		
		var loadedDocument = event.object;
		
		if(loadedDocument.aomJsFuncs == undefined) {
		    loadedDocument.aomJsFuncs = {};
			AOM.documents.setAOMJsFuncs(loadedDocument.id, loadedDocument.aomJsFuncs);
		}

		//Workaround for the check/uncheck startup prop.
		AOM.Workspace.removeCacheWorkspace();
		
		//create tabbedPalette
		var loadedTabbedPalette = new TabbedPalette(
			loadedDocument,
			AOM.localize("$$$/Output/JavaScript/MainPaletteTitle=Output"),
			"Output", "script");
		
		/* Never use app.document. Use this cached document. */
		loadedTabbedPalette.content.document = loadedDocument;
		loadedTabbedPalette.visible = false;
		loadedTabbedPalette.showMenuItem = false;
        loadedTabbedPalette.content.orientation = 'column';
		loadedTabbedPalette.content.margins = 0;
		loadedTabbedPalette.content.spacing = 0;
		
		loadedDocument.aomJsFuncs.outputPalette = loadedTabbedPalette;
		
		loadedDocument.aomJsFuncs.workspaceLoaded = false;
		
		
		loadedTabbedPalette.content.onResize = function()
		{
			var onResizeStatEle = AOM.StartupTimes.start("ContentOnResize");
			
			// Flag that a user has resized the tabbed palette. 
			this.hasResized = true;
			
			// Load scripts if not already loaded
			AOM.StartupTimes.start("LoadScript", onResizeStatEle);
			if (AOM.AMG == undefined || AOM.CS == undefined) {
			
				$.evalFile(AOM.Paths.project + "/IncludeHelper.jsxinc");
				AOM.Utils.checkPersistFiles();

				if(app.preferences.aomKeepPreference == undefined) {
					var userInputFile = File(AOM.CS.Paths.persistedUserData);
					if(userInputFile.exists)
						userInputFile.remove();
					
					AOM.AmgUserInput.deletePersistedData();
					app.preferences.aomKeepPreference = true;
				}
			}
			AOM.StartupTimes.end("LoadScript", onResizeStatEle);
			
			if (AOM.workspaceLoaded(this.document)) {
				AOM.StartupTimes.start("Layout", onResizeStatEle);
				this.layout.layout(true);
				AOM.StartupTimes.end("Layout", onResizeStatEle);
				
				AOM.StartupTimes.end(onResizeStatEle);
				return;
			}
			
			//create theme
			this.document.aomJsFuncs.gsTheme = new AOM.AOMUITheme(this);
			
			var headResource = 
			"group {\
				alignment:['left', 'top'], alignChildren:['left', 'top'], margins:[30, 10, 0, 10],  \
				pdfMode:IconButton{\
					text:'" + AOM.localize("$$$/ContactSheet/javascript/title/pdf=PDF") + "', \
					preferredSize:[72, 40],\
					btPressed:true, \
					imagePath:'"+ AOM.CS.Paths.images + "icon_pdf.png"+"',\
					themeType:'imagebutton',\
					name:'pdfMode'\
				},\
				webGalleryMode:IconButton{\
					text:'" + AOM.localize("$$$/ContactSheet/javascript/title/webGallery=WEB GALLERY") + "',\
					preferredSize:[168, 40],\
					btPressed:false,\
					imagePath:'"+ AOM.CS.Paths.images + "icon_webgallery.png"+"',\
					themeType:'imagebutton',\
					name:'webGalleryMode'\
				}\
			}";
		
			AOM.StartupTimes.start("InitialResource", onResizeStatEle);
			AOM.CSConstant.initialization();
			AOM.CSManager.initializationResources();
			AOM.StartupTimes.end("InitialResource", onResizeStatEle);
			
		
			//load userInputData
			AOM.StartupTimes.start("LoadUserInputdata", onResizeStatEle);
			var userInput = new AOM.CS.UserInput();
			this.document.aomJsFuncs.csUserInput = userInput;
			AOM.StartupTimes.end("LoadUserInputdata", onResizeStatEle);
			
			// Work-around for #1840160 
			userInput.window = loadedTabbedPalette.content.window;
			
			//add head group
			var headGroup = this.add(headResource);
			headGroup.document = this.document;
			var hasPdfMode = AOM.initializeHeadGroup(headGroup);
			
			
			//add UI stack
			AOM.StartupTimes.start("BuildUIStack", onResizeStatEle);
			loadedTabbedPalette.buildUIStack = function(isPDFMode, drawerType)
			{
				AOM.buildUIStack(this, isPDFMode, drawerType);
			}
			loadedTabbedPalette.buildUIStack(hasPdfMode, AOM.BridgePreferences.getDrawerType());
			AOM.StartupTimes.end("BuildUIStack", onResizeStatEle);
			
			AOM.StartupTimes.start("ApplyTheme", onResizeStatEle);
			AOM.theme(this.document).applyTheme(headGroup, true);
			AOM.StartupTimes.end("ApplyTheme", onResizeStatEle);
			
			this.document.aomJsFuncs.workspaceLoaded = true;
			
			AOM.StartupTimes.start("Layout", onResizeStatEle);
			this.layout.layout(true);
			AOM.StartupTimes.end("Layout", onResizeStatEle);
			
			AOM.StartupTimes.end(onResizeStatEle);
		}
	
		AOM.StartupTimes.end("WorkspacePreload");
	}


	if (event.object instanceof PreferencesDialog && event.location == "prefs") {
		var eventType = event.type;
		var eventObject = event.object;

		switch(eventType) {
    		case "create" :
    			AOM.BridgePreferences.create(eventObject);
    			break;
    		case "destroy" :
    			AOM.BridgePreferences.destroy();
    			break;
    		case "ok" :
				if (AOM.BridgePreferences.checkChanged(
								app.preferences.aomDrawerType, AOM.BridgePreferences.aomNewDrawerType)) {
					AOM.BridgePreferences.doSoloModeChange();
				}
			
				if (AOM.BridgePreferences.checkChanged(
								app.preferences.aomHasConvertMultibyte, AOM.BridgePreferences.aomNewHasConvertMultibyte)) {
					AOM.BridgePreferences.doConvertMultibyteChange();
				}
			
				if (AOM.BridgePreferences.checkChanged(
								app.preferences.aomPreserveColorProfile, AOM.BridgePreferences.aomNewPreserveColorProfile)) {
					AOM.BridgePreferences.doPreserveColorProfileChange();
				}
			
				if (AOM.BridgePreferences.checkChanged(
								AOM.BridgePreferences.oldUIBrightness, app.preferences.UIBrightness)) {
					AOM.BridgePreferences.doUIBrightnessChange();
				}
			
				if (AOM.BridgePreferences.checkChanged(
								AOM.BridgePreferences.oldImageBackdrop, app.preferences.ImageBackdrop)) {
					AOM.BridgePreferences.doImageBackdropChange();
				}
				break;
			case "disabled" :
				if (event.scriptName == "AdobeOutputModule")
					AOM.Workspace.disableStartupAOM = true;
				break;
			case "enabled" :
				if (event.scriptName == "AdobeOutputModule")
					AOM.Workspace.disableStartupAOM = false;
				break;
			default :
				break;
		}
	}

	if (event.type == "select" && event.object instanceof Document && event.location == "document") {
		AOM.syncFTPPresets(event.object);
		var designWindow = AOM.documents.getAOMJsFuncsFromDoc(event.object).csDesignWindow;
		if (designWindow != undefined) {
			designWindow.updateTemplate(event.object);
		}
		var tabbedPalette = AOM.tabbedPalette(event.object);
		if (tabbedPalette != undefined && tabbedPalette.content != undefined && tabbedPalette.content.visible == true && tabbedPalette.content.designGroup != undefined)
			AOM.AmgLoadStyleSection.updateStyle(event.object, tabbedPalette.content.designGroup);
		
		if (AOM.latestDocumentId != event.object.id) {
			var jsFunc = AOM.documents.getAOMJsFuncsFromDoc(event.object);
			if (jsFunc != undefined) {
				if (jsFunc.needRefresh == undefined)
					jsFunc.needRefresh = false;
				if (jsFunc.previewPalette != undefined && jsFunc.needRefresh == true) {
					if (File.fs == "Windows") {
						var oldUrl = jsFunc.previewPalette.url;
						AOM.previewPalette(event.object).display(oldUrl);
					}
					jsFunc.needRefresh = false;
				}
			}
		}
		AOM.latestDocumentId = event.object.id;
	}
	
	if (event.type == "close" && event.object instanceof Document && event.location == "document") {
	    //Workaround for the check/uncheck startup prop.
		if (app.documents.length == 1) {
			AOM.Workspace.disableWorkspace();
		}
		
		var closedDocument = event.object;
		
		// Remove the font groups which will soon be not on Bridge any longer from the global list,
		// which is used for notifying all font dropdown lists with system font deletion.
		if (AOM.SysFontGroupHelper != undefined) {
			AOM.SysFontGroupHelper.removeFontGroupForDocument(closedDocument);
		} 
		
		if(!AOM.workspaceLoaded(closedDocument)) {
			return;		
		}
	
		if (AOM.AMG.ftpPresetUserInput) {
			AOM.AMG.ftpPresetUserInput().persist();
		}
		if (AOM.userInput(closedDocument)) {
			AOM.userInput(closedDocument).persist();
		}
		if (AOM.AMG.userInput(closedDocument)) {
			AOM.AmgUserInput.persist(closedDocument);
		}
    
		
    }
    if (event.type == "destroy" && event.object instanceof App && event.location == "app") {
		// Purge Image Cache when Bridge quits.
		var cacheFolder = Folder.userData + "/Adobe/Bridge " + AOM.CS_VERSION + "/Adobe Output Module/ImageCache/";
		var tempImageCacheFolder = Folder(cacheFolder);
		var files = tempImageCacheFolder.getFiles();
		for(var j = 0; j < files.length; j++) {
			files[j].remove();
		}
		tempImageCacheFolder.remove();
	}
}

AOM.syncFTPPresets = function(document) {
	if (AOM.AMG != undefined && AOM.AMG.amgCreateGallerySection(document)) {
		var group = AOM.AMG.amgCreateGallerySection(document);
		var ftpDropDownList = group.ftpGroup.tGroup.ftpTemplate;
		var globalPresets = AOM.AMG.ftpPresetUserInput().getItems();
		var localPresets = ftpDropDownList.items;
			
		// add new item if needed.
		AOM.AmgCreateGallerySection.hasProgramInteract = true;
		for (var i = 0; i < globalPresets.length; i++) {
			var globalPreset = globalPresets[i].id;
			var hasFind = false;
			for (var j = 2; j < localPresets.length; j++) {
				var localPreset = localPresets[j].text;
				if (localPreset.toLowerCase() == globalPreset.toLowerCase()) {
					hasFind = true;
					break;
				}
			}
			if (!hasFind) {
				ftpDropDownList.add("item", globalPreset);
			}
		}
		AOM.AmgCreateGallerySection.hasProgramInteract = false;
			
		//remove old items if needed.
		AOM.AmgCreateGallerySection.hasProgramInteract = true;
		for (var i = 2; i < localPresets.length; i++) {
			var localPreset = localPresets[i].text;
			var hasFind = false;
			for (var j = 0; j < globalPresets.length; j++) {
				var globalPreset = globalPresets[j].id;
				if (localPreset.toLowerCase() == globalPreset.toLowerCase()) {
					hasFind = true;
					break;
				}
			}
			if (!hasFind) {
				ftpDropDownList.remove(localPresets[i]);
				ftpDropDownList.selection = localPresets[0];
			}
		}
		AOM.AmgCreateGallerySection.hasProgramInteract = false;
	}
}

AOM.buildUIStack = function(palette, isPDFMode, drawerType)
{
	palette.content.uiStack = palette.content.add(AOM.UIStackResource);
	palette.content.uiStack.layout = new AOM.UIStackLayout(palette.content.uiStack);
	palette.content.uiStack.pdfContactSheet.initialized = false;
	palette.content.uiStack.webGallery.initialized = false;
	
	/* Initial Policy 1: Initialize both modules. This increases the startup time but
	 *                   benifit the first switch. We prefer it for now because the slight
	 *                   extra startup time is not so obvious as the reduced first switch
	 *                   time, especially on fast speed machine.
	 */
	var buildUIStackStatEle = AOM.StartupTimes.findElement("ContentOnResize.BuildUIStack");
	AOM.StartupTimes.start("BuildPDF", buildUIStackStatEle);	
	var csDesignWindow =
		new AOM.CSManager.DesignWindow(palette.content.uiStack.pdfContactSheet, palette);
	palette.content.document.aomJsFuncs.csDesignWindow = csDesignWindow;
	palette.content.uiStack.pdfContactSheet.initialized = true;
	AOM.StartupTimes.end("BuildPDF", buildUIStackStatEle);
	
	AOM.StartupTimes.start("BuildWebGallery", buildUIStackStatEle);
	var drawerType = AOM.BridgePreferences.getDrawerType();
	AOM.AMG.switchTo(palette, palette.content.uiStack.webGallery,
	 			 drawerType == AOM.BridgePreferences.DRAWER_TYPE_CABINET);
	palette.content.uiStack.webGallery.initialized = true;
	AOM.StartupTimes.end("BuildWebGallery", buildUIStackStatEle);
	
	AOM.StartupTimes.start("SetVisiblePanel", buildUIStackStatEle);
	if (isPDFMode == true) {
		palette.content.uiStack.pdfContactSheet.visible = true;
		palette.content.uiStack.webGallery.visible = false;
	} else {
		palette.content.uiStack.pdfContactSheet.visible = false;
		palette.content.uiStack.webGallery.visible = true;
	} 
	AOM.StartupTimes.end("SetVisiblePanel", buildUIStackStatEle);
	
	/* Initial Policy 2: Only initial the module which the user is currently
	 *                   using. This reduce the startup time at the cost of a slow
	 *                   first switch.
	 *
	 *                   We consider turn it off for now since two slightly small delays
	 *                   are more obvious than one big, especially on fast-speed machine.
	 *
	if (isPDFMode == true) {
		var csDesignWindow =
			new AOM.CSManager.DesignWindow(palette.content.uiStack.pdfContactSheet, palette);
		palette.content.document.aomJsFuncs.csDesignWindow = csDesignWindow;
		palette.content.uiStack.pdfContactSheet.visible = true;
		palette.content.uiStack.webGallery.visible = false;
		palette.content.uiStack.pdfContactSheet.initialized = true;
	} else {
		var drawerType = AOM.BridgePreferences.getDrawerType();
		AOM.AMG.switchTo(palette, palette.content.uiStack.webGallery,
		 			 drawerType == AOM.BridgePreferences.DRAWER_TYPE_CABINET);
		palette.content.uiStack.pdfContactSheet.visible = false;
		palette.content.uiStack.webGallery.visible = true;
		palette.content.uiStack.webGallery.initialized = true;
	} */
}


AOM.PreviewPanel = function() {}

AOM.PreviewPanel.getPreviewPosition = function() {
    var cacheWorkspaceFile = new File(AOM.Workspace.CACHE_WORKSPACE_NAME);
    
    if (cacheWorkspaceFile.exists) {
    	cacheWorkspaceFile.open("r");
    	var content = cacheWorkspaceFile.read();
    	cacheWorkspaceFile.close();
        
        var findIndex = content.lastIndexOf("tab name='OutputPreview'");
		if (findIndex < 0) { return undefined; }
		
    	var xmlObj = new XML(content);
    	var elements = xmlObj.elements();
    	var elementsLen = elements.length();
    	for (var i = 0; i < elementsLen; i++) {
    		var hubSet = elements[i];
    		if (hubSet.name() == "hubset") {
    			var hubElements = hubSet.elements();
    			var hubElementsLen = hubElements.length();
    			for (var j = 0; j < hubElementsLen; j++) {
    				var hub = hubElements[j];
    				var tabElements = hub.elements();
    				var tabElementsLen = tabElements.length();
    				for (var k = 0; k < tabElementsLen; k++) {
    					var tab = tabElements[k];
    					var tabName = tab.@name.toLowerCase();
    					if (tabName == "outputpreview") {
    						var previewColPos = parseInt(hubSet.@position);
    						var previewRowPos = j;
    						return {col:previewColPos, row:previewRowPos};
    					}
    				}
    			}
    		}
    	}
    }

	return undefined;
}

AOM.PreviewPanel.getColString = function(number) {
    switch(number) {
    case 0: 
        return "left";
    case 1 :
        return "center";
    case 2 :
        return "right";
    default :
        return "center";
    }
}

AOM.PreviewPanel.checkPreviewPalette = function(loadedDocument) {
	try {
		if (AOM.previewPalette(loadedDocument) == undefined) {
			AOM.PreviewPanel.createPreviewPalette(loadedDocument);
		}
	} catch(e) {
		AOM.alert('AOM.PreviewPanel.checkPreviewPalette throw an error:' + e + e.line);
	}
}

AOM.PreviewPanel.createPreviewPalette = function(loadedDocument) {
    var previewPos = AOM.PreviewPanel.getPreviewPosition();
    var pcol = 1, prow = 0;
    if (previewPos != undefined) {
        pcol = previewPos.col;
        prow = previewPos.row;
    }
	var loadedPreviewPalette = new TabbedPalette(
			loadedDocument,
			AOM.localize("$$$/Output/JavaScript/PreviewPaletteTitle=Output Preview"),
			"OutputPreview", "web", "", AOM.PreviewPanel.getColString(pcol), prow);
			
	loadedPreviewPalette.visible = false;
	loadedPreviewPalette.showMenuItem = false;
	loadedDocument.aomJsFuncs.previewPalette = loadedPreviewPalette;
	loadedPreviewPalette.display = function(url) {
		//this.visible = false;
		this.visible = true;
		if (url != undefined) {
			this.url = url;
		}
	}

	loadedPreviewPalette.url = AOM.PreviewPanel.previewHtml();
}

AOM.PreviewPanel.previewHtml = function(sourceFilePath, htmlFile) {
	var path = AOM.Paths.userData + "/ContactSheet/";
	
	if(htmlFile == undefined) {
		htmlFile = new File(path + "Preview.html");
	}
	htmlFile.open("w", "TEXT");
	htmlFile.encoding = "UTF8";
	
	if(sourceFilePath == undefined)
		sourceFilePath = AOM.Paths.project + "/resources/htmls/Preview.htm";
	
	sourceFile = new File(sourceFilePath);
	sourceFile.open("r", "TEXT");
	
	brightness = app.preferences.ImageBackdrop;
	var brightnessString = brightness.toString(16);
	brightnessString = (brightnessString.length == 1) ? "0" + brightnessString : brightnessString;
	brightnessString = (brightnessString + brightnessString + brightnessString);
	while(!sourceFile.eof) {
		var line = sourceFile.readln();
		if(line.indexOf("background-color") < 0)
			htmlFile.writeln(line);
		else
			htmlFile.writeln("background-color: #" + brightnessString + ";");
	}

	htmlFile.close();
	sourceFile.close();
	
	return htmlFile.fsName;
}



AOM.initializeHeadGroup = function(headGroup) {
	//initial from user data
	var currentUserInput = AOM.userInput(headGroup.document);
	var hasPdfMode = AOM.CS.CString.strToBoolean(currentUserInput.get(AOM.PDF_MODE));
	var hasWebGalleryMode = AOM.CS.CString.strToBoolean(currentUserInput.get(AOM.WEB_GALLERY_MODE));
	if (hasPdfMode) {
		headGroup.pdfMode.btPressed = true;
		headGroup.webGalleryMode.btPressed = false;
	}  else {
		headGroup.pdfMode.btPressed = false;
		headGroup.webGalleryMode.btPressed = true;
	}

	//initial event handler
	headGroup.pdfMode.document = headGroup.document;
	headGroup.pdfMode.onClick = function() {
		if (this.btPressed == false) {
			var webGalleryMode = this.parent.webGalleryMode;
				
			this.btPressed = true;
			webGalleryMode.btPressed = false;
				
			AOM.userInput(this.document).setElement(this);
			AOM.userInput(this.document).setElement(webGalleryMode);
			
			/* Switch UI stack */
			var tabbedPalette = AOM.tabbedPalette(this.document);
			tabbedPalette.content.uiStack.pdfContactSheet.visible = true;
			tabbedPalette.content.uiStack.webGallery.visible = false;
			
			/* Initialize if not yet. The code is used for "Policy 2" only. */
			if(!tabbedPalette.content.uiStack.pdfContactSheet.initialized) {
				var csDesignWindow = new AOM.CSManager.DesignWindow(
					tabbedPalette.content.uiStack.pdfContactSheet,
				    tabbedPalette);
				tabbedPalette.content.document.aomJsFuncs.csDesignWindow = csDesignWindow;
				tabbedPalette.content.uiStack.pdfContactSheet.initialized = true;
			}
			if(tabbedPalette.content.hasResized == undefined || tabbedPalette.content.hasResized) {
				tabbedPalette.content.onResize();
				tabbedPalette.content.hasResized = false;
			}
						
			/* To Do: The following visibility operation is to work-around the
             *        redraw defect, but introduces palette flash. */
            tabbedPalette.content.visible = false;
            tabbedPalette.content.visible = true;
            tabbedPalette.fixupControls();
		}
	} 
	
	headGroup.webGalleryMode.document = headGroup.document;
	headGroup.webGalleryMode.onClick = function() {
		if (this.btPressed == false) {
			var pdfMode = this.parent.pdfMode;
				
			this.btPressed = true;
			pdfMode.btPressed = false;
			
			AOM.userInput(this.document).setElement(this);
			AOM.userInput(this.document).setElement(pdfMode);
			
			/* Switch UI stack */
			var tabbedPalette = AOM.tabbedPalette(this.document);
			tabbedPalette.content.uiStack.pdfContactSheet.visible = false;
			tabbedPalette.content.uiStack.webGallery.visible = true;
			
			/* Initialize if not yet. The code is used for "Policy 2" only. */
			if(!tabbedPalette.content.uiStack.webGallery.initialized) {
				var drawerType = AOM.BridgePreferences.getDrawerType();
				AOM.AMG.switchTo(tabbedPalette, tabbedPalette.content.uiStack.webGallery,
							 drawerType == AOM.BridgePreferences.DRAWER_TYPE_CABINET);
				tabbedPalette.content.uiStack.webGallery.initialized = true;
			}
			if(tabbedPalette.content.hasResized == undefined || tabbedPalette.content.hasResized) {
				tabbedPalette.content.onResize();
				tabbedPalette.content.hasResized = false;
			}
			
			/* To Do: The following visibility operation is to work-around the
             *        redraw defect, but introduces palette flash. */
            tabbedPalette.content.visible = false;
            tabbedPalette.content.visible = true;
            tabbedPalette.fixupControls();
            
            if (AOM.previewPalette(this.document) != undefined) {
                AOM.previewPalette(this.document).visible = false;        
            }
		}
	}

	return hasPdfMode;
}


app.eventHandlers.push({handler:AOM.eventHandler});

/*****************************************************************************************************************
                    Define Preferences handler here
******************************************************************************************************************/

AOM.BridgePreferences = {};
AOM.BridgePreferences.preferenceDialogConfigured = false;
AOM.BridgePreferences.create = function (dialog)
{
	if (dialog instanceof PreferencesDialog == false)
		return AOM.AMG.Log.writeError("BridgePreferences.create - dialog not a PreferencesDialog");
		
	try
	{
		if (!AOM.BridgePreferences.preferenceDialogConfigured)
		{
			var title = AOM.localize("$$$/ContactSheet/javascript/preferences/WindowTitle=Output");
			var panel = dialog.addPanel(title);
			panel.alignChildren = "fill";
			panel.orientation = "column";
			var pwidth = panel.size.width;
			var pheight = panel.size.height;
			var gfx = panel.graphics;
			
			//add maingroup
			var mainGroup = panel.add(
			"group{\
				orientation:'column', spacing:16, margins:[6, 10, 0, 0],alignment:['fill', 'top'], alignChildren:['left', 'top'],\
				titlegrp:Group{\
					orientation:'column', spacing:2, alignChildren:['left', 'top'],\
					title:StaticText{text:'"+title+"'},\
					line:StaticText{text:'', preferredSize:["+pwidth+", 1]},\
				},\
				sectiongrp:Group{\
					orientation:'row', alignChildren:['left', 'center'],\
					hasSoloMode:Checkbox{\
						text:'"+AOM.localizeEsc("$$$/ContactSheet/javascript/preferences/useSoloMode=Use Solo Mode for Output Panel Behavior")+"'},\
				},\
				multibytegrp:Group{\
					alignChildren:['left', 'top'],\
					hasConvertMultibyte:Checkbox{\
						text:'"+AOM.localizeEsc("$$$/MediaGallery/JavaScript/ConvertFileNameToAscii=Convert Multi-Byte Filenames to Full ASCII")+"',\
					},\
				},\
				preservecpgrp:Group{\
					alignChildren:['left', 'top'],\
					preserveColorProfile:Checkbox{\
						text:'"+AOM.localizeEsc("$$$/MediaGallery/JavaScript/PreserveColorProfile=Preserve Embedded Color Profile")+"',\
					},\
				},\
				resetgrp:Group{\
					alignChildren:['left', 'center'],\
					resetbtn:Button{text:'"+AOM.localizeEsc("$$$/MediaGallery/JavaScript/restoreSettingsBtn=Reset Panel to Defaults")+"'},\
				},\
			}");
			
            //add extra width to title's text otherwise the last letter of the text may be truncated
            var titlegfx =  mainGroup.titlegrp.title.graphics;
            var titleTextSize = titlegfx.measureString(mainGroup.titlegrp.title.text,  titlegfx.font);
            mainGroup.titlegrp.title.preferredSize.width = titleTextSize.width + 6;

			//add extra width to the reset button, bug #3057759
			//another option is to remove the resetgrp around the button
			//on windows you don't get the offset to the right, go figure
            var resetgfx =  mainGroup.resetgrp.resetbtn.graphics;
            var resetTextSize = resetgfx.measureString(mainGroup.resetgrp.resetbtn.text,  resetgfx.font);
            mainGroup.resetgrp.resetbtn.preferredSize.width = resetTextSize.width + 40;
            
			//layout
			panel.layout.layout(true);		
			
			//add titlegrp
			var titlegrp = mainGroup.titlegrp;
			//note: i'm not seeing this line get drawn at all
			if (File.fs == "Windows") {
				titlegrp.line.graphics.bgColor = gfx.newBrush(0, [.79, .77, .68]);
				//titlegrp.title.graphics.foregroundColor = gfx.newPen(0, [.25, .41, .84], 1);
			} else {
				titlegrp.line.graphics.bgColor = gfx.newBrush(0, [.53, .53, .53]);  //Macintosh
			}
			titlegrp.line.onDraw = function(drawState) {
				var gfx = this.graphics;
				var w = this.size.width;
				var h = this.size.height;
				gfx.newPath();
				gfx.rectPath(0, 0, w, h);
				gfx.fillPath(gfx.bgColor);
			}
			
			//add foldable section ddl "drawerType"
			var hasSoloMode = mainGroup.sectiongrp.hasSoloMode;
			var drawerType = AOM.BridgePreferences.getDrawerType();
			AOM.BridgePreferences.aomNewDrawerType = drawerType;
			if (drawerType == AOM.BridgePreferences.DRAWER_TYPE_ACCORDION) {
				hasSoloMode.value = true;
			} else { 
				hasSoloMode.value = false;
			}
			hasSoloMode.onClick = function()
			{
				if (this.value == true) {
					AOM.BridgePreferences.aomNewDrawerType = AOM.BridgePreferences.DRAWER_TYPE_ACCORDION;
				} else {
					AOM.BridgePreferences.aomNewDrawerType = AOM.BridgePreferences.DRAWER_TYPE_CABINET;
				}
			}
			
			//add restore button
			var resetBtn = mainGroup.resetgrp.resetbtn;
			resetBtn.onClick = function()
			{	
				AOM.alert(AOM.localize("$$$/MediaGallery/JavaScript/restoreSettings=Default gallery settings restored."));
				AOM.BridgePreferences.aomReset();
			}
			//add multi-byte selection
			var hasConvertMultibyte = mainGroup.multibytegrp.hasConvertMultibyte;
			hasConvertMultibyte.helpTip = AOM.localize("$$$/MediaGallery/JavaScript/ConvertFileNameToAsciiTip=Enable this option if one of the following problems occurs:\n- IE can't load image files with multi-byte filenames.\n- FTP Server doesn't accept multi-byte filenames.");
			var isEnabled = AOM.BridgePreferences.getHasConvertMultibyte();
			AOM.BridgePreferences.aomNewHasConvertMultibyte = isEnabled;
			hasConvertMultibyte.value = (isEnabled == "true");
			hasConvertMultibyte.onClick = function()
			{
				AOM.BridgePreferences.aomNewHasConvertMultibyte =  ((this.value == true) ? "true" : "false");
			}
		
			//add preserve color profile selection
			var preserveColorProfile = mainGroup.preservecpgrp.preserveColorProfile;
			isEnabled = AOM.BridgePreferences.getPreserveColorProfile();
			AOM.BridgePreferences.aomNewPreserveColorProfile = isEnabled;
			preserveColorProfile.value = (isEnabled == "true");
			preserveColorProfile.onClick = function()
			{
				AOM.BridgePreferences.aomNewPreserveColorProfile =  ((this.value == true) ? "true" : "false");
			}			
			AOM.BridgePreferences.preferenceDialogConfigured = true;
			
			//Persist AOM Preferences State
			AOM.BridgePreferences.oldUIBrightness = app.preferences.UIBrightness;
			AOM.BridgePreferences.oldImageBackdrop = app.preferences.ImageBackdrop;
		}
	}
	catch (e)
	{
		AOM.AMG.Log.writeError("BridgePreferences.create caught - " + e);
	}
}
AOM.BridgePreferences.destroy = function ()
{
		AOM.BridgePreferences.preferenceDialogConfigured = false;
}

AOM.BridgePreferences.alert = function(info)
{
    var dlg = new Window("dialog");
    dlg.text = "Adobe Bridge";
    dlg.add("group { \
        orientation: 'column', \
        info: StaticText { text: '" + info + "' } \
        closeBtn: Button { text: '" + AOM.localizeEsc("$$$/MediaGallery/JavaScript/OK=OK") + "' } \
    }");
    dlg.children[0].info.text = info;
    dlg.defaultElement = dlg.children[0].closeBtn;
    dlg.show();
}
	
AOM.BridgePreferences.DRAWER_TYPE_CABINET = "Cabinet";
AOM.BridgePreferences.DRAWER_TYPE_ACCORDION = "Accordion";

AOM.BridgePreferences.getDrawerType = function() {
	if (app.preferences.aomDrawerType == undefined) {
		app.preferences.aomDrawerType = AOM.BridgePreferences.DRAWER_TYPE_CABINET;
	}

	return app.preferences.aomDrawerType;
}

AOM.BridgePreferences.getHasConvertMultibyte = function() {
	if (app.preferences.aomHasConvertMultibyte == undefined) {
		app.preferences.aomHasConvertMultibyte = "true";
	}

	return app.preferences.aomHasConvertMultibyte;
}

AOM.BridgePreferences.getPreserveColorProfile = function() {
	if (app.preferences.aomPreserveColorProfile == undefined) {
		app.preferences.aomPreserveColorProfile = "false";
	}

	return app.preferences.aomPreserveColorProfile;
}

AOM.BridgePreferences.aomReset = function() {
	var hasDeleted = false;
	for(var index = 0; index < app.documents.length; index++) {
		var doc = app.documents[index];
		if (AOM.workspaceLoaded(doc)) {
			if (!hasDeleted) {
				AOM.AmgUserInput.deletePersistedData();
				hasDeleted = true;
			}
		
			var palette = AOM.tabbedPalette(doc);
			var hasPdfMode = AOM.CS.CString.strToBoolean(AOM.userInput(doc).get(AOM.PDF_MODE));
			var hasWebGalleryMode = AOM.CS.CString.strToBoolean(AOM.userInput(doc).get(AOM.MEDIA_GALLERY_MODE));
			
			//clear data
			AOM.userInput(doc).initialize(true);
			
			if (AOM.AMG.userInput(doc)) {
				AOM.AMG.userInput(doc).initialize();
			}
			
			//rebuilt
			var wasPalVisible = palette.visible;
			if (!palette.visible) {
				palette.visible = true;	// CS6 Mondo Adapter bug workaround #3055803
										// Crash when removing from an invisible tabbed panel.
			}
			palette.content.remove(palette.content.children[1]);
			palette.buildUIStack(hasPdfMode, AOM.BridgePreferences.getDrawerType());
			palette.content.onResize();
			if (palette.visible != wasPalVisible)
				palette.visible = wasPalVisible;
			
			AOM.userInput(doc).set(AOM.PDF_MODE, hasPdfMode);
			AOM.userInput(doc).set(AOM.MEDIA_GALLERY_MODE, hasWebGalleryMode);
		} 
	}
}

AOM.BridgePreferences.checkChanged = function(oldValue, newValue) {
	var changed;
	if (newValue == undefined) {
		changed = false;
	} else {
		if (oldValue == undefined) {
			changed = true;
		} else {
			if (oldValue == newValue) {
				changed = false;
			} else {
				changed = true;
			}
		}
	}
	return changed;
}

AOM.BridgePreferences.doUIBrightnessChange = function() {
	for (var index = 0; index < app.documents.length; ++index) {
		var doc = app.documents[index];
		if (AOM.workspaceLoaded(doc)) {
			var palette = AOM.tabbedPalette(doc);
			var theme = AOM.theme(doc);
			theme.applyTheme(palette.content, true);
			palette.content.layout.layout(true);
		}
	}
}

AOM.BridgePreferences.doImageBackdropChange = function() {
	for (var index = 0; index < app.documents.length; ++index) {
		var doc = app.documents[index];
		if (AOM.workspaceLoaded(doc)) {
			var palette = AOM.tabbedPalette(doc);
			
			//before change, check preview is initialized?
			if(AOM.previewPalette(doc) == undefined) {
				continue;
			}

			/* Change preview palette background. */
			var previewUrl = AOM.previewPalette(doc).url;
			var previewTempFile = new File(previewUrl + "1.htm")
			AOM.PreviewPanel.previewHtml(previewUrl, previewTempFile);
			previewTempFile.copy(previewUrl);
			previewTempFile.remove();
			AOM.previewPalette(doc).url = previewUrl;
		}
	}
}
	
AOM.BridgePreferences.doSoloModeChange = function() {
	// Persist drawertype
	app.preferences.aomDrawerType = AOM.BridgePreferences.aomNewDrawerType;
	
	// Clear the global list of font contorl groups. The list is used to inform all font
	// dropdown list controls with a system font deletion (face or family). Since the UI
	// will be re-built, the list should be rebuilt, too. It is cleared here and then
	// newly-created system font control groups will add themselves to the list again.
    if (AOM.SysFontGroupHelper != undefined)
        AOM.SysFontGroupHelper.fontGroupList = new Array();
			
	for(var index = 0; index < app.documents.length; ++index) {
		var doc = app.documents[index];
		
		if (AOM.workspaceLoaded(doc)) {
			var userInput = AOM.userInput(doc);
			var palette = AOM.tabbedPalette(doc);
			var hasPdfMode = AOM.CS.CString.strToBoolean(userInput.get(AOM.PDF_MODE));
			
			// Rebuilt UI
			var wasPalVisible = palette.visible;
			if (!palette.visible) {
				palette.visible = true;	// CS6 Mondo Adapter bug workaround #3055803
										// Crash when removing from an invisible tabbed panel.
			}
			palette.content.remove(palette.content.children[1]); 
			palette.buildUIStack(hasPdfMode, AOM.BridgePreferences.getDrawerType());
			palette.content.onResize();
			if (palette.visible != wasPalVisible)
				palette.visible = wasPalVisible;
		} 
	}
}

AOM.BridgePreferences.doConvertMultibyteChange = function() {
	app.preferences.aomHasConvertMultibyte = AOM.BridgePreferences.aomNewHasConvertMultibyte;
}

AOM.BridgePreferences.doPreserveColorProfileChange = function() {
	app.preferences.aomPreserveColorProfile = AOM.BridgePreferences.aomNewPreserveColorProfile;
}

//Workaround for the check/uncheck startup prop.
AOM.Workspace = function(){}
AOM.Workspace.BASEDIR = AOM.Paths.base + "/";
AOM.Workspace.WORKSPACE_NAME = AOM.Workspace.BASEDIR + "Workspaces/AdobeOutputModule.workspace";
AOM.Workspace.CACHE_WORKSPACE_NAME = AOM.Paths.workspace + "/!!-$$$AdobeOutputModule.workspace";

AOM.Workspace.removeCacheWorkspace = function() {
	var cacheWorkspaceFile = new File(AOM.Workspace.CACHE_WORKSPACE_NAME);
	
	if (cacheWorkspaceFile.exists) {
		cacheWorkspaceFile.open("r");
		var content = cacheWorkspaceFile.read();
		cacheWorkspaceFile.close();
		
		var findIndex = content.lastIndexOf("tab name='Output'");
		//if not find output config info into cache workspace file, remove this cache file.
		if (findIndex < 0) {
			cacheWorkspaceFile.remove();
		}
	} 
}

//disable workspace file method rename.
AOM.Workspace.DISABLE_SUFFIX = ".disable";
AOM.Workspace.disableWorkspace = function() {
	if(AOM.Workspace.disableStartupAOM == true) {
		AOM.Utils.moveFile(
			AOM.Workspace.WORKSPACE_NAME, 
			AOM.Workspace.WORKSPACE_NAME + AOM.Workspace.DISABLE_SUFFIX);
	}
}

AOM.Workspace.enableWorkspace = function() {
	AOM.Utils.moveFile(
		AOM.Workspace.WORKSPACE_NAME + AOM.Workspace.DISABLE_SUFFIX, 
		AOM.Workspace.WORKSPACE_NAME);
}

AOM.Utils = function(){}

AOM.Utils.moveFile = function(source, dest) {
	if (source == undefined || dest == undefined) {
		throw new Error("AOM.Utils.moveFile() throw an exception:source or dest parameters is null.");
	}

	var sourceFile = new File(source);
	if (sourceFile.exists) {
		if (sourceFile.readonly) {
			return false;
		}

		if (sourceFile.copy(dest)) {
			if (sourceFile.remove()) {
				return true;
			} else {
				var destFile = new File(dest);
				destFile.remove();
				return false;
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

AOM.Utils.writePersistFileHeader = function(persistFile)
{
	persistFile.writeln("/* Generated by Adobe Output Module");
	persistFile.writeln("        AOM Build:  [" + AOM.build + "]");
	persistFile.writeln("        File Version:  [" + AOM.persistFileVersion + "]");
	persistFile.writeln("*/");
}

AOM.Utils.checkPersistFiles = function()
{	
	var files = [
		AOM.CS.Paths.persistedUserData,
		AOM.AMG.Paths.persistedUserData,
		AOM.AMG.Paths.persistedFTPPresetUserData
	];
	
	for(var i = 0; i < files.length; ++i) {
		AOM.Utils.processPersistFile(files[i]);
	}
}

AOM.Utils.processPersistFile = function(filename)
{
	var persistFile = new File(filename);
	persistFile.open("r");
	
	var inHeader = false;
	var aomVersion;
	var fileVersion;
	
	while(!persistFile.eof) {
		line = persistFile.readln();
		if(inHeader == false && line.indexOf("/*") >= 0)
			inHeader = true;
		if(inHeader == true) {
			if(line.indexOf("*/") >= 0)
				break;
			if(line.indexOf("AOM Build") >= 0) {
				var reg = new RegExp("\\[.*\\]");
				var aomVersionArray = reg.exec(line);
				if(aomVersionArray.length > 0)
					aomVersion = aomVersionArray[0];
			}
			if(line.indexOf("File Version") >= 0) {
				var reg = new RegExp("\\[.*\\]");
				var fileVersion = reg.exec(line)[0];
			}
		}
	}
	persistFile.close();
	
	if(aomVersion == undefined || fileVersion == undefined || 
	   fileVersion != "[" + AOM.persistFileVersion + "]")
		persistFile.remove();
}



/* The Layout Manager specific to the group which is beneath
 * the header group (i.e. the one containing the two big buttons. */
 
AOM.UIStackLayout = function(group)
{
	this.group = group;
}

AOM.UIStackLayout.prototype.layout = function()
{
	/* The parent is the *content* group of the tabbed
	 * palette. */
	var containerWidth = this.group.parent.size.width;
	var containerHeight = this.group.parent.size.height;

	var startY = 0;
	var headerGroup = this.group.parent.children[0];
	if (headerGroup.size == undefined) {
		startY = headerGroup.preferredSize.height;
	} else {
		startY = headerGroup.size.height;
	}

	this.group.size = [containerWidth, containerHeight - startY];
	this.group.location = [0, startY];
	
	for(var i = 0; i < this.group.children.length; ++i) {
		var currentChild = this.group.children[i];
		currentChild.size = this.group.size;
		currentChild.location = [0, 0];
		if(currentChild.visible == true) {
			currentChild.layout.layout(true);
		}
	}
	
	/* To fix #1729261 bug, a small block can not live change. */
	var firstHeadGroup = this.group.parent.children[0];
	if (firstHeadGroup.layout != undefined) {
		firstHeadGroup.layout.layout(true);
	}
	firstHeadGroup.size =[containerWidth, firstHeadGroup.preferredSize.height];
}

AOM.UIStackResource =
	"group {\
		alignment: ['fill', 'fill'], \
		orientation: 'stack', \
		pdfContactSheet: Group { \
			name:'group1', \
			orientation:'column', \
			alignment:['fill', 'top'], \
			margins:0, spacing:0 \
		} \
		webGallery: Group { \
			name:'group2', \
			orientation:'column', \
			alignment:['fill', 'top'], \
			margins:0, spacing:0 \
		} \
	}";

//Workaround for the check/uncheck startup prop.
AOM.Workspace.enableWorkspace();

AOM.StartupTimes.end("ScriptLoading");

} // end of the else of 'if (BridgeTalk.appName != "bridge" || BridgeTalk.appVersion < AOM.requiredBridgeVersion)'
