function launch(URL,PopUp,width,height) {
    popup=window.open(URL,PopUp,"width="+width+",height="+height+",top=100,left=200,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,status=no,location=no")
}

// {{{ SFH: This is used for the guest user top-bar that displays Login/Register links

// this function is called when a user hovers over the "Login" or "Register"
// links in the registration top-bar when a user is logged in as a guest. The
// argument ``css_id`` is the css id or the hidden form to be displayed, and
// ``css_hide_id`` is the css id of the form to be hidden.
function showLogin(css_id, css_hide_id) {
    css_element = document.getElementById(css_id);
    css_element.className = 'top-bar-sub';
    css_element.email.focus();

    document.getElementById(css_hide_id).className = 'top-bar-sub hidden';
    $('top-bar-hide').removeClassName('hidden');
}

// calls showLogin after a certain timeout. Stores the event handler id in
// ``hover_handler``, so that calling showLogin can be cancelled if a user
// moves the mouse out of the "Login"/"Register" links.
var hover_handler;
function hoverLogin(css_id, css_hide_id) {
    hover_handler = window.setTimeout("showLogin('" + css_id + "', '" + css_hide_id + "')", 300);
}

// canceles a call to showLogin when the mouse leaves the "login"/"register" link.
function unhoverLogin() {
   window.clearTimeout(hover_handler);
}

// hides the Login and Register divs.
function hideLogin(css_id1, css_id2) {
  $('login-form').addClassName('hidden');
  $('register-form').addClassName('hidden');
  $('top-bar-hide').addClassName('hidden');
}

function showError(element, text) {
  element.innerHTML = text;
  element.removeClassName('hidden');
}

function topBarLogin() {
  var email = $('login-form').email.value;
  var pass = $('login-form').pass.value;

  if (email == "") {
    showError($('login-error'), "Please enter your school email address to login!");
  } else if (pass == "") {
    showError($('login-error'), "Please enter your password to login!");
  }

  new Ajax.Request('/ajax-login.php', {
    method: 'POST',
    parameters: {
      email: email,
      pass:  pass
    },
    onSuccess: function(response) {
      var is_valid = response.responseJSON['is_valid'];
      if (is_valid == 'ok') {
        //reload!
        if (document.location.search.startsWith('?')) {
          document.location.search += '&logged-in';
        } else {
          document.location.search = '?logged-in';
        }
      } else if (is_valid == 'failed') {
	showError($('login-error'), "The email address or password you specified are " +
                         "invalid. <a href='/password.php?email=" + escape(email) +
                         "' target='_blank'>Forgot password?</a>");
      } else if (is_valid == 'updating') {
        showError($('login-error'), "Your account is currently updating. Please try again, later.");
      } else if (is_valid == 'unconfirmed') {
        showError($('login-error'), "Your account has not yet been confirmed - <a href='/resend.php'>Resend the confirmation email</a>");
      } else {
        showError($('login-error'), "Login failed. Received invalid response code: " + is_valid);
      }
    },
    onFailure: function(response) {
      showError($('login-error'), "Couldn't perform login. Network down? Please try again.");
    }
  });
}

function topBarRegister() {
  var email = $('register-form').email.value;
  var password1 = $('register-form').password1.value;
  var password2 = $('register-form').password2.value;

  new Ajax.Request('/ajax-register.php', {
    method: 'POST',
    parameters: {
      email: email,
      password1: password1,
      password2: password2
    },
    onSuccess: function(response) {
      var errors = response.responseJSON['errors'];
      if (errors.length == 0) {
        document.location = '/register2.php?email=' + escape(email);
      } else if (errors[0] == 'invalid-email') {
        showError($('register-error'), "Please specify a valid email address.");
      } else if (errors[0] == 'invalid-school') {
        showError($('register-error'), "The email address you entered, " + email +
	  	", isn't valid for your school. Please specify your school email address.");
      } else if (errors[0] == 'password-mismatch') {
        showError($('register-error'), "The passwords you provided don't match.");
      } else if (errors[0] == 'is-registered') {
        showError($('register-error'), "This email address is already registered. Please " +
            "<a target='_blank' href='/password.php?email=" + escape(email) + "'>request your password</a> " +
            "if you don't remember what it is.");
      } else {
        showError($('register-error'), "Received invalid error message: " + errors[0]);
      }
    },
    onFailure: function(response) {
      showError($('register-error'), "Couldn't perform registration. Network down? Please try again.");
    }
  });
}

