var loadingCountyPage = false;
var initialLoad = true;
var currentState = '';
var currentParty = '';
var currentPrimaryType = '';
var currentRaceIndex = 0;
var currentXPFlagIndex = 0;
var currentPage;
var currentMapString='';
var currentlyIsMap = false;
var currentMapIsAvailable = false;
var mapWidth = 644;
var mapHeight = 535;
var cnnMapIsAllowed = true;
var mainSWF = 'bigMain.swf';
var countyflashxml='yes' ;

var jsonPath = '/ELECTION/2008/primary/json/county/';

//called by dropdown - if on state page
function loadYPage(val){
        YAHOO.util.History.navigate("val", val);
}

//Makes CSI call to get county information for a particular page/party/state combination
function loadCountyResultsPage(pageNum,state,party, map){try{
	if(loadingCountyPage) return;
	pageNum = (pageNum == undefined) ? getPageFromUrl() : pageNum;
	state	= (state == undefined) ? getStateFromUrl() : state;
	party	= (party == undefined) ? getPartyFromUrl() : (party == 'currentParty') ? currentParty : party; 
	map		= (map == undefined) ? getMapStringFromUrl() : map;
	currentMapIsAvailable = getHasCountyMap(state, party);
	currentPrimaryType = getPrimaryTypeFromUrl();
	currentlyIsMap = (map == 'MAP' && currentMapIsAvailable)?true:false;
	currentMapString = (currentMapIsAvailable)?map:'';
	currentPage = pageNum;
	currentState = (currentParty == party) ? currentState : undefined;
	if(currentParty != party){
		//swapAd('election');
	}
	currentParty = party;
	if(state=='' || party == ''){
                $('cnnElexRBCounty_left').innerHTML = '<br/>'+getPlaceholderText('padding: 25px 0px 0px 241px;');
                return;
        }	

	setTimeout(badPagePreventer,10000);
	CSIManager.getInstance().call(jsonPath+state+'p'+pageNum+'.html','',['cnnElexRBCounty_right'], [loadCountyResultsPageHandler], true);
	loadingCountyPage = true;
	scrollTo(0,0);
}catch(e){}}

//if an invalid page is requested, we default to page 1 - after 10 seconds of unsuccess
function badPagePreventer(){
	if($('cnnElexRBCounty_right').innerHTML.indexOf('loadingResultsTable')>-1){
		loadingCountyPage=false;
		loadYPage(buildVal(1,getStateFromUrl(),getPartyFromUrl(),getPrimaryTypeFromUrl(), getMapStringFromUrl()));
	}
}

//if the race is scheduled, make CSI call - but wait for the div/id to exist
var safetyCounter = 0;
function getScheduledBox(party,stateAbbr){
	if(safetyCounter > 25) return;
	try{
		var crasher = $('scheduledBox').innerHTML;
		CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/state/'+party+stateAbbr+'.html','','scheduledBox');
	}catch(e){
		setTimeout("getScheduledBox('"+party+"','"+stateAbbr+"')",100);
		safetyCounter++;
	}
}

//for the state machine variable
function buildVal(page, state, party, primaryType, mapString){
	return state+party+mapString+primaryType+page;
}

function getCurrentRaceIndex(obj){
	var thisSetOfRaces = obj.counties[0].races;
	for(var i=0; i<thisSetOfRaces.length; i++){
		var thisRace = thisSetOfRaces[i];
		if(	thisRace.primarytype.toUpperCase() == currentPrimaryType &&
			thisRace.party.toUpperCase() == currentParty){
				return i;
		}
	}
	for(var i=0; i<thisSetOfRaces.length; i++){
		var thisRace = thisSetOfRaces[i];
		if(thisRace.party.toUpperCase() == currentParty){
                	return i;
                }
	}
	return 0;
}

function getCurrentXPFlagIndex(obj){
	var thisSetOfXPFlags = obj.xpflags;
	for(var i=0; i<thisSetOfXPFlags.length; i++){
		var thisRace = thisSetOfXPFlags[i];
		if(	thisRace.primarytype && thisRace.primarytype.toUpperCase() == currentPrimaryType &&
			thisRace.party.toUpperCase() == currentParty){
				return i;
		}
	}
	for(var i=0; i<thisSetOfXPFlags.length; i++){
		var thisRace = thisSetOfXPFlags[i];
		if(thisRace.party.toUpperCase() == currentParty){
                	return i;
                }
	}
	return 0;
}

