var pollHandler = function(voteButtonId, resultsButtonId, requestPath)
{
	// html references
	this.pollDiv = document.getElementById("poll");
	this.pollForm = document.getElementById("poll_vote");
	this.voteButton = (voteButtonId && document.getElementById(voteButtonId)) ? document.getElementById(voteButtonId) : document.getElementById("poll_submit");
	this.resultsButton = (resultsButtonId && document.getElementById(resultsButtonId)) ? document.getElementById(resultsButtonId) : document.getElementById("poll_results_link");
	this.pollResultsJSON = false;
	this.pollQuestion = "Isn't this just the BEST THING ever?";
	this.voted = false;

	// request path
	this.requestPath = (requestPath) ? requestPath : "/ajax/polls";
	
	// dataloader 
	this.dataLoader = new contentLoader(); // requires dataLoader.js
	this.dataLoader.onload = this.onDataLoad;
	this.dataLoader.onerror = this.onDataError;
	this.dataLoader.parent = this;
	this.domainName = document.domain;
	
}
pollHandler.prototype =
{
	initalise:function()
	{
		if(this.dataLoader.isSupported()) // check we have http request functionality
		{
			var pollRef = this;
			// Only run this if the button exists on the page.
			if (this.voteButton)
			{
				this.voteButton.onclick = function()
				{
					var votePid = pollRef.getPid();
					var voteValue = pollRef.getVoteValue();
					var voteTxt = pollRef.getVoteText();
					var noCookieFlag = false;
					var pollCookieVal = Cookie.get('frontpage_poll_'+votePid+'_voted');
					var pollCookiePrefix = /[0-9]+:/;
					var pollCookieTxt = (pollCookieVal ? pollCookieVal.replace(pollCookiePrefix,"") : "");
					if (pollCookieVal) { pollRef.reportError("You have already voted for '" + pollCookieTxt + "' in this poll."); return false; }
					var myTestCookie = Cookie.set('frontpage_poll_'+votePid+'_test', 'test', {domain: pollRef.domainName});
					if (Cookie.get('frontpage_poll_'+votePid+'_test') != 'test') { noCookieFlag = true; } // Can't set cookie, so do it the OLdSkoOL way.
					if (document.getElementById("poll_error").childNodes.length > 0)
					{
						document.getElementById("poll_error").removeChild(document.getElementById("poll_error").childNodes[0]);
					}
					if (!noCookieFlag) { pollRef.myCookie = Cookie.set('frontpage_poll_'+votePid+'_voted', voteValue+":"+voteTxt, {domain: pollRef.domainName, duration: 730}); } // Expires in two years. That should do. =)
					Cookie.remove(myTestCookie); // Don't need this any more.
					pollRef.handleVote();
					pollRef.voted = true;
					return noCookieFlag;
				}
			}
			if (this.resultsButton)
			{
				this.resultsButton.onclick = function()
				{
					pollRef.handleGetResults();
					return false;
				}
			}
		}
	},
	handleVote:function()
	{
		var voteValue = this.getVoteValue();
		var pid = this.getPid();
		if (voteValue)
		{
			this.dataLoader.url = this.requestPath + "?pid=" + pid + "&vote=" + voteValue.toString();
			this.dataLoader.getData();
			this.voteButton.value = 'Voting...'
			this.resultsButton.style.display = 'none';
		}
	},
	handleGetResults:function()
	{
		var pid = this.getPid();
		this.dataLoader.url = this.requestPath + "?pid=" + pid;
		this.dataLoader.getData();
		this.resultsButton.innerHTML = 'Fetching results...'
		this.voteButton.style.display = 'none';
	},
	onDataLoad:function()
	{
		this.parent.handleResponseData(this.loadedData); // pass data into parent object
	},
	onDataError:function()
	{
		this.parent.handleError();
	},
	handleError:function()
	{
		return false;
	},
	handleResponseData:function(data)
	{
		var data = data;
		try
		{
			eval (data);
			this.pollResultsJSON = arrPoll;
		}
		catch (e)
		{
			this.voteButton.value = 'Vote';
			this.voteButton.style.display = "block";
			document.getElementById("poll_error").appendChild(document.createTextNode("There is a problem with the form submission system; please try again later."));
			Cookie.remove(this.myCookie); // Lets not leave this hanging around if the vote wasn't successfully cast.
			pollRef.voted = false;
			return false;
		}
		
		if (this.pollResultsJSON.error_message)
		{
			this.reportError(this.pollResultsJSON.error_message);
			Cookie.remove(this.myCookie); // Lets not leave this hanging around if the vote wasn't successfully cast.
			pollRef.voted = false;
			return false;
		}
		this.pollDiv.className = "poll_answer box";
		var pollResultsUl = this.createResultsUL();
		this.resultsButton.style.display = 'none';
		this.pollDiv.replaceChild( pollResultsUl , this.pollForm);
		this.pollDiv.insertBefore(this.createQuestionH5() , pollResultsUl);	
		
		//var voteCounter = parseInt(document.getElementById("vote_count").innerHTML) + (this.voted ? 1 : 0);
		//document.getElementById("vote_count").innerHTML = voteCounter;
		
	},
	reportError:function(errorMsg)
	{
		this.voteButton.style.display = 'none';
		this.resultsButton.style.display = 'none';
		document.getElementById("poll_error").appendChild(document.createTextNode(errorMsg));
	},
	getVoteValue:function()
	{
		var vote = false;
		var voteList = document.getElementsByName("poll_response");
		for (i = 0; i <voteList.length; i++)
		{
			if (voteList[i].checked)
			{
				vote = voteList[i].value.split("_")[1];
				break;
			}
		}
		return vote;
	},
	getVoteText:function()
	{
		var vote = false;
		var voteList = document.getElementsByName("poll_response");
		for (i = 0; i <voteList.length; i++)
		{
			if (voteList[i].checked)
			{
				voteTxt = voteList[i].nextSibling.innerHTML;
				break;
			}
		}
		return voteTxt;
	},
	getPid:function()
	{
		var tmp = document.getElementById("poll_id");
		if(tmp)
		{
			return tmp.value;
		}
		return -1;
	},
	createResultsUL:function()
	{
		var pollResEl = document.createElement("ul");
		pollResEl.id = "poll_results_list";
		for (i=0; i<this.pollResultsJSON.poll_results.length; i++)
		{
			var newLi = document.createElement("li");
			newLi.appendChild(document.createTextNode(this.pollResultsJSON.poll_results[i].optionName + " "));
			var newStrong = document.createElement("strong");
			var pollResult = this.pollResultsJSON.poll_results[i].optionVotes;
			newStrong.appendChild(document.createTextNode(parseInt(pollResult,10).toString() + "%"));
			var newSpan = document.createElement("span");
			newSpan.className = "res_" + pollResult;
			newStrong.appendChild(newSpan);
			newLi.appendChild(newStrong);
			pollResEl.appendChild(newLi);
		}
		return pollResEl;
	},
	createQuestionH5:function()
	{
		var pollQEl = document.createElement("h5");
		pollQEl.innerHTML = this.pollResultsJSON.poll_question ? this.pollResultsJSON.poll_question : this.pollQuestion;
		return pollQEl;
	}
}

