/*
I borrow heavily from Chromium Buildbot Monitor
http://code.google.com/chrome/extensions/samples.html#0e790e035a4a00b6f1def5ef9a7d7be1bce95ab5
*/
var statusURL = "http://us.battle.net/d3/en/status";

function checkStatus() {
	var xhr = new XMLHttpRequest();

	try {
		xhr.onreadystatechange = function(state) {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					var text = xhr.responseText;
					parseStatus(text);
				} 
			}
		}

		xhr.onerror = function(error) {
			console.log("xhr error: " + JSON.stringify(error));
			console.dir(error);
		}

		xhr.open("GET", statusURL, true);
		xhr.send({});
	} catch(e) {
		console.log("exception: " + e);
	}
}

function parseStatus(t) {
	console.log("got html");
	//now lets do a bit of regex. Right now this is brittle, but the logic is - find the first 
	//<div class="status-icon ...>
	//The second class represents our state and is either down or up
	var re = /<div class=\"status-icon (.*?)".*?>/;
	if(re.test(t)) {
		var match = t.match(re);
		if(match.length == 2) {
			var status = match[1];
			console.log(status);
			if(status != "up" && status != "down") return;
			chrome.browserAction.setTitle({"title":"The server is "+status});
			if(status == "up") chrome.browserAction.setIcon({path:"img/smile_grin_48.png"})
			else chrome.browserAction.setIcon({path:"img/smile_sad_48.png"});

		}
	} else {
		console.log("Regex failed to find a match");
	}
	setTimeout(checkStatus,60*1000);
}

window.onload = function() { setTimeout(checkStatus,100); }