//Driver function - creates the entire page / calls everything else
function loadCountyResultsPageHandler(obj){
	currentRaceIndex = getCurrentRaceIndex(obj);
	currentXPFlagIndex = getCurrentXPFlagIndex(obj);
	var listBoxOrder = (currentParty == 'DEM') ? ['DEMOCRATS','REPUBLICANS'] : ['REPUBLICANS','DEMOCRATS'];
	try{rearrangeSelectBox('cnnDD_elexCand_list',listBoxOrder,true);}catch(e){}
	setLeftTitleInfo(obj);
	document.title = 'Election Center 2008: Primary Results for '+getObjValue(obj,'state');
	var notes ='X';
	if(!initialLoad){
		try{notes=$('specialNotes').innerHTML;}catch(e){}
	}
	var tableMapClass = (currentlyIsMap)?'cnnElexPrimCountyMap':'cnnElexPrimCountyTable';
	var countyTableHeader = '<div class="'+tableMapClass+'" id="cnnElexPrimCountyTableId">';
	var countyTableFooter = '<div class="bottom"></div></div><div style="padding:9px 0px 10px 0px;"><div id="specialNotes" class="cnnElexPrimSNote">'+notes+'</div></div>'
	if( !currentlyIsMap ) {
		countyTableHeader += '<table cellspacing="0" cellpadding="0" border="0" width="644"><colgroup><col width="156"><col width="54"><col width="144"><col width="122"><col width="61"><col width="107"></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>County Votes*</span></div></td><td><div><span>Vote%</span></div></td><td class="end_right"><div><span>Precincts</span></div></td></tr>';
		countyTableFooter = '</table><div class="bottom"></div></div><div style="padding:9px 0px 10px 0px;"><table cellspacing="0" cellpadding="0" border="0" width="644"><tr valign="bottom"><td></td><td align="right" style="font:normal 10px helvetica, arial;color:#949494;">'+createArrowWidget(2,obj.thisPage,obj.totalPages)+'</td></tr></table><div id="specialNotes" class="cnnElexPrimSNote">'+notes+'</div></div>';
	}
	var resultsHTML = getResultsHeader(obj);
	resultsHTML += countyTableHeader;
    var counties = obj.counties;
	var isScheduled = true;
	if( !currentlyIsMap ) {
		for(var i=0; i<counties.length; i++){
			if(obj.counties[i].races[currentRaceIndex].status.toLowerCase() != 'scheduled') {
				if(i>0){
					resultsHTML += '<tr><td class="divider" colspan="6"><div></div></td></tr>';
				}
				var raceObj = obj.counties[i].races[currentRaceIndex];
				isScheduled = false;
				resultsHTML += generateCountyResultsRow(raceObj,obj.counties[i]);
			}
		}
	} else {
		var cnnFIPS = getFIPS(currentState);
		resultsHTML += loadCountyMaps(currentState, mapWidth, mapHeight, currentParty, mainSWF, cnnFIPS, currentPrimaryType);
	}
	resultsHTML += countyTableFooter;
	loadingCountyPage = false;
	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;

	if((initialLoad && !isScheduled) || (initialLoad && currentlyIsMap)){ setSpecialNotes()};
	initialLoad = false;

	if(isScheduled && !currentlyIsMap){
		var boxHTML = '';
		try{boxHTML = $("scheduledBox").innerHTML;}catch(e){boxHTML='';}
		resultsHTML = '<br/><br/><div class="waitingTableTop"><table><tr><td style="padding-top: 20px; padding-left: 20px;padding-right:20px; border-left:1px solid #DADADA; border-right:1px solid #DADADA; height:200px;"><div id="scheduledBox">'+boxHTML+'</div></td></tr></table><div class="bottom"></div><div class="cnnPad4Top"></div></div><div id="specialNotes" class="cnnElexPrimSNote"></div>';
		getScheduledBox(currentParty, currentState);
		setSpecialNotes();
	} 
	return resultsHTML;
}

//if the race is scheduled, make CSI call - but wait for the div/id to exist
var safetyCounter = 0;
function getScheduledBox(party,stateAbbr){
	if(safetyCounter > 25) return;
	try{
		var crasher = $('scheduledBox').innerHTML;
		CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/state/'+party+stateAbbr+'.html','','scheduledBox');
	}catch(e){
		setTimeout("getScheduledBox('"+party+"','"+stateAbbr+"')",100);
		safetyCounter++;
	}
}


