/*
ProjectItemsRenamer.jsx
version 1.7
(1.2 corrects unemptied variables, causing past renaming to be added to current operation)
(1.3 fixes evil while block with endless loop in some situations)
(1.4 fixes even more evil while block with endless loop. Sorry about that.)
(1.5 removes truncation for app version CS4 or later)
(1.6 search/replace now custom function, for various reasons, including my own mismanagement of files;
                                         the ultimate happy outcome is that renaming is now bug-free!)
 v1.7 replaces dangerous parseInts with parseFloats (because of radix feature in parseInt)
(by the guy who runs crgreen.com)
*/
var vers = '1.7';
var win = new Window('palette', 'Rename Project Items (v' + vers + ')',[300,100,645,362]);
var w = buildUI();
if (w != null) {
    w.show();
}

function buildUI() {
    if (win != null) {
        win.nameSearchLabel = win.add('statictext', [14,15,314,37], 'Search in Names:');
        win.nameSearchT = win.add('edittext', [25,40,325,62], '');
        win.nameReplaceLabel = win.add('statictext', [14,73,314,95], 'Replace with:');
        win.nameReplaceT = win.add('edittext', [25,98,325,120], '');
        win.typePnl = win.add('panel', [16,138,206,243], 'Rename Type:');
        
        win.repRad = win.typePnl.add('radiobutton', [14,13,174,35], 'Search and Replace');
        win.repRad.value = true;
        win.repRad.onClick = function () {
            doTextChange(win.nameSearchLabel, 'Search in Names:');
            doTextChange(win.nameReplaceLabel, 'Replace with:');
        };
        win.appRad = win.typePnl.add('radiobutton', [14,39,174,61], 'Append');
        win.appRad.onClick = function () {
            doTextChange(win.nameSearchLabel, 'Append Head with:');
            doTextChange(win.nameReplaceLabel, 'Append Tail with:');
        };
        win.remRad = win.typePnl.add('radiobutton', [14,65,174,87], 'Remove # of Characters');
        win.remRad.onClick = function () {
            doTextChange(win.nameSearchLabel, 'Remove this many chars from head (number):');
            doTextChange(win.nameReplaceLabel, 'Remove this many chars from tail (number):');
        };
        win.okBtn = win.add('button', [240,220,320,242], 'OK', {name:'OK'});
        win.okBtn.onClick = function () { doRenaming(this.parent); };
        
        win.cancBtn = win.add('button', [240,185,320,207], 'Close', {name:'Cancel'});
        win.cancBtn.onClick = function () {this.parent.close(1)};
    }
    return win
}

function doTextChange(target, newText) {
    target.text = newText;
}

function splitReplace(st, ss, rs) {
    var stArray = st.split(ss);
    var patchedString = "";
    var i = 0;
    while (i < (stArray.length)) {
        if (i == (stArray.length-1)) {rs = "";}
        patchedString = (patchedString + (stArray[i] + rs) );
        i = (i + 1);
    }
    return patchedString
}

function doRenaming(theDialog) {
    // make sure comps are selected
    var everyItem = app.project.items;
    selectedObs = new Array();
    for (var i = everyItem.length; i >= 1; i--) {
        eyeTem = everyItem[i];
        if (eyeTem.selected) {
            selectedObs[selectedObs.length] = eyeTem;
        }
    }
    
    if ( selectedObs.length == 0 ) {
        alert("No Project Items selected.");
    } else {
        var s = selectedObs;
        var selNum = s.length;
        
        app.beginUndoGroup("the renaming of project items");
        var inputError = false;
        
        for (var n = (selNum-1); n >= 0; n--) {
            if ( ! inputError ) {
                item = s[n];
                oldName = item.name;
                sear = theDialog.nameSearchT.text;
                repl = theDialog.nameReplaceT.text
                newName = oldName;
                
                if (theDialog.repRad.value) {
                    newName = splitReplace(newName, sear, repl);
                    if ((parseFloat(app.version) < 9.0)) {newName=(newName.substr(0,31));}
                } else if (theDialog.appRad.value) {
                    newName=(sear + oldName + repl );
                } else if (theDialog.remRad.value) {
                    if (sear == "") {sear = 0;}
                    if (repl == "") {repl = 0;}
                    sear = ( parseFloat(sear) );
                    repl = ( parseFloat(repl) );
                    if ( (isNaN(sear)) || (isNaN(repl)) ) {
                        alert('Error: Not a number?');
                        inputError = true;
                    } else {
                        newName=(newName.substr( sear, oldName.length-repl ));
                    }
                }
                //////////////////////
                try {
                    item.name = newName;
                } catch (error ) {
                    // just ignore errors; if it can't be named, what the hay
                }
                sear="";
                repl="";
                //////////////////////
            }
        }
        app.endUndoGroup();
    }
}

