var scheduledPrimaryQueue = new Array();
var scheduledForAnotherDate = 'NoRace';
var theDateID = '';
function cnnProcessDatePage(dateID) {
	theDateID = dateID;
	scheduledPrimaryQueue = new Array(); // This will be set by csiPopulateDateResults if applicable
	if(dateID == ''){
                $('cnnDateSummary').innerHTML = '<br/>'+getPlaceholderText();
                return;
        }
	CSIManager.getInstance().call('/ELECTION/2008/primary/json/date/'+dateID + '.html','',['cnnDateResults', 'primaryTimeStamp'], [csiPopulateDateResults,csiPopulateTimeStamp], true); 
	CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/notes/date/'+dateID+'.html','','cnnByDateNotes');
	CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/summary/date/'+dateID+'.html','','cnnDateSummary');
}

//if the race is scheduled, make CSI call for each party - but wait for the div/id to exist
function processPrimaryQueue(i, numTries){try{
	if(i>=scheduledPrimaryQueue.length || numTries > 20) return;
	var raceType = "";
	var party 	= (scheduledPrimaryQueue[i].indexOf('DEM')>-1) ? 'DEM' : 'REP';
	var stateAbbr = scheduledPrimaryQueue[i].substr(scheduledPrimaryQueue[i].length-2);

	var stateAbbr;
	if( scheduledPrimaryQueue[i].indexOf('_') > -1 ) {

		var temp = scheduledPrimaryQueue[i].substring( 0, scheduledPrimaryQueue[i].indexOf('_') );
		stateAbbr = temp.substring( temp.length-2);

		raceType = scheduledPrimaryQueue[i].substring(scheduledPrimaryQueue[i].indexOf('_'),scheduledPrimaryQueue[i].length);		
	} else {
		stateAbbr =  scheduledPrimaryQueue[i].substr(scheduledPrimaryQueue[i].length-2); 
	}	
	
	
	if($(scheduledPrimaryQueue[i])==undefined){
		numTries++;
		setTimeout("processPrimaryQueue("+i+","+numTries+")",100);
	}else{
		CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/state/'+party+stateAbbr+raceType+'.html','',scheduledPrimaryQueue[i]);
		
		i++;
		setTimeout("processPrimaryQueue("+i+",0)",100);
	}
}catch(e){return;}}

function cnnReturnDate(date) {
	var dateString = new Date(date);
	dateString = months[dateString.getUTCMonth()]+' '+ dateString.getUTCDate() +', ' + dateString.getUTCFullYear();
	return dateString;
}

///////DATE

function csiPopulateTimeStamp(obj){
	var timeStampText = '';
	if(typeof(obj.lts) != 'undefined'){
		timeStampText = ((getObjValue(obj,'lts')+'') == '0') ? '' : getElectionTimestamp(getObjValue(obj,'lts'),false);
	}
	if(timeStampText.indexOf('ago') > -1){
		$('primaryTimeStamp').className='cnnHtTimestamp';
	}else{
		$('primaryTimeStamp').className='cnnElex_ts over_hour';
	}
	return timeStampText
}

