var xmlHttp=null;
function initRequest() {
	try
		{
		 xmlHttp=new XMLHttpRequest(); 
	}catch (e){
		try{   
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
		}catch (e){
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  
			}catch (e){
				alert("Your browser does not support AJAX!");     
				return false;    
			} 
		}
	}
	return xmlHttp;
}
function submitVote(userId, pollId, selectedOption, linkText, showTotalVotes)
{
	var url = contextPath+"/updatePoll.jsp?userId="+userId+"&pollId="+pollId+"&selectedOption="+selectedOption; 
	var req = initRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				displayPollResults(pollId, linkText, showTotalVotes);
			}
		}
	};
	req.open("GET", url, true);
	req.send(null);
}
function submitVote2(userId, pollId, selectedOption, linkText, showTotalVotes, voted, keyValue)
{
	var url = contextPath+"/updatePoll.jsp?userId="+userId+"&pollId="+pollId+"&selectedOption="+selectedOption+"&voted="+voted; 
	var req = initRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				displayPollResults(pollId, linkText, showTotalVotes, voted, keyValue);
			}
		}
	};
	req.open("GET", url, true);
	req.send(null);
}
function submitForm(featureId,featureQuestion,linkText,showTotalVotes,keyValue)
{
	var result = readCookie(featureId);
	var voted = 0;
	if(result == null || result == ""){
		createCookie(featureId,'yes',30);
	}else{
		voted = 1;
	}
	if (typeof (sessionId) == 'undefined' || sessionId == null || sessionId == "") {
		sessionId = (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4()).toUpperCase();
	}
	if (typeof (sessionId) != 'undefined' && sessionId != null && sessionId != "") {
		selectedOption = getPollCheckedValue(document.forms[featureId].selectedOption);
		if (selectedOption != "") {
			//submitVote(sessionId, featureId, selectedOption, linkText, showTotalVotes);
			submitVote2(sessionId, featureId, selectedOption, linkText, showTotalVotes, voted, keyValue);

		}
		else {
			alert ("Please select your choice and click Vote!");
			return;
		}			
	}
}
function S4() {
	return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getPollCheckedValue(radioObj) 
{
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function displayPollResults(pollId, linkText, showTotalVotes, voted, keyValue) 
{
	//getPollResults(pollId);
	//document.getElementById('pollOptions').style.display = 'block';
	 window.open("/NBCSPPoll/jsp/showPollResult.jsp?featureId="+pollId+"&linkText="+linkText+"&showTotalVotes="+showTotalVotes+"&voted="+voted+"&keyValue="+keyValue,"pollresult","width=800,height=600,resizable=yes,scrollbars=yes,status=yes");

}

function getPollResults(featureId,showTotalVotes,voted)
{
	var url = contextPath + "/getPollResults.jsp?featureId=" + featureId;
	var req = initRequest();
	req.onreadystatechange = function() {		
		if (req.readyState == 4) {
			if (req.status == 200) {
				document.getElementById('resultList').style.display='block';
				var linkText = document.getElementById('resultList').innerHTML;
				var outputData = parsePollResults(req.responseXML.documentElement,featureId,showTotalVotes,voted,linkText);
				document.getElementById('pollResults').style.display = 'block';
				document.getElementById('resultList').innerHTML=outputData;
			}
		}
	};
	req.open("GET", url, true);
	req.send(null);
}

function parsePollResults(pollResults,featureId,showTotalVotes,voted,linkText) {
	var outputData = "";
	var totalCount = 0;
	if(voted == "1"){
		outputData += "<div style='text-align:left;padding:4px;display:block'><span style='font:italic 12px Georgia; color:#444444;'>You have already taken this poll -- your vote will not be tallied</span></div>";
	}
	var featureQuestion = window.opener.document.forms[featureId].featureQuestion.value;
	featureQuestion = unescape(featureQuestion);
	outputData += "<div style='text-align:left;padding:4px;display:block'><span style='font-family:Georgia; font-size:12px; color:#444444; font-weight:bold;'>"+featureQuestion+"</span></div>";
	outputData += "<table>";
	for (var k=0; k<window.opener.document.forms[featureId].selectedOption.length; k++) {
		var found = false;
		var value = new Array();
		value[0] = "";
		var tempValue="";
		var formOption = window.opener.document.forms[featureId].selectedOption[k].value;
		var formDisplayOption = window.opener.document.forms[featureId].elements['selectedOptionName'+formOption].value;
		formDisplayOption = unescape(formDisplayOption);
		for (var i = 0; i<pollResults.childNodes.length; i++) {
			if (pollResults.childNodes[i].getElementsByTagName("option")[0].childNodes[0].data == "count") {
				totalCount = pollResults.childNodes[i].getElementsByTagName("value")[0].childNodes[0].data; 
			}
			var dbOption = pollResults.childNodes[i].getElementsByTagName("option")[0].childNodes[0].data;
			//alert("dbOption=" + dbOption + ",formOption="+formOption);
			if (formOption == dbOption) {
				tempValue = pollResults.childNodes[i].getElementsByTagName("value")[0].childNodes[0].data;
				if (tempValue == null || tempValue == "null") {
					value[0] = "0";
				} else {
					tempValue = tempValue.replace(/\[/,"");
					tempValue = tempValue.replace(/\]/,"");
					tempValue = tempValue.split(",");
					for (x=0;x<tempValue.length-2;x++){
						if(x == tempValue.length-3){
							value[0] = value[0] + tempValue[x];
						}else if(tempValue[x]==""){
							value[0] = value[0] + ",";
						}else{
							value[0] = value[0] + tempValue[x] + ",";
						}
					}
					value[1] = tempValue[tempValue.length-2];
					value[2] = tempValue[tempValue.length-1];
				}	
				found = true;
			}
		}
		if (found) {
			value[1] =Math.round(((parseFloat(value[2]) / parseFloat(totalCount)) * 100) * 10) / 10;
			outputData += "<tr><td rowspan='2' valign='top' align='right' padding-right='10px'><span style='font-family:Georgia; font-size:12px; font-weight:bold; color:#3F910A;'>" + value[1] + "%" + "</span></td><td><span style='font-family:Georgia; font-size:12px; color:#444444;'>" + formDisplayOption + "</span></td></tr>";
			outputData += "<tr><td class='recap_very_light' style='margin-bottom:3px;-moz-border-radius: 5px;'><table><tr><td style='background:#3F910A;line-height: 4px;' width='"+ value[1]*2 +"' >&nbsp;</td></tr></table>";
			outputData += "</td></tr>";
			value="";
		}
		if (!found) {
			value = 0;
			outputData += "<tr><td rowspan='2' valign='top' align='right' padding-right='10px'><span style='font-family:Georgia; font-size:12px; font-weight:bold; color:#3F910A;'>" + value + "%" + "</span></td><td><span style='font-family:Georgia; font-size:12px; color:#444444;'>" + formDisplayOption + "</span></td></tr>";
			outputData += "<tr><td class='recap_very_light' style='margin-bottom:3px;-moz-border-radius: 5px;'><table><tr><td style='background:#3F910A;line-height: 4px;' width='1px' >&nbsp;</td></tr></table>";
			outputData += "</td></tr>";
				
		}
	}
	outputData += "</table></div><br/><div>"+linkText+"</div>";
	
	if(showTotalVotes == 1){
		if(totalCount == 1){
			outputData += "<span style='font-family:Georgia; font-size:11px; color:#444444;'>"+totalCount+" person has voted so far.</span>";
		}else{
			outputData += "<span style='font-family:Georgia; font-size:11px; color:#444444;'>"+totalCount+" people have voted so far.</span>";
		}
	}
	//outputData += "<div><div style='display:block'><div style='text-align:left;padding:4px'><font size='2'><b>Total Votes:"+totalCount+"</b></font></div></div></div>";
	//outputData += "<div><div style='display:block'><div style='text-align:left;padding:4px'><font size='1'><b>Thank you for participating in this totalhealth.iVillage.com survey.</b></font></div></div></div>";
	return outputData;
}

function hasUserVoted(pollId, userId) {
	var url = contextPath+"/hasUserVoted.jsp?userId="+userId+"&pollId="+pollId; 
	var req = initRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				var responseElement = req.responseXML.documentElement;
				var output = responseElement.childNodes[0].data;
				if (output == 'true') 
					displayPollResults();
			}
		}
	};
	req.open("GET", url, true);
	req.send(null);
}
function createCookie(name,value,days){
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}else
		var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++){
		var c = ca[i];
		while (c.charAt(0)==' ')
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
} 
