﻿/* Global Javascript Variables*/
var geraInfoStorage = new Array();
var apiScriptUrl = "http://www.pollsys.ee/gera/api/v1/poll/";
var apiStyleUrl = "http://www.pollsys.ee/gera/static/styles/client/v1/styles.css";
var activeInfoUnitID = 0;
/* Global Javascript Variables */

/* Helper class for storing info */
function geraInfoUnit(divID, clientAuthKey, pollId, divWidth, unitID) {
	this.id = unitID;
	this.geraDivID = divID;
	this.geraWidth = 175;
	if (divWidth != null)
		this.geraWidth = divWidth;
	this.geraDiv = "";
	this.geraClntAuthID = clientAuthKey;
	this.geraJsonContent = null;
	this.geraQuestionCount = "";
	this.pollID = pollId;
	this.answeredQuestions = new Array();
	this.isInQueue = true;
	this.showNextPoll = true;
	if (pollId != null)
		this.showNextPoll = false;
}
/* Helper class for storing info */
/* Gera Main Client Method which will be called */
function Gera(divID, clientAuthKey, pollId, divWidth) {
	loadGeraStyle(divID);
	var infoUnit = new geraInfoUnit(divID, clientAuthKey, pollId, divWidth,
			geraInfoStorage.length);
	geraInfoStorage.push(infoUnit);
	readGeraData(divID, clientAuthKey, pollId);
}
/* Gera Main Client Method which will be called */

/* Main method for reading dynamic info */
function processData(jsonData) {
	if (jsonData.poll == null) {
		activeInfoUnitID = getInfoStorageByPollID(jsonData.pollId);
		if (geraInfoStorage[activeInfoUnitID].geraJsonContent.results.pollId == jsonData.pollId) {
			geraInfoStorage[activeInfoUnitID].geraJsonContent.results.questionResults = jsonData.questionResults;
			if (geraInfoStorage[activeInfoUnitID].geraJsonContent.poll.questions.length == 1)
				buildSingleGeraResult(activeInfoUnitID, 0);
		}
	} else {
		activeInfoUnitID = getInfoStorageByPollID(jsonData.poll.id);
		if (geraInfoStorage[activeInfoUnitID] != null
				&& geraInfoStorage[activeInfoUnitID].geraJsonContent == null) {
			geraInfoStorage[activeInfoUnitID].geraJsonContent = jsonData;
			if (document.readyState === "complete") {
				buildGeraForm();
				return;
			}
			if (document.addEventListener) {
				document.addEventListener("DOMContentLoaded", buildGeraForm,
						false);
				window.addEventListener("load", buildGeraForm, false);
			} else if (document.attachEvent) {
				document.attachEvent("onreadystatechange", buildGeraForm);
				window.attachEvent("onload", buildGeraForm);
			}
		}
	}
}
/* Main method for reading dynamic info */

/*------------------------------*/
/* Gera Form Generation methods */
/*------------------------------*/

/*----------------------------------*/
/* Gera building form main method */
/*----------------------------------*/
function buildGeraForm() {
	for ( var i = 0; i < geraInfoStorage.length; i++) {
		if (geraInfoStorage[i].isInQueue
				&& geraInfoStorage[i].geraJsonContent != null) {
			geraInfoStorage[i].isInQueue = false;
			geraInfoStorage[i].geraDiv = document
					.getElementById(geraInfoStorage[i].geraDivID);
			geraInfoStorage[i].geraDiv.style.width = geraInfoStorage[i].geraWidth
					+ "px";
			geraInfoStorage[i].geraDiv.className += " geraMainContainer";
			geraInfoStorage[i].geraDiv.innerHTML = "";
			var error = geraInfoStorage[i].geraJsonContent.error;
			if (error != null) {
				geraInfoStorage[i].geraDiv.appendChild(createSingleElement(
						error.text, "Error"));
			} else {
				geraInfoStorage[i].geraQuestionCount = geraInfoStorage[i].geraJsonContent.poll.questions.length;
				buildSingleGeraQuestion(i, 0);
			}
		}
	}

}

/*----------------------------------*/
/* Gera building form main method */
/*----------------------------------*/

