/*
filename			: pollRenderer.js
Purpose				: IMPORTANT - PLEASE READ
					: Contains main functions needed for rendering polls, results and ajax vote request
					: As the page loads, poll js files are included eg /jsincludes/polls/1.js
					: These call wooPollInit() which draws a wrapper div and adds pollId and action('question' or 'answers') to an array
					: Once the page is completely loaded (not window.onload as that is too soon) pollInit() is called by one of the load detection funcs (top of this file)
					: pollInit calls renderAllPolls() to render the polls IN ORDER from the array.
					: This is because the polls must be rendered in order or it breaks.
Created On			: 07.02.07
Original Developer	: D Saunders

History	: Any amendments that have been made since the original version of the script
*/
/* Revision Value: $Revision$
Modification History
===============================================
$Log[4]$
*/ 


var xmlHttp = null;
var thisPollId;

function generateTS()	{
	var sTS = (''+new Date().getTime()).substring(4)+ (''+Math.random(1)).substring(2,6);
	return sTS;
}

/* these functions render the polls in their wrapper divs once the page is completely parsed */
function pollInit() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;
	renderAllPolls();
};

//LOAD DETECTION FUNCS

/* ie */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
        setTimeout('pollInit()', 50); // call the onload handler
    }
};
/*@end @*/

/* Mozilla */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", pollInit, false);
}

/* safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            clearInterval(_timer);
            pollInit(); // call the onload handler
        }
    }, 10);
}




/* global vars */
var pollArray = new Array();
var voted = new Object();
var ajaxUrl = "/admin/polls/recordAndShow_cf5.cfm";
var xmlHttp = false;
var youVoted = "";


/* called by poll js files: adds polls to rendering queue */
function wooPollInit(id)	
{
	//alert('wooPollInit('+id+')');
	var allcookies = document.cookie;
	var cookiestr;
	var pos;
	
	//if((self.suppressRender) && (typeof suppressRender == 'undefined') && (self.wooPollRender)){
	if(typeof suppressRender == 'undefined'){
		//alert("suppressRender == 'undefined'");
		
		//check cookie to find out if user has already voted on this poll
		cookiestr = "L" + id +'=';
		pos = allcookies.indexOf(cookiestr);
		if (pos != -1)	{
			var start = pos + cookiestr.length;
			var end = allcookies.indexOf(";",start);
			if (end == -1) end = allcookies.length;
			var cvalue = allcookies.substring(start, end);
			if (cvalue == "i") {
				voted[id] = true;
			}
		}
		
		//draw poll wrapper div and add poll instruction to rendering queue
		document.write('<div id="poll_'+id+'" class="pollPic"></div>\n');
		
		if (voted[id] == true)	{
			addPollToQueue(id,"answers");
			return;
		}	else	{
			addPollToQueue(id,"question");
		}
	}
}




/* 
   adds an entry in poll rendering queue array
  /jsincludes/polls/renderPollQueue.js is in the footer and reads this array after all poll js loaded
   and calls the renderer functions. 
*/ 
function addPollToQueue(id,s_action)	{
	var idx = pollArray.length;
	pollArray[idx] = new Object();
	pollArray[idx].id = id;
	pollArray[idx].action = s_action;
}




/* called from footer. Renders all polls in the page in order */
function renderAllPolls()	{
	for (i=0; i<pollArray.length; i++)	{
		if (pollArray[i].action == "question")	{
			wooPollRender(pollArray[i].id)
		}
		if (pollArray[i].action == "answers")	{
			loadResults(pollArray[i].id);
		}
	}
}




