
function insertOptions(elem, items, selected) {
    if(elem.options == null) {
        return;
    }
    var i = 0;
    for (k in items) {
        if (selected == k) {
           elem.selectedIndex = i;
        }
        elem.options[i] = new Option(items[k], k);
        i++;
    }
    return i;
}
/*
 * loadData is called to load some json data into another dropdown box
 * 
 * Example given an organization load the people in the organizaiton
 * ARGS:
 *  key - the query parameter to pass to the json request
 *  value - the form element holding the value for the query
 *  target - the form element meant as the target dropdown box
 *  selected - the value of the selected item 
 *  extras - any extra options you want added to the begining of target
 *  none_selected - options to present when none is selected
 * 
 *  USAGE: loadData('org_id', this, this.form['mydropdown'], 
 *                  'http://my.com/query/json/', {'':'None'},
 *                  {'':'Please select an orgization'})
 *         This would be on an onchange event of a dropdown
 *         It will query the page:
 *         http://my.com/query/json/?org_id=<the value of this>
 *         It expects a json return of the following format:
 *         {<value>:{'name':'The display name'}}
 */
function loadData(key, value, target, base_url, selected, extras, none_selected) {
    // if the dependent value has no value then set to none_selected
    if (!value.value) {
       target.length = 0;
       insertOptions(target, none_selected, selected);
       return;
    }
    target.length = 0;
    insertOptions(target, {'':'Loading...'}, selected);
    url = base_url + '?' + key + '=' + value.value;
    // function to load the data into the dropdown
    var gotData = function(data) {
        var payload = evalJSONRequest(data);
        target.length = 0;
        var i = insertOptions(target, extras, selected);
        for (k in data) {
            target.options[i] = new Option(data[k]['name'], k);
            if (selected == k) {
               target.selectedIndex = i;
            }
            i++;
        }

    }
    d = loadJSONDoc(url);
    d.addCallback(gotData);
}