//setting notes per state (only upon new state load)
function setSpecialNotes(){
	try{
		var tester = $('specialNotes').innerHTML;
		if(tester != undefined)
			CSIManager.getInstance().call('/.element/ssi/www/sect/2.0/ELECTION/primaries/notes/county/'+currentState+'.html','','specialNotes');
	}catch(e){
		setTimeout(setSpecialNotes,500);
	}
}

//generates a single row for a single county
function generateCountyResultsRow(countyObj,countyObj2){
	var rowHtml 	 = '<tr valign="top">';
	rowHtml 	+= '<td rowspan="'+countyObj.candidates.length+'">';
	rowHtml		+= '<div class="state_name"><b>'+getObjValue(countyObj2,'name')+'</b>';
	rowHtml		+= '<div style="padding:2px 0px 0px 0px;font-size:11px;">';
	rowHtml		+= (countyObj.ts == 0) ? '' : getElectionTimestamp(getObjValue(countyObj,'ts'),false).replace(/U/,'u').replace(/cnnGryTmeStmp/,'');
	rowHtml		+= '</div></div>';
	var statusImage = statusGraphicsArray[countyObj.status];
	if(statusImage == undefined) statusImage =  statusGraphicsArray['processing'];
	rowHtml		+= '<td class="status"><img src="'+statusImage+'" width="45" height="42" border="0" vspace="6"></td>';
	var candidates = countyObj.candidates;
	for(var i=0; i<candidates.length; i++){
		if(i>0){ 
			rowHtml += '<tr valign="top"><td></td>';
		}
		var candidateURL = '/ELECTION/2008/primaries/results/candidates/';
        	candidateURL    += '#'+getObjValue(candidates[i],'id');
	       	var cellClass = (i<candidates.length-1) ? "bord_b" : "";
		rowHtml		+= '<td class="cand '+cellClass+'"><div class="pad">';
		rowHtml		+= getCandidateLink(candidates[i]);
        	rowHtml		+= '</div></td>';
		cellClass = (cellClass == "pad") ? '' : cellClass;
		rowHtml        	+= '<td class="'+cellClass+'"><div class="pad">'+getObjValue(candidates[i],'cvotes')+'</div></td>';
        	rowHtml        	+= '<td class="'+cellClass+'"><div class="pad"><b>'+getObjValue(candidates[i],'vpct')+'%</b></div></td>';
		if(i==0){
			rowHtml += '<td rowspan="'+candidates.length+'" class="report"><div class="pad"><b>';
			rowHtml += getObjValue(countyObj,'pctsrep')+'%</b>';
			rowHtml += '<br><span style="font-size:10px;">reporting</span></div></td>';
		}
		rowHtml += '</tr>';
	}
	return rowHtml;
}

function getCandidateLink(candidate){
        if(!linkableCandidate(candidate.lname)){
                return candidate.lname;
        }else{
                return '<a href="/ELECTION/2008/primaries/results/candidates/#'+candidate.id+'"><b>'+candidate.lname+'</b></a>';
        }
}

//when selected from dropdown - update party in case it's changed
function selectAPage(page, state){
	$('cnnDD_elexCounty_list').value = "Programs";
        cnnDD.buildDropdown('cnnDD_elexCounty', 200, 200, 10, 'cnnDDWire');
	if(currentPage == page && state == currentState) return;
	loadYPage(buildVal(page,state,currentParty,currentPrimaryType,currentMapString));
}

