function handleAJAXResponse() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			var response = req.responseText;
			hits = response.split('|');
			if((hits[0].search(/No/)) == 0) {
				map.zoomOut();
				get_points(1);
			} else {
				for (var i = 1; i < hits.length; i++) {
					var lat = hits[i];
					i++;
					var lon = hits[i];
					var point = new GLatLng(lat,lon);
					i++;
					var name = hits[i];
					i++;
					var html = hits[i];
					i++;
					var m_icon = hits[i];
					if(m_icon == 'pointIcon') {
						m_icon = pointIcon;
					} else if (m_icon == 'c1') {
						m_icon = c1Icon;
					} else if (m_icon == 'c2') {
						m_icon = c2Icon;
					} else {
						m_icon = c3Icon;
					}
					// single marker add without manager
					var marker = createMarker(point,name,html,m_icon);
					map.addOverlay(marker);

					// if there is a studio at the exact center of the map, then open the info window (probably came from the studios page
					var center = map.getCenter();
					if(center.lat() == point.lat() && center.lng() == point.lng()) {
						GEvent.trigger(marker,"click");
					}
				}
			}
			document.getElementById('bounds').innerHTML = hits[0]+'<ul>'+side_bar_html+'</ul>';
		}
	}
}

function createMarker(point,name,html,m_icon) {
	var marker = new GMarker(point,m_icon);
	GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });
	// save the info we need to use later for the side_bar
	gmarkers[i] = marker;
	htmls[i] = html;
	// add a line to the side_bar html
	side_bar_html += '<li><a href="javascript:myclick(' + i + ')">' + name + '</a></li>';
	i++;
	return marker;
}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

function get_points(no_hits,x) {
	var no_hits = (no_hits == null) ? "0" : no_hits; // if no_hits not passed default to 0
	var x = (x == null) ? "0" : x;  // if no x passed default to 0
	side_bar_html = '';
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var lngSpan = northEast.lng() - southWest.lng();
	var z = map.getZoom();
	ajax_request('/get_points.html?sw_lat='+southWest.lat()+'&sw_lon='+southWest.lng()+'&ne_lat='+northEast.lat()+'&ne_lon='+northEast.lng()+'&z='+z+'&no_hits='+no_hits+'&x='+x,handleAJAXResponse);
}

function handle_zoom(oldZ,newZ) {
	if((oldZ < 9 && newZ >= 9) || ( oldZ > 8 && newZ <= 8) || (oldZ > 3 && newZ <= 3)) {
		map.clearOverlays();
		GEvent.trigger(map,"moveend");
	}
}