function csiPopulateDateResults(obj){
var returnString = "";
var cnnParties = [ 
	{
		"party":"DEM",
		"header":"DEMOCRATIC",
		"animal_icon":{
			"url":"http://i.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/icon_democrat.gif",
			"width":21,
			"height":14
		},
		"races":[]
	}, {
		"party":"REP",
		"header":"REPUBLICAN",
		"animal_icon":{
			"url":"http://i.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/icon_republican.gif",
			"width":18,
			"height":15
		},
		"races":[]
	}];

var cnnRacesArr = obj['races'];

cnnRacesArr.sort(
		//sort by state code, put primary in front of caucuses, then sort by party
		function(race1,race2){
			var thisCode = race1.code;
			var thatCode = race2.code;
			if(typeof(race1.primarytype) != "undefined") {
				thisCode += (race1.primarytype == "primary") ? 0 : 1;
			}
			if(typeof(race2.primarytype) != "undefined") {
				thatCode += (race2.primarytype == "primary") ? 0 : 1;
			}
			thisCode += race1.party;
			thatCode += race2.party;
			return (thisCode > thatCode) ? 1 : (thisCode < thatCode) ? -1 : 0;
		}
	);

var wdRacesArr = getRacesByDate(theDateID);

// Get thje results table header
returnString += '<table cellspacing="0" cellpadding="0" border="0" width="948"><tr>';
for (var p=0;p<cnnParties.length;p++) {
	var headerDate = '';
	var hasARaceForThisDate = checkIfHasARace(wdRacesArr, cnnParties[p].party);
	if( hasARaceForThisDate == true ) {
		headerDate = getPrettyDate(wdRacesArr[0].electiondate);
	}
	else if( wdRacesArr[0].electiondate == '20080601' ) { headerDate = 'February 24, 2008'; } //Hack for Puerto Rico's Republican header date
	returnString += (p>0)?'<td style="padding-left:13px">':'<td width="465">';
	returnString += '<div class="cnnElexPrimSTitle"><img src="'+cnnParties[p].animal_icon.url+'" width="'+cnnParties[p].animal_icon.width+'" height="'+cnnParties[p].animal_icon.height+'" alt="" border="0" style="vertical-align:top;margin:0px 5px 0px 0px;">'+cnnParties[p].header+' PRIMARIES / CAUCUSES <span>'+headerDate+'</span></div></td>';
}
returnString += '</tr>';

var diffArrLength = (( wdRacesArr.length - cnnRacesArr.length) > 0 )? wdRacesArr.length - cnnRacesArr.length : 0;
for (var s=0;s<wdRacesArr.length;s++) {
	if(wdRacesArr[s].skipDatePage != true ) {
		for (var p=0;p<cnnParties.length;p++) {
			if(wdRacesArr[s].party == cnnParties[p].party) {
				var otherPartyArrNum = (p==0)?1:0;
				var wdOtherParty = cnnParties[otherPartyArrNum].party;
				var wdTheState = wdRacesArr[s].code;
				var wdOtherStateDate = getRaceDate(wdTheState, wdOtherParty);
				if( !raceIsOnThisDate( wdTheState, wdOtherParty, theDateID ) ){
					cnnParties[otherPartyArrNum].races.push(getEmptyRaceTableObj(wdTheState, wdOtherParty, wdOtherStateDate));
				}
				var startIndexSearch4Race = ((s - diffArrLength) > 0) ? (s - diffArrLength) : 0;  // For efficiency
				cnnParties[p].races.push(getRaceFromRacesArr(cnnRacesArr , startIndexSearch4Race ,wdTheState, wdRacesArr[s].party, theDateID ))
			}
		}
	}
}

for (var r=0;r<cnnParties[0].races.length;r++) { //party rows ( both parties should have the smae number of races  or change wdRacesArr config )
	returnString += '<tr valign="top">';
	for (var p=0;p<cnnParties.length;p++) { //parties (  2 = DEM + REP )
	// The states party table cell
		if(typeof(cnnParties[p].races[r])=="undefined") { // just in case there's a problem with wdRacesArr
			returnString += '<td width="465">&nbsp;</td>';
		} else { // Has a race
			var theRace = cnnParties[p].races[r];
			returnString += (p>0)?'<td style="padding-left:13px">':'<td width="465">';
			if(theRace.status.indexOf('cheduled') > 0 || theRace.status == scheduledForAnotherDate) { 
				// 'Scheduled' or 'scheduled' could appear or
				// Case when only one party has a contest on this particular date
				var tmpID = theRace.status+theRace.party+theRace.code;
				
				if( theRace.code == 'TX' ) {				
					if( theRace.party == 'DEM' ) {
						tmpID += '_'+theRace.primarytype;
					} else {
						if( theRace.status == "NoRace" ) { 
							tmpID += '_caucus'; 
						} else { 
							tmpID += '_primary';
						}
					}
				}
				
				
				returnString += getDateNonResultsTable(tmpID);
				scheduledPrimaryQueue[scheduledPrimaryQueue.length] = tmpID;
			} else {
				returnString += '<div class="cnnElexPrimStateTable">';
				var tmpResultsTable = getDateResultsTable(theRace,cnnParties[p]);
				returnString += tmpResultsTable+'</div>';
			}
			returnString += '<div style="padding:0px 0px 7px 0px;"></div></td>';
		} // end if Has a race
	} //end loop on parties
	returnString += '</tr>';
} //end loop on party rows
returnString += '</table>';
processPrimaryQueue(0,0);
return returnString;
}

