// position_cds.js

// used with forms which include either position_cds_select.tt,
// new_select_district.tt, or new_school_select.tt

// position_cds_select.tt   new_select_district.tt  new_school_select.tt
// ----------------------   ----------------------  --------------------
// school_type                                      school_type
// county                   county                  county
// range                    range                   range
// district_select          district_select         district_select
// school_name                                      school_name
// position
// cf_name
// position_name

// the following are hidden and used during initialization

// set_district
// school

// ---------------------------------------------------------------------------

// used on page load to selectively display the position fields, and to
// populate the district and school dropdowns

function cdsInit(e) {

    var position    = document.getElementById('position');
    var school_name = document.getElementById('school_name');

    if (position) {

        _pcdsInit(e);

    }

    else if (school_name) {

        _cdsInit(e);

    }

    else {

        _cdInit(e);

    }

    adjustWings(e);

    return false;

}

// ---------------------------------------------------------------------------

function _pcdsInit(e) {

    var position    = document.getElementById('position');
    position        = position.options[position.selectedIndex].value;

    //  --- position ---                        --- fields displayed ---
    //  1 Classroom Teacher                     all cds
    //  2 County CTAP Representative            county
    //  3 County Office of Education Staff      county
    //  4 District Administrator                county, district_range, district
    //  5 Library Media Specialist              all cds
    //  6 Site Administrator                    all cds
    //  7 Technology Support Staff              all cds
    //  8 Other                                 position_other, all cds
    //  9 Teacher (Non-Classroom)               all cds
    // 10 Corporate/Non-Profit                  cf_name
    // 11 California Department of Education    none

    // by starting off by hiding the position_other field, we can
    // handle the case '8' by falling into default.

    hide_position_other();

    switch ( position ) {

        case '':        // not selected

            hide_cf_name();
            show_cds('none');
            break;

        case '2':       // County CTAP Representative
        case '3':       // County Office of Education Staff

            hide_cf_name();
            show_cds('cds_county_div');
            break;

        case '4':       // District Administrator

            hide_cf_name();

            // load the district and school dropdowns, and then clear initial
            // values so they won't be used if user changes county or range

            getDistricts(e);
            document.getElementById('set_district').value = '';

            show_cds('cds_county_div cds_range_div cds_district_div');
            break;

        case '10':      // Corporate/Non-Profit

            show_cf_name();
            show_cds('none');
            break;

        case '11':      // California Department of Education

            hide_cf_name();
            show_cds('none');
            break;

        case '8':       // Other

            show_position_other();
            // fall through to treat like the default

        default:        // all others

            hide_cf_name();

            // load the district and school dropdowns, and then clear initial
            // values so they won't be used if user changes county or range

            getDistricts(e);
            getSchools(e);

            document.getElementById('set_district').value = '';
            document.getElementById('school').value = '';

            show_cds();

            break;
    }

}

// ---------------------------------------------------------------------------

function _cdsInit(e) {

    // load the district and school dropdowns, and then clear initial
    // values so they won't be used if user changes county or range

    getDistricts(e);
    getSchools(e);

    document.getElementById('set_district').value = '';
    document.getElementById('school').value = '';

    show_cds();

}

// ---------------------------------------------------------------------------

function _cdInit(e) {

    // load the district dropdown, and then clear initial value
    // so it won't be used if user changes county or range

    getDistricts(e);

    document.getElementById('set_district').value = '';

    show_cds();

}

// ---------------------------------------------------------------------------

// called by ajax to populate the position related fields

