delfiQuiz_config = function() {
	var c = this;
/**
 * Configuration for Poll Application.
 */

/* where all frontend public files are located */
c.baseUrl = 'http://q.delfi.lt';

/* delfi picture base url */
c.pollEmbedPictureBase = 'http://q.delfi.lt/image.php?s=1&id=';

/* embed video config */
c.embedVideoMediaPlayerUrl = 'http://tv.delfi.lt/gfx/mediaplayer.swf';
c.embedVideoFileUrl = 'http://ytv.delfi.lt/v';
c.embedVideoThumbUrl = 'http://ytv.delfi.lt/th';
c.embedVideoRelatedUrl = 'http://tv.delfi.lt/related';
c.embedVideoWatermarkUrl = 'http://tv.delfi.lt/gfx/watermark.png';

/* force reloading files, use no cache, good for debug */
c.forceReloadSources = true;

/* Default language */
c.defaultLanguage = 'lt_LT';



/* where  jquery is located */
c.jQueryLibraryFullUrl = c.baseUrl + '/jquery/jquery.js?ver=1';

/* where templates are */
c.templatesBaseUrl = c.baseUrl + '/jstemplates';

/* polldata and voteing url must be in same domain because of cookies they use */
c.pollDataUrl = c.baseUrl + '/polldata.php';
c.pollVoteUrl = c.baseUrl + '/vote.php';

}
/**
 * Global variables used by this application
 */ 
if(typeof(delfiQuiz_isJQueryLoading) == 'undefined'){
	var delfiQuiz_isJQueryLoading = false;
}
if(typeof(delfiQuiz_pollInstances) == 'undefined'){
	var delfiQuiz_pollInstances = new Array();
}

/**
 * debug function for developing
 * fills textarea with given ID with given data
 */ 
if(typeof(ddebug) == 'undefined'){
	function ddebug(data, clean, divid){
		var clean = (clean == null) ? false : clean;
		var did = (divid == null) ? 'debug' : divid;
		
		var objTemp = document.getElementById(did);
		if(objTemp == null || typeof(objTemp) != 'object'){
			var oScript = document.createElement("div");
			oScript.setAttribute("id", did + '_div');
			document.body.appendChild(oScript);			
			var objTemp = document.getElementById(did + '_div');
			objTemp.style.position = 'absolute';
			objTemp.style.top = '5px';
			objTemp.style.right = '5px';
			objTemp.innerHTML = '<textarea id="' + did + '" cols="60" rows="15"></textarea>';
		}
		
		var objTemp = document.getElementById(did);
		if(objTemp){
			if(clean == true){
				objTemp.value = data;
			} else {
				objTemp.value = objTemp.value + '' + data + '\n';
			}
		}
	}
}


function print_r(data, intLev) {

	var intLev = (intLev == null) ? 0 : intLev;		
	var strRet = '';
	var eof = "\n";
	var pad = '';
	
	
	for(var x=0; x < intLev; x++){
		pad += "\t";
	}
	
	if(data.constructor == Array || data.constructor == Object) {
		for(var p in data){
			if(typeof(data[p]) == 'object'){
				strRet += pad + "\t["+p+"] => "+typeof(data) + eof;
				
				strRet += pad + "\t" + "(" + eof;
				strRet += print_r(data[p], intLev +1);
				strRet += pad + "\t" + ")" + eof;
				
			} else {
				strRet += pad + "\t["+p+"] => " + data[p] + eof;
			}
		}
	} else {
		strRet += pad + data + eof;
	}

	return strRet;
}


/**
 * adds script or css file to header of the document 
 * NOTE - in opera document must have HEAD element inserted in HTML, otherwise 
 * it won't work
 */
function delfiQuiz_addElementToHeader(type, src, id) {
	var id = (id == null) ? '' : id;
	
	if(type == 'script'){
		var oScript = document.createElement("script");
		oScript.type= 'text/javascript';
		oScript.setAttribute("src", src);
	} else {
		var oScript = document.createElement("link");
		oScript.rel = "stylesheet";
		oScript.type= 'text/css';
		oScript.href = src;
	}
	
	oScript.setAttribute("id", id);
	oScript.defer = true;
	
	var oHead = document.getElementsByTagName("head").item(0);	
	oHead.appendChild(oScript);
}

// function to determine if some part of DOM is loaded
function domFunction(f, a) {
	var n = 0;
	var t = setInterval(function() {
		var c = true;
		n++;
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null)) {
			c = false;
			if(typeof a == 'object') {
				for(var i in a) {
					if ((a[i] == 'id' && document.getElementById(i) == null) || (a[i] == 'tag' && document.getElementsByTagName(i).length < 1)) { 
						c = true; 
						break; 
					}
				}
			}
			if(!c) { f(); clearInterval(t); }
		}
		if(n >= 100)	{
			clearInterval(t);
		}
	}, 100);
};



/**
 * function that adds other functions into window.onload event 
 * leaving others also intact 
 */ 
function delfiQuiz_addOnLoadEvent(func) {
	// check if HEAD part is loaded, if yes then we need to load other scripts
	domFunction(func, 'head');
}


/**
 * Main function wichtrough polls are loaded
 * if password is set and it is right poll w'll be loaded even if it's not active 
 */ 
function _loadQuiz(pollId, password){
	var password = (typeof(password) == 'undefined') ? '' : password;
	var c = new delfiQuiz_config();
	
	/* get given extra params - do we ned those for individual poll anyway */
	arrExtraParams = new Array();
	arrExtraParams['quizRedirectURL'] = typeof(_quizRedirectURL) == 'undefined' || _quizRedirectURL == null	? '' : _quizRedirectURL;
	arrExtraParams['quizReloadPage'] = typeof(_quizReloadPage) == 'undefined' || _quizReloadPage == null	? '' : _quizReloadPage;
	arrExtraParams['quizShowResults'] = typeof(_quizShowResults) == 'undefined' || _quizShowResults == null	? '' : _quizShowResults;
	arrExtraParams['quizTemplate'] = typeof(_quizTemplate) == 'undefined' || _quizTemplate == null	? '' : _quizTemplate;
	var quizForceDivId = typeof(_quizForceDivId) == 'undefined' || _quizForceDivId == null	? '' : _quizForceDivId;
	if(typeof(_quizRedirectURL) != 'undefined') _quizRedirectURL = null;
	if(typeof(_quizReloadPage) != 'undefined') _quizReloadPage = null;
	if(typeof(_quizShowResults) != 'undefined') _quizShowResults = null; 
	if(typeof(_quizTemplate) != 'undefined') _quizTemplate = null;
	if(typeof(_quizForceDivId) != 'undefined') _quizForceDivId = null;

	/* generate random uniqe name for current poll div id ID not forced */
	if(quizForceDivId == '' || quizForceDivId == null){
		var intRand = Math.floor(Math.random() * 99);
		var currentTime = new Date();
		var divIdTmp = 'emb_' + currentTime.getTime() + intRand + '_' + pollId;
	}
	

	/* write inital div where later all poll contents will be transported if not forced to use precreated DIV */
	if(quizForceDivId == '' || quizForceDivId == null){
		var strDivData = '<a name="quiz_content"></a><a name="a_' + divIdTmp + '"></a><div id="' + divIdTmp + '" class="delfi_quiz_base"><center><img src="' + c.baseUrl + '/img/loading.gif"></center></div>';
		document.write(strDivData);
	}else {
		divIdTmp = quizForceDivId;
		document.getElementById(quizForceDivId).className = 'delfi_quiz_base';
	}

	/* call loader helper */
	delfiQuiz_loadQuizHelper(pollId, divIdTmp, password, false, arrExtraParams);
}


/**
 * Main function wichtrough grouped polls are loaded
 * It shows first active poll in given group 
 * if password is set and it is right poll w'll be loaded even if it's not active 
 */ 
function _loadGroupPoll(groupId, password){
	var password = (typeof(password) == 'undefined') ? '' : password;
	var c = new delfiQuiz_config();
	
	/* get given extra params */
	arrExtraParams = new Array();
	arrExtraParams['quizRedirectURL'] = typeof(_quizRedirectURL) == 'undefined' || _quizRedirectURL == null	? '' : _quizRedirectURL;
	arrExtraParams['quizReloadPage'] = typeof(_quizReloadPage) == 'undefined' || _quizReloadPage == null	? '' : _quizReloadPage;
	arrExtraParams['quizShowResults'] = typeof(_quizShowResults) == 'undefined' || _quizShowResults == null	? '' : _quizShowResults;
	arrExtraParams['quizTemplate'] = typeof(_quizTemplate) == 'undefined' || _quizTemplate == null	? '' : _quizTemplate;
	var quizForceDivId = typeof(_quizForceDivId) == 'undefined' || _quizForceDivId == null	? '' : _quizForceDivId;
	if(typeof(_quizRedirectURL) != 'undefined') _quizRedirectURL = null;
	if(typeof(_quizReloadPage) != 'undefined') _quizReloadPage = null;
	if(typeof(_quizShowResults) != 'undefined') _quizShowResults = null; 
	if(typeof(_quizTemplate) != 'undefined') _quizTemplate = null;
	if(typeof(_quizForceDivId) != 'undefined') _quizForceDivId = null;

	/* generate random uniqe name for current poll div id ID not forced */
	if(quizForceDivId == '' || quizForceDivId == null){
		var intRand = Math.floor(Math.random() * 99);
		var currentTime = new Date();
		var divIdTmp = 'emb_' + currentTime.getTime() + intRand + '_' + groupId;
	}
	
	/* write inital div where later all poll contents will be transported if not forced to use precreated DIV */
	if(quizForceDivId == '' || quizForceDivId == null){
		var strDivData = '<div id="' + divIdTmp + '" class="delfi_quiz_base"><center><img src="' + c.baseUrl + '/img/loading.gif"></center></div>';
		document.write(strDivData);
	} else {
		divIdTmp = quizForceDivId;
		document.getElementById(quizForceDivId).className = 'delfi_quiz_base';
	}
	
	/* call loader helper */
	delfiQuiz_loadQuizHelper(groupId, divIdTmp, password, true, arrExtraParams);
}


/**
 * helper function for _loadQuiz what passes new poll load function 
 * for waiting window.ready event 
 */ 
function delfiQuiz_loadQuizHelper(pollId, divId, password, group, arrParams){
	var tmpUrl = new String(document.location);
	if (tmpUrl.indexOf('_qa=true') > 0) {
		arrParams['quizShowResults'] = true;
	}
	if (arrParams['quizReloadPage'] == true) {
		if (!arrParams['quizRedirectURL']) {
			if (tmpUrl.indexOf('#') > 0) {
				tmpUrl = tmpUrl.substr(0, tmpUrl.indexOf('#'));
			}
			var tmpSeparator = (tmpUrl.indexOf('?') < 0) ? '?' : '&';
			tmpUrl += tmpSeparator + '_qa=true#quiz_content';
			arrParams['quizRedirectURL'] = tmpUrl;
		}
	}
	delfiQuiz_addOnLoadEvent(function(){
		delfiQuiz_loader(pollId, divId, 0, password, group, escape(arrParams['quizRedirectURL']), arrParams['quizShowResults'], arrParams['quizTemplate']);
	});
}




