﻿#target photoshop

//---Global vars-------------------------------------------------------------------------------------
var ProjectData = 
{
    procPaintFolder: (Folder.temp + "/ProcPaint"),
    procPaintFiles: [],
    maskFiles: [],
    procEditFiles: [],
    tileXY: null,
    procPaintMasterMapPath: "X:/gta5/assets/maps/procPaint/ProceduralSetmap.png",
    proceduralSetsXMLPath:"X:/gta5/assets/maps/procPaint/ProceduralSets.xml",
    
    procPaintMasterMap: [18300, 24900],
	tileSize: 100.0,
    
    swatchSize: 100.0,
    swatchBorder: 20.0,
    swatchItemWidth: (100.0 * 4.0),
    swatchItemHeight: (100.0 * 1.2),
    swatchOrientation: "vertical"
    
}

var ProceduralSetData =
{
        setDefinitions: [],
        proceduralDefinitions: []
    
}

var ProcDef = 
{
        name:null,
        hue:null
}

//---/Global vars-------------------------------------------------------------------------------------

//Process
//Find any mask files to be used as reference layers
discoverMasks();
getTileXY();
harvestProceduralSets();



//---------------------------   FUNCTIONS --------------------------------------------
function harvestProceduralSets()
{
    var SetDefinition =
    {
            name: null,
            proceduralHues: []
    }
   
   //Read the ProceduralSets.xml
    var f = new File(ProjectData.proceduralSetsXMLPath);
    f.open('r');
    var xmlFile = f.read();
    var procXML = new XML( xmlFile );
    f.close();
    
    //Create a list of proceduralDefinitions
    var procRoot = procXML.children('SetData')[0];
    var procDefs = procRoot.children('ProceduralDefinitions');
    
    for(var i=0; i<procDefs.length(); i++)
    {
            var procDef = new Object();
            procDef.name = procDefs.child(i).@Name;
            procDef.hue = procDefs.child(i).@ColorHue;
            ProceduralSetData.proceduralDefinitions.push(procDef);
    }

    //Create a list of SetDefinitions
    var setDefs = procXML.descendants('Set');
    $.writeln(setDefs.length());
    for(var i=0; i<setDefs.length(); i++)
    {
            var thisChild = setDefs.child(i);
            var setDef = new Object();
            setDef.name = setDefs.child(i).@Name;
            setDef.proceduralHue = [];
            var procHues = thisChild.children('ProceduralHue');
            
            for(var p=0; p<procHues.length(); p++)
            {
                   setDef.proceduralHue.push(parseInt(procHues[p]));
            }
        
            ProceduralSetData.setDefinitions.push(setDef);
    }
    
}

//Query the file location for mask region images.
function discoverMasks()
{
    //get the raw file list
    ProjectData.procPaintFiles = (new Folder(ProjectData.procPaintFolder)).getFiles();
    
    //Filter them out into masks and edit maps
    for(var f=0; f<ProjectData.procPaintFiles.length; f++)
    {
            var filePath = ProjectData.procPaintFiles[f];
            
            //split on the '[' if we get an array its a mask, if not, an edit map
            var nameBits = filePath.displayName.split("[");
            
            if(nameBits.length > 1)     //mask
            {
                ProjectData.maskFiles.push(filePath);
            }
            else
            {
                ProjectData.procEditFiles.push(filePath);
            }
    }
}

function openImageToLayer(filePath)
{
    var doc = app.open(filePath);
    app.activeDocument.selection.selectAll();
    app.activeDocument.selection.copy();
    app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
    activeDocument.paste();
    
}

function getNiceNamesforLayers()
{
    var names = [];
    for(var i=0; i< ProjectData.maskFiles.length; i++)
    {
        names.push( ((ProjectData.maskFiles[i].displayName).split("."))[0]);
    }

    return names;
}


function moveSelection(regionLayer, xPos, yPos)
{
    var topLeftX = regionLayer.bounds[0];
    var topLeftY = regionLayer.bounds[1];
    
    var deltaX = -topLeftX + xPos;
    var deltaY = -topLeftY+ yPos;
    
    regionLayer.translate(deltaX, deltaY);
}

function getTileXY()
{
        if(ProjectData.procEditFiles.length != 0)
        {
                var fileName = (ProjectData.procEditFiles[0].displayName).split(".")[0];
                var nameBits = fileName.split("_");
                ProjectData.tileXY = [nameBits[1], nameBits[2]];
        }
    
    return;
}

function getBitmapPosFromTileXy()
{
        if( ProjectData.tileXY == null ) { return []; }
        
        var xPos = ProjectData.tileXY[0] * ProjectData.tileSize;
        var yPos = ProjectData.tileXY[1] * ProjectData.tileSize;
        return [xPos, yPos];
}

function makeSwatch(top, left, bottom, right)
{
    var idMk = charIDToTypeID( "Mk  " );
    var desc4 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var ref2 = new ActionReference();
        var idcontentLayer = stringIDToTypeID( "contentLayer" );
        ref2.putClass( idcontentLayer );
    desc4.putReference( idnull, ref2 );
    var idUsng = charIDToTypeID( "Usng" );
        var desc5 = new ActionDescriptor();
        var idType = charIDToTypeID( "Type" );
        var idsolidColorLayer = stringIDToTypeID( "solidColorLayer" );
        desc5.putClass( idType, idsolidColorLayer );
        var idShp = charIDToTypeID( "Shp " );
            var desc6 = new ActionDescriptor();
            var idTop = charIDToTypeID( "Top " );
            var idPxl = charIDToTypeID( "#Pxl" );
            desc6.putUnitDouble( idTop, idPxl, top );
            var idLeft = charIDToTypeID( "Left" );
            var idPxl = charIDToTypeID( "#Pxl" );
            desc6.putUnitDouble( idLeft, idPxl, left );
            var idBtom = charIDToTypeID( "Btom" );
            var idPxl = charIDToTypeID( "#Pxl" );
            desc6.putUnitDouble( idBtom, idPxl, bottom );
            var idRght = charIDToTypeID( "Rght" );
            var idPxl = charIDToTypeID( "#Pxl" );
            desc6.putUnitDouble( idRght, idPxl, right );
        var idRctn = charIDToTypeID( "Rctn" );
        desc5.putObject( idShp, idRctn, desc6 );
    var idcontentLayer = stringIDToTypeID( "contentLayer" );
    desc4.putObject( idUsng, idcontentLayer, desc5 );
executeAction( idMk, desc4, DialogModes.NO );
}

