
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2008 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 2.0
*
* MediaGallery Originally Written by Quality Process Incorporated, Enhanced by
* Adobe System China. Contact Sheet written by Adobe System China.
* 
*
**************************************************************************/

AOM.ZStringDialogTitle = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/CreateGallery=Create Gallery");
AOM.ZStringGroupFile = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/GroupFile=Group file...");
AOM.ZStringGalleryCreationStoppedCouldNotOpenStyleFile = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailOpenStyleFile=Could not open style file - gallery creation stopped.");



AOM.AmgFlashGalleryCreator = function (images, destinationFolder, taskManager, document, createMode, jpegQuality)
{
	try
	{
	    /* Store the current document in order to distinguish between multiple
	     * Bridge windows. */
	    AOM.AmgFlashGalleryCreator.currentDocument = document;

		AOM.AmgFlashGalleryCreator.initializeFormValueList();
		var imageMaximumDimension = AOM.AmgFlashGalleryCreator.initializeSizesList();
		
		var currentFormValueList = AOM.AmgFlashGalleryCreator.formValueList(document);
		var galleryFolder = AOM.AmgFlashGalleryCreator.initializeFlashGalleryFolder(
                                destinationFolder, currentFormValueList.template);
		var resourcesFolder = galleryFolder + "resources/";
		var styleFile = resourcesFolder + "style.xml";
		var groupFile = resourcesFolder + "group.xml";
		var copyright = currentFormValueList.copyright;
		if (copyright == undefined)
			copyright = "";

		AOM.AmgFlashGalleryCreator.transformFiles(galleryFolder);
		AOM.AmgFlashGalleryCreator.writeStyleFile(currentFormValueList.models, new File(styleFile));

        AOM.AmgFlashGalleryCreator.currentDocument = undefined;

		var callback = function () {
            AOM.AmgFlashGalleryCreator.writeGroupFile(images, new File(groupFile), resourcesFolder, document);};
		AOM.AmgGalleryCreator.processImages(images, AOM.AmgFlashGalleryCreator.sizesList(document),
            imageMaximumDimension, resourcesFolder, copyright, taskManager, createMode,
            {action:callback, title: AOM.ZStringDialogTitle, description: AOM.ZStringGroupFile}, jpegQuality);
	}
	catch(e)
	{
	    taskManager.showProgressOnStop = false;
	    taskManager.stop({title: AOM.ZStringGroupFile,
                          description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/AccessDenied=Error creating gallery. Access denied."),
                          button: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/OK=OK")});
	    AOM.AMG.Log.writeError("AOM.AmgFlashGalleryCreator caught - " + e);
	}
}
AOM.AmgFlashGalleryCreator.initializeSizesList = function (desiredSizes)
{
    var document = AOM.AmgFlashGalleryCreator.currentDocument;
	var fvl = AOM.AmgFlashGalleryCreator.formValueList(document);
	document.aomJsFuncs.amgFlashGalleryCreatorSizesList = {}
	var sizes = document.aomJsFuncs.amgFlashGalleryCreatorSizesList;
	sizes.large = {}
	sizes.large.width = fvl.largeWidth;
	sizes.large.height = fvl.largeHeight;
	sizes.large.size = "large";
	sizes.medium = {}
	sizes.medium.width = fvl.mediumWidth;
	sizes.medium.height = fvl.mediumHeight;
	sizes.medium.size = "medium";
	sizes.thumbnail = {}
	sizes.thumbnail.width = fvl.thumbnailWidth;
	sizes.thumbnail.height = fvl.thumbnailHeight;
	sizes.thumbnail.size = "thumb";
	function sortDescending(a, b) {return b - a;}
	a = [fvl.largeWidth, fvl.largeHeight, fvl.mediumWidth, fvl.mediumHeight, fvl.thumbnailWidth, fvl.thumbnailHeight];
	return a.sort(sortDescending)[0]; // return the maximum value
}
AOM.AmgFlashGalleryCreator.writeGalleryStyle = function (outFile)
{
	// Copy the contents of the previously localized 
	// galleryStyle.xml to outFile. The only thing special
	// is that we have to skip the first line...
	var galleryStylePath = AOM.AMG.userFolder(AOM.AmgFlashGalleryCreator.currentDocument) + "galleryStyle.xml";
	var file = new File(galleryStylePath);
	if (!file.open("r"))
	{
		AOM.AMG.Log.writeError("writeGalleryStyle - could not open style file ("+file.fsName+")");
		throw({action:"stop", 
               title: AOM.ZStringDialogTitle,
               description: AOM.ZStringGalleryCreationStoppedCouldNotOpenStyleFile });
	}
		
	file.readln(); // get past the first line
	while(!file.eof)
	{
		outFile.writeln(file.readln());
	}
	file.close();
}
AOM.AmgFlashGalleryCreator.writeStyleFile = function (modelItems, file)
{
	if (file instanceof File == false)
		return AOM.AMG.Log.writeError("AOM.AmgFlashGalleryCreator.writeStyleFile - file is not File");
		
	file.lineFeed = "unix";
	file.encoding = "UTF8"
	if (!file.open("w", "TEXT", "????"))
	{
		AOM.AMG.Log.writeError("writeStyleFile - could not open style file ("+file.fsName+")");
		throw({action:"stop", title: AOM.ZStringDialogTitle,
               description: AOM.ZStringGalleryCreationStoppedCouldNotOpenStyleFile});
	}
	file.write("\uFEFF");

	file.writeln("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	file.writeln("<galleryStyle xmlns=\"http://ns.adobe.com/AMG/1.2/\">");
	
	AOM.AmgFlashGalleryCreator.writeGalleryStyle(file);
	
	var visitedElements = new Array();
	var openElement = function (element)
	{
		writeLine("<"+element+">");
		var s = new String(element);
		s.mode = "open";
		visitedElements.push(s);
	}
	var closeElement = function (element)
	{
		writeLine("</"+element+">");
	}
	var startElement = function (element)
	{
		write(indent()+"<"+element+" ");
		var s = new String(element);
		s.mode = "start";
		visitedElements.push(s);
	}
	var endElement = function (element)
	{
		write("/>\n");
	}
	var writeAttribute = function (attribute, value)
	{
		write(attribute+"='"+value+"' ");
	}
	var isOpen = function (element)
	{
		for (var i = 0; i < visitedElements.length; i++)
		{
			if (visitedElements[i] == element)
				return true;
		}
		return false;
	}
	var unwind = function (count)
	{
		while (visitedElements.length > count)
		{
			var e = visitedElements.pop();
			if (e.mode == "start")
				endElement(e);
			else
				closeElement(e);
		}
	}
	var write = function (s)
	{
		file.write(s);
	}
	var indent = function ()
	{
		var s = "	";
		for (var i = 0; i < visitedElements.length; i++)
			s += "	";
		return s;
	}
	var writeLine = function (s)
	{
		file.writeln(indent() + s);
	}

	modelItems = AOM.AMG.galleryMakerData(AOM.AmgFlashGalleryCreator.currentDocument).models.style;
	for (var i = 0; i < modelItems.length; i++)
	{
		mi = modelItems[i];
		var elements = mi.path.split(".");
		for (var j = 0; j < elements.length; j++)
		{
			var e = elements[j];
			if (isOpen(e) == true)
				continue;
			unwind(j);
			if (j == elements.length - 2) // next to last element is the last tag
			{
				startElement(e);
				continue;
			}
			if (j == elements.length - 1) // last element is attribute
			{
				var id = AOM.AmgGalleryMaker.idFromPath(mi.path, AOM.AmgFlashGalleryCreator.currentDocument);
				var value = AOM.AMG.userInput(AOM.AmgFlashGalleryCreator.currentDocument).get(id);
				writeAttribute(e, AOM.AMG.localize(value == undefined ? mi.value : value));
				continue;
			}
			//unwind(j);
			openElement(e);
		}
	}
	unwind(0);
	file.writeln("</galleryStyle>\n");
	file.close();
}
AOM.AmgFlashGalleryCreator.get = function (path, defaultValue)
{
	var id = AOM.AmgGalleryMaker.idFromPath(path);
	if (id == undefined)
		return defaultValue;
	var value = AOM.AMG.userInput().get(id);
	if (value == undefined)
		return AOM.AMG.localize(defaultValue);
	return AOM.AMG.localize(value);
}
AOM.AmgFlashGalleryCreator.transformFiles = function (galleryFolder)
{
	// At this point index.html and localText.xml should be 
	// in the gallery folder and ready to be transformed.
	var fvl = AOM.AmgFlashGalleryCreator.formValueList(AOM.AmgFlashGalleryCreator.currentDocument);
	
	// index.html - replace the following items with the associated string
	var replaceList = {};
	replaceList["%windowtitle%"]	= fvl.windowTitle;
	replaceList["%baseRefURL%"]		= fvl.baseRefUrl;	// does this ever change?
	replaceList["%groupxml%"]		= fvl.groupxml;		// does this ever change?
	replaceList["%stylexml%"]		= fvl.stylexml;
	var regex = /%[^%\s]*?%/; // Matches pairs of '%' with no whitespace in between.
	AOM.AmgFlashGalleryCreator.searchReplaceFile(new File(galleryFolder + "index.html"), regex, replaceList);
	
	// localText.xml - we want to replace all zstrings with localized text
	AOM.AMG.localizeFile(new File(galleryFolder + "/resources/localText.xml"));
}

AOM.AmgFlashGalleryCreator.searchReplaceFile = function (file, regex, replaceList)
{
	// Check for a match for regex in the contents of file. If found, use the match 
	// as an index into replaceList. Do a global replace of match with the value 
	// of replaceList[match].
	// Throw an exception if we get a match but it is not in replaceList.
	
	// For now we have small files and so we grab the whole thing. At some point we
	// may want to set a threshhold and do it line by line for big files.
	if (!file.open("r"))
	{
		AOM.AMG.Log.writeError("searchReplaceFile - could not open file for read ("+file.fsName+")");
		throw({action:"stop", title: AOM.ZStringDialogTitle,
               description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailOpenReadFile=Could not open/read file - gallery creation stopped.") });
	}
	var contents = file.read();
	file.close();
	// As long as we find a match for regex in contents replace w/replaceList[match].
	var match;
	while((match = contents.match(regex)) != null)
	{
			var replacement = replaceList[match];
			if (replacement == undefined)
			{
				AOM.AMG.Log.writeError("searchReplaceFile - no entry in replaceList for '" + match + "'");
				throw({action:"stop", title: AOM.ZStringDialogTitle,
                       description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailPerformOperation=Could not perform operation - gallery creation stopped.") });
			}
			contents = contents.replace(new RegExp(match, "g"), replacement);
	}
	file.encoding = "UTF8";
	if (!file.open("w", "TEXT", "????"))
	{
		AOM.AMG.Log.writeError("searchReplaceFile - could not open file for write ("+file.fsName+")");
		throw({action:"stop", title: AOM.ZStringDialogTitle,
               description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailOpenWriteFile=Could not open/write file - gallery creation stopped.") });
	}
	file.write("\uFEFF");
	file.write(contents);
	file.close();
}
/*
AOM.AmgFlashGalleryCreator.groupItemMetadata = function (image)
{
	AOM.AMG.Log.writeError("AOM.AmgFlashGalleryCreator.groupItemMetadata - not implemented");
	return "";
}
*/
AOM.AmgFlashGalleryCreator.escapeSpecialChars= function(filename, asTitle)
{
	// use this function to escape special chars in filename before write it into group.xml file
	if (filename == undefined || filename.length == 0) return filename;
	
	filename = filename.replace(/&/g, "&amp;"); 
	filename = filename.replace(/</g, "&lt;");
	filename = filename.replace(/>/g, "&gt;");
	filename = filename.replace(/\'/g, "&apos;");
	filename = filename.replace(/\"/g, "&quot;");
	if( !asTitle ) 
		filename = filename.replace(/#/g, "%23");
	
  	return filename;
}
AOM.AmgFlashGalleryCreator.writeGroupFile = function (images, file, resourcesFolder, document)
{
	var log = false;
	if (file instanceof File == false)
		return AOM.AMG.Log.writeError("AOM.AmgFlashGalleryCreator.writeGroupFile - file is not File");
	// create group.xml and the various resized images
	//AOM.AmgFlashGalleryCreator.groupItemXml = function (image, indent, taskmanager) // was itemText()
	var itemXml = function (image, indent)
	{
		if (AOM.AMG.verbose || log) AOM.AMG.Log.writeLine("itemXml - " + image.name);
		if (image.amg.sizes == undefined)
			return AOM.AMG.Log.writeError("itemXml - image.amg.sizes is undefined ("+image.name+")");
			
		var text = "";
		text += indent + "<item>\n";
		var title = "";
		if (AOM.AMG.galleryMakerData(document).models.galleryName.indexOf("journal") == -1)
		{
			title = image.name;
			// escape special chars to show correct filename in flash gallery. 
			title = AOM.AmgFlashGalleryCreator.escapeSpecialChars(title, true);
		}
		else
			title = AOM.AmgFlashGalleryCreator.groupItemMetadata(image);
		text += indent + "	<title>" + AOM.PDFGenerator.combineDiacriticMarks(title) + "</title>\n";
		text += indent + "	<description />\n";
		// NOTE - Rumor has it the following fields are ignored. Only title 
		//		  and description are used. Place metadata in title above
		// TODO - confirm this is the case
		text += indent + "	<metadata></metadata>\n";
		text += indent + "	<photographer></photographer>\n";
		text += indent + "	<copyright></copyright>\n";
		text += indent + "	<imageId image='' dbtype='' dbname='' />\n";
		text += indent + "	<mediaType category='image' format='jpeg' />\n";
		text += indent + "	<renditions>\n";
		for (var i in image.amg.sizes)
		{
			var size = image.amg.sizes[i];
			var relativePath = size.imagePath.substr(resourcesFolder.length); 
			// escape special chars to generate correct path in group.xml. 
			relativePath = AOM.AmgFlashGalleryCreator.escapeSpecialChars(relativePath);
			text += indent + "		<rendition src='"+ relativePath +"' height='"+ size.height +"' width='"+ size.width +"' size='"+ size.size +"' />\n";
		}
		text += indent + "	</renditions>\n";
		text += indent + "</item>\n";
		return text;
	}
	var fvl = AOM.AmgFlashGalleryCreator.formValueList(document);
	file.encoding = "UTF8";
	if (file.open("w", "TEXT", "????"))
	{
		file.write("\uFEFF");
		file.writeln("<?xml version='1.0' encoding='UTF-8'?>");
		file.writeln("<mediaGroup>");
		file.writeln(	AOM.PDFGenerator.combineDiacriticMarks(AOM.AmgFlashGalleryCreator.groupInfoXml("	", document)));
		file.writeln(	AOM.AmgFlashGalleryCreator.sizesXml("	", document));
		file.writeln("	<media>");
		for (var i = 0; i < images.length; i++)
		{
			// write the xml and create tasks for the image processing
			var image = images[i];
			if (!image.amgSkip())
			{
				var s = itemXml(image, "	");
				if (s != undefined)
					file.writeln(s);
			}
		}
		file.writeln("	</media>");
		file.writeln("</mediaGroup>");
		file.close();
	}
	else
	{
		AOM.AMG.Log.writeError(AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName);
		throw({action:"stop", title: AOM.ZStringDialogTitle, description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailOpenFile=Could not open file - gallery creation stopped.") });
	}
}
AOM.AmgFlashGalleryCreator.groupItemMetadata = function (image)
{
	var metadata = image.metadata;
	if (metadata == undefined)
		return "";
	if (AOM.AmgFlashGalleryCreator.metadataItemList == undefined)
	{
		AOM.AmgFlashGalleryCreator.metadataItemList = new Array();
		AOM.AmgFlashGalleryCreator.makeMedataItemList(AOM.AmgFlashGalleryCreator.metadataItemList);
	}
	var mil = AOM.AmgFlashGalleryCreator.metadataItemList;
	var formattedMetadata = new String();
	function  formatItem(s)
	{
		return ("<p>" + AOM.AmgFlashGalleryCreator.escapeSpecialChars(s) + "</p>\n");
	}
	for (var i = 0; i < mil.length; i++)
	{
		var mi = mil[i]; // Get the next MetadataPair.
		if (mi.title == "namespace")
			metadata.namespace = mi.description;
		else
		{
			switch (mi.title)
			{
			 default:
				// The default is the localized description followed by the value
				if (metadata[mi.title] != "") {
					if (mi.title == "CreateDate" || mi.title == "ModifyDate") {
						var dateString = metadata[mi.title];
						var dateFormat = dateString;
						if (AOM.CS.Validation.isDate(dateString)) {
							dateFormat = dateString.substr(0,4) + "/"
									+ dateString.substr(5,2) + "/"
									+ dateString.substr(8,2) + ", "
									+ dateString.substr(11,2) + ":"
									+ dateString.substr(14,2) + ":"
									+ dateString.substr(17,2);
						}
						formattedMetadata += formatItem(AOM.AMG.localize(mi.description) + dateFormat);
					} else
						formattedMetadata += formatItem(AOM.AMG.localize(mi.description) + metadata[mi.title]);
				}
				break;
		/*
			 case "Copyright":
				// overwrite Copyright if metadata.copyrightInfo exists...
				//if (otherMetadata.copyrightInfo != undefined) // <?> what is the source of this other metadata?
				//	formattedMetadata += formatItem(AOM.AMG.localize(mi.description) + otherMetadata.copyrightInfo);
				//else
				//{
					if (metadata[mi.title] != "")
						formattedMetadata += formatItem(AOM.AMG.localize(mi.description) + metadata[mi.title]);
				//}
				break;
		*/
			 case "Flash":
				// Is there any time when we don't want to show this item at all?
				var flash = metadata["Flash"]["exif:Flash/exif:Fired"];
				
				var flashString = undefined;
				if(flash != undefined) {
					if(typeof(flash) == "string") {
						if(flash.toLowerCase() == "true")
							flashString = AOM.AMG.localize("$$$/MediaGallery/htmlGallery/fired=fired");
						else if(flash.toLowerCase() == "false")
							flashString = AOM.AMG.localize("$$$/MediaGallery/htmlGallery/notFired=not fired");
					} else {
						if(flash == true)
							flashString = AOM.AMG.localize("$$$/MediaGallery/htmlGallery/fired=fired");;
						else if(flash == false)
							flashString = AOM.AMG.localize("$$$/MediaGallery/htmlGallery/notFired=not fired");
					}
				}
				
				// <?> should 'fired' and 'not fired' be localized?
				//Of Course!
				if(flashString != undefined)
					formattedMetadata += formatItem(AOM.AMG.localize("$$$/MediaGallery/JavaScript/flashFired=Flash fired: ") + flashString);
				break;
			 case "_comment_":
			    formattedMetadata += formatItem(AOM.AMG.localize(mi.description));
			}
		}
	}
	return formattedMetadata;
}
AOM.AmgFlashGalleryCreator.makeMedataItemList = function (metadataItemList)
{
	function MetadataPair(title, description)
	{
		this.title = title;
		this.description = description;
	}
	// from image.metadata
	metadataItemList.push(new MetadataPair("namespace", "http://purl.org/dc/elements/1.1/"));
	metadataItemList.push(new MetadataPair("title", "$$$/MediaGallery/JavaScript/title=Title: "));
	metadataItemList.push(new MetadataPair("subject", "$$$/MediaGallery/JavaScript/subject=Subject: "));
	metadataItemList.push(new MetadataPair("description", "$$$/MediaGallery/JavaScript/description=Description: "));
	metadataItemList.push(new MetadataPair("format", "$$$/MediaGallery/JavaScript/format=Format: "));
	metadataItemList.push(new MetadataPair("creator", "$$$/MediaGallery/JavaScript/creator=Creator: "));
	//
	metadataItemList.push(new MetadataPair("namespace", "http://ns.adobe.com/xap/1.0/"));
	metadataItemList.push(new MetadataPair("CreateDate", "$$$/MediaGallery/JavaScript/createDate=Creation date: "));
	metadataItemList.push(new MetadataPair("ModifyDate", "$$$/MediaGallery/JavaScript/modifyDate=Date file modified: "));
	//
	metadataItemList.push(new MetadataPair("namespace", "http://ns.adobe.com/tiff/1.0/"));
	metadataItemList.push(new MetadataPair("Make", "$$$/MediaGallery/JavaScript/cameraMake=Camera make: "));
	metadataItemList.push(new MetadataPair("Model", "$$$/MediaGallery/JavaScript/cameraModel=Camera model: "));
	metadataItemList.push(new MetadataPair("Software", "$$$/MediaGallery/JavaScript/software=Software: "));
	metadataItemList.push(new MetadataPair("Artist", "$$$/MediaGallery/JavaScript/artist=Artist: "));
	metadataItemList.push(new MetadataPair("Copyright", "$$$/MediaGallery/JavaScript/copyright=Copyright: "));
	metadataItemList.push(new MetadataPair("XResolution", "$$$/MediaGallery/JavaScript/xres=X resolution: "));
	metadataItemList.push(new MetadataPair("YResolution", "$$$/MediaGallery/JavaScript/yres=Y resolution: "));
	// resolutionUnit == 2 ? "inches" : "centimeters" 
	metadataItemList.push(new MetadataPair("ResolutionUnit", "$$$/MediaGallery/JavaScript/resolutionUnit=resolution unit: "));
	//
	/*
	var xres = 0, yres = 0;
	if (imetadata.XResolution != undefined && imetadata.XResolution != "" 
	 && imetadata.YResolution != undefined && imetadata.YResolution != "") 
	{
		eval("xres = 0 + " + imetadata.XResolution);
		eval("yres = 0 + " + imetadata.XResolution);
		returnStr += AOM.AMG.localize("$$$/MediaGallery/JavaScript/pixelResolutionx=Pixel resolution, x: ") + xres + " ";
		returnStr += AOM.AMG.localize("$$$/MediaGallery/JavaScript/pixelResolutiony=y: ") + yres + " , ";
		returnStr += AOM.AMG.localize("$$$/MediaGallery/JavaScript/resolutionUnit=resolution unit: ") + (imetadata.ResolutionUnit == 2 ? "inches" : "centimeters") + macCR;
	}
	*/
	//
	metadataItemList.push(new MetadataPair("namespace", "http://ns.adobe.com/exif/1.0/"));
	metadataItemList.push(new MetadataPair("_comment_", "$$$/MediaGallery/JavaScript/imageWidth=Image Size (in pixels)"));
	metadataItemList.push(new MetadataPair("PixelXDimension", "$$$/MediaGallery/JavaScript/x=  x: "));
	metadataItemList.push(new MetadataPair("PixelYDimension", "$$$/MediaGallery/JavaScript/y=  y: "));
	metadataItemList.push(new MetadataPair("MeteringMode", "$$$/MediaGallery/JavaScript/meteringMode=Metering mode: "));
	metadataItemList.push(new MetadataPair("FileSource", "$$$/MediaGallery/JavaScript/fileSource=File source: "));
	metadataItemList.push(new MetadataPair("FocalLength", "$$$/MediaGallery/JavaScript/focalLength=Focal length: "));
	metadataItemList.push(new MetadataPair("MaxApertureValue", "$$$/MediaGallery/JavaScript/maxApertureValue=Max aperture value: "));
	//
	// what is up w/this one?	
	metadataItemList.push(new MetadataPair("Flash", "$$$/MediaGallery/JavaScript/flashFired=Flash fired: "));
}


AOM.AmgFlashGalleryCreator.groupInfoXml = function(indent, document)
{
	var fvl = AOM.AmgFlashGalleryCreator.formValueList(document);
	var text = "";
	text += indent + "<groupInfo>\n";
	text += indent + "	<identifier>bluefire.adobe.gallery1</identifier>\n";
	text += indent + "	<thumbnailPath src='gallerythumb.jpg' />\n";
	text += indent + "	<previewPath src='' />\n";
	text += indent + "	<galleryName>"+fvl.galleryName+"</galleryName>\n";
	text += indent + "	<galleryDescription>"+fvl.galleryDescription+"</galleryDescription>\n";
	text += indent + "	<galleryVersion>1.0</galleryVersion>\n";
	text += indent + "	<x:xmpmeta xmlns:x='adobe:ns:meta/' >\n";
	text += indent + "		<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' >\n";
	text += indent + "			<rdf:Description xmlns:dc=\"http://purl.org/dc/elements/1.1/\" rdf:about=\"\" >\n";
	text += indent + "				<dc:creator>\n";
	text += indent + "					<rdf:Seq>\n";
	text += indent + "						<rdf:li>Adobe Systems</rdf:li>\n";
	text += indent + "					</rdf:Seq>\n";
	text += indent + "				</dc:creator>\n";
	text += indent + "				<dc:date>2006-05-23T12:00-00:00</dc:date>\n"; // todo - put in current date
	text += indent + "			</rdf:Description>\n";
	text += indent + "			<rdf:Description xmlns:xap=\"http://ns.adobe.com/xap/1.0/\" rdf:about=\"\" >\n";
	text += indent + "				<xap:CreatorTool>Adobe Bridge CS6</xap:CreatorTool>\n";
	text += indent + "			</rdf:Description>\n";
	text += indent + "		</rdf:RDF>\n";
	text += indent + "	</x:xmpmeta>\n";
	text += indent + "	<windowSize x='auto' y='auto' />\n";
	text += indent + "	<category>"+fvl.category+"</category>\n";
	text += indent + "	<styleNS url=\"adobe.com/schemas/webphotogallery1\" />\n";
	text += indent + "	<windowSize width='auto' height='auto' />\n";
	text += indent + "	<custom>\n";
	text += indent + "		<siteTitle>"+fvl.siteTitle+"</siteTitle>\n";
	text += indent + "		<groupTitle>"+fvl.groupTitle+"</groupTitle>\n";
	text += indent + "		<groupDescription>" + fvl.groupDescription + "</groupDescription>\n";
	if (!fvl.contactName.amgIsEmpty())
		text += indent + "		<contactName>"+fvl.contactName+"</contactName>\n";
	else
	{
		// if the user does not enter a contact name but does enter a contact email,
		// use contact email as the contact name
		if (!fvl.contactEmail.amgIsEmpty())
			text += indent + "		<contactName>"+fvl.contactEmail+"</contactName>\n";
		else
			text += indent + "		<contactName></contactName>\n";
	}
	if (fvl.contactEmail.amgIsEmpty())
		text += indent + "		<contactEmail></contactEmail>\n";
	else {
		var action = "";
		
		if(AOM.AMG.Tests.isEmail(fvl.contactEmail)) {
			action = "mailto:";
		} else if(!AOM.AMG.Tests.isSupportedURL(fvl.contactEmail)) {
			// It does not have a protocol prefix, but we still consider it a
			// URL. So use "http://" by default.		
			action = "http://";
		}

		text += indent + "		<contactEmail>"+action+fvl.contactEmail+"</contactEmail>\n";
	}
	text += indent + "	</custom>\n";
	text += indent + "</groupInfo>\n";
	return text;
}

AOM.AmgFlashGalleryCreator.sizesXml = function(indent, document)
{
	var text = "";
	var gallerySizeList = AOM.AmgFlashGalleryCreator.sizesList(document);
	text += indent + "<sizes>\n";
	for (var i in gallerySizeList)
	{
		var size = gallerySizeList[i];
		text += indent + "	<imageSize size='"+size.size+"' maxwidth='" +size.width+ "' maxheight='" +size.height+ "' />\n";
	}
	text += indent + "</sizes>\n";
	return text;
}

AOM.AmgFlashGalleryCreator.initializeFlashGalleryFolder = function (destinationFolder, template)
{
	// delete the destinationFolder if it exists
	// <?> in the case of save to disk, make sure the user is asked
	// if it's okay to blow away the destination folder contents. <?>
	if (destinationFolder.exists)
		AOM.AMG.removeFolderContents(destinationFolder);
	else
		destinationFolder.create();
	
	// create the directory structure
	var subFolders = new Array();
	subFolders.push("/resources");
	subFolders.push("/resources/images");
	var sizesList = AOM.AmgFlashGalleryCreator.sizesList(AOM.AmgFlashGalleryCreator.currentDocument);
	for (var i in sizesList)
	{
		subFolders.push("/resources/images/" + sizesList[i].size);
	}
	
	// create a list of source and destination files
	var source;
	var sourcePath = AOM.AMG.mediaGalleryFolder() + "/resources/flashgallery/";
	var filePath;
	var file;
	var files;
	var sourceDestinationList = new Array();

	var addFiles = function (files, destination, list)
	{
		for (var i = 0; i < files.length; i++)
		{
			filePath = destination + files[i];
			sourceDestinationList.push({'source' : sourcePath + files[i], 'destination' : filePath});
		}
	}
	
	// files for root of destination folder
	files = ["index.html"];
	addFiles(files, destinationFolder + "/", sourceDestinationList);
	
	// files for .../destination/resources
	files = ["gallery.swf", "loading.swf", "playerProductInstall.swf", "AC_OETags.js", "AC_RunActiveContent.js", "localText.xml"];
	addFiles(files, destinationFolder + "/resources/", sourceDestinationList);

	AOM.AMG.createFolderContents(destinationFolder, subFolders, sourceDestinationList);

	return destinationFolder + "/";
}
AOM.AmgFlashGalleryCreator.dealPercentSign = function(description)
{
	var temp = "";
	for (var i = 0; i < description.length; i++) {
		temp += description[i];
		if (description[i] == '%')
			temp += "%";
	}
	return temp;
}
AOM.AmgFlashGalleryCreator.initializeFormValueList = function ()
{
	// Isolate knowledge of the AMG control window layout.
	// Add functions that return a value from the AMG control window heirarchy.
	// <?> Is it okay to just grab all the values now or should these be functions?
	AOM.AmgFlashGalleryCreator.currentDocument.aomJsFuncs.amgFlashGalleryCreatorFvl = new Object();
	var fvl = AOM.AmgFlashGalleryCreator.currentDocument.aomJsFuncs.amgFlashGalleryCreatorFvl;
	
	fvl.template			= AOM.AmgFlashGalleryCreator.get("fvl_template");
	fvl.stylexml			= "style.xml";
	fvl.groupxml			= "group.xml";
	fvl.baseRefUrl			= "resources/";
	fvl.windowTitle			= AOM.AmgFlashGalleryCreator.get("fvl_windowTitle");
	fvl.category			= AOM.AMG.localize("$$$/FlashGallery/category=Web Photo Gallery");
	fvl.galleryName			= AOM.AmgFlashGalleryCreator.get("fvl_galleryName");
	fvl.galleryDescription	= AOM.AMG.localize(AOM.AmgFlashGalleryCreator.dealPercentSign(
		AOM.AmgFlashGalleryCreator.get("fvl_galleryDescription"))); // TODO - can localization be done in one place?
	fvl.siteTitle			= AOM.AmgFlashGalleryCreator.get("fvl_siteTitle");
	fvl.groupTitle			= AOM.AmgFlashGalleryCreator.get("fvl_groupTitle");
	fvl.groupDescription	= AOM.AmgFlashGalleryCreator.get("fvl_groupDescription");
	fvl.contactName			= AOM.AmgFlashGalleryCreator.get("fvl_contactName");
	fvl.contactEmail		= AOM.AmgFlashGalleryCreator.get("fvl_contactEmail");
    fvl.thumbnailSize		= AOM.AmgFlashGalleryCreator.get("fvl_thumbnailSize");
    fvl.slideShowSize		= AOM.AmgFlashGalleryCreator.get("fvl_slideShowSize");
    fvl.galleryShowSize		= AOM.AmgFlashGalleryCreator.get("fvl_galleryShowSize");
	fvl.copyright			= AOM.AmgFlashGalleryCreator.get("fvl_copyright");

	// ignore the image sizes supplied via gallerymaker.xml
	// and use the JeffT approved dimensions
	if (fvl.thumbnailSize == undefined || fvl.previewSize == undefined)
		AOM.AMG.Log.writeError("initializeFormValueList - missing thumbnailSize or previewSize");
	var sizes = AOM.AmgGalleryMaker.imageSizes;
    fvl.largeWidth          = fvl.slideShowSize;
    fvl.largeHeight         = fvl.slideShowSize;
    fvl.mediumWidth         = fvl.galleryShowSize;
    fvl.mediumHeight        = fvl.galleryShowSize;
    fvl.thumbnailWidth      = fvl.thumbnailSize;
    fvl.thumbnailHeight     = fvl.thumbnailSize;
	
	// If dosen't check showMetadata checkbox, set captionWidthPercentView value to zero.
	var showTitleViewJournal   = AOM.AmgFlashGalleryCreator.get("fvl_showTitleViewJournal");
	if (showTitleViewJournal != undefined && 
		(showTitleViewJournal == false || showTitleViewJournal == "false")) {
		AOM.AmgFlashGalleryCreator.set("fvl_captionWidthPercentView", 0);
	} else {	
		AOM.AmgFlashGalleryCreator.set(
			"fvl_captionWidthPercentView", 
			AOM.AmgFlashGalleryCreator.get("fvl_captionWidthPercentViewDisplay")
		);
	}
}
AOM.AmgFlashGalleryCreator.get = function (id)
{
	var value = AOM.AmgGalleryMaker.get(id, AOM.AmgFlashGalleryCreator.currentDocument);
	return (value == undefined ? new String("") : value);
}

AOM.AmgFlashGalleryCreator.set = function(id, value) {
	AOM.AmgGalleryMaker.set(id, value, AOM.AmgFlashGalleryCreator.currentDocument);
}


/* Accessor to per-window (i.e. per-document) object.
 *
 * These functions are not self-initialized. They must not be invoked before
 * the corresponding per-window object being initialized else-where. */

AOM.AmgFlashGalleryCreator.formValueList = function(document)
{
    return document.aomJsFuncs.amgFlashGalleryCreatorFvl;
}
AOM.AmgFlashGalleryCreator.sizesList = function(document)
{
    return document.aomJsFuncs.amgFlashGalleryCreatorSizesList;
}
