var _ITEM_LEVEL_EDIT_PAGE = 'edit-item.php';

function initAddenda() {
	
	$("#submitSurvey").click(submitSurvey);
	$("#surveyCourse").click(surveyCourse);

	$("#cancelMessage").click(clearClassPost);
	$("#classPost").focus(focusClassPost);
	$("#classPost").blur(blurClassPost);
	$("#postMessage").click(addClassPost);
	$(".deletePost").click(deleteClassPost);
	$(".changePage").click(changeClassPost);
	$("#manageClassDates").click(manageClassDates);
	$("#manageTimetable").click(manageTimetable);
	$(".uploadNotes").click(uploadNotes);
	$(".editNotes").click(editNotes);
	$(".deleteNotes").click(deleteNotes);
	$(".changeNotesPage").click(changeNotes);
	$("#changeGender").click(changeGender);
	$("#changePassword").click(changePassword);
	$("#changePicture").click(changePicture);
	$("#removePicture").click(removePicture);
	$("#resetPassword").click(resetPassword);
	$("#setNewPassword").click(setNewPassword);
	//$("#bookSearch").click(bookSearch);
	
	$("#regYear").change(registrationCourses);
	$("#regFaculty").change(registrationCourses);
	$("#regSubmit").click(registrationSubmit);
	
	$("#addMinutes").click(addMinutes);
	$("#deleteMinutes").click(deleteMinutes);
	
	$("#grindSubmit").click(submitGrind);
	$("#grindEdit").click(editGrind);
	$("#editcode").keypress(function(e) {
	    if (e.keyCode == 13 || e.which == 13) {
		    editGrind();
	    }
	});

	$("#collegeSearchBox").click(grindSearchBox);
	$("#collegeSearch").click(grindSearch);
	$("#juniorSearch").click(grindSearch);
	$("#leavingSearch").click(grindSearch);
	
	$(".anyQuestionsSubmit").click(questionsSubmit);
	
	printBusyTime();
	
	//$("#grindSubmit").click(submitGrind);
	// CREATE ITEM
	$(".createItem").click(function() {
		var table = $(this).attr("rel");
	    
		$.post(_ITEM_LEVEL_EDIT_PAGE + "?j=c&t=" + table, {}, function(text) {
		    $.historyLoad($("#hash").attr("value"));
		});	
	});
	
	// DELETE ITEM
	$(".deleteItem").click(function() {
		var table = $(this).attr("rel");
		var id = $(this).attr("id");
		
	    $("#dialog").dialog('option', 'height', 150);
	    $("#dialog").dialog('option', 'width', 300);
	    $("#dialog").dialog('option', 'title', 'Delete ' + table + ' item');
	    $("#dialog").dialog('option', 'resizable', false);
	    $("#dialog").dialog('option', 'buttons', {
		    "Cancel": function() { $(this).dialog("close"); },
		    "OK": function() {
			    $.post(_ITEM_LEVEL_EDIT_PAGE + "?j=d&t=" + table + "&id=" + id, {}, function(text) {
		    		$("#dialog").dialog('close');
		    		$.historyLoad($("#hash").attr("value"));
				});
		    }
		});
	    
		$("#dialog").html("Are you sure you want to delete this " + table + " item?");
		$("#dialog").dialog('open');
	});
	
	// PUBLISH ITEM
	$(".publishItem").click(function() {
		var table = $(this).attr("rel");
		var id = $(this).attr("id");
		
	    $("#dialog").dialog('option', 'height', 150);
	    $("#dialog").dialog('option', 'width', 300);
	    $("#dialog").dialog('option', 'title', 'Publish ' + table + ' item');
	    $("#dialog").dialog('option', 'resizable', false);
	    $("#dialog").dialog('option', 'buttons', {
		    "Cancel": function() { $(this).dialog("close"); },
		    "OK": function() {
			    $.post(_ITEM_LEVEL_EDIT_PAGE + "?j=p&t=" + table + "&id=" + id, {}, function(text) {
		    		$("#dialog").dialog('close');
		    		$.historyLoad($("#hash").attr("value"));
				});
		    }
		});
	    
		$("#dialog").html("Are you sure you want to publish this " + table + " item?");
		$("#dialog").dialog('open');
	});
	
	// UNPUBLISH ITEM
	$(".unpublishItem").click(function() {
		var table = $(this).attr("rel");
		var id = $(this).attr("id");
		
	    $("#dialog").dialog('option', 'height', 150);
	    $("#dialog").dialog('option', 'width', 300);
	    $("#dialog").dialog('option', 'title', 'Unpublish ' + table + ' item');
	    $("#dialog").dialog('option', 'resizable', false);
	    $("#dialog").dialog('option', 'buttons', {
		    "Cancel": function() { $(this).dialog("close"); },
		    "OK": function() {
			    $.post(_ITEM_LEVEL_EDIT_PAGE + "?j=u&t=" + table + "&id=" + id, {}, function(text) {
		    		$("#dialog").dialog('close');
		    		$.historyLoad($("#hash").attr("value"));
				});
		    }
		});
	    
		$("#dialog").html("Are you sure you want to unpublish this " + table + " item?");
		$("#dialog").dialog('open');
	});
}



function printBusyTime() {
	var count = $("#timeCount").attr('value');
	
	for (i = 0; i < count; i++) {
		var startTime = $("#st" + i).attr('value');
		var endTime = $("#et" + i).attr('value');
		
		var startParts = startTime.split('T');
		var startDay = dateToDay(startParts[0]);
		startTime = startParts[1];
		
		var endParts = endTime.split('T');
		var endDay = dateToDay(endParts[0]);
		endTime = endParts[1];
		
		var startParts = startTime.split(':');
		var startHour = parseInt(startParts[0], 10);
		var startMin = parseInt(startParts[1]);
		
		var endParts = endTime.split(':');
		var endHour = parseInt(endParts[0], 10);
		var endMin = parseInt(endParts[1]);
		
		for (d = startDay; d <= endDay; d++) {
			for (h = startHour; h <= endHour; h++) {
				var mLower = (h == startHour) ? startMin : 0;
				var mUpper = (h == endHour) ? endMin : 60;
				
				for (m = mLower; m < mUpper; m = m + 10) {
					if (m == 50) {
						$("#" + d + "-" + h + "-" + m).css('background', '#f04646');
					} else {
						$("#" + d + "-" + h + "-" + m).css('background', '#e03636');
					}
				}
			}
		}
		
		
	}
}

function dateToDay(date) {
	var parts = date.split("-");
	var dateObj = new Date(parts[0], parts[1] - 1, parts[2]);
	return dateObj.getDay() - 1;
}

