// SimpleViewer.jsx
// Copyright 2007-2009
// Written by Jeffrey Tranberry
// Photoshop for Geeks Version 3.0

/////////////////////////////////////////////
// Simple Viewer 1.9       			   	 
// http://www.airtightinteractive.com/simpleviewer/                   
/////////////////////////////////////////////

// enable double clicking from the 
// Macintosh Finder or the Windows Explorer
#target photoshop

// Make Photoshop the frontmost application
// in case we double clicked the file
app.bringToFront();


///////////////////////////
//       SET-UP
///////////////////////////

var gVersion = 1.9;

// a global variable for the title of the dialog
// this string will also be used for the preferences file I write to disk
// Photoshop Install Directory/Presets/Image Processor/Image Processor.xml for example

var gScriptName = "SimpleViewer";

// remember the dialog modes
var saveDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.NO;

try {

	// make sure they are running Photoshop CS2
	CheckVersion();

}

// Lot's of things can go wrong, Give a generic alert and see if they want the details
catch(e) {
	if ( confirm("Sorry, something major happened and I can't continue! Would you like to see more info?" ) ) {
		alert(e);
	}
}


// Save the current preferences
	var startRulerUnits = app.preferences.rulerUnits;
	var startTypeUnits = app.preferences.typeUnits;
	var startDisplayDialogs = app.displayDialogs;

// Set Photoshop to use pixels and display no dialogs
	app.preferences.rulerUnits = Units.PIXELS;
	app.preferences.typeUnits = TypeUnits.PIXELS;
	app.displayDialogs = DialogModes.NO;
	
// Set the script location

	var scriptLocation = findScript() + "0";

// A list of file extensions to skip, keep them lower case

	gFilesToSkip = Array( "db", "xmp", "thm", "txt", "doc", "md0", "tb0", "adobebridgedb", "adobebridgedbt", "bc", "bct", "js", "html", "mov", "xml", "swf" );

// Stuff I don't know much about

	var strButtonBrowse = localize("$$$/JavaScripts/ExportLayersToFiles/Browse=Browse...");
	var strAlertSpecifyDestination = localize("$$$/JavaScripts/ExportLayersToFiles/SpecifyDestination=Please specify an output folder.");
	var strAlertDestinationNotExist = localize("$$$/JavaScripts/ExportLayersToFiles/DestionationDoesNotExist=Output folder does not exist.");
	var strAlertSpecifyInputFolder = localize("$$$/JavaScripts/ExportLayersToFiles/SpecifyInputFolder=Please specify an input folder.");
	var strAlertInputFolderNotExist = localize("$$$/JavaScripts/ExportLayersToFiles/InputFolderDoesNotExist=Input folder does not exist.");

	var exportInfo = new Object();
    
	initExportInfo(exportInfo);  
	
