GeoTest = window.GeoTest || {}

GeoTest.NAME;
GeoTest.CAPITAL;
GeoTest.FORM;
GeoTest.ONE_OF;

GeoTest.state = GeoTest.state || {};

GeoTest.ui = {
	ONE: "the capital",
	FIRST: "one of the capitals",
	ANOTHER: "another capital",
	STATE: "of the state",
	next: function () {
		if (GeoTest.data.isArray(GeoTest.state.capital) && GeoTest.state.capital.length > 0) {
			GeoTest.ONE_OF.text(this.ANOTHER);
		} else {
			var current = GeoTest.data.choose();
			var text = "";
			
			GeoTest.state.country = current;
			
			
			if (GeoTest.data.isArray(current["capital"])) {
				text = this.FIRST;
				GeoTest.state.capital = current["capital"].slice();
			} else {
				text = this.ONE;
				GeoTest.state.capital = current["capital"];
			}
			
			if (current["state"]) text += ' ' + GeoTest.ui.STATE;
			
			if (GeoTest.map) GeoTest.map.countryChanged(current);
			
			GeoTest.ONE_OF.text(text);
			
			GeoTest.NAME.text(current["name"]);
		}
		
		GeoTest.CAPITAL.val("").removeAttr("disabled")[0].focus();
	}
}

$(function() {
	GeoTest.NAME = $("#country");
	GeoTest.CAPITAL = $("#capital");
	GeoTest.FORM = $("form");
	GeoTest.ONE_OF = $("#one-of");
	
	GeoTest.data.reload(function () {
		GeoTest.ui.next();
	});
	
	GeoTest.FORM.submit(function () {
		var guess = GeoTest.CAPITAL.val();
		
		var right = false;
		var correction = "";
		
		if (GeoTest.data.isArray(GeoTest.state.capital)) {
			for (var i in GeoTest.state.capital) {
				var capital = GeoTest.state.capital[i];
				
				right = GeoTest.data.compare(guess, capital);
				
				if (right) {
					GeoTest.state.capital.splice(i, 1);
					break;
				}
			}
			
			correction = GeoTest.state.country.capital.join(", ");
		} else {
			right = GeoTest.data.compare(guess, GeoTest.state.capital);
			
			correction = GeoTest.state.capital;
		}
		
		if (right) {
			GeoTest.ui.next();
		} else {
			
			GeoTest.state.capital = [];
			
			GeoTest.CAPITAL[0].blur();
			GeoTest.CAPITAL.attr("disabled", "disabled").val(correction);
			
			var body = $("body").css({backgroundColor:"#900"});
			
			setTimeout(function () { body.css({backgroundColor:""})}, 50);

			setTimeout(function () { GeoTest.ui.next(); }, 5 * 1000);
		}
		
		return false;
	})
	
	var pageTracker = _gat._getTracker("UA-8382002-1");
	pageTracker._trackPageview();
});