function cdsSet(position_id, position_other, cf_name,
    county_index, district_name, district_id, school_id, school_type) {

    _set_selected_index('position', position_id);

    // by starting off by hiding the position_other field, we can
    // handle the case '8' by falling into default.

    hide_position_other();

    switch ( position_id ) {

        case '':        // not selected

            hide_cf_name();
            show_cds('none');
            break;

        case '2':       // County CTAP Representative
        case '3':       // County Office of Education Staff

            hide_cf_name();
            _set_selected_index('county', county_index);
            show_cds('cds_county_div');
            break;

        case '4':       // District Administrator

            hide_cf_name();
            _set_selected_index('county', county_index);
            _set_range(district_name);

            // set district used to retrieve the dropdown values, and then clear
            // so they it won't be used if user changes county

            document.getElementById('set_district').value   = district_id;

            getDistricts();

            document.getElementById('set_district').value = '';

            show_cds('cds_county_div cds_range_div cds_district_div');
            break;

        case '10':      // Corporate/Non-Profit

            show_cf_name(cf_name);
            show_cds('none');
            break;

        case '11':      // California Department of Education

            hide_cf_name();
            show_cds('none');
            break;

        case '8':       // Other

            show_position_other(position_other);
            // fall through to treat like the default

        default:        // all others

            hide_cf_name();
            _set_selected_index('county',       county_index);
            _set_selected_index('school_type',  school_type);
            _set_range(district_name);

            // set district and school used to retrieve the dropdown values,
            // and then clear so they won't be used if user changes county or range

            document.getElementById('set_district').value   = district_id;
            document.getElementById('school').value         = school_id;

            getDistricts();
            getSchools();

            document.getElementById('set_district').value = '';
            document.getElementById('school').value = '';

            show_cds();

            break;
    }

    adjustWings();

    return false;

}

// ---------------------------------------------------------------------------

function _set_selected_index(name, value) {

    var select = document.getElementById(name);

    for ( var i = 0; i < select.options.length; i++ ) {

        if (select.options[i].value == value) {

            select.selectedIndex = i;
            return false;

        }

    }

    select.selectedIndex = 0;

    return false;

}

// ---------------------------------------------------------------------------

function _set_range(district_name) {

    var select = document.getElementById('range');

    var character = district_name.substr(0,1);

    for ( var i = 0; i < select.options.length; i++ ) {

        if (select.options[i].value.substr(0,1) <= character &&
            select.options[i].value.substr(2,1) >= character) {

            select.selectedIndex = i;
            return false;

        }

    }

    select.selectedIndex = 0;

    return false;

}

// ---------------------------------------------------------------------------
//
// Listeners
//
// ---------------------------------------------------------------------------

// clear district range when county changed

function resetRange(e) {

    document.getElementById('range').selectedIndex              = 0;
    document.getElementById('district_select').selectedIndex    = 0;
    if (document.getElementById('school_name'))
        document.getElementById('school_name').selectedIndex    = 0;

    return false;

}

// ---------------------------------------------------------------------------

// retrieve districts and clear schools when district range is changed
// also called during initialization

function getDistricts(e) {

    var district_select = document.getElementById('district_select');
    var county_select   = document.getElementById('county');
    var range_select    = document.getElementById('range');
    var school_select   = document.getElementById('school_name');

    // we need to empty the school data at this point

    if (school_select) {

        for ( var i = school_select.length -1; i > 0; i-- )
            school_select.options[i].parentNode.removeChild(school_select.options[i]);

        school_select.options[0].value = '';
        school_select.options[0].text  = '----';

    }

    var range  = range_select.options[range_select.selectedIndex].value;

    if ( range == '' ) {

        return false;

    }

    var county = county_select.options[county_select.selectedIndex].value;

    var url = '/global_ajax/cds_ajax.pl?ajax_action=get_districts_in_county_range';

    url += '&county=' + county;
    url += '&range='  + range;

    //alert(url);

    var xmlhttp = new XMLHttpRequest();

    // last value set to false -- do not want async.
    xmlhttp.open('GET', url, false);

    xmlhttp.send(null);

    //alert(xmlhttp.responseText);

    var response = xmlhttp.responseXML;

    if ( ! response ) {

        alert( 'ERROR:' + xmlhttp.responseText );
        return false;

    }

    var districts = response.getElementsByTagName('district');

    district_select.length = districts.length + 1;

    //district_select.options[0] = new Option('- Select a district -', '');

    district_select.options[0].value = '';
    district_select.options[0].text  = '- Select a district -';

    district_select.selectedIndex = 0;

    var selected_district = document.getElementById('set_district').value;

    for ( var i = 0; i < districts.length; i++ ) {

        var id   = districts[i].getElementsByTagName('id');
        var name = districts[i].getElementsByTagName('name');

        //district_select.options[i + 1] = new Option(name.item(0).firstChild.nodeValue, id.item(0).firstChild.nodeValue);
        district_select.options[i + 1].value = id.item(0).firstChild.nodeValue;
        district_select.options[i + 1].text  = name.item(0).firstChild.nodeValue;

        if (id.item(0).firstChild.nodeValue == selected_district) {

            district_select.selectedIndex = i + 1;

        }

    }

    return false;

}