/**
 * adds jQuery library if not added yet and afterwards requests poll data 
 *   
 * This function will be looped until jQuery object is loaded or timeout
 * will be reached (hitcount over X cycles). If jQuery is loaded data URL w'll be asked. 
 * After that this cycle stops. For that moment asked data JS callback function 
 * is responsible of program flow for current poll or group
 * 
 * also add quiz main css file and swf object writer class file if needed
 */ 
function delfiQuiz_loader(pollId, divId, hitCount, password, group, quizRedirectURL, quizShowResults, quizTemplate) {
	var hitCount = hitCount + 1;	
	var c = new delfiQuiz_config();
	/* add jQuery library file if not yet added, also image needed by thickbox  */
	if(hitCount == 1 && delfiQuiz_isJQueryLoading == false){
		delfiQuiz_addElementToHeader('script', c.jQueryLibraryFullUrl);		
		delfiQuiz_isJQueryLoading = true;
		
		delfiQuiz_imgLoader = new Image();
		delfiQuiz_imgLoader.src = strSrc = c.baseUrl + '/img/loading_thickbox.gif';
	}
	
	/**
	 * is jQuery library loaded yet or not?
	 * if not, we have to come back later to check on it 
	 */
	if(typeof($) == 'undefined'){
		if(hitCount < 400){
			setTimeout("delfiQuiz_loader(' " + pollId + "' , '" + divId + "', " + hitCount + ", '" + password + "', "+ group +", '" + quizRedirectURL + "', '"+ quizShowResults +"', '" + quizTemplate + "')", 50);
		} else {
			/* throw 'JQuery library load timeout'; */
		}
	} else {		
		/* add msie6 dedection */
		jQuery.browser.msie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && !window["XMLHttpRequest"];
		
		/**
		 * finaly start loading image data object and stop cycle
		 * also add main css and swf object file + thickbox loader image 
		 */		
		var strSrc = c.baseUrl + '/' + 'css/delfiquiz.css';
		if(c.forceReloadSources){
			strSrc += '?rnd=' + divId;
		}		
		delfiQuiz_addElementToHeader('style', strSrc);
		
		if(typeof(SWFObject) == 'undefined'){
			$.ajax({				
				url: c.baseUrl + '/swfobject.js',
				type: "GET",
				dataType: "script"
			});
		}
		
		$.ajax({				
			url: c.pollDataUrl + '?pollId=' + parseInt(pollId) + 
				'&divId=' + divId + 
				'&password=' + password + 
				'&group=' + group + 
				'&quizRedirectURL=' + quizRedirectURL + 
				'&quizTemplate=' + quizTemplate +
				'&quizShowResults=' + quizShowResults,
			type: "GET",
			dataType: "script"
		});	
	}
}

/**
 * thi is callback function from polldata
 * it initalizes given poll and renders it on page 
 * also adds needed events 
 */ 
function delfiQuiz_initPollInstance(divId){
	/* do initial stuff */
	delfiQuiz_pollInstances[divId].initPoll();
	
	/* render poll */
	delfiQuiz_pollInstances[divId].renderPoll();
	
	/* add click, mouseover and other cool events and actions */
	delfiQuiz_pollInstances[divId].addEvents();
}


function delfiQuiz_noSuchPoll(divId, lang){
	$("#" + divId).html(delfiQuiz_translate('noSuchPoll', lang));
}

function delfiQuiz_pollNotActive(divId, lang){
	$("#" + divId).html(delfiQuiz_translate('pollNotActive', lang));
}


function delfiQuiz_pollInFuture(divId, lang){
	$("#" + divId).html('');
}


/**
 * base-global methods for templates 
 */ 
function delfiQuiz_templateBase() {	
	this.showVoteButton = false;
	this.isQuizType = false;
	this.showInlineThankYou = false;
	this.showInlineQuestions = true;
	
	/* currently answered questions */
	this.arrCurrentAnswers = Array();
	
	/* currently answered questions, copy of last one for other reasons(chained, obligatory, shown) */
	this.arrCurrentAnswersCheck = Array();

	/* does this poll have chained questions */
	this.hasChainedQuestions = false;
	
	/**
	 * Maximum number of votes given to this poll
	 */
	this.maxVotes = 0;
	
	/**
	 * If every question has no result, this remains true
	 */
	this.allQuestionsNoResult = true;
	
	/**
	 * If every question is already answered this remains true
	 */
	this.allQuestionsAnswered = true;
}


/**
 * Some inital actions are wrapped here
 */ 
delfiQuiz_templateBase.prototype.initPoll = function() {
		/* prepare data for template */
		this.prepareData();
		
		var qCount = this.pdata['questions'].length - 1;
		
		/**
		 * put array key also in question data
		 * is the vote button nessecary
		 * is there quiz question too
		 * is question shown in initial view (cchained question)
		 */		 
		for (var i=0;i<=qCount;i++) {
			/* put array key also along */
			this.pdata['questions'][i]['qKey'] = i;
			
			/* this says is question showed at intial view */
			this.pdata['questions'][i]['view_at_astart'] = 1; 
			
			//tells that is question shown at moment
			this.pdata['questions'][i]['view'] = 0;
			
			/* is this question answered and page is not reloaded yet */
			this.pdata['questions'][i]['no_refresh_answered'] = 0;
			
			var tempInt = parseInt(this.pdata['questions'][i]['type']);
			var tempInt2 = parseInt(this.pdata['questions'][i]['result_type']);
			var tempInt3 = parseInt(this.pdata['questions'][i]['already_answered']);
			
			if(tempInt == 1 || tempInt == 2 || tempInt == 5){
				this.showVoteButton = true;
			}
			
			if(tempInt == 1){
				this.isQuizType = true;
			}
			
			if(tempInt2 != 5){
				this.allQuestionsNoResult = false;
			}
			
			if(tempInt3 != 1){
				this.allQuestionsAnswered = false;
			}
			
			/**
			 * look trough chains if any, and find out questions that cant't be in inital view (view_at_astart) 
			 * First question is always shown
			 */
			if(i > 0){
				var isChainedQ = false;
				var isChainedA = false;
				if(this.pdata['chains'].length > 0){
					var qChainsCnt = this.pdata['chains'].length - 1;
					
					for (var j=0;j<=qChainsCnt;j++){
						if(this.pdata['chains'][j]['chained_to_q'] == this.pdata['questions'][i]['question_id'] && this.pdata['chains'][j]['from_type'] == 'q'){
							isChainedQ = true;
						}
						if(this.pdata['chains'][j]['chained_to_q'] == this.pdata['questions'][i]['question_id'] && this.pdata['chains'][j]['from_type'] != 'q'){
							isChainedA = true;
						}
					}
					
				}
				
				if(isChainedQ && isChainedA){
					this.pdata['questions'][i]['view_at_astart'] = 0;
					this.hasChainedQuestions = true;
				} else if(isChainedA && !isChainedQ){
					this.pdata['questions'][i]['view_at_astart'] = 0;
					this.hasChainedQuestions = true;
				} else if(isChainedQ){
					this.pdata['questions'][i]['view_at_astart'] = 0;
					this.hasChainedQuestions = true;
				}
			}
			
		}
		
		/**
		 * No we find out are inital questions even viewable. They might be answered or somthing allready
		 */
		if(this.hasChainedQuestions){
			this.allQuestionsAnswered = true;
			for (var i=0;i<=qCount;i++) {
				if(this.pdata['questions'][i]['view_at_astart']){				
					var tempInt3 = parseInt(this.pdata['questions'][i]['already_answered']);
					if(tempInt3 != 1){
						this.allQuestionsAnswered = false;
					}
				}
			}
		}
		
		
		
		
		/* are (inline) answers forced? */
		if(this.pdata['quizShowResults']){		
			this.allQuestionsAnswered = true;
		}
		
		/* kui koikidele kysimustele on juba vastatud, siis ara n2ita vastamise nuppu */
		if(this.allQuestionsAnswered){
			this.showVoteButton = false;
		} 
		
		//Mittenähtav kui vastatud kõik ja pole popup vastuseid
		if(this.pdata['poll']['answer_in_popup'] == 0 && this.allQuestionsAnswered){
			this.pdata['poll']['show_results_button'] = 0;
		}
		
		if(this.allQuestionsNoResult && this.allQuestionsAnswered && !this.isQuizType){
			this.showInlineThankYou = true;
		}


		/* if poll not active rewrite some statuses */
		if(this.pdata['poll_active'] == 0){
			this.allQuestionsAnswered = true;
			if(this.allQuestionsNoResult && this.allQuestionsAnswered && !this.isQuizType){
				this.showInlineThankYou = true;
			} else {
				this.showInlineQuestions = true;
			}
			this.showVoteButton = false;
		}
	
	//how many votes to add after answering questions to on-site-answercount
	this.intMaxVotesAdd = 1;
}


/**
 * Check for question - answer for chaining.
 * Returns next question ID if chained
 * otherwise it returns false 
 */ 
delfiQuiz_templateBase.prototype.checkForChain = function(qId, aId) {
	if(aId === false) {
		return false;
	}
	
	if(this.pdata['chains'].length > 0){
		var qChainsCnt = this.pdata['chains'].length - 1;
		//by answer
		for (var j=0;j<=qChainsCnt;j++){
			if(this.pdata['chains'][j]['chained_from_q'] == qId && this.pdata['chains'][j]['from_type'] != 'q' && this.pdata['chains'][j]['chained_from_a'] == aId){
				return this.pdata['chains'][j]['chained_to_q'];
			}
		}
		//by question
		for (var j=0;j<=qChainsCnt;j++){
			if(this.pdata['chains'][j]['chained_from_q'] == qId && this.pdata['chains'][j]['from_type'] == 'q'){
				return this.pdata['chains'][j]['chained_to_q'];
			}
		}
	}
	
	return false;
}


/**
 * foreaches every embed object in array and get-s html for them 
 * if this type of embed method is in this template
 * use that, otherwise use global one .. 
 * 
 * at moment, html will not be returned, 
 * instead it will be omitted current objects embed object data buffer wichtrough 
 * html is grabed where it was orginally requested     
 */ 
