/**
 * Polls.js
 * This file should be hosted with the polls project. It simply combines
 * the two function libraries, as they are always loaded together, saving
 * a request.
 */
/**
 * Formerly of pollview.js
 */
function checkOptions(poll_id, isLoginRequired, serverPath, divId){
	if(isLoginRequired=="true"){
		if(readCookie("userId").length==0){
			$('errorMsg'+divId).update("Please Login To Vote!");
			return;
		}
	}
	
	if(poll_id.length>0){
		var radio = document.getElementsByTagName("INPUT");
		var isChecked = false;
		var selectedText = "";
		var optionName = "option_id" + divId;		
		for(var i=0; i<radio.length; i++){
		  if(radio[i].checked && (radio[i].type=="radio") && radio[i].name == optionName){
		  	selectedText = radio[i].value;
		  	isChecked= true;
		  }
		}
		
		if(isChecked){
			var key_master = document.getElementById("key_master" + divId).value;
			if(key_master.length>0){
				var key = document.getElementById("key" + divId).value;					
				if(key.length==0){
					$('errorMsg'+divId).update("The security key cannot be left blank.");
				}else{
					submitVote(serverPath+"/castvote", selectedText, key, key_master, poll_id, divId);	
				}
			}else{
				submitVote(serverPath+"/castvote", selectedText, "", "", poll_id, divId);
			}
		}else{
			$('errorMsg'+divId).update("Select an Answer to Vote!");
		}
	}else{
		$('errorMsg'+divId).update("Cannot Vote, Page is Broken!");
	}		
}

function submitVote(voteURL, option_id, securityKey, hashSecurityKey, poll_id, divId){

	castVoteFlag = poll_id;
    voteURL += "?option_id=" + option_id + "&key=" + securityKey + "&hkey=" + hashSecurityKey + "&poll_id=" + poll_id;
    var myAjax = new Ajax.Request(voteURL, {
    	method: 'post',
    	onSuccess: function(transport) {     
    		parseInfo(transport.responseText, divId);
    	}
     }); 
}

function parseInfo(result, divId){
  		if (result.match("0")){
  			$('errorMsg'+divId).update("The word you entered did not match the image. Please try again.");
	}else if (result.match("1") || result.match("2")){ 			
			var element = document.getElementById(divId);
			var divs = element.immediateDescendants();
			
			if(divs[0].tagName=="DIV")
			{
				divs[0].style.display = "";
				divs[1].style.display = "none";
			}
			else if(divs[0].tagName=="SCRIPT")
			{
				divs[1].style.display = "";
				divs[2].style.display = "none";
			}
			
		//$('divId')
			//analytics: poll event, which is on the home page
  			parent.setPollEvent("event13");
  			document.fire("polls:pollsuccess");
	/*}else if (result.match("2")){
		$('errorMsg'+divId).update("Please enable cookies to cast your vote.");
	*/
	}else if (result.match("3")){
		$('errorMsg'+divId).update("No more votes allowed for this session!");
  		}else{
  			$('errorMsg'+divId).update("System Busy, Please Try Again!");
  		}
   }
      
   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 "";
}    

function getPollView(pollURL){
	pollURL = escape(pollURL);
    var myAjax = new Ajax.Request(pollURL, {
    	onSuccess: function(transport) {     
    		return transport.responseText;
    	}
     }); 
}
/**
 * Formerly of IframeHelper.js
 */
var castVoteFlag;

function showPoll(pollServerPath, location, cid, width, nflpollUoF, nflpollSO, divId) {
	var url 	= pollServerPath + '/vote';
	var params	= ('random=' + Math.floor(Math.random()*10000));
	if (location != null && location != '') { params += ('&loc=' + location); }
	if (cid != null && cid != '') { params += ('&cid='+ cid); }
	if (width != null) { params += ('&width='+ width); }
	if (castVoteFlag != null) {
		params += ('&castVoteFlag=' + castVoteFlag);
	}
	new Ajax.Request(url,{
		method:'get',
		onSuccess: function(transport){
			var response = transport.responseText || "";
			$(divId).update(response);
			setIframeHeight(nflpollUoF, nflpollSO, divId);
		},
		onFailure: function(){},
		parameters: params.toQueryParams()
	});
}

var docLoc = document.location + '';

var globalCookieContent = '';
if(docLoc.indexOf("/gamecenter") == -1)
{
	//if (document.domain.indexOf("nfl.com") != -1) document.domain = 'nfl.com';
}