function submitGrind() {
	var error = 0;
	
	var giveGet = $(".grindsForm #giveget").attr('value');
	
	var level = $(".grindsForm #level").attr('value');
	var hp = '';
	if (level == undefined) {
		level = '';
		if ($(".grindsForm input[value=junior]").attr('checked')) {
			level += '1';
		}
		if ($(".grindsForm input[value=leaving]").attr('checked')) {
			level += '2';
		}
		
		if ($(".grindsForm input[value=higher]").attr('checked')) {
			hp += 'h';
		}
		if ($(".grindsForm input[value=ordinary]").attr('checked')) {
			hp += 'p';
		}
	}
	
	if (level == '' || (hp == '' && level != 3)) {
		$(".grindsForm td:eq(1)").css('background', '#FCC');
		error = 1;
	}
	
	var options = $(".grindsForm #course").attr('options');
	var selection = new Array();
	var selCount = 0;
	for (i = 0; i < options.length; i++) {
		if (options[i].selected) {
			selection[selCount] = options[i].value;
			selCount++;
		}
	}
	
	if (selCount == 0) {
		$(".grindsForm #course").css('background', '#FCC');
		error = 1;
	}
	
	if (!isNumber($(".grindsForm #rate").attr('value')) && giveGet == 0) {
		$(".grindsForm #rate").css('background', '#FCC');
		error = 2;
	}
	
	if ($(".grindsForm #qualification").attr('value') == '' && giveGet == 0) {
		$(".grindsForm #qualification").css('background', '#FCC');
		error = 1;
	}
	
	if ($(".grindsForm #rate").attr('value') == '' && giveGet == 0) {
		$(".grindsForm #rate").css('background', '#FCC');
		error = 1;
	}
	
	if ($(".grindsForm #name").attr('value') == '') {
		$(".grindsForm #name").css('background', '#FCC');
		error = 1;
	}
	
	if ($(".grindsForm #email").attr('value') == '') {
		$(".grindsForm #email").css('background', '#FCC');
		error = 1;
	}
	
	if (error == 1) {
		$(".grindsForm #error").html('Please complete the form before you submit it.');
		$(".grindsForm #course").focus(unError);
		$(".grindsForm #qualification").focus(unError);
		$(".grindsForm #rate").focus(unError);
		$(".grindsForm #name").focus(unError);
		$(".grindsForm #email").focus(unError);
		return false;
	} else if (error == 2) {
		$(".grindsForm #error").html('Please ensure the <b>rate</b> is a number.');
		$(".grindsForm #rate").focus(unError);		
	} else {
		var dataString = '&sc=' + selCount;
		for (i = 0; i < selCount; i++) {
			dataString += "&c" + i + "=" + selection[i];
		}
		//dataString += "&c=" + $(".grindsForm #course").attr('value');
		dataString += "&q=" + $(".grindsForm #qualification").attr('value');
		dataString += "&r=" + $(".grindsForm #rate").attr('value');
		dataString += "&d=" + $(".grindsForm #details").attr('value');
		dataString += "&n=" + $(".grindsForm #name").attr('value');
		dataString += "&e=" + $(".grindsForm #email").attr('value');
		dataString += "&p=" + $(".grindsForm #phone").attr('value');
		dataString += "&gg=" + $(".grindsForm #giveget").attr('value');
		dataString += "&l=" + level;
		dataString += "&hp=" + hp;
		
	    $.post("functions/grinds.php?j=n" + dataString, function(text) {
		    $("#grindEntry").css('display', 'none');
    		$("#afterGrind").css('display', 'block');
		    $("#afterGrind").html(text);
			//$("#afterGrind a[rel='history']").bind('click.navigation', historyNav);
		    $(".anotherGrind").click(function() {
	    		$("#afterGrind").css('display', 'none');
			    $("#grindEntry").css('display', 'block');
				$(".grindsForm #qualification").attr('value', '');
				$(".grindsForm #rate").attr('value', '');
				$(".grindsForm #details").attr('value', '');
				$(".grindsForm #name").attr('value', '');
				$(".grindsForm #email").attr('value', '');
				$(".grindsForm #phone").attr('value', '');
				$(".grindsForm #course option").attr('selected', '');
				if (level != 3) {
					$(".grindsForm input[value=junior]").attr('checked', 'true');
					$(".grindsForm input[value=leaving]").attr('checked', '');
					$(".grindsForm input[value=higher]").attr('checked', 'true');
					$(".grindsForm input[value=ordinary]").attr('checked', '');
				}
		    });
		});
	}
}

function editGrind() {
    $("#grindEntry").css('display', 'block');
    $("#afterGrind").css('display', 'none');
    
	var dataString = '';
	dataString += "&e=" + $("#editemail").attr('value');
	dataString += "&rc=" + $("#editcode").attr('value');
	dataString += "&l=" + $("#editlevel").attr('value');
	$.post("functions/grinds.php?j=e" + dataString, function(text) {
		var data = JSON.parse(text);
		
		if (data.response != undefined) {
			$("#editError").html(data.response);
		} else {
			$("#editError").html('');
			if (data.level != 3) {
				
				if (data.level == 1 || data.level == 12) {
					$(".grindsForm input[value=junior]").attr('checked', 'true');
				} else {
					$(".grindsForm input[value=junior]").attr('checked', '');
				}
				
				if (data.level == 2 || data.level == 12) {
					$(".grindsForm input[value=leaving]").attr('checked', 'true');
				} else {
					$(".grindsForm input[value=leaving]").attr('checked', '');
				}
				
				if (data.honpass == 'h' || data.honpass == 'hp') {
					$(".grindsForm input[value=higher]").attr('checked', 'true');
				} else {
					$(".grindsForm input[value=higher]").attr('checked', '');
				}
				
				if (data.honpass == 'p' || data.honpass == 'hp') {
					$(".grindsForm input[value=ordinary]").attr('checked', 'true');
				} else {
					$(".grindsForm input[value=ordinary]").attr('checked', '');
				}
			}
			
			$(".grindsForm #grindid").attr('value', data.id);
			$("#editcode").attr('value', '');
			$("#editemail").attr('value', '');
			
			$(".grindsForm #course option[rel=select]").attr('rel', '');
			for (i = 0; i < data.courses.length; i++) {
				$(".grindsForm #course option[value=" + data.courses[i] + "]").attr('rel', 'select');
			}		
			$(".grindsForm #course option[rel=select]").attr('selected', 'selected');
			
			$(".grindsForm #qualification").attr('value', data.qualification);
			var newRate = data.rate.substr(0, data.rate.length - 2) + ".";
			newRate += data.rate.substr(data.rate.length - 2);
			$(".grindsForm #rate").attr('value', newRate);
			$(".grindsForm #details").attr('value', data.details);
			$(".grindsForm #name").attr('value', data.name);
			$(".grindsForm #email").attr('value', data.email);
			$(".grindsForm #phone").attr('value', data.phone);
			
			$("#grindSubmit").unbind('click');
			$("#grindSubmit").click(submitEdit);
		}
	});
}

