// Import Folder as Layers - Photoshop CS/CS2 Script
// Description: Imports a series of images (from the designated folder) as named layers into a new document
// Author: Trevor Morris (tmorris@fundy.net) - with help from Krista Cook and Gunnar Landva
// Version: 1.3.2, 7/Jun/2005

// debugging code
/*
debugger;
$.level = 1;
*/

// determine Photoshop version number
function getCSVersion() {
	return parseInt(app.version);
}

function getFolder() {
	// display the Path Entry dialog with Browse option for Photoshop CS
	if (getCSVersion() === 8) {
		// create dialog for pasting/typing path to images folder
		var dlg = new Window('dialog', 'Import Folders as Layers', [0,0,480,118]);
		dlg.center();
		dlg.add('statictext', [15,15,460,35], 'Please enter the path of the folder to be imported:');
		dlg.add('edittext', [15,45,465,65], '', {name:'pathText'});
		dlg.pathText.active = true;
		dlg.add('button', [235,80,305,103], 'Browse', {name:'browse'});
		dlg.browse.onClick = function() {this.parent.close(3);};
		dlg.add('button', [315,80,385,103], 'OK', {name:'ok'});
		dlg.add('button', [395,80,465,103], 'Cancel', {name:'cancel'});

		// display dialog
		dlg.result = dlg.show();

		if (dlg.result == 3) { // Browse
			return Folder.selectDialog('Please select the folder to be imported:', Folder('~'));
		} else if (dlg.result == 1) { // OK
			return Folder(dlg.pathText.text);
		} else { // Cancel (dlg.result == 0)
			return null;
		}
	}
	// display only the browse dialog for Photoshop CS2+
	else {
		return Folder.selectDialog('Please select the folder to be imported:', Folder('~'));
	}
}

function importFolderAsLayers(selectedFolder) {

	// if a folder was selected continue with action, otherwise quit
	if (selectedFolder) {

		// create document list from files in selected folder
		var docList = selectedFolder.getFiles();
		for (var i = 0; i < docList.length; i++) {

			// open each document in file list
			if (docList[i] instanceof File) {

				// get the file name
				var fName = docList[i].name.toLowerCase();

				// check for supported file formats
				if ((fName.indexOf(".gif") == -1) && (fName.indexOf(".jpg") == -1) && (fName.indexOf(".png") == -1) && (fName.indexOf(".bmp") == -1) && (fName.indexOf(".tif") == -1) && (fName.indexOf(".psd") == -1)) {
					// skip unsupported formats
				} else {

					// if supported documents exist, create a new document
					if (!newCanvas) {

						// remember unit settings and change to pixels
						var originalRulerUnits = preferences.rulerUnits;
						preferences.rulerUnits = Units.PIXELS;
						var newDoc = app.documents.add(300, 300, 72, "Imported Layers", NewDocumentMode.RGB, DocumentFill.TRANSPARENT, 1);

						// restore original unit setting
						preferences.rulerUnits = originalRulerUnits;
						var newCanvas = 1;
					}

					// open documents from list; get document name; flatten; duplicate to new document; close;
					// name layer in new document using the original document name
					open(docList[i]);
					var docRef = app.activeDocument;
					var docName = docRef.name;
					docRef.flatten();
					docRef.changeMode(ChangeMode.RGB);
					docRef.activeLayer.duplicate(documents[newDoc.name],ElementPlacement.PLACEATBEGINNING);
					docRef.close(SaveOptions.DONOTSAVECHANGES);
					newDoc.activeLayer.name = docName.substring(0, docName.lastIndexOf("."));
				}
			}
		}

		// delete empty "Layer 1", then reveal and trim canvas to fit all layers
		if (newCanvas) {
			app.activeDocument.artLayers["Layer 1"].remove();
			app.activeDocument.revealAll();
			app.activeDocument.trim(TrimType.TRANSPARENT, true, true, true, true);
			/*
			// save the final document (prompt)
			var saveDoc = File.saveDialog("Save the new document as:");
			if (saveDoc) {app.activeDocument.saveAs(saveDoc);}
			*/
		} else {
			// display error message if no supported documents were found in the designated folder
			alert("Sorry, but the designated folder does not contain any recognized image formats.\n\nPlease choose another folder.");
			importFolderAsLayers(getFolder());
		}
	} else {
		// alert("The action has been cancelled.");
	}
}

importFolderAsLayers(getFolder());
