var jsonPath = '/ELECTION/2008/primary/json/candidate/';
var loadingCandidateResults = false;
var partyAbbr = 'DEM';
function loadCandidateResultInfo(val){
        if(loadingCandidateResults) return;
        if(val==''){
	        $('resultsTable').innerHTML = '<br/>'+getPlaceholderText('padding: 25px 0px 0px 165px;');
                return;
        }
        loadingCandidateResults = true;
        CSIManager.getInstance().call(jsonPath+val+'.html','',['resultsTable','candidateBlurb'], [csiPopulateCandidateResults,csiPopulateCandidateBlurb], true);
}

//called by dropdown - if on state page
var currentCandidate = '';
function loadCandidateByUrl(cnnCandidate){
        var cnnCandidate = cnnCandidate.substring(cnnCandidate.indexOf('#')+1);
	if(cnnCandidate == currentCandidate){ return; }
	currentCandidate = cnnCandidate;
	YAHOO.util.History.navigate("val", cnnCandidate);
} 	

//populates the blurb section of primary results
function csiPopulateCandidateBlurb(obj) {

if (obj.party.toUpperCase() == 'DEM') {
var unpledgedLabel='Superdelegates';
}else if(obj.party.toUpperCase() == 'REP'){
var unpledgedLabel='Unpledged RNC*';
}

	var winnerHTML = (obj.winner) ? '<div style="width:154px;height:35px;background:#055AAD;color:#ffffff;font-weight:bold;font-size:24px;text-align:center;"><div style="padding-top:9px;">WINNER!</div></div>' : '';
	var partyIconHTML = '<img src="http://i.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/r.gif" width="15" height="15" alt="" border="0" />';
	var scorecardLinkText = 'Full Republican Results';
	if(getObjValue(obj,'party').toUpperCase().indexOf('DEM') > -1){
		partyIconHTML = '<img src="http://i.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/d.gif" width="15" height="15" alt="" border="0" />';
		scorecardLinkText = 'Full Democratic Results';
	}
	document.title = 'Election Center 2008: Results for '+getObjValue(obj,"fname")+' '+getObjValue(obj,"lname")+' - Elections & Politics news from CNN.com';
	var resultsHTML = '';
	resultsHTML += '<div id="cnnElexRBC_left">';
	resultsHTML += '<div class="cnnElexPrim_head"><h1>RESULTS:<br/><b>'+getObjValue(obj,"fname")+' '+getObjValue(obj,"lname")+'&nbsp;'+partyIconHTML+'</b></h1></div>';
	resultsHTML += '<div><img src="http://i.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/candidate/bio/'+getObjValue(obj,"id")+'.jpg" width="154" height="211" alt="'+getObjValue(obj,"fname")+' '+getObjValue(obj,"lname")+'" border="0">'+winnerHTML+'</div>';
	resultsHTML += '<div style="padding:10px 0px 0px 0px;">';
	resultsHTML += '<div style="font:normal 16px/19px helvetica, arial;">Delegate Total*</div>';
	resultsHTML += '<div style="font:bold 48px/53px helvetica, arial;">'+commify(getObjValue(obj,"totaldelegates"))+'</div>';
	resultsHTML += 'Pledged: <b>'+commify(getObjValue(obj,"tpledged"))+'</b><br/>'+unpledgedLabel+': <b>'+commify(getObjValue(obj,"tunpledged"))+'</b>';
	resultsHTML += '<div style="padding-top:14px;font:normal 12px/14px helvetica, arial;">All candidates:<br/><a href="/ELECTION/2008/primaries/results/scorecard/#'+getObjValue(obj,'party').toUpperCase().substring(0,1)+'"><b>'+scorecardLinkText+'</b></a></div>';
	resultsHTML += '<div style="background-color:#DADADA;margin:7px 0px 10px 0px;height:1px;overflow:hidden;"></div>';
	resultsHTML += '<div id="candidateDescription"></div><br/><br/>';
	resultsHTML += '<a href="/ELECTION/2008/candidates/'+getObjValue(obj,'fname').toLowerCase()+'.'+getObjValue(obj,'lname').toLowerCase()+'.html"><b>Full profile &raquo;</b></a>';
	resultsHTML += '</div></div>';
	CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/notes/candidate/'+getObjValue(obj,'id')+'.html','','candidateNotes');
	setCandidateDescription(getObjValue(obj,'id'));
	var listBoxOrder = (getObjValue(obj,'party').toUpperCase().indexOf('DEM') > -1) ? ['DEMOCRATS','REPUBLICANS'] : ['REPUBLICANS','DEMOCRATS'];
	try{rearrangeSelectBox('cnnDD_elexCand_list',listBoxOrder,true);}catch(e){}
	return resultsHTML;
}