function submitEdit() {
	var error = 0;
	
	var giveGet = $(".grindsForm #giveget").attr('value');
	
	var level = $(".grindsForm #level").attr('value');
	var hp = '';
	if (level == undefined) {
		level = '';
		if ($(".grindsForm input[value=junior]").attr('checked')) {
			level += '1';
		}
		if ($(".grindsForm input[value=leaving]").attr('checked')) {
			level += '2';
		}
		
		if ($(".grindsForm input[value=higher]").attr('checked')) {
			hp += 'h';
		}
		if ($(".grindsForm input[value=ordinary]").attr('checked')) {
			hp += 'p';
		}
	}
	
	if (level == '' || (hp == '' && level != 3)) {
		$(".grindsForm td:eq(1)").css('background', '#FCC');
		error = 1;
	}
	var options = $(".grindsForm #course").attr('options');
	var selection = new Array();
	var selCount = 0;
	for (i = 0; i < options.length; i++) {
		if (options[i].selected) {
			selection[selCount] = options[i].value;
			selCount++;
		}
	}
	
	if (selCount == 0) {
		$(".grindsForm #course").css('background', '#FCC');
		error = 1;
	}
	
	if (!isNumber($(".grindsForm #rate").attr('value')) && giveGet == 0) {
		$(".grindsForm #rate").css('background', '#FCC');
		error = 2;
	}
	
	if ($(".grindsForm #qualification").attr('value') == '' && giveGet == 0) {
		$(".grindsForm #qualification").css('background', '#FCC');
		error = 1;
	}
	
	if ($(".grindsForm #rate").attr('value') == '' && giveGet == 0) {
		$(".grindsForm #rate").css('background', '#FCC');
		error = 1;
	}
	
	if ($(".grindsForm #name").attr('value') == '') {
		$(".grindsForm #name").css('background', '#FCC');
		error = 1;
	}
	
	if ($(".grindsForm #email").attr('value') == '') {
		$(".grindsForm #email").css('background', '#FCC');
		error = 1;
	}
	
	if (error == 1) {
		$(".grindsForm #error").html('Please complete the form before you submit it.');
		$(".grindsForm #course").focus(unError);
		$(".grindsForm #qualification").focus(unError);
		$(".grindsForm #rate").focus(unError);
		$(".grindsForm #name").focus(unError);
		$(".grindsForm #email").focus(unError);
		return false;
	} else if (error == 2) {
		$(".grindsForm #error").html('Please ensure the <b>rate</b> is a number.');
		$(".grindsForm #rate").focus(unError);		
	} else {
		var dataString = '&sc=' + selCount;
		for (i = 0; i < selCount; i++) {
			dataString += "&c" + i + "=" + selection[i];
		}
		//dataString += "&c=" + $(".grindsForm #course").attr('value');
		dataString += "&q=" + $(".grindsForm #qualification").attr('value');
		dataString += "&r=" + $(".grindsForm #rate").attr('value');
		dataString += "&d=" + $(".grindsForm #details").attr('value');
		dataString += "&n=" + $(".grindsForm #name").attr('value');
		dataString += "&e=" + $(".grindsForm #email").attr('value');
		dataString += "&p=" + $(".grindsForm #phone").attr('value');
		dataString += "&id=" + $(".grindsForm #grindid").attr('value');
		dataString += "&gg=" + $(".grindsForm #giveget").attr('value');
		dataString += "&l=" + level;
		dataString += "&hp=" + hp;
		
	    $.post("functions/grinds.php?j=fe" + dataString, function(text) {
		    $("#grindEntry").css('display', 'none');
    		$("#afterGrind").css('display', 'block');
		    $("#afterGrind").html(text);
			//$("#afterGrind a[rel='history']").bind('click.navigation', historyNav);
		    $(".anotherGrind").click(function() {
	    		$("#afterGrind").css('display', 'none');
			    $("#grindEntry").css('display', 'block');
				$(".grindsForm #qualification").attr('value', '');
				$(".grindsForm #rate").attr('value', '');
				$(".grindsForm #details").attr('value', '');
				$(".grindsForm #name").attr('value', '');
				$(".grindsForm #email").attr('value', '');
				$(".grindsForm #phone").attr('value', '');
				$(".grindsForm #course option").attr('selected', '');
				if (level != 3) {
					$(".grindsForm input[value=junior]").attr('checked', 'true');
					$(".grindsForm input[value=leaving]").attr('checked', '');
					$(".grindsForm input[value=higher]").attr('checked', 'true');
					$(".grindsForm input[value=ordinary]").attr('checked', '');
				}
				
				$("#grindSubmit").unbind('click');
				$("#grindSubmit").click(submitGrind);
		    });
		});
	}
}

function unError() {
	$(".grindsForm #course").css('background', '#FFF');
	$(".grindsForm #qualification").css('background', '#FFF');
	$(".grindsForm #rate").css('background', '#FFF');
	$(".grindsForm #name").css('background', '#FFF');
	$(".grindsForm #email").css('background', '#FFF');
	$(".grindsForm td:eq(1)").css('background', '#FFF');
	$(".grindsForm #error").html('');
}

function isNumber(text) {
	var result = true;
	for (i = 0; i < text.length; i++) {
		if (!isDigit(text.charAt(i)) && text.charAt(i) != '.') {
			result = false;
		}
	}
	return result;
}

function isDigit(c) {
	return ((c >= "0") && (c <= "9"));
}

function grindSearchBox() {
	var level = $(this).attr('rel');
	var options = $("#" + level + "-course").attr('options');
	var giveGet = $("#giveget").attr('value');
	var selection = new Array();
	var selCount = 0;
	for (i = 0; i < options.length; i++) {
		if (options[i].selected) {
			selection[selCount] = options[i].value;
			selCount++;
		}
	}

	var dataString = '&sc=' + selCount;
	for (i = 0; i < selCount; i++) {
		dataString += "&c" + i + "=" + selection[i];
	}
	dataString += "&gg=" + giveGet;
	
    $.post("functions/grinds.php?j=s" + dataString, function(text) {
	    hideLeftCol();
	    $("#middleCol").html('<div class="middleColBoxTitle boxTitle">Grinds Search Results</div>' + text);
		$("#middleCol tr:odd td").css('background', '#E9E9F9');
		$(".grindContact").click(function() {
			var grindID = $(this).attr('rel');
			//$.post("functions/grinds.php?j=gct", function(text) {
			    $("#dialog").dialog('option', 'height', 370)
			    $("#dialog").dialog('option', 'width', 470);
			    $("#dialog").dialog('option', 'title', 'Contact');
			    $("#dialog").dialog('option', 'resizable', false);
			    $("#dialog").dialog('option', 'buttons', {
				    "Send Message": function() {
					    dataString = '&id=' + grindID;
					    dataString += '&name=' + $("#contactName").attr('value');
					    dataString += '&email=' + $("#contactEmail").attr('value');
					    dataString += '&message=' + $("#contactMessage").attr('value');
					    dataString += '&gg=' + giveGet;
					    alert(dataString);
					    var rcC = $("#recaptcha_challenge_field").attr('value');
					    var rcR = $("#recaptcha_response_field").attr('value');
				    	$.post("functions/grinds.php?j=ct" + dataString, {recaptcha_challenge_field: rcC, recaptcha_response_field: rcR}, function(text) {
				    		$("#dialog").dialog('option', 'buttons', {
							    "OK": function() {
							    	$(this).dialog("close");
								}
							});
					    	if (text == '1') {
					    		$("#dialog").html("The tutor has been contacted.");
				    		} else {
					    		$("#dialog").html("There was an error sending your message, please try again.");
				    		}
				    	});
					},
				    "Cancel": function() {
				    	$(this).dialog("close");
					}
				});
				
				var htmlt = '<table class="grindsForm"  border="0"><tr><td>Your Name</td><td><input type="input" id="contactName" /></td></tr>';
				htmlt += '<tr><td>Your Email</td><td><input type="input" id="contactEmail" /></td></tr>';
				htmlt += '<tr><td>Message (Optional)</td><td><textarea id="contactMessage"></textarea></td></tr>';
				htmlt += '<tr><td colspan="2">The following test is necessary to send the email.</td></tr>';
				htmlt += '</table>';
				htmlt += '<div id="recaptcha"></div>';

				$("#dialog").html(htmlt);
				$("#dialog").dialog('open');
				
				Recaptcha.create("6Lds-wcAAAAAAB8zLKj4PiLBJTdwj6VNRBzKUwTQ", 'recaptcha', {
					theme: 'clean',
					tabindex: 0,
					callback: Recaptcha.focus_response_field
				});
			//});
		});
	});
}

