//GLOBAL VARIABLES************
var swfServerHost = 'http://i.cdn.turner.com/cnn';

var statusGraphicsArray = new Array();
statusGraphicsArray['projected'] = 'http://i2.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/projected.gif';
statusGraphicsArray['processing'] = 'http://i2.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/processing.gif';
statusGraphicsArray['scheduled'] = 'http://i2.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/scheduled.gif';
statusGraphicsArray['voting'] = 'http://i2.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/voting.gif';
statusGraphicsArray['called'] = 'http://i2.cdn.turner.com/cnn/.element/img/2.0/sect/election/primaries/results/common/projected.gif';

var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

//END GLOBAL VARIABLES**********

//protects against the wide variety of status capital vs. lowercase combinations
function getStatusGraphic(status){
	return statusGraphicsArray[status.toLowerCase()];
}

//triggers loading sequence with nifty animation
function triggerLoading(id) {
        if (location.search || location.hash) {
                $(id).innerHTML = '<div class="loading"><img src="http://i2.cdn.turner.com/cnn/ELECTION/2008/images/loading.gif" alt="Please wait while we retrieve your data" border="0"><br>Please wait while we retrieve the data</div>';
        }
}

//ensures the property is defined in the object - prevents errors/seeing 'undefined'
function getObjValue(obj,property){try{
        return (obj[property] != undefined || obj[property]==0) ? obj[property] : '';
        }catch(e){return '';}
}

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

//Gets eastern date from timestamp
function getEasternDate(ts){
	var myDate = new Date();
	var newDate = new Date(ts);
	myDate.setUTCFullYear(newDate.getUTCFullYear());
	myDate.setUTCDate(newDate.getUTCDate());
	myDate.setUTCMonth(newDate.getUTCMonth());
	myDate.setUTCHours(newDate.getUTCHours());
	myDate.setUTCMinutes(newDate.getUTCMinutes());
	myDate.setUTCSeconds(newDate.getUTCMinutes());
	var now = new Date(cnnCurrTime);
	var newTime = myDate.getTime() + (myDate.getTimezoneOffset() * 60000) + (-5) * 3600000;
	var resultsDate = new Date(newTime);
	return resultsDate;
}

//Gets date format from a unix timestamp
function getElectionTimestamp(ts,forResultsRow,hideYear){
        if(ts+'' == '0'){ return ''; }
	var myDate = new Date(); //getting an EDT date
	var utcDate = new Date(ts);
	var offsetThing = -5;
	myDate.setUTCFullYear(utcDate.getUTCFullYear());
	myDate.setUTCMonth(utcDate.getUTCMonth());	
	myDate.setUTCDate(utcDate.getUTCDate());
	myDate.setUTCHours(utcDate.getUTCHours());
	myDate.setUTCMinutes(utcDate.getUTCMinutes());
	myDate.setUTCSeconds(utcDate.getUTCSeconds());
	var now = new Date(cnnCurrTime);
	var myDateTime = myDate.getTime();
	var newTime = myDate.getTime() + (myDate.getTimezoneOffset() * 60000) + offsetThing * 3600000;
	myDate = new Date(newTime);

	
	var hours = (myDate.getHours() > 12) ? myDate.getHours()-12 : (myDate.getHours() == 0) ? myDate.getHours()+12 : myDate.getHours();
        var amOrPm = (myDate.getHours() >= 12) ? 'p.m.' : 'a.m.';
        var minutes = (myDate.getMinutes() < 10) ? '0'+myDate.getMinutes() : myDate.getMinutes();
        var currentTimeMS = now.getTime();
		if(now.getTime()-ts < 3600000 && now.getTime()-ts>-120000 && forResultsRow){
                var minutes = Math.floor(((now.getTime()-ts)/1000)/60);
		if(minutes<1){minutes=1;}
                if(minutes==1)
                {
	                myDate = '<div class="cnnHtTimestamp">Updated '+minutes+' minute ago</div>';
                }
                else
                {
	                myDate = '<div class="cnnHtTimestamp">Updated '+minutes+' minutes ago</div>';
	            }
        }else{
                var month = months[myDate.getMonth()];
		var year = (hideYear) ? '' : ', ' + myDate.getFullYear();
		if(forResultsRow){
                        month = months[myDate.getMonth()].substring(0,3);
                        myDate = '<div class="cnnGryTmeStmp">Updated '+hours+':'+minutes+' '+amOrPm+' EST, '+month+' '+myDate.getDate()+year+'</div>';
                }else if(now.getTime()-ts < 3600000 && now.getTime()-ts>-120000){   //PAGE TIMESTAMP
                 var minutes = Math.floor(((now.getTime()-ts)/1000)/60);
				if(minutes<1){minutes=1;}
					if(minutes==1)
					{
						myDate = 'updated '+minutes+' minute ago';
					}
					else
					{
						myDate = 'updated '+minutes+' minutes ago';
					}
                }else{
                        myDate = 'updated '+hours+':'+minutes+' '+amOrPm+' EST, '+month+' '+myDate.getDate() +year;
                }
        }
	if(myDate.indexOf('undefined')>-1){
		myDate = '';
	}
        return myDate;
}

