var gmarkers = [];
var map;
var stationinfo = new google.maps.InfoWindow();

// A function to create the marker and set up the event window
function createMarker(point, name, description, url, id) {
	var marker = new google.maps.Marker({
		position : point,
		clickable : true,
		title : name,
		map : map
	});
	google.maps.event.addListener(marker, "click", function() {
		document.getElementById("output").innerHTML = '<a href=\"' + url
				+ '\">' + name + '</a>';
		// stationinfo.open(map, marker);
	});
	// save the info we need to use later for the side_bar
	//gmarkers[id] = marker;
	gmarkers.push(marker);
	return marker;
}

function GetNewMarkers() {
	// get boundries
	var bounds = map.getBounds();
	var swlat = bounds.getSouthWest().lat();
	var swlong = bounds.getSouthWest().lng();
	var nelong = bounds.getNorthEast().lng();
	var nelat = bounds.getNorthEast().lat();
	var request_string = '/tuner/geo.json?stream_formats=icy&swlat=' + swlat
			+ '&nelat=' + nelat + '&swlong=' + swlong + '&nelong=' + nelong;

	//document.forms[0]['email'].value = request_string;	
	// get new markers
	var ListenEventsObject = {};
	var request = new XMLHttpRequest();
	request.open("GET", request_string, true);
	loading = 1;
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			ListenEventsObject = eval('(' + request.responseText + ')');
			for (var le = 0; le < ListenEventsObject.listen_events.length; le++) {
				var point = new google.maps.LatLng(
						ListenEventsObject.listen_events[le].point[1],
						ListenEventsObject.listen_events[le].point[0]);
				var description = ListenEventsObject.listen_events[le].description;
				var name = ListenEventsObject.listen_events[le].name;
				var id = ListenEventsObject.listen_events[le].entry_id;
				var url = ListenEventsObject.listen_events[le].url;
				createMarker(point, name, description, url, id);
			}
		}
	}
	request.send(null);
}

function RefreshMarkers() {
	ClearMarkers();
	GetNewMarkers();
}

function ClearMarkers() {
	// clear old markers
	if (gmarkers.length > 0) {
		for (var ii = 0; ii < gmarkers.length; ii++) {
			gmarkers[ii].setMap(null);
		}
	}
	gmarkers = [];
}

function detectBrowser() {
	var useragent = navigator.userAgent;
	var mapdiv = document.getElementById("map_canvas");

	if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1) {
		mapdiv.style.width = '100%';
		mapdiv.style.height = '100%';
	} else {
		mapdiv.style.width = '500px';
		mapdiv.style.height = '300px';
	}
}

Function.prototype.debounce = function(threshold, execAsap) {
	var func = this, // reference to original function
	timeout; // handle to setTimeout async task (detection period)
	// return the new debounced function which executes the original function
	// only once
	// until the detection period expires
	return function debounced() {
		var obj = this, // reference to original context object
		args = arguments; // arguments at execution time
		// this is the detection function. it will be executed if/when the
		// threshold expires
		function delayed() {
			// if we're executing at the end of the detection period
			if (!execAsap)
				func.apply(obj, args); // execute now
			// clear timeout handle
			timeout = null;
		}
		;
		// stop any current detection period
		if (timeout)
			clearTimeout(timeout);
		// otherwise, if we're not already waiting and we're executing at the
		// beginning of the detection period
		else if (execAsap)
			func.apply(obj, args); // execute now
		// reset the detection period
		timeout = setTimeout(delayed, threshold || 100);
	};
};

// startup map
function map_initialize() {
	// detectBrowser();
	var sanfran = new google.maps.LatLng(37.62510898062149, -122.1514892578125);
	var myOptions = {
		zoom : 7,
		center : sanfran,
		mapTypeControl : false,
		navigationControl : true,
		navigationControlOptions : {
			style : google.maps.NavigationControlStyle.SMALL
		},
		mapTypeId : google.maps.MapTypeId.HYBRID
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	google.maps.event.addListener(map, "idle", RefreshMarkers.debounce(500));
	//google.maps.event.addListener(map, "idle", RefreshMarkers());

	// Try W3C Geolocation (Preferred)
	if (navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
			initialLocation = new google.maps.LatLng(position.coords.latitude,
					position.coords.longitude);
			map.setCenter(initialLocation);
			addLinkLocationInfo(position.coords.latitude,
					position.coords.longitude);
		}, function() {
			handleNoGeolocation(browserSupportFlag);
		});
		// Try Google Gears Geolocation
	} else if (google.gears) {
		browserSupportFlag = true;
		var geo = google.gears.factory.create('beta.geolocation');
		geo.getCurrentPosition(function(position) {
			initialLocation = new google.maps.LatLng(position.latitude,
					position.longitude);
			map.setCenter(initialLocation);
			addLinkLocationInfo(position.latitude, position.longitude);
		}, function() {
			handleNoGeoLocation(browserSupportFlag);
		});
		// Browser doesn't support Geolocation
	} else {
		browserSupportFlag = false;
		handleNoGeolocation(browserSupportFlag);
	}

	function addLinkLocationInfo(lat, lng) {
		var as = document.getElementsByTagName("a");
		var len = as.length;
		for ( var i = 0; i < len; i++) {
			if (as[i].href.match(/listen/)) {
				as[i].href = as[i].href + '&lat=' + lat + '&long=' + lng;
			}
		}
	}

	function handleNoGeolocation(errorFlag) {
		// keep on keeping on
	}
}