function getDocHeight(doc) {
  var docHt = 0, sh, oh;
  if (doc.height) docHt = doc.height;
  else if (doc.body) {
  	if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
  	if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
  	
  	if(isNaN(oh)==0){
  		if (sh && oh) docHt = Math.max(sh, oh);
  	}else{
  		docHt=1;
  	}
  }
  return docHt;
};
	
function setIframeHeight(cookieUoF, cookieSO, divId) {
 var cookieContent = "";
 var cookieName = "";
 
 if(cookieUoF.length>0){
   cookieContent=cookieUoF;
   cookieName="nflpollUoF";
 }else if(cookieSO.length>0){
	 cookieContent=cookieSO;	   
   cookieName="nflpollSO";
 }else{
	 cookieName="";
 }
 
  if(cookieName.length>0){
  	var val = cookieContent.split("V"); 
  	if(val.length>1){
  	var pollID = val[0];
  	var pollType = val[1];
  		 
  	// remove cookie if expired in case pollType==SessionOnly
  	if(pollType==1){
  		//alert("[SO] Remove Cookie If Expired");
  		removeExpiredCookie("nflpollSO");			
  	}
  		writeJSCookie(pollID,cookieContent, pollType, divId);
  	}
	}
};
	
function removeExpiredCookie(cookieName){
	var cookieContent = getCookie(cookieName);
	var updatedContent = skipPoll(cookieContent);
	setCookie(cookieName, updatedContent, getExpDate(7, 0, 0), '/');
	return updatedContent;
};

function skipPoll(cookieContent){
	var currMillis = 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;
};

function writeJSCookie(pollID,sCookieContent, pollType, divId){
  if(pollType==1){
    handleNoCookieAkamiCase("nflpollSO",pollID,sCookieContent, divId);
  }else{
    handleNoCookieAkamiCase("nflpollUoF",pollID,sCookieContent, divId);
  }
};
		
// Check if first time poll then append new cookie content to existing cookie.
function handleNoCookieAkamiCase(cookieName, pollId, sCookieContent, divId){
	var cookieContent = '';
	if (globalCookieContent != '') {
		cookieContent = globalCookieContent;
	} else {
		cookieContent = getCookie(cookieName);
	}

	// if no cookie content for specific poll. **new element inside of cookie**
	if(sCookieContent.length > 0 && cookieContent.indexOf(pollId)<0){
		var updatedCookie = ""; 
		
		var expTime = sCookieContent.split("V");
		if(parseInt(expTime[2])>0){ //session only case
			updatedCookie = expTime[0]+"V"+expTime[1]+"V"+getExpMillis(0, parseInt(expTime[2]), 0)+"V"+expTime[3]+"V"+expTime[4]+"E"+cookieContent;
			globalCookieContent = updatedCookie;
			setCookie(cookieName, unescape(updatedCookie) , getExpDate(7, 0, 0), '/');	
		}else{ //ulimited or fixed case
			updatedCookie = sCookieContent + cookieContent;
			globalCookieContent = updatedCookie;
			setCookie(cookieName, unescape(updatedCookie) , null, '/');
		}
		
	}else{ //if we have element inside cookie

		if(cookieContent.indexOf(pollId)>-1){
			
			var poll = getSingleCookie(cookieContent, pollId);
			if(null!=poll){
				handlePollExipred(cookieName, poll, divId); //flip if curr votes >= max votes
			}
			
		}
	}
};
	
/**
*
*/
function getExpMillis(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();
	}
};


/**
* Return Poll Array
* 0 - PollID, 1-PollType, 2-Exp, 3-Max, 4-Current

*/	
function getSingleCookie(cookieContent, pollId){
	var polls = cookieContent.split("E");
	for(var ctr=0;ctr<polls.length;ctr++){
		var poll = (polls[ctr]).split("V");
		if(poll[0]==pollId){
			return poll;
		}
	}	
	return null;
};

function handlePollExipred(cookieName, cookieValue, divId){
	
	if(cookieValue.length==5){
		if(isPollExipred(cookieValue[0], cookieValue[1], cookieValue[3],cookieValue[4])){ 			
 			var element = document.getElementById(divId);
 			var divs = element.immediateDescendants();
 			divs[0].style.display = "";
 			divs[1].style.display = "none";
		}
	}
};
	
function isPollExipred(pollId, 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; 
};
/**/