/*
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: 1.2 $
Modification History
===============================================
$Log[4]$
*/

var pollLayouts = [];

/* 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()', 500); // call the onload handler
        setTimeout('renderAllPolls()', 1000); // 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)	
{
	var allcookies = document.cookie;
	var cookiestr;
	var pos;
	//alert('initing');
  firebugConsoleMsg('wooPollInit('+id+')' ,'info');
	
	//if((self.suppressRender) && (typeof suppressRender == 'undefined') && (self.wooPollRender)){
	if(typeof 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+'" ></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)	{
	//alert('adding to queue');
  firebugConsoleMsg('addPollToQueue('+id+','+s_action+')' ,'info');
	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()	{
	//alert('rendering everything: ' + pollArray.length);
  firebugConsoleMsg('renderAllPolls() called with a pollArray.length of ' + pollArray.length, 'info');
	for (i=0; i<pollArray.length; i++)	{
		//alert('pollArray[i].action = ' + pollArray[i].action);
		if (pollArray[i].action == "question")	{
			if(pollLayouts && pollLayouts[i]) { 
      	//alert('Poll render WITH layout');
			  wooPollRender(pollArray[i].id, pollLayouts[i]); 
			} 
			else { 
      	//alert('Poll render WITHOUT layout');
			  wooPollRender(pollArray[i].id); 
			}							
		}
		if (pollArray[i].action == "answers")	{
			loadResults(pollArray[i].id);
		}
	}
}

function determinePollWidth() {
	var classMatch = 'pollPic_';
  var foundMatch = false;
  // Loop over the document and find all the divs. 
  var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++){                      
    var classname = divs[i].className;
    if(classname.indexOf(classMatch) != -1) {
    	// Get the size from the div.
      var start = classname.indexOf(classMatch) + classMatch.length;
      var size = classname.substring(start, (start+3));
      foundMatch = true;
      break;
    	//alert(classname + ', ' + size);
    } 
    //if(divname.indexOf("sometext") == 0) { 
        //yes it is, do something
  	//}
	}
  
  if(foundMatch) {
  	firebugConsoleMsg('determinePollWidth() found a poll width of '+classMatch+size ,'info');
  	return  classMatch + size
  }
  else {
  	firebugConsoleMsg('determinePollWidth() found this isn\'t a stretchy poll so defaults used.' ,'info');
  	return foundMatch ;
  }
}


/* render the poll */
function wooPollRender(s_pollID, s_style, s_action)	
{
	//alert('rendering '+s_pollID);
	// make sure the the question (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 s_out = "";
	var barMaxWidth = 238;
	var p_width = s_style;	
	
	//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 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')
		{
			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><input type="hidden" name="ans_'+sCounter+'" value="'+sCounter+'__'+st_thePoll["answer"][tmpAnswer]["answer"]+'">';
				s_out += '<input name="answer" type="radio" value="'+sCounter+'" class="radio"><span class="polltxt">'+st_thePoll["answer"][tmpAnswer]["answer"]+'</span></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 {		
			//alert('I am rendering ' + 	s_pollID + ' now!');	
      var w = determinePollWidth();
      if(w) {
      	p_width = w;
      }
			if(p_width) {
				// Se define el valor de barMaxWidth segun el ancho de la poll
				switch(p_width) {
					case 'pollPic_125':
						barMaxWidth = 113;
						break;
					case 'pollPic_250':
						barMaxWidth = 238;				
						break;
					case 'pollPic_300':
						barMaxWidth = 288;				
						break;
					case 'pollPic_500':
						barMaxWidth = 488;				
						break;	
					default: 
						barMaxWidth = 238;
						break;
				}
			}
			
			// output question
			s_out +='<div class="question">' + st_thePoll["question"] + '</div>\n';			

			//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>\n';
        s_out+='  <div class="text_answer">'+st_thePoll["answer"][ansIdx]["answer"]+'&nbsp;-&nbsp;'+thisPercent+'%&nbsp;('+st_poll_results["st_results"][s_selector]+'&nbsp;votes)\n';
        s_out+='    <div class="barraTot" style="clear:both;">\n';
        s_out+='      <div id="b'+(ansIdx+1)+'" class="barraPorc">\n';
        if(thisBarWidth) {
        	s_out+='				<img src="/images/polls/quote_graphic.gif" width="'+thisBarWidth+'" height="14" class="bar">\n';
        }
        s_out+='			</div>\n';
        s_out+='    </div>\n';
        s_out+='  </div>\n';
        s_out+='</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)
{
	//alert('submitting '+s_pollID);
	var radioChecked = false;
	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=' + (''+new Date().getTime()).substring(4)+ (''+Math.random(1)).substring(2,6);
		//s_url += "dest=showresults&voted=true";
		voted[s_pollID]=true;
		return pollAjaxRequest(s_url, s_pollID);
	}
}	




/* make ajax request to record vote */
function pollAjaxRequest(url, pollId)	{
	//alert('AJAXIFICATION baby');
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
  		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
  		try {
    		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  			} catch (e2) {
    			xmlHttp = false;
  			}
	}
	@end @*/
	
	if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
  		xmlHttp = new XMLHttpRequest();
	}
 	// Callback function
   	if (navigator.appName=="Microsoft Internet Explorer"){
    	xmlHttp.onreadystatechange = new Function (resultsDelayer(pollId));
	}	else	{
		xmlHttp.onreadystatechange = resultsDelayer(pollId);
	}
	var sRandTS = (''+new Date().getTime()).substring(4)+ (''+Math.random(1)).substring(2,6)*1000000;
	url += '&'+sRandTS;

  
  	// Open a connection to the server
  	xmlHttp.open("GET", url, true);

  	// Send the request
  	xmlHttp.send(null); 
	return false;
}

/* 
 * 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)	{
	//alert('loading results '+ pollId);
	firebugConsoleMsg('loadResults('+ pollId+')', 'info');
	try{
		// append results js to dom
		var script = document.createElement('script');
		script.src = '/jsincludes/polls/results_' + pollId + '.js';
		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');	
		//alert('I changed the world');	
	}
	catch (e)	{
	//alert('oops error in writing js file');
	}
}

function delayProcessing(iMS)	{
	//alert('starting delay');
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); }
	while(curDate-date < iMS);
	//alert('ending delay');
}




/* 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));
}

// Function to use the console message API in Firebug.
// Shame there is no equal in IE.
function firebugConsoleMsg(msg, consoleType) {
	// If the console isn't available - for IE - then stop there.
	if(typeof console == 'undefined') {
  	return;
  }
  
	var types = ['log', 'info', 'debug', 'warn', 'error'];
	var typeMatched = false;
  var defaultConsoleType = 'info';
  
  // If a console type wasn't passed in then use a default.
	if(typeof consoleType == 'undefined') {
  	var consoleType = defaultConsoleType;
  }
	for(var i in types) {
  	
  	if(consoleType.toString().toLowerCase() === types[i]) {
			typeMatched = true;
		}
	}
  // if we couldn't match the type passed in then use the default.
  if(typeMatched === false) {
  	consoleType = defaultConsoleType;
  }	
  
  // Display the appropriate console message type.
  switch(consoleType) {
  	case 'log' : console.log(msg) ; break;
  	case 'info' : console.info(msg) ; break;
  	case 'debug' : console.debug(msg) ; break;
  	case 'warn' : console.warn(msg) ; break;
  	case 'error' : console.error(msg) ; break;
    default : console.error('Invalid type passed in ('+consoleType+') with message of: ' + msg);
  }
}