//rearranges a select box according to titles (e.g., DEMOCRATIC / REPUBLICAN) - pass in the id of select box
function rearrangeSelectBox(id,arrayOfTitles,isCnnDD){
        var selectBox = $(id);
        var arrayOfOptionLists = new Array();
        var titleIndex = -1;
        var arrayPointer = -1;
        for(var i=0; i<selectBox.length && titleIndex < 0; i++){
                for(var j=0; j<arrayOfTitles.length && titleIndex < 0; j++){
                        if(selectBox.options[i].text == arrayOfTitles[j]){
                                titleIndex = i;
                                arrayPointer = j;
                        }
                }
        }
        for(var i=0; i<arrayOfTitles.length; i++){
                        arrayOfOptionLists[i] = new Array();
        }
        for(var i=titleIndex; i<selectBox.length; i++){
                var foundOne = false;
                for(var j=0; j<arrayOfTitles.length && !foundOne; j++){
                        if(arrayOfTitles[j] == selectBox.options[i].text){
                                foundOne = true;
                                arrayPointer = j;
                        }
                }
                var thisOption  = document.createElement("OPTION");
                thisOption.text = selectBox.options[i].text;
                thisOption.value = selectBox.options[i].value;
                thisOption.disabled = (foundOne) ? "disabled" : "";
                arrayOfOptionLists[arrayPointer][arrayOfOptionLists[arrayPointer].length] = thisOption;
        }
        var resultPointer = titleIndex;
        for(var i=0; i<arrayOfOptionLists.length; i++){
                for(var j=0; j<arrayOfOptionLists[i].length; j++){
                        selectBox.options[resultPointer].text   = arrayOfOptionLists[i][j].text;
                        selectBox.options[resultPointer].value  = arrayOfOptionLists[i][j].value;
                        selectBox.options[resultPointer].disabled = arrayOfOptionLists[i][j].disabled;
                        resultPointer++;
                }
        }
        var selectString = '';
        for(var i=0; i<selectBox.length; i++){
                selectString += selectBox.options[i].text+' '+selectBox.options[i].value+'\n';
        }
        selectBox.value = "Default";
        if(isCnnDD){
                cnnDD.buildDropdown(id.replace(/_list/,''), 110, 240, 10, 'cnnDDWire');
        }
}

//adds commas to 4+ digit numbers
function commify(num){
        num = ''+num;
        if(num.indexOf(',')>-1){ return num; }
	try{var test = parseInt(num);}catch(e){return num;} //if not a number...don't commify
        var result = '';
        for(var i=1; i<=num.length; i++){
                if(i>1 && ((i-1)%3==0)){
                        result = ','+result;
                }
                result = num.charAt(num.length-i)+result;
        }
        return result;
}

//Converts 1 to 1st...etc
function getOrdinalNum(num){
        try{num = parseInt(num);}catch(e){return num;} //safety first
        if(num%100 < 20 && num%100 > 10){
                return num+'th';
        }else{
                switch(num%10){
                        case 1: return num+"st";
                        case 2: return num+"nd";
                        case 3: return num+"rd";
                        default: return num+"th";
                }
        }
}

//converts js date obj to yyyymmdd formatted string
function dateToYYYYMMDD(dateObj){
        var month       = (dateObj.getMonth()+1);
        var date        = dateObj.getDate();
        var year        = dateObj.getFullYear();
        month = (month < 10) ? "0"+month : ""+month;
        var date = (date<10) ? "0"+date : ""+date;
        return year+month+date;
}

//converts yyyymmdd formatted string to date object
function YYYYMMDDtoDate(yyyymmdd){
        var year = parseInt(yyyymmdd.substring(0,4));
        var month = parseInt(yyyymmdd.substring(4,6));
        var dateday = parseInt(yyyymmdd.substring(6))
        if(yyyymmdd.substring(6,7) == '0'){
                dateday = parseInt(yyyymmdd.substring(7));
        }
        var theDate = getToday();
        theDate.setFullYear(year);
        theDate.setMonth(month-1);
        theDate.setDate(dateday);
        theDate.setMonth(month-1);
	return theDate;
}

function getToday(){
	//var today = new Date();
	//today.setFullYear(2008);
	//today.setDate(7);
	//today.setMonth(0);
	var today = new Date(cnnCurrTime);
	return today;
}

function linkableCandidateOld(candidateLastName){
	var thisCandidate = candidateLastName.toLowerCase();
	if(	thisCandidate == "no preference" ||
		thisCandidate == "uncommitted" ||
		thisCandidate == "uninstructed"
	){
		return false;
	}
	return true;
}