/* render the poll */
function wooPollRender(s_pollID, s_style, s_action)	
{
	// make sure the the question (and optionally results) js files have been included and parsed.
	var thisDivId = 'poll_'+s_pollID;
	var s_selector;
	var i_maxPercentage;
	var i_barScaleFactor;
	var b_allOk = true;
	var f_pct;
	var s_out = "";
	var barmaxwidth;
	var textwidth;
	
	//default to portal style
	if (typeof s_style == 'undefined') {s_style = "portal";}
	else if (s_style != 'forum') {s_style = "portal";}
	
	//Note for future: when we use it on forums the overall width will need to be 300px
	//if (s_style == "forum") i_graphWidth = 300;
	//else i_graphWidth = 80;

	//display question or results 
	if (typeof s_action == 'undefined') {s_action = "question";}
	else if (s_action != 'answers') {s_action = "question";}
	//test poll object
	try {
		var st_thePoll = eval("st_poll_"+s_pollID);
	} catch (er) {
		b_allOk = false;
	}
	
	//test results object
	if (s_action == 'answers')	{
		try	{
			var st_poll_results = eval("st_poll_results_"+s_pollID);
			} 
			catch (er) {
				alert('Sorry, we experienced a problem trying to record your vote, please try again.');
			}
	}
	
	//main rendering
	if(b_allOk)
	{
		
		//Now we're going to branch based on the value of whatToRender param 
		if (s_action == 'question')
		{
			textwidth = document.getElementById(thisDivId).offsetWidth - 30;
			
			s_out += '<form method="get" action="" id="form_'+st_thePoll["pollid"]+'" onSubmit="return wooSubmitPollVote(this,\''+s_pollID + '\',\''+s_style+'\',true);">';
			s_out += '<input type="Hidden" name="pollid" value="' + st_thePoll["pollid"]  + '">';
			s_out += '<input type="Hidden" name="question" value="' + st_thePoll["question"] + '">';
			s_out += '<input type="hidden" name="style" value="'+s_style+'">';
			s_out += '<input type="hidden" name="done" value="true">';
			s_out += '<input type="hidden" name="multi" value="';
			if(st_thePoll["allowmultiplevotes"] == "on")
				s_out += 'true">';
			else
				s_out += 'false">';
			s_out += '<input type="hidden" name="forumid" value="' + st_thePoll["forumid"] + '">';
			s_out += '<input type="hidden" name="forummsgid" value="' + st_thePoll["forummsgid"] + '">';
			
			// pass thru testing url params.
			if(window.location.href.indexOf("devtest") != -1)
				s_out += '<input type="hidden" name="devtest" value="1">';
			if(window.location.href.indexOf("qatest") != -1)
				s_out += '<input type="hidden" name="qatest" value="1">';
			if(window.location.href.indexOf("devmxtest") != -1)
				s_out += '<input type="hidden" name="devmxtest" value="1">';
			
			// track all the links
			if((st_thePoll["discussionlinkurl"]) != "")
				st_thePoll["discussionlinkurl"] = wooTrackExtLinks(wooGetTrackingId(), "poll_discussion", "poll_", st_thePoll["discussionlinkurl"], '');		
			
			// output question
			s_out += '<div class="question">' + st_thePoll["question"] + '</div>';
			
			//loop thru and display question/answers
			var iCounter=1;
			var sCounter;
			if (typeof st_thePoll["answer"] == "Object") s_out += '<ul>\n';
			for (tmpAnswer in st_thePoll["answer"])
			{
				sCounter = new String(iCounter);
				s_out += '<li><div class="pollradio"><input type="hidden" name="ans_'+sCounter+'" value="'+sCounter+'__'+st_thePoll["answer"][tmpAnswer]["answer"]+'">';
				s_out += '<input name="answer" type="radio" value="'+sCounter+'" class="radio"></div><div class="polltxt" style="float:left; width:'+textwidth+'px;">'+st_thePoll["answer"][tmpAnswer]["answer"]+'</div></li>\n';
				//s_out += '<input name="answer" type="radio" value="'+sCounter+'" class="radio"></div><div class="polltxt">'+st_thePoll["answer"][tmpAnswer]["answer"]+'</div></li>\n';
				iCounter++;
			}
			if (typeof st_thePoll["answer"] == "Object") s_out += '</ul>\n';
			
			//vote button
			s_out += '<div class="vote">\n';
			s_out += '<input type="image" src="/images/tools/vote_imgGallery.gif" border="0" alt="Vote">\n';
			s_out += '</div>\n';
			
			
			s_out += '</form>';
		}
		
		//Otherwise render just the answers
		else {
			
			// output question
			s_out +='<div class="question">' + st_thePoll["question"] + '</div>\n';
			// do maths for answers display		
			barMaxWidth = document.getElementById(thisDivId).offsetWidth - 15;
			//barMaxWidth = 237;
			
			//loop thru and display question/answers
			
			if (typeof st_thePoll["answer"] == "object") s_out+='<ul>\n';
			if (typeof st_thePoll["answer"][parseInt(youVoted)] == "object") s_out +='<li class="answer">You voted '+st_thePoll["answer"][parseInt(youVoted)]["answer"]+'</li>\n';
			for(ansIdx=0; ansIdx<st_thePoll["answer"].length; ansIdx++)	{
				s_selector = "a"+ansIdx;
				if(st_poll_results["i_total"] > 0 && st_poll_results["st_results"][s_selector] > 0)	{
					thisFraction = st_poll_results["st_results"][s_selector] / st_poll_results["i_total"];
					thisPercent  = Math.round(thisFraction * 100);
					thisBarWidth = Math.round(thisFraction * barMaxWidth);
				}	else	{
					thisFraction = 0;
					thisPercent = 0;
					thisBarWidth = 0;
				}	
				s_out+='<li>'+st_thePoll["answer"][ansIdx]["answer"]+' - '+thisPercent+'% ('+st_poll_results["st_results"][s_selector]+' votes)<div class="barraTot"><div id="b'+(ansIdx+1)+'" class="barraPorc"><img src="/images/polls/quote_graphic.gif" width="'+thisBarWidth+'" height="14" class="bar"></div></div></li>\n';
			}
			
			if (typeof st_thePoll["answer"] == "Object") s_out+='</ul>\n';
		}	
		//dump the content in the wrapper div
		document.getElementById('poll_'+st_thePoll.pollid).innerHTML = s_out;
	}
}




