//Course Feeds related javascript
//Uses jQuery 1.2.6
$('document').ready(function() {
	$('a.title').toggle(function() {
		$(this).parent().parent().find('div').show();
		$(this).parent().addClass('open');
		$(this).parent().removeClass('closed');
	}, function() {
		$(this).parent().parent().find('div.course').hide();
		$(this).parent().addClass('closed');
		$(this).parent().removeClass('open');
	});
	
	//hide courses with no description
	$('ul.courses').each(function(i) {
		evaluateCourse($(this));
	});
	
	//Change 'A R R' to 'Arranged' and 'R' to 'Th' in the course schedule
	$('td.days').each(function(i) {
		changeARR1($(this));
	});
	
	//remove duplicate AM or PM in class times
	$('td.times').each(function(i) {
		changeTimes($(this));
	});
	
	//display the link
	displayIncomingLink();
	
	//clean up table formatting in IE
	$('table.section-list tr').each(function() {
		$(this).find('td:first').css('border-left', 'none');										  
	});
	
});

// if the incoming link specifies a course to display, display it
function displayIncomingLink() {
var locate = location.href;

	if (locate.indexOf('#') > -1) {
		var begin = locate.indexOf('#') + 3;
		var course = locate.substring(begin, (begin + 5));
		$('#ul_' + course).children().find('a.title').click();
	}
}

function evaluateCourse(course) {
	var descriptionLength, courseID;
	
	courseID = (course.attr('id')).substr(3,5);
	descriptionLength = (course.find('div.description').attr('innerHTML')).length;
	
	if (descriptionLength < 20) { // if the course doesn't have a description, don't display it
		course.css('display','none');	
	} else if (document.getElementById('schedule_' + courseID) == null) { // if the class isn't scheduled this semester then delete the section header and "offered" copy; if IE, reformat section div
		course.find('p.semester').css('display', 'none');
		$('#offered_' + courseID).css('display', 'none');
	}
	
	//hide schedule info - remove when updating for summer 2010
	$(".section-list").hide();
	$('#offered_' + courseID).hide();
}


// replace "A, R, R" with "Arranged" and "R" with "Th" in the days field; getElementsByName method doesn't work in IE, so this is a work-around
function changeARR1(element) {
	var temp = element.attr('innerHTML');
	if (temp == "A, R, R") {
		element.attr('innerHTML', 'Arranged');
	} else if (temp.indexOf("R") > -1) {
		temp = temp.slice(0,temp.indexOf("R")) + "Th";
		element.attr('innerHTML', temp);
	}
}
	
function changeTimes(element) {
	// if there are two instances of AM or PM, remove the first
	try {
		var text = element.attr('innerHTML');
		var pm = text.match(/PM/g);
		var am = text.match(/AM/g);
		if (am != null && am.length > 1) {
			text = text.replace(/AM/, "");
		} else if (pm != null && pm.length > 1) {
			text = text.replace(/PM/, "");
		}
		element.attr('innerHTML', text);
	} catch(err) {
		return;
	}
}