var objAjaxObjects = new Array();
var strPollURLAjax = "/poll/ajax?"
var strPollURLNoAjax = "/poll/vote?"
var strPollURLResults = "/poll/result?"


/* ---------------------------------------------------------------------- *\

  Function    : pollInitPoll
  Description : Initializes and fills a poll, given its id ans its values.
  Usage       : pollInitPoll(id, values)
  Arguments   : id: id of the poll on the page
                values: array of values for the poll (for each value an id and value is given ie: new Array(1, 100, 2, 0))

\* ---------------------------------------------------------------------- */

function pollInitPoll(id, values) {

	// Search for all polls
	for (var i=0; i < values.length; i++) {

		// Load poll and its value
		pollLoadPoll(id + "_" + values[i], values[i+1]);
		i++;

	}

}


/* ---------------------------------------------------------------------- *\

  Function    : pollLoadPoll
  Description : Initializes a poll, by first clearing it and then initializes its slider
  Usage       : pollLoadPoll(id, value)
  Arguments   : id: id of the poll on the page
                value: the value (based on percentages/max 100) which the slider must show

\* ---------------------------------------------------------------------- */

function pollLoadPoll(id, value) {

	// Load page objects
	var objPoll = document.getElementById(id);
	var objImage = objPoll.getElementsByTagName("img")[0];
	var objDivs = objPoll.getElementsByTagName("div");
	var objDiv = pollGetPollDataObject(id);


	// Set image width
	if (objImage) {
		objImage.style.width = 0;
	}

	// Clear result-text (percentage) fields
	if (objDiv) {
		objDiv.innerHTML = "";
	}

	// Start slider animation
	window.setTimeout("pollMovePoll('" + id + "', " + value + ");", 250);

}


/* ---------------------------------------------------------------------- *\

  Function    : pollMovePoll
  Description : If the slider of a poll doesn't show the value, this function will move the slider in animated steps
  Usage       : pollMovePoll(id, value)
  Arguments   : id: id of the poll on the page
                value: the value (based on percentages/max 100) which the slider must show

\* ---------------------------------------------------------------------- */

function pollMovePoll(id, value) {

	// Load page objects
	var objPoll = document.getElementById(id);
	var objImage = objPoll.getElementsByTagName("img")[0];
	var objDivs = objPoll.getElementsByTagName("div");
	var blnDoNextStep = true;
	var intStep = 5;

	// Get current width of the image
	var strCurrentWidth = objImage.style.width.replace("px", "");

	if (strCurrentWidth.length == 0) {
		strCurrentWidth = 0;
	}

	var intCurrentWidth = parseInt(strCurrentWidth);

	var intNeededWidth = value * 2;

	// Take action based on current width and needed width
	if (intCurrentWidth == intNeededWidth) {

		blnDoNextStep = false;
		objDivs[1].innerHTML = Math.round((intCurrentWidth / 2)) + "%";

	} else if ((intCurrentWidth + intStep) < intNeededWidth) {

		objImage.style.width = intCurrentWidth + intStep;
		objDivs[1].innerHTML = Math.round(((intCurrentWidth + intStep) / 2)) + "%";

	} else if ((intCurrentWidth - intStep) > intNeededWidth) {

		objImage.style.width = intCurrentWidth - intStep;
		objDivs[1].innerHTML = Math.round(((intCurrentWidth - intStep) / 2)) + "%";

	} else {

		objImage.style.width = intNeededWidth;
		objDivs[1].innerHTML = Math.round((intNeededWidth / 2)) + "%";
		blnDoNextStep = false;

	}

	// Show nextstep? Do next animation step
	if (blnDoNextStep) {

		window.setTimeout("pollMovePoll('" + id + "', " + value + ");", 10);

	} else {

		// Set final width and text to prevent errors
		objImage.style.width = value * 2;
		objDivs[1].innerHTML = Math.round(value) + "%";

	}
}


