// check if voting is allowed
function voteAllowed(id) {
	canvote = true;
	voted = getCookie("v");
	if (voted!=null) {
		voted = voted.split("|");
		for (i=0;i<voted.length;i++){
			if (voted[i]==id)
				canvote=false;
		}
	}
	return canvote;
}

// generate vote icon
var votedHTML = "<span class=\"voted\">VOTED</span>";
var votedClicked = false;

function voteLink(id,userid,fbid) {
	if (userid=="" || voteAllowed(id))
		document.write("VOTE");
	else
		document.write(votedHTML);
}

function voteClick(id,userid,fbid) {
	if (votedClicked) {
		return;
	}

	votedClicked = true;
	if (userid=="") {
		window.location = "user_login?msg=Please%20login%20to%20continue&nexturl="+location.href;
		return;
	}
	else if (!voteAllowed(id))
		alert("You have already voted for this");
	else if (fbid==0)
		sendVote(id,userid,fbid);
	else if (fbid>0)
		FB.Connect.showPermissionDialog('publish_stream',function(){sendVote(id,userid,fbid)});
}

function sendVote(id,userid,fbid) {
	makeHttpRequest("api/vote.php?id="+id+"&userid="+userid+"&fbid="+fbid, "done("+id+",");
}

function done(id, response) {
	// update vote count
	if (document.getElementById) {
		x = document.getElementById("vcount"+id);
		x.innerHTML = parseInt(response);
	}
	else if (document.all) {
		x = document.all["vcount"+id];
		x.innerHTML = parseInt(response);
	}

	// update vote link
	if (document.getElementById) {
		x = document.getElementById("vicon"+id);
		x.innerHTML = '';
		x.innerHTML = votedHTML;
	}
	else if (document.all) {
		x = document.all["vicon"+id];
		x.innerHTML = votedHTML;
	}

	// add to cookie to track vote
	voted = getCookie("v");
	d = new Date();
	d.setFullYear(2099);
	if (voted!=null) {
		voted = voted + "|" + id;
		setCookie("v",voted,d);
	}
	else {
		setCookie("v",id,d);
	}
}

function makeHttpRequest(url, callback_function) {
   var http_request = false;

   if (window.XMLHttpRequest) { // Mozilla, Safari,...
	   http_request = new XMLHttpRequest();
	   if (http_request.overrideMimeType) {
		   http_request.overrideMimeType('text/xml');
	   }
   } else if (window.ActiveXObject) { // IE
	   try {
		   http_request = new ActiveXObject("Msxml2.XMLHTTP");
	   } catch (e) {
		   try {
			   http_request = new ActiveXObject("Microsoft.XMLHTTP");
		   } catch (e) {}
	   }
   }

   if (!http_request) {
	   alert('Not available at this time.');
	   return false;
   }
   http_request.onreadystatechange = function() {
	   if (http_request.readyState == 4) {
		   if (http_request.status == 200) {
			   eval(callback_function + 'http_request.responseText)');
		   } else {
			   alert('HTTP Error code: ' + http_request.status + ')');
		   }
	   }
   }
   http_request.open('GET', url, true);
   http_request.send(null);
}