function setCandidateDescription(id){
	if($('candidateDescription') !== undefined){
		CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/candidate_blurbs/'+id+'.html','','candidateDescription');
	}else{
		setTimeout("setCandidateDescription("+id+")",10);
	}
}

var candidateResultsObj;
function sortCandidateTable(criteria,primaryType,linkId){
	if($(linkId).className == "active"){ return; }
	if(candidateResultsObj){
		var tempArray = new Array();
		var otherArray = new Array();
		var statesArray = candidateResultsObj.states;
		for(var i=0; i<statesArray.length; i++){
			if(statesArray[i].primarytype.toLowerCase() == primaryType.toLowerCase()){
				tempArray[tempArray.length] = statesArray[i];
			}else{
				otherArray[otherArray.length] = statesArray[i];
			}
		}
		tempArray = tempArray.sort(criteria);
		candidateResultsObj.states = tempArray.concat(otherArray);
		toggleSortLink(linkId);
		$('resultsTable').innerHTML = csiPopulateCandidateResults(candidateResultsObj,linkId);
	}
}

//gets current className from link
function getSortLinkStatus(linkId,presorted){
	var classText = '';
	try{
	if((presorted == 'resultsTable') && (linkId.indexOf('Time') > -1)){
		classText = 'active';
	}else if(linkId.indexOf('primary') == presorted.indexOf('caucus')){
		classText = $(linkId).className;
	}else if(linkId == presorted){
		classText = 'active';
	}else{
		classText = '';
	}
	}catch(e){classText = '';}
	return classText;
}

//sort states by state name
function sortByState(state1, state2){
	if( state1.state == 'Unallocated Delegates' ) { return 1; }
	else if( state2.state == 'Unallocated Delegates' ) { return -1; }
	var s1 = state1.state.toLowerCase();
	var s2 = state2.state.toLowerCase();
	return ((s1 < s2) ? -1 : ((s1 > s2) ? 1 : 0));
}

//sort by whether or not it's today...do alphabetical if both are
function sortByIsToday(state1,state2){
	if( state1.state == 'Unallocated Delegates' ) { return 1; }
	else if( state2.state == 'Unallocated Delegates' ) { return -1; }
	var s1 = state1.electiondate;
	var s2 = state2.electiondate;
	var todayElectionDate = dateToYYYYMMDD(getToday());
	if(s1 == todayElectionDate && s2 != todayElectionDate){
		return -1;
	}else if(s1 != todayElectionDate && s2 == todayElectionDate){
		return 1;
	}else{
		return sortByState(state1,state2);
	}
}

//sort states by 'most recent' timestamp
function sortByTimestamp(state1, state2){
	if( state1.state == 'Unallocated Delegates' ) { return 1; }
	else if( state2.state == 'Unallocated Delegates' ) { return -1; }
	var s1 = state1.ts;
	var s2 = state2.ts;
	// Put those with empty ts - put at the end of the list.
	if(s1 == 0 || isNaN(s1)) { s1 = -1;}
	if(s2 == 0 || isNaN(s2)) { s2 = -1; }
	
	if(state1.electiondate == dateToYYYYMMDD(getToday()) || state2.electiondate == dateToYYYYMMDD(getToday())){
		return sortByIsToday(state1,state2);
	}

	return (s1 > s2) ? -1 : (s1 < s2) ? 1 : sortByElectionDate(state1,state2);
}

function reverseSort(answer){
	return (answer == 1) ? -1 : (answer == -1) ? 1 : 0
}