// define the dialog	
// [left, top, right, bottom]
function createDialog(){

	// Create an empty dialog window near the upper left of the screen
	var dlg = new Window('dialog', 'SimpleViewer');
	dlg.frameLocation = [50, 50];
	// Add a panel to hold title and 'message text' strings
	dlg.msgPn2 = dlg.add('panel', undefined, 'Input Folder');
	dlg.msgPn2.orientation = "row";
	dlg.msgPn2.alignChildren = 'Right';
	
	dlg.msgPn2.InputFolder = dlg.msgPn2.add('group');
	dlg.msgPn2.InputFolder.orientation = "row";
	dlg.msgPn2.etInputFolder = dlg.msgPn2.add("edittext", undefined, exportInfo.destination.toString());
	dlg.msgPn2.etInputFolder.preferredSize.width = 275;
	dlg.msgPn2.etInputFolder.helpTip = "Choose a folder of images to process.";

	dlg.msgPn2.btnBrowse = dlg.msgPn2.add("button", undefined, strButtonBrowse);
	dlg.msgPn2.btnBrowse.helpTip = "Choose a folder of images to process.";
	dlg.msgPn2.btnBrowse.onClick = function() {
		var defaultFolder = dlg.msgPn2.etInputFolder.text;
		var testFolder = new Folder(dlg.msgPn2.etInputFolder.text);
		if (!testFolder.exists) {
			defaultFolder = "~";
		}
		// var selFolder = Folder.selectDialog(dlg.msgPn2.etInputFolder.text, defaultFolder);
		dlg.selInputFolder = Folder.selectDialog(dlg.msgPn2.etInputFolder.text, defaultFolder);
		if ( dlg.selInputFolder != null ) {
	        dlg.msgPn2.etInputFolder.text = dlg.selInputFolder.fsName;
	    }
		//dlg.msgPn2.defaultElement.active = true;
	}

	// Add a panel to hold title and 'message text' strings
	dlg.msgPn3 = dlg.add('panel', undefined, 'Output Folder');
	dlg.msgPn3.orientation = "row";
	dlg.msgPn3.alignChildren = 'Right';
	
	dlg.msgPn3.Destination = dlg.msgPn3.add('group');
	dlg.msgPn3.Destination.orientation = "row";
	dlg.msgPn3.etDestination = dlg.msgPn3.add("edittext", undefined, exportInfo.destination.toString());
	dlg.msgPn3.etDestination.preferredSize.width = 275;
	dlg.msgPn3.etDestination.helpTip = "Choose a folder to export your webgallery to.";

	dlg.msgPn3.btnBrowse = dlg.msgPn3.add("button", undefined, strButtonBrowse);
	dlg.msgPn3.btnBrowse.helpTip = "Choose a folder to export your webgallery to.";
	dlg.msgPn3.btnBrowse.onClick = function() {
		var defaultFolder = dlg.msgPn3.etDestination.text;
		var testFolder = new Folder(dlg.msgPn3.etDestination.text);
		if (!testFolder.exists) {
			defaultFolder = "~";
		}
		dlg.selOutputFolder = Folder.selectDialog(dlg.msgPn3.etDestination.text, defaultFolder);
		if ( dlg.selOutputFolder != null ) {
	        dlg.msgPn3.etDestination.text = dlg.selOutputFolder.fsName;
	    }
		//dlg.msgPn3.defaultElement.active = true;
	}
	
	
	dlg.msgPnl = dlg.add('panel', undefined, 'SWF Options');
	dlg.msgPnl.orientation = "column";
	dlg.msgPnl.alignChildren = 'right';
	
	dlg.msgPnl.ImageSz = dlg.msgPnl.add('group');
	dlg.msgPnl.ImageSz.orientation = "row";
	dlg.msgPnl.ImageSz.st = dlg.msgPnl.ImageSz.add('statictext', undefined, 'Image Size:');
	dlg.msgPnl.ImageSz.et = dlg.msgPnl.ImageSz.add('edittext', undefined, '640');
	dlg.msgPnl.ImageSz.st = dlg.msgPnl.ImageSz.add('statictext', undefined, 'px');
	dlg.msgPnl.ImageSz.et.preferredSize = [60,20];
	dlg.msgPnl.ImageSz.helpTip = "Resizes the images to the desired dimensions for the webgallery";
	
	dlg.msgPnl.bgColor = dlg.msgPnl.add('group');
	dlg.msgPnl.bgColor.orientation = "row";
	dlg.msgPnl.bgColor.st = dlg.msgPnl.bgColor.add('statictext', undefined, 'Background Color #:');
	dlg.msgPnl.bgColor.et = dlg.msgPnl.bgColor.add('edittext', undefined, '181818');
	dlg.msgPnl.bgColor.st = dlg.msgPnl.bgColor.add('statictext', undefined, '    ');
	dlg.msgPnl.bgColor.et.preferredSize = [60,20];
	dlg.msgPnl.bgColor.helpTip = "Choose a Hex value for the background color";
	
	dlg.msgPnl.maxImageWidth = dlg.msgPnl.add('group');
	dlg.msgPnl.maxImageWidth.orientation = "row";
	dlg.msgPnl.maxImageWidth.st = dlg.msgPnl.maxImageWidth.add('statictext', undefined, 'Maximum Image Width:');
	dlg.msgPnl.maxImageWidth.et = dlg.msgPnl.maxImageWidth.add('edittext', undefined, '480');
	dlg.msgPnl.maxImageWidth.Valuest = dlg.msgPnl.maxImageWidth.add('statictext', undefined, 'px');
	dlg.msgPnl.maxImageWidth.et.preferredSize = [60,20];
	dlg.msgPnl.maxImageWidth.helpTip = "The maximum image width of preview images.";
	
	dlg.msgPnl.maxImageHeight = dlg.msgPnl.add('group');
	dlg.msgPnl.maxImageHeight.orientation = "row";
	dlg.msgPnl.maxImageHeight.st = dlg.msgPnl.maxImageHeight.add('statictext', undefined, 'Maximum Image Height:');
	dlg.msgPnl.maxImageHeight.et = dlg.msgPnl.maxImageHeight.add('edittext', undefined, '480');
	dlg.msgPnl.maxImageHeight.Valuest = dlg.msgPnl.maxImageHeight.add('statictext', undefined, 'px');
	dlg.msgPnl.maxImageHeight.et.preferredSize = [60,20];
	dlg.msgPnl.maxImageHeight.helpTip = "The maximum image height of preview images.";
	
	dlg.msgPnl.textColor = dlg.msgPnl.add('group');
	dlg.msgPnl.textColor.orientation = "row";
	dlg.msgPnl.textColor.st = dlg.msgPnl.textColor.add('statictext', undefined, 'Text Color #:');
	dlg.msgPnl.textColor.et = dlg.msgPnl.textColor.add('edittext', undefined, 'ffffff');
	dlg.msgPnl.textColor.st = dlg.msgPnl.textColor.add('statictext', undefined, '    ');
	dlg.msgPnl.textColor.et.preferredSize = [60,20];
	dlg.msgPnl.textColor.helpTip = "Choose a Hex value for the text color";
	
	dlg.msgPnl.frameColor = dlg.msgPnl.add('group');
	dlg.msgPnl.frameColor.orientation = "row";
	dlg.msgPnl.frameColor.st = dlg.msgPnl.frameColor.add('statictext', undefined, 'Frame Color #:');
	dlg.msgPnl.frameColor.et = dlg.msgPnl.frameColor.add('edittext', undefined, 'ffffff');
	dlg.msgPnl.frameColor.st = dlg.msgPnl.frameColor.add('statictext', undefined, '    ');
	dlg.msgPnl.frameColor.et.preferredSize = [60,20];
	dlg.msgPnl.frameColor.helpTip = "Choose a Hex value for the frame color";
	
	dlg.msgPnl.frameWidth = dlg.msgPnl.add('group');
	dlg.msgPnl.frameWidth.orientation = "row";
	dlg.msgPnl.frameWidth.st = dlg.msgPnl.frameWidth.add('statictext', undefined, 'Frame Width:');
	dlg.msgPnl.frameWidth.et = dlg.msgPnl.frameWidth.add('edittext', undefined, '20');
	dlg.msgPnl.frameWidth.Valuest = dlg.msgPnl.frameWidth.add('statictext', undefined, 'px');
	dlg.msgPnl.frameWidth.et.preferredSize = [60,20];
	dlg.msgPnl.frameWidth.helpTip = "How wide - in pixels - you want the frame around your images.";
	
	dlg.msgPnl.stagePadding = dlg.msgPnl.add('group');
	dlg.msgPnl.stagePadding.orientation = "row";
	dlg.msgPnl.stagePadding.st = dlg.msgPnl.stagePadding.add('statictext', undefined, 'Stage Padding:');
	dlg.msgPnl.stagePadding.et = dlg.msgPnl.stagePadding.add('edittext', undefined, '40');
	dlg.msgPnl.stagePadding.Valuest = dlg.msgPnl.stagePadding.add('statictext', undefined, 'px');
	dlg.msgPnl.stagePadding.et.preferredSize = [60,20];
	dlg.msgPnl.stagePadding.helpTip = "Width of padding - in pixels - around gallery edge. To have the image flush to the edge of the swf, set this to 0.";
	
	dlg.msgPnl.navigationPadding = dlg.msgPnl.add('group');
	dlg.msgPnl.navigationPadding.orientation = "row";
	dlg.msgPnl.navigationPadding.st = dlg.msgPnl.navigationPadding.add('statictext', undefined, 'Navigation Padding:');
	dlg.msgPnl.navigationPadding.et = dlg.msgPnl.navigationPadding.add('edittext', undefined, '40');
	dlg.msgPnl.navigationPadding.Valuest = dlg.msgPnl.navigationPadding.add('statictext', undefined, 'px');
	dlg.msgPnl.navigationPadding.et.preferredSize = [60,20];
	dlg.msgPnl.navigationPadding.helpTip = "Distance - in pixels - between image and thumbnails";
	
	dlg.msgPnl.thumbnailColumns = dlg.msgPnl.add('group');
	dlg.msgPnl.thumbnailColumns.orientation = "row";
	dlg.msgPnl.thumbnailColumns.st = dlg.msgPnl.thumbnailColumns.add('statictext', undefined, 'Thumbnail Columns:');
	dlg.msgPnl.thumbnailColumns.et = dlg.msgPnl.thumbnailColumns.add('edittext', undefined, '3');
	dlg.msgPnl.thumbnailColumns.Valuest = dlg.msgPnl.thumbnailColumns.add('statictext', undefined, '    ');
	dlg.msgPnl.thumbnailColumns.et.preferredSize = [60,20];
	dlg.msgPnl.thumbnailColumns.helpTip = "The number of columns of thumbnails in the webgallery.";
	
	dlg.msgPnl.thumbnailRows = dlg.msgPnl.add('group');
	dlg.msgPnl.thumbnailRows.orientation = "row";
	dlg.msgPnl.thumbnailRows.st = dlg.msgPnl.thumbnailRows.add('statictext', undefined, 'Thumbnail Rows:');
	dlg.msgPnl.thumbnailRows.et = dlg.msgPnl.thumbnailRows.add('edittext', undefined, '3');
	dlg.msgPnl.thumbnailRows.Valuest = dlg.msgPnl.thumbnailRows.add('statictext', undefined, '    ');
	dlg.msgPnl.thumbnailRows.et.preferredSize = [60,20];
	dlg.msgPnl.thumbnailRows.helpTip = "The number of rows of thumbnails in the webgallery.";
	
	

	
	
	dlg.msgPnl.navPosition = dlg.msgPnl.add('group');
	dlg.msgPnl.navPosition.orientation = "row";
	dlg.msgPnl.navPosition.st = dlg.msgPnl.navPosition.add('statictext', undefined, 'Thumbnail Nav Position:');
	dlg.msgPnl.navPosition = dlg.msgPnl.navPosition.add('dropdownlist');
	dlg.msgPnl.navPosition.helpTip = "Choose how you want to align the thumbnails in relation to the preview image.";
	// dlg.msgPnl.navPosition.preferredSize.width = StrToIntWithDefault( DDFileType=100, 100 );
    //dlg.msgPnl.navPosition.alignment = 'left';
	
	// the drop down list indexes for position type
	var leftIndex = 0; 
	var rightIndex = 1;
	var topIndex = 2;
	var bottomIndex = 3;

    dlg.msgPnl.navPosition.add("item", "left");
    dlg.msgPnl.navPosition.add("item", "right");
    dlg.msgPnl.navPosition.add("item", "top");
	dlg.msgPnl.navPosition.add("item", "bottom");
	
	dlg.msgPnl.navPosition.items[0].selected = true;
	
	dlg.msgPnl.navPosition.text = dlg.msgPnl.navPosition.items[0];
	
	dlg.msgPnl.navPosition.onChange = function() {
		// hideAllFileTypePanel();
		switch(this.selection.index) {
			case bottomIndex:	
				dlg.msgPnl.navPosition.text = dlg.msgPnl.navPosition.items[3];
				break;
			case topIndex:	
				dlg.msgPnl.navPosition.text = dlg.msgPnl.navPosition.items[2];
				break;
			case rightIndex:	
				dlg.msgPnl.navPosition.text = dlg.msgPnl.navPosition.items[1];
				break;
			case leftIndex:	
			default:		
				dlg.msgPnl.navPosition.text = dlg.msgPnl.navPosition.items[0];
				break;
				}
		}


	dlg.msgPnl.vAlign = dlg.msgPnl.add('group');
	dlg.msgPnl.vAlign.orientation = "row";
	dlg.msgPnl.vAlign.st = dlg.msgPnl.vAlign.add('statictext', undefined, 'Vertical Placment:');
	dlg.msgPnl.vAlign = dlg.msgPnl.vAlign.add('dropdownlist');
	dlg.msgPnl.vAlign.helpTip = "Vertical placment of the image and thumbnails within the SWF. Can be 'center', 'top' or 'bottom'.  For large format galleries this is best set to 'center'. For small format galleries setting this to 'top' or 'bottom' can help get the image flush to the edge of the swf.";
	// dlg.msgPnl.navPosition.preferredSize.width = StrToIntWithDefault( DDFileType=100, 100 );
    //dlg.msgPnl.navPosition.alignment = 'left';
	
	// the drop down list indexes for position type
	var vcenterIndex = 0; 
	var vtopIndex = 1;
	var vbottomIndex = 2;

    dlg.msgPnl.vAlign.add("item", "center");
    dlg.msgPnl.vAlign.add("item", "top");
	dlg.msgPnl.vAlign.add("item", "bottom");
	
	dlg.msgPnl.vAlign.items[0].selected = true;
	
	dlg.msgPnl.vAlign.text = dlg.msgPnl.vAlign.items[0];
	
	dlg.msgPnl.vAlign.onChange = function() {
		// hideAllFileTypePanel();
		switch(this.selection.index) {
			case vbottomIndex:	
				dlg.msgPnl.vAlign.text = dlg.msgPnl.vAlign.items[2];
				break;
			case vtopIndex:	
				dlg.msgPnl.vAlign.text = dlg.msgPnl.vAlign.items[1];
				break;
			case vcenterIndex:	
			default:		
				dlg.msgPnl.vAlign.text = dlg.msgPnl.vAlign.items[0];
				break;
				}
		}
	
	
	
	dlg.msgPnl.hAlign = dlg.msgPnl.add('group');
	dlg.msgPnl.hAlign.orientation = "row";
	dlg.msgPnl.hAlign.st = dlg.msgPnl.hAlign.add('statictext', undefined, 'Horizontal Placment:');
	dlg.msgPnl.hAlign = dlg.msgPnl.hAlign.add('dropdownlist');
	dlg.msgPnl.hAlign.helpTip = "Horizontal placment of the image and thumbnails within the SWF. Can be 'center', 'top' or 'bottom'.  For large format galleries this is best set to 'center'. For small format galleries setting this to 'top' or 'bottom' can help get the image flush to the edge of the swf.";
	// dlg.msgPnl.navPosition.preferredSize.width = StrToIntWithDefault( DDFileType=100, 100 );
    //dlg.msgPnl.navPosition.alignment = 'left';
	
	// the drop down list indexes for position type
	var hcenterIndex = 0; 
	var htopIndex = 1;
	var hbottomIndex = 2;

    dlg.msgPnl.hAlign.add("item", "center");
    dlg.msgPnl.hAlign.add("item", "top");
	dlg.msgPnl.hAlign.add("item", "bottom");
	
	dlg.msgPnl.hAlign.items[0].selected = true;
	
	dlg.msgPnl.hAlign.text = dlg.msgPnl.hAlign.items[0];
	
	dlg.msgPnl.hAlign.onChange = function() {
		// hideAllFileTypePanel();
		switch(this.selection.index) {
			case hbottomIndex:	
				dlg.msgPnl.hAlign.text = dlg.msgPnl.hAlign.items[2];
				break;
			case htopIndex:	
				dlg.msgPnl.hAlign.text = dlg.msgPnl.hAlign.items[1];
				break;
			case hcenterIndex:	
			default:		
				dlg.msgPnl.hAlign.text = dlg.msgPnl.hAlign.items[0];
				break;
				}
		}
	
	
	dlg.msgPnl.title = dlg.msgPnl.add('group');
	dlg.msgPnl.title.orientation = "row";
	dlg.msgPnl.title.st = dlg.msgPnl.title.add('statictext', undefined, 'Gallery Title:');
	dlg.msgPnl.title.et = dlg.msgPnl.title.add('edittext', undefined, 'SimpleViewer Title');
	dlg.msgPnl.title.st = dlg.msgPnl.title.add('statictext', undefined, '    ');
	dlg.msgPnl.title.et.preferredSize = [175,20];
	dlg.msgPnl.title.helpTip = "Enter a Gallery Title.";
	
	/*dlg.msgPnl.enableRightClickOpen = dlg.msgPnl.add('group');
	dlg.msgPnl.enableRightClickOpen.orientation = "row";
	dlg.msgPnl.enableRightClickOpen.st = dlg.msgPnl.enableRightClickOpen.add('statictext', undefined, 'Enable Right-Click:');
	dlg.msgPnl.enableRightClickOpen.et = dlg.msgPnl.enableRightClickOpen.add('edittext', undefined, 'true');
	dlg.msgPnl.enableRightClickOpen.st = dlg.msgPnl.enableRightClickOpen.add('statictext', undefined, '    ');
	dlg.msgPnl.enableRightClickOpen.et.preferredSize = [60,20];
	dlg.msgPnl.enableRightClickOpen.helpTip = "Enter a Gallery Title.";*/
	
	dlg.msgPnl.enableRightClickOpen = dlg.msgPnl.add('group');
	dlg.msgPnl.enableRightClickOpen.orientation = "row";
	dlg.msgPnl.enableRightClickOpen.st = dlg.msgPnl.enableRightClickOpen.add('checkbox', undefined, 'Enable Right-Click');
	//dlg.msgPnl.enableRightClickOpen.et = dlg.msgPnl.enableRightClickOpen.add('edittext', undefined, 'true');
	//dlg.msgPnl.enableRightClickOpen.st = dlg.msgPnl.enableRightClickOpen.add('statictext', undefined, '    ');
	//dlg.msgPnl.enableRightClickOpen.et.preferredSize = [60,20];
	dlg.msgPnl.enableRightClickOpen.helpTip = "Enable right-click to allow image download.";
	
	
	// Add a panel with buttons to test parameters and
	//dlg.buttonPanel = dlg.add('panel', undefined);
	//dlg.buttonPanel.orientation = "row";
	//dlg.msgPnl = dlg.add('row');
	//dlg.msgPnl.orientation = "row";
	//dlg.buttonPanel.cancelBtn = dlg.buttonPanel.add('button', undefined, '  Cancel   ', {name:'cancel'});
	//dlg.buttonPanel.testBtn = dlg.buttonPanel.add('button', undefined, '   Build Photo Gallery   ');
	dlg.msgPnl.buttons = dlg.msgPnl.add('group');
	dlg.msgPnl.buttons.orientation = "row";
	dlg.msgPnl.buttons.cancelBtn = dlg.msgPnl.buttons.add ('button', undefined,'Cancel');
	dlg.msgPnl.buttons.runBtn = dlg.msgPnl.buttons.add ('button', undefined,'Build Web Gallery');

	return dlg;
	}

	var params = new Array();
	params['InputFolder'] = "";
	params['OutputFolder'] = "";
	params['ImageSize'] = "";
	params['BackgroundColor'] = "";
	params['MaximumImageWidth'] = "";
	params['MaximumImageHeight'] = "";
	params['TextColor'] = "";
	params['FrameColor'] = "";
	params['FrameWidth'] = "";
	params['StagePadding'] = "";
	params['NavigationPadding'] = "";
	params['NumberofColumns'] = "";
	params['NumberofRows'] = "";
	params['NumberofRows'] = "";
	params['NavPosition'] = "";
	params['vAlign'] = "";
	params['hAlign'] = "";
	params['GalleryTitle'] = "";
	params['RightClick'] = "";
	
	LoadParamsFromDisk( GetDefaultParamsFile(), params );

	function initializeDialog (SimpleViewer){
	with(SimpleViewer) {
		
	msgPn2.etInputFolder.value = params['InputFolder'];
	msgPn3.etDestination.value = params['OutputFolder'];
	msgPnl.ImageSz.et.value = params['ImageSize'];
	msgPnl.bgColor.et.value = params['BackgroundColor'];
	msgPnl.maxImageWidth.et.value = params['MaximumImageWidth'];
	msgPnl.maxImageHeight.et.value = params['MaximumImageHeight'];
	msgPnl.textColor.et.value = params['TextColor'];
	msgPnl.frameColor.et.value = params['FrameColor'];
	msgPnl.frameWidth.et.value = params['FrameWidth'];
	msgPnl.stagePadding.et.value = params['StagePadding'];
	msgPnl.navigationPadding.et.value = params['NavigationPadding'];
	msgPnl.thumbnailColumns.et.value = params['NumberofColumns'];
	msgPnl.thumbnailRows.et.value = params['NumberofRows'];
	msgPnl.navPosition.value = params['NavPosition'];
	msgPnl.vAlign.value = params['VerticalPosition'];
	msgPnl.hAlign.value = params['HorizontalPosition'];
	msgPnl.title.et.value = params['GalleryTitle'];
	//msgPnl.enableRightClickOpen.et.value = params['RightClick'];
	
	// Run the web photo gallery
	// checking for valid settings
	msgPnl.buttons.runBtn.onClick = function() {
	
	// check if the input folder setting is proper
			var inptfld = SimpleViewer.msgPn2.etInputFolder.text;
			if (inptfld.length == 0) {
				alert(strAlertSpecifyInputFolder);
				return;
			}
			var testFolder = new Folder(inptfld);
			if (!testFolder.exists) {
				alert(strAlertInputFolderNotExist);
				return;
			}
			
			// check if the output folder setting is proper
			var destination = SimpleViewer.msgPn3.etDestination.text;
			if (destination.length == 0) {
				alert(strAlertSpecifyDestination);
				return;
			}
			var testFolder = new Folder(destination);
			if (!testFolder.exists) {
				alert(strAlertDestinationNotExist);
				return;
			}
			
			// See if the input folder and the output folder are the same
			if (SimpleViewer.msgPn3.etDestination.text == SimpleViewer.msgPn2.etInputFolder.text) {
				var result = confirm("Are you sure you want your output folder to be the same as your input folder");
				if (result) {
				} else {
					return;
				}
    		}
			
			// check to see if the image size is setting is proper
			var imageSizeStr = isNaN(SimpleViewer.msgPnl.ImageSz.et.text);
			if (imageSizeStr == true) {
        		alert("Please enter a valid number 300-1600 for 'Image Size'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.ImageSz.et.text >= 300 && SimpleViewer.msgPnl.ImageSz.et.text <= 1600)) {
				alert("You must enter a number between 300-1600 for 'Image Size'");
				return;
    		}
    		
    		// check to see if the maxImageWidth is setting is proper
			var imageSpaceStr = isNaN(SimpleViewer.msgPnl.maxImageWidth.et.text);
			if (imageSpaceStr == true) {
        		alert("Please enter a valid number 300-5000 for 'Maximum Image Width'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.maxImageWidth.et.text >= 300 && SimpleViewer.msgPnl.maxImageWidth.et.text <= 5000)) {
				alert("You must enter a number between 300-5000 for 'Maximum Image Width'");
				return;
    		}
 
     		// check to see if the maxImageHeight is setting is proper
			var imageSpaceStr = isNaN(SimpleViewer.msgPnl.maxImageHeight.et.text);
			if (imageSpaceStr == true) {
        		alert("Please enter a valid number 300-5000 for 'Maximum Image Height'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.maxImageHeight.et.text >= 300 && SimpleViewer.msgPnl.maxImageWidth.et.text <= 5000)) {
				alert("You must enter a number between 300-5000 for 'Maximum Image Height'");
				return;
    		}
		
    		// check to see if the Number of Image Columns setting is proper
			var columnsStr = isNaN(SimpleViewer.msgPnl.thumbnailColumns.et.text);
			if (columnsStr == true) {
        		alert("Please enter a valid number 1-12 for 'Number of thumbnail columns'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.thumbnailColumns.et.text >= 1 && SimpleViewer.msgPnl.thumbnailColumns.et.text <= 12)) {
				alert("You must enter a number between 1-12 for 'Number of thumbnail columns'");
				return;
    		}
		
		    // check to see if the Number of Image Rows setting is proper
			var rowStr = isNaN(SimpleViewer.msgPnl.thumbnailRows.et.text);
			if (rowStr == true) {
        		alert("Please enter a valid number 1-12 for 'Number of Thumbnail rows'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.thumbnailRows.et.text >= 1 && SimpleViewer.msgPnl.thumbnailRows.et.text <= 12)) {
				alert("You must enter a number between 1-12 for 'Number of thumbnail rows'");
				return;
    		}
    		
    		// check to see if the Frame Width is proper
			var frameWidthStr = isNaN(SimpleViewer.msgPnl.frameWidth.et.text);
			if (frameWidthStr == true) {
        		alert("Please enter a valid number 1-300 for 'Frame Width'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.frameWidth.et.text >= 0 && SimpleViewer.msgPnl.frameWidth.et.text <= 300)) {
				alert("You must enter a number between 1-300 for 'Frame Width'");
				return;
    		}
		
		    // check to see if the Stage Padding is proper
			var stagePaddingStr = isNaN(SimpleViewer.msgPnl.stagePadding.et.text);
			if (stagePaddingStr == true) {
        		alert("Please enter a valid number 1-300 for 'Stage Padding'");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.stagePadding.et.text >= 0 && SimpleViewer.msgPnl.stagePadding.et.text <= 300)) {
				alert("You must enter a number between 1-300 for 'Stage Padding'");
				return;
    		}
		
			// check to see if the Navigation Padding is proper
			var navigationPaddingStr = isNaN(SimpleViewer.msgPnl.navigationPadding.et.text);
			if (navigationPaddingStr == true) {
        		alert("Please enter a valid number 1-300 for 'Navigation Padding");
        		return;
        	}
    		if (!(SimpleViewer.msgPnl.navigationPadding.et.text >= 0 && SimpleViewer.msgPnl.navigationPadding.et.text <= 300)) {
				alert("You must enter a number between 1-300 for 'Navigation Width'");
				return;
    		}
    		
	close( 1 );
	}
	msgPnl.buttons.cancelBtn.onClick = function() { close( 2 ); }
	}
	}

	function runDialog(SimpleViewer){
		
	// Warn the user if they have an open document and exit the script with return
	if (documents.length > 0){
		alert ("This script requires that there are no open documents to run.");
	return;
	}		
		
	return SimpleViewer.show()
	}
		
	var SimpleViewer = createDialog()	
	initializeDialog(SimpleViewer)
	
	
	
	
//=====================Start=====================================================

	if (runDialog(SimpleViewer) == 1){
	// transfer values from the dialog to my internal params
	params['InputFolder'] = SimpleViewer.msgPn2.etInputFolder.value;
	params['OutputFolder'] = SimpleViewer.msgPn3.etDestination.value;
	params['ImageSize'] = SimpleViewer.msgPnl.ImageSz.et.value;
	params['BackgroundColor'] = SimpleViewer.msgPnl.bgColor.et.value;
	params['MaximumImageWidth'] = SimpleViewer.msgPnl.maxImageWidth.et.value;
	params['MaximumImageHeight'] = SimpleViewer.msgPnl.maxImageHeight.et.value;	
	params['TextColor'] = SimpleViewer.msgPnl.textColor.et.value;
	params['FrameColor'] = SimpleViewer.msgPnl.frameColor.et.value;
	params['FrameWidth'] = SimpleViewer.msgPnl.frameWidth.et.value;
	params['StagePadding'] = SimpleViewer.msgPnl.stagePadding.et.value;
	params['NavigationPadding'] = SimpleViewer.msgPnl.navigationPadding.et.value;
	params['NumberofColumns'] = SimpleViewer.msgPnl.thumbnailColumns.et.value;
	params['NumberofRows'] = SimpleViewer.msgPnl.thumbnailRows.et.value;
	params['NavPosition'] = SimpleViewer.msgPnl.navPosition.value;
	params['VerticalPosition'] = SimpleViewer.msgPnl.vAlign.value;
	params['HorizontalPosition'] = SimpleViewer.msgPnl.hAlign.value;
	params['GalleryTitle'] = SimpleViewer.msgPnl.title.et.value;
	//params['RightClick'] = SimpleViewer.msgPnl.enableRightClickOpen.et.value;

	
	// Save the params from the above
	SaveParamsToDisk( GetDefaultParamsFile(), params );
	
	// Gets the output folder from the UI
			var inputFolder = SimpleViewer.msgPn2.etInputFolder.text;
			//alert(inputFolder);
			
			// Gets the output folder from the UI
			var outputFolder = SimpleViewer.msgPn3.etDestination.text;
			//alert(outputFolder);
			
			// Gets the Image Size from the UI
			var imageSize = SimpleViewer.msgPnl.ImageSz.et.text;
			//alert(imageSize);
			
			// Determine line feed and then save out text files.  Note that "Desktop" is localized
			// on Win, when so we don't reference the desktop if it can not be found.
			
				if (File.fs == "Windows") {
					fileLineFeed = "windows";
					var desktopFolder = Folder("~/" + outputFolder);
					if (desktopFolder.exists != 1) {
						var ImageFileFolder = new Folder(outputFolder + "/images");
						var ThumbsFileFolder = new Folder(outputFolder + "/thumbs");
					} else {
						var ImageFileFolder = new Folder("~/" + outputFolder + "/images");
						var ThumbsFileFolder = new Folder("~/" + outputFolder + "/thumbs");
					}
				} else {
					fileLineFeed = "macintosh";
					var ImageFileFolder = new Folder(outputFolder + "/images");
					var ThumbsFileFolder = new Folder(outputFolder + "/thumbs");
				}
				ImageFileFolder.create();
				ThumbsFileFolder.create();
				
			// Generate HTML File    
    
			var HTMLFilePath = outputFolder + "/" + "index.html";
			var HTMLFile = File(HTMLFilePath);
			HTMLFile.remove();
			var HTMLFilePath = new File(outputFolder + "/" + "index.html");
    
			// Generate XML File 
    
    		var XMLFilePath = outputFolder + "/" + "gallery.xml";
			var XMLFile = File(XMLFilePath);
			XMLFile.remove();
			var XMLFilePath = new File(outputFolder + "/" + "gallery.xml");
    
			// Copy SWF File from the Presets/Scripts folder to the specified output folder 
  
			var SWFFilePath = scriptLocation.slice(0,-17) + "viewer.swf";
			var SWFFile = File(SWFFilePath);
			SWFFile.copy(outputFolder + "/viewer.swf");
    
			// Copy .js File from the Presets/Scripts folder to the specified output folder 
  
			var JSFilePath = scriptLocation.slice(0,-17) + "~swfobject.js";
			var JSFile = File(JSFilePath);
			JSFile.copy(outputFolder + "/swfobject.js");
			
			// Copy ReadMe File from the Presets/Scripts folder to the specified output folder 
  
			var JSFilePath = scriptLocation.slice(0,-17) + "readme.html";
			var JSFile = File(JSFilePath);
			JSFile.copy(outputFolder + "/readme.html");

			// Write out XML Header to the file created in the set-up
			
			//alert(SimpleViewer.msgPnl.enableRightClickOpen.st.value);
			//alert(SimpleViewer.msgPnl.navPosition.text);
			var navPos = SimpleViewer.msgPnl.navPosition.text.toString();
			var vAlignPos = SimpleViewer.msgPnl.vAlign.text.toString();
			var hAlignPos = SimpleViewer.msgPnl.hAlign.text.toString();
			//alert(navPos);
			//alert(SimpleViewer.msgPnl.frameColor.et.text);

			writeXMLHeader(XMLFile, SimpleViewer.msgPnl.maxImageWidth.et.text, SimpleViewer.msgPnl.maxImageHeight.et.text, SimpleViewer.msgPnl.textColor.et.text, SimpleViewer.msgPnl.frameColor.et.text, SimpleViewer.msgPnl.frameWidth.et.text, SimpleViewer.msgPnl.stagePadding.et.text, SimpleViewer.msgPnl.navigationPadding.et.text, SimpleViewer.msgPnl.thumbnailColumns.et.text, SimpleViewer.msgPnl.thumbnailRows.et.text, navPos, vAlignPos, hAlignPos, SimpleViewer.msgPnl.title.et.text, SimpleViewer.msgPnl.enableRightClickOpen.st.value);
			
			// Open and process a folder of Images
			
			OpenFolder(SimpleViewer.selInputFolder, SimpleViewer.selOutputFolder, XMLFile, imageSize);
			
			// Write out XML Footer to the file created in the set-up
	
			writeXMLFooter(XMLFile);
			
			// Write out all the HTML to the file created in the set-up
	
			writeHTMLDoc(HTMLFile, SimpleViewer.msgPnl.bgColor.et.text);
			
			// launch the web gallery in a browser
			
			File(outputFolder + "/index.html").execute();

	// Return the app preferences
	app.preferences.rulerUnits = startRulerUnits;
	app.preferences.typeUnits = startTypeUnits;
	app.displayDialogs = saveDialogMode;
	
	
	

} // the end






///////////////////////
// Helper Functions 
///////////////////////


///////////////////////////////////////////////////////////////////////////////
// Function: initExportInfo
// Usage: create our default parameters
// Input: a new Object
// Return: a new object with params set to default
///////////////////////////////////////////////////////////////////////////////
function initExportInfo(exportInfo) {
    exportInfo.destination = new String("");
    exportInfo.fileNamePrefix = new String("untitled_");
    exportInfo.visibleOnly = false;
//    exportInfo.fileType = psdIndex;
    exportInfo.icc = true;
    exportInfo.jpegQuality = 8;
    exportInfo.psdMaxComp = true;
    exportInfo.tiffCompression = TIFFEncoding.NONE;
    exportInfo.tiffJpegQuality = 8;
    exportInfo.pdfEncoding = PDFEncoding.JPEG;
    exportInfo.pdfJpegQuality = 8;
    exportInfo.targaDepth = TargaBitsPerPixels.TWENTYFOUR;
    exportInfo.bmpDepth = BMPDepthType.TWENTYFOUR;

    try {
        exportInfo.destination = Folder(app.activeDocument.fullName.parent).fsName; // destination folder
        var tmp = app.activeDocument.fullName.name;
        exportInfo.fileNamePrefix = decodeURI(tmp.substring(0, tmp.indexOf("."))); // filename body part
    } catch(someError) {
        exportInfo.destination = new String("");
//        exportInfo.fileNamePrefix = app.activeDocument.name; // filename body part
    }
}
    
// Find the location where this script resides

function findScript() {
	var where = "";
	try {
		FORCEERROR = FORCERRROR;
	}
	catch(err) {
		// alert(err.fileName);
		// alert(File(err.fileName).exists);
		where = File(err.fileName);
	}
	return where;
}

////////////////////////////
// File Writing Functions 
////////////////////////////

// Write out image name XML

    function writeXMLDocRef() {
        writeXML(
"<image>" + "\n" +
"	<filename>" + app.activeDocument.name + "</filename>" + "\n" +
"	<caption>" + app.activeDocument.name + "</caption>" + "\n" +
"</image>"  + "\n");
    }

// Write out XML header

    function writeXMLHeader(fileType, maxImageWidth, maxImageHeight, textColor, frameColor, frameWidth, stagePadding, navigationPadding, thumbnailColumns, thumbnailRows, navPosition, vAlign, hAlign, title, enableRightClickOpen) {
		//alert(navPosition);
		XMLFile = fileType;
		writeXML(
'<?xml version="1.0" encoding="UTF-8"?>' + "\n" + 
'<simpleviewerGallery maxImageWidth="' + maxImageWidth + '" maxImageHeight="' + maxImageHeight + '" textColor="0x' + textColor + '" frameColor="0x'+ frameColor +'" frameWidth="' + frameWidth + '" stagePadding="' + stagePadding + '" navPadding="' + navigationPadding + '" thumbnailColumns="' + thumbnailColumns + '" thumbnailRows="' + thumbnailRows + '" navPosition="' + navPosition+ '" vAlign="' + vAlign  +'" hAlign="' + hAlign + '" title="' + title + '" enableRightClickOpen="' + enableRightClickOpen+ '" backgroundImagePath="" imagePath="" thumbPath="">'  + "\n");
    }
    
// Write out XML footer

    function writeXMLFooter(fileType) {
    	XMLFile = fileType;
		writeXML("</simpleviewerGallery>");
    }

// Write XML file

    function writeXML(log) {
        try {
            if(XMLFile.exists) {
                XMLFile.open ("e");
                XMLFile.seek (0,2);      // Move to EOF
            } else {
            XMLFile.open ("w");          // Add unicode marker if we change to XML file format for this log file
        }
        XMLFile.encoding = "UTF8"; // set UTF8
        XMLFile.write(log);
        XMLFile.close();
        } catch (e) {
            alert(e);
        } finally {
        }
        return;
    }
    
// Write index HTML file

    function writeHTML(log) {
        try {
            if(HTMLFile.exists) {
                HTMLFile.open ("e");
                HTMLFile.seek (0,2);      // Move to EOF
            } else {
            HTMLFile.open ("w");          // Add unicode marker if we change to XML file format for this log file
        }
        HTMLFile.encoding = "UTF8"; // set UTF8
        HTMLFile.write(log);
        HTMLFile.close();
        } catch (e) {
            alert(e);
        } finally {
        }
        return;
    }
    
/*/ Write upgrade HTML file

    function writeUGHTML(log) {
        try {
            if(UGHTMLFile.exists) {
                UGHTMLFile.open ("e");
                UGHTMLFile.seek (0,2);      // Move to EOF
            } else {
            UGHTMLFile.open ("w");          // Add unicode marker if we change to XML file format for this log file
        }
        UGHTMLFile.encoding = "UTF8"; // set UTF8
        UGHTMLFile.write(log);
        UGHTMLFile.close();
        } catch (e) {
            alert(e);
        } finally {
        }
        return;
    }
*/

// Function for returning current date and time

    function getDateTime() {
        var date = new Date();
        var dateTime = "";
        if ((date.getMonth() + 1) < 10) {
            dateTime += "0" + (date.getMonth() + 1) + "/";
        } else {
            dateTime += (date.getMonth() + 1) + "/";
        }
        if (date.getDate() < 10) {
            dateTime += "0" + date.getDate() + "/";
        } else {
            dateTime += date.getDate() + "/";
        }
        dateTime += date.getFullYear() + ", ";
        if (date.getHours() < 10) {
            dateTime += "0" + date.getHours() + ":";
        } else {
            dateTime += date.getHours() + ":";
        }
        if (date.getMinutes() < 10) {
            dateTime += "0" + date.getMinutes() + ":";
        } else {
            dateTime += date.getMinutes() + ":";
        }
        if (date.getSeconds() < 10) {
            dateTime += "0" + date.getSeconds();
        } else {
            dateTime += date.getSeconds();
        }
        return dateTime;
    }
    
// resetPrefs function for resetting the preferences

	function resetPrefs() {
		preferences.rulerUnits = startRulerUnits;
		preferences.typeUnits = startTypeUnits;
		displayDialogs = startDisplayDialogs;
	}
    
////////////////////////////////////
// File Opening/Closing Functions
////////////////////////////////////
    
// Given the a Folder of files, open them

function OpenFolder(inputFolder, outputFolder, fileType, imageSize) {
        var filesOpened = 0;
        //alert(inputFolder);
        //alert(outputFolder);
        var fileList = inputFolder.getFiles();
        for ( var i = 0; i < fileList.length; i++ ) {
        		   // Make sure all the files in the folder are compatible with PS
                if ( fileList[i] instanceof File && ! fileList[i].hidden && ! IsFileOneOfThese( fileList[i], gFilesToSkip )) {
                        open( fileList[i] );
                        filesOpened++;
                        var docRef = activeDocument;

					if (!(docRef.height * 1 < imageSize * 1 || docRef.width * 1 < imageSize * 1)){
						//alert(docRef.height * 1 + imageSize * 1);
						//alert(docRef.width + imageSize);
						if (docRef.height > docRef.width)
							{
							resizePortrait(imageSize);
							}
						else
							{
							resizeLandscape(imageSize);
							}	
					}
						
					resolveColorModes();
						
					app.activeDocument.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC);
					
					app.activeDocument.flatten();
					
					saveJPG(outputFolder + "/images/");
					
					writeXMLDocRef(fileType);
					
		
						if (docRef.height > docRef.width)
							{
							resizePortrait(100);
							}
						else
							{
							resizeLandscape(100);
							}


					saveJPG(outputFolder + "/thumbs/");
					

                 fileClose(SaveOptions.DONOTSAVECHANGES);

                }
        }
        return filesOpened;
}


// given a file name and a list of extensions
// determine if this file is in the list of extensions

function IsFileOneOfThese( inFileName, inArrayOfFileExtensions ) {
	var lastDot = inFileName.toString().lastIndexOf( "." );
	if ( lastDot == -1 ) {
		return false;
	}
	var strLength = inFileName.toString().length;
	var extension = inFileName.toString().substr( lastDot + 1, strLength - lastDot );
	extension = extension.toLowerCase();
	for (var i = 0; i < inArrayOfFileExtensions.length; i++ ) {
		if ( extension == inArrayOfFileExtensions[i] ) {
			return true;
		}
	}
	return false;
}


// fileClose function for closing current document

function fileClose(options) {
	
		app.activeDocument.close(options);
}

////////////////////////////////
// Image Processing Functions 
////////////////////////////////

// resize landscape

function resizeLandscape(imageSize) {
//alert(imageSize);
var id3 = charIDToTypeID( "ImgS" );
    var desc2 = new ActionDescriptor();
    var id4 = charIDToTypeID( "Wdth" );
    var id5 = charIDToTypeID( "#Pxl" );
    desc2.putUnitDouble( id4, id5, imageSize );
    var id6 = charIDToTypeID( "Rslt" );
    var id7 = charIDToTypeID( "#Rsl" );
    desc2.putUnitDouble( id6, id7, 72.000000 );
    var id8 = stringIDToTypeID( "scaleStyles" );
    desc2.putBoolean( id8, true );
    var id9 = charIDToTypeID( "CnsP" );
    desc2.putBoolean( id9, true );
    var id10 = charIDToTypeID( "Intr" );
    var id11 = charIDToTypeID( "Intp" );
    var id12 = charIDToTypeID( "Bcbc" );
    desc2.putEnumerated( id10, id11, id12 );
executeAction( id3, desc2, DialogModes.NO );
}

// resize Portrait

function resizePortrait(imageSize) {
//alert(imageSize);
var id15 = charIDToTypeID( "ImgS" );
    var desc4 = new ActionDescriptor();
    var id16 = charIDToTypeID( "Hght" );
    var id17 = charIDToTypeID( "#Pxl" );
    desc4.putUnitDouble( id16, id17, imageSize );
    var id18 = charIDToTypeID( "Rslt" );
    var id19 = charIDToTypeID( "#Rsl" );
    desc4.putUnitDouble( id18, id19, 72.000000 );
    var id20 = stringIDToTypeID( "scaleStyles" );
    desc4.putBoolean( id20, true );
    var id21 = charIDToTypeID( "CnsP" );
    desc4.putBoolean( id21, true );
    var id22 = charIDToTypeID( "Intr" );
    var id23 = charIDToTypeID( "Intp" );
    var id24 = charIDToTypeID( "Bcbc" );
    desc4.putEnumerated( id22, id23, id24 );
executeAction( id15, desc4, DialogModes.NO );
}

// Save JPG

function saveJPG(filePath){
var jpegOptions = new JPEGSaveOptions();
jpegOptions.quality = 10;
jpegOptions.embedColorProfile = false;
app.activeDocument.saveAs( File( filePath), jpegOptions, false);
}

function resolveColorModes(){
	// Remove all alpha channels
	app.activeDocument.channels.removeAll();

	if(app.activeDocument.bitsPerChannel == BitsPerChannelType.SIXTEEN || app.activeDocument.bitsPerChannel == BitsPerChannelType.THIRTYTWO) {

		app.activeDocument.bitsPerChannel = BitsPerChannelType.EIGHT;
		
		}
	if(app.activeDocument.mode == DocumentMode.BITMAP) { 
	
	app.activeDocument.changeMode(ChangeMode.GRAYSCALE);
	app.activeDocument.changeMode(ChangeMode.RGB); 
	
	} else if (app.activeDocument.mode == DocumentMode.CMYK){ 
	app.activeDocument.changeMode(ChangeMode.RGB); 
	} else if (app.activeDocument.mode == DocumentMode.INDEXEDCOLOR){ 
	app.activeDocument.changeMode(ChangeMode.RGB); 
	}
}

///////////////////////////////
// Document Set-up Functions
///////////////////////////////

// Write out HTML File

    function writeHTMLDoc(fileType, bgColorStr) {
        HTMLFile = fileType;
        writeHTML(
'<!-- saved from url=(0014)about:internet -->' + '\n' +
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
'<head>' + '\n' +
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' + '\n' +
'<title>SimpleViewer</title>' + '\n' +
'<!-- Download SimpleViewer at www.airtightinteractive.com/simpleviewer -->' + '\n' +
'<script type="text/javascript" src="swfobject.js"></script>' + '\n' +
'<style type="text/css">' + '\n' +
'	/* hide from ie on mac \\*/' + '\n' +
'	html {' + '\n' +
'		height: 100%;' + '\n' +
'		overflow: hidden;' + '\n' +
'	}' + '\n' + '\n' +
'	#flashcontent {' + '\n' +
'		height: 100%;' + '\n' +
'	}' + '\n' +
'	/* end hide */' + '\n' + '\n' +
'	body {' + '\n' +
'		height: 100%;' + '\n' +
'		margin: 0;' + '\n' +
'		padding: 0;' + '\n' +
'		background-color: #' + bgColorStr + ';' + '\n' +
'		color:#ffffff;' + '\n' +
'		font-family:sans-serif;' + '\n' +
'		font-size:20;' + '\n' +
'	}' + '\n' + '\n' +	
'	a {	' + '\n' +
'		color:#cccccc;' + '\n' +
'	}' + '\n' +
'</style>' + '\n' +
'</head>' + '\n' +
'<body>' + '\n' +
'	<div id="flashcontent">SimpleViewer requires JavaScript and the Flash Player. <a href="http://www.macromedia.com/go/getflashplayer/">Get Flash.</a></div>' + '\n' +	
'	<script type="text/javascript">' + '\n' + '\n' +
'		var fo = new SWFObject("viewer.swf", "viewer", "100%", "100%", "8", "#' + bgColorStr + '");' + '\n' + '\n' +
'		// SIMPLEVIEWER CONFIGURATION OPTIONS' + '\n' +
'		// To use an option, uncomment it by removing the "//" at the start of the line' + '\n' +
'		// For a description of config options, go to:' + '\n' + 
'		// http://www.airtightinteractive.com/simpleviewer/options.html' + '\n' + '\n' +		
'		//fo.addVariable("xmlDataPath", "gallery.xml");' + '\n' +
'		//fo.addVariable("firstImageIndex", "5");' + '\n' +	
'		//fo.addVariable("langOpenImage", "Open Image in New Window");' + '\n' +
'		//fo.addVariable("langAbout", "About");' + '\n' +	
'		//fo.addVariable("preloaderColor", "0xFFFFFF");' + '\n' + '\n' +
'		fo.write("flashcontent");' + '\n' +
'	</script>' + '\n' +
'</body>' + '\n' +
'</html>');
    }

// CheckVersion
function CheckVersion() {
	var numberArray = version.split(".");
	if ( numberArray[0] < 9 ) {
		alert( "You must use Photoshop CS2 or later to run this script!" );
		throw( "You must use Photoshop CS2 or later to run this script!" );
	}
}

// load my params from the xml file on disk if it exists
// gParams["myoptionname"] = myoptionvalue
// I wrote a very simple xml parser, I'm sure it needs work
function LoadParamsFromDisk ( loadFile, params ) {
	// var params = new Array();
	if ( loadFile.exists ) {
		loadFile.open( "r" );
		var projectSpace = ReadHeader( loadFile );
		if ( projectSpace == GetScriptNameForXML() ) {
			while ( ! loadFile.eof ) {
				var starter = ReadHeader( loadFile );
				var data = ReadData( loadFile );
				var ender = ReadHeader( loadFile );
				if ( ( "/" + starter ) == ender ) {
					params[starter] = data;
				}
				// force boolean values to boolean types
				if ( data == "true" || data == "false" ) {
					params[starter] = data == "true";
				}
			}
		}
		loadFile.close();
		if ( params["version"] != gVersion ) {
			// do something here to fix version conflicts
			// this should do it
			params["version"] = gVersion;
		}
	} 
	return params;
}

// save out my params, this is much easier
function SaveParamsToDisk ( saveFile, params ) {
	saveFile.encoding = "UTF8";
	saveFile.open( "w", "TEXT", "????" );
	// unicode signature, this is UTF16 but will convert to UTF8 "EF BB BF"
	saveFile.write("\uFEFF"); 
	var scriptNameForXML = GetScriptNameForXML();
	saveFile.writeln( "<" + scriptNameForXML + ">" );
	for ( var p in params ) {
		saveFile.writeln( "\t<" + p + ">" + params[p] + "</" + p + ">" );
	}
	saveFile.writeln( "</" + scriptNameForXML + ">" );
	saveFile.close();
}

// you can't save certain characters in xml, strip them here
// this list is not complete
function GetScriptNameForXML () {
	var scriptNameForXML = new String( gScriptName );
	var charsToStrip = Array( " ", "'", "." );
	for (var a = 0; a < charsToStrip.length; a++ )  {
		var nameArray = scriptNameForXML.split( charsToStrip[a] );
		scriptNameForXML = "";
		for ( var b = 0; b < nameArray.length; b++ ) {
			scriptNameForXML += nameArray[b];
		}
	}
	return scriptNameForXML;
}

// figure out what I call my params file
function GetDefaultParamsFile() {
	var paramsFolder = new Folder( path + "/Presets/" + gScriptName );
	paramsFolder.create();
	return ( new File( paramsFolder + "/" + gScriptName + ".xml" ) );
}

// a very crude xml parser, this reads the "Tag" of the <Tag>Data</Tag>
function ReadHeader( inFile ) {
	var returnValue = "";
	if ( ! inFile.eof ) {
		var c = "";
		while ( c != "<" && ! inFile.eof ) {
			c = inFile.read( 1 );
		}
		while ( c != ">" && ! inFile.eof ) {
			c = inFile.read( 1 );
			if ( c != ">" ) {
				returnValue += c;
			}
		}
	} else {
		returnValue = "end of file";
	}
	return returnValue;
}

// very crude xml parser, this reads the "Data" of the <Tag>Data</Tag>
function ReadData( inFile ) {
	var returnValue = "";
	if ( ! inFile.eof ) {
		var c = "";
		while ( c != "<" && ! inFile.eof ) {
			c = inFile.read( 1 );
			if ( c != "<" ) {
				returnValue += c;
			}
		}
		inFile.seek( -1, 1 );
	}
	return returnValue;
}

