// New Flex Skin - Photoshop CS/CS2/CS3 Script
// Description: Loads Flex component templates into Photoshop
// Author: Mark Maguire
// Version: 1.0, 17/June/2007

/*
@@@BUILDINFO@@@ NewFlexSkins.jsx 1.0.0.0
*/

//
// NewFlexSkins.jsx - does just that.
//

/*

// BEGIN__HARVEST_EXCEPTION_ZSTRING

<javascriptresource>
<name>$$$/JavaScripts/NewFlexSkins/Menu=New Flex Skin...</name>
<about>$$$/JavaScripts/NewFlexSkins/About=New Flex Skin^r^rCopyright 2006-2007 Adobe Systems Incorporated. All rights reserved.^r^rLoads Flex component templates into Photoshop for processing.</about>
<category>flexskins</category>
</javascriptresource>

// END__HARVEST_EXCEPTION_ZSTRING

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

// on localized builds we pull the $$$/Strings from a .dat file
$.localize = true;

// enable double-clicking from Mac Finder or Windows Explorer
#target photoshop // this command only works in Photoshop CS2 and higher

// bring application forward for double-click events
app.bringToFront();

// globals
// Array of Flex components (version: Flex 2.0.1)
var FlexComponents = new Array("Application","Button","AccordionHeader","ButtonBarButtons","Checkbox","ColorPicker","ComboBox","CursorManager","DataGrid","DateChooser","DateField","DragManager","DividedBox","FormItem","Image","LinkButton","Loader","Menu","MenuBar","NumericStepper","Panel","ControlBar","PopUpButton","ProgressBar","RadioButton","ScrollBar","Slider","HSlider","VSlider","TabBar","ToolTip","Tree");

// New Flex Skin script
var strPresetsFolderDirectory = localize( "$$$/Windows/PresetsFolder/Directory=Presets" );
var strFlexSamplesFolderDirectory = localize( "$$$/Windows/FlexSamplesFolder/Directory=Flex Skins" );
var strDialogName = localize( "$$$/Adobe/NewFlexSkins/DialogName=New Flex Skin" );
var folderRef = new Folder(app.path.toString() + "/" + strPresetsFolderDirectory + "/" + strFlexSamplesFolderDirectory);
var filenamesinfolder = folderRef.getFiles();
folderRef = null;
var w = new Window(
	"dialog {					\
		orientation: 'column',	\
		st:	StaticText { text: 'Create skins for:', alignment:'center' },	\
		radiobuttons: Group { orientation: 'column', alignment:'left', \
			multiBtn: RadioButton { text:'Multiple Flex Components' , alignment:'left', value:'true', properties:{name:'multi'} }, \
			oneBtn: RadioButton { text:'Specific Component' , alignment:'left', properties:{name:'specific'} }, \
		} \
		flexcomp: ListBox { preferredSize:[250,200] , alignment:'center' , enabled:false}, \
		instancegroup: Group { orientation: 'row', alignment:'left', \
			sapply: StaticText { text: 'Apply skin to:', alignment:'left' },	\
			radioinstances: Group { orientation: 'column', 	\
				allinstBtn: RadioButton { text:'All instances', alignment:'left', value:'true', enabled:false, properties:{name:'all'} }, \
				styleinstBtn: RadioButton { text: 'Instances with style name:' , alignment:'left', enabled:false, properties:{name:'style'} }, \
				stylename: EditText { preferredSize: [120, 20] , alignment:'left', enabled:false }, \
			} \
		} \
		buttons: Group { orientation: 'row', alignment:'right', \
			okBtn: Button { text:'OK' , properties:{name:'ok'} }, \
			cancelBtn: Button { text:'Cancel' , properties:{name:'cancel'} }, \
		} \
	}", strDialogName );

var item;
for( var i1 = 0; i1 < filenamesinfolder.length; i1++)
{
	var componentName;
	var nameOfSkin = filenamesinfolder[i1].name;
	var lastDot = nameOfSkin.toString().lastIndexOf( "." );
	if ( lastDot == -1 ) {
		componentName = nameOfSkin;
	}
	else
	{
		var strLength = nameOfSkin.toString().length;
		componentName = nameOfSkin.toString().substr(0, strLength - 4 );
	}
	if (componentName != "FlexSkins")
		item = w.flexcomp.add('item',componentName);
}
w.radiobuttons.multiBtn.onClick = function () {w.flexcomp.enabled = false; w.instancegroup.radioinstances.allinstBtn.enabled = false; w.instancegroup.radioinstances.styleinstBtn.enabled = false; w.instancegroup.radioinstances.stylename.enabled = false; };
w.radiobuttons.oneBtn.onClick = function () {w.flexcomp.enabled = true; w.flexcomp.selection = w.flexcomp.items[0]; w.instancegroup.radioinstances.allinstBtn.enabled = true; w.instancegroup.radioinstances.styleinstBtn.enabled = true;};
w.instancegroup.radioinstances.allinstBtn.onClick = function () {w.instancegroup.radioinstances.stylename.enabled = false;};
w.instancegroup.radioinstances.styleinstBtn.onClick = function () {w.instancegroup.radioinstances.stylename.enabled = true;};
w.buttons.cancelBtn.onClick = function () { exitApp();};
w.buttons.okBtn.onClick = function () { openComponents();};
w.show();

// ---------------------------------------------------------------------------------------------------------------------
// change style names if we need to
// ---------------------------------------------------------------------------------------------------------------------
function ChangeLayerSetName(obj, stylename)
{
 	var len = obj.layers.length;
	for (var i = 0; i < len; i++) {
		var currentLayer = obj.layers[i];
		if (currentLayer.typename == 'LayerSet') {
		  if (currentLayer.name[0] != '_')
			ChangeLayerSetName(currentLayer, stylename);
		}
		else {
			
			var firstunderbar = currentLayer.name.toString().indexOf( "_" );
			if ( firstunderbar == -1 ) {
				currentLayer.name = stylename + '_' + currentLayer.name;
			}
			else
			{	
				var firstpart,lastpart;
				var strLength = currentLayer.name.toString().length;
				firstpart = currentLayer.name.toString().substr(0, firstunderbar);
				lastpart = currentLayer.name.toString().substr(firstunderbar, strLength);
				currentLayer.name = firstpart + '_' + stylename + lastpart;
			}
		}
	}
}

// ---------------------------------------------------------------------------------------------------------------------
// openComponents - Load flex templates
// ---------------------------------------------------------------------------------------------------------------------
function openComponents() {
	var componentSelected;
	var style;
	var usestyle = false;
	if (w.instancegroup.radioinstances.styleinstBtn.value == true)
	{
    		style = w.instancegroup.radioinstances.stylename.text;
		usestyle = true;
	}
	else
		style = "none";
	if (w.radiobuttons.multiBtn.value == true)
    		componentSelected = strFlexSamplesFolderDirectory + "/" + 'FlexSkins.psd';
	else
		componentSelected = strFlexSamplesFolderDirectory + "/" + w.flexcomp.selection.toString() + ".psd";
	w.close ();
	var fileRef = new File(app.path.toString() + "/" + strPresetsFolderDirectory + "/" + componentSelected);
	open (fileRef);
	fileRef = null;
	var docName = app.activeDocument.name;  // save the app.activeDocument name before duplicate.
	app.activeDocument = app.documents[docName];
	var duppedDocument = app.activeDocument.duplicate();
	app.activeDocument = duppedDocument;
	app.documents[docName].close();
	if (usestyle == true)
	{
		// begin try/catch
		try {
		   ChangeLayerSetName(activeDocument, style);
		}
		// display error message if something goes wrong
		catch(e) {
			if (confirm('An unknown error has occurred. Would you like to see more information?')) {
				alert(e + ': on line ' + e.line, 'Script Error', true);
			}
		}
	}
}


// ---------------------------------------------------------------------------------------------------------------------
// exitApp
// ---------------------------------------------------------------------------------------------------------------------
function exitApp() 
{
	try{
		w.close ();
	}
	catch(e) {
		alert(e);
	}
}

