var top6voteBusy = false;
var voteCountUpdateId = false;

function top6vote(collabsid, tasksid, voteCountElementId) {
	var isLoggedIn = document.getElementById("isLoggedIn").value == "1";
	if(!isLoggedIn) {
		window.location = "login.php?from=index.php";
		// shouldnt need this but is good form to exit
		return;
	}
	var isValid = validateTop6vote();
	if (!isValid) {
		return;
	}
	// go go go
	voteCountUpdateId = voteCountElementId;
	enableTop6vote(false);
//	showTop6voteFeedback("Please wait...");
	var dataString = "collabsid=" + collabsid + 
			"&tasksid=" + tasksid;
	$.ajax( {
		type : "POST",
		url : "ajaxtop6vote.php",
		data : dataString,
		success : onTop6voteAjaxSuccess,
		error : onTop6voteAjaxError
	});
}

function enableTop6vote(enabled) {
	if(enabled) {
		top6voteBusy = false;
	}else{
		top6voteBusy = true;
	}
}

function validateTop6vote() {
	if(top6voteBusy) {
		showSaveTeamFeedback("Still working, please wait...", null, 0);
		return false;
	}
	return true;
}

function showTop6voteFeedback(s, focusElement, status) { // status -1 (default) = normal, 0 = error, 1 = success
//	var fb = s ? s : "&nbsp;";
//	switch(status) {
//		case 0:
//			fb = "<span class=\"feedbackNegative\">" + fb + "</span>";
//			break;
//		case 1:
//			fb = "<span class=\"feedbackPositive\">" + fb + "</span>";
//			break;
//	}
//	$("#" + feedbackSaveTeamId).html(fb);
//	if(focusElement){
//		focusElement.focus();
//	}
	alert(s);
}

function onTop6voteAjaxSuccess(data, textStatus, xhRequest) {
	// alert("SUCCESS: data=" + data + "\ntextStatus=" + textStatus +
	// "\nxhRequest=" + xhRequest);
	var split = data.split(":");
	var success = split.length > 1 && split[0] == "success";
	if (!success) {
		showTop6voteFeedback(data, null, 0);
	} else {
		var voteCount = Number(split[1]);
		$("#" + voteCountUpdateId).html(voteCount + (voteCount == 1 ? " vote" : " votes"));
		showTop6voteFeedback("Thank you for voting", null, 1);
		// refresh
//		window.location.href = window.location.href;
	}
	enableTop6vote(true);
}

function onTop6voteAjaxError(xhRequest, textStatus, errorThrown) {
	// alert("ERROR: textStatus=" + textStatus + "\nerrorThrown=" + errorThrown
	// + "\nxhRequest=" + xhRequest);
	showTop6voteFeedback("AJAX error: " + textStatus, null, 0);
	enableTop6vote(true);
}