function checkPasswords(field1, field2, error_display) {
    if (field1.value != '' && field2.value != ''
            && field1.value != field2.value) {
        error_display.removeClassName('hidden');
    } else {
        error_display.addClassName('hidden');
    }
}

// Keeps track of which tab we were on to preserve browser history.
// If we're on the wrong tab, switch us over to the right one.
var last_maintab = '';
function checkTabHistory() {
  if (document.location.hash != last_maintab) {
    last_maintab = document.location.hash;
    var tabname = document.location.hash.replace('#maintab-', '');
    if (tabname == '' || tabname == '#') {
      tabname = initial_maintab;
    }
    showTab('main', tabname, true);
  }
  setTimeout('checkTabHistory()', 200);
}
// }}} SFH

function showTab(group,name,keep_location_hash) {
    switch (group) {
    
    case 'main':
        var panels = new Array('home', 'addclasses', 'selectedclasses', 
                               'personal', 'possible', 
                               'saved', 'final');
        break;
    case 'selectedclasses':
        var panels = new Array('group1', 'group2', 'group3', 'group4',
                               'group5');
        break;
    case 'personal':
        var panels = new Array('addedit', 'selected');
        break;
    default:
        return;
    }
    var got_one = false;
    for(i=0; i<panels.length; i++) {
        var item = document.getElementById(panels[i]);
        var item_b = document.getElementById(panels[i] + '_b');
        if (name == panels[i]) {
            got_one = true;
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
        if (group == "main") {
            item_b.className =
            (name == panels[i]) ? 'tabon':'tab';
        }
        if (group == "selectedclasses" || group == "personal") {
            item_b.className =
            (name == panels[i]) ? 'subon':'';
        }
    }
    /* TODO SFH
    if (!got_one) {
        var item = document.getElementById(panels[0]);
        item.style.display = 'block';
        var item_b = document.getElementById(panels[0] + '_b');
        item_b.className = 'tabon';
    }
    */
    // if we're on the "Welcome" screen, don't display the bottom-ad
    if (group === 'main' &&
            document.getElementById(panels[0] + '_b').className === 'tabon') {
        document.getElementById('bottomad').display='none';
    } else {
        document.getElementById('bottomad').display='block';
    }

    var c = "";
    if (group == "main") {
        c = "maintabs";
        if (typeof(keep_location_hash) == 'undefined') {
            last_maintab = '#maintab-' + name;
            document.location.hash = '#maintab-' + name;
        }
    }
    else {
        c = "subtabs";
    }

    var hiddens = getElementsByClass(document,c,"input");
    for (i=0; i<hiddens.length; i++) {
        hiddens[i].setAttribute("value", name);
    }

    var errors = getElementsByClass(document,"error","div");
    for (i=0; i<errors.length; i++)
        errors[i].style.display = "none";
    
    var messages = getElementsByClass(document,"message","div");
    for (i=0; i<messages.length; i++)
        messages[i].style.display = "none";
}   

function setfinal(a,sched) {
    var setfinalform = document.getElementById("setfinalform");
    setfinalform.a.setAttribute("value", a);
    setfinalform.sched.setAttribute("value", sched);
    setfinalform.submit();
}

window.onload = function() {
        checkTabHistory();

        var uls = document.getElementsByTagName('ul');
        for (var i = 0; i < uls.length; i++) {
            if (uls[i].id.indexOf('b_') == -1)
                continue;
            var broken = uls[i].id.split('_');
            DragDrop.makeListContainer(uls[i], "container"+broken[1]);
            uls[i].onDragOver = function() { 
                this.style["background"] = "#EEF";
            };
            uls[i].onDragOut = function() {
                this.style["background"] = "none";
                var h = this.childNodes.length;
                if (h == 1) {
                    this.style["height"] = "2em";
                }
                else {
                    this.style["height"] = "auto";
                }
            };
        }
        //var sortlist = document.getElementById('sortlist');
        //DragDrop.makeListContainer(sortlist, "sortlist");
        if (document.getElementById('savepchanges')) {
            document.getElementById('savepchanges').onclick = 
                parseAndSendPersonal;
        }
        document.getElementById('savesortbutton').onclick = 
            parseAndSendSortOptions;
        document.getElementById('personalsubmitb').onclick =
            validateSubmitTimes;
        if (document.getElementById('personalsubmitb2'))
            document.getElementById('personalsubmitb2').onclick =
                validateSubmitTimes2;
        pidselect = document.getElementById('pidselect');
        setPersonal();
        //localeInit();

}

function getElementsByClass(node,searchClass,tag) {
    var classElements = new Array();
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
           classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function editPersonal(pid) {
    setPersonal(pid);
    showTab('personal', 'addedit');
    var select = document.getElementById('pidselect');
    var nodes = select.childNodes;
    for (var i=0; i<nodes.length; i++) {
        if (nodes[i].value == pid) {
            select.selectedIndex = i;
            break;
        }
    }
}

function parseAndSendPersonal() {
    removes = document.getElementsByName('p_removes');
    f_p_submit = document.getElementById('savepchangessubmit');

    selected = new Array();

    for (i=0; i<removes.length; i++) {
        if (removes[i].checked==false) {
            pid = removes[i].value;
            active_cb = document.getElementById('p_active_' + pid);
            if (active_cb.checked==true) {
                active = 1;
            }
            else {
                active = 0;
            }
            selected[i] = pid + ',' + active;
        }
    }
    f_p_submit.p_selected.value = selected.join("/");
    f_p_submit.submit();
}

function parseAndSendSortOptions() {
    var form = document.getElementById('sortform');
    var lis = document.getElementById('sortlist').childNodes;
    var sort = new Array();
    var pos = 0;
    for(var i=0; i<lis.length; i++) {
        if (lis[i].style.display == 'none') {
            continue;
        }
        var els = lis[i].childNodes
        var options = els[0].childNodes;
        var major = options[els[0].selectedIndex].getAttribute("value");
        var minor = "";
        if (major == "0")
            continue;
        if (major == 1) {
            if (els[3].childNodes[1].checked == true) {
                minor = "0";
            }
            else {
                minor = "1";
            }
        }
        if (major == 2) {
            if (els[4].childNodes[1].checked == true) {
                minor = "0";
            }
            else {
                minor = "1";
            }
        }
        if (major == 4) {
            var counter = 0;
            for (var j=1; j<14; j=j+2) {
                if (els[6].childNodes[j].checked == true) {
                    minor = ("" + minor) + counter;
                }
                counter++;
            }
        }
        if (major == 5) {
            var lunch_min = els[7].childNodes[1];
            var lunch_start = els[7].childNodes[3];
            var lunch_end = els[7].childNodes[5];
            minor = lunch_min.childNodes
                        [lunch_min.selectedIndex].getAttribute("value");
            minor += lunch_start.childNodes
                        [lunch_start.selectedIndex].getAttribute("value");
            minor += lunch_end.childNodes
                        [lunch_end.selectedIndex].getAttribute("value");
        }
        if (major == 6) {
            options = els[8].childNodes[1].getElementsByTagName("option");
            minor = 
              options[els[8].childNodes[1].selectedIndex].getAttribute("value");
        }
        sort[pos] = major + "/" + minor;
        pos++;
    }
    form.sort.setAttribute("value", sort.join(","));
    form.submit();
}

function showSubSort(id) {
    var nodes = document.getElementById(id).childNodes;
    var options = nodes[0].childNodes;
    var main_sort_num = 0;
    main_sort_num = options[nodes[0].selectedIndex].getAttribute("value");
    for (var i=2; i<nodes.length-2; i++) {
        nodes[i].style.display = ((i-2) == main_sort_num) ? 'inline':'none';
    }
}

function remove(id) {
    var i = 0;
    var node = document.getElementById(id);
    node.style.display = 'none';
    var list = node.parentNode;
    var els = node.childNodes;
    els[2].style.display = 'inline';
    for (i=3; i<els.length-2; i++) {
        els[i].style.display = 'none';
    }
    els[0].selectedIndex = 0;
    els[3].childNodes[1].checked = false;
    els[3].childNodes[3].checked = true;
    els[4].childNodes[1].checked = false;
    els[4].childNodes[3].checked = true;
    for (i=1; i<14; i=i+2) {
        els[6].childNodes[i].checked = false;
    }
    els[8].childNodes[1].selectedIndex = 0;

    var num_nodes = 0;
    for (i=0; i<list.childNodes.length; i++) {
        if (list.childNodes[i].style.display != 'none') {
            num_nodes++;
        }
    }
    if (num_nodes < 6) {
        document.getElementById("add_link").style.display = 'inline';
    }
    var links = getElementsByClass(list, "remove_links", "a");
    for (i=0; i<links.length; i++) {
        links[i].style.display = (num_nodes == 1) ? 'none':'inline';
    }
    return false;
}

function add() {
    var list = document.getElementById("sortlist");
    var lis = list.childNodes;
    var blanks = new Array();
    var pos = 0;
    var i = 0;
    //Resequence list items: store blanks at end
    for (i=0; i<lis.length; i++) {
        if (lis[i].style.display == 'none') {
            blanks[pos] = list.removeChild(lis[i]);
            i--;
            pos++;
        }
    }
    for (i=0; i<blanks.length; i++) {
        list.appendChild(blanks[i]);
    }
    //Unhide the first hidden blank
    lis = document.getElementById("sortlist").childNodes;
    for (i=0; i<lis.length; i++) {
        if (lis[i].style.display == 'none') {
            lis[i].style.display = 'list-item';
            break;
        }
    }
    
    var num_nodes = 0;
    for (i=0; i<list.childNodes.length; i++) {
        if (list.childNodes[i].style.display != 'none') {
            num_nodes++;
        }
    }
    if (num_nodes >= 6) {
        document.getElementById("add_link").style.display = 'none';
    }
    var links = getElementsByClass(list, "remove_links", "a");
    for (i=0; i<links.length; i++) {
        links[i].style.display = (num_nodes == 1) ? 'none':'inline';
    }
}

function remove_ptime(e) {
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3)
        targ = targ.parentNode;
    row = targ.parentNode.parentNode.parentNode;
    tbody = row.parentNode;
    tbody.removeChild(row);
    if (tbody.childNodes.length == 2) { //2, since first is header
        var link = getElementsByClass(tbody, "remove_links", "a");
        link[0].style.display = 'none';
    }
    return false;
}

function add_ptime(pid) {
    var container;
    if (pid == "")
        container = document.getElementById("personaltimecontainer");
    else
        container = document.getElementById("personaltimecontainer_" + pid);
    container = container.childNodes[0];
    var nodes = container.childNodes;
    var new_pos = nodes.length - 1;
    var start = createTime();
    var end = createTime();
    var days = createDays();
    
    start.childNodes[0].selectedIndex = 11;
    start.childNodes[2].selectedIndex = 0;
    start.childNodes[3].selectedIndex = 0;
    end.childNodes[0].selectedIndex = 11;
    end.childNodes[2].selectedIndex = 0;
    end.childNodes[3].selectedIndex = 0;
    
    var remove_link = document.createElement("span");
    remove_link.className = "small";
    var link = document.createElement("a");
    link.href = "#";
    link.onclick = remove_ptime;
    link.className = "remove_links";
    link.appendChild(document.createTextNode("Remove"));
    remove_link.appendChild(link);
    var newrow = document.createElement("tr");
    newrow.id = "p_time_row_" + new_pos;
    var td = document.createElement("td");
    td.appendChild(start);
    newrow.appendChild(td);
    td = document.createElement("td");
    td.appendChild(document.createTextNode(" - "));
    newrow.appendChild(td);
    td = document.createElement("td");
    td.appendChild(end);
    newrow.appendChild(td);
    td = document.createElement("td");
    td.appendChild(document.createTextNode(" "));
    newrow.appendChild(td);
    td = document.createElement("td");
    td.appendChild(days);
    newrow.appendChild(td);
    td = document.createElement("td");
    td.appendChild(remove_link);
    newrow.appendChild(td);
    container.appendChild(newrow);
    
    if (container.childNodes.length > 2) { //2, since first is header
        var link = getElementsByClass(container, "remove_links", "a");
        link[0].style.display = 'inline';
    }
}

function getTimes(time) {
    if (time == "") {
        return new Array(new Array(12, "00", "am", 12, "00", "am", ""));
    }
    var ret_val = new Array();
    var ret_val_pos = 0;
    var ranges = time.split(',');
    for (var i=0; i<ranges.length; i++) {
        var tmp = ranges[i].split('-');
        var start = tmp[0] % 288;
        var end = tmp[1] % 288;
        var day = Math.floor(tmp[0] / 288);
        var hours_start = Math.floor((start * 5) / 60);
        var min_start = (start * 5) % 60;
        if ((min_start+"").length == 1) {
            min_start = "0" + min_start;
        }
        var ampm_start = "";
        if (hours_start >= 12) {
            ampm_start = "pm";
        }
        else {
            ampm_start = "am";
        }
        if (hours_start >= 13) {
            hours_start -= 12;
        }
        if (hours_start == 0) {
            hours_start = 12;
        }
        var hours_end = Math.floor((end * 5) / 60);
        var min_end = (end * 5) % 60;
        if ((min_end+"").length == 1) {
            min_end = "0" + min_end;
        }
        var ampm_end = "";
        if (hours_end >= 12) {
            ampm_end = "pm";
        }
        else {
            ampm_end = "am";
        }
        if (hours_end >= 12) {
            hours_end -= 12;
        }
        if (hours_end == 0) {
            hours_end = 12;
        }

        var found = false;
        for (var j=0; j<ret_val.length; j++) {
            var r = ret_val[j];
            if (r[0]==hours_start && r[1]==min_start && r[2]==ampm_start &&
                r[3]==hours_end && r[4]==min_end && r[5]==ampm_end) {
                ret_val[j][6] = ret_val[j][6] + "" + day;
                found = true;
            }
        }
        if (found == false) {
            ret_val[ret_val_pos] = new Array(hours_start, min_start,
                                             ampm_start, hours_end, min_end,
                                             ampm_end, day);
            ret_val_pos++;
        }
    }
    return ret_val;
}

function createTime() {
    var hour = document.createElement("select");
    for (j=1; j<=12; j++) {
        var option = document.createElement("option");
        var text = document.createTextNode("" + j);
        option.appendChild(text);
        option.setAttribute("value", j);
        hour.appendChild(option);
    }
    var min = document.createElement("select");
    for (j=0; j<=55; j+=5) {
        var option = document.createElement("option");
        var text = "" + j;
        if (text.length == 1) {
            text = "0" + text;
        }
        var textnode = document.createTextNode("" + text);
        option.appendChild(textnode);
        option.setAttribute("value", j);
        min.appendChild(option);
    }
    var ampm = document.createElement("select");
    var option = document.createElement("option");
    option.appendChild(document.createTextNode("am"));
    option.setAttribute("value", "am");
    ampm.appendChild(option);
    var option = document.createElement("option");
    option.appendChild(document.createTextNode("pm"));
    option.setAttribute("value", "pm");
    ampm.appendChild(option);
    var span = document.createElement("span");
    span.appendChild(hour);
    span.appendChild(document.createTextNode(":"));
    span.appendChild(min);
    span.appendChild(ampm);
    return span;
}

function createDays() {
    var days = new Array();
    var dow = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    var span = document.createElement("span");
    for (j=0; j<7; j++) {
        var checkbox = document.createElement("input");
        checkbox.setAttribute("type", "checkbox");
        span.appendChild(document.createTextNode(" "+dow[j]));
        span.appendChild(checkbox);
    }
    return span;
}

function setPersonalTimes(name,time,pid) {
    var ranges = new Array();
    var i = 0;
    var j = 0;
    var pos = 0;
    var container;
    if (pid == "")
        container = document.getElementById("personaltimecontainer");
    else
        container = document.getElementById("personaltimecontainer_" + pid);
    container = container.childNodes[0];
    var nodes = container.childNodes;
    //Remove current time selection elements
    for (i=1; i<nodes.length; i++) {
        container.removeChild(nodes[i]);
        i--;
    }
    var times = getTimes(time);
    //Insert lines of time selection elements
    for (i=0; i<times.length; i++) {
        var start = createTime();
        var end = createTime();
        var days = createDays();
        for (j=0; j<7; j++) {
            if ((""+times[i][6]).indexOf(j+"") != -1) {
                days.childNodes[(j*2)+1].defaultChecked = true;
            }
        }
        var remove_link = document.createElement("span");
        remove_link.className = "small";
        var link = document.createElement("a");
        link.href = "#";
        link.onclick = remove_ptime;
        link.appendChild(document.createTextNode("Remove"));
        link.className = "remove_links";
        remove_link.appendChild(link);
        start.childNodes[0].selectedIndex = times[i][0]-1;
        start.childNodes[2].selectedIndex = times[i][1] / 5;
        start.childNodes[3].selectedIndex = (times[i][2] == "am") ? 0:1;
        end.childNodes[0].selectedIndex = times[i][3]-1;
        end.childNodes[2].selectedIndex = times[i][4] / 5;
        end.childNodes[3].selectedIndex = (times[i][5] == "am") ? 0:1;
       
        var newrow = document.createElement("tr");
        newrow.id = "p_time_row_" + i;
        var td = document.createElement("td");
        td.appendChild(start);
        newrow.appendChild(td);
        td = document.createElement("td");
        td.appendChild(document.createTextNode(" - "));
        newrow.appendChild(td);
        td = document.createElement("td");
        td.appendChild(end);
        newrow.appendChild(td);
        td = document.createElement("td");
        td.appendChild(document.createTextNode(" "));
        newrow.appendChild(td);
        td = document.createElement("td");
        td.appendChild(days);
        newrow.appendChild(td);
        td = document.createElement("td");
        td.appendChild(remove_link);
        newrow.appendChild(td);
        container.appendChild(newrow);
    }
    if (container.childNodes.length == 2) { //2, since first is header
        var link = getElementsByClass(container, "remove_links", "a");
        link[0].style.display = 'none';
    }
}

//Validates a single personal time box, returns array of errors
function validateTimeBox(container) {
    container = container.childNodes[0];
    var nodes = container.childNodes;
    var j = 0;
    var internal_times = new Array();
    var error_messages = new Array();
    //Validate each row
    for (i=1; i<nodes.length; i++) {
        //Validate this row
        var start_nodes = nodes[i].childNodes[0].childNodes[0].childNodes;
        var start_hours = start_nodes[0].selectedIndex + 1;
        var start_min = start_nodes[2].selectedIndex * 5;
        if ((start_min+"").length == 1) {
            start_min = "0" + start_min;
        }
        var start_ampm = (start_nodes[3].selectedIndex == 0) ? "am":"pm";
        
        var end_nodes = nodes[i].childNodes[2].childNodes[0].childNodes;
        var end_hours = end_nodes[0].selectedIndex + 1;
        var end_min = end_nodes[2].selectedIndex * 5;
        if ((end_min+"").length == 1) {
            end_min = "0" + end_min;
        }
        var end_ampm = (end_nodes[3].selectedIndex == 0) ? "am":"pm";

        var dow_nodes = nodes[i].childNodes[4].childNodes[0].childNodes;
        var dow = "";
        for (j=0; j<7; j++) {
            if (dow_nodes[(j*2)+1].checked == true) {
                dow += j;
            }
        }
        var internal_start = start_hours;
        if (start_hours != 12 && start_ampm == "pm") {
            internal_start += 12;
        }
        if (start_hours == 12 && start_ampm == "am") {
            internal_start = 0;
        }
        internal_start *= 12;
        internal_start += start_min / 5;
        var internal_end = end_hours;
        if (end_hours != 12 && end_ampm == "pm") {
            internal_end += 12;
        }
        if (end_hours == 12 && end_ampm == "am") {
            internal_end = 0;
        }
        if (end_hours == 12 && end_ampm == "am" && end_min == 0) {
            internal_end = 288;
        }
        else {
            internal_end *= 12;
            internal_end += end_min / 5;
        }
        if (internal_end <= internal_start) {
            error_messages[error_messages.length] = start_hours+":"+start_min+
                start_ampm+"-"+end_hours+":"+end_min+end_ampm+
                " is not a valid time range";
        }
        if (dow == "") {
            error_messages[error_messages.length] = start_hours+":"+start_min+
                start_ampm+"-"+end_hours+":"+end_min+end_ampm+
                " does not have any days of the week checked";
        }
        for (j=0; j<dow.length; j++) {
            internal_times[internal_times.length] = 
                ((internal_start*1) + (dow.charAt(j)*288)) + "-" +
                ((internal_end*1) + (dow.charAt(j)*288));
        }
    }
    var ret_val = new Array();
    ret_val["error_messages"] = error_messages;
    ret_val["internal_times"] = internal_times;
    return ret_val;
}

//Validates the new personal event box, sets internal time string
function validateSubmitTimes() {
    var container = document.getElementById("personaltimecontainer");
    var validate_return = validateTimeBox(container);
    var addedit = document.getElementById("addedit");
    var node;
    while (addedit.childNodes.length > 2) {
        node = addedit.childNodes[0];
        addedit.removeChild(node);
    }
    if (validate_return["error_messages"].length > 0) {
        var div = document.createElement("div");
        div.className = "error";
        if (validate_return["error_messages"].length > 1) {
            div.appendChild(document.createTextNode("There were errors with " +
                "your new personal event:"));
        }
        else {
            div.appendChild(document.createTextNode("There was an error with" +
                " your new personal event:"));
        }
        var ul = document.createElement("ul");
        for (j=0; j<validate_return["error_messages"].length; j++) {
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(
                validate_return["error_messages"][j]));
            ul.appendChild(li);
        }
        div.appendChild(ul);
        addedit.insertBefore(div, addedit.childNodes[0]);
    }
    else {
        var form = document.getElementById("addeditf");
        form.p_time.value = validate_return["internal_times"].join(",");
        form.submit();
    }
}