var firstTime = true;
//builds HTML and sets the information on the left side
function setLeftTitleInfo(obj){try{
	//if(currentState == getObjValue(obj,'code')) { //updating key title fields
	//	$('currentCountySet').innerHTML = '('+obj.counties[0].name+' - '+obj.counties[obj.counties.length-1].name+')';
	//	$('cnnDD_elexCounty_list').value = "Programs";
	//	cnnDD.buildDropdown('cnnDD_elexCounty', 200, 200, 10, 'cnnDDWire');
	//	return; //no need to create everything
	//}
	currentState = getObjValue(obj,'code');
	if(firstTime){ //loading areas
		firstTime = false;
		var leftTitleHtml  = '<div class="cnnElexPrimC_head">';
		leftTitleHtml 	+= '<h1><div id="pageTitle">COUNTY RESULTS:*</div>';
		leftTitleHtml	+= '<div style="padding:8px 0px 8px 0px;font-size:22px;"><b><a href="/ELECTION/2008/primaries/results/state/#'+getObjValue(obj,'code')+'">'+getObjValue(obj,'state')+'</a></b></div></h1>';
		leftTitleHtml+= '<div style="padding-bottom:5px;font-size:16px;" id="primaryTypeText">'+primaryTypeToTitle(obj.counties[0].races[currentRaceIndex].primarytype.toUpperCase())+'</div>';
		var countySetStyle = (currentlyIsMap)?' style="display:none"':'';
		leftTitleHtml+= '<span id="currentCountySet"'+ countySetStyle +'>('+obj.counties[0].name+' - '+obj.counties[obj.counties.length-1].name+')</span>';
		leftTitleHtml	+= '</div>';
		var dropdownStyle = (currentlyIsMap)?' style="display:none"':'';
		leftTitleHtml	+= '<div id="cnnDD_elexCounty_wrap"'+ dropdownStyle +'></div>';
		leftTitleHtml	+= '<select id="cnnDD_elexCounty_list" onChange="selectAPage(this.options[selectedIndex].value,\''+currentState+'\')">';
		leftTitleHtml	+= 	'<option value="Programs">Select a county</option>';
		leftTitleHtml	+=	'<option disabled="disabled">----------------------------------------</option>';
	
		//build county page list	
		for(var i=0; i<obj.pages.length; i++){
			leftTitleHtml += '<option value="'+obj.pages[i].thisPage+'">'+obj.pages[i].firstCounty+' - '+obj.pages[i].lastCounty+'</option>';
		}
		
		var stateURL= '/ELECTION/2008/primaries/results/state/#' + getObjValue(obj,'code');
		leftTitleHtml	+= '</select>';
		leftTitleHtml	+= '</form>';
		var chooseViewStyle = (currentMapIsAvailable)?'':' style="display:none"';
		leftTitleHtml += '<div id="cnnChooseView" class="cnnViewNav"'+ chooseViewStyle +'><span style="color:#000000;font-weight:normal;">CHOOSE VIEW:</span> ';
		var tableLinkClass = (!currentlyIsMap)? 'class="active" ' : ""
		var mapLinkClass = (currentlyIsMap)? 'class="active" ' : ""
		leftTitleHtml += '<a '+ tableLinkClass +'id="cnnTableLink" href="javascript:loadYPage(buildVal(1,\''+currentState+'\',\''+currentParty+'\',\''+currentPrimaryType+'\',\'\'))">Table</a> | ';
		leftTitleHtml += '<a '+ mapLinkClass +'id="cnnMapLink" href="javascript:loadYPage(buildVal(1,\''+currentState+'\',\''+currentParty+'\',\''+currentPrimaryType+'\',\'MAP\'))">Map</a></div>';
		var xpflag = obj.xpflags[currentXPFlagIndex].xpoll;

		var polltype = (obj.polltype == 'exit') ? 'Exit' : 'Entrance';	
		leftTitleHtml += (xpflag) ? '<div id="exitPollLink" style="font-weight:bold;padding-top:5px;"><a href="/ELECTION/2008/primaries/results/epolls/#'+getObjValue(obj,'code')+currentParty+'">'+polltype+' Polls</a></div>' : '<div id="exitPollLink" style="font-weight:bold;padding-top:5px;"></div>';


		$('cnnElexRBCounty_left').innerHTML = leftTitleHtml;
		cnnDD.buildDropdown('cnnDD_elexCounty', 200, 200, 10, 'cnnDDWire');firstTime=false;
	}else{ // switching parties
		$('primaryTypeText').innerHTML = primaryTypeToTitle(obj.counties[0].races[currentRaceIndex].primarytype.toUpperCase());
		var polltype = (obj.polltype == 'exit') ? 'Exit' : 'Entrance';
		var xpflag = obj.xpflags[currentXPFlagIndex].xpoll;
		$('exitPollLink').innerHTML = (xpflag) ? '<a href="/ELECTION/2008/primaries/results/epolls/#'+getObjValue(obj,'code')+currentParty+'">'+polltype+' Polls</a></div>' : '';
		$('currentCountySet').innerHTML = '('+obj.counties[0].name+' - '+obj.counties[obj.counties.length-1].name+')';
		if($('demLink')) { $('demLink').className = (currentParty == 'DEM') ? "active" : "";}
		if($('repLink')) { $('repLink').className = (currentParty == 'REP') ? "active" : "";}
		$('cnnTableLink').href = (cnnMapIsAllowed) ? 'javascript:loadYPage(buildVal(1,\''+currentState+'\',\''+currentParty+'\',\''+currentPrimaryType+'\',\'\'))' : '#';
		$('cnnMapLink').href = (cnnMapIsAllowed) ? 'javascript:loadYPage(buildVal(1,\''+currentState+'\',\''+currentParty+'\',\''+currentPrimaryType+'\',\'MAP\'))' : '#';
		$('cnnTableLink').className = (!currentlyIsMap)? "active" : ""; //style="color:#949494;"
		$('cnnMapLink').className = (currentlyIsMap)? "active" : "";	
		$('currentCountySet').innerHTML = '('+obj.counties[0].name+' - '+obj.counties[obj.counties.length-1].name+')';
		$('cnnDD_elexCounty_list').value = "Programs";
		cnnDD.buildDropdown('cnnDD_elexCounty', 200, 200, 10, 'cnnDDWire');
		
		$('cnnDD_elexCounty_wrap').style.display = (currentlyIsMap)? "none" : "block";
		$('currentCountySet').style.display = (currentlyIsMap)? "none" : "block";
		$('cnnChooseView').style.display = (currentMapIsAvailable)? "block" : "none";
	}
}catch(e){}}

