// JavaScript Document

function addShortList(school) {
	myAjax.requestFile = '/scripts/addShortList.php?s='+school;
	document.getElementById("shortlist" + school).innerHTML = "Adding to your shortlist";
	myAjax.onCompletion = addedShortList; 
	myAjax.runAJAX(); // Execute AJAX function
}

function addedShortList() {
	var string = myAjax.response;
	var response_array = string.split("^^");
	var div = response_array[0];
	var response = response_array[1];
	if (response == "log") {
		alert("You must login before adding schools to your shortlist");
		resetText(div);
	} else if (response == "done") {
		var user = response_array[2];
		document.getElementById("shortlist" + div).innerHTML = "On shortlist";
		refreshShortlist(user)
	} else if (response == "already"){
		alert("That school is already on your shortlist");
		resetText(div);
	} else {
		alert("There was an error adding that school to your shortlist, please try again");
		resetText(div);
	}
}

function resetText(div) {
	var htmlString = "<a class=\"greyLink\" href=\"javascript:addShortList('"+div+"')\">";
	document.getElementById("shortlist" + div).innerHTML = htmlString+"Add to shortlist</a>";
}

function refreshShortlist(user) {
	var shortlist = document.getElementById("shortlistContent");
	if (shortlist) {
		myAjax.requestFile = '/scripts/shortlistDisplayWrapper.php'; 
		myAjax.onCompletion = refreshshortlistReturn; 
		myAjax.runAJAX(); 
	}
}

function refreshshortlistReturn() {
	var value = myAjax.response;
	document.getElementById("shortlistContent").innerHTML = value;
}

function shortlistLogin() {
	var email = document.getElementById("email-shortlist").value;
	var password = document.getElementById("password-shortlist").value;
	if (password == "" || email == "") {
		document.getElementById("shortlistError").innerHTML = "<strong>Incorrect login details</strong>";
	} else {
		document.getElementById("shortlistError").innerHTML = "<strong>Logging in...</strong>";
		myAjax.requestFile = '/scripts/shortlist?email='+email+'&password='+password; 
		myAjax.onCompletion = shortlistReturn; 
		myAjax.runAJAX(); 
	}
}

function shortlistReturn() {
	var value = myAjax.response;
	if (value == "error") {
		document.getElementById("shortlistError").innerHTML = "<p><strong>Incorrect login details</strong></p>";
	} else {
		document.getElementById("shortlistContent").innerHTML = value;
	}
}