function linkableCandidate(candidate){try{
	var badIds = [100004,100005,100006,100007,100008,100012];
	for(var i=0; i<badIds.length; i++){
		if(candidate.id == badIds[i]){
			return false;
		}
	}
	return true;}catch(e){return false;}
}

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


function getPlaceholderText(outerStyle){
	var theOuterStyle = (outerStyle)?outerStyle:'padding: 25px;';
	var results = '<div align="center" style="' + theOuterStyle + '"><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"><table style="margin: -8px 0px 0px;width:400px"><tr><td valign="top" style="font-weight:bold;font-size:14px;text-align:left;">CNN.com delivers the latest election results for the Democratic and Republican presidential primaries and caucuses. To view election results, visit the <a href="/ELECTION/2008/">CNN.com Election Center</a> or make a selection from one of the pulldowns above.</td></tr></table></div></td></tr></table><div class="bottom"></div><div class="cnnPad4Top"></div></div></div>';
	return results;
}

// Loads county map.  This method should only be called if it can display a map.
function loadCountyMaps(stateAbbr, width, height, party, mainSWF, cnnFIPS, raceType){
	var stateAbbr = (stateAbbr == undefined) ? getStateFromUrl() : stateAbbr;
	var returnHTML = '';
	var displayRaceType = '';
	if(countyflashxml == "yes" && raceType.toUpperCase().indexOf('CAUCUS') >-1){
		displayRaceType = 'Caucuses ';
	} else if(countyflashxml == "yes" || stateAbbr == "TX" || stateAbbr == "WV"){ 
		displayRaceType = 'Primary ';
	}
	var xmlFileSubstring = (party.toUpperCase().indexOf('DEM') >-1)?'Democrat':'Republican';
	var displayParty = (party.toUpperCase().indexOf('DEM') >-1)?'Democratic ':'Republican ';
	var flashLinkVar ='';
	var dataFileExt = '.xml';
	var swfDir = '/states_sm'
	if (countyflashxml == "yes"){
		swfDir = '/states';
	}
	if(countyflashxml == "yes" && stateAbbr == "TX" && raceType.toUpperCase().indexOf('CAUCUS') >-1 )
	{
		if (party.toUpperCase() == 'REP'){ dataFileExt = '-S.xml'; }
		else{ dataFileExt = '-E.xml'; }
	} else if(countyflashxml == "yes" && stateAbbr == "WA" && raceType.toUpperCase().indexOf('PRIMARY') >-1 ) 
	{
		if (party.toUpperCase() == 'DEM'){ dataFileExt = '-D.xml'; }
		else{ dataFileExt = '-R.xml'; }
	}
	if ( ( stateAbbr != '' ) && ( typeof CNN_FlashDetect != 'undefined' ) && new CNN_FlashDetect().detectVersion( 8 ) ) {
		try {
			returnHTML = '<div>'+displayParty+displayRaceType + 'Results by County</div>';
			if(countyflashxml == "no"){
				flashLinkVar= "link=/ELECTION/2008/primaries/results/county/#"+stateAbbr+party.toUpperCase()+"MAP"+raceType;
			}
			if(xmlFileSubstring != '') {
				var cnn_electionMap = new CNN_FlashObject(
					"cnn_electionMap",
					swfServerHost+"/.element/swf/2.0/sect/ELECTION/2008/primaries/maps/"+mainSWF,
					width, height, 
					null,
					flashLinkVar+"&swf_url="+swfServerHost+"/.element/swf/2.0/sect/ELECTION/2008/primaries/maps/&map="+cnnFIPS+"&mapPath="+swfServerHost+"/.element/swf/2.0/sect/ELECTION/2008/primaries/maps"+swfDir+"/"+cnnFIPS+".swf&xmlPath=/ELECTION/2008/primary/json/county/"+xmlFileSubstring+"/"+stateAbbr+dataFileExt
				);
				returnHTML += '<div>' + cnn_electionMap.getHtml() + '</div>';
			} else { returnHTML = ''; }
		} catch ( e ) {
			returnHTML = '';
		}
	}
	else {
		returnHTML ="<div class=\"cnnNoFlashContainer\"><div class=\"cnnNoFlash\"><p class=\"cnnTopGraf\">This CNN.com feature is optimized for Adobe Flash Player version "+(((window.navigator.platform.toLowerCase()).indexOf('mac') > -1) ? '9' : '8')+" or higher.<\/p><p><b>You are currently using Flash Player " + parseInt(CNN_FlashDetect.prototype.getVersion()) + "<\/b><\/p><a href=\"http://www.adobe.com/go/getflashplayer\" target=\"blank\"><img src=\"http://i.l.cnn.net/cnn/.element/img/2.0/global/noflash/install_btn.gif\" class=\"cnnGetBtn\" width=\"155\" height=\"31\" alt=\"Get Flash Player\" border=\"0\"><\/a><\/div><\/div>";
	}
	return returnHTML;
}