//these are races that do not have the other party's race - WA and TX should be the only ones.
function weirdRace(state,party,primaryType){
	if(state == "WA" && party.toUpperCase() == "REP" && primaryType.toUpperCase() == "PRIMARY"){
		return true;
	}
	if(state == "TX" && party.toUpperCase() == "DEM" && primaryType.toUpperCase() == "CAUCUS"){
		return true;
	}
	return false;
}

//builds the HTML for the title of the county table
function getResultsHeader(obj){
	var nextPageNum = (obj.totalPages > obj.thisPage) ? obj.thisPage+1 : 0;
	var currentState = getObjValue(obj,'code');
	//resultsHeader = '<div style="padding:10px 0px 0px 0px;font-size:14px;color:#949494;"><a href="#" style="color:#949494;"><b>Democrats</b></a> | <a href="#"><b>Republicans</b></a></div>';
	var resultsHeader = '';
	var DEMClass = (currentParty == 'DEM') ? "active" : "";
	var REPClass = (currentParty == 'REP') ? "active" : "";
	if(!weirdRace(currentState,currentParty,currentPrimaryType) && (typeof(obj.counties[0].races[currentRaceIndex].opcountyresults) == 'undefined' || obj.counties[0].races[currentRaceIndex].opcountyresults == true)){
		var foundTheOtherRace = false;
		var theOtherPrimaryType = "PRIMARY";
		for(var i=0; i<obj.counties[0].races.length && !foundTheOtherRace; i++){
			if(i != currentRaceIndex && !weirdRace(currentState, obj.counties[0].races[i].party, obj.counties[0].races[i].primarytype)){
				if(obj.counties[0].races[i].party.toUpperCase() != currentParty){
					foundTheOtherRace = true;
					theOtherPrimaryType = obj.counties[0].races[i].primarytype.toUpperCase();
				}
			}
		}
		repPrimaryType = (currentParty == "REP") ? currentPrimaryType : theOtherPrimaryType;
		demPrimaryType = (currentParty == "DEM") ? currentPrimaryType : theOtherPrimaryType;
		resultsHeader 	+= '<div id="otherPartyLink" class="party_nav"><a id="demLink" href="javascript:loadYPage(buildVal(1,\''+currentState+'\',\'DEM\',\''+demPrimaryType+'\',\''+currentMapString+'\'));" class="'+DEMClass+'"><b>Democrats</b></a> | <a id="repLink" href="javascript:loadYPage(buildVal(1,\''+currentState+'\',\'REP\',\''+repPrimaryType+'\',\''+currentMapString+'\'));" class="'+REPClass+'" ><b>Republicans</b></a></div>';
	} else {
		resultsHeader 	+= '<div id="otherPartyLink" class="party_nav"></div>';
	}
	
	resultsHeader +=  '<table cellspacing="0" cellpadding="0" border="0" width="644">';
	resultsHeader += '<tr>';
	resultsHeader += '<td><div class="cnnElexPrimSTitle"><h2>';
	resultsHeader += '<img src="'+getPartyIcon(currentParty)+'" style="vertical-align:top;margin:0px 5px 0px 0px;"/>';
	
	var currentRace = obj.counties[0].races[currentRaceIndex];
	
	resultsHeader += partyCodeToText(currentParty).toUpperCase()+' PRIMARIES / CAUCUSES <span>'+getPrettyDate(getObjValue(currentRace,'electiondate'))+'</span>';
	resultsHeader += '</h2></div></td>';
	resultsHeader += '<td align="right" style="font:normal 10px helvetica, arial;color:#949494;">';
	resultsHeader += createArrowWidget(1,getObjValue(obj,'thisPage'),getObjValue(obj,'totalPages'));
	resultsHeader += '</td></tr>';
	resultsHeader += '</table>';
	return resultsHeader;
}