//sort states by election date
function sortByElectionDate(state1, state2){
	if( state1.state == 'Unallocated Delegates' ) { return 1; }
	else if( state2.state == 'Unallocated Delegates' ) { return -1; }
	if(getObjValue(state1,'electiondate')==''){
                state1.electiondate = getRaceDate(getObjValue(state1,'code'),partyAbbr);
        }
	if(getObjValue(state2,'electiondate')==''){
                state2.electiondate = getRaceDate(getObjValue(state2,'code'),partyAbbr);
        }
	var s1 = parseInt(state1.electiondate);
	var s2 = parseInt(state2.electiondate);
	// Put those with empty dates at the end of the list.
	if(isNaN(s1)) { s1 = 99999999;}
	if(isNaN(s2)) { s2 = 99999999; }
	return ((s1 < s2) ? -1 : ((s1 > s2) ? 1 : sortByState(state1,state2)));
}

//toggles active/inactive sort link
function toggleSortLink(linkId){
	$(linkId).className = "active";
        if(linkId.indexOf("Date") > -1){
        	$(linkId.replace(/Date/,"State")).className = "";
        }else{
        	$(linkId.replace(/State/,"Date")).className = "";
        }
}

//csiCallback function for building the results table
function csiPopulateCandidateResults(obj,presorted){

if (obj.party == 'Dem') {
var unpledgedLabel='';
unpledgedLabel += 'SUPERDEL*';

}else if(obj.party == 'Rep'){
var unpledgedLabel='UNPL. RNC*';
}
        partyAbbr = (getObjValue(obj,'party').toUpperCase().indexOf('DEM')>-1) ? 'DEM' : 'REP';
	var returnString = "";
	if(presorted == 'resultsTable'){
		obj.states = obj.states.sort(sortByTimestamp);
	}
        candidateResultsObj = obj;
        var divider = '<tr><td class="divider" colspan="8"><div></div></td></tr>';
        var tableFooter = '</table><div class="bottom"></div></div>';

	//create sort links for primaries
	var primarySortLinks = '<div style="padding:0px 0px 10px 0px;">Sort state primaries by: '+getLinkForPolltype('primary',presorted)+'</div>';

	//create sort links for caucuses (cauci?...)
	var caucusSortLinks  = '<div style="padding:10px 0px 10px 0px;">Sort state caucuses by: '+getLinkForPolltype('caucus',presorted)+'</div>';

	//primary table header
	var primaryTable = '<div class="cnnElexPrimCandTable"><table cellspacing="0" cellpadding="0" border="0" width="765"><colgroup><col width="207"><col width="68"><col width="110"><col width="60"><col width="66"><col width="66"><col width="66"><col width="122"></colgroup><tr class="header"><td class="begin_left"><div><span>Primary</span></div></td><td><div><span>Status*</span></div></td><td><div><span>Votes</span></div></td><td><div><span>Vote%</span></div></td><td colspan="3" valign="top" class="del_mid"><div style="height:20px;margin-bottom:2px;"><span>Delegates</span></div><div class="sub">PLEDGED</div><div class="sub">'+unpledgedLabel+'</div><div class="sub">TOTAL</div></td><td class="end_right"><div><span>Precincts</span></div></td></tr>';

	//caucus table header
	var caucusTable = '<div class="cnnElexPrimCandTable"><table cellspacing="0" cellpadding="0" border="0" width="765"><colgroup><col width="207"><col width="68"><col width="110"><col width="60"><col width="66"><col width="66"><col width="66"><col width="122"></colgroup><tr class="header"><td class="begin_left"><div><span>Caucuses</span></div></td><td><div><span>Status*</span></div></td><td><div><span>State Delegates*</span></div></td><td><div><span>%</span></div></td><td colspan="3" valign="top" class="del_mid"><div style="height:20px;margin-bottom:2px;"><span>Delegates</span></div><div class="sub">PLEDGED</div><div class="sub">'+unpledgedLabel+'</div><div class="sub">TOTAL</div></td><td class="end_right"><div><span>Precincts</span></div></td></tr>';

	var states = obj.states;
        var caucusCount = 0;
        var primaryCount = 0;
	for(var i=0; i<states.length; i++){
            switch(getObjValue(states[i],'primarytype').toLowerCase()){
                        case "primary":

                                        if(primaryCount > 0){
                                                primaryTable += divider;
                                        }
                                        primaryCount++;
                                        primaryTable += generateResultsRow(states[i]);
                                        break;
                        case "caucus":

                                        if(caucusCount > 0){
                                                caucusTable += divider;
                                        }
                                        caucusCount++;
                                        caucusTable += generateResultsRow(states[i]);
                                        break;
                        default:
                                        break;
                }
	}

	//only show sort-links if there are multiple entires
	primaryTable = (primaryCount > 1) ? primarySortLinks + primaryTable : '<br/>'+primaryTable;
	caucusTable = (caucusCount > 1) ? caucusSortLinks + caucusTable : '<br/>'+caucusTable;

	//only show table if there is at least one entry
	primaryTable = (primaryCount>0) ? primaryTable+tableFooter : "";
	caucusTable = (caucusCount>0) ? caucusTable+tableFooter : "";



	var timeStampText = (obj.lts == 0) ? '' : getElectionTimestamp(obj.lts,false);

	if(timeStampText.indexOf('ago') > -1){
		$('primaryTimeStamp').className='cnnHtTimestamp';
	}else{
                $('primaryTimeStamp').className='cnnElex_ts over_hour';
        }
	$('primaryTimeStamp').innerHTML = timeStampText;

	returnString = (primaryTable!='' || caucusTable !='') ? primaryTable + caucusTable : "There are currently no results for this candidate.";
	loadingCandidateResults = false;
	return returnString;
}