function getRaceFromRacesArr(theRacesArr , startIndex , theState, theParty, theDate ) {
	var noRaceFound = true;
	var returnRaceObj = [];
	for (var i=startIndex;i<theRacesArr.length && noRaceFound == true;i++) {
		if(theRacesArr[i].code == theState && theRacesArr[i].party == theParty) {
			noRaceFound = false;
			returnRaceObj = theRacesArr[i];
		}
	}
	if(noRaceFound == true) {
		for (var i=0;i<startIndex && noRaceFound == true;i++) {
			if(theRacesArr[i].code == theState && theRacesArr[i].party == theParty) {
				noRaceFound = false;
				returnRaceObj = theRacesArr[i];
			}
		}
	}
	if(noRaceFound == true) {
		returnRaceObj = getEmptyRaceTableObj(theState, theParty, theDate);
	}
	return returnRaceObj;
}

function checkIfHasARace(wdRacesArr, party){
	var hasARaceForThisDate = false;
	if( typeof(wdRacesArr) == 'object' && wdRacesArr.length >= 0 ) {
		for (var i=0;i<wdRacesArr.length && hasARaceForThisDate == false;i++) {
			if(wdRacesArr[i].party == party) {
				hasARaceForThisDate = true;
			}
		}
	}
	return hasARaceForThisDate;
}

function getDateNonResultsTable ( cnnMessageID )
{				
	var returnString = '<div class="waitingTableTop">\
		<table><tbody><tr>\
			<td style="border-left: 1px solid rgb(218, 218, 218); border-right: 1px solid rgb(218, 218, 218); padding: 20px; height: 230px;">\
				<div><span id="'+cnnMessageID+'"></span></div>\
			</td>\
		</tr></tbody></table><div class="bottom"></div>\
	</div>';
	return returnString;
}

