var voted = new Object();
var whatToRender = 'poll';
// find current domain

var s_location = window.location.href;



// simple link tracking routine.
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;	
}

// Extracted the popup/ window handling routenes from the submit function so you don't allways have to submit
function resultsHandler(inputURL)
	{
		fsPopUp(inputURL, '100','100',false, true);
	}

// routine called when submitting the poll. we want the results to appear in a popup, so to make life
// easier this routine builds a GET url string out of all the form fields, and opens a window to that
// address.	
function fsPopUp(theURL,theWidth,theHeight,theScroll,theResize){
	var theProperties="width="+theWidth+",height="+theHeight+",scrollbars="+theScroll+",resizable="+theResize+",top=10,left=10,status=no";
fsPopwin=window.open(theURL,"wooPoll",theProperties);
}

function wooSubmitPollVote(obj_form, s_pollID, s_style, passValue)
{
	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 = "/admin/polls/gateway.htm?";
		for(i = 0; i < obj_form.length; i++)
		{
			if(obj_form.elements[i].type=="radio" && passValue)
			{
				if(obj_form.elements[i].checked == true)
					s_url += obj_form.elements[i].name + "="+escape(obj_form.elements[i].value)+"&";
			}
			else if (obj_form.elements[i].type!="radio")
			{
				s_url += obj_form.elements[i].name + "="+escape(obj_form.elements[i].value)+"&";
			}	
		}
		s_url += "dest=showresults&voted=true";
		voted[s_pollID]=true;

		// FIX: fspop seems to behave differently on the forums, so if fsPopup is defined (as it is on the forum)
		// use that, otherwise use fsPop (on the portal).
		resultsHandler(s_url);
	}
	if(s_style != "portal")
		window.setTimeout("wooRefreshPageWithResults();", 3000);
	return false;
}	

function wooRefreshPageWithResults()
{
	s_tmp = window.location.href + "";
	window.location.href=s_tmp.replace("wanadooDisplayVote=1","");
}