//generates a set of sort links for a poll type (caucus or primary)
function getLinkForPolltype(polltype,presorted){
	return '<a id="'+polltype+'TimeSortLink" href="javascript:sortCandidateTable(sortByTimestamp,\''+polltype+'\',\''+polltype+'TimeSortLink\');" class="'+getSortLinkStatus(polltype+'TimeSortLink',presorted)+'"><b>Most recent</b></a> | <a id="'+polltype+'DateSortLink" href="javascript:sortCandidateTable(sortByElectionDate,\''+polltype+'\',\''+polltype+'DateSortLink\');" class="'+getSortLinkStatus(''+polltype+'DateSortLink',presorted)+'"><b>Date</b></a> | <a id="'+polltype+'StateSortLink" href="javascript:sortCandidateTable(sortByState,\''+polltype+'\',\''+polltype+'StateSortLink\');" class="'+getSortLinkStatus(''+polltype+'StateSortLink',presorted)+'"><b>Alphabetical order</b></a>';
}

//if data cannot suppress later elections, we'll use this - difficult to test with - due to 'now' calculation.
function notAfterToday(state,ts){
	var today = new Date(ts);
	var month = today.getMonth()+1;
	var date  = today.getDate();
	month = (month < 10) ? '0'+month : month;
	date  = (date < 10) ? '0'+date : date;
	var nowDate = (ts == 0) ? 20080103 : parseInt(''+today.getFullYear()+month+date);
	var eDate = parseInt(state.electiondate);
	return(eDate <= nowDate);
}