/* ---------------------------------------------------------------------- *\

  Function    : pollVote
  Description : Save the selected answer in the poll to the server. The function searches for the selected answer and posts it back with AJAX
  Usage       : pollVote(id)
  Arguments   : id: id of the poll on the page

\* ---------------------------------------------------------------------- */

function pollVote(id) {

	// Load page objects
	var objPoll = document.getElementById(id);
	var objDiv = pollGetPollDataObject(id);

	if (!objDiv) {
		return;
	}

	var objAnswers = objDiv.getElementsByTagName("div");
	var strAnswer = "";

	// Choose selected answer
	for (var intAnswer=0; intAnswer < objAnswers.length; intAnswer++) {
	
		var objAnswer = objAnswers[intAnswer].getElementsByTagName("input")[0];

		if (objAnswer) {

			// If object found is radiobutton, check if option is checked and store value
			if (objAnswer.type == "radio") {
				if (objAnswer.checked) {
					strAnswer = objAnswer.value;
					break;
				}
			}

			// If object found is radiobutton, disable it
			if (objAnswer.type == "button") {
				//objAnswer.disabled = true;
			}

		}
		
	}

	// If no answer selected, inform user
	if (strAnswer.length == 0) {
		alert("Je hebt geen keuze gemaakt");
		return;
	}
	

	// Send answer to server by AJAX
	var intAjaxIndex = objAjaxObjects.length;

	objAjaxObjects[intAjaxIndex] = new sack();
	objAjaxObjects[intAjaxIndex].method = "POST";
	objAjaxObjects[intAjaxIndex].requestFile = strPollURLAjax + "action=vote&id=" + id.replace("poll_", "") + "&aid=" + strAnswer + "&u=" + new Date().getTime();

	objAjaxObjects[intAjaxIndex].onCompletion = function() { pollShowResults(id, intAjaxIndex); };
	objAjaxObjects[intAjaxIndex].onError = function() { pollNoAjaxVote(id, strAnswer); };
	objAjaxObjects[intAjaxIndex].onFail = function() { pollNoAjaxVote(id, strAnswer); };

	objAjaxObjects[intAjaxIndex].runAJAX();

}


/* ---------------------------------------------------------------------- *\

  Function    : pollShowResultsNoVote
  Description : Shows the results of the poll, without voting in the poll
  Usage       : pollShowResultsNoVote(id)
  Arguments   : id: id of the poll on the page

\* ---------------------------------------------------------------------- */

function pollShowResultsNoVote(id) {

	// Send answer to server by AJAX
	var intAjaxIndex = objAjaxObjects.length;
	
	objAjaxObjects[intAjaxIndex] = new sack();
	objAjaxObjects[intAjaxIndex].method = "GET";
	objAjaxObjects[intAjaxIndex].requestFile = strPollURLAjax + "action=result&id=" + id.replace("poll_", "") + "&u=" + new Date().getTime();;
	
	objAjaxObjects[intAjaxIndex].onCompletion = function() { pollShowResults(id,intAjaxIndex); };
	objAjaxObjects[intAjaxIndex].onError = function() { pollNoAjaxResults(id); };
	objAjaxObjects[intAjaxIndex].onFail = function() { pollNoAjaxResults(id); };
	objAjaxObjects[intAjaxIndex].runAJAX();
}


/* ---------------------------------------------------------------------- *\

  Function    : pollNoAjaxVote
  Description : When AJAX fails to store the answer, this function can redirect the user to a "normal" page where the answer will be stored
  Usage       : pollNoAjaxVote(id, answer)
  Arguments   : id: id of the poll on the page
		answer: selected answer in the poll

\* ---------------------------------------------------------------------- */

function pollNoAjaxVote(id, answer) {

	// Redirect user
	location.href = strPollURLNoAjax + "id=" + id.replace("poll_", "") + "&aid=" + answer + "&u=" + new Date().getTime();

}