function buildSingleGeraQuestion(infoUnitID, questionSeq) {
	geraInfoStorage[infoUnitID].geraDiv.innerHTML = "";
	var footerMenu = document.createElement("div");
	footerMenu.ID = "divGeraFooterMenu" + infoUnitID;
	footerMenu.className = "divGeraFooterMenu";

	if (questionSeq < geraInfoStorage[infoUnitID].geraQuestionCount) {
		var questionData = geraInfoStorage[infoUnitID].geraJsonContent.poll.questions[questionSeq];
		if (questionData != null) {
			var divQuest = createQuestionElement(infoUnitID, questionData);
			var answers = questionData.answers;
			var answerCount = answers.length;
			geraInfoStorage[infoUnitID].geraDiv.appendChild(divQuest);
			for ( var i = 0; i < answerCount; i++) {
				geraInfoStorage[infoUnitID].geraDiv
						.appendChild(createAnswerElement(
								infoUnitID,
								answers[i],
								geraInfoStorage[infoUnitID].geraJsonContent.poll.id,
								questionData.id, questionSeq));
			}
		}
		if (geraInfoStorage[infoUnitID].geraJsonContent.poll.questions.length > 1) {
			footerMenu.appendChild(createQuestionResultInfo(infoUnitID, 0));
		}
		if (geraInfoStorage[infoUnitID].showNextPoll
				&& geraInfoStorage[infoUnitID].geraJsonContent.poll.nextPollID != -1) {
			footerMenu
					.appendChild(createNextPollElement(
							infoUnitID,
							geraInfoStorage[infoUnitID].geraJsonContent.poll.nextPollID));
		}
		if (footerMenu.hasChildNodes())
			geraInfoStorage[infoUnitID].geraDiv.appendChild(footerMenu);
	} else {
		buildSingleGeraResult(infoUnitID, 0);
	}
}

function buildSingleGeraResult(infoUnitID, currentResultSeq) {
	geraInfoStorage[infoUnitID].geraDiv.innerHTML = "";
	var resultContainer = document.createElement("div");
	resultContainer.ID = "divGeraResultContainer" + infoUnitID;
	resultContainer.className = "divGeraResultContainer";

	var footerMenu = document.createElement("div");
	footerMenu.ID = "divGeraFooterMenu";
	footerMenu.className = "divGeraFooterMenu";
	var answQuestCount = geraInfoStorage[infoUnitID].answeredQuestions.length
	if (answQuestCount > 0 && currentResultSeq <= answQuestCount) {
		var questionData = geraInfoStorage[infoUnitID].geraJsonContent.results.questionResults[currentResultSeq];
		var result = questionData.answerResults;
		var geraNavi = buildGeraNavigation(infoUnitID, answQuestCount,
				currentResultSeq);
		if (geraNavi != null) {
			resultContainer.appendChild(geraNavi);
		}
		var resultTable = createSingleResultElement(infoUnitID,
				questionData.id, result);
		resultContainer.appendChild(resultTable);
	} else {
		buildSingleGeraQuestion(infoUnitID, 0);
		return;
	}
	if (geraInfoStorage[infoUnitID].showNextPoll
			&& geraInfoStorage[infoUnitID].geraJsonContent.poll.nextPollID != -1)
		footerMenu.appendChild(createNextPollElement(infoUnitID,
				geraInfoStorage[infoUnitID].geraJsonContent.poll.nextPollID));
	if (resultContainer.hasChildNodes())
		geraInfoStorage[infoUnitID].geraDiv.appendChild(resultContainer);
	if (footerMenu.hasChildNodes())
		geraInfoStorage[infoUnitID].geraDiv.appendChild(footerMenu);
}
function createSingleResultElement(infoUnitID, questionId, answerResults) {
	var resultTable = document.createElement("div");
	resultTable.ID = "divGeraResultTable" + infoUnitID;
	resultTable.className = "divGeraResultTable";
	var questionText = getTextById(infoUnitID, questionId);
	resultTable.appendChild(createSingleElement(infoUnitID, questionText,
			"Question"));
	for ( var i = 0; i < answerResults.length; i++) {
		resultTable.appendChild(createResultDivRow(infoUnitID, questionId,
				answerResults[i]));
	}
	return resultTable;
}
function createResultDivRow(infoUnitID, questionId, answerResult) {
	var answerText = getTextById(infoUnitID, questionId, answerResult.id);
	var resultRow = document.createElement("div");
	resultRow.className = "divGeraAnswerRow";

	var resultCol1 = document.createElement("div");
	resultCol1.className = "divGeraAnswerCol1";
	resultCol1.innerHTML = answerText + ":&nbsp;&nbsp;&nbsp;&nbsp;";
	var resultCol2 = document.createElement("div");

  resultCol2.className = "divGeraAnswerCol2";

  var bar = document.createElement("div");

  var percentage = document.createElement("span");
  percentage.innerHTML = answerResult.percent + "%";

  resultCol2.appendChild(bar);
  resultCol2.appendChild(percentage);

  resultRow.appendChild(resultCol1);
	resultRow.appendChild(resultCol2);

  $fx(bar).fxAdd({ type: 'width', from: 0, to: answerResult.percent, unit: '%', step: 3, delay: 20 }).fxRun(null, 1);

  return resultRow;
}