function makeSwatchDescriptor(text)
{
var idMk = charIDToTypeID( "Mk  " );
    var desc127 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var ref43 = new ActionReference();
        var idTxLr = charIDToTypeID( "TxLr" );
        ref43.putClass( idTxLr );
    desc127.putReference( idnull, ref43 );
    var idUsng = charIDToTypeID( "Usng" );
        var desc128 = new ActionDescriptor();
        var idTxt = charIDToTypeID( "Txt " );
        desc128.putString( idTxt, text );
        var idwarp = stringIDToTypeID( "warp" );
            var desc129 = new ActionDescriptor();
            var idwarpStyle = stringIDToTypeID( "warpStyle" );
            var idwarpStyle = stringIDToTypeID( "warpStyle" );
            var idwarpNone = stringIDToTypeID( "warpNone" );
            desc129.putEnumerated( idwarpStyle, idwarpStyle, idwarpNone );
            var idwarpValue = stringIDToTypeID( "warpValue" );
            desc129.putDouble( idwarpValue, 0.000000 );
            var idwarpPerspective = stringIDToTypeID( "warpPerspective" );
            desc129.putDouble( idwarpPerspective, 0.000000 );
            var idwarpPerspectiveOther = stringIDToTypeID( "warpPerspectiveOther" );
            desc129.putDouble( idwarpPerspectiveOther, 0.000000 );
            var idwarpRotate = stringIDToTypeID( "warpRotate" );
            var idOrnt = charIDToTypeID( "Ornt" );
            var idHrzn = charIDToTypeID( "Hrzn" );
            desc129.putEnumerated( idwarpRotate, idOrnt, idHrzn );
        var idwarp = stringIDToTypeID( "warp" );
        desc128.putObject( idwarp, idwarp, desc129 );
        var idTxtC = charIDToTypeID( "TxtC" );
            var desc130 = new ActionDescriptor();
            var idHrzn = charIDToTypeID( "Hrzn" );
            var idPrc = charIDToTypeID( "#Prc" );
            desc130.putUnitDouble( idHrzn, idPrc, 13.483146 );
            var idVrtc = charIDToTypeID( "Vrtc" );
            var idPrc = charIDToTypeID( "#Prc" );
            desc130.putUnitDouble( idVrtc, idPrc, 7.382550 );
        var idPnt = charIDToTypeID( "Pnt " );
        desc128.putObject( idTxtC, idPnt, desc130 );
        var idtextGridding = stringIDToTypeID( "textGridding" );
        var idtextGridding = stringIDToTypeID( "textGridding" );
        var idNone = charIDToTypeID( "None" );
        desc128.putEnumerated( idtextGridding, idtextGridding, idNone );
        var idOrnt = charIDToTypeID( "Ornt" );
        var idOrnt = charIDToTypeID( "Ornt" );
        var idHrzn = charIDToTypeID( "Hrzn" );
        desc128.putEnumerated( idOrnt, idOrnt, idHrzn );
        var idAntA = charIDToTypeID( "AntA" );
        var idAnnt = charIDToTypeID( "Annt" );
        var idantiAliasSharp = stringIDToTypeID( "antiAliasSharp" );
        desc128.putEnumerated( idAntA, idAnnt, idantiAliasSharp );
        var idtextShape = stringIDToTypeID( "textShape" );
            var list19 = new ActionList();
                var desc131 = new ActionDescriptor();
                var idTEXT = charIDToTypeID( "TEXT" );
                var idTEXT = charIDToTypeID( "TEXT" );
                var idPnt = charIDToTypeID( "Pnt " );
                desc131.putEnumerated( idTEXT, idTEXT, idPnt );
                var idOrnt = charIDToTypeID( "Ornt" );
                var idOrnt = charIDToTypeID( "Ornt" );
                var idHrzn = charIDToTypeID( "Hrzn" );
                desc131.putEnumerated( idOrnt, idOrnt, idHrzn );
                var idTrnf = charIDToTypeID( "Trnf" );
                    var desc132 = new ActionDescriptor();
                    var idxx = stringIDToTypeID( "xx" );
                    desc132.putDouble( idxx, 1.000000 );
                    var idxy = stringIDToTypeID( "xy" );
                    desc132.putDouble( idxy, 0.000000 );
                    var idyx = stringIDToTypeID( "yx" );
                    desc132.putDouble( idyx, 0.000000 );
                    var idyy = stringIDToTypeID( "yy" );
                    desc132.putDouble( idyy, 1.000000 );
                    var idtx = stringIDToTypeID( "tx" );
                    desc132.putDouble( idtx, 0.000000 );
                    var idty = stringIDToTypeID( "ty" );
                    desc132.putDouble( idty, 0.000000 );
                var idTrnf = charIDToTypeID( "Trnf" );
                desc131.putObject( idTrnf, idTrnf, desc132 );
                var idrowCount = stringIDToTypeID( "rowCount" );
                desc131.putInteger( idrowCount, 1 );
                var idcolumnCount = stringIDToTypeID( "columnCount" );
                desc131.putInteger( idcolumnCount, 1 );
                var idrowMajorOrder = stringIDToTypeID( "rowMajorOrder" );
                desc131.putBoolean( idrowMajorOrder, true );
                var idrowGutter = stringIDToTypeID( "rowGutter" );
                var idPnt = charIDToTypeID( "#Pnt" );
                desc131.putUnitDouble( idrowGutter, idPnt, 0.000000 );
                var idcolumnGutter = stringIDToTypeID( "columnGutter" );
                var idPnt = charIDToTypeID( "#Pnt" );
                desc131.putUnitDouble( idcolumnGutter, idPnt, 0.000000 );
                var idSpcn = charIDToTypeID( "Spcn" );
                var idPnt = charIDToTypeID( "#Pnt" );
                desc131.putUnitDouble( idSpcn, idPnt, 0.000000 );
                var idframeBaselineAlignment = stringIDToTypeID( "frameBaselineAlignment" );
                var idframeBaselineAlignment = stringIDToTypeID( "frameBaselineAlignment" );
                var idalignByAscent = stringIDToTypeID( "alignByAscent" );
                desc131.putEnumerated( idframeBaselineAlignment, idframeBaselineAlignment, idalignByAscent );
                var idfirstBaselineMinimum = stringIDToTypeID( "firstBaselineMinimum" );
                var idPnt = charIDToTypeID( "#Pnt" );
                desc131.putUnitDouble( idfirstBaselineMinimum, idPnt, 0.000000 );
                var idbase = stringIDToTypeID( "base" );
                    var desc133 = new ActionDescriptor();
                    var idHrzn = charIDToTypeID( "Hrzn" );
                    desc133.putDouble( idHrzn, 0.000000 );
                    var idVrtc = charIDToTypeID( "Vrtc" );
                    desc133.putDouble( idVrtc, 0.000000 );
                var idPnt = charIDToTypeID( "Pnt " );
                desc131.putObject( idbase, idPnt, desc133 );
            var idtextShape = stringIDToTypeID( "textShape" );
            list19.putObject( idtextShape, desc131 );
        desc128.putList( idtextShape, list19 );
        var idTxtt = charIDToTypeID( "Txtt" );
            var list20 = new ActionList();
                var desc134 = new ActionDescriptor();
                var idFrom = charIDToTypeID( "From" );
                desc134.putInteger( idFrom, 0 );
                var idT = charIDToTypeID( "T   " );
                desc134.putInteger( idT, 30 );
                var idTxtS = charIDToTypeID( "TxtS" );
                    var desc135 = new ActionDescriptor();
                    var idstyleSheetHasParent = stringIDToTypeID( "styleSheetHasParent" );
                    desc135.putBoolean( idstyleSheetHasParent, true );
                    var idfontPostScriptName = stringIDToTypeID( "fontPostScriptName" );
                    desc135.putString( idfontPostScriptName, "ArialMT" );
                    var idFntN = charIDToTypeID( "FntN" );
                    desc135.putString( idFntN, "Arial" );
                    var idFntS = charIDToTypeID( "FntS" );
                    desc135.putString( idFntS, "Regular" );
                    var idScrp = charIDToTypeID( "Scrp" );
                    desc135.putInteger( idScrp, 0 );
                    var idFntT = charIDToTypeID( "FntT" );
                    desc135.putInteger( idFntT, 1 );
                    var idSz = charIDToTypeID( "Sz  " );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc135.putUnitDouble( idSz, idPnt, 18.000000 );
                    var idHrzS = charIDToTypeID( "HrzS" );
                    desc135.putDouble( idHrzS, 100.000000 );
                    var idVrtS = charIDToTypeID( "VrtS" );
                    desc135.putDouble( idVrtS, 100.000000 );
                    var idsyntheticBold = stringIDToTypeID( "syntheticBold" );
                    desc135.putBoolean( idsyntheticBold, false );
                    var idsyntheticItalic = stringIDToTypeID( "syntheticItalic" );
                    desc135.putBoolean( idsyntheticItalic, false );
                    var idautoLeading = stringIDToTypeID( "autoLeading" );
                    desc135.putBoolean( idautoLeading, true );
                    var idTrck = charIDToTypeID( "Trck" );
                    desc135.putInteger( idTrck, 0 );
                    var idBsln = charIDToTypeID( "Bsln" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc135.putUnitDouble( idBsln, idPnt, 0.000000 );
                    var idcharacterRotation = stringIDToTypeID( "characterRotation" );
                    desc135.putDouble( idcharacterRotation, 0.000000 );
                    var idAtKr = charIDToTypeID( "AtKr" );
                    var idAtKr = charIDToTypeID( "AtKr" );
                    var idmetricsKern = stringIDToTypeID( "metricsKern" );
                    desc135.putEnumerated( idAtKr, idAtKr, idmetricsKern );
                    var idfontCaps = stringIDToTypeID( "fontCaps" );
                    var idfontCaps = stringIDToTypeID( "fontCaps" );
                    var idNrml = charIDToTypeID( "Nrml" );
                    desc135.putEnumerated( idfontCaps, idfontCaps, idNrml );
                    var idbaseline = stringIDToTypeID( "baseline" );
                    var idbaseline = stringIDToTypeID( "baseline" );
                    var idNrml = charIDToTypeID( "Nrml" );
                    desc135.putEnumerated( idbaseline, idbaseline, idNrml );
                    var idotbaseline = stringIDToTypeID( "otbaseline" );
                    var idotbaseline = stringIDToTypeID( "otbaseline" );
                    var idNrml = charIDToTypeID( "Nrml" );
                    desc135.putEnumerated( idotbaseline, idotbaseline, idNrml );
                    var idstrikethrough = stringIDToTypeID( "strikethrough" );
                    var idstrikethrough = stringIDToTypeID( "strikethrough" );
                    var idstrikethroughOff = stringIDToTypeID( "strikethroughOff" );
                    desc135.putEnumerated( idstrikethrough, idstrikethrough, idstrikethroughOff );
                    var idUndl = charIDToTypeID( "Undl" );
                    var idUndl = charIDToTypeID( "Undl" );
                    var idunderlineOff = stringIDToTypeID( "underlineOff" );
                    desc135.putEnumerated( idUndl, idUndl, idunderlineOff );
                    var idunderlineOffset = stringIDToTypeID( "underlineOffset" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc135.putUnitDouble( idunderlineOffset, idPnt, 0.000000 );
                    var idligature = stringIDToTypeID( "ligature" );
                    desc135.putBoolean( idligature, true );
                    var idaltligature = stringIDToTypeID( "altligature" );
                    desc135.putBoolean( idaltligature, false );
                    var idcontextualLigatures = stringIDToTypeID( "contextualLigatures" );
                    desc135.putBoolean( idcontextualLigatures, false );
                    var idalternateLigatures = stringIDToTypeID( "alternateLigatures" );
                    desc135.putBoolean( idalternateLigatures, false );
                    var idoldStyle = stringIDToTypeID( "oldStyle" );
                    desc135.putBoolean( idoldStyle, false );
                    var idfractions = stringIDToTypeID( "fractions" );
                    desc135.putBoolean( idfractions, false );
                    var idordinals = stringIDToTypeID( "ordinals" );
                    desc135.putBoolean( idordinals, false );
                    var idswash = stringIDToTypeID( "swash" );
                    desc135.putBoolean( idswash, false );
                    var idtitling = stringIDToTypeID( "titling" );
                    desc135.putBoolean( idtitling, false );
                    var idconnectionForms = stringIDToTypeID( "connectionForms" );
                    desc135.putBoolean( idconnectionForms, false );
                    var idstylisticAlternates = stringIDToTypeID( "stylisticAlternates" );
                    desc135.putBoolean( idstylisticAlternates, false );
                    var idornaments = stringIDToTypeID( "ornaments" );
                    desc135.putBoolean( idornaments, false );
                    var idfigureStyle = stringIDToTypeID( "figureStyle" );
                    var idfigureStyle = stringIDToTypeID( "figureStyle" );
                    var idNrml = charIDToTypeID( "Nrml" );
                    desc135.putEnumerated( idfigureStyle, idfigureStyle, idNrml );
                    var idproportionalMetrics = stringIDToTypeID( "proportionalMetrics" );
                    desc135.putBoolean( idproportionalMetrics, false );
                    var idkana = stringIDToTypeID( "kana" );
                    desc135.putBoolean( idkana, false );
                    var iditalics = stringIDToTypeID( "italics" );
                    desc135.putBoolean( iditalics, false );
                    var idruby = stringIDToTypeID( "ruby" );
                    desc135.putBoolean( idruby, false );
                    var idbaselineDirection = stringIDToTypeID( "baselineDirection" );
                    var idbaselineDirection = stringIDToTypeID( "baselineDirection" );
                    var idrotated = stringIDToTypeID( "rotated" );
                    desc135.putEnumerated( idbaselineDirection, idbaselineDirection, idrotated );
                    var idtextLanguage = stringIDToTypeID( "textLanguage" );
                    var idtextLanguage = stringIDToTypeID( "textLanguage" );
                    var idenglishLanguage = stringIDToTypeID( "englishLanguage" );
                    desc135.putEnumerated( idtextLanguage, idtextLanguage, idenglishLanguage );
                    var idjapaneseAlternate = stringIDToTypeID( "japaneseAlternate" );
                    var idjapaneseAlternate = stringIDToTypeID( "japaneseAlternate" );
                    var iddefaultForm = stringIDToTypeID( "defaultForm" );
                    desc135.putEnumerated( idjapaneseAlternate, idjapaneseAlternate, iddefaultForm );
                    var idmojiZume = stringIDToTypeID( "mojiZume" );
                    desc135.putDouble( idmojiZume, 0.000000 );
                    var idgridAlignment = stringIDToTypeID( "gridAlignment" );
                    var idgridAlignment = stringIDToTypeID( "gridAlignment" );
                    var idroman = stringIDToTypeID( "roman" );
                    desc135.putEnumerated( idgridAlignment, idgridAlignment, idroman );
                    var idenableWariChu = stringIDToTypeID( "enableWariChu" );
                    desc135.putBoolean( idenableWariChu, false );
                    var idwariChuCount = stringIDToTypeID( "wariChuCount" );
                    desc135.putInteger( idwariChuCount, 2 );
                    var idwariChuLineGap = stringIDToTypeID( "wariChuLineGap" );
                    desc135.putInteger( idwariChuLineGap, 0 );
                    var idwariChuScale = stringIDToTypeID( "wariChuScale" );
                    desc135.putDouble( idwariChuScale, 0.500000 );
                    var idwariChuWidow = stringIDToTypeID( "wariChuWidow" );
                    desc135.putInteger( idwariChuWidow, 2 );
                    var idwariChuOrphan = stringIDToTypeID( "wariChuOrphan" );
                    desc135.putInteger( idwariChuOrphan, 2 );
                    var idwariChuJustification = stringIDToTypeID( "wariChuJustification" );
                    var idwariChuJustification = stringIDToTypeID( "wariChuJustification" );
                    var idwariChuAutoJustify = stringIDToTypeID( "wariChuAutoJustify" );
                    desc135.putEnumerated( idwariChuJustification, idwariChuJustification, idwariChuAutoJustify );
                    var idtcyUpDown = stringIDToTypeID( "tcyUpDown" );
                    desc135.putInteger( idtcyUpDown, 0 );
                    var idtcyLeftRight = stringIDToTypeID( "tcyLeftRight" );
                    desc135.putInteger( idtcyLeftRight, 0 );
                    var idleftAki = stringIDToTypeID( "leftAki" );
                    desc135.putDouble( idleftAki, -1.000000 );
                    var idrightAki = stringIDToTypeID( "rightAki" );
                    desc135.putDouble( idrightAki, -1.000000 );
                    var idjiDori = stringIDToTypeID( "jiDori" );
                    desc135.putInteger( idjiDori, 0 );
                    var idnoBreak = stringIDToTypeID( "noBreak" );
                    desc135.putBoolean( idnoBreak, false );
                    var idClr = charIDToTypeID( "Clr " );
                        var desc136 = new ActionDescriptor();
                        var idRd = charIDToTypeID( "Rd  " );
                        desc136.putDouble( idRd, 0.000000 );
                        var idGrn = charIDToTypeID( "Grn " );
                        desc136.putDouble( idGrn, 0.000000 );
                        var idBl = charIDToTypeID( "Bl  " );
                        desc136.putDouble( idBl, 0.000000 );
                    var idRGBC = charIDToTypeID( "RGBC" );
                    desc135.putObject( idClr, idRGBC, desc136 );
                    var idstrokeColor = stringIDToTypeID( "strokeColor" );
                        var desc137 = new ActionDescriptor();
                        var idRd = charIDToTypeID( "Rd  " );
                        desc137.putDouble( idRd, 53.239578 );
                        var idGrn = charIDToTypeID( "Grn " );
                        desc137.putDouble( idGrn, 53.239578 );
                        var idBl = charIDToTypeID( "Bl  " );
                        desc137.putDouble( idBl, 53.239578 );
                    var idRGBC = charIDToTypeID( "RGBC" );
                    desc135.putObject( idstrokeColor, idRGBC, desc137 );
                    var idFl = charIDToTypeID( "Fl  " );
                    desc135.putBoolean( idFl, true );
                    var idStrk = charIDToTypeID( "Strk" );
                    desc135.putBoolean( idStrk, false );
                    var idfillFirst = stringIDToTypeID( "fillFirst" );
                    desc135.putBoolean( idfillFirst, true );
                    var idfillOverPrint = stringIDToTypeID( "fillOverPrint" );
                    desc135.putBoolean( idfillOverPrint, false );
                    var idstrokeOverPrint = stringIDToTypeID( "strokeOverPrint" );
                    desc135.putBoolean( idstrokeOverPrint, false );
                    var idlineCap = stringIDToTypeID( "lineCap" );
                    var idlineCap = stringIDToTypeID( "lineCap" );
                    var idbuttCap = stringIDToTypeID( "buttCap" );
                    desc135.putEnumerated( idlineCap, idlineCap, idbuttCap );
                    var idlineJoin = stringIDToTypeID( "lineJoin" );
                    var idlineJoin = stringIDToTypeID( "lineJoin" );
                    var idmiterJoin = stringIDToTypeID( "miterJoin" );
                    desc135.putEnumerated( idlineJoin, idlineJoin, idmiterJoin );
                    var idlineWidth = stringIDToTypeID( "lineWidth" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc135.putUnitDouble( idlineWidth, idPnt, 1.000000 );
                    var idmiterLimit = stringIDToTypeID( "miterLimit" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc135.putUnitDouble( idmiterLimit, idPnt, 4.000000 );
                    var idlineDashoffset = stringIDToTypeID( "lineDashoffset" );
                    desc135.putDouble( idlineDashoffset, 0.000000 );
                var idTxtS = charIDToTypeID( "TxtS" );
                desc134.putObject( idTxtS, idTxtS, desc135 );
            var idTxtt = charIDToTypeID( "Txtt" );
            list20.putObject( idTxtt, desc134 );
        desc128.putList( idTxtt, list20 );
        var idparagraphStyleRange = stringIDToTypeID( "paragraphStyleRange" );
            var list21 = new ActionList();
                var desc138 = new ActionDescriptor();
                var idFrom = charIDToTypeID( "From" );
                desc138.putInteger( idFrom, 0 );
                var idT = charIDToTypeID( "T   " );
                desc138.putInteger( idT, 30 );
                var idparagraphStyle = stringIDToTypeID( "paragraphStyle" );
                    var desc139 = new ActionDescriptor();
                    var idAlgn = charIDToTypeID( "Algn" );
                    var idAlg = charIDToTypeID( "Alg " );
                    var idLeft = charIDToTypeID( "Left" );
                    desc139.putEnumerated( idAlgn, idAlg, idLeft );
                    var idfirstLineIndent = stringIDToTypeID( "firstLineIndent" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc139.putUnitDouble( idfirstLineIndent, idPnt, 0.000000 );
                    var idstartIndent = stringIDToTypeID( "startIndent" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc139.putUnitDouble( idstartIndent, idPnt, 0.000000 );
                    var idendIndent = stringIDToTypeID( "endIndent" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc139.putUnitDouble( idendIndent, idPnt, 0.000000 );
                    var idspaceBefore = stringIDToTypeID( "spaceBefore" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc139.putUnitDouble( idspaceBefore, idPnt, 0.000000 );
                    var idspaceAfter = stringIDToTypeID( "spaceAfter" );
                    var idPnt = charIDToTypeID( "#Pnt" );
                    desc139.putUnitDouble( idspaceAfter, idPnt, 0.000000 );
                    var iddropCapMultiplier = stringIDToTypeID( "dropCapMultiplier" );
                    desc139.putInteger( iddropCapMultiplier, 1 );
                    var idautoLeadingPercentage = stringIDToTypeID( "autoLeadingPercentage" );
                    desc139.putDouble( idautoLeadingPercentage, 1.200000 );
                    var idleadingType = stringIDToTypeID( "leadingType" );
                    var idleadingType = stringIDToTypeID( "leadingType" );
                    var idleadingBelow = stringIDToTypeID( "leadingBelow" );
                    desc139.putEnumerated( idleadingType, idleadingType, idleadingBelow );
                    var idhyphenate = stringIDToTypeID( "hyphenate" );
                    desc139.putBoolean( idhyphenate, true );
                    var idhyphenateWordSize = stringIDToTypeID( "hyphenateWordSize" );
                    desc139.putInteger( idhyphenateWordSize, 6 );
                    var idhyphenatePreLength = stringIDToTypeID( "hyphenatePreLength" );
                    desc139.putInteger( idhyphenatePreLength, 2 );
                    var idhyphenatePostLength = stringIDToTypeID( "hyphenatePostLength" );
                    desc139.putInteger( idhyphenatePostLength, 2 );
                    var idhyphenateLimit = stringIDToTypeID( "hyphenateLimit" );
                    desc139.putInteger( idhyphenateLimit, 0 );
                    var idhyphenationZone = stringIDToTypeID( "hyphenationZone" );
                    desc139.putDouble( idhyphenationZone, 36.000000 );
                    var idhyphenateCapitalized = stringIDToTypeID( "hyphenateCapitalized" );
                    desc139.putBoolean( idhyphenateCapitalized, true );
                    var idhyphenationPreference = stringIDToTypeID( "hyphenationPreference" );
                    desc139.putDouble( idhyphenationPreference, 0.500000 );
                    var idjustificationWordMinimum = stringIDToTypeID( "justificationWordMinimum" );
                    desc139.putDouble( idjustificationWordMinimum, 0.800000 );
                    var idjustificationWordDesired = stringIDToTypeID( "justificationWordDesired" );
                    desc139.putDouble( idjustificationWordDesired, 1.000000 );
                    var idjustificationWordMaximum = stringIDToTypeID( "justificationWordMaximum" );
                    desc139.putDouble( idjustificationWordMaximum, 1.330000 );
                    var idjustificationLetterMinimum = stringIDToTypeID( "justificationLetterMinimum" );
                    desc139.putDouble( idjustificationLetterMinimum, 0.000000 );
                    var idjustificationLetterDesired = stringIDToTypeID( "justificationLetterDesired" );
                    desc139.putDouble( idjustificationLetterDesired, 0.000000 );
                    var idjustificationLetterMaximum = stringIDToTypeID( "justificationLetterMaximum" );
                    desc139.putDouble( idjustificationLetterMaximum, 0.000000 );
                    var idjustificationGlyphMinimum = stringIDToTypeID( "justificationGlyphMinimum" );
                    desc139.putDouble( idjustificationGlyphMinimum, 1.000000 );
                    var idjustificationGlyphDesired = stringIDToTypeID( "justificationGlyphDesired" );
                    desc139.putDouble( idjustificationGlyphDesired, 1.000000 );
                    var idjustificationGlyphMaximum = stringIDToTypeID( "justificationGlyphMaximum" );
                    desc139.putDouble( idjustificationGlyphMaximum, 1.000000 );
                    var idsingleWordJustification = stringIDToTypeID( "singleWordJustification" );
                    var idAlg = charIDToTypeID( "Alg " );
                    var idJstA = charIDToTypeID( "JstA" );
                    desc139.putEnumerated( idsingleWordJustification, idAlg, idJstA );
                    var idhangingRoman = stringIDToTypeID( "hangingRoman" );
                    desc139.putBoolean( idhangingRoman, false );
                    var idautoTCY = stringIDToTypeID( "autoTCY" );
                    desc139.putInteger( idautoTCY, 1 );
                    var idkeepTogether = stringIDToTypeID( "keepTogether" );
                    desc139.putBoolean( idkeepTogether, true );
                    var idburasagari = stringIDToTypeID( "burasagari" );
                    var idburasagari = stringIDToTypeID( "burasagari" );
                    var idburasagariNone = stringIDToTypeID( "burasagariNone" );
                    desc139.putEnumerated( idburasagari, idburasagari, idburasagariNone );
                    var idpreferredKinsokuOrder = stringIDToTypeID( "preferredKinsokuOrder" );
                    var idpreferredKinsokuOrder = stringIDToTypeID( "preferredKinsokuOrder" );
                    var idpushIn = stringIDToTypeID( "pushIn" );
                    desc139.putEnumerated( idpreferredKinsokuOrder, idpreferredKinsokuOrder, idpushIn );
                    var idkurikaeshiMojiShori = stringIDToTypeID( "kurikaeshiMojiShori" );
                    desc139.putBoolean( idkurikaeshiMojiShori, false );
                    var idtextEveryLineComposer = stringIDToTypeID( "textEveryLineComposer" );
                    desc139.putBoolean( idtextEveryLineComposer, false );
                    var iddefaultTabWidth = stringIDToTypeID( "defaultTabWidth" );
                    desc139.putDouble( iddefaultTabWidth, 36.000000 );
                    var iddefaultStyle = stringIDToTypeID( "defaultStyle" );
                        var desc140 = new ActionDescriptor();
                        var idfontPostScriptName = stringIDToTypeID( "fontPostScriptName" );
                        desc140.putString( idfontPostScriptName, "MyriadPro-Regular" );
                        var idFntN = charIDToTypeID( "FntN" );
                        desc140.putString( idFntN, "Myriad Pro" );
                        var idFntS = charIDToTypeID( "FntS" );
                        desc140.putString( idFntS, "Regular" );
                        var idScrp = charIDToTypeID( "Scrp" );
                        desc140.putInteger( idScrp, 0 );
                        var idFntT = charIDToTypeID( "FntT" );
                        desc140.putInteger( idFntT, 0 );
                        var idSz = charIDToTypeID( "Sz  " );
                        var idPnt = charIDToTypeID( "#Pnt" );
                        desc140.putUnitDouble( idSz, idPnt, 12.000000 );
                        var idHrzS = charIDToTypeID( "HrzS" );
                        desc140.putDouble( idHrzS, 100.000000 );
                        var idVrtS = charIDToTypeID( "VrtS" );
                        desc140.putDouble( idVrtS, 100.000000 );
                        var idsyntheticBold = stringIDToTypeID( "syntheticBold" );
                        desc140.putBoolean( idsyntheticBold, false );
                        var idsyntheticItalic = stringIDToTypeID( "syntheticItalic" );
                        desc140.putBoolean( idsyntheticItalic, false );
                        var idautoLeading = stringIDToTypeID( "autoLeading" );
                        desc140.putBoolean( idautoLeading, true );
                        var idTrck = charIDToTypeID( "Trck" );
                        desc140.putInteger( idTrck, 0 );
                        var idBsln = charIDToTypeID( "Bsln" );
                        var idPnt = charIDToTypeID( "#Pnt" );
                        desc140.putUnitDouble( idBsln, idPnt, 0.000000 );
                        var idcharacterRotation = stringIDToTypeID( "characterRotation" );
                        desc140.putDouble( idcharacterRotation, 0.000000 );
                        var idAtKr = charIDToTypeID( "AtKr" );
                        var idAtKr = charIDToTypeID( "AtKr" );
                        var idmetricsKern = stringIDToTypeID( "metricsKern" );
                        desc140.putEnumerated( idAtKr, idAtKr, idmetricsKern );
                        var idfontCaps = stringIDToTypeID( "fontCaps" );
                        var idfontCaps = stringIDToTypeID( "fontCaps" );
                        var idNrml = charIDToTypeID( "Nrml" );
                        desc140.putEnumerated( idfontCaps, idfontCaps, idNrml );
                        var idbaseline = stringIDToTypeID( "baseline" );
                        var idbaseline = stringIDToTypeID( "baseline" );
                        var idNrml = charIDToTypeID( "Nrml" );
                        desc140.putEnumerated( idbaseline, idbaseline, idNrml );
                        var idotbaseline = stringIDToTypeID( "otbaseline" );
                        var idotbaseline = stringIDToTypeID( "otbaseline" );
                        var idNrml = charIDToTypeID( "Nrml" );
                        desc140.putEnumerated( idotbaseline, idotbaseline, idNrml );
                        var idstrikethrough = stringIDToTypeID( "strikethrough" );
                        var idstrikethrough = stringIDToTypeID( "strikethrough" );
                        var idstrikethroughOff = stringIDToTypeID( "strikethroughOff" );
                        desc140.putEnumerated( idstrikethrough, idstrikethrough, idstrikethroughOff );
                        var idUndl = charIDToTypeID( "Undl" );
                        var idUndl = charIDToTypeID( "Undl" );
                        var idunderlineOff = stringIDToTypeID( "underlineOff" );
                        desc140.putEnumerated( idUndl, idUndl, idunderlineOff );
                        var idunderlineOffset = stringIDToTypeID( "underlineOffset" );
                        var idPnt = charIDToTypeID( "#Pnt" );
                        desc140.putUnitDouble( idunderlineOffset, idPnt, 0.000000 );
                        var idligature = stringIDToTypeID( "ligature" );
                        desc140.putBoolean( idligature, true );
                        var idaltligature = stringIDToTypeID( "altligature" );
                        desc140.putBoolean( idaltligature, false );
                        var idcontextualLigatures = stringIDToTypeID( "contextualLigatures" );
                        desc140.putBoolean( idcontextualLigatures, false );
                        var idalternateLigatures = stringIDToTypeID( "alternateLigatures" );
                        desc140.putBoolean( idalternateLigatures, false );
                        var idoldStyle = stringIDToTypeID( "oldStyle" );
                        desc140.putBoolean( idoldStyle, false );
                        var idfractions = stringIDToTypeID( "fractions" );
                        desc140.putBoolean( idfractions, false );
                        var idordinals = stringIDToTypeID( "ordinals" );
                        desc140.putBoolean( idordinals, false );
                        var idswash = stringIDToTypeID( "swash" );
                        desc140.putBoolean( idswash, false );
                        var idtitling = stringIDToTypeID( "titling" );
                        desc140.putBoolean( idtitling, false );
                        var idconnectionForms = stringIDToTypeID( "connectionForms" );
                        desc140.putBoolean( idconnectionForms, false );
                        var idstylisticAlternates = stringIDToTypeID( "stylisticAlternates" );
                        desc140.putBoolean( idstylisticAlternates, false );
                        var idornaments = stringIDToTypeID( "ornaments" );
                        desc140.putBoolean( idornaments, false );
                        var idfigureStyle = stringIDToTypeID( "figureStyle" );
                        var idfigureStyle = stringIDToTypeID( "figureStyle" );
                        var idNrml = charIDToTypeID( "Nrml" );
                        desc140.putEnumerated( idfigureStyle, idfigureStyle, idNrml );
                        var idproportionalMetrics = stringIDToTypeID( "proportionalMetrics" );
                        desc140.putBoolean( idproportionalMetrics, false );
                        var idkana = stringIDToTypeID( "kana" );
                        desc140.putBoolean( idkana, false );
                        var iditalics = stringIDToTypeID( "italics" );
                        desc140.putBoolean( iditalics, false );
                        var idruby = stringIDToTypeID( "ruby" );
                        desc140.putBoolean( idruby, false );
                        var idbaselineDirection = stringIDToTypeID( "baselineDirection" );
                        var idbaselineDirection = stringIDToTypeID( "baselineDirection" );
                        var idrotated = stringIDToTypeID( "rotated" );
                        desc140.putEnumerated( idbaselineDirection, idbaselineDirection, idrotated );
                        var idtextLanguage = stringIDToTypeID( "textLanguage" );
                        var idtextLanguage = stringIDToTypeID( "textLanguage" );
                        var idenglishLanguage = stringIDToTypeID( "englishLanguage" );
                        desc140.putEnumerated( idtextLanguage, idtextLanguage, idenglishLanguage );
                        var idmojiZume = stringIDToTypeID( "mojiZume" );
                        desc140.putDouble( idmojiZume, 0.000000 );
                        var idgridAlignment = stringIDToTypeID( "gridAlignment" );
                        var idgridAlignment = stringIDToTypeID( "gridAlignment" );
                        var idroman = stringIDToTypeID( "roman" );
                        desc140.putEnumerated( idgridAlignment, idgridAlignment, idroman );
                        var idenableWariChu = stringIDToTypeID( "enableWariChu" );
                        desc140.putBoolean( idenableWariChu, false );
                        var idwariChuCount = stringIDToTypeID( "wariChuCount" );
                        desc140.putInteger( idwariChuCount, 2 );
                        var idwariChuLineGap = stringIDToTypeID( "wariChuLineGap" );
                        desc140.putInteger( idwariChuLineGap, 0 );
                        var idwariChuScale = stringIDToTypeID( "wariChuScale" );
                        desc140.putDouble( idwariChuScale, 0.500000 );
                        var idwariChuWidow = stringIDToTypeID( "wariChuWidow" );
                        desc140.putInteger( idwariChuWidow, 2 );
                        var idwariChuOrphan = stringIDToTypeID( "wariChuOrphan" );
                        desc140.putInteger( idwariChuOrphan, 2 );
                        var idwariChuJustification = stringIDToTypeID( "wariChuJustification" );
                        var idwariChuJustification = stringIDToTypeID( "wariChuJustification" );
                        var idwariChuAutoJustify = stringIDToTypeID( "wariChuAutoJustify" );
                        desc140.putEnumerated( idwariChuJustification, idwariChuJustification, idwariChuAutoJustify );
                        var idtcyUpDown = stringIDToTypeID( "tcyUpDown" );
                        desc140.putInteger( idtcyUpDown, 0 );
                        var idtcyLeftRight = stringIDToTypeID( "tcyLeftRight" );
                        desc140.putInteger( idtcyLeftRight, 0 );
                        var idleftAki = stringIDToTypeID( "leftAki" );
                        desc140.putDouble( idleftAki, -1.000000 );
                        var idrightAki = stringIDToTypeID( "rightAki" );
                        desc140.putDouble( idrightAki, -1.000000 );
                        var idjiDori = stringIDToTypeID( "jiDori" );
                        desc140.putInteger( idjiDori, 0 );
                        var idnoBreak = stringIDToTypeID( "noBreak" );
                        desc140.putBoolean( idnoBreak, false );
                        var idClr = charIDToTypeID( "Clr " );
                            var desc141 = new ActionDescriptor();
                            var idRd = charIDToTypeID( "Rd  " );
                            desc141.putDouble( idRd, 0.000000 );
                            var idGrn = charIDToTypeID( "Grn " );
                            desc141.putDouble( idGrn, 0.000000 );
                            var idBl = charIDToTypeID( "Bl  " );
                            desc141.putDouble( idBl, 0.000000 );
                        var idRGBC = charIDToTypeID( "RGBC" );
                        desc140.putObject( idClr, idRGBC, desc141 );
                        var idstrokeColor = stringIDToTypeID( "strokeColor" );
                            var desc142 = new ActionDescriptor();
                            var idRd = charIDToTypeID( "Rd  " );
                            desc142.putDouble( idRd, 0.000000 );
                            var idGrn = charIDToTypeID( "Grn " );
                            desc142.putDouble( idGrn, 0.000000 );
                            var idBl = charIDToTypeID( "Bl  " );
                            desc142.putDouble( idBl, 0.000000 );
                        var idRGBC = charIDToTypeID( "RGBC" );
                        desc140.putObject( idstrokeColor, idRGBC, desc142 );
                        var idFl = charIDToTypeID( "Fl  " );
                        desc140.putBoolean( idFl, true );
                        var idStrk = charIDToTypeID( "Strk" );
                        desc140.putBoolean( idStrk, false );
                        var idfillFirst = stringIDToTypeID( "fillFirst" );
                        desc140.putBoolean( idfillFirst, true );
                        var idfillOverPrint = stringIDToTypeID( "fillOverPrint" );
                        desc140.putBoolean( idfillOverPrint, false );
                        var idstrokeOverPrint = stringIDToTypeID( "strokeOverPrint" );
                        desc140.putBoolean( idstrokeOverPrint, false );
                        var idlineCap = stringIDToTypeID( "lineCap" );
                        var idlineCap = stringIDToTypeID( "lineCap" );
                        var idbuttCap = stringIDToTypeID( "buttCap" );
                        desc140.putEnumerated( idlineCap, idlineCap, idbuttCap );
                        var idlineJoin = stringIDToTypeID( "lineJoin" );
                        var idlineJoin = stringIDToTypeID( "lineJoin" );
                        var idmiterJoin = stringIDToTypeID( "miterJoin" );
                        desc140.putEnumerated( idlineJoin, idlineJoin, idmiterJoin );
                        var idlineWidth = stringIDToTypeID( "lineWidth" );
                        var idPnt = charIDToTypeID( "#Pnt" );
                        desc140.putUnitDouble( idlineWidth, idPnt, 1.000000 );
                        var idmiterLimit = stringIDToTypeID( "miterLimit" );
                        var idPnt = charIDToTypeID( "#Pnt" );
                        desc140.putUnitDouble( idmiterLimit, idPnt, 4.000000 );
                        var idlineDashoffset = stringIDToTypeID( "lineDashoffset" );
                        desc140.putDouble( idlineDashoffset, 0.000000 );
                    var idTxtS = charIDToTypeID( "TxtS" );
                    desc139.putObject( iddefaultStyle, idTxtS, desc140 );
                var idparagraphStyle = stringIDToTypeID( "paragraphStyle" );
                desc138.putObject( idparagraphStyle, idparagraphStyle, desc139 );
            var idparagraphStyleRange = stringIDToTypeID( "paragraphStyleRange" );
            list21.putObject( idparagraphStyleRange, desc138 );
        desc128.putList( idparagraphStyleRange, list21 );
        var idkerningRange = stringIDToTypeID( "kerningRange" );
            var list22 = new ActionList();
        desc128.putList( idkerningRange, list22 );
    var idTxLr = charIDToTypeID( "TxLr" );
    desc127.putObject( idUsng, idTxLr, desc128 );
executeAction( idMk, desc127, DialogModes.NO );    
}

function getProceduralsFromSet(set)
{
    if(ProceduralSetData.setDefinitions.length == 0)
    {
        return [];
    }

    //get the hue list for the set required
    var procHuesList = null;
    for(var i=0; i<ProceduralSetData.setDefinitions.length; i++)
    {
            if(ProceduralSetData.setDefinitions[i].name == set)
            {
                    procHuesList = ProceduralSetData.setDefinitions[i].proceduralHue;
            }
    }
    
    var proceduralDefinitionsList = []
    if(procHuesList != null && procHuesList.length > 0)
    {
            for(var i=0; i < procHuesList.length; i++)
            {
                for(var k=0; k < ProceduralSetData.proceduralDefinitions.length; k++)
                {
                        if(procHuesList[i] == ProceduralSetData.proceduralDefinitions[k].hue)
                        {
                            proceduralDefinitionsList.push(ProceduralSetData.proceduralDefinitions[k]);
                        }
                }
            }
    }
    
    return proceduralDefinitionsList;
}    


//---------------------------   /FUNCTIONS --------------------------------------------

//--------- UI -----------------------------------------------------------------------------------------------

var toolWindow = new Window("dialog", "Procedural Map Preset");
toolWindow.Orientation="row";

var myMessage = toolWindow.add("statictext");
myMessage.text = "Procedural Working image";

var layerTree = toolWindow.add("listbox", [0, 0, 250, 200], getNiceNamesforLayers());

/*
layerTree.onChange = function()
{
		$.writeln("Selection has changed");
}
*/

//////////////////////////////////////////////////////////////////////////////////////////
// Create working Document
//////////////////////////////////////////////////////////////////////////////////////////
var setButton = toolWindow.add("button", undefined, "Import Layers ", {name:"ok"});
setButton.onClick = function()
{
    //var procDoc = app.documents.add();
    var procDoc = app.open(ProjectData.procEditFiles[0]);
    //figure out what size it should be from the procEditFiles
    
    
    //First add in the mask layers into thier own layer group    
    var maskLayerGroup = procDoc.layerSets.add();
    maskLayerGroup.name = "Masks";
    
    for(var i=0; i<ProjectData.maskFiles.length; i++)
    {
            var newLayer = procDoc.artLayers.add();
            
            //name the layer
            var nameFromFile = ((ProjectData.maskFiles[i].displayName).split("."))[0];
            newLayer.name = nameFromFile;
            
            openImageToLayer(ProjectData.maskFiles[i]);
            
            //move in to maskLayerGroup
            newLayer.move(maskLayerGroup, ElementPlacement.INSIDE);
    }
    
    //Add the edit layers
    for(var i=0; i<ProjectData.procEditFiles.length; i++)
    {
            var newLayer = procDoc.artLayers.add();
            
             //name the layer
            var nameFromFile = ((ProjectData.procEditFiles[i].displayName).split("."))[0];
            newLayer.name = nameFromFile;
    }
    //procDoc.layers.add()
    
    //copy the backGround to the top...
    var backGroundLayer = procDoc.artLayers.getByName("Background");
    backGroundLayer.copy();
    procDoc.paste();
    
    //.. and delete the first layer
    backGroundLayer.remove();
    
    
    //close the window
    toolWindow.close();
 };

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the colour swatch image for painting procedural sets
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var procSetsDropDownList = function()
{
    var theList = [];
    for(var i=0; i<ProceduralSetData.setDefinitions.length; i++)
    {
        theList.push(ProceduralSetData.setDefinitions[i].name);
    }

    return theList;
};

var swatchControlPanel = toolWindow.add('panel');
var procSetsDropDown = swatchControlPanel.add("dropdownlist", undefined, procSetsDropDownList());

//if we have some item in the dropdownlist then initially set the selection to the first item
if(procSetsDropDown.items.length != 0)
{
      procSetsDropDown.selection = 0;
}

var createSwatches = swatchControlPanel.add("button", undefined, "Create Swatches");
createSwatches.onClick = function()
{
    var procs = getProceduralsFromSet(procSetsDropDown.selection.text);
    
    //if we have no procs then theres now swatches to create, alert the user
    if(procs.length == 0)
    {
        alert("There are no procedural definitions for this set,\n No swatches to create", "Create Swatches");
        return;
    }
    
    //Create an image big enough to hold all the swatches
    //$.writeln(procs);
    var swatchImageHeight = (ProjectData.swatchItemHeight * procs.length) + ProjectData.swatchBorder;
    //$.writeln(ProjectData.swatchItemWidth);
    //$.writeln(swatchImageHeight);
    
    //Make sure ruler units are in pixels so we get the correct canvas size
    app.preferences.rulerUnits = Units.PIXELS;
    
    //create the image
    var swatchImage = app.documents.add(ProjectData.swatchItemWidth,  swatchImageHeight, 72, procSetsDropDown.selection.text);
    
    //for each item create a swatch colour and text for type
    var border = ProjectData.swatchBorder;
    for(var i=0; i<procs.length; i++)
    {
        //create the swatch
        app.foregroundColor.hsb.hue = parseInt(procs[i].hue);
        app.foregroundColor.hsb.saturation = 100;
         app.foregroundColor.hsb.brightness = 100;
       
        var top = (i * ProjectData.swatchSize) + (i * border) + border;
        var left = border;
        var bottom = top + ProjectData.swatchSize;
        var right = left + ProjectData.swatchSize;
        
        makeSwatch( top, left, bottom, right);

        //Now the descriptor
        makeSwatchDescriptor(procs[i].name.toString());
        
        //position it
        var textBounds = app.activeDocument.activeLayer.bounds;
        var deltaX = -textBounds[0] + right + border;
        var deltaY = -textBounds[1] + top + (0.5 * (bottom - top));
        app.activeDocument.activeLayer.translate(deltaX, deltaY);
    }
    
    //close the window
    toolWindow.close();
}

//////////////////////////////////////////////////////////////////////////////////////////
// Recombine working doc into the main image
//////////////////////////////////////////////////////////////////////////////////////////
var combineButton = toolWindow.add("button", undefined, "Re-Combine");
combineButton.onClick = function()
{
    var procPaintmasterMap = null;
    
    //load the master image, if its not open already
    var procPaintMasterMapIsLoaded = false;
    for(var i=0; i<app.documents.length; i++)
    {
            if(app.documents[i].name == "ProceduralSetMap.png")
            {
                    procPaintMasterMapIsLoaded = true;
                    procPaintmasterMap = app.documents[i];
            }
    }

    if( !procPaintMasterMapIsLoaded )
    {
        procPaintmasterMap = app.open( File(ProjectData.procPaintMasterMapPath) );
    }

    //get the bitmap pos from the tilePos
    var pos = getBitmapPosFromTileXy();

    //copy the region map into the master map
    var procDoc = app.documents.getByName(ProjectData.procEditFiles[0].displayName);
    app.activeDocument = procDoc;
    var topLayer = procDoc.artLayers[0];
    topLayer.copy();
    app.activeDocument = procPaintmasterMap;
    procPaintmasterMap.paste();
    
    //adjust the position
    moveSelection(procPaintmasterMap.artLayers[0], pos[0], pos[1]);

    //flatten the mega map
    

    //save it
    
     //close the window
    toolWindow.close();
}


//Show the UI
toolWindow.show();
