// ISO_SelectAlternatingLayers.jsx
// Artist: https://www.jasonfletcher.info/
// Code generated by ChatGPT-5.5 Mini
// Date: July 24, 2026
// Description: This After Effects script will select alternating layers in the active comp (using only the layers selected prior to running this script).

(function () {
    app.beginUndoGroup("Select Alternate Layers From Initial Selection");

    var processedCount = 0;
    var selectedCount = 0;
    var mode = "";

    try {
        var comp = app.project.activeItem;

        if (comp === null || !(comp instanceof CompItem)) {
            alert("Error:\n\nPlease open a composition and make it active before running this script.");
            return;
        }

        // Store the initially selected layers
        var initialSelection = [];

        for (var i = 1; i <= comp.numLayers; i++) {
            var currentLayer = comp.layer(i);

            if (currentLayer.selected) {
                initialSelection.push(currentLayer);
            }
        }

        if (initialSelection.length === 0) {
            alert("Error:\n\nPlease select at least one layer before running this script.");
            return;
        }

        var choice = prompt(
            "Select which alternating layers from the current selection?\n\n" +
            "A = Selected Layers 1, 3, 5, 7...\n" +
            "B = Selected Layers 2, 4, 6, 8...",
            "A"
        );

        if (choice === null) {
            return;
        }

        choice = choice.toUpperCase();

        if (choice !== "A" && choice !== "B") {
            alert("Invalid selection.\n\nPlease enter either A or B.");
            return;
        }

        mode = choice;

        // Clear current selection
        for (var j = 1; j <= comp.numLayers; j++) {
            comp.layer(j).selected = false;
        }

        // Determine starting index within the original selection array
        var startIndex = 0;

        if (choice === "B") {
            startIndex = 1;
        }

        // Select alternating layers from the original selection only
        for (var k = startIndex; k < initialSelection.length; k += 2) {

            var layer = initialSelection[k];

            if (layer !== null) {
                processedCount++;

                layer.selected = true;
                selectedCount++;
            }
        }

        alert(
            "Select Alternate Layers Complete.\n\n" +
            "Composition: " + comp.name + "\n" +
            "Selection Mode: " + mode + "\n" +
            "Initially Selected Layers: " + initialSelection.length + "\n" +
            "Layers Checked: " + processedCount + "\n" +
            "Layers Selected: " + selectedCount
        );

    } catch (err) {
        alert(
            "An error occurred:\n\n" +
            err.toString()
        );

    } finally {
        app.endUndoGroup();
    }

})();