function getTextById(infoUnitID, questionId, answerId) {
	for ( var i = 0; i < geraInfoStorage[infoUnitID].geraQuestionCount; i++) {
		if (geraInfoStorage[infoUnitID].geraJsonContent.poll.questions[i].id == questionId)
			if (answerId == null) {
				return geraInfoStorage[infoUnitID].geraJsonContent.poll.questions[i].text;
			} else {
				var answCount = geraInfoStorage[infoUnitID].geraJsonContent.poll.questions[i].answers.length;
				for ( var j = 0; j < answCount; j++) {
					if (geraInfoStorage[infoUnitID].geraJsonContent.poll.questions[i].answers[j].id == answerId)
						return geraInfoStorage[infoUnitID].geraJsonContent.poll.questions[i].answers[j].text;
				}
			}
	}
	return "";
}

function buildGeraNavigation(infoUnitID, answQuestCount, currentResultSeq) {
	var nextResultSeq = currentResultSeq + 1;

	if (geraInfoStorage[infoUnitID].geraQuestionCount > 1
			&& currentResultSeq <= answQuestCount && answQuestCount != 0) {
		var geraNaviMain = document.createElement("div");
		geraNaviMain.ID = "divGeraNaviMain" + infoUnitID;
		geraNaviMain.className = "divGeraNaviMain";

		if (currentResultSeq < geraInfoStorage[infoUnitID].geraQuestionCount - 1) {
			var geraNaviPartLeft = document.createElement("div");
			geraNaviPartLeft.className = "divGeraNaviCursor";
			geraNaviPartLeft.innerHTML = "&nbsp;&gt;";
			geraNaviPartLeft.onclick = function() {
				activeInfoUnitID = infoUnitID;
				if (currentResultSeq >= answQuestCount - 1) {

					buildSingleGeraQuestion(infoUnitID, nextResultSeq);
				} else {
					buildSingleGeraResult(infoUnitID, nextResultSeq);
				}
			}
			geraNaviMain.appendChild(geraNaviPartLeft);
		}
		var geraNaviPartInfo = document.createElement("div");
		geraNaviPartInfo.className = "divGeraNaviCounter";
		geraNaviPartInfo.innerHTML = nextResultSeq + "/"
				+ geraInfoStorage[infoUnitID].geraQuestionCount;
		geraNaviMain.appendChild(geraNaviPartInfo);

		if (currentResultSeq > 0) {
			var geraNaviPartRight = document.createElement("div");
			geraNaviPartRight.className = "divGeraNaviCursor";
			geraNaviPartRight.innerHTML = "&lt;&nbsp;";
			geraNaviPartRight.onclick = function() {
				activeInfoUnitID = infoUnitID;
				buildSingleGeraResult(infoUnitID, currentResultSeq - 1);
			}
			geraNaviMain.appendChild(geraNaviPartRight);
		}
		return geraNaviMain;
	}
}

function createSingleElement(infoUnitID, val, elName) {
	var resultElement = document.createElement("div");
	resultElement.ID = "divGera" + elName + infoUnitID;
	resultElement.className = "divGera" + elName;
	resultElement.innerHTML = val;
	return resultElement;
}

function createQuestionResultInfo(infoUnitID, questionSeqID) {
	var questioResultElement = document.createElement("div");
	questioResultElement.ID = "divGeraQuestionResult" + infoUnitID;
	questioResultElement.className = "divGeraQuestionResult";
	questioResultElement.innerHTML = "Question Result";
	questioResultElement.onclick = function() {
		activeInfoUnitID = infoUnitID;
		buildSingleGeraResult(infoUnitID, questionSeqID);
	}
	return questioResultElement;
}