function grindSearch() {

	var level = $(this).attr('rel');
	var options = $("#" + level + "-course").attr('options');
	var giveGet = $("#giveget").attr('value');
	var selection = new Array();
	var selCount = 0;
	/*for (i = 0; i < options.length; i++) {
		if (options[i].selected) {
			selection[selCount] = options[i].value;
			selCount++;
		}
	}*/
	$("#" + level + "-course option:selected").each(function() {
		selection[selCount] = $(this).val();
		selCount++;
	});

	var dataString = '&sc=' + selCount;
	for (i = 0; i < selCount; i++) {
		dataString += "&c" + i + "=" + selection[i];
	}
	dataString += "&gg=" + giveGet;

	/*var page = '145';
	var section = '3';
	var editing = $("#editing").attr("value");
	var searchQuery = $(this).attr("rel");
	var searchPage = $(this).attr("href");
	
	var hash = "s=" + encode(section)
	
	if ($("#loggedIn").attr("value") == "1") {
		hash += "&e=" + encode(editing);
	}
	
	if (page != '') {
		hash += "&p=" + encode(page);
	}
	//hash += "&gs=" + encode(dataString);
	hash += dataString;
	hash = hash.replace(/^.*#/, '');
	$.historyLoad(hash);
	return false;*/
	
	
    $.post("functions/grinds.php?j=s" + dataString, function(text) {
	    $("#grindSearchBox").html(text);
		$("#grindSearchBox tr:odd td").css('background', '#E9E9F9');
		$(".grindContact").click(function() {
			var grindID = $(this).attr('rel');
			//$.post("functions/grinds.php?j=gct", function(text) {
			    $("#dialog").dialog('option', 'height', 370)
			    $("#dialog").dialog('option', 'width', 470);
			    $("#dialog").dialog('option', 'title', 'Contact');
			    $("#dialog").dialog('option', 'resizable', false);
			    $("#dialog").dialog('option', 'buttons', {
				    "Send Message": function() {
					    dataString = '&id=' + grindID;
					    dataString += '&name=' + $("#contactName").attr('value');
					    dataString += '&email=' + $("#contactEmail").attr('value');
					    dataString += '&message=' + $("#contactMessage").attr('value');
					    dataString += '&gg=' + giveGet;
					    alert(dataString);
					    var rcC = $("#recaptcha_challenge_field").attr('value');
					    var rcR = $("#recaptcha_response_field").attr('value');
				    	$.post("functions/grinds.php?j=ct" + dataString, {recaptcha_challenge_field: rcC, recaptcha_response_field: rcR}, function(text) {
				    		$("#dialog").dialog('option', 'buttons', {
							    "OK": function() {
							    	$(this).dialog("close");
								}
							});
					    	if (text == '1') {
					    		$("#dialog").html("The tutor has been contacted.");
				    		} else {
					    		$("#dialog").html("There was an error sending your message, please try again.");
				    		}
				    	});
					},
				    "Cancel": function() {
				    	$(this).dialog("close");
					}
				});
				
				var htmlt = '<table class="grindsForm"  border="0"><tr><td>Your Name</td><td><input type="input" id="contactName" /></td></tr>';
				htmlt += '<tr><td>Your Email</td><td><input type="input" id="contactEmail" /></td></tr>';
				htmlt += '<tr><td>Message (Optional)</td><td><textarea id="contactMessage"></textarea></td></tr>';
				htmlt += '<tr><td colspan="2">The following test is necessary to send the email.</td></tr>';
				htmlt += '</table>';
				htmlt += '<div id="recaptcha"></div>';

				$("#dialog").html(htmlt);
				$("#dialog").dialog('open');
				
				Recaptcha.create("6Lds-wcAAAAAAB8zLKj4PiLBJTdwj6VNRBzKUwTQ", 'recaptcha', {
					theme: 'clean',
					tabindex: 0,
					callback: Recaptcha.focus_response_field
				});
			//});
		});
	});
}

function grindSearchResults() {
	
	var selCount = $("#searchQuery").attr('value');
	var courseString = $("#searchPage").attr('value');
	var courses = courseString.split(', ');
	
	var dataString = '&sc=' + selCount;
	for (i = 0; i < selCount; i++) {
		dataString += "&c" + i + "=" + courses[i];
	}
	
	$.post("functions/grinds.php?j=s" + dataString, function(text) {
	    $("#grindsSearchResults").html(text);
		$("#grindsSearchResults tr:odd td").css('background', '#E9E9F9');
	});
}

function questionsSubmit() {
	/*var dataString = "e=" + $("#anyQuestions input[type=text]").attr('value');
	dataString += "&q=" + $("#anyQuestions textarea").attr('value');
	
	$.post("functions/anyquestions.php?j=n&" + dataString, function(text) {
		alert(text);
		$("#anyQuestions").html("Your question has been submitted and we'll get back to you as soon as possible. Thank you.");
	});*/
	var params = new Object();
	params.email = $("#anyQuestions input[type=text]").attr('value');
	params.text = $("#anyQuestions textarea").attr('value');
	$.post("functions/anyquestions.php?j=n", params, function(text) {
		if (text == 1) {
			alert('An error occured while submitting your question. Please try again.');
		} else {
			$("#anyQuestions").html("Your question has been submitted and we'll get back to you as soon as possible. Thank you.");
		}
	});
}

function focusClassPost() {
	if ($("#classPost").val() == 'Post a message') {
		$("#classPost").css('color', '#000');
		$("#classPost").val('');
	}
}

function blurClassPost() {
	if ($("#classPost").val() == '') {
		$("#classPost").css('color', '#aaa');
		$("#classPost").val('Post a message');
	}
}

