nfl.partners.poll	= Class.create();
nfl.partners.poll.prototype	= {
	initialize: function(options){
		//pollId="0_0_1218226280931" pollTitle="Rookies Poll" partner="Rookies of Week/Year Page" pollSkin="1" skinNae="sirius" pollType="0" votesAllowed="0" sessionLength="0" optionCount="4" maxAnswer="0"
		this.id				= options.id;
		this.title			= options.title;
		this.type			= options.type;
		this.skin			= options.skin;
		this.skinName		= options.skinName;
		this.votesAllowed	= options.votesAllowed;
		this.sessionLength	= options.sessionLength;
		this.maxAnswers		= options.maxAnswers;
		this.question		= options.question;
		this.options		= options.options;
		this.postPath		= nfl.global.pollpath +"/castvote";
		this.keys			= {key:'',hkey:''}
		this.hasVoted		= false;
		this.loginRequired	= options.loginRequired;
		this.error			= false;
		this.errorMessage	= "";
		this.successMessage	= options.successMessage;
		this.cookie			= false;
		this.expired		= (this.options.length == 0)?true:options.expired;
		this.nflpollUoF		= options.nflpollUoF;
		this.nflpollSO		= options.nflpollSO;
		
		this.initializeCookies(this.nflpollUoF,this.nflpollSO);
	},
	initializeCookies: function(cookieUoF, cookieSO){
		nfl.log("nfl.partners.poll.initializeCookies('"+cookieUoF+"','"+cookieSO+"')");
		if (cookieUoF.length > 0) {
			this.cookie	= cookieUoF;
			this.cookieName = "nflpollUoF";
		} else if (cookieSO.length > 0) {
			this.cookie	= cookieSO;
			this.cookieName = "nflpollSO";
		}
		if(this.cookie){
			var cVal	= this.cookie.split("V");
			if(cVal.length > 1){
				if(cVal[1] == 1){
					//remove expired cookie
					var updatedContent = this.skipPoll(nfl.util.cookies.getCookie("nflpollSO"));
					nfl.util.cookies.setCookie("nflpollSO", updatedContent, nfl.util.cookies.getExpDate(7, 0, 0), '/');
				}
				//this.writeCookie(val[0], cookieContent, pollType);
				this.writeCookie(this.cookie);
			}
		}
	},
	writeCookie: function(sCookieContent){
		nfl.log("nfl.partners.poll.writeCookie('"+sCookieContent+"'): type = "+ this.type);
		if(this.type == 1){
			this.handleNoAkamaiCookie("nflpollSO", sCookieContent);
		}else{
			this.handleNoAkamaiCookie("nflpollUoF", sCookieContent);
		}
	},
	getSingleCookie: function(cookieContent) {
	    var polls = cookieContent.split("E");
	    for (var ctr = 0; ctr < polls.length; ctr++) {
	        var poll = polls[ctr].split("V");
	        if (poll[0] == this.id) {
	            return poll;
	        }
	    }
	    return null;
	},
	skipPoll: function(cookieContent) {
	    var currMillis = this.getExpMillis(0, 0, 0);
	    var updateCookieContent = "";
	    var polls = cookieContent.split("E");
	    for (var ctr = 0; ctr < polls.length; ctr++) {
	        var poll = polls[ctr].split("V");
	        if (currMillis < parseInt(poll[2])) {
	            updateCookieContent += polls[ctr] + "E";
	        }
	    }
	    return updateCookieContent;
	},
	getExpMillis: function(days, hours, minutes) {
	    var expDate = new Date;
	    if (typeof days == "number" &&
	        typeof hours == "number" && typeof hours == "number") {
	        expDate.setDate(expDate.getDate() + parseInt(days));
	        expDate.setHours(expDate.getHours() + parseInt(hours));
	        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
	        return expDate.getTime();
	    }
	},
	handleNoAkamaiCookie: function(cookieName, sCookieContent){
		nfl.log("nfl.partners.poll.handleNoAkamaiCookie('"+cookieName+"','"+sCookieContent+"')");
		var cookieContent	= (globalCookieContent != "")?globalCookieContent:(nfl.util.cookies.getCookie(cookieName));
		if (sCookieContent.length > 0 && cookieContent.indexOf(this.id) < 0) {
			var updatedCookie = "";
			var expTime = sCookieContent.split("V");
			if (parseInt(expTime[2]) > 0) {
				globalCookieContent = expTime[0] + "V" + expTime[1] + "V" + this.getExpMillis(0, parseInt(expTime[2]), 0) + "V" + expTime[3] + "V" + expTime[4] + "E" + cookieContent;
				nfl.util.cookies.setCookie(cookieName, unescape(globalCookieContent) , getExpDate(7, 0, 0), '/');	
			}else{
				globalCookieContent = sCookieContent + cookieContent;
				nfl.util.cookies.setCookie(cookieName, unescape(globalCookieContent), null, "/");
			}
		}else{
	        if (cookieContent.indexOf(this.id) > -1) {
	            var poll = this.getSingleCookie(cookieContent);
	            if (null != poll) {
					if(poll.length==5){
						if(this.isExpired(poll[1], poll[3], poll[4])){ this.expired = true; }
					}
	            }
	        }
		}
	},
	isExpired: function(pollType, maxValue, currValue){
		nfl.log("nfl.partners.poll.isExpired('"+pollType+"','"+maxValue+"','"+currValue+"')");
		// if pollType is Unlimited(0) or no cookie content for pollId then poll cannot be expired.
		if(pollType==0) return false;
		if(pollType==1 || pollType==2){ 
			//if session or fixed
			if(currValue<maxValue){
				return false;
			}
		}
		return true;
	},
	getOptionById: function(optionId){
		for(var i=0; i < this.options.length; i++){
			if(this.options[this.options.length].id == optionId){
				return this.options[this.options.length]
				break;
			}
		}
	},
	post: function(option){
		if(typeof option == 'undefined' || this.hasVoted){ return false }
		if(this.loginRequired){
			if(!nfl.global.Authentication.isAuthenticated()){
				this.error			= true;
				this.errorMessage	= "Please Login To Vote!";
				return false;
			}
		}
		/* post option val as vote to this poll */
		//var votedata	= {'poll_id': this.id, 'cmdOption': 'CastVote', 'option_idpollcontent': option.id};
		var postparams	= {'poll_id': this.id, 'option_id': option.id, 'key': this.keys.key, 'hkey': this.keys.hkey,'random':(new Date()).getTime()};
		//voteURL += "?option_id=" + option_id + "&key=" + securityKey + "&hkey=" + hashSecurityKey + "&poll_id=" + poll_id;
		nfl.log("nfl.partners.poll.isExpired: posting to \""+ this.postPath+"?"+ Object.toQueryString(postparams) +"\"\n\rparams:"+ Object.toJSON(postparams));
		new Ajax.Request(this.postPath+"?"+Object.toQueryString(postparams), { onSuccess: this.onXMLResponse.bind(this), onFailure: this.onXMLFailure.bind(this), method: "post", params: postparams});
		
		/*
								id: itemOptions[o].getAttribute('optionId'),
								order: parseInt(itemOptions[o].getAttribute('order')),
								category: itemOptions[o].getAttribute('optionCategory'),
								teamcode: itemOptions[o].getAttribute('teamCode'),
								teamname: (nfl.data.TEAMS[itemOptions[o].getAttribute('teamCode')].city +" "+ nfl.data.TEAMS[itemOptions[o].getAttribute('teamCode')].nickname),
								playerid: itemOptions[o].getAttribute('playerId'),
								contentid: itemOptions[o].getAttribute('contentId'),
								playername: (itemOptions[o].childNodes[1].textContent || itemOptions[o].childNodes[1].innerText)
		*/
	},
	onXMLResponse: function(transport){
		var result		= transport.responseText;
		if (result.match("0")) {
			this.error			= true;
			this.errorMessage	= "The word you entered did not match the image. Please try again.";
			document.fire('polls:poll:postresponse');
			return
		}
		if (result.match("1") || result.match("2")) {
			this.hasVoted	= true;
			this.error			= false;
			parent.setPollEvent("event13");
			document.fire('polls:poll:postresponse');
			return
		}
		if (result.match("3")) {
			this.error			= true;
			this.errorMessage	= "No more votes allowed for this session!";
			document.fire('polls:poll:postresponse');
			return
		}
		this.error			= true;
		this.errorMessage	= "System Busy, Please Try Again!";
		document.fire('polls:poll:postresponse');
		return
	},
	onXMLFailure: function(transport){
		//this.error			= true;
		//this.errorMessage	= "System Busy, Please Try Again!";
		this.hasVoted	= true;
		this.error		= false;
		document.fire('polls:poll:postresponse');
	}
}
nfl.partners.polls = Class.create();
nfl.partners.polls.prototype	= {
	initialize: function(containerid, xmlURL) {
		nfl.log("nfl.partners.polls.initialize");
		this.containerid	= containerid;
		this.xmlURL			= xmlURL;
		//this.xmlURL			= ''
		this.polls			= [];
		this.pollsResponded	= 0;
		if(this.xmlURL != ''){
	 		this.getXML();
	 	}
	 	document.observe('polls:poll:postresponse',this.onPollPostResponse.bind(this));
	},
	getXML: function(){
		nfl.log("nfl.partners.polls.getXML; "+ this.xmlURL);
		this._XHRRequest	= new Ajax.Request(this.xmlURL, {contentType: "text/xml", onSuccess: this.onXMLResponse.bind(this), onFailure: this.onXMLFailure.bind(this), method: "get" });
	},
	onXMLResponse: function(transport){
		if(transport.getResponseHeader("content-type") != 'application/xml'){
			//dude, ninja monkeys raining down foo of DOOM!!
			// alert("nfl.partners.polls.onXMLResponse: Content-Type:"+ transport.getResponseHeader("content-type"));
		}else{
			// alert("Content-Type:"+ transport.getResponseHeader("content-type") +"\n\rXML Object Type:"+ (typeof transport.responseXML) +"\n\rXMLContent:'"+ transport.responseXML.xml +"'\n\rTEXT:"+ transport.responseText);
		}
		nfl.log("nfl.partners.polls.onXMLResponse:\n\r"+ transport.responseText);
		var x				= transport.responseXML;
		try {
			x.firstChild;
		}
		catch(e) {
			x = (new DOMParser()).parseFromString(transport.responseText, "text/xml");
		}
		var numberofpolls	= parseInt(x.getElementsByTagName('polls')[0].getAttribute('numberOfPolls'));
		var items			= x.getElementsByTagName('poll');
		//create array of items
		for(var i=0; i < items.length; i++){
			var item		= items[i];
			var itemOptions	= (item.getElementsByTagName('pollOptions').length > 0)?item.getElementsByTagName('pollOptions')[0].getElementsByTagName('option'):[];
			var pollOptions	= [];
			for(o=0; o < itemOptions.length; o++){
				var playerName	= (itemOptions[o].childNodes.length > 1)?(itemOptions[o].childNodes[1].textContent || itemOptions[o].childNodes[1].innerText):itemOptions[o].childNodes[0].childNodes[0].xml;
				var tOpt	= {
								id: itemOptions[o].getAttribute('optionId'),
								order: parseInt(itemOptions[o].getAttribute('order')),
								category: itemOptions[o].getAttribute('optionCategory'),
								teamcode: itemOptions[o].getAttribute('teamCode'),
								teamname: (nfl.data.TEAMS[itemOptions[o].getAttribute('teamCode')].city +" "+ nfl.data.TEAMS[itemOptions[o].getAttribute('teamCode')].nickname),
								playerid: itemOptions[o].getAttribute('playerId'),
								contentid: itemOptions[o].getAttribute('contentId'),
								playername: playerName
							  }
				//alert("created options json for item #"+ i +" option #"+o+" which had "+ itemOptions[o].childNodes.length +" children nodes");
				pollOptions[pollOptions.length]	= tOpt;
			}
			var tPollJSON	= {
								id: item.getAttribute('pollId'),
								title: item.getAttribute('pollTitle'),
								type: item.getAttribute('pollType'),
								skin: item.getAttribute('pollSkin'),
								skinName: item.getAttribute('skinName'),
								votesAllowed: item.getAttribute('votesAllowed'),
								sessionLength: item.getAttribute('sessionLength'),
								maxAnswers: item.getAttribute('maxAnswer'),
								question: (((item.getElementsByTagName('question')[0].childNodes[0].xml || item.getElementsByTagName('question')[0].textContent).replace(/&lt;/g,'<')).replace(/&gt;/g,'>')),
								successMessage: item.getAttribute('noResultMsg'),
								nflpollUoF: item.getAttribute('nflpollUoF'),
								nflpollSO: item.getAttribute('nflpollSO'),
								expired: eval(item.getAttribute('expired')),
								options: pollOptions
							  }
			this.polls[this.polls.length]	= new nfl.partners.poll(tPollJSON);
		}
		if(numberofpolls > 0){
			this.successMessage	= this.polls[0].successMessage;
			this.expired		= this.polls[0].expired;
			if(document.loaded){
				//call immediately
				if(!this.expired){
					this.write();
				}else{
					$(this.containerid).update("<div id=\"vg-polls-thank-you\">"+ this.successMessage +"</div>");
				}
			}else{
				document.observe('dom:loaded',function(){
					//call on dom load
					if(!this.expired){
						this.write();
					}else{
						$(this.containerid).update("<div id=\"vg-polls-thank-you\">"+ this.successMessage +"</div>");
					}
				}.bind(this));
			}
		}
	},
	onXMLFailure: function(){
		nfl.log("nfl.partners.polls.onXMLFailure");
	},
	write: function(){
		nfl.log("nfl.partners.polls.write");
		var htmlContent	= "";
		for(var i=0; i < this.polls.length; i++){
			var cPoll	 = this.polls[i];
			htmlContent	+= "<div id=\"vg-poll-"+ cPoll.id +"\" class=\"vg-poll\">";
			htmlContent	+= "\t<h3>"+ cPoll.question +"</h3>";
			htmlContent	+= "\t\t<ul>";
			for(var o=0; o < cPoll.options.length; o++){
				var cPollOpt		= cPoll.options[o];
				htmlContent	+= "\t\t\t<li class=\"vg-poll-option vg-poll-team-"+ (cPollOpt.teamcode).toLowerCase() +"\" id=\""+ cPollOpt.id +"\"><input type=\"radio\" value=\""+ cPollOpt.id +"\" name=\""+ cPoll.id +"-option\" id=\""+ cPoll.id +"-"+ cPollOpt.id +"\"><div class=\"vg-poll-option-text\"><h3>"+ cPollOpt.playername +"</h3>"+ cPollOpt.teamname;
				if(cPollOpt.contentid && cPollOpt.contentid != ''){
					htmlContent += " | <a onclick=\"document.fire('polls:video:click',{contentid:'"+ cPollOpt.contentid +"'})\">Video</a>";
				}
				htmlContent += "</div></li>";
			}
			htmlContent	+= "\t\t</ul>";
			htmlContent	+= "</div>";
		}
		htmlContent	+= "<div id=\"vg-polls-button\"><img src=\""+ nfl.global.imagepath +"/img/shim.gif\" width='147' height='28'></div>";
		$(this.containerid).update(htmlContent);
		$('vg-polls-button').observe('click',this.onPollVoteClick.bind(this));
	},
	onVideoClick: function(event){
		/* find thumbnail associated with this contentid, and fire an event from it */
		nfl.log("nfl.partners.polls.onVideoClick");
	},
	onPollVoteClick: function(event){
		nfl.log("nfl.partners.polls.onPollVoteClick");
		/* loop through the poll objects */
		var pollOptions		= [];
		var submitPolls		= true;
		for(var i=0; i < this.polls.length; i++){
			var cPoll	 = this.polls[i];
			/* grab the vote values per poll */
			for(var o=0; o < cPoll.options.length; o++){
				var cPollOpt		= cPoll.options[o];
				var cPollOptEle		= $(cPoll.id +"-"+ cPollOpt.id);
				if(cPollOptEle && cPollOptEle.checked){
					/* an option has been selected */
					pollOptions[i]	= cPollOpt;
					break;
				}
			}
			if(typeof pollOptions[i] == 'undefined'){
				/* this poll has no selected poll option */
				this.polls[i].error			= true;
				this.polls[i].errorMessage	= "Please select an option for "+ this.polls[i].title +"";
				submitPolls	= false;
			}else{
				this.polls[i].error			= false;
				this.polls[i].errorMessage	= '';
			}
		}
		if(submitPolls){
			nfl.log("nfl.partners.polls.onPollVoteClick: all polls are ready for submission.");
			/* reset polls responded counter so we can respond only when all polls have recieved xml response */
			this.pollsResponded	= 0;
			/* call the post method on each poll with it's selected option */
			for(var i=0; i < this.polls.length; i++){
				this.polls[i].post(pollOptions[i]);
			}
		}else{
			this.onPollFailure();
		}
		nfl.log("nfl.partners.polls.onPollVoteClick: exit");
	},
	onPollPostResponse: function(event){
		nfl.log("nfl.partners.polls.onPollPostResponse");
		this.pollsResponded	= (this.pollsResponded + 1);
		nfl.log("nfl.partners.polls.onPollPostResponse: \npollsResponded = "+ this.pollsResponded +"\nthis.polls.length = "+ this.polls.length);
		if(this.pollsResponded == this.polls.length){
			/* all polls have responded to the last post request */
			/* check them for errors */
			var allPollsSuccessful	= true;
			for(var i=0; i < this.polls.length; i++){
				if(!this.polls[i].hasVoted || this.polls[i].error){ 
					allPollsSuccessful = false; break;
				} 
			}
			if(allPollsSuccessful){
				this.onPollSuccess();
			}else{
				this.onPollFailure();
			}
		}
	},
	onPollSuccess: function(){
		nfl.log("nfl.partners.polls.onPollSuccess");
		/* show thank you response */
		$(this.containerid).update("<div id=\"vg-polls-thank-you\">"+ this.successMessage +"</div>");
		//alert("nfl.partners.polls.onPollSuccess: all polls submitted successfully. show thank you message.");
		document.fire("polls:pollsuccess");
	},
	onPollFailure: function(){
		nfl.log("nfl.partners.polls.onPollFailure");
		/* show error messages */
		//alert("nfl.partners.polls.onPollFailure: errors were encountered. show them to the user.");
		var errors			= [];
		for(var i=0; i < this.polls.length; i++){
			if(this.polls[i].error){
				errors[errors.length]	= this.polls[i].errorMessage;
			}
		}
		document.fire('polls:pollfailure',{'errors':errors,'totalpolls':this.polls.length,'polls':this.polls});
	}
}