function createQuestionElement(infoUnitID, question) {
	var questionElement = document.createElement("div");
	questionElement.className += " divGeraQuestion";
	questionElement.ID = " divGeraQuestion" + infoUnitID + "_" + question.id;
	questionElement.innerHTML = question.text;
	return questionElement;
}

function createAnswerElement(infoUnitID, answer, pollId, questionID,
		questionSeq) {
	var answerElement = document.createElement("div");
	answerElement.ID = "divGeraAnswer" + answer.id;
	answerElement.className += " divGeraAnswer";

	var rbnLabel = document.createElement("label");
	rbnLabel.className = "geraRadioLabel";

	var rbnElement = document.createElement("input");
	rbnElement.type = "radio";
	rbnElement.name = "rbnGeraAnswer";
	rbnElement.className = "rbnGeraAnswer";
	rbnElement.id = "rbnGeraAnswer" + infoUnitID + "_" + answer.id;
	rbnElement.value = answer.id;
	rbnElement.onclick = function() {
		activeInfoUnitID = infoUnitID;
		readGeraData(geraInfoStorage[infoUnitID].geraDivID,
				geraInfoStorage[infoUnitID].geraClntAuthID, pollId, questionID,
				this.value);
		geraInfoStorage[infoUnitID].answeredQuestions.push(questionID);
		if (geraInfoStorage[infoUnitID].geraJsonContent.poll.questions.length > 1)
			buildSingleGeraQuestion(infoUnitID, questionSeq + 1);
	}

	rbnLabel.appendChild(rbnElement);
	rbnLabel.htmlFor = rbnElement.id;
	rbnLabel.appendChild(document.createTextNode(answer.text));

	answerElement.appendChild(rbnLabel);
	return answerElement;
}

function createNextPollElement(infoUnitID, nextPollID) {
	var nextPollElement = document.createElement("div");
	nextPollElement.ID = "divGeraNextPoll";
	nextPollElement.className += " divGeraNextPoll";
	;
	nextPollElement.innerHTML = "Next Poll";
	nextPollElement.onclick = function() {
		geraInfoStorage[infoUnitID].geraJsonContent = null;
		geraInfoStorage[infoUnitID].pollID = nextPollID;
		readGeraData(geraInfoStorage[infoUnitID].geraDivID,
				geraInfoStorage[infoUnitID].geraClntAuthID, nextPollID);
	}
	return nextPollElement;
}

/*------------------------------*/
/* Gera Form Generation methods */
/*------------------------------*/

/* Gera addiotional files (scripts, in future styles adding) */
function readGeraData(geraDivID, clntAuthID, pollID, questionID, answerID) {
	var scriptId = geraDivID + clntAuthID;
	removePreviousGeraScript(scriptId);
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.id = scriptId
	newScript.type = 'text/javascript';
	newScript.language = "javascrtipt";
	newScript.src = apiScriptUrl + clntAuthID;
	if (pollID != null) {
		newScript.src += '/' + pollID;
	}
	if (questionID != null && answerID != null) {
		newScript.src += '/' + questionID + '/' + answerID;
	}
	headID.appendChild(newScript);
}

function loadGeraStyle() {

	var headID = document.getElementsByTagName("head")[0];
	var styleRef = document.createElement("link");
	styleRef.setAttribute("rel", "stylesheet");
	styleRef.setAttribute("type", "text/css");
	styleRef.setAttribute("href", apiStyleUrl);
	headID.appendChild(styleRef);
}
/* Gera addiotional files (scripts, in future styles adding) */

function removePreviousGeraScript(scriptId) {
	var allFound = document.getElementsByTagName("script")
	for ( var i = 0; i < allFound.length; i++) {
		if (allFound[i].id != null && allFound[i].id == scriptId) {
			document.getElementsByTagName("head")[0].removeChild(allFound[i]);
			break;
		}
	}
}
function getInfoStorageByPollID(pollID) {
	for ( var i = 0; i < geraInfoStorage.length; i++) {
		if (geraInfoStorage[i].pollID != null
				&& geraInfoStorage[i].pollID == pollID) {
			return geraInfoStorage[i].id;
		} else if (geraInfoStorage[i].pollID == null) {
			geraInfoStorage[i].pollID = pollID;
			return geraInfoStorage[i].id;
		}
	}
}

