~[if#page.modaccess]
<style>
#LoadListDiv {
    text-align: right;
    padding-bottom: 10px;
    padding-right: 50px;
    margin-top: -25px;
    font-size: 110%;
}
.lsDivMargin {
    margin-right: 10px;
    margin-bottom: 10px;
    margin-left: 10px;
}
.lsHidden {
    display: none;
}
#lsNewschoolCheckUl, #lsEditschoolCheckUl {
    column-count: 4;
    column-gap: 15px;
}
#lsNewschoolCheckUl li, #lsEditschoolCheckUl li {
    list-style-type: none;
}
optgroup:empty {
  display: none
}
a.disabled {
  pointer-events: none;
  cursor: default;
}
.schoolFilterRow {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 6px 0 12px 0;
    flex-wrap: wrap;
}
.schoolFilterInput {
    padding: 4px 8px;
    width: 320px;
    max-width: 100%;
    box-sizing: border-box;
}
.schoolCheckAllLabel {
    cursor: pointer;
    user-select: none;
}
.schoolCheckScroll {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 8px;
    background: #fff;
}
#lsSuccessBanner {
    max-width: 400px;
}
.lsListDescription {
    display: block;
    background: #f0f7ff;
    border-left: 4px solid #4a90c9;
    padding: 6px 12px;
    margin: 2px 4px;
    font-style: italic;
    color: #333;
}
</style>

<div id="lsToggleDiv" class="lsHidden" style="font-size: 110%;padding-bottom: 10px;">
    <a id="lsToggleSettings" class="button">~[text:nicktech.lsa.button.save_edit_list_set]</a>
</div>

<div id="lsSettingsDiv" class="lsHidden">
    <div class="box-round">
        <h2>~[text:nicktech.lsa.heading.edit_current]</h2>
        <div id="lsCurrentDiv" style="padding:10px"><strong>~[text:nicktech.lsa.label.current_list_set]</strong> <span id="lsCurrentName">~[text:nicktech.lsa.label.none_selected]</span></div>
        <div id="lsEditDiv" style="padding:10px">
            <a id="lsEditButton" class="button disabled">~[text:nicktech.lsa.button.update_current]</a> &nbsp;&nbsp;

            <a id="lsDelButton" class="button disabled">~[text:nicktech.lsa.button.delete_current]</a>
        </div>
        <div id="lsNameCurDiv" style="padding-top: 20px;" class="lsHidden lsDivMargin">
            <strong>~[text:nicktech.lsa.label.list_set_name_required]</strong> <input type="text" id="lsEdit_name" name="lsEdit_name" value="" size=30>
            <div style="padding-top: 10px;"><strong>~[text:nicktech.lsa.label.description_optional]</strong> <input type="text" id="lsEdit_description" name="lsEdit_description" value="" size=60 maxlength="500"></div>
        </div>
        <div id="lsEditSchoolChecksDiv" class="lsHidden">
            <div id="lsEditSchoolNoteDiv" class="feedback-note schoolAccess">~[text:nicktech.lsa.feedback.school_only_available] ~(schoolname)</div>
            <div class="lsDivMargin districtAccess">
                <strong>~[text:nicktech.lsa.label.make_available_under]</strong>
                <div class="schoolFilterRow">
                    <input type="text" class="schoolFilterInput" placeholder="~[text:nicktech.lsa.placeholder.filter_schools]" aria-label="~[text:nicktech.lsa.placeholder.filter_schools]">
                    <label class="schoolCheckAllLabel">
                        <input type="checkbox" name="allSchoolCheck" value="" id="lsEditallSchoolCheck" class="allSchoolCheck"> <em><span class="schoolCheckAllText">~[text:nicktech.lsa.toggle.check_all]</span></em>
                    </label>
                </div>
                <div class="schoolCheckScroll">
                    <ul id="lsEditschoolCheckUl">
                        <li class="schoolCheckDiv"><input type="checkbox" id="lsEdit_check0" name="check0" value="0" class="schoolCheck" data-schoolabv="District"> ~[text:nicktech.lsa.school.district_office]</li>
                        ~[tlist_sql;
                        SELECT school_number,ABBREVIATION,name
                        FROM schools
                        ORDER BY name;]
                        <li class="schoolCheckDiv"><input type="checkbox" id="lsEdit_check~(school_number)" name="check~(school_number)" value="~(school_number)" class="schoolCheck" data-schoolabv="~(ABBREVIATION)"> ~(name)</li>
                        [/tlist_sql]
                    </ul>
                </div>
                <div id="editSchoolWarn" class="feedback-alert schoolWarn lsHidden">~[text:nicktech.lsa.feedback.school_warn]</div>
            </div>
        </div>

        <div id="lsDeleteDiv" class="feedback-alert lsHidden">~[text:nicktech.lsa.feedback.delete_confirm]</div>
        <div id="lsSubmitCurDiv" class="button-row lsHidden"><a id="lsCurSubmit" class="button">~[text:nicktech.lsa.button.submit]</a></div>
        <div id="lsSubmitDelDiv" class="button-row lsHidden"><a id="lsDelSubmit" class="button">~[text:nicktech.lsa.button.confirm_delete]</a></div>

    </div><!-- end box-round -->
    <div class="box-round">
        <h2>~[text:nicktech.lsa.heading.create_new]</h2>
        <div id="lsNewDiv" style="padding:10px">
            <a id="lsNewPerButton" class="button">~[text:nicktech.lsa.button.save_new_personal]</a> &nbsp;&nbsp;

            <a id="lsNewSchButton" class="disabled button">~[text:nicktech.lsa.button.save_new_school]</a>
        </div>

        <div id="lsNewNameDiv" style="padding-top: 20px;" class="lsHidden lsDivMargin">
            <strong><span id="lsNewNameLabel"></span> ~[text:nicktech.lsa.label.list_set_name_required]</strong> <input type="text" id="lsNew_name" name="lsNew_name" value="" size=30>
            <div style="padding-top: 10px;"><strong>~[text:nicktech.lsa.label.description_optional]</strong> <input type="text" id="lsNew_description" name="lsNew_description" value="" size=60 maxlength="500"></div>
        </div>
        <div id="lsNewSchoolChecksDiv" class="lsHidden">
            <div id="lsNewSchoolNoteDiv" class="feedback-note schoolAccess">~[text:nicktech.lsa.feedback.school_only_available] ~(schoolname)</div>
            <div class="lsDivMargin districtAccess">
                <strong>~[text:nicktech.lsa.label.make_available_under]</strong>
                <div class="schoolFilterRow">
                    <input type="text" class="schoolFilterInput" placeholder="~[text:nicktech.lsa.placeholder.filter_schools]" aria-label="~[text:nicktech.lsa.placeholder.filter_schools]">
                    <label class="schoolCheckAllLabel">
                        <input type="checkbox" name="allSchoolCheck" value="" id="lsNewallSchoolCheck" class="allSchoolCheck"> <em><span class="schoolCheckAllText">~[text:nicktech.lsa.toggle.check_all]</span></em>
                    </label>
                </div>
                <div class="schoolCheckScroll">
                    <ul id="lsNewschoolCheckUl">
                        <li class="schoolCheckDiv"><input type="checkbox" id="lsNew_check0" name="check0" value="0" class="schoolCheck" data-schoolabv="District"> ~[text:nicktech.lsa.school.district_office]</li>
                        ~[tlist_sql;
                        SELECT school_number,ABBREVIATION,name
                        FROM schools
                        ORDER BY name;]
                        <li class="schoolCheckDiv"><input type="checkbox" id="lsNew_check~(school_number)" name="check~(school_number)" value="~(school_number)" class="schoolCheck" data-schoolabv="~(ABBREVIATION)"> ~(name)</li>
                        [/tlist_sql]
                    </ul>
                </div>
                <div id="newSchoolWarn" class="feedback-alert schoolWarn lsHidden">~[text:nicktech.lsa.feedback.school_warn]</div>
            </div>
        </div><!-- end lsNewSchoolChecksDiv -->

        <div id="lsPerSubmitDiv" class="button-row lsHidden"><a id="lsPerSubmit" class="button">~[text:nicktech.lsa.button.submit]</a></div>
        <div id="lsSchSubmitDiv" class="button-row lsHidden"><a id="lsSchSubmit" class="button">~[text:nicktech.lsa.button.submit]</a></div>
    </div><!-- end box-round -->