function wooPollRender(s_pollID, s_style, s_action)	
{
	// make sure the the questions (and optionally results) js files have been included and parsed.
		
	var s_selector;
	var i_maxPercentage;
	var i_barScaleFactor;
	var b_allOk = true;
	var i_graphWidth;
	var f_pct;
	var allcookies = document.cookie;
	var cookiestr;
	var pos;

	
	//default to portal style
	if (typeof s_style == 'undefined') {s_style = "portal";}
	else if (s_style != 'forum') {s_style = "portal";}
	
	//determine graph width from context
	if (s_style == "forum") i_graphWidth = 300;
	else i_graphWidth = 80;

	//display questions only or results too
	if (typeof s_action == 'undefined') {s_action = "questions";}
	else if (s_action != 'answers') {s_action = "questions";}
	//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.');
		}
		whatToRender = 'results';
	}
	
	//find out if user has already voted;
	cookiestr = "L" + st_thePoll["pollid"]+'=';
	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[s_pollID] = true;
		}
	}
	
	//main rendering
	if(b_allOk)
	{
		//Now we're going to branch based on the value of whatToRender param 
		if (whatToRender == 'poll' )
		{
			
			//wrapper div, form and hidden fields
			document.write('<div class="poll">\n');
			document.write('<div class="shadow">\n');
			document.write('<h3>'+st_thePoll["headingtext"]+'</h3>\n');
			document.write('<form method="get" action="/admin/polls/gateway.htm" id="form_'+st_thePoll["pollid"]+'" onSubmit="return wooSubmitPollVote(this,\''+s_pollID + '\',\''+s_style+'\',true);">');
			document.write('<input type="Hidden" name="pollid" value="' + st_thePoll["pollid"]  + '">');
			document.write('<input type="Hidden" name="question" value="' + st_thePoll["question"] + '">');
			document.write('<input type="hidden" name="style" value="'+s_style+'">');
			document.write('<input type="hidden" name="done" value="true">');
			document.write('<input type="hidden" name="multi" value="');
			if(st_thePoll["allowmultiplevotes"] == "on")
				document.write('true">');
			else
				document.write('false">');
			document.write('<input type="hidden" name="forumid" value="' + st_thePoll["forumid"] + '">');
			document.write('<input type="hidden" name="forummsgid" value="' + st_thePoll["forummsgid"] + '">');
			
			// pass thru testing url params.
			if(window.location.href.indexOf("devtest") != -1)
				document.write('<input type="hidden" name="devtest" value="1">');
			if(window.location.href.indexOf("qatest") != -1)
				document.write('<input type="hidden" name="qatest" value="1">');
			if(window.location.href.indexOf("devmxtest") != -1)
				document.write('<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
			document.write('<div class="bgbdy">');
			document.write('<h2>' + st_thePoll["question"] + '</h2>');
			
			//loop thru and display questions/answers
			var iCounter=1;
			var sCounter;
			if (typeof st_thePoll["answer"] == "Object") document.write('<ul>\n');
			for (tmpAnswer in st_thePoll["answer"])
			{
				sCounter = new String(iCounter);
				document.write('<li><input type="hidden" name="ans_'+sCounter+'" value="'+sCounter+'__'+st_thePoll["answer"][tmpAnswer]["answer"]+'">');
				document.write('<input name="answer" type="radio" value="'+sCounter+'" class="radio"><span class="txbdy">'+st_thePoll["answer"][tmpAnswer]["answer"]+'</span></li>\n');
				iCounter++;
			}
			if (typeof st_thePoll["answer"] == "Object") document.write('</ul>\n');
			
			//vote button
			document.write('<div class="button">\n');
			document.write('<input type="image" src="/images/tools/vote.gif" class="vote" hspace="0" vspace="4" border="0" alt="Vote">\n');
			document.write('</div>\n');
			
			// results link
			if(s_style=="portal")
				document.write('<a target="_self" href="javascript:;" class="lnk" onClick="wooSubmitPollVote(document.getElementById(\'form_'+st_thePoll["pollid"]+'\'),\''+s_pollID + '\',\''+s_style+'\',false);">Results</a>');
			else
				document.write('<a class="wanadooPollLink" target="_self" href="javascript:wooRefreshPageWithResults();" >View Results</a>\n');
			
			// debate link
			if(s_style=="portal" && st_thePoll["showjointhedebatelink"] == "on" && st_thePoll["discussionlinkurl"] != "")
			document.write('<br>'+st_thePoll["discussiontextpre"]+'<a href="'+st_thePoll["discussionlinkurl"]+'" class="lnkr">'+st_thePoll["discussionlinktext"]+'</a>\n');
			
			document.write('</div>');
			document.write('</form>');
			document.write('</div>');
			document.write('</div>');
	
		}
		//Otherwise render just the answers
		else {
			
			//wrapper div, form and hidden fields
			document.write('<div class="poll">\n');
			document.write('<h3>'+st_thePoll["headingtext"]+'</h3>\n');
			
			// output question
			document.write('<div class="bgbdy">');
			document.write('<h2>' + st_thePoll["question"] + '</h2>');
			
			// do maths for answers display		
			i_maxPercentage = 0;
			st_poll_results["st_percentages"] = new Object();
			for (tmpAnswer in st_poll_results["st_results"])
			{
				if(st_poll_results["i_total"] > 0)
					f_pct = (st_poll_results["st_results"][tmpAnswer] / st_poll_results["i_total"]) * 100; 
				else
					f_pct = 0;
				st_poll_results["st_percentages"][tmpAnswer] = f_pct;
				if(f_pct > i_maxPercentage) i_maxPercentage = f_pct;
			}
			i_barScaleFactor = i_graphWidth / i_maxPercentage ;		
			
			//loop thru and display questions/answers
			var iCounter=1;
			var sCounter;
			if (typeof st_thePoll["answer"] == "Object") document.write('<ul>\n');
			for (tmpAnswer in st_thePoll["answer"])
			{
				sCounter = new String(iCounter);
				s_selector = "a"+iCounter;
				if(typeof st_poll_results["st_percentages"][s_selector] != 'undefined')
					s_pct = st_poll_results["st_percentages"][s_selector];
				else
					s_pct = "0";
				document.write('<li><span class="txbdy">'+st_thePoll["answer"][tmpAnswer]["answer"]+'</span><div><img src="/images/polls/quote_graphic.gif" width="'+eval(Math.round(i_barScaleFactor*s_pct))+'" height="14" class="bar"> <span class="txbdy">'+Math.round(s_pct)+'%</span></div></li>\n');
				iCounter++;
			}
			if (typeof st_thePoll["answer"] == "Object") document.write('</ul>\n');
			
			//vote button
			if (st_thePoll["shownumberofvotescast"] == "on")	{
				document.write('<div class="numvotes">Number of votes cast: ' + st_poll_results["i_total"] + '</div>');
			}
			
			document.write('</div>');
			document.write('</div>');

		}	
	}
}


function wooPollInit(id)	
{
	if(typeof suppressRender == 'undefined')
		wooPollRender(id);
}






