// ==========================================================
// 		Global Values
// ==========================================================
var poll, status, section;
var updateVotingPoll;
var theQuestions;
var bComplete = false;
// page locations
var pollURL = "xmldata/pollchoices.xml";
var voteURL = "Poll_Processor.aspx"

// ==========================================================

function initVotingPoll(){
	var oInit = new XHConn();
	if(updateVotingPoll){ clearTimeout(updateVotingPoll) }
	if (!oInit) alert("We are unable to register your vote. Try a newer/better browser.");
	var fnDisplayPoll = function (oXML) {
		xml = oXML.responseXML;
		var voting = xml.getElementsByTagName("votingBooth")[0];
		status = voting.attributes[0].nodeValue
		section = xml.getElementsByTagName("section")[0].firstChild.data;
		headerPollDesc(status);
		if(status != "now"){ // hide content areas
			document.getElementById("pollContent").style.display = "none";
			document.getElementById("pollQuestions").style.display = "none";
		}
		if(status == "now"){
			var skaters = xml.getElementsByTagName("name");
			var theSkaters = new Array();
			for(var n=0,nm=skaters.length; n<nm; n++){
				theSkaters[theSkaters.length] = skaters[n].firstChild.data;
			}
			setVoteOptions(theSkaters.toString());
			checkVotingPoll();
		}
		// ===== REFRESH ==========
		if(status != "end"){ updateVotingPoll = setTimeout("initVotingPoll()",15000) };
	};
	oInit.connect(pollURL, "GET", "", fnDisplayPoll);
}
// ==========================================================


