geo = function () {
	var maps_appid = 'EhZddZHV34FAWSysO3xqfEq5EO42zRrtW1YBZbynu.G2Lc01_Eg4j7re_dS8s5z0fA--',
		//gmaps_api = 'ABQIAAAAjVE7EpGfYp2HHiMZIhMOHBRkkVTuzYFyQzZENT18TTVAigJIzBRTpNJftg2fkHm7srH_M1TkU4zIyg',
		gmaps_api = 'ABQIAAAAGpLi0-hqoha_dC3-tr5gYRSbwe2X2m0Jp2Nnqe4kS8CKg6gtbhTr6UcieIoaXveLx3DnPy7n-DpJFg',
		geo_appid = 'HM9QAWLV34HhHmvoaY6EoacEKGWerL2rWlEWUSgz7FLWHhIty7UpVA9LpGENxwmVwQ--',
		map = null // map object beneath Pong;

	function empty_matrix(w, h) {
		var matrix = [], i=0;
		matrix.length = w;
		for(;i<w;i++) {
			matrix[i] = [];
			matrix[i].length = h;
		}
		return matrix;
	}

	function clean_geo_info(json) {
		var geo = {},
			interesting = null, bb = null;
		if (json.places.count) {
			interesting = json.places.place[0];

			geo.woeid = interesting.woeid;
			bb = interesting.boundingBox;
			geo.bbox = [bb.southWest.longitude, bb.southWest.latitude,
						bb.northEast.longitude, bb.northEast.latitude];
			geo.coordinates = [interesting.centroid.longitude,
								interesting.centroid.latitude];
		}
		return geo;
	}

	function clean_geo_images(json) {
		var xml_photos = json.query.results.photo,
			photos = [];
		$(xml_photos).each(function () {
			photos.push({
//				'woeid': this.location.woeid,
//				'coordinates': [this.location.longitude, this.location.latitude],
				'woeid': this.woeid,
				'coordinates': [this.longitude, this.latitude],
				'url': "http://farm"+this.farm+".static.flickr.com/"+this.server+"/"+this.id+"_"+this.secret+"_s.jpg"
			});
		});
		return photos;
	}

	function get_geo_info(place, func) {
		var url = 'http://where.yahooapis.com/v1/places.q(%27'+encodeURIComponent(place)+'%27)?appid='+geo_appid+'&format=json&callback=?';
		$.getJSON(url, func);
	}

	function get_geo_images(geo, func) {
		var bbox = encodeURIComponent(geo.bbox.join(",")),
//			url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20flickr.photos.info%20where%20photo_id%20in%20(select%20id%20from%20flickr.photos.search(40)%20where%20bbox%3D%22"+bbox+"%22%20and%20license%3D%221%2c2%2c3%2c4%2c5%2c6%2c7%22)&format=json&callback=?";
			url = "http://query.yahooapis.com/v1/public/yql?q=select%20farm%2Cserver%2Cid%2Csecret%2Clatitude%2Clongitude%2Cwoe%20from%20flickr.photos.search(100)%20where%20bbox%3D%22"+bbox+"%22%20and%20license%3D%221%2C2%2C3%2C4%2C5%2C6%2C7%22%20and%20extras%3D%22geo%22&format=json&callback=?";
		$.getJSON(url, func);
	}

	function get_map_image(geo, size) {
		var coord = geo.coordinates,
			bbox = geo.bbox,
			url = "http://maps.google.com/staticmap?center="+coord[1]+"%2c"+coord[0]+"&size="+size[0]+"x"+size[1]+"&key="+gmaps_api+"&sensor=false&maptype=satellite";
		url += "&span="+(bbox[2]-bbox[0])+"%2c"+(bbox[3]-bbox[1]);
		return url;
	}

	function save_images(json) {
		var clean = clean_geo_images(json),
			qw = (geo.bbox[2]-geo.bbox[0])/geo.boxw,
			qh = (geo.bbox[3]-geo.bbox[1])/geo.boxh,
			i = 0, x = 0, y = 0;

		// Go through images and save them in their quadrant
		for(;i<clean.length;i++) {
			x = Math.floor((clean[i].coordinates[0]-geo.bbox[0])/ qw);
			y = Math.floor((geo.bbox[3]-clean[i].coordinates[1])/ qh);
			if (!geo.quadrants[x][y]) {
				// No image yet. Add it!
				geo.quadrants[x][y] = clean[i].url;
				$('<img src="' + clean[i].url + '" alt="" />').appendTo('body').hide().bind('load', function () {$(this).remove();});
			}
		}
	}

	window.start_geo = function(q) {
		get_geo_info(q, function (json) {
			var clean = clean_geo_info(json);
			geo.woeid = clean.woeid;
			geo.coordinates = clean.coordinates;
			geo.bbox = clean.bbox;
	
			// Set pong bg
			var back = get_map_image(geo, [640,480]), i = 0;
			setbg = function () {
				$('<img src="' + back + '" alt="" />').appendTo('body').hide().bind('load', function () {
					$(this).remove();
					$("#pongbg").css("background-image", "url("+back+")");
				}).bind('error', function () {
					$(this).remove();
					i += 1;
					if (i < 10) {
						setbg();
					}
				});
			}
			setbg();
	
			// Fetch ball images and save them into quadrant matrix
			get_geo_images(geo, save_images);
		});
	}

	window.changeImage = function (sqx, sqy) {
		if (geo.quadrants[sqx][sqy]) {
			$(".ball").css("background-image", "url("+geo.quadrants[sqx][sqy]+")");
		}
	}


	var geo = {
		boxw : 16,
		boxh : 12,
		quadrants : empty_matrix(16, 12),
		get_info: get_geo_info,
		get_images: get_geo_images
	};
	return geo;

}();