delfiQuiz_templateBase.prototype.getEmbedHtml = function(arrEmbed) {
	if(typeof(arrEmbed) != 'undefined'){
		var aeCount = arrEmbed.length - 1;
		this.embedData = '';
		var that = this;
		
		if(aeCount > -1){
			var j = 0;
			for (j=0;j<=aeCount;j++)
			{
				var localFunc = 'getEmbedHtmlLocal_' + arrEmbed[j]['type'];
				var globalFunc = 'getEmbedHtmlGlobal_' + arrEmbed[j]['type'];
				var arrEmbedData = arrEmbed[j];
				
				var evalString = '';
				evalString += 'if(typeof(that.' + localFunc + ') != "undefined"){ ';
				evalString += '	that.' + localFunc + '("' + arrEmbed[j]['data'] + '");';
				evalString += '} else if (typeof(that.' + globalFunc + ') != "undefined"){ ';
				evalString += '	that.' + globalFunc + '(arrEmbedData);';
				evalString += '}';
								
				eval(evalString);
			}
		}
	} else {
		/* throw 'No embed data given in delfiQuiz_templateBase::getEmbedHtml()'; */
	}
}


/**
 * this method loads new questions data 
 * callback method is processQuestionsData 
 **/ 
delfiQuiz_templateBase.prototype.loadQuestionsData = function(strDir) {	
	
	if(strDir == 'prev'){
		var intStart = this.pdata['otherQuestions']['start'] - this.pdata['otherQuestionsPerPage'];
	} else {
		var intStart = this.pdata['otherQuestions']['start'] + this.pdata['otherQuestionsPerPage'];
	}
	
	$.ajax({		
		url: this.c.baseUrl + '/archivedata.php?pollId=' + this.pollId + '&divId=' + this.divId + '&start=' + intStart + '&count=' + this.pdata['otherQuestionsPerPage'],
		type: "GET",
		dataType: "script"
	});
	
}


/**
 * adds "next" and "prev" button events in otherQuestions part.. 
 * also  all otherQuestion links w'll get onclick action 
 */ 
delfiQuiz_templateBase.prototype.addEventsToOtherQuestions = function() {
	var baseId = this.getOtherQuestionsDivId();
	var that = this;
	
	/* next button */
	$('#' + baseId + '_next').click(function(){
		that.loadQuestionsData('next');
		return false;		
	});
	
	/* prev button */
	$('#' + baseId + '_prev').click(function(){
		that.loadQuestionsData('prev');
		return false;		
	});

	var eQCount = this.pdata['otherQuestions']['questions'].length - 1;
	
	var j = 0;
	for (j=0;j<=eQCount;j++){	
		this.addEventToOtherQuestion(j);
	}
		
}


/* just a helper for previus method */
delfiQuiz_templateBase.prototype.addEventToOtherQuestion = function(oqKey) {
	var that = this;
	var baseId = this.getOtherQuestionsDivId();
	
	$('#' + baseId + '_q_' + oqKey).click(function(){
		that.renderOtherQuestion(oqKey);		
		return false;		
	});
}


/* just a helper for previus method */
delfiQuiz_templateBase.prototype.renderOtherQuestion = function(m) {
	/* hide other answers */
	var qCount = this.pdata['questions'].length - 1;
	var i = 0;
	for (i=0;i<=qCount;i++)
	{
		$("#" + this.getQuestionPopupAnswerDivId(i)).css('display', 'none');
	}
	
	/* hide quiz answer */ 	
	$("#" + this.getQuizResultDivId() + '_popup').css('display', 'none');
	
	/* show one otherQuestion div */
	$("#" +  this.getOtherQuestionsDivId() + '_question').css('display', '');	
	
	$('#' + this.getOtherQuestionsDivId() + '_question').html(this.renderQuestionResult(this.pdata['otherQuestions']['questions'][m], 'return'));
}


/**
 * grabs new other questions data and process it
 */ 
delfiQuiz_templateBase.prototype.processOtherQuestionsData = function(data) {
	if(typeof(data['questions'].length) != 'undefined' && data['questions'].length > 0){
		this.pdata['otherQuestions'] = data;
		this.renderOtherQuestions();
	}
}


/**
 * Render poll
 */ 
delfiQuiz_templateBase.prototype.renderPoll = function() {
	var htmlOut = '';
	var qId = null;
	var qKey = null;
	
	/* add this polls css file into header */
	var strSrc = this.c.templatesBaseUrl + '/' + this.pdata['template'] + '/style.css';
	if(this.c.forceReloadSources){
		strSrc += '?rnd=' + this.divId;
	}
	delfiQuiz_addElementToHeader('style', strSrc);
	
	/* get question count */
	var qMainCount = this.pdata['questions'].length - 1;
	
	/**
	 * cycle trough every question in poll data 
	 * and get HTML parts out of them and join them all togheter
	 */
	htmlOut = this.renderHeader();
	
	if(this.showInlineThankYou){
		htmlOut += this.renderInlineThankYou(this.pdata['poll']['thanks_text']);		
	}
	
	//create question divs
	if(!this.showInlineThankYou && this.showInlineQuestions){
		var i = 0;
		for (i=0;i<=qMainCount;i++)
		{
			qId = this.pdata['questions'][i]['question_id'];
			var qKey = this.pdata['questions'][i]['qKey'];
			var tmpTotalVotes = 0;
			if (typeof(this.pdata['questions'][i]['result_serialized']) != 'undefined') {
				
				if (typeof(this.pdata['questions'][i]['result_serialized']['totalVotes']) != 'undefined') {
					tmpTotalVotes += this.pdata['questions'][i]['result_serialized']['totalVotes'];
				}
			
			}
			
			this.maxVotes = (this.maxVotes > tmpTotalVotes) ? this.maxVotes : tmpTotalVotes;
			
			var dName = this.divId + '_qplot_' + qKey;
			
			htmlOut += '<div id="' + dName + '">';			
			htmlOut += this.renderQuestionHeader(qId);
			htmlOut += this.renderQuestionFooter(i);			
			htmlOut += '</div>';
			
		}
	}
	htmlOut += this.renderQuizResultDiv();
	htmlOut += this.renderFooter();
	
	/* put HTML into prepared div */
	$("#" + this.divId).html(htmlOut);
	
	
	//render questions into their divs
	if(!this.showInlineThankYou && this.showInlineQuestions){
		var i = 0;
		for (i=0;i<=qMainCount;i++)
		{
			qId = this.pdata['questions'][i]['question_id'];
			this.hideQuestionByKey(i);
			this.renderQuestionByKey(i);
			
			/* and can we show it at inital view */
			if(this.pdata['questions'][i]['view_at_astart'] == 1){
				this.showQuestionByKey(i);
				this.pdata['questions'][i]['view'] = 1;
			}

		}
	}
	
	
	
	/**
	 * now render inline results also where needed
	 */
	var inPopup = this.pdata['poll']['answer_in_popup'];
	var allInline = true;
	for (i=0;i<=qMainCount;i++)
	{
		if(parseInt(this.pdata['questions'][i]['already_answered']) == 1 || this.pdata['poll_active'] == 0 || this.pdata['quizShowResults']){
			this.renderQuestionResult(this.pdata['questions'][i], 'inline');
		} else{
			 allInline = false;
		}
	}
	
	/* is some are inline, we have to show result button when having popup mode on */
	if(inPopup == 0 && allInline == true){
		$('#' + this.pdata['divId'] + '_both_buttons').css('display', 'none');				

	}

	/* create container for popup div data */
	var popupBufferDivId = this.getPopupResultBufferDivId();	
	$("#" + this.divId).append('<div id="' + popupBufferDivId + '_main" style="diplay: none"><div id="' + popupBufferDivId + ' class="main" ></div></div>');
	$("#" + popupBufferDivId + '_main').css('display', 'none');
	
	/**
	 * also prepare div-s for question parts into buffer div
	 */	 
	for (i=0;i<=qMainCount;i++)
	{
		$("#" + popupBufferDivId + '_main').append('<div id="' + this.getQuestionPopupAnswerDivId(i) + '"></div>');
	}
	
	/* also container for one another question */ 	
	$("#" + popupBufferDivId + '_main').append('<div id="' + this.getOtherQuestionsDivId() + '_question"></div>');	
	
	/* also quiz answer */ 	
	$("#" + popupBufferDivId + '_main').append('<div id="' + this.getQuizResultDivId() + '_popup"></div>');
	
	/* also container for another questions */ 	
	$("#" + popupBufferDivId + '_main').append('<div id="' + this.getOtherQuestionsDivId() + '"></div>');
	
	if(this.isQuizType && this.allQuestionsAnswered){
		this.preCalculateResultData();
		this.renderQuestionResultQuiz('inline');
	}
	
	return false;
}


delfiQuiz_templateBase.prototype.renderQuestionByKey = function(qKey) {
	var qId = this.pdata['questions'][qKey]['question_id'];
	var strQHtml = '';
	var qDivId = this.getQuestionDivId(qId);
	
	switch(parseInt(this.pdata['questions'][qKey]['type'])){
		case 1:
			strQHtml += this.renderQuestionType1(qKey);
		break
		case 2:
			strQHtml += this.renderQuestionType2(qKey);
		break
		case 3:
			strQHtml += this.renderQuestionType3(qKey);
		break
		case 4:
			strQHtml += this.renderQuestionType4(qKey);
		break
		case 5:
			strQHtml += this.renderQuestionType5(qKey);
		break
	}
	
	$('#' + qDivId).html(strQHtml);
}

delfiQuiz_templateBase.prototype.hideQuestionByKey = function(qKey) {
	var dName = this.divId + '_qplot_' + qKey;
	$('#' + dName).hide();
}

delfiQuiz_templateBase.prototype.showQuestionByKey = function(qKey) {
	var dName = this.divId + '_qplot_' + qKey;
	$('#' + dName).show();
	//this.addQuestionEvents(qKey);
}

/**
 * show thank you text
 */
delfiQuiz_templateBase.prototype.showThankYou = function(hideQuestions) {
	var hideQuestions = (hideQuestions == null) ? false : hideQuestions;
	
	/* hide questions */
	if(hideQuestions){
		var qCount = this.pdata['questions'].length - 1;	
		var i = 0;
		for (i=0;i<=qCount;i++)
		{	
			var divId = this.getQuestionDivId(this.pdata['questions'][i]['question_id']);
			$('#' + divId).css('display', 'none');
		}
	}

	var divName = this.divId + '_inline_thankyou';
	var divName2 = this.divId + '_both_buttons';
	$('#' + divName).html(this.renderInlineThankYou(this.pdata['poll']['thanks_text']));
	$('#' + divName2).css('display', 'none');
}


/**
 * this function renders inline results
 * for every question on poll
 */
delfiQuiz_templateBase.prototype.renderInlineResults = function() {
	this.preCalculateResultData();

	/* update inline answers count */
	$("#" + this.divId + '_answered_users').html(' ' + this.maxVotes);

	var qMainCount = this.pdata['questions'].length - 1;
	
	for (i=0;i<=qMainCount;i++)
	{
		this.renderQuestionResult(delfiQuiz_pollInstances[this.divId].pdata['questions'][i], 'inline');
	}
	
	$('#' + this.getFooterDivId()).css('diplay', 'none');
	
	if(this.isQuizType){
		this.renderQuestionResultQuiz('inline');
	}
}