//Validates all existing personal event box, sets internal time strings
function validateSubmitTimes2() {
    var pids = allPids();
    var all_errors = new Array();
    var container;
    var validate_return;
    var div;
    var ul;
    var li;
    var addedit;
    var form;
    var name;
    var do_submit;
    var node;
    var to_remove;
    form = document.getElementById("addeditf2");
    addedit = document.getElementById("addedit");
    do_submit = true;
    while (addedit.childNodes.length > 2) {
        node = addedit.childNodes[0];
        addedit.removeChild(node);
    }
    for(var i=0; i<pids.length; i++) {
        //If this event is set to be removed, don't validate
        to_remove = document.getElementsByName("p_remove_" + pids[i]);
        if (to_remove[0].checked == true)
            continue;
        container = 
            document.getElementById("personaltimecontainer_" + pids[i]);
        validate_return = validateTimeBox(container);
        name = form["p_name_" + pids[i]].value;
        if (validate_return["error_messages"].length > 0) {
            div = document.createElement("div");
            div.className = "error";
            if (validate_return["error_messages"].length > 1) {
                div.appendChild(document.createTextNode(
                "There were errors modifying your personal event "+name+":"));
            }
            else {
                div.appendChild(document.createTextNode(
                "There was an error modifying your personal event "+name+":"));
            }
            ul = document.createElement("ul");
            for (j=0; j<validate_return["error_messages"].length; j++) {
                li = document.createElement("li");
                li.appendChild(document.createTextNode(
                    validate_return["error_messages"][j]));
                ul.appendChild(li);
            }
            div.appendChild(ul);
            addedit.insertBefore(div, addedit.childNodes[0]);
            do_submit = false;
        }
        else
            form["p_time_" + pids[i]].value = 
                validate_return["internal_times"].join(",");
    }
    if (do_submit == true)
        form.submit();
}
    
