
/*************************************************************************
*
* 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.
* 
*
**************************************************************************/


/*
	various functions that are shared between mediaGallery.jsx 
	and the assorted .jsxinc files
*/
AOM.AMG.createFolderContents = function(createfolder, subFolders, files)
{
	// creates a folder that contains subFolders and files
	// createFolder is a Folder object
	//   if it exists, all contents are removed
	//   if it does not exist, it is created
	// subFolders is an array of paths relative to createFolder
	//   the first character of each path should start with a '/'
	// files is an array of associative arrays
	//   file[x].source is the path and filename of the source file
	//   file[x].destination is the path and filename of the destination file
	
	if (createfolder instanceof Folder == false)
		throw("createFolderContents - createfolder " + AOM.AMG.localize("$$$/MediaGallery/htmlGallery/notFolder=is not a folder."));
	
	if (createfolder.exists) // remove the contents of createFolder if it exists
	{
		AOM.AMG.removeFolderContents(createfolder);
	}
	else // otherwise create it
	{
		if (!createfolder.create()) {
		    AOM.alert(AOM.AMG.localize("$$$/MediaGallery/htmlGallery/writeDeny=Target folder cannot be created."));
			throw ("createFolderContents - create() " + AOM.AMG.localize("$$$/MediaGallery/htmlGallery/failedFor=failed for ") + createfolder.fsName);
		}
	}

	// create the subFolders
	for (var i = 0; i < subFolders.length; i++)
	{
		var folder = new Folder(createfolder + subFolders[i]);
		if (!folder.create()) {
		    AOM.alert(AOM.AMG.localize("$$$/MediaGallery/htmlGallery/writeDeny=Target folder cannot be created."));
			throw("createFolderContents - Folder.create() " + AOM.AMG.localize("$$$/MediaGallery/htmlGallery/failedFor=failed for ") + createfolder + subFolders[i]);
	    }
	}
	
	// copy the files
	for (var i = 0; i < files.length; i++)
	{
		var file = new File(files[i].source);
		if (!file.exists)
			throw("createFolderContents - file.exists " + AOM.AMG.localize("$$$/MediaGallery/htmlGallery/failedFor=failed for ") + createfolder + files[i].destination);
		if (!file.copy(files[i].destination)) {
		    /* AUTORUN.inf is not allowed to be copyed by ES.
			throw("createFolderContents - file.copy() " + AOM.AMG.localize("$$$/MediaGallery/htmlGallery/failedFor=failed for ") + createfolder + files[i].destination); */
		}
	}
}
AOM.AMG.removeFolderContents = function(removeFolder)
{
	// remove all files and subdirectories of a folder
	// assumes valid, existing folder passed in
	var files = removeFolder.getFiles();
	for (var i = 0; i < files.length; i++)
	{
		var file = files[i];
		if (file instanceof Folder) {
			AOM.AMG.removeFolderContents(file);
		}
		file.remove();	
	}
}
AOM.AMG.localizeFile = function (file)
{
	// 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"))
		throw("AOM.AmgFlashGalleryCreator.fileLocalize - couldn't open file for read. (" + file + ")");
	var localizedContent = "";
	do
	{
		var line = file.readln();
		var match;
		var replacement;
		//while((match = line.match(/\"\$\$\$\/.*?\"/)) != null) // matches "$$$/..."
		if ((match = line.match(/\"\$\$\$\/.*?\"/)) != null) // matches "$$$/..."
		{
			eval("replacement = " + match); // make a string from the quote delimited match
			replacement = "\"" + AOM.AMG.localize(replacement) + "\""; // quote delimit the localized string
			line = line.replace(match, replacement);
		}
		localizedContent += line + "\n";
		
	} while(file.eof == false);
	
	file.close();
	file.encoding = "UTF8";
	if (!file.open("w", "TEXT", "????"))
		throw("AOM.AmgFlashGalleryCreator.fileSearchReplace - couldn't open file for write. (" + file + ")");
	file.write("\uFEFF");
	file.write(localizedContent);
	file.close();
}

AOM.AMG.mediaGalleryFolder = function() {return AOM.Paths.project + "/mediagallery";}

Thumbnail.prototype.amgBitmapData = function (preserveColorProfile)
{
	// return full bitmap
	// rotated if neccessary
	var b = new BitmapData(this.path, preserveColorProfile);
	if (b.amgIsValid())
	{
		if (this.rotation != 0) {
			var old = b;
			b = b.rotate(this.rotation);
			old.dispose();
		}
	}
	return b;
}
Thumbnail.prototype.amgPreview = function ()
{
	// return HQ preview
	// rotated if neccessary
	
	/* Work-around for a Bridge memory leak. Use a Thumbnail object
	 * retrieved from Document.selection to retrieve cached preview
	 * cause Bridge memory increase consistently. */
	var newThumbnail = new Thumbnail(this.uri);
	
	if (newThumbnail.core.preview.cacheData.status != "good")
	{
		newThumbnail.refresh("preview");
		return undefined;
	}

	app.synchronous = true;
	var b = newThumbnail.core.preview.preview;
	newThumbnail = null;
	
	app.synchronous = false;
	if (b.amgIsValid())
	{
		if (this.rotation != 0) {
			var old = b;
			b = b.rotate(this.rotation);
			old.dispose();
		}
	}
	return b;
}
Thumbnail.prototype.amgSkip = function (skip)
{
	/* this.amg was created in previous task. But seems Bridge may change
	 * it to undefined. Potential problem and re-created it here. */
	if (this.amg == undefined)
		this.amg = {};
	
	if (skip != undefined)
	{
		this.amg.skip = (skip == true ? true : false);
	}
		
	return this.amg.skip;
}
Thumbnail.prototype.amgIsImage = function(testBitmap)
{
	// NOTE - We may want to include tests for other known image mime types
	// otherwise they may be opened by BitmapData un-neccessarily. We may
	// also want to test for known non-image mime types and reject them before
	// they are opened by BitmapData.
	
	// is this a folder?
	if (this.container)
		return false	
	// on the known bad list?
	var badExtensions = {".mpg":true};
	var ext = this.name.substr(this.name.length-4, 4);
	if (badExtensions[ext] != undefined)
		return false;
	// if 'image' appears in the mime type return true
	if (this.mimeType.indexOf("image") != -1)
		return true;
	// at this point we need to request a bitmap but that's pretty expensive
	// so only do it if asked to...
	if (testBitmap == undefined || testBitmap != false)
	{
		var bitmapData = new BitmapData(this.path);
		if (bitmapData.amgIsValid())
		{
			bitmapData.dispose();
			return true;
		}
		return false;
	}
	else
		return true;
}
Thumbnail.prototype.amgMaximumDimension = function()
{
	var metadata = this.metadata;
	if (metadata == undefined)
		return undefined;
	metadata.namespace = "http://ns.adobe.com/exif/1.0/";
	var width = metadata.PixelXDimension;
	var height = metadata.PixelYDimension;
	var max = Math.max(width, height);
	return max > 0 ? max : undefined;
}
BitmapData.prototype.amgIsValid = function()
{
	return this.pointer == undefined ? false : true;
}
String.prototype.amgIsEmpty = function()
{
	if (this.amgTrim().length == 0)
		return true;
	return false;
}
String.prototype.amgIsValidPath = function(os)
{
	var re = AOM.AMG.badPathCharacters(os);
	return (this.match(re) == null ? true : false);
}
String.prototype.amgIsValidFile = function(os)
{
	var re = AOM.AMG.badFileCharacters(os);
	return (this.match(re) == null ? true : false);
}
String.prototype.amgTrim = function()
{
	// returns a string with leading and trailing whitespace removed
	var s = this;
	// left trim
	var re = /\s*((\S+\s*)*)/;
	s = s.replace(re, "$1");
	// right trim
	re = /((\s*\S+)*)\s*/;
	return s.replace(re, "$1");
}
AOM.AMG.badPathCharacters = function(os)
{
	// return a regex with all bad path characters
	if (os == undefined) // use the local file system
		os = File.fs;
	var re = new RegExp();
	switch(os)
	{
	case 'Windows':
		re = /[\/*?"<>|]/; // this should be /, *, ?, ", <, >, and |.
		re.toString = function () { return "/*?\"<>|"; } /**/// if you use this regex for something else and then call toString on it, allow me to apologize...
		break;
	case 'Macintosh':
		re = /:/;
		re.toString = function () { return ":"; } // see comment above...
		break;
	default:
		AOM.alert(AOM.AMG.localize("$$$/private/badPathCharactersUnknownOs=AOM.AMG.badPathCharacters - unknown os."));
		break;
	}
	return re;
}
AOM.AMG.badFileCharacters = function(os)
{
	// return a regex with all bad file characters
	if (os == undefined) // use the local file system
		os = File.fs;
	var re = new RegExp();
	switch(os)
	{
	case 'Windows':
		re = /[\/\\:*?"<>|]/; // this should be /, \, :, *, ?, ", <, >, and |.
		re.toString = function () { return "/\\:*?\"<>|"; } // see comment in badPathCharacters...
		break;
	case 'Macintosh':
		re = /:/;
		re.toString = function () { return ":"; } // see comment above...
		break;
	default:
		AOM.alert(AOM.AMG.localize("$$$/private/badFileCharactersUnknownOs=AOM.AMG.badFileCharacters - unknown os."));
		break;
	}
	return re;
}

AOM.AMG.getRandNum = function(n) {
	return Math.floor(Math.random() * n) ;
}

AOM.AMG.getRandString = function() {
	var currentDate = new Date();
	var rands = new String(currentDate.getTime());	
	for (var i = 0; i < 5; i++) {
		rands += AOM.AMG.getRandNum(10);
	}
	return rands;
}

AOM.AMG.getUserInputDataOfCustomCheckbox = function(document, control) {
	var isChecked = false;
	if (control.name != undefined) {
		var value = AOM.AMG.userInput(document).get(control.name);
		if (value != undefined) {
			switch(typeof value)
			{
			case 'boolean':
				isChecked = value;
			case 'string':
				isChecked = (value == "true" || value == "1");
				break;
			default:
				AOM.AMG.Log.writeError(control.name + " get a unknown value type :" + value);
				isChecked = true;
				break;
			}
		} 
	}
	
	return isChecked;
}