/* ---------------------------------------------------------------------- *\

  Function    : pollNoAjaxResults
  Description : When AJAX fails to load the results of a poll, this function van redirect the user to a "normal" page
  Usage       : pollNoAjaxResults(id)
  Arguments   : id: id of the poll on the page

\* ---------------------------------------------------------------------- */

function pollNoAjaxResults(id) {

	// Redirect user
	location.href = strPollURLResults + "id=" + id.replace("poll_", "") + "&u=" + new Date().getTime();;

}


/* ---------------------------------------------------------------------- *\

  Function    : pollShowResults
  Description : Takes the XML result from AJAX and parses the results of the poll within the page
  Usage       : pollVote(id, intAjaxIndex)
  Arguments   : id: id of the poll on the page
		intAjaxIndex: index of the AJAX interace used

\* ---------------------------------------------------------------------- */

function pollShowResults(id, intAjaxIndex) {

	var objPoll = document.getElementById(id);

	// Parse result from XML object
	pollParseResults(id, objAjaxObjects[intAjaxIndex].responseXML);

}


/* ---------------------------------------------------------------------- *\

  Function    : pollParseResults
  Description : Creates the pollresults on the page based on a given XML response object
  Usage       : pollParseResults(id, objXML)
  Arguments   : id: id of the poll on the page
		objXML: the response from the server with the results of the poll

\* ---------------------------------------------------------------------- */

function pollParseResults(id, objXML) {

	// Load page objects
	var objPoll = document.getElementById(id);
	var strOutputType;
	var strPollID = "";

	strOutputType = objXML.getElementsByTagName("poll")[0].attributes.getNamedItem("outputstyle").nodeValue;
	strPollID = objXML.getElementsByTagName("poll")[0].attributes.getNamedItem("id").nodeValue;
	
	if (strOutputType == "html") {

		// Retreive HTML	
		var strHTML = objXML.getElementsByTagName("poll")[0].firstChild.nodeValue;
		
		// Set HTML
		objPoll.innerHTML = strHTML;
		
		// Search for script objects to execute
		var strPattern = "\<script.*?\>(.*?)\</script\>";
		var objRegEx = new RegExp(strPattern, "gi");
		
		// Remove any new lines
		var objMatches = objRegEx.exec(strHTML.replace(/\n/gim, ""));
		
		if (objMatches == null) {
			
		} else {
			
			// Matches found
			for (var intMatch = 0; intMatch < objMatches.length; intMatch++) {
				
				// If second match (inner script) execute it
				if ((intMatch % 2)) {
					eval(objMatches[intMatch]);
				}
			}
		}
		
	}
	
	if (strOutputType == "xml") {

		var objPollDiv = pollGetPollDataObject(id);
		var arrData = new Array();

		var blnShowResults = pollGetSetting(objXML, "showresults");
	
		// Load answers
		var objAnswers = objXML.getElementsByTagName("answer");

		// Clear DIV where results will be positioned
		objPollDiv.innerHTML = "";
	
		for (var intAnswer = 0; intAnswer < objAnswers.length; intAnswer++) {

			// Get values
			//var strID = objAnswers[intAnswer].childNodes[0].firstChild.nodeValue;
			var strID = objAnswers[intAnswer].attributes[0].nodeValue;
			var strType = objAnswers[intAnswer].childNodes[0].firstChild.nodeValue;
			var strValue = objAnswers[intAnswer].childNodes[1].firstChild.nodeValue;
			var strTitle = objAnswers[intAnswer].childNodes[2].firstChild.nodeValue;
			var strDescription = objAnswers[intAnswer].childNodes[3].firstChild.nodeValue;
			var intVotes = 0; //objAnswers[intAnswer].childNodes[4].firstChild.nodeValue;

			// Create main DIV
			var objAnswerDiv = document.createElement('DIV');
			objAnswerDiv.className = "pollanswer";
			objAnswerDiv.id = id + "_" + strID;
			objPollDiv.appendChild(objAnswerDiv);

			if (blnShowResults == "1") {

				// Create image container div
				var objAnswerDivSlider = document.createElement('DIV');
				objAnswerDivSlider.className = "pollanswer_i";
				objAnswerDiv.appendChild(objAnswerDivSlider);

				// Create image slider
				var objAnswerDivSliderImg = document.createElement('IMG');
				objAnswerDivSliderImg.className = "pollanswer_im";
				objAnswerDivSliderImg.src = "stat.gif";
				objAnswerDivSliderImg.style.width = 0;
				objAnswerDivSlider.appendChild(objAnswerDivSliderImg);

				// Create value div (percentage)
				var objAnswerDivValue = document.createElement('DIV');
				objAnswerDivValue.className = "pollanswer_p";
				objAnswerDiv.appendChild(objAnswerDivValue);

			}

			// Create answertitle P
			var objAnswerDivTitle = document.createElement('P');
			objAnswerDivTitle.className = "pollanswer_t";
			objAnswerDivTitle.innerHTML = strTitle;
			objAnswerDiv.appendChild(objAnswerDivTitle);


			// Store ID and value for slider
			arrData[arrData.length] = strID;
			arrData[arrData.length] = intVotes;
			
		}

		// Load Messages
		var objMessages = objXML.getElementsByTagName("message");

		for (var intMessage = 0; intMessage < objMessages.length; intMessage++) {

			// Get values
			var strID = objMessages[intMessage].attributes[0].nodeValue;
			var strValue = objMessages[intMessage].childNodes[0].firstChild.nodeValue;

			// Show thankyou message (after voting) in page.
			if (strID == "thankyou") {

				var objTotalVotesDiv = document.createElement('DIV');
				objTotalVotesDiv.className = "pollthankyou";
				objTotalVotesDiv.innerHTML = strValue;
				objPollDiv.insertBefore(objTotalVotesDiv, objPollDiv.firstChild);

			}

			// Show total votes/count in page
			if (strID == "totalvotes") {

				var objTotalVotesDiv = document.createElement('DIV');
				objTotalVotesDiv.className = "pollvotes";
				objTotalVotesDiv.innerHTML = strValue;
				objPollDiv.appendChild(objTotalVotesDiv);

			}

			// Show (error) message
			if (strID == "messagebox") {

				alert(strValue);

			}

		}

		if (blnShowResults == "1") {

			// Poll information collected, initialize poll and start sliders
			pollInitPoll(id, arrData);

		}
		
	}
		
}


