var ready = false;
var key = "to9X4ghGndFmQbzJS2VIrlg";
var jsonData = null;

var script = document.createElement('script');
script.setAttribute('src', 'http://spreadsheets.google.com/feeds/cells/'+key+'/2/public/values?alt=json-in-script&callback=setJson&timestamp=' + new Date());
script.setAttribute('id', 'jsonScript');
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);

function drawVisualization() {

	// Empty target div
	var viz = document.getElementById('visualization');
	if (viz == null) {
		return;
	}

	while(viz.firstChild) {
    		viz.removeChild(viz.firstChild);
	}

	if (jsonData == null) {
		// No JSON yet, render the placeholder
		var img = document.createElement('img');
		img.setAttribute('src', '/app/images/placeholder-map.jpg');
		img.setAttribute('id', 'placeholder-map');
		viz.appendChild(img);
                return;
        }

	var states=[];
	var data = new google.visualization.DataTable();
	data.addRows(55);
	data.addColumn('string', 'State');
	data.addColumn('number', 'Orders');

	for (var i=2; i < jsonData.feed.entry.length; i=i+2) {
		var state = jsonData.feed.entry[i].content.$t;
		var count = parseInt(jsonData.feed.entry[i+1].content.$t);
		if (state == null || state == "") break;
		data.setValue(i-1, 0, state);
		data.setValue(i-1, 1, count);
	}
	var geochart = new google.visualization.GeoChart(viz);
	geochart.draw(data, {backgroundColor: "#ffffff", resolution: "provinces", region: "US", width: 487, height: 304});
}

function setJson(json) {
	if (json != null && json.feed.entry.length > 10 &&
		json.feed.entry[2].content.$t != 'US-#VALUE!' &&
		typeof json.feed.entry[2].content.$t !== "undefined" &&
		json.feed.entry[2].content.$t != null && 
		json.feed.entry[2].content.$t.length > 3) {
		jsonData = json;
	}
	drawVisualization();
}


function refresh() {
        var jsScript = document.getElementById('jsonScript');
	document.documentElement.firstChild.removeChild(jsScript);

	var script = document.createElement('script');
	script.setAttribute('src', 'http://spreadsheets.google.com/feeds/cells/'+key+'/2/public/values?alt=json-in-script&callback=setJson&timestamp=' + new Date());
	script.setAttribute('id', 'jsonScript');
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);
}


setInterval("refresh()", 120000);