/* function to validate and submit vote when button pressed */
function wooSubmitPollVote(obj_form, s_pollID, s_style, passValue)
{
	var radioChecked = false;
	var sTS = generateTS();
	st_thePoll = eval("st_poll_"+s_pollID); 
	if(st_thePoll)
	{
		if (typeof st_thePoll["allowmultiplevotes"] == 'undefined') st_thePoll["allowmultiplevotes"] = 0;
		
		if (voted[s_pollID]==true && st_thePoll["allowmultiplevotes"] != 1 && passValue==true)	{
			alert ('You have already voted - Thank you for registering your vote, but only one vote on a poll is accepted per person.');
			return false;
		}
		s_url = ajaxUrl + "?";
		for(i = 0; i < obj_form.length; i++)
		{
			if(obj_form.elements[i].type=="radio" && passValue)
			{
				if(obj_form.elements[i].checked == true)	{
					radioChecked = true;
					s_url += obj_form.elements[i].name + "="+escape(obj_form.elements[i].value)+"&";
					// store 'you voted' on client so this can be displayed. 
					//Minus 1 from value as radio idex starts at 1, js index starts at 0
					youVoted = (obj_form.elements[i].value - 1);
				}
			}
			else if (obj_form.elements[i].type!="radio")
			{
				s_url += obj_form.elements[i].name + "="+escape(obj_form.elements[i].value)+"&";
			}	
		}
		if (!radioChecked)	{
			alert('Please choose an option');
			return false;
		}
		
		s_url += 'rnd=' + sTS;
		//s_url += "dest=showresults&voted=true";
		voted[s_pollID]=true;
		pollAjaxRequest(s_url, s_pollID);
		return false;
	}
}	