function clearClassPost() {
	$("#classPost").css('color', '#aaa');
	$("#classPost").val('Post a message');
}

function addClassPost() {
	if ($("#classPost").val() != 'Post a message') {
		var message = $("#classPost").val();
		var cclass = $("#class").val();
		var user = $("#user").val();
		$.post('functions/classpost-add.php', {message: message, cclass: cclass, user: user}, function(error) {
			if (error == 1) {
				alert('There was an error posting your message. Please try again.');
			} else {
				$("#classPost").css('color', '#aaa');
				$("#classPost").val('Post a message');
				updateClassPostList();
			}
		});
	}
}

function deleteClassPost() {
	var ans = confirm('Are you sure you want to delete this post?');
	if (ans) {
		var postID = $(this).attr('id');
		$.post('functions/classpost-delete.php', {pid: postID}, function(error) {
			if (error == 1) {
				alert('An error occured while attempting to delete your post. Please try again.');
			} else {
				updateClassPostList();
			}
		});
	}
}

function updateClassPostList() {
	var cclass = $("#class").val();
	var page = $("#currentPage").val();
	$.post('functions/classpost-update.php', {cclass: cclass, page: page}, function(text) {
		if (text == 1) {
			alert('An error occured while updating the list of posts.');
			location.reload(true);
		} else {
			$("#classPostArea").html(text);
			$(".deletePost").click(deleteClassPost);
			$(".changePage").click(changeClassPost);
		}
	});
}

function changeClassPost() {
	var cclass = $("#class").val();
	var newPage = $(this).attr('id');
	$.post('functions/classpost-update.php', {cclass: cclass, page: newPage}, function(text) {
		if (text == 1) {
			alert('An error occured while updating the list of posts.');
			location.reload(true);
		} else {
			$("#classPostArea").html(text);
			$(".deletePost").click(deleteClassPost);
			$(".changePage").click(changeClassPost);
		}
	});
}

/* CLASS CALENDAR MANAGER */
/**************************/

function hoverOn() {
	$(this).addClass("ui-state-hover");
}

function hoverOff() {
	$(this).removeClass("ui-state-hover");
}

function manageClassDates() {
	var cclass = $("#class").val();
	$.post('functions/classcal-manager.php', {cclass: cclass}, function(text) {
		$("#dialog").dialog('option', 'height', 400)
		$("#dialog").dialog('option', 'width', 650);
		$("#dialog").dialog('option', 'title', 'Class Calendar Manager');
		$("#dialog").dialog('option', 'resizable', false);
		$("#dialog").dialog('option', 'buttons', {
			"Close Class Calendar Manager": function() {
				$(this).dialog("close");
				location.reload(true);
			}, "Add an Entry to the Calendar": function() {
				$.post('functions/classcal-new.php', {mode: 'addText'}, function(text) {
					$("#dialog2").dialog('option', 'height', 200)
					$("#dialog2").dialog('option', 'width', 330);
					$("#dialog2").dialog('option', 'title', 'Add Calendar Entry');
					$("#dialog2").dialog('option', 'resizable', false);
					$("#dialog2").dialog('option', 'buttons', {
						"Cancel": function() {
							$(this).dialog("close");
						}, "Add Event": function() {
							var useTime = $("#dateHour").attr('disabled');
							var hour = $("#dateHour").val();
							var minute = $("#dateMinute").val();
							var date = $("#dateDate").val();
							var event = $("#dateEvent").val();
							var cclass = $("#class").val();
							$.post('functions/classcal-new.php', {mode: 'addSQL', useTime: useTime, hour: hour, minute: minute, date: date, event: event, cclass: cclass}, function(error) {
								if (error == 1) {
									alert('An error occured while adding this event to the class calendar. Please try again.');
								} else {
									updateManagerClassDate();
								}
							});
						}
					});
					$("#dialog2").html(text);
					$("#dateDate").datepicker({dateFormat: 'dd-mm-yy'});
					$("#ui-datepicker-div").css('z-index', '2000');
					$("#dateCheck").toggle(function(e) {
						e.preventDefault();
						$("#dateHour").attr('disabled', 'true');
						$("#dateMinute").attr('disabled', 'true');
						$(this).val('Use Time');
					}, function(e) {
						e.preventDefault();
						$("#dateHour").removeAttr("disabled");
						$("#dateMinute").removeAttr("disabled");
						$(this).val('Don\'t Use Time');
					});
					$("#dialog2").dialog('open');
				});
			}/*, "Manage Class Timetable": function() {
				var class = $("#class").val();
				$.post('functions/classcal-tt.php', {class: class}, function(text) {
					$("#dialog2").dialog('option', 'height', 210)
					$("#dialog2").dialog('option', 'width', 330);
					$("#dialog2").dialog('option', 'title', 'Mangage Class Timetable');
					$("#dialog2").dialog('option', 'resizable', false);
					$("#dialog2").dialog('option', 'buttons', {
						"Cancel": function() {
							$(this).dialog("close");
						}, "Change Timetable Link": function() {
							$(this).dialog("close");
						}
					});
					$("#dialog2").html(text);
					$("#dialog2").dialog('open');
				});
			}*/
		});
		$("#dialog").html(text);

		$(".ui-state-default").hover(hoverOn, hoverOff);
		$(".editClassDate").click(editClassDate);
		$(".deleteClassDate").click(deleteClassDate);

		$("#dialog").dialog('open');

		$("#dialog2").dialog({
			modal:		true,
			autoOpen:	false
		});
	});
}

function updateManagerClassDate() {
	var cclass = $("#class").val();
	$.post('functions/classcal-manager.php', {cclass: cclass}, function(text) {
		$("#dialog").html(text);
		$("#dialog2").dialog("close");
		$(".ui-state-default").hover(hoverOn, hoverOff);
		$(".editClassDate").click(editClassDate);
		$(".deleteClassDate").click(deleteClassDate);
	});
}

function editClassDate() {
	var dateID = $(this).attr('rel');
	$.post('functions/classcal-new.php', {mode: 'editText', id: dateID}, function(text) {
		$("#dialog2").dialog('option', 'height', 200)
		$("#dialog2").dialog('option', 'width', 330);
		$("#dialog2").dialog('option', 'title', 'Edit Calendar Entry');
		$("#dialog2").dialog('option', 'resizable', false);
		$("#dialog2").dialog('option', 'buttons', {
			"Cancel": function() {
				$(this).dialog("close");
			}, "Submit Edit": function() {
				var useTime = $("#dateHour").attr('disabled');
				var hour = $("#dateHour").val();
				var minute = $("#dateMinute").val();
				var date = $("#dateDate").val();
				var event = $("#dateEvent").val();
				var cclass = $("#class").val();
				$.post('functions/classcal-new.php', {mode: 'editSQL', useTime: useTime, hour: hour, minute: minute, date: date, event: event, cclass: cclass, id: dateID}, function(error) {
					if (error == 1) {
						alert('An error occured while adding this event to the class calendar. Please try again.');
					} else {
						updateManagerClassDate();
					}
				});
			}
		});
		$("#dialog2").html(text);
		$("#dateDate").datepicker({dateFormat: 'dd-mm-yy'});
		$("#ui-datepicker-div").css('z-index', '2000');
		if ($("#dateCheck").val() == 'Don\'t Use Time') {
			$("#dateCheck").toggle(function(e) {
				e.preventDefault();
				$("#dateHour").attr('disabled', 'true');
				$("#dateMinute").attr('disabled', 'true');
				$(this).val('Use Time');
			}, function(e) {
				e.preventDefault();
				$("#dateHour").removeAttr("disabled");
				$("#dateMinute").removeAttr("disabled");
				$(this).val('Don\'t Use Time');
			});
		} else {
			$("#dateCheck").toggle(function(e) {
				e.preventDefault();
				e.preventDefault();
				$("#dateHour").removeAttr("disabled");
				$("#dateMinute").removeAttr("disabled");
				$(this).val('Don\'t Use Time');
			}, function(e) {
				$("#dateHour").attr('disabled', 'true');
				$("#dateMinute").attr('disabled', 'true');
				$(this).val('Use Time');
			});
		}
		$("#dialog2").dialog('open');
	});
}