/**
 * this function renders results for popup in hidden div 
 * later it w'll be grabbed into tightbox
 */
delfiQuiz_templateBase.prototype.renderPopupResults = function() {
	this.preCalculateResultData();
	
	/* update inline answers count */
	$("#" + this.divId + '_answered_users').html(' ' + this.maxVotes);

	/* hide another question */ 	
	$("#" +  this.getOtherQuestionsDivId() + '_question').css('display', 'none');	
	
	/* show quiz answer */ 	
	$("#" + this.getQuizResultDivId() + '_popup').css('display', '');
	
	var qMainCount = this.pdata['questions'].length - 1;
	for (i=0;i<=qMainCount;i++)
	{
		this.renderQuestionResult(this.pdata['questions'][i], 'popup');
	}
	
	if(this.pdata['is_group_poll'] == 1 && this.pdata['otherQuestions']['questions'].length > 0){
		this.renderOtherQuestions();
	}
	
	if(this.isQuizType){
		this.renderQuestionResultQuiz('popup');
	}
}


/**
 * calculate some data before rendering results
 */ 
delfiQuiz_templateBase.prototype.preCalculateResultData = function() {		
	/* calculate quiz points */
	var pointCnt = 0;
	var qCount = this.pdata['questions'].length - 1;
	var arrFrequency = Array();

	var i = 0;
	for (i=0;i<=qCount;i++)
	{		
		switch(parseInt(this.pdata['questions'][i]['type'])){
			case 1:
				/* quiz selection */
				if(this.pdata['questions'][i]['already_answered'] == 0){
					var optionName = this.divId + '_' + this.pdata['questions'][i]['question_id'];
					var answer = $("input[@name=" + optionName + "]:checked").val();
				} else {
					var answer = this.pdata['questions'][i]['already_answered_int_value'];
				}
				
				/* if there is no answer, it will be zero (there cant be zero point given answers, so its OK) 
				 * Its like zero is a answer too, but really its not. 
				 */
				if(typeof(answer) == 'undefined'){
					answer = 0;
				}

				/* get the points */
				var aCount = this.pdata['questions'][i]['answers'].length - 1;
				if(aCount > -1){
					var j = 0;
					for (j=0;j<=aCount;j++){
						
						if(this.pdata['questions'][i]['answers'][j]['question_answer_id'] == answer){
							var tmp = parseInt(this.pdata['questions'][i]['answers'][j]['quiz_points']);
							pointCnt += tmp;
							if(typeof(arrFrequency[tmp]) == 'undefined'){
								arrFrequency[tmp] = 1;
							} else {
								arrFrequency[tmp] += 1;
							}
						}
					}
				}
				
				if(answer == 0){
					tmp = 0;
					if(typeof(arrFrequency[tmp]) == 'undefined'){
						arrFrequency[tmp] = 1;
					} else {
						arrFrequency[tmp] += 1;
					}
				}
			break
		}
	}

	this.pdata['quizResultData'] = Array();
	this.pdata['quizResultData']['result_html'] = '';

	/* and get answer based on points count  */	
	if(this.pdata['poll']['quiz_type'] == 0){
		var qaCount = this.pdata['quiz_results'].length;
		var i = 0;
		for (i=0;i<=qaCount;i++){
			if(typeof(this.pdata['quiz_results'][i]) != 'undefined'){
				if(pointCnt >= this.pdata['quiz_results'][i]['from_points'] && pointCnt <= this.pdata['quiz_results'][i]['to_points']){
					this.pdata['quizResultData']['result_html'] = this.pdata['quiz_results'][i]['result_html'];
				}
			}
		}
	}

	/* and get answer based on frequency */	
	if(this.pdata['poll']['quiz_type'] == 1){	
		/* wich answer was most often choosed */		
		var mostFreq  = 0;
		var mostFreqAnswer  = 0;
		var multiSameFreq = false;
		var arrWithSame = new Array();
		
		var qaCount = arrFrequency.length;
		
		/*
	[1] => 2
	[2] => 1
	[3] => 1

		*/
		
		var i = 0;
		for(i=0;i<=qaCount;i++){
			if(arrFrequency[i] >= mostFreq){
				if(mostFreq == arrFrequency[i]){
					multiSameFreq = true;
				}
				mostFreq = arrFrequency[i];
				mostFreqAnswer = i;
			}
		}
				
		if(multiSameFreq){
			mostFreqAnswer = -1;
		}

		/* and find it */
		if(!multiSameFreq){
			var qaCount = this.pdata['quiz_results'].length;
			var i = 0;
			for (i=0;i<=qaCount;i++){
				if(typeof(this.pdata['quiz_results'][i]) != 'undefined'){
					if(mostFreqAnswer == this.pdata['quiz_results'][i]['frequency_points']){
						this.pdata['quizResultData']['result_html'] = this.pdata['quiz_results'][i]['result_html'];
					}
				}
			}
		} else {
			//mostFreq
			for(var x in arrFrequency){
				if(arrFrequency[x] == mostFreq && x != 0){
					var qaCount = this.pdata['quiz_results'].length;
					var i = 0;
					for (i=0;i<=qaCount;i++){
						if(typeof(this.pdata['quiz_results'][i]) != 'undefined'){
							if(x == this.pdata['quiz_results'][i]['frequency_points']){
								this.pdata['quizResultData']['result_html'] += '<br />' + this.pdata['quiz_results'][i]['result_html'];
							}
						}
					}
				}
			}
			
		}
		
		
		
	}
	
}


delfiQuiz_templateBase.prototype.round = function(tmpVar, commas) {
	tmpVar = tmpVar.toFixed(commas);
	return tmpVar;
}


/**
 * recalculate precalculated answer values with currently selectes vote
 */ 
delfiQuiz_templateBase.prototype.addCurrentAnswers = function(qKey) {
	var qType  = parseInt(this.pdata['questions'][qKey]['type']);
	var qResult  = parseInt(this.pdata['questions'][qKey]['result_type']);
	var totalVotes = 0;
	var answers = this.arrCurrentAnswers[this.pdata['questions'][qKey]['question_id']];
	
	//if no answers in select. no result data is given by server when no options are in select
	// so we dont have to calculate answers, because they dont exist
	if((qResult == 1 || qResult == 2) && typeof(this.pdata['questions'][qKey]['result_data']['answers']) == 'undefined'){
		return false;
	}
	
	/* get total vote count */
	if((qResult == 1 || qResult == 2) && typeof(this.pdata['questions'][qKey]['result_data']['answers']) != 'undefined'){
		var qCount = this.pdata['questions'][qKey]['result_data']['answers'].length - 1;
		var i = 0;
		for (i=0;i<=qCount;i++) {
			totalVotes += this.pdata['questions'][qKey]['result_data']['answers'][i]['count'];
		}
		totalVotes++;	
	}
	
	for(var aK2 in answers){
		answer = answers[aK2];
		
		switch(qResult) {
			case 1:
				/* diagram */		
				if(qType == 1 || qType == 2 || qType == 3 || qType == 4){
					for (i=0;i<=qCount;i++) {
						if(this.pdata['questions'][qKey]['result_data']['answers'][i]['answer_id'] == answer) {
							this.pdata['questions'][qKey]['result_data']['answers'][i]['count'] += 1;
						} 
						var tmpVar = this.pdata['questions'][qKey]['result_data']['answers'][i]['count'] * (100 / totalVotes);
						this.pdata['questions'][qKey]['result_data']['answers'][i]['percent'] = this.round(tmpVar, 1);
					}
				} 
			break; 
				
			case 2: 
				/* cake */
				if(qType == 1 || qType == 2 || qType == 3 || qType == 4){
					for (i=0;i<=qCount;i++) {
						if(this.pdata['questions'][qKey]['result_data']['answers'][i]['answer_id'] == answer) {
							this.pdata['questions'][qKey]['result_data']['answers'][i]['count'] += 1;
						} 
						var tmpVar = this.pdata['questions'][qKey]['result_data']['answers'][i]['count'] * (100 / totalVotes);
						this.pdata['questions'][qKey]['result_data']['answers'][i]['percent'] = this.round(tmpVar, 1);
					}
				} 
			break; 
				
			case 3: 
				/* average */
				var vcount = 0;
				
				if(qType == 3) {
					/* thumbs */		
					if(typeof(this.pdata['questions'][qKey]['result_serialized']) != 'undefined'){
						if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes']) != 'undefined'){
							
							if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes'][5]) != 'undefined'){
								vcount += this.pdata['questions'][qKey]['result_serialized']['votes'][5];
								totalVotes += this.pdata['questions'][qKey]['result_serialized']['votes'][5] * 5;
							}
													
							if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes'][0]) != 'undefined'){
								vcount += this.pdata['questions'][qKey]['result_serialized']['votes'][0];
							}
						}
					}
				}
				
				if(qType == 4) {
					/* stars */	
					if(typeof(this.pdata['questions'][qKey]['result_serialized']) != 'undefined'){
						if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes']) != 'undefined'){
							for (i=1;i<=5;i++) {
								if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes'][i]) != 'undefined'){
									totalVotes += parseInt(this.pdata['questions'][qKey]['result_serialized']['votes'][i]) * i;
									vcount += parseInt(this.pdata['questions'][qKey]['result_serialized']['votes'][i]);
									
								}							
							}
						}
					}
				}
				
			
				totalVotes += answer;
				vcount += 1;			
				tmpVar = totalVotes > 0 && vcount > 0 ? totalVotes / vcount : 0;
				this.pdata['questions'][qKey]['result_data']['average'] = this.round(tmpVar, 1);
			break; 
				
			case 4: 
				/* user answers */
				var aCnt = this.pdata['questions'][qKey]['result_data']['answers'].length;
				var tmpArr = Array();
				tmpArr['text_value'] = answer;
				
				/* lets push current answer to the first place */
				if(aCnt == 0){
					this.pdata['questions'][qKey]['result_data']['answers'][0] = tmpArr;
				} else {
					for (i=9;i>=0;i--) {
						if(i < 9 && typeof(this.pdata['questions'][qKey]['result_data']['answers'][i]) != 'undefined'){
							this.pdata['questions'][qKey]['result_data']['answers'][i + 1] = this.pdata['questions'][qKey]['result_data']['answers'][i];
						}
					}
					this.pdata['questions'][qKey]['result_data']['answers'][0] = tmpArr;
				}
			break; 
	
				
			case 6: 
				/* thumb percent */
					var up = 0;
					var down = 0;
					if(typeof(this.pdata['questions'][qKey]['result_serialized']) != 'undefined'){
						if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes']) != 'undefined'){
	
							if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes'][5]) != 'undefined'){
								up = this.pdata['questions'][qKey]['result_serialized']['votes'][5];
							}
							if(typeof(this.pdata['questions'][qKey]['result_serialized']['votes'][0]) != 'undefined'){
								down = this.pdata['questions'][qKey]['result_serialized']['votes'][0];
							}
						}
					}
	
										
					if(answer == 0){
						down = down + 1;
					} else {
						up = up + 1;						
					}
					
					var totalCntX = up + down;
					
					this.pdata['questions'][qKey]['result_data']['down_percent'] = down * (100 / totalCntX);
					this.pdata['questions'][qKey]['result_data']['up_percent'] = up * (100 / totalCntX);
					
					/* round up */
					this.pdata['questions'][qKey]['result_data']['down_percent'] = this.round(this.pdata['questions'][qKey]['result_data']['down_percent'], 1);
					this.pdata['questions'][qKey]['result_data']['up_percent'] = this.round(this.pdata['questions'][qKey]['result_data']['up_percent'], 1);
	
			break; 
		}
	}
	
}