function number_type(id) {
    var first = document.getElementById(id + "_1");
    var span = document.getElementById(id + "_extra_number");
    var select = document.getElementById(id);
    if (select.options[select.selectedIndex].value == "between")
        span.style.visibility="visible";
    else
        span.style.visibility="hidden";
    if (select.options[select.selectedIndex].value == "") {
        first.value = "";
        first.disabled = true;
    }
    else {
        first.disabled = false;
    }
}
    

function set_binding_inputs() {
    var classnum = 0;
    var bindingnum = 0;
    var field;
    var bindings;
    var outarray;
    var outid;
    var group;
    var i;
    var test;
    var tmp;
    
    while (true) {
        test = document.getElementById("class" + classnum);
        if (test == null)
            break;
        field = document.getElementById("bindings_input_" + classnum);
        if (field == null) {
            classnum++;
            continue;
        }
        outid = document.getElementById("bindings_input_" + classnum);
        if (document.getElementById("bindings_" + classnum).style.display ==
                "none") {
            outid.value = "none";
        }
        else {
            bindingnum = 0;
            outarray = new Array();
            while (true) {
                group = document.getElementById("b_"+classnum+"_"+bindingnum);
                if (group == null)
                    break;
                bindings = new Array();
                for (i=0; i<group.childNodes.length; i++) {
                    bindings[i] = group.childNodes[i].className;
                }
                outarray[bindingnum] = bindings.join(",");
                bindingnum++;
            }
        }
        outid.value = outarray.join("/");
        classnum++;
    }
}

function bindings(bid) {
    var span = document.getElementById("blink"+bid);
    var table = document.getElementById("bindings_"+bid);
    if (table.style.display == "none") {
        table.style.display = "block";
        span.removeChild(span.childNodes[0]);
        span.appendChild(document.createTextNode("Disable Bindings"));
    }
    else {
        table.style.display = "none";
        span.removeChild(span.childNodes[0]);
        span.appendChild(document.createTextNode("Enable Bindings"));
    }
}

function section_select(obj, active) {
    //alert('hello');
    var inputs = obj.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("input");
    var i;
    for (i=0; i<inputs.length; i++)
        if (inputs[i].type == "checkbox" && inputs[i].disabled != true)
                inputs[i].checked = active;
    return false;
}

function display_all_supported_schools(dummy) {
    $("list_of_schools").addClassName("hidden");
    $("list_of_all_schools").removeClassName("hidden");
}

//this function hides the element with given css_id
function unshow(css_id){
    css_element = $(css_id);
    css_element.addClassName('hidden');
}

function unhide(css_id){
    css_element = $(css_id);
    css_element.removeClassName('hidden');
}