function deleteClassDate() {
	var dateID = $(this).attr('rel');
	$("#dialog2").dialog('option', 'height', 150)
	$("#dialog2").dialog('option', 'width', 250);
	$("#dialog2").dialog('option', 'title', 'Delete Calendar Entry');
	$("#dialog2").dialog('option', 'resizable', false);
	$("#dialog2").dialog('option', 'buttons', {
		"Cancel": function() {
			$(this).dialog("close");
		}, "Delete": function() {
			$.post('functions/classcal-delete.php', {id: dateID}, function(error) {
				if (error == 1) {
					alert('An error occured while deleting this entry from the calendar. Please try again.');
				} else {
					updateManagerClassDate();
				}
			});
		}
	});
	$("#dialog2").html('Are you sure you want to delete this calendar entry?');
	$("#dialog2").dialog('open');
}

/* CLASS TIMETABLE MANAGER */
/**************************/

function manageTimetable() {
	var cclass = $("#class").val();
	$.post('functions/classtt-manager.php', {cclass: cclass}, function(text) {
		$("#dialog").dialog('option', 'height', 450)
		$("#dialog").dialog('option', 'width', 650);
		$("#dialog").dialog('option', 'title', 'Class Timetable Manager');
		$("#dialog").dialog('option', 'resizable', false);
		$("#dialog").dialog('option', 'buttons', {
			"Close Class Timetable Manager": function() {
				$(this).dialog("close");
				location.reload(true);
			}
		});
		$("#dialog").html(text);

		//$(".ui-state-default").hover(hoverOn, hoverOff);
		$(".classTTEmpty").hover(classTTEmptyHoverOn, classTTEmptyHoverOff);
		$(".classTTEmpty").click(addTTEntry);
		$(".classTTFilled").hover(ttEntryHoverOn, ttEntryHoverOff);
		$(".ttEntry").click(editTTEntry);

		$("#dialog").dialog('open');

		$("#dialog2").dialog({
			modal:		true,
			autoOpen:	false
		});
	});
}

function updateTimetableManager() {
	var cclass = $("#class").val();
	$.post('functions/classtt-manager.php', {cclass: cclass}, function(text) {
		$("#dialog").html(text);
		$("#dialog2").dialog('close');
		$(".classTTEmpty").hover(classTTEmptyHoverOn, classTTEmptyHoverOff);
		$(".classTTEmpty").click(addTTEntry);
		$(".classTTFilled").hover(ttEntryHoverOn, ttEntryHoverOff);
		$(".ttEntry").click(editTTEntry);
	});
}

function addTTEntry() {
	var params = new Object();
	params.time = $(this).attr('id');
	params.day = $(this).attr('rel');
	$.post('functions/classtt-add-get.php', params, function(text) {
		$("#dialog2").dialog('option', 'height', 170)
		$("#dialog2").dialog('option', 'width', 280);
		$("#dialog2").dialog('option', 'title', 'Add an Entry to the Timetable');
		$("#dialog2").dialog('option', 'resizable', false);
		$("#dialog2").dialog('option', 'buttons', {
			"Cancel": function() {
				$(this).dialog("close");
			}, "Add Entry": function() {
				var params2 = new Object();
				params2.cclass = $("#class").val();
				params2.title = $("#TTtitle").val();
				params2.day = params.day;
				params2.start = params.time;
				params2.end = $("#TTend").val();
				$.post('functions/classtt-add.php', params2, function(error) {
					if (error == 1) {
						alert('An error occured while adding this entry to the calendar. Please try again.');
					} else {
						updateTimetableManager();			
					}
				});
			}
		});
		$("#dialog2").html(text);
		
		$("#dialog2").dialog('open');
	});
}

function editTTEntry() {
}

function classTTEmptyHoverOn() {
	//$(this).css('background', '#ccc');
	$(this).html('Add Entry');
}

function classTTEmptyHoverOff() {
	//$(this).css('background', '#fff');
	$(this).html('');
}

function ttEntryHoverOn() {
	$(this).css('background', '#eee');
}

function ttEntryHoverOff() {
	$(this).css('background', '#dfdfdf');
}

/* CLASS NOTES */
/**************************/

function uploadNotes() {
	var cclass = $("#class").val();
	var page = $("#currentClassPage").val();
	var result = $(this).attr('rel');
	$.post('functions/classnotes-uploader.php', {cclass: cclass, page: page, result: result}, function(text) {
		$("#dialog").dialog('option', 'height', 200)
		$("#dialog").dialog('option', 'width', 320);
		$("#dialog").dialog('option', 'title', 'Class Notes Uploader');
		$("#dialog").dialog('option', 'resizable', false);
		$("#dialog").dialog('option', 'buttons', {
			"Cancel": function() {
				$(this).dialog("close");
				location.reload(true);
			}, "Upload": function() {
				var title = $("#notesAddTitle").val();
				var body = $("#notesAddBody").val();
				var file = $("#notesAddFile").val();
				if (title == '') {
					alert('Please give these notes a title.');
				} else if (body == '') {
					alert('Please give these notes a description.');
				} else if (file == '') {
					alert('Please give these notes a file to upload.');
				} else {
					$("#fileForm").submit();
				}
			}
		});
		$("#dialog").html(text);
		$("#dialog").dialog('open');
	});
}

function editNotes() {
	var params = new Object();
	params.cclass = $("#class").val();
	params.page = $("#currentClassPage").val();
	params.result = $(this).attr('rel');
	params.id = $(this).attr('id');
	$.post('functions/classnotes-edit.php', params, function(text) {
		$("#dialog").dialog('option', 'height', 220)
		$("#dialog").dialog('option', 'width', 320);
		$("#dialog").dialog('option', 'title', 'Edit your Class Notes');
		$("#dialog").dialog('option', 'resizable', false);
		$("#dialog").dialog('option', 'buttons', {
			"Cancel": function() {
				$(this).dialog("close");
				location.reload(true);
			}, "Submit Edit": function() {
				var title = $("#notesAddTitle").val();
				var body = $("#notesAddBody").val();
				var file = $("#notesAddFile").val();
				if (title == '') {
					alert('Please give these notes a title.');
				} else if (body == '') {
					alert('Please give these notes a description.');
				} else {
					$("#fileForm").submit();
				}
			}
		});
		$("#dialog").html(text);
		$("#dialog").dialog('open');
	});
}