/* make ajax request to record vote */
function pollAjaxRequest(url, pollId)	{
	
	//Generate an object for non IE browsers
	if (window.XMLHttpRequest) {
		  xmlHttp=new XMLHttpRequest();
	}
	//Otherwise go with an IE version
	else if (window.ActiveXObject)  {
		//Here we try to see whether we have IE6 which uses a faster version of the interface
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
		}
		//otherwise go with the base on in IE5.5
		catch(e) {
			 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
		}
	}
	
	thisPollId = pollId;
	//To prevent IE caching - generate a timestamp and append it to the URL
	var sRandTS = (''+new Date().getTime()).substring(4)+ (''+Math.random(1)).substring(2,6)*1000000;
	url += '&'+sRandTS;
	
	xmlHttp.open("GET", url, true);
		
	xmlHttp.onreadystatechange = stateChanged;
		
	// Send the request
	xmlHttp.send(null); 

}


function stateChanged()	{
	//a readyState value of 4 or "complete" means our object is ready to use so change the boolean to true
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		//readyState is complete - but let's double check we got a 200 status
		if (xmlHttp.status == 200 && xmlHttp.statusText == "OK") {
				resultsDelayer(thisPollId);
		}
		else {
			alert('Sorry, we were unable to record your vote.');
		}
	} 
}

/* 
 * Added this to delay getting the results js file as sometimes it tries to get
 * it before it's available on the server so the user might see the results which 
 * don't include their own vote.
 * This is called once the users vote has been processed in pollAjaxRequest(...).
 */
function resultsDelayer(pollId) {
	//alert('delaying poll results by 3 seconds.');
	setTimeout('loadResults('+pollId+')', 1000);
}

/* append results js to DOM 
   this executes wooPollRender(id,"answers"); to render results */
function loadResults(pollId)	{
	try{
		// append results js to dom
		var script = document.createElement('script');
		script.src = '/jsincludes/polls/results_' + pollId + '.js?rnd='+Math.random();
		script.type = 'text/javascript';
		script.id = 'pollResultsScript_' + pollId
		var head = document.getElementsByTagName('head').item(0);
		var oldscript = document.getElementById('pollResultsScript');
		if (oldscript) head.removeChild(oldscript);
		head.appendChild(script);
		var cookieName = "L"+pollId;
		var expiry = new Date(2010,01,01,0,0,0,0);
		setCookie(cookieName,'i',expiry,'/','.orange.co.uk');		
	}
	catch (e)	{
	}
}




/* link tracking functions */
function wooTrackExtLinks(sLinkfrom, sLink, sArticle, sLinkto, sTrackingDomainPrefix)
{
	var sTrackedUrl = "";
	if(sLinkto.indexOf("http://") != 0) return sLinkto;
	
	var aSplitUrl = window.location.href.split("/");
	if(window.location.href.indexOf(".orange.co.uk/") != -1)
	{
		// internal page
		var sTopDir = aSplitUrl[3];
		var sTrackedUrl = "";
		if(sTopDir.indexOf("?") != -1)
			sTrackedUrl = sTrackingDomainPrefix+"/redirect/redirect=ext&";
		else 
			sTrackedUrl = sTrackingDomainPrefix+"/" + sTopDir + "/redirect/redirect=ext&";
	}
	else
	{
		// external page
		sTrackedUrl = sTrackingDomainPrefix+"/redirect/redirect=ext&";
	}
	sTrackedUrl = sTrackedUrl + "linkfrom=" + sLinkfrom + "&link=" + sLink + "&article=" + sArticle + "&linkto=" + sLinkto.substring(7,(sLinkto.length));
	return sTrackedUrl;
}




// if this is a bp tracking page, return the bp tracking id, if not, fashion one out of the page url.
function wooGetTrackingId()
{
	if ( typeof bp_trackingPage == 'undefined' )
	{
		illegalChars = /[^a-zA-Z0-9]/g
		sEnd = window.location.href.indexOf("?");
		sUrl = window.location.href.substr(0,sEnd);
		return sUrl.replace(illegalChars,"_");
	}
	else
		return bp_trackingPage;	
}




/* cookie handling functions */
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}




function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

