ajax = {
	xmlhttp: false,
	load: function(method, url, variables, callback)
	{
		method = method.toLowerCase()
		if (!method.match(/get|post|head/))
			method="get"
		
		if (method == 'post')
		{
			this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

		}
		
		this.xmlhttp.open(method, url,true);
		this.xmlhttp.onreadystatechange=function()
		{
			if (this.readyState==4)
			{
				if (callback)
					callback(this.responseText)
			}
		}
		this.xmlhttp.send(variables)

	},
	
	init: function()
	{
		var xmlhttp=false;
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
		if (!xmlhttp && window.createRequest) {
			try {
				xmlhttp = window.createRequest();
			} catch (e) {
				xmlhttp=false;
			}
		}
		this.xmlhttp = xmlhttp
	}
}

vote = {
	voteup: function(id, key)
	{
		ajax.load('get', 'vote.php?v=1&id='+id+'&k='+key, null , this.handleresponse)
	},
	
	votedown: function(id, key)
	{
		ajax.load('get', 'vote.php?v=0&id='+id+'&k='+key, null , this.handleresponse)
	},
	
	flag: function(id, key)
	{
		ajax.load('get', 'vote.php?v=2&id='+id+'&k='+key, null , this.handleflagging)
	},
	
	voteworked: function(html)
	{
		reply = html.match(/(You voted [-|+]1 for quote #(\d+)?)/)
		return (reply == null) ? false : true
	},
	
	whichvote: function(html)
	{
		reply = html.match(/(You voted [-|+]1 for quote #(\d+)?)/)
		if (reply == null)
		{
			reply = html.match(/(Error proccessing vote|Your CSRF key is invalid) for quote #(\d+)?/)
		}
		reply = reply[0]
		return reply.substr(reply.indexOf('#')+1)
		
	},
	
	reportworked: function(html)
	{
		return (html.indexOf("You flagged quote ") == -1) ? false : true
	},
	
	whichreport: function(html)
	{
		reply = html.match(/(You flagged quote #(\d+)?)/)
		if (reply == null)
		{
			reply = html.match(/Your CSRF key is invalid for quote #(\d+)?/)
		}
		reply = reply[0]
		return reply.substr(reply.indexOf('#')+1)
		
	},
	
	handleresponse: function(html)
	{
		worked	= vote.voteworked(html)
		vote.feedback(worked? 'Vote successful' : 'Vote failed', 'votefeedback_'+vote.whichvote(html))
	},
	
	handleflagging: function(html)
	{
		worked	= vote.reportworked(html)
		vote.feedback(worked? 'Report successful' : 'Report failed', 'votefeedback_'+vote.whichreport(html))
	},
	
	feedback: function(msg, obj_id)
	{
		output	= document.getElementById(obj_id)
		// remove any previous outputs
		if (output.childNodes.length > 0)
			output.removeChild(output.childNodes[0])
		feedback	= document.createTextNode(msg)
		output.appendChild(feedback)
	}
}

ajax.init()