function deleteNotes() {
	var ans = confirm('Are you sure you want to delete these notes?');
	if (ans) {
		var notesID = $(this).attr('rel');
		$.post('functions/classnotes-delete.php', {id: notesID}, function(error) {
			if (error == 1) {
				alert('An error occured while retriving the url for these notes. Please try again.');
			} else if (error == 2) {
				alert('An error occured while deleting these notes. Please try again.');
			} else if (error == 3) {
				alert('An error occured while deleting these notes from the database. Please try again.');
			} else {
				location.reload(true);
			}
		});
	}
}

function changeNotes() {
	var cclass = $("#class").val();
	var newPage = $(this).attr('id');
	$.post('functions/classnotes-update.php', {cclass: cclass, page: newPage}, function(text) {
		if (text == 1) {
			alert('An error occured while updating the list of notes.');
			location.reload(true);
		} else {
			$("#notesPaginationArea").html(text);
			$(".uploadNotes").click(uploadNotes);
			$(".editNotes").click(editNotes);
			$(".deleteNotes").click(deleteNotes);
			$(".changeNotesPage").click(changeNotes);
		}
	});
}

/* MINUTES */
/**************************/

function addMinutes() {
	var comID = $("#committee").val();
	$.post('functions/minutes-add.php', {id: comID}, function(text) {
		$("#dialog").dialog('option', 'height', 450)
		$("#dialog").dialog('option', 'width', 650);
		$("#dialog").dialog('option', 'title', 'Add New Minutes');
		$("#dialog").dialog('option', 'resizable', false);
		$("#dialog").dialog('option', 'buttons', {
			"Cancel": function() {
				$(this).dialog("close");
				location.reload(true);
			}, "Add Minutes": function() {
				var params = new Object();
				params.date = $("#minutesDate").val();
				params.body = $("#minutesBody").val();
				params.committee = comID;
				$.post('functions/minutes-add-submit.php', params, function(error) {
					if (error == 1) {
						alert('An error occured while attempting to add these minutes. Please try again.');
					} else {
						$(this).dialog("close");
						location.reload(true);
					}
				});
			}
		});
		$("#dialog").html(text);
		
		$("#minutesDate").datepicker({dateFormat: 'dd-mm-yy'});
		$("#ui-datepicker-div").css('z-index', '2000');

		$("#dialog").dialog('open');

		$("#dialog2").dialog({
			modal:		true,
			autoOpen:	false
		});
	});
}

function deleteMinutes() {
	var ans = confirm('Are you sure you want to delete these minutes?');
	if (ans) {
		var minID = $("#minute").val();
		$.post('functions/minutes-delete.php', {id: minID}, function(error) {
			if (error == 1) {
				alert('An error occured while attempting to delete these minutes. Please try again.');
			} else {
				location.href = '?s=1&p=15';
			}
		});
	}
}

/* USER SETTINGS */
/****************/

function changeGender() {
	var gender = $("#currentGender").val();
	$("#dialog").dialog('option', 'height', 120)
	$("#dialog").dialog('option', 'width', 200);
	$("#dialog").dialog('option', 'title', 'Change your Gender');
	$("#dialog").dialog('option', 'resizable', false);
	$("#dialog").dialog('option', 'buttons', {
		"Cancel": function() {
			$(this).dialog("close");
		}, "OK": function() {
			var params = new Object();
			params.gender = $("#newGender").val();
			params.user = $("#userID").val();
			$.post('functions/settings-gender.php', params, function(error) {
				if (error == 1) {
					alert('An error occured while changing your settings. Please try again.');
				} else {
					location.reload(true);					
				}
			});
		}
	});
	$("#dialog").html('<i>Select your gender from the menu below</i><br /><br /><select id="newGender"><option value="0">Male</option><option value="1">Female</option></select>');
	$("#dialog").dialog('open');
}

function changePassword() {
	var params = new Object();
	params.oldp = $("#currentPassword").val();
	params.newp = $("#newPasswordA").val();
	params.user = $("#userID").val();
	if (params.newA != params.newB) {
		alert("The new passwords you entered do not match. Please try again.");
	} else {
		$.post('functions/settings-password.php', params, function(error) {
			if (error == 1) {
				alert('The current password you entered does not match your password. Please try again.');
			} else if (error == 2) {
				alert('An error occured while changing your password. Please try again.');
			} else {
				alert('Your password has been successfully changed.');
				location.href = '?s=30';
			}
		});
	}
}

function changePicture() {
	var params = new Object();
	params.user = $("#userID").val();
	$.post('functions/settings-picture.php', params, function(text) {
		$("#dialog").dialog('option', 'height', 150)
		$("#dialog").dialog('option', 'width', 320);
		$("#dialog").dialog('option', 'title', 'Change your Picture');
		$("#dialog").dialog('option', 'resizable', false);
		$("#dialog").dialog('option', 'buttons', {
			"Cancel": function() {
				$(this).dialog("close");
			}, "Upload New Picture": function() {
				if ($("#uploadNewPicture").val() == '') {
					alert('Please select a picture to upload.');
				} else {
					$("#pictureForm").submit();
				}
			}
		});
		$("#dialog").html(text);
		$("#dialog").dialog('open');
	});
}

function removePicture() {
	var ans = confirm('Are you want to remove your picture?');
	if (ans) {
		var params = new Object();
		params.user = $("#userID").val();
		$.post('functions/settings-picture-remove.php', params, function(error) {
			if (error == 1) {
				alert('An error occured while attempting to remove your picture. Please try again.');
			} else if (error == 2) {
				alert('An error occured while attempting to remove your picture from the database. Please try again.');
			} else {
				location.href = '?s=30';
			}
		});
	}
}

/* USER REGISTRATION */
/****************/

function registrationCourses() {
	var year = $("#regYear").val();
	var faculty = $("#regFaculty").val();
	if (year == -1 || faculty == -1) {
		return false;
	} else {
		$.post('functions/reg-courses.php', {year: year, faculty: faculty}, function(text) {
			if (text == 1) {
				alert('An error occured while retrieving your courses. Please try again.');
			} else {
				$("#regCourseArea").html(text);
				//$("#regCourse").attr('disabled', '');
			}
		});
	}
}