// ---------------------------------------------------------------------------

// retrieve schools when school type or district is changed
// also called during initialization

function getSchools(e) {

    var school_select   = document.getElementById('school_name');

    if (! school_select)
        return false;

    var position_select = document.getElementById('position');
    var district_select = document.getElementById('district_select');
    var county_select   = document.getElementById('county');
    var range_select    = document.getElementById('range');
    var type_select     = document.getElementById('school_type');

    var position = position_select.options[position_select.selectedIndex].value;
    var county   = county_select.options[county_select.selectedIndex].value;
    var range    = range_select.options[range_select.selectedIndex].value;
    var district = district_select.options[district_select.selectedIndex].value;
    var type     = type_select.options[type_select.selectedIndex].value;

    // don't show schools if there is no district, or for district admin

    if ( district == '' || position == '4')
        return false;

    var url = '/global_ajax/cds_ajax.pl?ajax_action=get_schools_in_district';

    url += '&county='    + county;
    url += '&district='  + district;
    url += '&type='      + type;

    //alert(url);

    var xmlhttp = new XMLHttpRequest();

    // last value set to false -- do not want async.
    xmlhttp.open('GET', url, false);

    xmlhttp.send(null);

    //alert(xmlhttp.responseText);

    var response = xmlhttp.responseXML;

    if ( ! response ) {

        alert( 'ERROR:' + xmlhttp.responseText );
        return false;

    }

    var schools = response.getElementsByTagName('school');

    school_select.length = schools.length + 1;

    school_select.options[0].value = '';
    school_select.options[0].text  = '- Select a school -';

    school_select.selectedIndex = 0;

    var selected_school = document.getElementById('school').value;

    for ( var i = 0; i < schools.length; i++ ) {

        var id   = schools[i].getElementsByTagName('id');
        var name = schools[i].getElementsByTagName('name');

        school_select.options[i + 1].value = id.item(0).firstChild.nodeValue;
        school_select.options[i + 1].text  = name.item(0).firstChild.nodeValue;

        if (id.item(0).firstChild.nodeValue == selected_school) {

            school_select.selectedIndex = i + 1;

        }

    }

    return false;

}

// ---------------------------------------------------------------------------

// show/hide the cf_name or the CDS fields when the position field is changed,
// and clear district and school fields if not used

// resetting the district range will clear the districts and schools

