$(function(){
    // EDULEADGEN-309: part 2
    // - show closest matches in programs from selected schools
    $('select.degree_list').change(function () {
        var q = '';
        // build q from the text of every selected program name
        $('select.degree_list option:selected').each(function () {
            if (this.value.match(/_/)) {
                q += $(this).text() + ' ';
            }
        });
        if (!q) {
            return;
        }
        // remake optgroup for every 'Pick a Degree' select based on q
        $('select.degree_list option:selected').each(function () {
            if (this.value.match(/_/)) {
                return true;
            }
            var pids = [],
                $opt_pickadegree = $(this),
                $select = $opt_pickadegree.parent(),
                $siblings = $opt_pickadegree.siblings();
                
            $siblings.children().each(function () {
                if ($(this).val().match(/_/)) {
                    pids.push(
                        // grab program_id from "#_#_#" string
                        $(this).val().split('_')[2]
                    );
                }
            });
            if (pids.length === 0) {
                return true;
            }
            
            $.post(
                '/ajax/match_against_programs.php',
                {'q': q,
                'limit': true,
                'pids[]': pids},
                function (opids) {
                    if (opids.length === 0) {
                        $('optgroup[label="Suggested"]', $select).remove();
                        return;
                    }
                    
                    var $optgroup = $('optgroup[label="Suggested"]', $select);
                    
                    if (!$optgroup.length) {
                        $opt_pickadegree.after('<optgroup label="Suggested"></optgroup>');
                        $optgroup = $('optgroup[label="Suggested"]', $select);
                    }
                    else {
                        $optgroup.empty();
                    }
                    
                    // build string of all program options to find
                    var findopts = '';
                    for(var i=0; i != opids.length; i++) {
                        findopts += 'option[value$="'+opids[i]+'"],';
                    }
                    findopts = findopts.substring(0, findopts.length-1);
                    
                    // append options to our optgroup
                    $siblings.find(findopts).clone().each(function () {
                        $optgroup.append($(this));
                    });
                },
                'json'
            );
            return true;
        });
    });
});
