var bnElPollImgPath = 'http://wwwimage.cbsnews.com/election2008/images/';

function bnElPoll (){}

bnElPoll.prototype.getTimestamp = function(){
	return new Date().getTime();
}

bnElPoll.prototype.fetch = function(){
	var ts = this.getTimestamp();

	// If it's too recent, abort
	if(typeof this.lastFetch == 'undefined' || ts-10*1000 > this.lastFetch){
		this.requestFetch();
		return false;
	}
	this.populateData();
}

bnElPoll.prototype.requestFetch = function(){
	var obj = this;
	
	$.ajax({
		url: '/election2008/xmlfiles/PresSummary.xml',
		success: function(xml){ obj.processResponse(xml); obj.populateData();}
	});

	this.lastFetch = this.getTimestamp();
}

bnElPoll.prototype.processResponse = function(xml){
	$xml = $(xml);

	// This is pretty repetitive, but simple is our goal here.

	// Dem Data
	var $dem = $('Cand[Party=D]', $xml);
	this.demVotes = $dem.attr('Votes');	
	this.demVPct = $dem.attr('VPct');	
	this.demElectoral = parseInt($dem.attr('Electoral'));	

	if ($dem.attr('Call') == "Winner"){
		this.demWinCheck = true;
	} else {
		this.demWinCheck = false;
	}
	// Rep data
	var $rep = $('Cand[Party=R]', $xml);
	this.repVotes = $rep.attr('Votes');	
	this.repVPct = $rep.attr('VPct');
	this.repElectoral = parseInt($rep.attr('Electoral'));

	if ($rep.attr('Call') == "Winner"){
		this.repWinCheck = true;
	} else {
		this.repWinCheck = false;
	}
}

bnElPoll.prototype.populateData = function(){
	$('.demVotes').html(addCommas(this.demVotes.toString()));
	$('.demVPct').html(this.demVPct.toString()+'%');
	$('.demElectoral').html(this.demElectoral.toString());
	if(this.demWinCheck){
		$('.demWinCheck').html('<img src="' + bnElPollImgPath + 'check_d.gif" alt="Winner" />');
		$('.demWinCheckOld').html('<img src="' + bnElPollImgPath + 'check_blue_40.gif" alt="Winner" />');
	} else {
		$('.demWinCheck, .demWinCheckOld').html('');
	}
	$('.repVotes').html(addCommas(this.repVotes.toString()));
	$('.repVPct').html(this.repVPct.toString()+'%');
	$('.repElectoral').html(this.repElectoral.toString());
	if(this.repWinCheck){
		$('.repWinCheck').html('<img src="' + bnElPollImgPath + 'check_r.gif" alt="Winner" />');
		$('.repWinCheckOld').html('<img src="' + bnElPollImgPath + 'check_red_40.gif" alt="Winner" />');
	} else {
		$('.repWinCheck, .repWinCheckOld').html('');
	}

	$('.votesRemaining').html(538 - (this.repElectoral + this.demElectoral));
}


function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


// Initialize this
var xBnElPoll = new bnElPoll;

// Ticker should call this
//function bnTickerGetDataCompleteCallback(){
//	xBnElPoll.fetch();
//}