function positionChange(e) {

    var target = (window.event) ? window.event.srcElement : e.target;

    // special behaviors based on position

    //  --- position ---                        --- fields displayed ---
    //  1 Classroom Teacher                     all cds
    //  2 County CTAP Representative            county
    //  3 County Office of Education Staff      county
    //  4 District Administrator                county, district_range, district
    //  5 Library Media Specialist              all cds
    //  6 Site Administrator                    all cds
    //  7 Technology Support Staff              all cds
    //  8 Other                                 position_other, all cds
    //  9 Teacher (Non-Classroom)               all cds
    // 10 Corporate/Non-Profit                  cf_name
    // 11 California Department of Education    none

    var position = target.options[target.selectedIndex].value;

    // by starting off by hiding the position_other field, we can
    // handle the case '8' by falling into default.

    hide_position_other();

    switch ( position ) {

        case '':        // none

            hide_cf_name();
            show_cds('none');
            resetRange(e);
            break;

        case '2':       // County CTAP Representative
        case '3':       // County Office of Education Staff

            hide_cf_name();
            show_cds('cds_county_div');
            resetRange(e);

            // if no county is currently selected, we'll default to Los Angeles
            // we're relying on the countys being in order so that the index
            // is the same as the county number

            if (document.getElementById('county').selectedIndex == 0) {

                document.getElementById('county').selectedIndex = 19;

            }

            break;

        case '4':       // District Administrator

            hide_cf_name();

            if (document.getElementById('county').selectedIndex == 0) {

                document.getElementById('county').selectedIndex = 19;

            }

            document.getElementById('school_name').selectedIndex = 0;

            show_cds('cds_county_div cds_range_div cds_district_div');
            break;

        case '10':      // Corporate/Non-Profit

            show_cf_name();
            show_cds('none');
            resetRange(e);
            break;

        case '11':      // California Department of Education

            hide_cf_name();
            show_cds('none');
            resetRange(e);
            document.getElementById('county').selectedIndex = 0;
            break;

        case '8':       // Other

            show_position_other();
            // fall through to treat like the default

        default:        // all others

            // if we have a district and no schools, will need to populate
            // the school dropdown

            var need_schools =
                isVisible(document.getElementById('district_select')) &&
                ! isVisible(document.getElementById('school_name'));

            if (document.getElementById('county').selectedIndex == 0)
                document.getElementById('county').selectedIndex = 19;

            show_cds();
            if (need_schools)
                getSchools(e);
            hide_cf_name();
            break;
    }


    adjustWings(e);

    return false;

}

// ---------------------------------------------------------------------------
//
// other subroutines
//
// ---------------------------------------------------------------------------

function show_cds(only) {

    var divs = "cds_school_type_div cds_county_div cds_range_div cds_district_div cds_school_div";

    var divisions = divs.split(' ');

    for (var ix = 0; ix < divisions.length; ix ++) {

        var division = divisions[ix];

        var display_mode = 'block';

        if (only) {

            var re = new RegExp('\\b' + division + '\\b');

            if (! only.match(re)) {

                display_mode = 'none';

            }

        }

        var div = document.getElementById(division);

        if (div)
            div.style.display = display_mode;

    }

    if (only && only == 'none') {

        document.getElementById('cds_all_div').style.display = 'none';

    } else {

        document.getElementById('cds_all_div').style.display = 'block';

    }

    return false;

}

// ---------------------------------------------------------------------------

function show_cf_name(optional_value) {

    if (optional_value) {

        document.getElementById('cf_name').value = optional_value;

    }

    document.getElementById('cds_cfname_div').style.display = 'block';

    return false;

}

// ---------------------------------------------------------------------------

function hide_cf_name() {

    document.getElementById('cds_cfname_div').style.display = 'none';

    document.getElementById('cf_name').value = '';


    return false;

}

// ---------------------------------------------------------------------------

function show_position_other(optional_value) {

    if (optional_value) {

        document.getElementById('position_other').value = optional_value;

    }

    document.getElementById('cds_position_other_div').style.display = 'block';

    return false;

}

// ---------------------------------------------------------------------------

function hide_position_other() {

    document.getElementById('cds_position_other_div').style.display = 'none';

    document.getElementById('position_other').value = '';

    return false;

}

// ----------------------------------------------------------------------------

function addListeners(e) {

    var listen = document.getElementById('county');
    if (listen)
        addEvent(listen, 'change', resetRange, false);

    listen = document.getElementById('range');
    if (listen)
        addEvent(listen, 'change', getDistricts, false);

    listen = document.getElementById('district_select');
    if (listen)
        addEvent(listen, 'change', getSchools, false);

    listen = document.getElementById('school_type');
    if (listen)
        addEvent(listen, 'change', getSchools, false);

    listen = document.getElementById('position');
    if (listen)
        addEvent(listen, 'change', positionChange, false);

}

// ---------------------------------------------------------------------------

addEvent(window, 'load', addListeners, false);

// ---------------------------------------------------------------------------