function registrationSubmit() {
	var params = new Object();
	params.firstname = $("#firstname").val();
	params.surname = $("#surname").val();
	params.email = $("#email").val();
	params.gender = $("#gender").val();
	params.year = $("#regYear").val();
	
	params.faculty = $("#regFaculty").val();
	if (params.faculty < 4) {
		params.course = $("#regCourse").val();
	} else {
		params.courseA = $("#regCourseA").val();
		params.courseB = $("#regCourseB").val();
	}

	params.password = $("#passwordA").val();
	var passwordB = $("#passwordB").val();
	
	if (params.firstname == '' || params.surname == '' || params.email == '' || params.password == '') {
		alert('Please complete all fields before submitting the form.');
	} else if (params.year == '-1') {
		alert('Please select your year before submitting the form.');
	} else if (params.faculty == '-1') {
		alert('Please select your faculty before submitting the form.');
	} else if (params.password != passwordB) {
		alert('The passwords you have entered do not match. Please try again.');
	} else if (params.year == 'X' || params.faculty == 'X') {
		var message = 'If you do not fit into any category listed then unfortunately you cannot use this system to register an account.';
		message += ' To register for this website please contact the Technical Officer at technical<span style="display: none">--REMOVE THIS TEXT TO EMAIL THE TECHNICAL OFFICER--</span>@tcdsu.org';
		message += '<br /><br /><a href="?s=31">Click here to return to the registration page.</a>';
		$("#regBox").html(message);
	} else {
		var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!regex.test(params.email)) {
			alert('Please enter a valid email address.');
		} else {
			var parts = params.email.split('@');
			if (parts[1] != 'tcd.ie') {
				alert('Please enter a valid TCD email address.');
			} else {
				$.post('functions/reg-register.php', params, function(error) {
					if (error == 1) {
						alert('An account has already been registered with this email address. If you think this is incorrect, contact the Technical Officer immediately.');
					} else if (error == 2) {
						alert('An error occured while registering your details. Please try again. (Error 0xFE2)');
					} else if (error == 3) {
						alert('An error occured while registering your details. Please try again. (Error 0xFE3)');
					} else if (error == 4) {
						alert('An error occured while registering your details. Please try again. (Error 0xFE4)');
					} else if (error == 5) {
						alert('An error occured while registering your details. Please try again. (Error 0xFE5)');
					} else if (error == 6) {
						alert('An error occured while registering your details. Please try again. (Error 0xFE6)');				
					} else {
						$("#regBox").html('You have successfully registered.<br /><br />An email has been dispatched to you containing a confirmation link. You must click this link before using your account.<br /><br />If you cannot find the email in your inbox, check your spam.');
					}
				});
			}
		}
	}
}

function resetPassword() {
	var email = $("#resetEmail").val();
	var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!regex.test(email)) {
		alert('Please enter a valid email address.');
	} else {
		var parts = email.split('@');
		if (parts[1] != 'tcd.ie') {
			alert('Please enter a valid TCD email address.');
		} else {
			$.post('functions/reset-send.php', {username: parts[0]}, function(error) {
				if (error == 1) {
					alert('An error occured while attempting to reset your password. Please try again.');
				} else if (error == 2) {
					alert('An error occured while attempting to retrieve database information on your account. Please try again.');
				} else if (error == 3) {
					alert('An error occured while attempting to email you a reset link. Please try again.');
				} else if (error == 0) {
					alert('An email has been sent to your tcd.ie email account. Please view it to reset your password.');
					$("#resetEmail").val('');
				} else {
					alert('An unknown error has occured. Please try again.');
				}
			});
		}
	}
}

function setNewPassword() {
	var params = new Object();
	params.password = $("#passwordA").val();
	params.user = $("#userID").val();
	var passwordB = $("#passwordB").val();
	if (params.password != passwordB) {
		alert('The passwords you have entered do not match.');
	} else if (params.password == '') {
		alert('Please enter a new password before submitting the form.');
	} else {
		$.post('functions/reset-reset.php', params, function(error) {
			if (error == 1) {
				alert('An error occured while attempting to reset your password. Please try again.');
			} else if (error == 0) {
				$("#setNewPasswordArea").html('Your password has been successfully changed. You can now log in using this password.');
			} else {
				alert('An unknown error has occured. Please try again.');
			}
		});
	}
}

/******************************
BOOKSHOP CATALOGUE
*************/

function bookSearch() {
	/*var params = new Object();
	params.query = $("#booksearchquery").val();
	$.post('functions/bookshop-search.php', params, function(text) {
		$("#bookshopResultsArea").html(text);
	});*/
	var query = $("#booksearchquery").val();
	location.href = '?s=1&p=208&q=' + query;
}

/********************************/

function submitSurvey() {
	var params = new Object();
	
	params.year = $("#year").val();
	if (params.year == '-1') {
		alert('You are required to select a year before submitting the survey.');
		return false;
	}
	
	params.course = $("#course").val();
	var otherCourse = $("#courseOther").val();
	if (otherCourse != '' && otherCourse != undefined) {
		params.course = otherCourse;
	} else if (params.course == '-1') {
		alert('You are required to select a course before submitting the survey.');
		return false;
	}
	
	if ($("#workloadIncreased").val() == 'on') {
		params.workload = 'Increased';
	} else if ($("#workloadDecreased").val() == 'on') {
		params.workload = 'Decreased';
	} else {
		params.workload = 'N/A';
	}
	params.workloadComments = $("#workloadComments").val();
	if (params.workloadComments.length > 4096) {
		alert('A maximum size of 4,096 characters applies to the comment fields.');
		return false;
	}
	
	if ($("#readingYes").val() == 'on') {
		params.reading = 'Yes';
	} else if ($("#readingNo").val() == 'on') {
		params.reading = 'No';
	} else {
		params.reading = 'N/A';
	}
	params.readingComments = $("#readingComments").val();
	if (params.readingComments.length > 4096) {
		alert('A maximum size of 4,096 characters applies to the comment fields.');
		return false;
	}
	
	if ($("#reasonsYes").val() == 'on') {
		params.reasons = 'Yes';
	} else if ($("#reasonsNo").val() == 'on') {
		params.reasons = 'No';
	} else {
		params.reasons = 'N/A';
	}
	params.reasonsComments = $("#reasonsComments").val();
	if (params.reasonsComments.length > 4096) {
		alert('A maximum size of 4,096 characters applies to the comment fields.');
		return false;
	}
	
	params.changeComments = $("#changeComments").val();
	if (params.changeComments.length > 4096) {
		alert('A maximum size of 4,096 characters applies to the comment fields.');
		return false;
	}
	
	params.otherComments = $("#otherComments").val();
	if (params.otherComments.length > 4096) {
		alert('A maximum size of 4,096 characters applies to the comment fields.');
		return false;
	}
	
	$.post('functions/survey-submit.php', params, function(error) {
		if (error == 1) {
			alert('An error occured while submitting your survey. Please try again.');
		} else if (error == 0) {
			alert('Your survey has been successfully submitted');
			location.href = 'http://www.tcdsu.org';
		} else {
			alert('An unknown error occured. Please try again.');
		}
	});
	
	return false;	
}

function surveyCourse() {
	$("#courseOtherBox")
		.html('<input type="text" id="courseOther" style="width: 300px;" />')
		.css('text-align', 'left');
	return false;
}