function getDateResultsTable(theRace,cnnParties){
	var raceCanShowMap = getHasCountyMap(theRace.code, theRace.party);
	var returnString = '<table cellspacing="0" cellpadding="0" border="0" width="465">\
	<colgroup>\
		<col width="116">\
		<col width="54">\
		<col width="94">\
		<col width="72">\
		<col width="41">\
		<col width="30">\
		<col width="58">\
	</colgroup>\
	<tr class="header">\
		<td class="begin_left"><div><span>Race</span></div></td>\
		<td><div><span>Status</span></div></td>\
		<td class="cand_mid"><div><span>Candidate</span></div></td>\
		<td><div><span>';
	returnString += theRace.votelabel;
	returnString += '</span></div></td><td><div><span>';
	returnString += (theRace.primarytype.match('aucus'))?'':'Vote';
	returnString += '%</span></div></td>\
		<td><div><span>Del*</span></div></td>\
		<td class="end_right"><div><span>Precincts</span></div></td>\
	</tr>';
	var rows = theRace.candidates.length;
	for (var i = 0; i< theRace.candidates.length;i++) { //candidates
		if (i ==0) {
			returnString += '<tr valign="top">\
		<td rowspan="'+rows+1+'">\
			<div class="state_name"><b><a href="/ELECTION/2008/primaries/results/state/#'+theRace.code+'">'+theRace.state+'</a></b><br>';
			returnString += (theRace.primarytype.match('aucus'))?'Caucuses':'Primary';
			var timestamp = (theRace.ts == 0) ? '' : getElectionTimestamp(getObjValue(theRace,'ts'),true);
			returnString += '<br>\
				<span style="font-size:11px;">'+timestamp+'<br><br>';
			if(raceCanShowMap && theRace.countyresults) {
				returnString += '<div style="color:#949494;" align="left"><b>County:</b> <a href="/ELECTION/2008/primaries/results/county/#'+theRace.code+theRace.party+theRace.primarytype+'"><b><span style="font-size:11px;">Table</span></b></a> | <a href="/ELECTION/2008/primaries/results/county/#'+theRace.code+theRace.party+'MAP'+theRace.primarytype+'"><b><span style="font-size:11px;">Map</span></b></a></div>';
			} else if(theRace.countyresults){
				returnString += '<a href="/ELECTION/2008/primaries/results/county/#'+theRace.code+theRace.party+theRace.primarytype+'"><b>County Results</b></a><br>';
			}
			if(theRace.xpoll){
				returnString += '<a href="/ELECTION/2008/primaries/results/epolls/#'+theRace.code+theRace.party+'"><b>';
				returnString += (theRace.primarytype.match('aucus')) ? 'Entrance' : 'Exit';
				returnString += ' Polls</b></a><br>';
			}
			returnString += '</span>\
			</div>\
		</td>\
		<td class="status"><img src="'+getStatusGraphic(theRace.status)+'" width="45" height="42" alt="" border="0" vspace="6"></td>\
		<td class="cand bord_b"><div class="pad">';
		
		returnString += getCandidateLink(theRace.candidates[i]);
			
		returnString += '</div></td>\
		<td class="votes bord_b"><div class="pad">'+theRace.candidates[i].cvotes+'</div></td>\
		<td class="bord_b"><div class="pad"><b>'+theRace.candidates[i].vpct+'%</b></div></td>\
		<td class="bord_b"><div class="pad"><b>'+theRace.candidates[i].tdelegates+'</b></div></td>\
		<td rowspan="'+rows+'" class="report"><div class="pad"><b>'+theRace.pctsrep+'%</b><br><span \style="font-size:10px;">reporting</span></div></td>\
	</tr>';
		} else if(i==(theRace.candidates.length-1)){
			returnString += '\
	<tr valign="top">\
		<td></td>\
		<td class="cand"><div class="pad">';
	
		returnString += getCandidateLink(theRace.candidates[i]);

		returnString += '</div></td>\
		<td class="votes"><div class="pad">'+theRace.candidates[i].cvotes+'</div></td>\
		<td><div class="pad"><b>'+theRace.candidates[i].vpct+'%</b></div></td>\
		<td><div class="pad"><b>'+theRace.candidates[i].tdelegates+'</b></div></td>\
	</tr>';
		} else {
			returnString += '\
	<tr valign="top">\
		<td></td>\
		<td class="cand bord_b"><div class="pad">';
	
		returnString += getCandidateLink(theRace.candidates[i]);	

		returnString += '</div></td>\
		<td class="votes bord_b"><div class="pad">'+theRace.candidates[i].cvotes+'</div></td>\
		<td class="bord_b"><div class="pad"><b>'+theRace.candidates[i].vpct+'%</b></div></td>\
		<td class="bord_b"><div class="pad"><b>'+theRace.candidates[i].tdelegates+'</b></div></td>\
	</tr>';
		} //end if
	} //end candidates for loop
	returnString += '</table>'
	returnString += '<div><img src="http://i.cdn.turner.com/cnn/ELECTION/2008/primaries/images/table_footer_results.gif" width="465" height="7" alt="" border="0"></div>';
	return returnString;
}

function getEmptyRaceTableObj(state, party, date) {
	var emptyRaceObj = {
      "status" : scheduledForAnotherDate,
      "party" : party,
      "electiondate" : date,
      "code" : state
    };
	return emptyRaceObj;
}
/////////render functions end

function loadDateResultInfo(path){
	YAHOO.util.History.navigate("val", path.substring(path.indexOf('#')).replace(/#/,''));
}

var cnnDocDomain = '';
if(location.hostname.indexOf('cnn.com')>0) {cnnDocDomain='cnn.com';}
if(location.hostname.indexOf('turner.com')>0) {if(document.layers){cnnDocDomain='turner.com:'+location.port;}else{cnnDocDomain='turner.com';}}
if(cnnDocDomain) {document.domain = cnnDocDomain;}
// DO NOT PUT ANYTHING BENEATH THIS!