// inlined $fx library code
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('q $1y(g){7(g.18&&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I)9 3;A(8 p 1r m){7(!c[p])c[p]=m[p]};7(!c.D){A(8 e 1r k)7((T K(e,\'i\').1Y(c.r))){c.D=k[e];1Z}};c.J=(c.J&&c.J.B)?c.J:q(){};c.M=(c.M&&c.M.B)?c.M:q(){};7(!3.6[c.r]){7(n[c.r])3.6[c.r]=n[c.r];t{8 f=3;3.6[c.r]=q(a,b){7(W(a)==\'X\')9 u(f.v[c.r]);t f.v[c.r]=u(a)+b}}};7(z(c.F)){7(z(3.6[c.r]()))7(o[c.r])c.F=o[c.r]();t c.F=0;t c.F=3.6[c.r]()}c.11=c.F;3.6[c.r](c.F,c.D);3.6.4[d].w.20(c);9 3};h.1s=q(a,b,c){8 d=h.6.C;7(3.6.4[d].I){9 3}1t(q(){7(h.6.4[d].I)9 h;h.6.4[d].I=12;7(h.6.4[d].N>0)9 h;h.6.4[d].13=(a&&a.B)?a:q(){};h.6.4[d].1u=(c&&c.B)?c:q(){};7(!z(b))h.6.4[d].V=b;A(8 i=0;i<h.6.4[d].w.G;i++){h.6.4[d].w[i].J.B(h);h.6.O(d,i)}},h.6.4[d].10);9 3};h.1v=q(a,b){3.6.4[!z(b)?b:3.6.C].14=a;9 3};h.1w=q(a){3.6.4[!z(a)?a:3.6.C].15=12;9 3};h.1x=q(){A(8 i=0;i<3.6.4.G;i++){A(8 j=0;j<3.6.4[i].w.G;j++){8 a=3.6.4[i].w[j];7(z(a.11))3.6[a.r](\'\',\'\');t 3.6[a.r](a.11,a.D)}}8 b=[\'6\',\'1p\',\'1q\',\'1o\',\'1s\',\'1v\',\'1w\',\'1x\'];A(8 i=0;i<b.G;i++)1a{1b 3[b[i]]}1c(1d){3[b[i]]=Q}3.L=12};h.6.R=q(){8 a=3.4.G;3.C=a;3.4[a]={};3.4[a].V=1;3.4[a].15=16;3.4[a].w=[];3.4[a].N=0;3.4[a].P=0;3.4[a].10=0;3.4[a].14=16;3.4[a].I=16;3.4[a].13=q(){};9 3};h.6.O=q(a,b){7(!3.4[a]||3.4[a].15||h.L)9;8 c=3.4[a].w[b];8 d=3[c.r]();7((c.H>0&&d+c.H<=c.17)||(c.H<0&&d+c.H>=c.17)){7(!3.4[a].14)3[c.r](d+c.H,c.D);8 e=3;1t(q(){7(e.O)e.O(a,b)},c.1k)}t{3[c.r](c.17,c.D);3.4[a].N++;c.M.B(h);7(3.4[a].w.G==3.4[a].N){3.4[a].N=0;3.4[a].P++;3.4[a].1u.B(h,3.4[a].P);7(3.4[a].P<3.4[a].V||3.4[a].V==-1){A(8 i=0;i<3.4[a].w.G;i++){3[c.r](c.F,3.4[a].w[i].D);3.4[a].w[i].J.B(h,3.4[a].P);3.O(a,i)}}t{3.4[a].13.B(h)}}}};h.6.R();9 h}',62,125,'|||this|sets||_fx|if|var|return|||||||||||||||||function|type||else|parseInt|style|_queue|||isNaN|for|call|_currSet|unit|opacity|from|length|step|_isrunning|onstart|RegExp|_fxTerminated|onfinish|_effectsDone|_process|_loopsDone|null|_addSet|100|new|backgroundPosition|_loops|typeof|undefined|exec|Math|_holdTime|_initial|true|_onfinal|_paused|_stoped|false|to|nodeType|match|try|delete|catch|err|left|top|width|height|backgroundx|backgroundy|delay|alpha|filter|offsetParent|fxAddSet|fxHold|fxAdd|in|fxRun|setTimeout|_onloop|fxPause|fxStop|fxReset|fx|String|document|getElementById|fxVersion|right|bottom|margin|padding|spacing|px|font|pt|navigator|userAgent|MSIE|ig|round|parseFloat|min|max|zoom|offsetWidth|offsetHeight|offsetLeft|offsetTop|test|break|push'.split('|'),0,{}))