</div><!-- end lsSettingsDiv -->

<!-- warn if don't have permission to the helper page -->
<div id="lsDenyDiv" class="lsHidden feedback-error">
~[text:nicktech.lsa.error.modify_access_denied_student]
</div>

<div id="lsAutoLoadDiv" class="lsHidden">
    <div id="LoadListDiv" class="bold">
        ~[text:nicktech.lsa.label.load_list] <select name="loadlist" id="loadlist" onChange="loadlistfunc()">
                <option value="" selected></option>
                <optgroup label="~[text:nicktech.lsa.optgroup.district_school]">
                    ~[tlist_sql;
                    SELECT 
                        id, 
                        list_schools, 
                        list_schools_abv, 
                        list_description,
                        list_name
                    FROM U_LS_AUTOLOAD
                    WHERE ','|| list_schools ||',' like '%,'||'~(curschoolid)'||',%'
                        AND list_personal is null
                    ORDER BY list_name;]
                    <option value="~(id)" data-listtype="school" data-schools="~(list_schools)" data-schoolsabv="~(list_schools_abv)" data-description="~(list_description;html)">~(name)</option>
                    [/tlist_sql]
                </optgroup>
                <optgroup label="~[text:nicktech.lsa.optgroup.personal]">
                    ~[tlist_sql;
                    SELECT 
                        id, 
                        list_description,
                        list_name
                    FROM U_LS_AUTOLOAD
                    WHERE list_personal = ~[x:users_dcid]
                    ORDER BY list_name;]
                    <option value="~(id)" data-listtype="personal" data-schools="" data-schoolsabv="" data-description="~(list_description;html)">~(name)</option>
                    [/tlist_sql]
                    </optgroup>
                    ~[if#manage.~(gpv.mode)=manage]
                    <optgroup label="~[text:nicktech.lsa.optgroup.currently_managing]">
                        ~[tlist_sql;
                        SELECT 
                            id, 
                            list_schools, 
                            list_schools_abv, 
                            list_description,
                            list_name
                        FROM U_LS_AUTOLOAD
                        WHERE id = ~(gpv.listid;sqlText)
                        AND list_personal is null
                        AND 'manage' = '~(gpv.mode;sqlText)'
                        ORDER BY list_name;]
                        <option value="~(id)" data-listtype="school" data-schools="~(list_schools)" data-schoolsabv="~(list_schools_abv)" data-description="~(list_description;html)">~(name)</option>
                        [/tlist_sql]
                </optgroup>
                [/if#manage]
        </select>
    </div>
</div>
<div id="lsTipsDiv" class="lsHidden">
    <a class="dialogDivM lsTipsLink" title="Tips and Tricks" href="#lsTips" style="margin-left:10px">Tips and Tricks</a>
    <div class="hide" id="lsTips" style="max-width: 900px;">
        <h2>Did you know you can include these in a custom list?</h2>
        <table class="grid">
            <thead>
                <tr>
                    <th>Example Field Name</th>
                    <th>Example Result</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>studentphoto</td>
                    <td><img src="/images/lsExamplePhoto.jpeg"></td>
                    <td>Include the student's photo in your list.</td>
                </tr>
                <tr>
                    <td>age</td>
                    <td>15 years and 6 months</td>
                    <td>Include the student's age in your list.</td>
                </tr>
                <tr>
                    <td>first_name) ^(last_name</td>
                    <td>Pugsley Addams</td>
                    <td>Combine multiple fields into a single column using the pattern: field1) ^(field2</td>
                </tr>
                <tr>
                    <td>street)&lt;br&gt;^(city), ^(state) ^(zip</td>
                    <td>123 Pretend St.<br>Chicago, IL 60053</td>
                    <td>Combine multiple fields and include a line break (&lt;br&gt;).</td>
                </tr>
                <tr>
                    <td>decode;^(grade_level);-2;PK3;-1;PK4;0;K;^(grade_level)</td>
                    <td>K</td>
                    <td>You can use a DECODE to transform values.<br>In the form of: decode;^(field_name);value1;Display This1;value2;Display This2;Else Display This</td>
                </tr>
                <tr>
                    <td>decode;;;Some Text</td>
                    <td>Some Text</td>
                    <td>Interesting use of the DECODE tag is to spit out a static piece of text.<br>For example, you want the first column to contain a checkbox. You can get pretty close using: decode;;;[ ]</td>
                </tr>
                <tr>
                    <td>*DA;T1</td>
                    <td>57.50</td>
                    <td>Display daily attendance for a specified term (*DA;T1 would be for the term "T1")<br>This can only be used at the school level, not district office.</td>
                </tr>
                <tr>
                    <td>*DABS;T1</td>
                    <td>6.50</td>
                    <td>Display daily absences for a specified term (*DA;T1 would be for the term "T1")<br>This can only be used at the school level, not district office.</td>
                </tr>
                <tr>
                    <td>*gpa method=&quot;your_gpa_method&quot;</td>
                    <td>4.00</td>
                    <td>You can list a student's GPA.<br>You just need to know the name of the GPA method your district has setup (ex. "Weighted").</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<script>
// can this user edit lists (returns school/district/null)
~[tlist_sql;
SELECT allow_autolistschool
FROM GEN
JOIN U_LS_AUTOLOAD_GEN_EXT on gendcid = gen.dcid
WHERE cat = 'groups'
AND id IN (~[x:usersroles])
ORDER BY CASE WHEN allow_autolistschool = 'district' THEN 1 ELSE 2 END
fetch first 1 rows only
;nonemessage=let editSchools = '']
let editSchools = '~(value)';
[/tlist_sql]

~[if#help.security.pagemod=/admin/studentlist/studentlist1.html]
$j(document).ready(function(){
    // move list select into place
    var loadHTML = $j('#lsAutoLoadDiv').html();
    $j('#lsAutoLoadDiv').remove();
    $j('#content-main div.box-round').first().before(loadHTML);

    // move Tips and Tricks into place
    var loadTips = $j('#lsTipsDiv').html();
    $j('#lsTipsDiv').remove();
    $j('td:contains("Report Title")').find('input').after(loadTips);
    
    // move settings button
    var myDiv = $j('#lsToggleDiv');
    $j('#content-main div.box-round').first().append(myDiv);
    $j(myDiv).show();
    
    // add in IDs and classes that should already be there PS developers!
    $j('#content-main').find('input:visible').addClass('listField');
    $j('#content-main').find('select:visible').addClass('listField');
    $j('td:contains("Report Title")').find('input').attr('id', 'LSreportTitle');
    $j('input[id^="tt"]').each(function(){
      $j(this).closest('td').next('td').find('input').attr('id', 'LStitle' + this.id);
    });
    $j('td:contains("Padding In Each Cell")').next('td').find('input').attr('id', 'LSpadding');
    $j('td:contains("# Rows In Between Breaks")').next('td').find('input').attr('id', 'LSrowsBetween');
    $j('td:contains("Gridlines")').find('input:visible').first().attr('id', 'LSgridlines');
    $j('td:contains("Gridlines")').find('input:visible').last().attr('id', 'LSexport');
    $j('td:contains("Sort Field Name")').closest('tr').next('tr').find('td').first().find('input').attr('id', 'LSsort1');
    $j('td:contains("Sort Field Name")').closest('tr').next('tr').find('td').last().find('select').attr('id', 'LSdirection1');
    $j('#LSsort1').closest('tr').next('tr').find('td').first().find('input').attr('id', 'LSsort2');
    $j('#LSsort1').closest('tr').next('tr').find('td').last().find('select').attr('id', 'LSdirection2');
    $j('#LSsort2').closest('tr').next('tr').find('td').first().find('input').attr('id', 'LSsort3');
    $j('#LSsort2').closest('tr').next('tr').find('td').last().find('select').attr('id', 'LSdirection3');
    
    // form container div out of the main form (where ajax puts form)
    $j('body').append('<div id="lsFormDiv" class="lshidden"></div>');
        
    // enable save school/district buttons and divs if allowed
    if(editSchools == '') {
        $j('#lsNewSchButton').hide();
    }
    ~[if#sch.is.a.school]
    if(editSchools == 'school' || editSchools == 'district') {
        $j('#lsNewSchButton').removeClass('disabled');
    }
    [else#sch]
    if(editSchools == 'district') {
        $j('#lsNewSchButton').removeClass('disabled');
    }
    [/if#sch]
    
    if(editSchools == 'school') {
        $j('.schoolAccess').show();
        $j('.districtAccess').hide();
    } else if(editSchools == 'district') {
        $j('.districtAccess').show();
        $j('.schoolAccess').hide();
    } else {
        $j('#lsEditSchoolChecksDiv').remove();
        $j('#lsNewSchoolChecksDiv').remove();
    }
    
    // trigger these keyups so the replacements happen when you use the back button after runnning a list
    $j("input:text").trigger("keyup");

    // load list if gpv
    ~[if#load.~(gpv.listid)=][else#load]
    var listID = ~(gpv.listid;encodejsstring);
    $j('#loadlist').val(listID);
    $j('#loadlist').trigger('change');
    [/if#load]
    
    // add note to the page permission "gold bar" 
    ~[if#pagemod.modifypagepermissions]
    $j('#pageLevelModAccess').append('<div id="modAccessAdd">MODIFY PERMISSIONS TO THE <a href="/admin/security/modaccess.html?path=studentlist/studentlistauto_helper.html">LIST STUDENTS AUTO-LOADER "HELPER" PAGE</a>, IN ADDITION TO THIS PAGE, TO INSURE EDITING LIST SETS CONTINUE WORKING</div>');
    [/if#pagemod]
}); // end doc ready
[/if#help]

// "~" doesn't seem to work will with JSON parsing
$j("input:text").keyup(function() {
    $j(this).val($j(this).val().replaceAll("~","^"));
});

// warn that list wont be available under the current school
$j('.schoolCheck').on('change', function(){
 if($j(this).closest('div.districtAccess').find('input.schoolCheck[value="~(curschoolid)"]').is(':checked')){
    $j(this).closest('div.districtAccess').find('.schoolWarn').fadeOut();
 } else {
    $j(this).closest('div.districtAccess').find('.schoolWarn').fadeIn();
 }
});

// clear all values and hide the save/edit fields/buttons
function resetForm($form)
{
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').prop('checked', false).prop('selected', false);
    $j('#lsSchSubmitDiv, #lsSubmitCurDiv, #lsNameCurDiv, #lsDeleteDiv, #lsSubmitDelDiv, #lsNewSchoolChecksDiv, #lsEditSchoolChecksDiv, #lsNewNameDiv, #lsPerSubmitDiv').hide();
}

// populate the form from JSON values
function populateForm($form, data)
{
    resetForm($form);
    $j.each(data, function(key, value) {
        var $ctrl = $form.find('[id='+key+']');
        if ($ctrl.is('select')){
            $j('option', $ctrl).each(function() {
                if (this.value == value)
                    this.selected = true;
            });
        } else if ($ctrl.is('textarea')) {
            $ctrl.val(value);
        } else {
            switch($ctrl.attr("type")) {
                case "text":
                case "hidden":
                    $ctrl.val(value);   
                    break;
                case "checkbox":
                    if (value == '1')
                        $ctrl.prop('checked', true);
                    else
                        $ctrl.prop('checked', false);
                    break;
            } 
        }
    });
} // end of populateForm() function 

// function to run when load list select changes
function loadlistfunc() 
{	
    var loadListID = $j('#loadlist').val();
    var loadListName = $j("#loadlist option:selected").text();
    var loadListType = $j("#loadlist option:selected").data('listtype');
    var listSchools = $j("#loadlist option:selected").data('schools');
    var listSchoolsAbv = $j("#loadlist option:selected").data('schoolsabv');
    var pageInner = $j('#content-main div.box-round').first();
    var url = 'studentlistauto_JSON.html?editID=' + loadListID;
        
    if(loadListID === ""){
        resetForm(pageInner);
    } else {    
        $j.get(url, function(data){
            var listDataPre = data.replaceAll("\\\\","\\");
            var listData = JSON.parse(listDataPre);
            populateForm(pageInner, listData);
        });
        
        // enable/disable the save/delete current list buttons
        if(loadListType == 'school' && listSchools == '~(curschoolid)' && ~[if#sch.is.a.school](editSchools == 'school' || editSchools == 'district')[else#sch]editSchools == 'district'[/if#sch]) {
            $j('#lsEditDiv a.button').removeClass('disabled');
        } else if(loadListType == 'school' && editSchools == 'district') {
            $j('#lsEditDiv a.button').removeClass('disabled');
        } else if(loadListType == 'personal') {
            $j('#lsEditDiv a.button').removeClass('disabled');
        } else {
            $j('#lsEditDiv a.button').addClass('disabled');
            $j('#lsNameCurDiv').hide();
            $j('#lsSubmitCurDiv').hide();
            $j('#lsEditSchoolChecksDiv').hide();
        }
        
        if (loadListType == 'school' && typeof listSchools == "string") {
            var displayType = 'multiple schools';
        } else if (loadListType == 'school') {
            var displayType = 'single school';
        } else {
            var displayType = 'personal';
        }
        $j('#lsCurrentName').text(loadListName + ' (type: ' + displayType + ')');
        $j('#lsEdit_name').val(loadListName);
        $j('#lsEdit_description').val($j("#loadlist option:selected").data('description') || '');
    
        // check schools in list_schools if 
        if (editSchools == 'district' && loadListType == 'school'){
            if (typeof listSchools == "string") {
                var schoolArray = listSchools.split(",");
                $j('#lsEditSchoolChecksDiv .schoolCheck').each(function(index) {
                    var val = $j(this).val();
                    if (schoolArray.includes(val)) {
                      $j(this).prop('checked', true);
                    }
                });
            } else {
                $j('#lsEditSchoolChecksDiv input.schoolCheck[value="' + listSchools + '"]').prop('checked', true);
            }
        }
    }
    lsShowListDescription($j("#loadlist option:selected").data('description') || '');
} // end of loadlistfunc() function

function saveValues(lstype)
{
    // construct JSON of list inputs
    var listData = {};
    $j('.listField').each(function() {
      if ($j(this).prop('type') == 'checkbox' && $j(this).prop('checked') == true){
          listData[this.id] = "1";
      } else if ($j(this).prop('type') == 'checkbox' && $j(this).prop('checked') == false){
          listData[this.id] = "0";
      } else {
          listData[this.id] = this.value;
      }
    });
    var listJsonPre = JSON.stringify(listData);
    var listJson = listJsonPre.replaceAll("\\","\\\\");
    $j('#list_data').val(listJson);
    //var listJson = JSON.stringify({ MyList: listData });
    //console.log(listJson);
    
    // join checked schools
    if(lstype !== 'personal') {
        if(editSchools == 'school' && ~(curschoolid) !== 0 && lstype) {
            $j('#list_schools').val('~(curschoolid)');
            $j('#list_schools_abv').val("~(schoolabbr)");
        } else if (editSchools == 'district') {
            if(lstype === 'edit'){
                var checksArray = $j('#lsEditSchoolChecksDiv input.schoolCheck:checked').map(function () {  
                return this.value;
                }).get().join(",");
                $j('#list_schools').val(checksArray);
                // save abv value for display on manage lists
                var numberOfChecked = $j('#lsEditSchoolChecksDiv input.schoolCheck:checked').length;
                var totalCheckboxes = $j('#lsEditSchoolChecksDiv input.schoolCheck').length;
                if (numberOfChecked === totalCheckboxes) {
                    $j('#list_schools_abv').val('All');
                } else {
                    var checksArrayAbv = $j('#lsEditSchoolChecksDiv input.schoolCheck:checked').map(function () {  
                    return $j(this).data('schoolabv');
                    }).get().join(",");
                    $j('#list_schools_abv').val(checksArrayAbv);
                }
            } else if(lstype === 'new'){
                var checksArray = $j('#lsNewSchoolChecksDiv input.schoolCheck:checked').map(function () {  
                return this.value;
                }).get().join(",");
                $j('#list_schools').val(checksArray);
                // save abv value for display on manage lists
                var numberOfChecked = $j('#lsNewSchoolChecksDiv input.schoolCheck:checked').length;
                var totalCheckboxes = $j('#lsNewSchoolChecksDiv input.schoolCheck').length;
                if (numberOfChecked === totalCheckboxes) {
                    $j('#list_schools_abv').val('All');
                } else {
                    var checksArrayAbv = $j('#lsNewSchoolChecksDiv input.schoolCheck:checked').map(function () {  
                    return $j(this).data('schoolabv');
                    }).get().join(",");
                    $j('#list_schools_abv').val(checksArrayAbv);
                }
            }
        }
    }
    // copy the description from whichever name div is currently visible
    if ($j('#lsEdit_description').is(':visible')){
        $j('#list_description').val($j.trim($j('#lsEdit_description').val()));
    } else if ($j('#lsNew_description').is(':visible')){
        $j('#list_description').val($j.trim($j('#lsNew_description').val()));
    }
} // end of saveValues() function

function scrollToBottom(id){
    var el = document.getElementById(id);
    if (!el) return;
    // double rAF defers the scroll until AFTER the next layout/paint —
    // Chrome occasionally misses the first scrollIntoView when called from a slideDown callback
    // because the new element height hasn't been committed to the rendering pipeline yet.
    requestAnimationFrame(function(){
        requestAnimationFrame(function(){
            el.scrollIntoView({ behavior: 'smooth', block: 'center' });
        });
    });
}

// inject the selected list set's description into the spacer cell under the report title
function lsShowListDescription(text){
    var $cell = $j('#aForm .box-round > table > tbody > tr').eq(1).find('td[colspan="4"]').first();
    if (!$cell.length) return;
    if (text){
        $cell.empty().append($j('<div class="lsListDescription"></div>').text(text));
    } else {
        $cell.html('&nbsp;');
    }
}

// update the "ALL/FILTERED SCHOOLS" toggle label based on filter and checkbox state
function updateAllSchoolsLabel($scope){
    var hasFilter = $j.trim($scope.find('.schoolFilterInput').val()).length > 0;
    var isChecked = $scope.find('.allSchoolCheck').prop('checked');
    var labels = {
        check_all: "~[text:nicktech.lsa.toggle.check_all]",
        uncheck_all: "~[text:nicktech.lsa.toggle.uncheck_all]",
        check_filtered: "~[text:nicktech.lsa.toggle.check_filtered]",
        uncheck_filtered: "~[text:nicktech.lsa.toggle.uncheck_filtered]"
    };
    var key = (isChecked ? 'uncheck_' : 'check_') + (hasFilter ? 'filtered' : 'all');
    $scope.find('.schoolCheckAllText').text(labels[key]);
}

// place a banner above #LoadListDiv when present, else fall back h1
function lsPlaceTopBanner($banner){
    var $target = $j('#LoadListDiv');
    if ($target.length){
        $banner.insertBefore($target);
    } else {
        $banner.insertAfter('h1:first:visible');
    }
}

// show a persistent error banner inline next to the triggering button (does not auto-fade);
// falls back to above #LoadListDiv if no button is provided
function lsShowError(msg, $button){
    $j('#lsErrorBanner').remove();
    var $banner;
    if ($button && $button.length){
        $banner = $j('<span id="lsErrorBanner" class="feedback-alert"></span>')
            .text(msg)
            .css({display: 'inline-block', marginRight: '10px', verticalAlign: 'middle'});
        $banner.insertBefore($button);
    } else {
        $banner = $j('<div id="lsErrorBanner" class="feedback-alert"></div>').text(msg);
        lsPlaceTopBanner($banner);
        if ($banner[0] && $banner[0].scrollIntoView){
            $banner[0].scrollIntoView({behavior: 'smooth', block: 'center'});
        }
    }
}

// show a success banner above #LoadListDiv that fades out after 3s
function lsShowSuccess(msg){
    $j('#lsSuccessBanner').remove();
    var $banner = $j('<div id="lsSuccessBanner" class="feedback-confirm"></div>').text(msg);
    lsPlaceTopBanner($banner);
    setTimeout(function(){
        $banner.animate({opacity: 0}, 500, function(){ $j(this).remove(); });
    }, 3000);
}

// focus trap helpers — keep Tab/Shift+Tab inside the settings panel while it's open
function lsGetFocusable($container){
    return $container
        .find('input:visible, select:visible, textarea:visible, button:visible, a[href]:visible, [tabindex]:visible')
        .filter(':not(:disabled):not(.disabled)');
}
function lsActivateFocusTrap($container){
    // make a.button elements focusable while the panel is open
    $container.find('a.button').not('.disabled').attr('tabindex', '0');
    var $focusable = lsGetFocusable($container);
    if ($focusable.length){
        $focusable.first().focus();
    } else {
        $container.attr('tabindex', '-1').focus();
    }
    $j(document).on('keydown.lsFocusTrap', function(e){
        if (!$container.is(':visible')) return;
        if (e.key === 'Escape'){
            $j('#lsToggleSettings').click();
            return;
        }
        if (e.key !== 'Tab') return;
        var $visible = lsGetFocusable($container);
        if (!$visible.length) return;
        var $first = $visible.first();
        var $last = $visible.last();
        // pull focus back into the panel if it leaked out
        if (!$j.contains($container[0], document.activeElement)){
            $first.focus();
            e.preventDefault();
            return;
        }
        if (e.shiftKey && document.activeElement === $first[0]){
            $last.focus();
            e.preventDefault();
        } else if (!e.shiftKey && document.activeElement === $last[0]){
            $first.focus();
            e.preventDefault();
        }
    });
}
function lsDeactivateFocusTrap($container){
    $j(document).off('keydown.lsFocusTrap');
    $container.find('a.button[tabindex="0"]').removeAttr('tabindex');
    $container.removeAttr('tabindex');
    $j('#lsToggleSettings').focus();
}

// show/hide settings div
$j('#lsToggleSettings').on('click', function(){
    // warning if don't have mod access to helper page, else
    ~[if#help.security.pagemod=/admin/studentlist/studentlistauto_helper.html]
    $j('#lsSettingsDiv').slideToggle('fast', function() {
        var $panel = $j('#lsSettingsDiv');
        if ($panel.is(':visible')) {
            // reset the school filter so stale text doesn't carry between toggles
            $panel.find('.schoolFilterInput').val('');
            $panel.find('li.schoolCheckDiv').show();
            $panel.find('.districtAccess').each(function(){ updateAllSchoolsLabel($j(this)); });
            scrollToBottom('lsSettingsDiv');
            lsActivateFocusTrap($panel);
        } else {
            lsDeactivateFocusTrap($panel);
        }
    });
    [else#help]
    ~[if#help2.security.pagemod=/admin/studentlist/studentlist1.html]
    $j('#lsDenyDiv').slideToggle('fast', function() {
        if ($j('#lsDenyDiv').is(':visible')) {
            scrollToBottom('lsDenyDiv');
        }
    });
    [/if#help2]
    [/if#help]
});
    
// show/hide extra form values based on button clicked
$j('#lsNewPerButton').on('click', function(){
    $j('#lsNewNameLabel').text("~[text:nicktech.lsa.label.name_type_personal]");
    $j('#lsNewNameDiv').slideDown('fast', function() {
        $j('#lsPerSubmitDiv').show();
        scrollToBottom('lsPerSubmitDiv');
    });
    $j('#lsSchSubmitDiv, #lsSubmitCurDiv, #lsNameCurDiv, #lsDeleteDiv, #lsSubmitDelDiv, #lsNewSchoolChecksDiv, #lsEditSchoolChecksDiv').hide();
});
$j('#lsNewSchButton').on('click', function(){
    $j('#lsNewNameLabel').text("~[text:nicktech.lsa.label.name_type_school]");
    $j('#lsNewNameDiv').slideDown('fast', function() {
        $j('#lsSchSubmitDiv').show();
        $j('#lsNewSchoolChecksDiv').show();
        scrollToBottom('lsSchSubmitDiv');
    });
    $j('#lsPerSubmitDiv, #lsSubmitCurDiv, #lsNameCurDiv, #lsSubmitDelDiv, #lsDeleteDiv, #lsEditSchoolChecksDiv').hide();
});
$j('#lsEditButton').on('click', function(){
    $j('#lsNameCurDiv').slideDown('fast', function() {
        $j('#lsSubmitCurDiv').show();
        scrollToBottom('lsSubmitCurDiv');
        $j('.schoolCheck:visible').first().trigger('change');
    });
    var loadListType = $j("#loadlist option:selected").data('listtype');
    if(loadListType == 'school') {
        $j('#lsEditSchoolChecksDiv').slideDown('fast', function() {
            scrollToBottom('lsEditSchoolChecksDiv');
        });
    } else {
        $j('#lsEditSchoolChecksDiv').hide();
    }
    $j('#lsSchSubmitDiv, #lsPerSubmitDiv, #lsDeleteDiv, #lsSubmitDelDiv, #lsNewNameDiv, #lsNewSchoolChecksDiv').hide();
});
$j('#lsDelButton').on('click', function(){
    $j('#lsDeleteDiv').slideDown('fast', function() {
        $j('#lsSubmitDelDiv').show();
        scrollToBottom('lsSubmitDelDiv');
    });
    $j('#lsSchSubmitDiv, #lsSubmitCurDiv, #lsNameCurDiv, #lsNewNameDiv, #lsEditSchoolChecksDiv, #lsNewSchoolChecksDiv').hide();
});

// toggle all school checkboxes using "all schools" (respects active filter — only affects visible rows)
$j('.allSchoolCheck').on('change', function(){
    var $scope = $j(this).closest('div.districtAccess');
    var checked = $j(this).prop('checked') == true;
    $scope.find('input.schoolCheck:visible').prop('checked', checked);
    $scope.find('input.schoolCheck:visible').first().trigger('change');
    updateAllSchoolsLabel($scope);
})

// filter school checkboxes by typed text
$j('.schoolFilterInput').on('keyup', function(){
    var query = $j.trim($j(this).val()).toLowerCase();
    var $container = $j(this).closest('div.districtAccess');
    $container.find('li.schoolCheckDiv').each(function(){
        if (query === '' || $j(this).text().toLowerCase().indexOf(query) > -1) {
            $j(this).show();
        } else {
            $j(this).hide();
        }
    });
    // a filter change invalidates the "all/filtered" toggle — uncheck so the label always reflects reality
    $container.find('.allSchoolCheck').prop('checked', false);
    updateAllSchoolsLabel($container);
})

// set initial "ALL SCHOOLS" toggle labels
$j('.districtAccess').each(function(){
    updateAllSchoolsLabel($j(this));
});

// save new personal list
$j('#lsPerSubmit').on('click', function(){
    var $btn = $j(this);
    if ($j.trim($j('#lsNew_name').val()).length > 0){
        var listName = $j.trim($j('#lsNew_name').val());
        loadingDialog();
        $j.ajax({
            type: 'POST',
            url: 'studentlistauto_helper.html?authId=-1',
            success: function(results){
                $j('#lsFormDiv').append(results);
                if ($j('#lsFormDiv form').length === 0){
                    closeLoading();
                    lsShowError("~[text:nicktech.lsa.error.save_denied]", $btn);
                    return;
                }
                saveValues('personal');
                $j('#list_personal').val('~[x:users_dcid]');
                $j('#list_name').val(listName);
                try {
                    sessionStorage.setItem('lsFeedback', "~[text:nicktech.lsa.feedback.list_set_saved]");
                    sessionStorage.setItem('lsNewSelectName', listName);
                    sessionStorage.setItem('lsNewSelectType', 'personal');
                } catch(e) {}
                $j('#lsFormDiv form').submit();
            },
            error: function(jq){
                closeLoading();
                lsShowError("~[text:nicktech.lsa.error.save_failed_prefix]" + jq.status + "~[text:nicktech.lsa.error.save_failed_suffix]", $btn);
            }
        });
    } else {
        lsShowError("~[text:nicktech.lsa.error.list_set_name_required]", $j('#lsNew_name'));
        return false;
    }
});

// save new school/district list
$j('#lsSchSubmit').on('click', function(){
    var $btn = $j(this);
    if ($j.trim($j('#lsNew_name').val()).length > 0){
        // require at least one school to be checked for a school/district list
        // (gate on visible checkboxes — school-only users have .districtAccess hidden and skip this check)
        if ($j('#lsNewSchoolChecksDiv input.schoolCheck:visible').length > 0 && $j('#lsNewSchoolChecksDiv input.schoolCheck:checked').length === 0){
            lsShowError("~[text:nicktech.lsa.error.school_required]", $btn);
            return false;
        }
        var listName = $j.trim($j('#lsNew_name').val());
        loadingDialog();
        $j.ajax({
            type: 'POST',
            url: 'studentlistauto_helper.html?authId=-1',
            success: function(results){
                $j('#lsFormDiv').append(results);
                if ($j('#lsFormDiv form').length === 0){
                    closeLoading();
                    lsShowError("~[text:nicktech.lsa.error.save_denied]", $btn);
                    return;
                }
                saveValues('new');
                $j('#list_name').val(listName);
                try {
                    sessionStorage.setItem('lsFeedback', "~[text:nicktech.lsa.feedback.list_set_saved]");
                    sessionStorage.setItem('lsNewSelectName', listName);
                    sessionStorage.setItem('lsNewSelectType', 'school');
                } catch(e) {}
                $j('#lsFormDiv form').submit();
            },
            error: function(jq){
                closeLoading();
                lsShowError("~[text:nicktech.lsa.error.save_failed_prefix]" + jq.status + "~[text:nicktech.lsa.error.save_failed_suffix]", $btn);
            }
        });
    } else {
        lsShowError("~[text:nicktech.lsa.error.list_set_name_required]", $j('#lsNew_name'));
        return false;
    }
});

// save existing list
$j('#lsCurSubmit').on('click', function(){
    var $btn = $j(this);
    var loadListType = $j("#loadlist option:selected").data('listtype');
    if ($j.trim($j('#lsEdit_name').val()).length > 0){
        // require at least one school to be checked when editing a school/district list
        // (gate on visible checkboxes — school-only users have .districtAccess hidden and skip this check)
        if ($j('#lsEditSchoolChecksDiv input.schoolCheck:visible').length > 0 && $j('#lsEditSchoolChecksDiv input.schoolCheck:checked').length === 0){
            lsShowError("~[text:nicktech.lsa.error.school_required]", $btn);
            return false;
        }
        var loadListID = $j('#loadlist').val();
        var listName = $j.trim($j('#lsEdit_name').val());
        loadingDialog();
        $j.ajax({
            type: 'POST',
            url: 'studentlistauto_helper.html?authId=' + loadListID,
            success: function(results){
                $j('#lsFormDiv').append(results);
                if ($j('#lsFormDiv form').length === 0){
                    closeLoading();
                    lsShowError("~[text:nicktech.lsa.error.save_denied]", $btn);
                    return;
                }
                if(loadListType == 'personal'){
                    saveValues('personal');
                } else {
                    saveValues('edit');
                }
                $j('#list_name').val(listName);
                try { sessionStorage.setItem('lsFeedback', "~[text:nicktech.lsa.feedback.list_set_updated]"); } catch(e) {}
                $j('#lsFormDiv form').submit();
            },
            error: function(jq){
                closeLoading();
                lsShowError("~[text:nicktech.lsa.error.save_failed_prefix]" + jq.status + "~[text:nicktech.lsa.error.save_failed_suffix]", $btn);
            }
        });
	} else {
        lsShowError("~[text:nicktech.lsa.error.list_set_name_required]", $j('#lsEdit_name'));
        return false;
    }
});

// delete existing list
$j('#lsDelSubmit').on('click', function(){
    var $btn = $j(this);
    var loadListID = $j('#loadlist').val();
    loadingDialog();
    $j.ajax({
        type: 'POST',
        url: 'studentlistauto_helper.html?authId=' + loadListID + '&delete=1',
        success: function(results){
            $j('#lsFormDiv').append(results);
            if ($j('#lsFormDiv form').length === 0){
                closeLoading();
                lsShowError("~[text:nicktech.lsa.error.delete_denied]", $btn);
                return;
            }
            try { sessionStorage.setItem('lsFeedback', "~[text:nicktech.lsa.feedback.list_set_deleted]"); } catch(e) {}
            $j('#lsFormDiv form').submit();
        },
        error: function(jq){
            closeLoading();
            lsShowError("~[text:nicktech.lsa.error.delete_failed_prefix]" + jq.status + "~[text:nicktech.lsa.error.delete_failed_suffix]", $btn);
        }
    });
});

// auto-select a just-created list set in the Load List dropdown
// (lsPerSubmit / lsSchSubmit store the name + type in sessionStorage before submitting;
//  on reload we find the matching option with the highest id — that's the new row — and trigger change)
$j(function(){
    try {
        var newName = sessionStorage.getItem('lsNewSelectName');
        var newType = sessionStorage.getItem('lsNewSelectType');
        if (newName){
            sessionStorage.removeItem('lsNewSelectName');
            sessionStorage.removeItem('lsNewSelectType');
            // only fire if nothing was already pre-selected via the gpv.listid path
            if ($j('#loadlist').val() === ''){
                var bestId = 0, $best = null;
                $j('#loadlist option').filter(function(){
                    return $j(this).text() === newName && (!newType || $j(this).data('listtype') === newType);
                }).each(function(){
                    var id = parseInt($j(this).val(), 10);
                    if (id > bestId){ bestId = id; $best = $j(this); }
                });
                if ($best){
                    $j('#loadlist').val($best.val()).trigger('change');
                }
            }
        }
    } catch(e) {}
});

// show any pending feedback from a prior action that reloaded the page
// (wrapped in doc-ready so it fires AFTER the #lsAutoLoadDiv move — otherwise the banner
//  gets re-parsed by the .html() move and our closure reference becomes detached)
$j(function(){
    try {
        var msg = sessionStorage.getItem('lsFeedback');
        if (msg){
            sessionStorage.removeItem('lsFeedback');
            lsShowSuccess(msg);
        }
    } catch(e) {}
});

// prevent form resubmit on refresh
if ( window.history.replaceState ) {
    window.history.replaceState( null, null, window.location.href );
}
</script>
[/if#page]