$(document).ready(function(){
    loadtextsize();
    loadprograms();
    loadterms();
    loadbooks();
$('#timestamp').fadeIn('fast',function() {
    loadclasses(); 
});
});

// fixing strings

function state(cell, success_msg, failure_msg) {
  if ((typeof(cell)=="string" && cell.length > 0) || typeof(cell)=='number') {
    if  (success_msg==null || typeof(success_msg)==undefined) {
      return(cell.replace(/&apos;/g,'\''));
//	return(cell);
    }
    return(success_msg);
  }
  if (failure_msg != null && typeof(success_msg) != undefined) {
    return(failure_msg);
  }
  return "";
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function urlencode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function urldecode(encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%.{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

function showdepartment(dept,deptcode,depttype,hyphen,dept_index) {
    department = '<option value="'+deptcode.toLowerCase()+'"';
    if(thisdept == deptcode.toLowerCase()) {
        department += ' selected="selected"';
        deptindex = dept_index;
    }
    department += '>';
    if(hyphen) {
        department += '- ';
    }
    department += dept+' ('+deptcode+')</option>';
    return department;
}

function loadterms() {
    var termsrc = '/ws/soc/api1c/terms';
    $.getJSON(termsrc, function(json) {   
        termscode = '';
        for(i=0; i<json.term.length; i++) {
            if(json.term[i].substring(4) == 1) { termname = 'Spring'; }
            if(json.term[i].substring(4) == 2) { termname = 'Summer'; }
            if(json.term[i].substring(4) == 3) { termname = 'Fall'; }  
            termyear = json.term[i].substr(0,4);
            termscode += '<option value="'+ json.term[i] + '"';
            if(json.term[i]==thisterm) {
                termscode += ' selected="selected"';
                termindex = i;
            }
            termscode += '>' + termname + ' ' + termyear + '</option>';
        }
        $("#termselect").html(termscode);
    });
}

function loadbooks() {
    var booksrc = '/ws/soc/hasbooks.js/'+thisterm.substring(2);
    $.getJSON(booksrc, function(json) {
	$('#main_parent').append('<input type="hidden" id="booksec" value="'+json+'" />');
    });
}

function loadclasses() {
    $("#data").hide();
    $("#data").ajaxError(function(request, settings){
	if(courses_empty) {
	    class_list = '';
//<p class="error">Sorry, there are no courses listed for the requested department in this term.</p>';
	} else {
	    class_list = '';
//<p class="error">Sorry, there was an error loading data.</p>';
	}
	$("#course_table").prepend(class_list);
	$("#data").fadeIn("fast",function() { $("#content").css("background-image","none"); });
    });
    courses_empty = 1;
    $.getJSON(coursesrc, function(json) {
	if(json) {
	    showdeptheader(json.Dept_Info);
	    if(state(json.schd_sync_dtm)) {
		$("#timestamp").html("Information accurate as of <strong>" + json.schd_sync_dtm + "</strong>.");
//if(archive) { $("#timestamp").append( <a href=\"/ws/soc_archive/soctest/" + thisterm + "/" + thisdept + ".html\">Archive version</a>"); }
	    }

	    // Class list
	    if(json.OfferedCourses) {
		if(json.OfferedCourses.course) {
		    showcourselist(json.OfferedCourses,json.Dept_Info.abbreviation,json.Dept_Info.department,thisterm);
		    courses_empty = 0;
		}
	    } 
	}
	if(courses_empty) {
	    class_list = '<p class="empty">Sorry, the course list for the requested department in this term is unavailable.</p>';
	    $("#course_table").append(class_list);
	    $("#data").fadeIn("fast",function() { $("#content").css("background-image","none"); });
	}
    });

}

function loadprograms() {
    var deptsrc = '/ws/soc/api1c/departments/'+thisterm;
    $.getJSON(deptsrc, function(json) {
        var programs = '';
        var di = 0;
        for(i=0; i<json.department.length; i++) {
            if(json.department[i].type!='Y') {
                programs += showdepartment(json.department[i].name,json.department[i].code,json.department[i].type,0,di); di++;
            } else {
                var deptlength = 1;
                programs += '<option value="none" disabled="disabled">' + json.department[i].name + '</option>';
                di++;
                if(json.department[i].department.length) {
                    deptlength = json.department[i].department.length;
                    for(j=0; j< deptlength; j++) {
                        programs += showdepartment(json.department[i].department[j].name,json.department[i].department[j].code,json.department[i].department[j].type,1,di);
                        di++;
                    }
                } else {
                    programs += showdepartment(json.department[i].department.name,json.department[i].department.code,json.department[i].department.type,1,di);
                    di++;
                }
            }
        }
        $('#programs').html(programs);
    });
}

function showdeptheader(deptinfo) {
    // Page title
    document.title = deptinfo.department + ' | USC Schedule of Classes';

    // Department header
    $("#dept_title").append(deptinfo.department+' <strong>(<abbr title="'+deptinfo.department+'">'+deptinfo.abbreviation+'</abbr>)</strong>');
    var contact_info = '';
    if(state(deptinfo.dept_url)) {
	contact_info += '<li class="link"><a href="'+deptinfo.dept_url+'">'+deptinfo.dept_url+'</a>';
    }

    if(trim(deptinfo.phone_number) != '-' || state(deptinfo.address)) {
        contact_info += '<li class="contact">D class assignments available';
        if(state(deptinfo.address)) { contact_info += ' in '+deptinfo.address; }
        if(trim(deptinfo.phone_number) != '-') { contact_info += '; phone '+deptinfo.phone_number; }
        contact_info += '.</li>';
    }
    if(trim(deptinfo.ugrad_dclass_phone_number) != '-' || state(deptinfo.ugrad_dclass_address)) {
        contact_info += '<li class="contact">D class assignments for undergraduates available';
        if(state(deptinfo.ugrad_dclass_address)) { contact_info += ' in '+deptinfo.ugrad_dclass_address; }
        if(trim(deptinfo.ugrad_dclass_phone_number) != '-') { contact_info += '; phone '+deptinfo.ugrad_dclass_phone_number; }
        contact_info += '.</li>';
    }  
    if(trim(deptinfo.grad_dclass_phone_number) != '-' || state(deptinfo.grad_dclass_address)) {
        contact_info += '<li class="contact">D class assignments for graduate students available';   
        if(state(deptinfo.grad_dclass_address)) { contact_info += ' in '+deptinfo.grad_dclass_address; }
        if(trim(deptinfo.grad_dclass_phone_number) != '-') { contact_info += '; phone '+deptinfo.grad_dclass_phone_number; }
        contact_info += '.</li>';
    }
    if(contact_info) { $("#dept_notices").append(contact_info); }

    // Departmental notes
    var dept_notes = '';
    if(state(deptinfo.Notes)) { dept_notes += '<li class="note">'+deptinfo.Notes+'</li>'; }
    if(state(deptinfo.TermNotes)) { dept_notes += '<li class="termnote">'+deptinfo.TermNotes+'</li>'; }
    if(dept_notes) { $("#dept_notices").append(dept_notes); }
}

function showcourselist(offeredcourses,dept,department,term) {
    var course_list = '';
if(offeredcourses.course[0]) {
    for(i=0; i<offeredcourses.course.length; i++) {
        published = state(offeredcourses.course[i].PublishedCourseID);
        course_list = '<div class="course_info expandable" id="'+published+'"><div class="course_id">';
        course_list += showcoursetitle(published,offeredcourses.course[i],dept,0);
        course_list += '</div><div class="course_details" id="'+published+'_details">';
        course_list += showcoursedetails(offeredcourses.course[i],department,0,term);
        if((offeredcourses.course[i].ConcurrentCourse) && (published != 'WRIT-140') && (published != 'MDA-140')) {
            if(state(offeredcourses.course[i].ConcurrentCourse.PublishedCourseID)) {
                published = offeredcourses.course[i].ConcurrentCourse.PublishedCourseID;
                course_list += '<div class="concurrent"><a name="'+published+'_concurrent"></a>';
                course_list += showcoursetitle(published,offeredcourses.course[i].ConcurrentCourse,offeredcourses.course[i].ConcurrentCourse.CourseData.prefix,1);
                course_list += showcoursedetails(offeredcourses.course[i].ConcurrentCourse,department,1,term);
                course_list += '</div>';
	    } else {
                for(j=0; j<offeredcourses.course[i].ConcurrentCourse.length; j++) {
                    published = offeredcourses.course[i].ConcurrentCourse[j].PublishedCourseID;
                    course_list += '<div class="concurrent"><a name="'+published+'_concurrent"></a>';
                    course_list += showcoursetitle(published,offeredcourses.course[i].ConcurrentCourse[j],offeredcourses.course[i].ConcurrentCourse[j].CourseData.prefix,1);
                    course_list += showcoursedetails(offeredcourses.course[i].ConcurrentCourse[j],department,1,term);
                    course_list += '</div>';
                }
            }
        }


        course_list += '</div></div>';
        $("#course_table").append(course_list);
        if((i+1)==offeredcourses.course.length) {
            $(".course_details").slideUp("fast");
            finished();
        }
    } 
} else {
        published = state(offeredcourses.course.PublishedCourseID);
        course_list = '<div class="course_info expandable" id="'+published+'"><div class="course_id">';
        course_list += showcoursetitle(published,offeredcourses.course,dept,0);
        course_list += '</div><div class="course_details" id="'+published+'_details">';
        course_list += showcoursedetails(offeredcourses.course,department,0,term);
        if((offeredcourses.course.ConcurrentCourse) && (published != 'WRIT-140') && (published != 'MDA-140')) {
                published = offeredcourses.course.ConcurrentCourse.PublishedCourseID;
                course_list += '<div class="concurrent"><a name="'+published+'_concurrent"></a>';
                course_list += showcoursetitle(published,offeredcourses.course.ConcurrentCourse,offeredcourses.course.ConcurrentCourse.CourseData.prefix,1);
                course_list += showcoursedetails(offeredcourses.course.ConcurrentCourse,department,1,term);
                course_list += '</div>';
        }
        course_list += '</div></div>';
        $("#course_table").append(course_list);
	$(".course_details").slideUp("fast");
	finished();
    }
}

function finished() {
    expansion();
    TB_init(); 
    $("#content").css("background-image","none");
    $("#data").fadeIn("fast",function() {
	document.display.terms.selectedIndex = termindex;
	document.display.programs.selectedIndex = deptindex;
    });
}

function showcoursetitle(published,course,dept,concurrency) {
    prefix = state(course.CourseData.prefix);
    suffix = state(course.CourseData.suffix);
    coursetitle = state(course.CourseData.title);
    units = state(course.CourseData.units);
    if(units.match(', ')) {
        if(units.substring(0,2)!='1,') {
            units = units.replace(', ',' units, max ');
        } else {
            units = units.replace(', ',' unit, max ');
        }
    } else { 
        if(units=='1') { 
            units += ' unit'; 
        } else {
            units += ' units'; 
        }
    }
    crosslist = state(course.IsCrossListed);
    course_title = '<h3>';
    if(concurrency==1) {
        course_title += 'Concurrent Course<br />';
    } 
    if(crosslist=='Y') { course_title += '<span class="crosslist">Crosslist </span>'; }
    course_id = published.toLowerCase();
    course_id += suffix;
    if(prefix) { course_id = course_id.replace(dept.toLowerCase(),dept); course_id = course_id.replace(prefix.toLowerCase(),prefix); }
    course_id = course_id.replace('-',' ');
    course_title += '<strong>'+course_id+':</strong> '+coursetitle+' <span class="units">(' + units + ')</span></h3>';
    return course_title;
}

function showcoursenotes(course,concurrency) {
    if(state(course.CourseNotes)) {
        course_notes = '<li class="alert"><strong>Note:</strong> '+course.CourseNotes+' </li>';
    } else {
        if(course.SectionData[0]) {
            if(state(course.SectionData[0].description)) {
                course_notes = '<li class="alert"><strong>Note:</strong> '+course.SectionData[0].description+' </li>';
            } else {
                course_notes = '';
            }
        } else {
            if(state(course.SectionData.description)) {
                course_notes = '<li class="alert"><strong>Note:</strong> '+course.SectionData.description+' </li>';
            } else {
                course_notes = '';
            }
        }
    }
    if(state(course.CourseTermNotes)) {
        course_notes += '<li class="termnote"><strong>Note:</strong> '+course.CourseTermNotes+' </li>';
    }

if(course_notes) {
    course_notes = fixnote(course_notes);
    return course_notes;
} else {
    return '';
}
}

function showconcurrencynotes(course,concurrency) {
    concurrency_notes = '';
    if(course.ConcurrentCourse) {
        if(course.ConcurrentCourse[0]) {
            if((concurrency==1)||((course.PublishedCourseID!='WRIT-140')&&(course.PublishedCourseID!='MDA-140'))) {
                for(o=0; o<course.ConcurrentCourse.length; o++) {
                    concurrency_notes += '<li class="concurrency"><strong>Concurrent enrollment:</strong> <a href="#'+course.ConcurrentCourse[o].PublishedCourseID+'_concurrent">'+course.ConcurrentCourse[o].PublishedCourseID+'</a></li>';
                }   
            } else {
		if(course.PublishedCourseID=='WRIT-140') {
		    concurrency_notes += '<li class="alert">WRIT 140 is offered as a concurrent writing section for the courses listed in <strong><a href="si.html">General Education, Social Issues (SI)</a></strong>. Follow the links below for information about these courses:</li>';
		} else {
		    concurrency_notes += '<li class="alert">MDA 140 is offered as a concurrent multimedia authorship section for the courses listed in <strong><a href="cmm.html">General Education, Core Multi-Media (CMM)</a></strong>. Follow the links below for information about these courses:</li>';
		}
		for(o=0; o<course.ConcurrentCourse.length; o++) {		
		    concurrency_notes += '<li class="go"><a href="'+course.ConcurrentCourse[o].CourseData.prefix.toLowerCase()+'.html?c=' + course.ConcurrentCourse[o].PublishedCourseID + '"><strong>' + course.ConcurrentCourse[o].CourseData.prefix + ' ' + course.ConcurrentCourse[o].CourseData.number + state(course.ConcurrentCourse[o].CourseData.suffix) + ':</strong> ' + course.ConcurrentCourse[o].CourseData.title + '</a></li>';
		}
            }
        } else {
            if((concurrency==1)||((course.PublishedCourseID!='WRIT-140')&&(course.PublishedCourseID!='MDA-140'))) {
                concurrency_notes += '<li class="concurrency"><strong>Concurrent enrollment:</strong> <a href="#'+course.ConcurrentCourse.PublishedCourseID+'_concurrent">'+course.ConcurrentCourse.PublishedCourseID+'</a></li>';
            }
        }
    }
    return concurrency_notes;
}

function fixnote(note) {
    if(note) {
        note += ' ';
        note = note.replace(/Lec /g,"Lecture ");
        note = note.replace(/lec /g,"lecture ");
        note = note.replace(/lec,/g,"lecture,");
        note = note.replace(/lec\./g,"lecture.");
        note = note.replace(/lec-/g,"lecture-");
        note = note.replace(/Dis /g,"Discussion ");
        note = note.replace(/dis /g,"discussion ");
        note = note.replace(/dis,/g,"discussion,");
        note = note.replace(/dis\./g,"discussion.");
        note = note.replace(/dis\)/g,"discussion)");
        note = note.replace(/ 1 /g," one ");
        note = note.replace(/\&amp; /g,"and ");
        note = note.replace(/qz/g,"quiz");
        return note;
    }
}

function showcoursedetails(course,dept,concurrency,term) {
    // catalogue text
    var coursedetails = '<div class="catalogue">' + state(course.CourseData.description);
    if(state(course.CourseData.prereq_text)) { coursedetails += ' <em>Prerequisite:</em> '+course.CourseData.prereq_text; } 
    if(state(course.CourseData.coreq_text)) { coursedetails += ' <em>Corequisite:</em> '+course.CourseData.coreq_text; }    
    coursedetails += '</div><ul class="notes">';
    if(state(course.CourseData.restriction_by_major)) { coursedetails += '<li class="restriction"><strong>Restriction:</strong> '+course.CourseData.restriction_by_major+'</li>'; }
    if(state(course.CourseData.restriction_by_class)) { coursedetails += '<li class="restriction"><strong>Restriction:</strong> '+course.CourseData.restriction_by_class+'</li>'; }
    if(state(course.CourseData.restriction_by_school)) { coursedetails += '<li class="restriction"><strong>Restriction:</strong> '+course.CourseData.restriction_by_school+'</li>'; }
    if(course.IsCrossListed=='Y') { coursedetails += '<li class="crosslist"><strong>Crosslist:</strong> This course is offered by the '+course.CourseData.prefix+' department but qualifies for major credit in '+dept+'. To register, enroll in <a href="'+course.CourseData.prefix.toLowerCase()+'.html?c='+course.CourseData.prefix+'-'+course.CourseData.number+'">'+course.CourseData.prefix+' '+course.CourseData.number+'</a>.</li>'; }
    coursedetails += showcoursenotes(course.CourseData,concurrency);
    coursedetails += showconcurrencynotes(course,concurrency);
    coursedetails += '</ul>';

if((concurrency==1)||((course.PublishedCourseID!='WRIT-140')&&(course.PublishedCourseID!='MDA-140'))) {
    coursedetails += showsections(course,term);
} 
    return coursedetails;
}

function showsections(course,term) {
    sections = '<table class="sections" cellspacing="0"><tr class="headers">';
    
    if(term.substring(4) == 2) {
	sections += '<th width="5%" class="session">Session</th>';
    }
    sections += '<th class="section" width="10%">Section</th>';
    if(course.CourseData.units.match(',')) {
        comma_position = course.CourseData.units.indexOf(',');
    } else {
        comma_position = course.CourseData.units.length;
    }
    if(course.CourseData.SectionData[0]) {
        section_units = course.CourseData.SectionData[0].units;
    } else {
        section_units = course.CourseData.SectionData.units;
    }
    if((course.CourseData.units.match('-')) && (state(course.CourseData.SectionData[1]) || (course.CourseData.units.substring(0,comma_position) != section_units))) {
        var units_vary = 1;
        sections += '<th class="units" width="5%">Units</th>';
    }
    sections += '<th class="type" width="10%">Type</th><th class="time" width="15%">Time</th><th class="days" width="10%">Days</th>';

    if(units_vary) {
        sections += '<th class="registered" width="10%">Registered</th>';
    } else { 
        sections += '<th class="registered" width="15%">Registered</th>'; 
    }
    sections += '<th class="instructor" width="';
    if(term.substring(4) == 2) {
        sections += '10';
    } else {
        sections += '12';
    }
    sections += '%">Instructor</th><th class="location" width="10%">Location</th><th class="syllabus" width="10%%">Syllabus</th><th class="info" width="';
    if(term.substring(4) == 2) {
        sections += '10';
    } else {
        sections += '13';
    }
    sections += '%">Info</th></tr>';

    if(course.CourseData.SectionData[0]) {
        for(k=0; k<course.CourseData.SectionData.length; k++) { 
            sections += showsection(course.CourseData.SectionData[k],course.CourseData.title,k,units_vary,term);
        } 
    } else { 
        sections += showsection(course.CourseData.SectionData,course.CourseData.title,0,units_vary,term);
    }

    sections += '</table>';

    return sections;
}

function fixtime(time,ampm) {
    hours = time.substring(0,2);
    if(hours[0]=='0') {
        hours = hours.substring(1);
    }
    if(hours > 11) {
if(hours > 12) {
        hours = hours - 12;
}
        meridiem = 'pm';
    } else {
        meridiem = 'am';
    }
    minutes = time.substring(3,5);
    fixed = hours + ':' + minutes;
    if(ampm) {
        fixed += meridiem;
    }
    return fixed;
}

function fixday(day) {
    if(day.length==1) {
        day = day.replace("M","Monday");
        day = day.replace("T","Tuesday");
        day = day.replace("W","Wednesday");
        day = day.replace("H","Thursday");
        day = day.replace("F","Friday");
        day = day.replace("S","Saturday");
    } else {
        day = day.replace("H","Th");
    }
    return day;
}

function showsection(section,course_title,section_index,units_vary,term) {

    section_id = state(section.id);
    section_type = state(section.type);
    section_type = section_type.replace('Dis','Discussion');
    section_type = section_type.replace('Qz','Quiz');
    section_type = section_type.replace('Lec','Lecture');
    multiline = 0;

    start_time = end_time = times = '';
    if(state(section.start_time)) {
        start_time = state(section.start_time);
        end_time = state(section.end_time);
    } else {
        start_time = end_time = '';
        if(section.start_time) {
            start_time = section.start_time[0]; 
            end_time = section.end_time[0];
	    times = section.start_time.length;
            multiline = 1;
        }
    }

    section_day = days = '';
    if(state(section.day)) {
        section_day = fixday(state(section.day));
    } else {
        section_day = '';
        if(section.day) {
            if(section.day[0]) {
		if(state(section.day[0])) { 
		    if(state(section.day[0])=='TBA') {
			section_day = 'TBA';
		    } else {
		        section_day = fixday(section.day[0]); 
		    }
		}
		days = section.day.length;
                multiline = 1;
            }
        }
    }

    instructor_first = instructor_last = instructor_link = instructors = '';
    if(section.instructor) {
	if(section.instructor.last_name) {
        if(state(section.instructor.last_name)) {
            instructor_last = state(section.instructor.last_name);
            instructor_first = state(section.instructor.first_name);
	    if(state(section.instructor.bio_url)) {
		instructor_link = state(section.instructor.bio_url);
	    } else {
		instructor_link = '';
	    }
	}
        } else {
            if(state(section.instructor[0].last_name)) {
                instructors = section.instructor.length;
            }
        }
    }

    section_location = locations = '';
    if(section.location) {
        if(state(section.location)) {
            section_location = state(section.location);
        } else {
            section_location = '';
            if(section.location) {
                if(section.location[0]) {
		    section_location = state(section.location[0]);
		    locations = section.location.length;
                    multiline = 1;
                }
            }
        }
    } else {
        section_location = 'TBA';
    }

    format = ''; filesize = '';
    if(section.syllabus) {
        if(state(section.syllabus.format)) {
            section_syllabus_format = state(section.syllabus.format);
            if(section_syllabus_format == 'application/pdf') {
                format = 'PDF'; extension = 'pdf';

            } else {
                if(section_syllabus_format.indexOf('word')!=-1) {
                    format = 'Word'; extension = 'doc';
                }
            }
        }
        if(state(section.syllabus.filesize)) {
            section_syllabus_filesize = state(section.syllabus.filesize);
            if(section_syllabus_filesize.length < 4) {
                filesize = section_syllabus_filesize + ' bytes';
            } else {
                if(section_syllabus_filesize.length < 7) {
                    filesize = section_syllabus_filesize + ' KB';
                } else {
                    if(section_syllabus_filesize.length < 10) {
                        filesize = section_syllabus_filesize + ' MB';
                    } else {
                        if(section_syllabus_filesize.length < 7) {
                            filesize = section_syllabus_filesize + ' GB';
                        }
                    }
                }
            }
        }
    }

    info = ''; infolink = '';

    if(section.comment) {
        if(state(section.comment)) {
            comment = section.comment;
            info += '<img src="../dl_sm.gif" width="16" height="16" border="0" alt="distance learning" />';
            infolink += '&amp;dl=' + urlencode(comment);
        }
    }

    blackboard = state(section.blackboard);
    if(blackboard) {
        if(section.blackboard != 'N') {
            blackboard = 1;
            info += '<img src="../blackboard.gif" width="17" height="13" border="0" alt="Blackboard" />'; 
            infolink += '&amp;b=1';
        }
    }
    if(state(section.notes)) {
        note = section.notes;
        info += '<img src="../alert.gif" width="16" height="12" border="0" alt="note" />'; 
        infolink += '&amp;n=';
        infolink += urlencode(note);
    } else {
	if(section.notes[0]) {
            note = section.notes[0];
            info += '<img src="../alert.gif" width="16" height="12" border="0" alt="note" />';
            infolink += '&amp;n=';
            infolink += urlencode(note);
	}
    }
    if(section.fee) {
        if(state(section.fee.description)) {
            fee_description = section.fee.description;
            infolink += '&amp;f0=';
            infolink += urlencode(fee_description);
            fee_amount = section.fee.amount;
            infolink += '&amp;a0=';
            infolink += urlencode(fee_amount);
            info += '<img src="../moneybag.gif" width="16" height="16" border="0" alt="fee" />';
        } else {
            if(section.fee[0]) {
                for(m=0; m<section.fee.length; m++) {
                    infolink += '&amp;f' + m + '=';
                    infolink += urlencode(section.fee[m].description);
                    infolink += '&amp;a' + m + '=';
                    infolink += urlencode(section.fee[m].amount);
                }
                info += '<img src="../moneybag.gif" width="16" height="16" border="0" alt="fee" />';
            }
        }
    }

    if(section.session) { 
        if((state(section.session)!='001')) {
            session = section.session;
            info += '<img src="../calendar_sm.gif" width="13" height="13" border="0" alt="session dates" />';
            infolink += '&amp;s=' + session;
        } 
    }
    var booksec = document.getElementById('booksec').value;
    if(booksec.indexOf(section.id)!=-1) {
	    info += '<img src="../books.gif" width="16" height="14" border="0" alt="book list" />';
    }
    sec = '';
    if(section_id) {
        if(state(section.section_title)) {
            section_title = section.section_title;
            sec += '<tr class="firstline ';
            if((section_index % 2) != 1) {
                sec += ' odd ';
            }
            sec += section_id+'"><td colspan="';
            if(units_vary) { 
                sec += '10'; 
            } else { 
                sec += '9'; 
            }
            sec += '" class="section_title">' + section_title + '</td></tr>';
        } else {
            section_title = coursetitle;
        }
        sec += '<tr id="' + section_id + '" class="'+section_id+' ';
        if(multiline) {
            sec += 'firstline ';           
        }

        if(section.section_title) {
            sec += 'secondline ';
        }
        if((section_index % 2) != 1) {
            sec += 'odd';
        } else {
            sec += 'even';
        }
        sec += '">';

	if(term.substring(4) == 2) {
	    sec += '<td class="session"><a class="thickbox" href="session.html?width=400&amp;height=400&amp;t='+ term +'&amp;s=' + state(section.session) +'">' + state(section.session) + '</a></td>';
	} 

	sec += '<td class="section">' + section_id + section.dclass_code + '</td>';
        if(units_vary) {
            sec += '<td class="units">' + section.units + '</td>';
        }
        sec += '<td class="type">' + section_type + '</td><td class="time">';
        if(start_time && end_time) {
            if(trim(start_time)=='TBA') { 
                sec += 'TBA';
            } else {
                sec += fixtime(start_time,0) + '-' + fixtime(end_time,1);
            }
        } else {
            sec += 'TBA';
        }
        sec += '</td><td class="days">'
        if(section_day) {
            sec += fixday(section_day);
        } else {
            sec += 'TBA';
        }
        sec += '</td><td class="registered">';
        if(state(section.canceled)=='Y') {
            sec += '<div class="closed">Canceled</div>';
        } else {
            if(parseInt(state(section.number_registered)) < parseInt(state(section.spaces_available))) {
                sec += state(section.number_registered) + ' of ' + state(section.spaces_available);
            } else {
                sec += '<div class="closed">' + state(section.number_registered) + ' of ' + state(section.spaces_available) + '</div>';
            }
            if(parseInt(state(section.wait_qty))) {
                sec += ' (' + state(section.wait_qty) + ' on waitlist)';
            }
        }
        sec += '</td><td class="instructor">';
        if(instructor_first && instructor_last) {
	    if(instructor_link) {
		sec += '<a href="' + instructor_link + '" target="_new">';
	    }
            sec += instructor_first + ' ' + instructor_last;
	    if(instructor_link) {
		sec += '</a>';
	    }
        } else {
            if(instructors) {
                if(!multiline) {
                    for(l=0; l<instructors; l++) {
			if(state(section.instructor[l].bio_url)) {
			    sec += '<a href="' + section.instructor[l].bio_url + '" target="_new">';
			}
                        sec += section.instructor[l].first_name + ' ' + section.instructor[l].last_name;
                        if(state(section.instructor[l].bio_url)) {
                            if((l+1) < instructors) {
				sec += ',';
			    }
                            sec += '</a>';
                        } else {
                        if((l+1) < instructors) {
                            sec += ',<br />';
                        }
			}
                    }
                } else {
                    if(state(section.instructor[0].bio_url)) {
                        sec += '<a href="' + section.instructor[0].bio_url + '" target="_new">';
                    }
                    sec += state(section.instructor[0].first_name) + ' ' + state(section.instructor[0].last_name) + ',';
                    if(state(section.instructor[0].bio_url)) {
			sec += '</a>';
		    } else {
                        sec += '<br />';
                    }
		}
            }
        }
        sec += '</td><td class="location">' + section_location + '</td><td class="syllabus">';
        if(format) {
            format_lower = format.toLowerCase();
            sec += '<a class="' + format_lower + '" href="../syllabus/'+term+'/'+section_id+'.'+extension+'">'+format+'</a> <span class="filesize">('+filesize+')</span>';
        }
        sec += '</td><td class="info">';

            sec += '<a class="thickbox" href="';
	    infolink = 'section.html?width=400&amp;height=400&amp;c=' + urlencode(section_title) + '&amp;i='+section_id+'&amp;t='+term+infolink;
	    sec += infolink + '">';
	if(info) {
	    sec += info;
	}
	sec += '</a>';

        sec += '</td></tr>';
 
        if(multiline) {
            sec += '<tr class="secondline ';
            if((section_index % 2) != 1) {
                sec += ' odd';
            }
            sec += '">';
    if(term.substring(4) == 2) {
        sec += '<td class="session"></td>';
    }
	    sec += '<td class="section"></td>';
            if(units_vary) {
                sec += '<td class="units"></td>';
            }
            sec += '<td class="type"></td><td class="time">';
            if(times) {
                for(t=1; t<times; t++) {
                    if(state(section.start_time[t])) {
                        if(trim(section.start_time[t])=='TBA') {
                            sec += 'TBA<br />';
                        } else {
                            sec += fixtime(section.start_time[t],0) + '-' + fixtime(section.end_time[t],1) + '<br />';
                        }
		    }
                }
            }
            sec += '</td><td class="days">'
            if(days) {
                for(d=1; d<days; d++) {
                    if(state(section.day[d])) {
                        sec += fixday(section.day[d])+'<br />';
                    }
                }
            }
            sec += '</td><td class="registered"></td><td class="instructor">';
            if(instructors) {
                for(l=1; l<instructors; l++) {
                    if(state(section.instructor[l].bio_url)) {
			sec += '<a href="' + section.instructor[l].bio_url + '" target="_new">';
		    }
		    sec += section.instructor[l].first_name + ' ' + section.instructor[l].last_name;
		    if(state(section.instructor[l].bio_url)) {
			if((l+1) < instructors) {
			    sec += ',';
			}
			sec += '</a> ';
		    } else {
			if((l+1) < instructors) {
                            sec += ',<br />';
                        }
		    }
                }
            }
            sec += '</td><td class="location">';
            if(locations) {
                for(p=1; p<locations; p++) {
                    if(state(section.location[p])) {
                        sec += section.location[p]+'<br />';
                    }
                }
            }

            sec += '</td><td class="syllabus"></td><td class="info"></td></tr>';
        }
    }
    return sec;
}

function expansion() {
$("div.course_id h3").mouseup(function(){
        t = this.parentNode.parentNode.className;
        if(t.indexOf('expandable') != -1) {
        $(this.parentNode.parentNode).removeClass("expandable").addClass("expanded");
        $(this.parentNode.nextSibling).slideDown("normal");
	return false;
        } else {
        $(this.parentNode.parentNode).removeClass("expanded").addClass("expandable");
        $(this.parentNode.nextSibling).slideUp("normal");
        }
    });


//expand all
    $("span.expand").mouseup(function(){
        $("div.course_details:hidden").slideDown("normal");
        $("div.expandable").removeClass("expandable").addClass("expanded");;
    });
        
//collapse all
    $("span.collapse").mouseup(function(){
        $("div.course_details:visible").slideUp("normal");
        $("div.expanded").removeClass("expanded").addClass("expandable");   
    });

//initially expanded course
var ss = location.search.substring(1);
if(thiscourse) {
    ss = 'c='+thiscourse+'&s='+thissection;
}
if(ss) {
    exp = ss.indexOf('expand');
    if(exp != -1) {
        $(".course_details").slideDown("fast");
	$(".course_info").removeClass("expandable").addClass("expanded");
    }
    op = ss.indexOf('c=');
    if(op != -1) {
	thiscourse = ss.substring(op+2).toUpperCase();
	if(thiscourse.indexOf('&') != -1) { 
	    thiscourse = thiscourse.substring(0,thiscourse.indexOf('&'));
	    if(ss.indexOf('s=') != -1) { 
		thissection = ss.substring(ss.indexOf('s=')+2);
		if(document.getElementById(thissection)) {
		    $("."+thissection).addClass("active");
		    if(document.getElementById(thissection)) {
			$("."+thissection).addClass("active");
		    }
		}
	    }
	}
	if(document.getElementById(thiscourse)) {
	    document.getElementById(thiscourse).className = "course_info expanded";
	    $("#"+thiscourse+"_details").slideDown("normal",function() {
        	coursey = document.getElementById(thiscourse).offsetTop;
        	window.scrollTo(0,coursey);
            });
	}
    }
} else {
    $(".course_info:only-child").removeClass("expandable").addClass("expanded");
    $(".course_info:only-child .course_details").slideDown("normal");
}
}