//builds the << page 1 of 15 >> widget - the 'num' is a unique id for enabling rollover effects (there are 2 widgets on the page)
function createArrowWidget(num,pageNum,total){
	var arrowWidget ='';
	if(!currentlyIsMap){
		arrowWidget = createArrow('left',pageNum-1,total,num);
		arrowWidget += '&nbsp; '+pageNum+' of '+total+' &nbsp;';
		arrowWidget += createArrow('right',pageNum+1,total,num);
	}
	return arrowWidget;
}

//creates a single arrow - called by createArrowWidget()
function createArrow(direction,pageNum,total,num){
	var imgPath = 'http://i2.cdn.turner.com/cnn/ELECTION/2008/primaries/images/county/';
	var arrowHTML = '<img src="'+imgPath+direction+'_gray.gif" width="29" height="22" style="vertical-align:middle;"/>';
	if((pageNum>0 && direction=='left') || (pageNum<=total && direction=='right')){
		arrowHTML = '<a href="javascript:loadYPage(buildVal('+pageNum+',\''+currentState+'\',\''+currentParty+'\',\''+currentPrimaryType+'\',\''+currentMapString+'\'))" onmouseover="document.images[\'nav_'+direction+'_top'+num+'\'].src = \''+imgPath+direction+'_red.gif\';" onmouseout="document.images[\'nav_'+direction+'_top'+num+'\'].src = \''+imgPath+direction+'.gif\';"><img src="'+imgPath+direction+'.gif" width="29" height="22" alt="" border="0" style="vertical-align:middle;" name="nav_'+direction+'_top'+num+'"></a>';
	}
	return arrowHTML;
}

//gets the appropraite party icon for DEM or REP
function getPartyIcon(party){
	var imgPath = 'http://i2.cdn.turner.com/cnn/ELECTION/2008/primaries/images/common/';
	imgPath += (party=='DEM') ? 'icon_democrat.gif' : 'icon_republican.gif';
	return imgPath;
}

//converts 20080310 to March 10, 2008
function getPrettyDate(theDate){
	var year = parseInt(theDate.substring(0,4));
	var month = parseInt(theDate.substring(4,5));
	var day = parseInt(theDate.substring(6));
	return months[month]+' '+day+', '+year;
}

function primaryTypeToTitle(primaryType){
	return (primaryType.toUpperCase() == "PRIMARY") ? "PRIMARIES" : "CAUCUSES";
}

//exchanges partyCode for Republican or Democratic
function partyCodeToText(partyCode){
	return (partyCode == 'REP') ? 'Republican' : 'Democratic';
}

function getHashVal(){
	return location.href.substring(location.href.indexOf('#')).replace(/#/,'').replace(/val=/,'');
}

//rather easy to understand, i would think.
function getPartyFromUrl(){
	return (location.href.indexOf('REP') > -1) ? 'REP' : 'DEM';
}

function getPrimaryTypeFromUrl(){
	return (getHashVal().toUpperCase().indexOf("PRIMARY") > -1) ? "PRIMARY" : (getHashVal().toUpperCase().indexOf("CAUCUS") > -1) ? "CAUCUS" : "CAUCUS";
}

function getMapStringFromUrl(){
	return (getHashVal().toUpperCase().indexOf("MAP") > -1) ? "MAP" : "";
}

//gets the State from the URL
function getStateFromUrl(){
	var state = getHashVal().toUpperCase().replace(/DEM/,'').replace(/PRIMARY/,'').replace(/CAUCUS/,'').replace(/REP/,'').replace(/MAP/,'').substring(0,2);
	return state;
}

function getPageFromUrl(){
	try{
	var page = parseInt(getHashVal().replace(/DEM/,'').replace(/PRIMARY/,'').replace(/CAUCUS/,'').replace(/REP/,'').replace(/MAP/,'').substring(2));
	}catch(e){page = 1;}
	return (page > 0) ? page : 1;
}

//return the party that isn't the current one - for links to the 'other' race
function getOtherParty(thisParty){
	return (thisParty == 'DEM') ? 'REP' : 'DEM';
}


//////on load, won't be able to wait until onload in real world.
//Event.observe(window, 'load', initialLoadCounty);

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!