// ==========================================================
function submitResults(){
	if(getRadioValue(window.poll) == null){ 
		alert("Please vote for your favorite skater"); 
	} else {
		if(getCookie(window.poll) == null){
			var oVote = new XHConn();
			if (!oVote) alert("We are unable to register your vote. Try a newer/better browser.");
			var voteSuccess = function (oXML) {
				setCookie(window.poll,"true",365);
				displayPollContent(false);
				showThankYou();
				// advance header to next section when a vote is submitted;
				headerPollDesc(status);
				if(getCookie("questionnaire") == null){
					document.getElementById("pollQuestions").style.display = "block";
				}
			};
			oVote.connect(voteURL, "POST", "poll="+section+"&skater="+getRadioValue(section), voteSuccess);
		}
	}
}
// ==========================================================
function getSurveyValue(){
	var zipcode = document.getElementById("zipcode").value;
	var fanRanking = getRadioValue("fanRanking");
	var visited = getRadioValue("visited");
	var shopped = getRadioValue("shopped");
	var birthyear = document.getElementById("birthyear").value;
	return "poll=survey&zipcode="+zipcode+"&fanRanking="+fanRanking+"&visited="+visited+"&shopped="+shopped+"&birthyear="+birthyear;
}
function submitQuestionnaire(){
	document.getElementById("pollQuestions").style.display = "none";
	var oSurvey = new XHConn();
	if (!oSurvey) alert("We are unable to register your vote. Try a newer/better browser.");
	var fnSurvey = function (oXML) { 
		document.getElementById("pollQuestions").style.display = "none";
		setCookie("questionnaire","true",365);
	};
	oSurvey.connect(voteURL, "POST", getSurveyValue(), fnSurvey);
}
function cancelQuestionnaire(){
	document.getElementById("pollQuestions").style.display = "none";
	setCookie("questionnaire","true",365);
}
// ==========================================================
function headerPollDesc(txt){
	var desc = "<table border='0' cellpadding='4' cellspacing='0' id='pollDescription'>";
		if(section == "finals"){
			desc += "<tr><td><img src='images/poll/logo_MarshallsChallenge_final.gif' width='342' height='78' border='0' /></td></tr>";
		} else {
			desc += "<tr><td><img src='images/poll/logo_MarshallsChallenge.gif' width='342' height='78' border='0' /></td></tr>";
		}
		desc += "<tr><td>";
			if(txt == "soon"){
				desc += "<span style='font:normal 24px arial; color:#005DAB; letter-spacing:-1px;'>Coming Soon</span><br />The Marshalls U.S. Figure Skating Challenge online voting will be available soon. Once the competition has begun, you will have the option to vote three times during the event – once during each session (West Coast semifinal, East Coast semifinal, and final). We hope you enjoy the competition which will be aired live on ABC beginning at 1:00 p.m. EST.";
			} else if(txt == "end"){
				desc += "<span style='font:normal 12px arial'><span style='font:normal 24px arial; color:#005DAB; letter-spacing:-1px;'>The Poll is Closed</span><br /><b>The winners will be announced soon, live on ABC. Stay tuned!<br /><br />Live on ABC, 1-3 p.m. (EST). Enjoy the show!</b></span>";
			} else if(txt == "now"){
				var headerText = "";
				if(section == "westCoast"){
					if(getCookie("westCoast") == null){ headerText = "westCoast" } else { headerText = "eastCoast" }
				} else if(section == "eastCoast"){
					if(getCookie("eastCoast") == null){ headerText = "eastCoast" } else { headerText = "finals" }
				} else if(section == "finals"){
					if(getCookie("finals") == null){ headerText = "finals" } else { headerText = "closed" }
				}
				switch(headerText){
					case "westCoast" 	: desc += "Welcome to the Marshalls U.S. Figure Skating Challenge online voting. You will have the option to vote three times during the event – once during each session (West Coast semifinal, East Coast semifinal, and final). Thank you for participating and enjoy the competition now being aired live on ABC.";break;
					case "eastCoast" 	: desc += "Welcome to the Marshalls U.S. Figure Skating Challenge online voting. You will have the option to vote two more times during the event – once during each session (East Coast semifinal and final). Thank you for participating and enjoy the competition now being aired live on ABC.";break;
					case "finals"	 	: desc += "Welcome to the Marshalls U.S. Figure Skating Challenge online voting. You will have one more opportunity to vote during the event (final). Thank you for participating and watch today's live coverage to find out the winner!";break;
					case "closed"		: desc += ""; 
				}
			}
		desc += "</td></tr></table>";
	document.getElementById("pollHeader").innerHTML = desc;
};
// ==========================================================
function setVoteOptions(){
	if(getRadioValue(section) == null){
		// ===== HEADER =====
		if(section == "westCoast"){
			var options = "<div class='title'>Vote for you favorite West Coast skater to advance to the final.</div>";
		} else if(section == "eastCoast"){
			var options = "<div class='title'>Vote for you favorite East Coast skater to advance to the final.</div>";
		} else {
			var options = "<div class='title'>Choose your favorite skater, then watch the Marshalls&nbsp;Challenge where we'll reveal the winner.</div>";
		}
		// ===== SKATERS =====
		var skater = [
			[ "Cohen", { name:"Sasha Cohen", id:"mCohen", photo:"SashaCohen" } ],
			[ "Inoue", { name:"Rena Inoue / John Baldwin", id:"mInoue", photo:"RenaInoue" } ],
			[ "Lysacek", { name:"Evan Lysacek", id:"mLysacek", photo:"EvanLysacek" } ],
			[ "Taylor", { name:"Katy Taylor", id:"mTaylor", photo:"KatyTaylor" } ],
			
			[ "Belbin", { name:"Tanith Belbin / Ben Agosto", id:"mBelbin", photo:"TanithBelbin" } ],
			[ "Hughes", { name:"Emily Hughes", id:"mHughes", photo:"EmilyHughes" } ],
			[ "Meissner", { name:"Kimmie Meissner", id:"mMeissner", photo:"KimmieMeissner" } ],
			[ "Weir", { name:"Johnny Weir", id:"mWeir", photo:"JohnnyWeir" } ]
		]
		var theOptions = arguments[0].split(",");
		options += "<div class='pollBkgd'><table border='0' cellpadding='0' cellspacing='0'>";
		for(var x=0,sl=theOptions.length; x<sl; x++){
			if(x%2==0){
				options += "<tr>";
			}
			for(var n=0,nl=skater.length; n<nl; n++){
				if(theOptions[x] == skater[n][0]){
					options += "<td class='radio'><input type='radio' name='"+section+"' id='"+skater[n][1].id+"' value='"+skater[n][1].id+"'></td>";
					options += "<td class='photo'><label for='"+skater[n][1].id+"'><img src='images/poll/poll_p_"+skater[n][1].photo+".jpg' width='67' height='66' border='0' alt='"+skater[n][1].name+"' /></label></td>";
					options += "<td class='name'><label for='"+skater[n][1].id+"'>"+skater[n][1].name+"</label></td>";
				}
			}
			if(x%2==1){
				options += "</tr>";
			}
		}
		options += "</table></div>";
		options += "<table border='0' cellpadding='0' cellspacing='0' width='80%' align='center' class='pollFooter'><tr>";
		options += "<td>Results will be posted after the<br>final winners are determined.</td>";
		options += "<td align='right'><a href='#' onClick='submitResults();return false;'><img src='images/poll/poll_btn_VOTE.gif' width='89' height='28' border='0' alt='VOTE' /></a></td>";
		options += "</tr></table><div id='voteMsg'></div>";
		document.getElementById("pollContent").style.display = "block";
		document.getElementById("pollContent").innerHTML = options;
	}
}
function showThankYou(){
	msg = "<h1>Thank You!</h1>";
	switch(section){
		case "westCoast" 	: msg += "<span style='font:normal 12px arial'>Your vote has been counted for this round of competition. The next round will begin shortly. The finalists will be announced soon, live on ABC. Stay tuned!</span>"; break;
		case "eastCoast" 	: msg += "<span style='font:normal 12px arial'>Your vote has been counted for this round of competition. The next round will begin shortly. The finalists will be announced soon, live on ABC. Stay tuned!</span>"; break;
		case "finals" 		: msg += "<span style='font:normal 12px arial'>Your vote has been counted for this round of competition. The finalists will be announced soon, live on ABC. Stay tuned!</span>";;break;
	}
	msg += "<center><br><b>Live on ABC, 1-3 PM (EST)  Enjoy the show!</b></center>";
	document.getElementById("voteMsg").className = "voteMsg";
	document.getElementById("voteMsg").innerHTML = msg;
}
// ==========================================================
function checkVotingPoll(){
	window.poll = section;
	//delCookie(window.poll);
	//delCookie("questionnaire");
	var hasVoted = (getCookie(window.poll) != null)? true : false;
	if(hasVoted){ // show 'thank you' message
		displayPollContent(false);
		showThankYou();
	}
}
// ==========================================================
// 		Get Radio Value
// ==========================================================
function getRadioValue(field){
	var radio = document.forms["usfsa"].elements[field];
	if(radio == undefined) return null;
	for(var i=0,rl=radio.length; i<rl; i++) {
		if(radio[i].checked){ return radio[i].value; }
	}
	return null;
}
// ==========================================================
// 		Check for ClassName
// ==========================================================
function hasClass(node, className) {
  if (node.className == className) {
    return true;
  }
  var reg = new RegExp('(^| )'+ className +'($| )')
  if (reg.test(node.className)) {
    return true;
  }
  return false;
}
// ==========================================================
function displayPollContent(toggle){
	displayVoteOptions("div","title",toggle);
	displayVoteOptions("div","finals",toggle);
	displayVoteOptions("div","pollBkgd",toggle);
	displayVoteOptions("table","pollFooter",toggle);
}
function displayVoteOptions(node,className,toggle){
	var poll = document.getElementsByTagName(node);
	for(var d=0,dl=poll.length; d<dl; d++){
		if(hasClass(poll[d],className) && (d > 0)){
			poll[d].style.display = (toggle)? "block" : "none";
		}
	}
}
// ==========================================================
// 		COOKIEs
// ==========================================================
function getCookie(NameOfCookie){
	if (document.cookie.length > 0) {              
		begin = document.cookie.indexOf(NameOfCookie+"=");       
		if (begin != -1) {           
			begin += NameOfCookie.length+1;       
			end = document.cookie.indexOf(";", begin);
			if (end == -1) end = document.cookie.length;
				return unescape(document.cookie.substring(begin, end));
			} 
		}
	return null;
}
function setCookie(NameOfCookie, value, expiredays) {
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
	
	document.cookie = NameOfCookie + "=" + escape(value) + 
	((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}
function delCookie (NameOfCookie) {
	if (getCookie(NameOfCookie)) {
		document.cookie = NameOfCookie + "=" +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}
// ==========================================================
//		Browser Check
// ==========================================================
var agent 	= navigator.appName.toLowerCase();
if(agent == "opera"){
	var version = navigator.appVersion.substring(0,4);
	if(version < 8.5){
		alert("Please upgrade your browser. You will not be able to submit your vote with an Opera browser less than version 8.5. We apologize for any inconvience");
	}
}
// ==========================================================
//initVotingPoll();
if(!bComplete) updateVotingPoll = setTimeout("initVotingPoll()",250)