/**
 * calculate all data needed and 
 * show result depens on question and result
 */
delfiQuiz_templateBase.prototype.renderQuestionResult = function(arrDataOut, where) {
	var qKey = arrDataOut['qKey'];	
	var popupBufferDivId = this.getPopupResultBufferDivId();	
	var resultType = parseInt(arrDataOut['result_type']);	
	var questionType = parseInt(arrDataOut['type']);	
	var resultHtml = '';
	
	/* if current user has voted, add current voting also in voting data 
		and make undefined so it will not be aadded once again later (onclick answers need this)
	*/
	if(typeof(delfiQuiz_pollInstances[this.divId].arrCurrentAnswers[arrDataOut['question_id']]) != 'undefined'){
		this.addCurrentAnswers(qKey);
		delfiQuiz_pollInstances[this.divId].arrCurrentAnswers[arrDataOut['question_id']] = undefined;
	}
	
	/* update embed data to results also */
	if(typeof(this.pdata['questions'][qKey]) != 'undefined' && typeof(this.pdata['questions'][qKey]['answers']) != 'undefined'){
		var aCount = this.pdata['questions'][qKey]['answers'].length - 1;
		if(aCount > -1){
			var j = 0;
			for (j=0;j<=aCount;j++){
				if(typeof(this.pdata['questions'][qKey]['answers'][j]['embed_data']) != 'undefined'){
					var eACount = this.pdata['questions'][qKey]['answers'][j]['embed_data'].length - 1;
					var k = 0;
					for (k=0;k<=eACount;k++){
						var tmpEData = this.pdata['questions'][qKey]['answers'][j]['embed_data'][k];
						this.pdata['questions'][qKey]['answers'][j]['embed_data'][k]['delfiVideoX'] = tmpEData['delfiVideoX'];
						this.pdata['questions'][qKey]['answers'][j]['embed_data'][k]['delfiVideoY'] = tmpEData['delfiVideoY'];			
						this.pdata['questions'][qKey]['answers'][j]['embed_data'][k]['width'] = tmpEData['width'];
						this.pdata['questions'][qKey]['answers'][j]['embed_data'][k]['height'] = tmpEData['height'];			
						this.pdata['questions'][qKey]['answers'][j]['embed_data'][k]['divId'] = this.divId;						
						this.pdata['questions'][qKey]['result_data']['answers'][j]['embed_data'][k]['qKey'] = qKey;			
						this.pdata['questions'][qKey]['result_data']['answers'][j]['embed_data'][k]['aKey'] = j;
						
						//delfiQuiz_pollInstances[this.divId].pdata['questions'][i]['result_data'][j]['answers'][k]['embed_data'][m]['aKey'] = k;
					}
				}
			}
		}
	}
	

	/* format dots to commas */
	if(typeof(this.pdata['questions'][qKey]) != 'undefined'){
		if(typeof(this.pdata['questions'][qKey]['result_data']['answers']) != 'undefined' && this.pdata['questions'][qKey]['type'] != 5){
			var eACount = this.pdata['questions'][qKey]['result_data']['answers'].length - 1;
			var k = 0;
			for (k=0;k<=eACount;k++){
				if(typeof(this.pdata['questions'][qKey]['result_data']['answers'][k]['percent']) != 'undefined'){
					var tempStr =  this.pdata['questions'][qKey]['result_data']['answers'][k]['percent'] + '';
					this.pdata['questions'][qKey]['result_data']['answers'][k]['percent'] = tempStr.replace(/\./g, ',');
				}
			}
		}
		
		if(typeof(this.pdata['questions'][qKey]['result_data']['average']) != 'undefined'){
			var tempStr =  this.pdata['questions'][qKey]['result_data']['average'] + '';
			this.pdata['questions'][qKey]['result_data']['average'] = tempStr.replace(/\./g, ',');
		}
		if(typeof(this.pdata['questions'][qKey]['result_data']['up_percent']) != 'undefined'){
			var tempStr =  this.pdata['questions'][qKey]['result_data']['up_percent'] + '';
			this.pdata['questions'][qKey]['result_data']['up_percent'] = tempStr.replace(/\./g, ',');
		}
		if(typeof(this.pdata['questions'][qKey]['result_data']['down_percent']) != 'undefined'){
			var tempStr =  this.pdata['questions'][qKey]['result_data']['down_percent'] + '';
			this.pdata['questions'][qKey]['result_data']['down_percent'] = tempStr.replace(/\./g, ',');
		}
	}
	/* get result HTML based on type */
	switch(resultType){
		/* diagram */
		case 1:
			resultHtml += this.renderQuestionResult1(arrDataOut, where);
		break

		/* pie */
		case 2:
			resultHtml += this.renderQuestionResult2(arrDataOut, where);
		break
		
		/* average */
		case 3:			
			resultHtml += this.renderQuestionResult3(arrDataOut, where);
		break

		/* answers */
		case 4:			
			resultHtml += this.renderQuestionResult4(arrDataOut, where);
		break
		
		/* no results */
		case 5:
			/* hide question also in inline */
			if(where == 'inline'){
				if(arrDataOut['type'] == 3 || arrDataOut['type'] == 4){
					//var inlineResultsDivId = this.getQuestionInlineAnswerDivId(i);
					var tmpDivId = this.getQuestionInlineAnswerDivId(arrDataOut['qKey']);
					$('#' + tmpDivId).html('');
				} else {
					var tmpDivId = this.getQuestionDivId(arrDataOut['question_id']);
					$('#' + tmpDivId).html('');
				}
			}
			resultHtml += this.renderQuestionResult5(arrDataOut, where);
		break
		

		/* thumb percent */
		case 6:			
			resultHtml += this.renderQuestionResult6(arrDataOut, where);
		break
	}
	
	/* We have result HTML, but what to do with it */
	if(where == 'inline'){
		var qAnswerdivId = this.getQuestionInlineAnswerDivId(arrDataOut['qKey']);
		$('#' + qAnswerdivId).html(resultHtml);
	} else if(where == 'popup') {
		var qPopupDivId = this.getQuestionPopupAnswerDivId(qKey);
		$("#" + qPopupDivId).css('display', '');
		$('#' + qPopupDivId).html(resultHtml);	
	} else {
		return resultHtml;
	}
}


/**
 * generates Div id for DIV element 
 * wich is wrapped around one question  
 * @param qId int is question id
 */ 
delfiQuiz_templateBase.prototype.getQuestionDivId = function(qId) {
	var strReturn = this.divId + '_' + this.pollId + '_qId_' + qId;
	return strReturn;
}


/**
 * generates Div id for DIV element 
 * wich is wrapper for inline question answer  
 * @param qKey int is key in questions array  
 */ 
delfiQuiz_templateBase.prototype.getQuestionInlineAnswerDivId = function(qKey) {
	var strReturn = this.divId + '_' + this.pollId + '_questionKey_' + qKey + '_inLineAnswer';
	return strReturn;
}


/**
 * generates Div id for DIV element 
 * wich is wrapper for popup question answer  
 * @param qKey int is key in questions array  
 */ 
delfiQuiz_templateBase.prototype.getQuestionPopupAnswerDivId = function(qKey) {
	var strReturn = this.divId + '_' + this.pollId + '_questionKey_' + qKey + '_popupAnswer';
	return strReturn;
}


/**
 * generates Div id for DIV element 
 * where popup result is stored before
 * rendered in popup  
 */ 
delfiQuiz_templateBase.prototype.getPopupResultBufferDivId = function() {
	var strReturn = this.divId + '_' + this.pollId + '_popup_buffer';
	return strReturn;
}


/**
 * generates Div id for DIV element 
 * where popup result is stored before
 * rendered in popup  
 */ 
delfiQuiz_templateBase.prototype.getPopupResultBufferDivId = function() {
	var strReturn = this.divId + '_' + this.pollId + '_popup_buffer';
	return strReturn;
}


/**
 * generates ID for thumbs and stars 
 * real ID is constructed where this is needed first place
 */ 
delfiQuiz_templateBase.prototype.getAnswerItemBaseId = function(qKey) {
	var strReturn = this.divId + '_' + this.pollId + '_' + qKey + '_item';
	return strReturn;
}


/**
 * footer div ID .. where result and vote buttons are 
 */ 
delfiQuiz_templateBase.prototype.getFooterDivId = function() {
	var strReturn = this.divId + '_footer';
	return strReturn;
}


/**
 * div where other questoions w'll be diplayed
 */ 
delfiQuiz_templateBase.prototype.getOtherQuestionsDivId = function() {
	var strReturn = this.divId + '_oQuestions';
	return strReturn;
}


/**
 * quiz result (based on points) div ID base .. this is where that result is placed  
 */ 
delfiQuiz_templateBase.prototype.getQuizResultDivId = function() {
	var strReturn = this.divId + '_quizAnswer';
	return strReturn;
}


/**
 * checks for is all questions answered. 
 * And if is, show inline thank you text when needed
 */ 
delfiQuiz_templateBase.prototype.checkIsAllQuestionsAnswered = function() {
	var qCount = this.pdata['questions'].length - 1;
	var boolAllAnswered = true;
	
	var i = 0;
	for (i=0;i<=qCount;i++)
	{	
		if(parseInt(this.pdata['questions'][i]['no_refresh_answered']) == 0){
			boolAllAnswered = false;
		}
	}

	if(boolAllAnswered && this.allQuestionsNoResult){
		this.showThankYou(true);
	}
}


/**
//  * add vote button onclick event and result buttons also 
 */ 