/* ---------------------------------------------------------------------- *\

  Function    : pollGetPollDataObject
  Description : Searches for the data object in the poll
  Usage       : pollGetPollDataObject(id)
  Arguments   : id: id of the poll on the page

\* ---------------------------------------------------------------------- */

function pollGetPollDataObject(id) {

	// Load page objects
	var objPoll = document.getElementById(id);
	var objDiv; 

	var objDivs = objPoll.getElementsByTagName("div");

	for (var intDiv=0; intDiv < objDivs.length; intDiv++) {
		if (objDivs[intDiv].className == "polldata") {
			objDiv = objDivs[intDiv];
			break;
		}
	}

	return objDiv;

}


/* ---------------------------------------------------------------------- *\

  Function    : pollGetSetting
  Description : Gets a setting from the XML response
  Usage       : pollGetSetting(objXML, id)
  Arguments   : objXML: the response from the server with the results of the poll
		id: id of the requested setting

\* ---------------------------------------------------------------------- */

function pollGetSetting(objXML, id) {

	// Load settings
	var objSettings = objXML.getElementsByTagName("setting");
	var strValue = "";

	for (var intSetting = 0; intSetting < objSettings.length; intSetting++) {

		// Get values
		//var strID = objSettings[intSetting].childNodes[0].firstChild.nodeValue;
		var strID = objSettings[intSetting].attributes[0].nodeValue;
		if (strID == id) {
			strValue = objSettings[intSetting].childNodes[0].nodeValue;
			break;
		}

	}

	return strValue;

}