//Generates a single row from a state object for the results table
function generateResultsRow(stateObj){
	try{
        var status = '';
	if(	(stateObj.status.toLowerCase() == 'projected' && parseInt(stateObj.voteorder) == 1) ||
		(stateObj.status.toLowerCase() == 'called' && parseInt(stateObj.voteorder) == 1) ||
		stateObj.status.toLowerCase() == 'processing' ||
		stateObj.status.toLowerCase() == 'scheduled' ||
		stateObj.status.toLowerCase() == 'voting'){
                status = '<img src="'+statusGraphicsArray[stateObj.status.toLowerCase()]+'" alt="" border="0" height="42" vspace="10" width="45">';
        }else if(stateObj.status.toLowerCase() == 'projected'){
		status = '<img src="'+statusGraphicsArray['processing']+'" alt="" border="0" height="42" vspace="10" width="45">';
	}else{
     if (stateObj.voteorder !=0 ) {
	 status = '<div class="pad">'+getOrdinalNum(stateObj.voteorder)+'<br><span style="font-size: 12px;">place</span></div>';
	}
        	//status = '<div class="pad"><br></div>';
	}
	var row = '<tr valign="top">';
	row += '<td><div class="state_name"><h2>';
	if( stateObj.status.toLowerCase() != 'scheduled' && stateObj.status.toLowerCase() != '') {
		row += '<a href="/ELECTION/2008/primaries/results/state/#'+getObjValue(stateObj,'code')+'">';
	}
	row += '<b>'+getObjValue(stateObj,'state')+'</b>';
	if( stateObj.status.toLowerCase() != 'scheduled' && stateObj.status.toLowerCase() != '') {
		row += '</a>';
	}
	row += '</h2>';
	if(getObjValue(stateObj,'electiondate')==''){
		stateObj.electiondate = getRaceDate(getObjValue(stateObj,'code'),partyAbbr);
	}
	var electionDate = getObjValue(stateObj,'electiondate')+'';
	if (electionDate != "") {
		row += '<span style="font-size:11px;"><b>';
		if( stateObj.status.toLowerCase() != 'scheduled' && stateObj.status.toLowerCase() != '') {
			row += '<a href="/ELECTION/2008/primaries/results/dates/#'+electionDate+'">';
		}
		row += months[parseInt(electionDate.substring(4,6))-1]+' '+electionDate.substring(6)+', '+electionDate.substring(0,4);
		if( stateObj.status.toLowerCase() != 'scheduled' && stateObj.status.toLowerCase() != '') {
			row += '</a>';
		}
		row += '</b></span><br/>';
	}
	var timestamp = (getObjValue(stateObj,'ts') == '0') ? '' : getElectionTimestamp(getObjValue(stateObj,'ts'), true).replace(/U/,'u').replace(/cnnGryTmeStmp/,'');
	row += '<span style="font-size:11px;color:#000000;">'+timestamp+'</span>';
	row += '<span style="font-size:11px;">';
	var raceCanShowMap = getHasCountyMap(getObjValue(stateObj,'code'), partyAbbr);
	if(stateObj.countyresults && raceCanShowMap){
		row += '<div style="color:#949494;" align="left"><b>County:</b> <a href="/ELECTION/2008/primaries/results/county/#'+getObjValue(stateObj,'code')+partyAbbr+getObjValue(stateObj,'primarytype')+'"><b><span style="font-size:11px;">Table</span></b></a> | <a href="/ELECTION/2008/primaries/results/county/#'+getObjValue(stateObj,'code')+partyAbbr+'MAP'+getObjValue(stateObj,'primarytype')+'"><b><span style="font-size:11px;">Map</span></b></a></div>';
	} else if (stateObj.countyresults) {
		row += '<a href="/ELECTION/2008/primaries/results/county/#'+getObjValue(stateObj,'code')+partyAbbr+getObjValue(stateObj,'primarytype')+'"><b>County Results</b></a><br/>';
	}
	if(stateObj.polltype == undefined){ stateObj.polltype = 'exit'; }
	row += (stateObj.xpoll == true) ? '<a href="/ELECTION/2008/primaries/results/epolls/#'+getObjValue(stateObj,'code')+partyAbbr+'"><b>'+getObjValue(stateObj,'polltype').charAt(0).toUpperCase()+getObjValue(stateObj,'polltype').substring(1).toLowerCase()+' Polls</b></a></span></div></td>' : '';
	var theVpct = (getObjValue(stateObj,'vpct') === '')?'':getObjValue(stateObj,'vpct')+'%';
	var thePctsrep = (getObjValue(stateObj,'pctsrep') === '')?'':getObjValue(stateObj,'pctsrep')+'%';;
	row += '<td class="status">'+status+'</td>';
	row += '<td><div class="pad">'+getObjValue(stateObj,'cvotes')+'</div></td>';
	row += '<td><div class="pad"><b>'+theVpct+'</b></div></td>';
	row += '<td><div class="pad"><b>'+getObjValue(stateObj,'edelegates')+'</b></div></td>';
	row += '<td><div class="pad"><b>'+getObjValue(stateObj,'udelegates')+'</b></div></td>';
	row += '<td><div class="pad"><b>'+getObjValue(stateObj,'tdelegates')+'</b></div></td>';
	row += '<td><div class="pad"><b>'+thePctsrep+'</b></div></td>';
	row += '</tr>';
	return row;
	}catch(e){return '';}
}

/////////render functions end

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!