delfiQuiz_templateBase.prototype.addEvents = function() {
	var popupBufferDivName = this.getPopupResultBufferDivId();
	var divIdTmp = this.divId;
	
	var that = this;
	
	/* setup vote button event */
	$('#' + this.divId + '_vote').click(function() {
		/* gather answers and form a nice array out of them */
		var arrAnswers = Array();
		var arrKeyVsQid = Array();
		var qCount = that.pdata['questions'].length - 1;
		var boolAllAnswered = true;
		var nextChain = false;
		
		var i = 0;
		for (i=0;i<=qCount;i++)
		{
			if(that.pdata['questions'][i]['view'] == 1){
				
				/* is this question already answered, and page is not refreshed yet */
				var refAnswerCheck = parseInt(that.pdata['questions'][i]['no_refresh_answered']);
				
				arrKeyVsQid[parseInt(that.pdata['questions'][i]['question_id'])] = i;
				
				var boolMultiAnser = that.pdata['questions'][i]['multianswer'] == 1 ? true : false;
				
				if(typeof(that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']]) == 'undefined'){
					that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']] = new Array();
				}
				
				switch(parseInt(that.pdata['questions'][i]['type'])){
					case 1:
						/* quiz selection */
						var optionName = that.divId + '_' + that.pdata['questions'][i]['question_id'];
						var answer = $("input[@name=" + optionName + "]:checked").val();
						if(answer == null){
							answer = 0;
						}
	
						if(answer == 0 && that.pdata['questions'][i]['obligatory_answer'] == 1){
							boolAllAnswered = false;
						} else {
							if(refAnswerCheck == 0){
								if(typeof(arrAnswers[that.pdata['questions'][i]['question_id']]) == 'undefined'){
									arrAnswers[that.pdata['questions'][i]['question_id']] = new Array();
								}
								arrAnswers[that.pdata['questions'][i]['question_id']][arrAnswers[that.pdata['questions'][i]['question_id']].length] = answer;

								that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']][that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
								that.arrCurrentAnswersCheck[that.pdata['questions'][i]['question_id']] = answer;
							}
						}
					break
					case 2:
						/* selection */
						if(boolMultiAnser){
							var cntTVotes = 0;
							//gather multi answers
							var boolOneAnswered = false;
							if(typeof(that.pdata['questions'][i]['answers']) != 'undefined' && that.pdata['questions'][i]['answers'].length > 0){
								for (var ak in that.pdata['questions'][i]['answers']) {
									var chackName = that.divId + '_' + that.pdata['questions'][i]['question_id'] + '_' + that.pdata['questions'][i]['answers'][ak]['question_answer_id'];
									var answer = $("input[@name=" + chackName + "]:checked").val();
									if(answer == null){
										answer = 0;
									}
									
									if(answer > 0){
										boolOneAnswered = true;
										if(typeof(arrAnswers[that.pdata['questions'][i]['question_id']]) == 'undefined'){
											arrAnswers[that.pdata['questions'][i]['question_id']] = new Array();
										}
										arrAnswers[that.pdata['questions'][i]['question_id']][arrAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
										that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']][that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
										cntTVotes++;
									}
									
								}
							}
							
							if(!boolOneAnswered && that.pdata['questions'][i]['obligatory_answer'] == 1){
								boolAllAnswered = false;
							} else {
								if(refAnswerCheck == 0){									
									that.arrCurrentAnswersCheck[that.pdata['questions'][i]['question_id']] = answer;
								}
							}
							
							that.intMaxVotesAdd = cntTVotes;
						} else {
							//usual radio button answer
							var optionName = that.divId + '_' + that.pdata['questions'][i]['question_id'];
							var answer = $("input[@name=" + optionName + "]:checked").val();
							if(answer == null){
								answer = 0;
							}
							
							if(answer == 0 && that.pdata['questions'][i]['obligatory_answer'] == 1){
								boolAllAnswered = false;
							} else {
								if(refAnswerCheck == 0){
									if(typeof(arrAnswers[that.pdata['questions'][i]['question_id']]) == 'undefined'){
										arrAnswers[that.pdata['questions'][i]['question_id']] = new Array();
									}
									arrAnswers[that.pdata['questions'][i]['question_id']][arrAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
									that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']][that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
									that.arrCurrentAnswersCheck[that.pdata['questions'][i]['question_id']] = answer;
								}
							}
							//
						}
					break
					case 3:
						/* thumb up n down type will be sent onclick event */
						if(that.pdata['questions'][i]['obligatory_answer'] == 1 && typeof(that.arrCurrentAnswersCheck[that.pdata['questions'][i]['question_id']]) == 'undefined'){
							boolAllAnswered = false;
						}
					break
					case 4:
						/*5 stars will be sent onclick */
						if(that.pdata['questions'][i]['obligatory_answer'] == 1 && typeof(that.arrCurrentAnswersCheck[that.pdata['questions'][i]['question_id']]) == 'undefined'){
							boolAllAnswered = false;
						}
					break
					case 5:
						/* user answer */
						var fieldId = that.getAnswerItemBaseId(i) + '_usertext';
						var answer = $("#" + fieldId).val();
						
						if(answer == '' && that.pdata['questions'][i]['obligatory_answer'] == 1){
							boolAllAnswered = false;
						} else {
							if(refAnswerCheck == 0){
								if(typeof(arrAnswers[that.pdata['questions'][i]['question_id']]) == 'undefined'){
									arrAnswers[that.pdata['questions'][i]['question_id']] = new Array();
								}
								arrAnswers[that.pdata['questions'][i]['question_id']][arrAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
								that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']][that.arrCurrentAnswers[that.pdata['questions'][i]['question_id']].length] = answer;
								that.arrCurrentAnswersCheck[that.pdata['questions'][i]['question_id']] = answer;
							}
						}
					break
				}
				
				
			}
		}
		
		if(boolAllAnswered){
			
			if(that.hasChainedQuestions){
				//is here a chained question in currently answered and shown questions
				var arrNewActive = new Array();
				var isChainedPresent = false;
				var f = 0;
				for (f=0;f<=qCount;f++) {
					if(that.pdata['questions'][f]['view'] == 1){
						that.pdata['questions'][f]['view'] = 0;
						that.hideQuestionByKey(f);
						
						
						var cAnswer = typeof(that.arrCurrentAnswersCheck[that.pdata['questions'][f]['question_id']]) != 'undefined' ? that.arrCurrentAnswersCheck[that.pdata['questions'][f]['question_id']] : false;
						
						if(that.pdata['questions'][f]['type'] != 3 && that.pdata['questions'][f]['type'] != 4){
							cAnswer = parseInt(cAnswer);
						}
						
						var tmpC = that.checkForChain(that.pdata['questions'][f]['question_id'], cAnswer);
						
						if(tmpC !== false){
							isChainedPresent = true;
							var qK = that.getQuestionKeyById(tmpC);
							that.showQuestionByKey(qK);
							arrNewActive[qK] = qK;
						}
					}
				}
				
				for (var h in arrNewActive) {					
					that.pdata['questions'][h]['view'] = 1;
					delete that.arrCurrentAnswers[that.pdata['questions'][h]['question_id']];
					delete that.arrCurrentAnswersCheck[that.pdata['questions'][h]['question_id']];
					that.pdata['questions'][h]['no_refresh_answered'] = 0;
					nextChain = true;
				}
			}
			
			//do this only when no new questions are shown
			if(!nextChain){
				//do the rest
				$('#' + that.pdata['divId'] + '_vote').css('display', 'none');
				if(that.pdata['poll']['answer_in_popup'] != 1){
					$('#' + that.pdata['divId'] + '_results').css('display', 'none');			
					$('#' + that.pdata['divId'] + '_both_buttons').css('display', 'none');	
				}
				
				if(that.pdata['poll']['show_results_button'] == 0){
					$('#' + that.pdata['divId'] + '_both_buttons').css('display', 'none');
				}
				
				if(that.allQuestionsNoResult && that.isQuizType == false){
					that.showThankYou();
				}
			}
			
			
			/* send answers to server */	
			var strData = '';
			for (var i in arrAnswers )
			{
				for (var i2 in arrAnswers[i] ){
					strData = strData  + '&answers[' + i + '][]=' + arrAnswers[i][i2];
				}
				that.pdata['questions'][arrKeyVsQid[i]]['no_refresh_answered'] = 1;
			}
			
			strData += '&pollId=' + that.pollId;	
			strData += '&divId=' + that.pdata['divId'];
			
			$.ajax({
				url: that.c.pollVoteUrl,
				data: strData,
				type: "GET",
				dataType: "script"
			});


			if(!isChainedPresent){
				/* show results */
				that.maxVotes += that.intMaxVotesAdd;
				
				
				if(!nextChain){
					/* if redirect page set, instead of showing result - redirect to that page */
					if(that.pdata['quizRedirectURL'] != ''){
						document.location.href = that.pdata['quizRedirectURL'];
						return;
					}
					
					if(that.pdata['poll']['answer_in_popup'] == 1){
						var href = '#TB_inline?height=480&;width=640&inlineId=' + popupBufferDivName + '_main';
						
						delfiQuiz_pollInstances[divIdTmp].renderPopupResults();
						var t = "";
						var a = href;
						var g = "";
						tb_show(t,a,g);
						this.blur();
					} else {
						delfiQuiz_pollInstances[divIdTmp].renderInlineResults();
						document.location = document.location.href + '#a_' + that.pdata['divId'];
					}
				}
			}
		} else {
			alert(delfiQuiz_translate('answerAllQuestions', that.pdata['language']));
		}
		
		that.checkIsAllQuestionsAnswered();
		return false;
	});
	
	/* setup results button */
	if(this.pdata['poll']['show_results_button'] == 1){
		btnName = '#' + this.pdata['divId'] + '_results';

		/* show results */
		if(this.pdata['poll']['answer_in_popup'] == 1){
			$(btnName).click(function() {
				/* if redirect page set, instead of showing result - redirect to that page */
				if(that.pdata['quizRedirectURL'] != ''){
					document.location.href = that.pdata['quizRedirectURL'];
					return;
				}
				delfiQuiz_pollInstances[divIdTmp].renderPopupResults();
				var t = this.title || this.name || null;
				var a = this.href || this.alt;
				var g = this.rel || false;
				tb_show(t,a,g);
				this.blur();
				return false;
			});		 	 
		} else {			
			$(btnName).click(function() {
				/* if redirect page set, instead of showing result - redirect to that page */
				if(that.pdata['quizRedirectURL'] != ''){
					document.location.href = that.pdata['quizRedirectURL'];
					return;
				}
				$('#' + that.pdata['divId'] + '_both_buttons').css('display', 'none');
				$('#' + that.pdata['divId'] + '_vote').css('display', 'none');
				$('#' + that.pdata['divId'] + '_results').css('display', 'none');
				delfiQuiz_pollInstances[divIdTmp].renderInlineResults();
				document.location.href = document.location.href + '#a_' + that.pdata['divId'] ;
				return false;
			});
		}
	}
	
	
	/* add some other events needed for poll */
	var qCount = this.pdata['questions'].length - 1;
	
	var i = 0;
	for (i=0;i<=qCount;i++)
	{
		this.addQuestionEvents(i);
	}
	
	
}

//add event by question key
delfiQuiz_templateBase.prototype.addQuestionEvents = function(qKey){
	switch(parseInt(this.pdata['questions'][qKey]['type'])){
		case 1:
			/* quiz */
		break
		case 2:
			/* selection */
		break
		case 3:
			/* this is thumb up n down type */
			this.thumbHelper(qKey);
		break
		case 4:
			/* five stars type */
			var j = 0;
			for (j=1;j<=5;j++)
			{
				this.fiveStarHelper(qKey, j);
			}
		break
		case 5:
			/* free text */
		break
	}
}


delfiQuiz_templateBase.prototype.getQuestionKeyById = function(qId){
	var qCount = this.pdata['questions'].length - 1;
	var h = 0;
	for (h=0;h<=qCount;h++) {
		if(this.pdata['questions'][h]['question_id'] == qId){
			return h;
		}
	}
	
	return false;
}

delfiQuiz_templateBase.prototype.thumbHelper = function(qKey){
	var baseId = this.getAnswerItemBaseId(qKey);
	var qid = this.pdata['questions'][qKey]['question_id'];
	
	$('#' + baseId + '_up').css('cursor', 'pointer');
	$('#' + baseId + '_down').css('cursor', 'pointer');
	
	var that = this;
	
	$('#' + baseId + '_up').click(function() {
		$.ajax({
			url: that.c.pollVoteUrl + '?pollId=' + parseInt(that.pollId) + '&answers[' + qid + '][]=5' + '&divId=' + that.pdata['divId'],
			type: "GET",
			dataType: "script"
		});
		
		if(typeof(delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']]) == 'undefined'){
			delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']] = new Array();
		}
		var tLen = delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']].length;
		
		delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']][tLen] = 5;
		delfiQuiz_pollInstances[that.divId].arrCurrentAnswersCheck[that.pdata['questions'][qKey]['question_id']] = 5;		
		that.pdata['questions'][qKey]['no_refresh_answered'] = 1;
		
		
		//is here a chained question in currently answered and shown questions
		/*
		var tmpC = that.checkForChain(that.pdata['questions'][qKey]['question_id'], 5);
		if(tmpC !== false){
			var qK = that.getQuestionKeyById(tmpC);
			that.showQuestionByKey(that.pdata['questions'][qK]['qKey']);
			that.pdata['questions'][that.pdata['questions'][qK]['qKey']]['view'] = 1;
			that.hideQuestionByKey(qKey);
			that.pdata['questions'][qKey]['view'] = 0;
		}
		*/
		
		that.renderQuestionResult(that.pdata['questions'][qKey], 'inline');
		that.checkIsAllQuestionsAnswered();
	});
	
	$('#' + baseId + '_down').click(function() {
		$.ajax({
			url: that.c.pollVoteUrl + '?pollId=' + parseInt(that.pollId) + '&answers[' + qid + '][]=0' + '&divId=' + that.pdata['divId'],
			type: "GET",
			dataType: "script"
		});
		
		if(typeof(delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']]) == 'undefined'){
			delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']] = new Array();
		}
		var tLen = delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']].length;
		
		delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']][tLen] = 0;
		delfiQuiz_pollInstances[that.divId].arrCurrentAnswersCheck[that.pdata['questions'][qKey]['question_id']] = 0;		
		that.pdata['questions'][qKey]['no_refresh_answered'] = 1;
		
		
		//is here a chained question in currently answered and shown questions
		/*
		var tmpC = that.checkForChain(that.pdata['questions'][qKey]['question_id'], 0);
		if(tmpC !== false){
			var qK = that.getQuestionKeyById(tmpC);
			that.showQuestionByKey(that.pdata['questions'][qK]['qKey']);
			that.pdata['questions'][that.pdata['questions'][qK]['qKey']]['view'] = 1;
			that.hideQuestionByKey(qKey);
			that.pdata['questions'][qKey]['view'] = 0;
		}
		*/
		
		
		that.renderQuestionResult(that.pdata['questions'][qKey], 'inline');
		that.checkIsAllQuestionsAnswered();
	});
}


/**
 * setup events for this star
 */
delfiQuiz_templateBase.prototype.fiveStarHelper = function(qKey, starId){
	var qid = this.pdata['questions'][qKey]['question_id'];	
	var baseId = this.getAnswerItemBaseId(qKey);
	
	var that = this;
		
	$('#' + baseId + '_' + starId).css('cursor', 'pointer');
	$('#' + baseId + '_' + starId).click(function() {
		$.ajax({
			url: that.c.pollVoteUrl + '?pollId=' + parseInt(that.pollId) + '&answers[' + qid + '][]=' + starId + '&divId=' + that.pdata['divId'],
			type: "GET",
			dataType: "script"
		});
		
		if(typeof(delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']]) == 'undefined'){
			delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']] = new Array();
		}
		var tLen = delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']].length;
		
		
		delfiQuiz_pollInstances[that.divId].arrCurrentAnswers[that.pdata['questions'][qKey]['question_id']][tLen] = starId;
		delfiQuiz_pollInstances[that.divId].arrCurrentAnswersCheck[that.pdata['questions'][qKey]['question_id']] = starId;
		that.pdata['questions'][qKey]['no_refresh_answered'] = 1;
		
		
		//is here a chained question in currently answered and shown questions
		/*
		var tmpC = that.checkForChain(that.pdata['questions'][qKey]['question_id'], starId);
		if(tmpC !== false){			
			var qK = that.getQuestionKeyById(tmpC);
			that.showQuestionByKey(that.pdata['questions'][qK]['qKey']);
			that.pdata['questions'][that.pdata['questions'][qK]['qKey']]['view'] = 1;
			that.hideQuestionByKey(qKey);
			that.pdata['questions'][qKey]['view'] = 0;
		}
		*/
		
		that.renderQuestionResult(that.pdata['questions'][qKey], 'inline');		
		that.checkIsAllQuestionsAnswered();
	});
	
	$('#' + baseId + '_' + starId).mouseover(function() {		
		var i2 = 0;
		for (i2=1;i2<=5;i2++)
		{
			if(i2 <= starId){				
				that.fiveStarHighLightHelper(qKey, i2, 'y');
			} else {
				that.fiveStarHighLightHelper(qKey, i2, 'n');
			}
				
		}
	});	
	
	$('#' + baseId + '_' + starId).mouseout(function() {
		var i2 = 0;
		for (i2=1;i2<=5;i2++)
		{
				that.fiveStarHighLightHelper(qKey, i2, 'n');				
		}
	});	
}


/**
 * is this star highlighted or not
 */
delfiQuiz_templateBase.prototype.fiveStarHighLightHelper = function(qKey, starId, dowhat){	
	var strImgBase = this.c.templatesBaseUrl + '/' + this.template;
	var baseId = this.getAnswerItemBaseId(qKey);
	
	if(dowhat == 'y'){
		$('#' + baseId + '_' + starId).attr('src', strImgBase + '/star.gif');		
	} else {
		$('#' + baseId + '_' + starId).attr('src', strImgBase + '/blankstar.gif');
	}
}





/**
 * these are so called helpers.. for embed content
 */ 
delfiQuiz_templateBase.prototype.getEmbedHtmlGlobal_video = function(data) {
	var aKey = typeof(data['aKey']) != 'undefined' ? data['aKey'] : 0;
	var _delfiVideoSalt = data['data'];	
	var _delfiVideoDivId = data['divId'] + data['qKey'] + aKey + data['data'];
	var _delfiVideoX = (typeof(data['delfiVideoX']) != 'undefined') ? data['delfiVideoX'] : this.defaultWidth;
	var _delfiVideoY = (typeof(data['delfiVideoY']) != 'undefined') ? data['delfiVideoY'] : this.defaultHeight;
	
	var s1 = new SWFObject(this.c.embedVideoMediaPlayerUrl,"mpl", _delfiVideoX, _delfiVideoY,7);
	s1.addParam("allowscriptaccess","always");
	s1.addParam("allowfullscreen","true"); 
	s1.addVariable("file", this.c.embedVideoFileUrl + '/'+_delfiVideoSalt+'.flv');
	s1.addVariable("image", this.c.embedVideoThumbUrl + '/'+_delfiVideoSalt+'.jpg');
	s1.addVariable("recommendations", this.c.embedVideoRelatedUrl + '/'+_delfiVideoSalt+'/?xml=1');
	s1.addVariable("repeat","list");
	s1.addVariable("shuffle","false");
	s1.addVariable("linkfromdisplay","true");
	s1.addVariable("linktarget","_self");
	s1.addVariable("javascriptid","delfivideo");
	s1.addVariable("enablejs","true");
	s1.addVariable("shownavigation","true");
	s1.addVariable("callback","analytics");
	s1.addVariable("lightcolor","0xF2C201");
	s1.addVariable("frontcolor","0x666666");
	s1.addVariable("backcolor","0xFFFFFF");
	s1.addVariable("width",_delfiVideoX);
	s1.addVariable("height",_delfiVideoY);
	s1.addVariable("autostart","false");
	s1.addParam("allowscriptaccess","always");
	s1.addParam("allowfullscreen","true");

	// setup timer to inject the player html
	var timer = setInterval(function() {
		if (document.getElementById(_delfiVideoDivId)) {
			s1.write(_delfiVideoDivId);
			clearInterval(timer);
		}
	}, 300);

	var strOut = "<div id=\""+ _delfiVideoDivId + "\"><a href=\"http://www.macromedia.com/go/getflashplayer\">Get the Flash Player</a> to see this player.</div>";
	this.embedData = strOut;
}

delfiQuiz_templateBase.prototype.getEmbedHtmlGlobal_picture = function(data) {
	var _width = (typeof(data['width']) != 'undefined') ? data['width'] : this.defaultWidth;
	//var imgId = 'picUrl_' + data['qKey'] +' _' + data['aKey'];
	
	/* add max width style based on browser version */
	var styleString = 'max-width: ' + _width + 'px;';
	if(jQuery.browser.msie && jQuery.browser.version < 8){
		styleString = "width: " + _width + "px;";
	} 
	
	this.embedData += '<img src="' + c.pollEmbedPictureBase + '/' + data['data'] +'&width=' + _width + '&height=1000' + '" border="0" alt="" class="left_pic2" style="' + styleString + '" />';
}

delfiQuiz_templateBase.prototype.getEmbedHtmlGlobal_pictureurl = function(data) {
	var _width = (typeof(data['width']) != 'undefined') ? data['width'] : this.defaultWidth;
	//var imgId = 'picUrl_' + data['qKey'] +' _' + data['aKey'];
	
	/* add max width style based on browser version */
	var styleString = 'max-width: ' + _width + 'px;';
	if(jQuery.browser.msie && jQuery.browser.version < 8){
		styleString = "width: " + _width + "px;";
	} 
	
	this.embedData += '<img src="' + data['data'] + '" border="0" alt="" class="left_pic2" style="' + styleString + '" />';
}

delfiQuiz_templateBase.prototype.returnEmbedData = function() {
	return this.embedData;
}


/**
 * Result chart helper.. it loads given question chart into given div 
 */ 
delfiQuiz_templateBase.prototype.loadChartIntoElement = function(qId, contentDivId, w, h) {
	var w = (w == null) ? '100%' : w;
	var h = (h == null) ? '100%' : h;
	
	if(this.c.forceReloadSources){
		var urlPart = this.divId;
	} else {
		var urlPart = '1';
	}
	
	var so = new SWFObject(this.c.baseUrl + "/graph/quiz.swf", "ampie", w, h, "8", "#FFFFFF");
	so.addVariable("path", this.c.baseUrl + "/graph/");
	so.addVariable("settings_file", escape(this.c.baseUrl + "/graph/dquiz_settings.xml?ts=" + urlPart));
	so.addVariable("data_file", escape(this.c.baseUrl + "/graph/amcolumn_data.php?ts=" + urlPart + "&question_id=" + qId));
	so.addParam("scale", "noscale");
	so.addParam("salign", "lt");
	so.addVariable("chart_type", "column");
	so.addVariable("preloader_color", "#999999");
	so.addParam("wmode", "transparent");
	so.write(contentDivId);
}


/**
 * Result pie helper.. it loads given question chart into given div 
 */ 
delfiQuiz_templateBase.prototype.loadPieIntoElement = function(qId, contentDivId, w, h) {
	var w = (w == null) ? '100%' : w;
	var h = (h == null) ? '100%' : h;
	
	if(this.c.forceReloadSources){
		var urlPart = this.divId;
	} else {
		var urlPart = '1';
	}
	
	var so = new SWFObject(this.c.baseUrl + "/graph/quiz.swf", "ampie", w, h, "8", "#FFFFFF");
	so.addVariable("path", this.c.baseUrl + "/graph/");
	so.addVariable("settings_file", escape(this.c.baseUrl + "/graph/dquiz_settings.xml?ts=" + urlPart));
	so.addVariable("data_file", escape(this.c.baseUrl + "/graph/amcolumn_data.php?ts=" + urlPart + "&question_id=" + qId));
	so.addParam("scale", "noscale");
	so.addParam("salign", "lt");
	so.addVariable("chart_type", "pie");
	so.addVariable("preloader_color", "#999999");
	so.addParam("wmode", "transparent");
	so.write(contentDivId);
}
/**
 * This is function returns appropriate translation
 */ 
function delfiQuiz_translate(word, lang) {
	var c = new delfiQuiz_config();
	var lang = typeof(lang) != 'undefined' ? lang : c.defaultLanguage;
	var out = '';
	
	if(typeof(delfiQuiz_languages[lang]) != 'undefined'){
		if(typeof(delfiQuiz_languages[lang][word]) != 'undefined'){
			out = delfiQuiz_languages[lang][word];
		}
	}
	
	/**
	 * Some languages need to be converted to HTML entities to work
	 * If there will be more languages maybe we should just convert them all, so there would be no problem
	
	var langPart = lang.substring(0, 2);
	if(langPart == 'ru'){
		out = delfiQuiz_convertUtf8ToHtmlEntity(out);
	}
	 */	
	return out;
}

/*

function delfiQuiz_convertUtf8ToHtmlEntity(strUtf8Text) {
		
	String.prototype.delfiQuiz_trim = function () {
		return this.replace(/^\s+|\s+$/g, '');
	}

	var strHtmlEntity = '';
	
	strUtf8Text = strUtf8Text.delfiQuiz_trim();		
	
	for(i=0; i<=strUtf8Text.length; i++) {
		if(strUtf8Text.charCodeAt(i)>127){ //Higher than 127 w'll be processed
			strHtmlEntity += '&#' + strUtf8Text.charCodeAt(i) + ';';
		}	else {
			strHtmlEntity += strUtf8Text.charAt(i);//output the unprocessed charactor
		}
	}
	alert(strUtf8Text+  "\n\r"+strHtmlEntity);
	return strHtmlEntity;
}
*/
if(typeof(delfiQuiz_languages) == 'undefined'){
	delfiQuiz_languages = new Array();
}
delfiQuiz_languages['en_US'] = {
	'comments': 'Comments', 
	'btn_vote_default': 'Vote', 
	'btn_results_default': 'Results', 
	'noSuchPoll': 'Requested poll does not exist', 
	'rating': 'Rating', 
	'usersvoted': 'Answers', 
	'tb_or_esc_key': 'or Esc Key', 
	'tb_close': 'Close', 
	'pollNotActive': 'Requested poll is not active', 
	'olderQuestions': 'Older questions', 
	'questionsArchive': 'Poll archive', 
	'answerAllQuestions': 'Please answer all questions' 
};
 

if(typeof(delfiQuiz_languages) == 'undefined'){
	delfiQuiz_languages = new Array();
}
delfiQuiz_languages['et_EE'] = {
	'comments': 'Kommentaarid', 
	'btn_vote_default': 'Vasta', 
	'btn_results_default': 'Tulemused', 
	'noSuchPoll': 'Hetkel ei toimu &uuml;htegi k&uuml;sitlust.<br/><br/>Paku head p&auml;evak&uuml;simust: <a href="mailto:delfi@delfi.ee">delfi@delfi.ee</a>', 
	'rating': 'Keskmine', 
	'usersvoted': 'Vastanuid', 
	'tb_or_esc_key': 'v&otilde;i Esc klahvi', 
	'tb_close': 'Sulge', 
	'pollNotActive': 'K&uuml;simustik ei ole aktiivne', 
	'olderQuestions': 'Vanemad k&uuml;simused', 
	'questionsArchive': 'K&uuml;simuste arhiiv', 
	'answerAllQuestions': 'Vastake k&otilde;ik k&uuml;simused' 
};
 

if(typeof(delfiQuiz_languages) == 'undefined'){
	delfiQuiz_languages = new Array();
}
delfiQuiz_languages['lt_LT'] = {
	'comments': 'Comments', 
	'btn_vote_default': 'Balsuoti', 
	'btn_results_default': 'Rezultatai', 
	'noSuchPoll': 'Tokio klausimo n&#279;ra.', 
	'rating': 'Vertinimas', 
	'usersvoted': 'Atsakymai', 
	'tb_or_esc_key': 'arba Esc klavi&scaron;&#261;', 
	'tb_close': 'U&#382;daryti', 
	'pollNotActive': 'Klausimas n&#279;ra aktyvus.', 
	'olderQuestions': 'Ankstesni klausimai', 
	'questionsArchive': 'Klausim&#371; archyvas', 
	'answerAllQuestions': 'Pra&scaron;ome atsakyti &#303; visus klausimus' 
};
 

if(typeof(delfiQuiz_languages) == 'undefined'){
	delfiQuiz_languages = new Array();
}
delfiQuiz_languages['lv_LV'] = {
	'comments': 'Comments', 
	'btn_vote_default': 'Vote', 
	'btn_results_default': 'Results', 
	'noSuchPoll': '&ETH;&acirc;da aptauja nepast&acirc;v.', 
	'rating': 'Balsis', 
	'usersvoted': 'V&#275;rt&#275;jums', 
	'tb_or_esc_key': 'vai tausti&ograve;u [Esc]', 
	'tb_close': 'Aizv&ccedil;rt', 
	'pollNotActive': '&ETH;&icirc; aptauja nav ak&icirc;va.', 
	'olderQuestions': 'Agr&#257;ki jaut&#257;jumi', 
	'questionsArchive': 'Aptaujas arh&#299;vs', 
	'answerAllQuestions': 'L&#363;dzu atbildiet uz visiem jaut&#257;jumiem' 
};
 

if(typeof(delfiQuiz_languages) == 'undefined'){
	delfiQuiz_languages = new Array();
}
delfiQuiz_languages['ru_RU'] = {
	'comments': '&#1050;&#1086;&#1084;&#1084;&#1077;&#1085;&#1090;&#1072;&#1088;&#1080;&#1080;', 
	'btn_vote_default': '&#1043;&#1086;&#1083;&#1086;&#1089;&#1086;&#1074;&#1072;&#1090;&#1100;', 
	'btn_results_default': '&#1056;&#1077;&#1079;&#1091;&#1083;&#1100;&#1090;&#1072;&#1090;&#1099;', 
	'noSuchPoll': '&#1058;&#1072;&#1082;&#1086;&#1075;&#1086; &#1074;&#1086;&#1087;&#1088;&#1086;&#1089;&#1072; &#1085;&#1077;&#1090;', 
	'rating': '&#1054;&#1094;&#1077;&#1085;&#1082;&#1072;', 
	'usersvoted': '&#1054;&#1090;&#1074;&#1077;&#1090;&#1099;', 
	'tb_or_esc_key': '&#1080;&#1083;&#1080; &#1082;&#1083;&#1072;&#1074;&#1080;&#1096;&#1091; Esc', 
	'tb_close': '&#1047;&#1072;&#1082;&#1088;&#1099;&#1090;&#1100;', 
	'pollNotActive': '&#1042;&#1086;&#1087;&#1088;&#1086;&#1089; &#1085;&#1077; &#1072;&#1082;&#1090;&#1080;&#1074;&#1080;&#1088;&#1086;&#1074;&#1072;&#1085;', 
	'olderQuestions': '&#1057;&#1090;&#1072;&#1088;&#1099;&#1077; &#1074;&#1086;&#1087;&#1088;&#1086;&#1089;&#1099;', 
	'questionsArchive': '&#1040;&#1088;&#1093;&#1080;&#1074; &#1086;&#1087;&#1088;&#1086;&#1089;&#1086;&#1074;', 
	'answerAllQuestions': '&#1055;&#1086;&#1078;&#1072;&#1083;&#1091;&#1081;&#1089;&#1090;&#1072;, &#1086;&#1090;&#1074;&#1077;&#1090;&#1100;&#1090;&#1077; &#1085;&#1072; &#1074;&#1089;&#1077; &#1074;&#1086;&#1087;&#1088;&#1086;&#1089;&#1099;' 
};
 

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/


/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/


//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
	try {
		// Hide some things, because they peek trough 	
		$('select, iframe, object').css({ 'visibility' : 'hidden' });
		// and stil show our result flashes 
		embeds = document.getElementsByTagName("embed");
		for (i = 0; i != embeds.length; i++) {
			if(embeds[i]['id'] != 'ampie'){
				embeds[i].style.visibility = "hidden";
			} else {
				embeds[i].style.visibility = "";
			}
		}
		embeds = document.getElementsByTagName("object");
		for (i = 0; i != embeds.length; i++) {
			if(embeds[i]['id'] != 'ampie'){
				embeds[i].style.visibility = "hidden";
			} else {
				embeds[i].style.visibility = "";
			}
		}

		
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+delfiQuiz_imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>" + delfiQuiz_translate('tb_close') + "</a> " + delfiQuiz_translate('tb_or_esc_key') + "</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
							$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>" + delfiQuiz_translate('tb_close') + "</a> " + delfiQuiz_translate('tb_or_esc_key') + "</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	
	$('select, iframe, object, embed').css({ 'visibility' : 'visible' });
	return false;
}

function tb_position() {		
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
