// JavaScript Document
var map;
var world_level = 15;
var country_level = 14;
var region_level = 11;
var lat;
var lng;
var geoZoomLevel;
var mapZoomLevel;
var mapToLoad;
var loadedMarkers = new Array();
var loadedMarkersHtml = new Array();
var loadedMarkersIdx = new Array();
var latestMarkerUrl = "";
var pendingInfoWindow = false;
var pendingInfoWindowIdx;
var isInloadingPeriod = false;
if (!GBrowserIsCompatible()) {
	console = false;
}
function pageLoad() {
	allPagesOnLoad();
	if (!GBrowserIsCompatible()) {
		document.getElementById("html_content").style.zIndex = 2;
		document.getElementById("html_content").style.visibility = "visible";
		document.getElementById("html_content_noscript").style.zIndex = 1;
		document.getElementById("html_content_noscript").style.visibility = "hidden";
		document.getElementById("content_frame").style.zIndex = 0;
		document.getElementById("content_frame").style.visibility = "hidden";
		document.getElementById("html_content_inner").innerHTML = document.getElementById("html_content_noscript_inner").innerHTML;
	}
	if (GBrowserIsCompatible()) {
		document.getElementById("content_frame").style.zIndex = 2;
		document.getElementById("content_frame").style.visibility = "visible";
		document.getElementById("html_content").style.zIndex = 1;
		document.getElementById("html_content").style.visibility = "hidden";
		document.getElementById("html_content_noscript").style.zIndex = 0;
		document.getElementById("html_content_noscript").style.visibility = "hidden";

		document.getElementById("map_header").style.visibility = "visible";
		document.getElementById("search_frame").style.visibility = "visible";
		document.getElementById("map").style.visibility = "visible";
		document.getElementById("results").style.visibility = "visible";
		document.getElementById("html_content").style.visibility = "hidden";
		map = new GMap(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());

		GEvent.addListener(map, "moveend", function() {
			markersLoading(true);
			if (map.getZoomLevel() >= country_level) {
				if (geoZoomLevel != 3) {
					geoZoomLevel = 3;
					clearAllMarkers()
				}
				loadMarkers("/user_map_country.xml?minLng=" + map.getBoundsLatLng().minX + "&maxLng=" + map.getBoundsLatLng().maxX + "&minLat=" + map.getBoundsLatLng().minY + "&maxLat=" + map.getBoundsLatLng().maxY);
			} else if (map.getZoomLevel() >= region_level) {
				if (geoZoomLevel != 2) {
					geoZoomLevel = 2;
					clearAllMarkers()
				}
				loadMarkers("/user_map_region.xml?minLng=" + map.getBoundsLatLng().minX + "&maxLng=" + map.getBoundsLatLng().maxX + "&minLat=" + map.getBoundsLatLng().minY + "&maxLat=" + map.getBoundsLatLng().maxY);
			} else {
				if (geoZoomLevel != 1) {
					geoZoomLevel = 1;
					clearAllMarkers()
				}
				loadMarkers("/user_map_city.xml?minLng=" + map.getBoundsLatLng().minX + "&maxLng=" + map.getBoundsLatLng().maxX + "&minLat=" + map.getBoundsLatLng().minY + "&maxLat=" + map.getBoundsLatLng().maxY);
			}
		});
		GEvent.addListener(map, "zoom", function(oldZoomLevel, newZoomLevel) {
			markersLoading(true);
			var isLoadingNewFile = false;
			if (newZoomLevel >= country_level) {
				geoZoomLevel = 3;
				if (oldZoomLevel < country_level) {
					clearAllMarkers();
					isLoadingNewFile = true;
					loadMarkers("/user_map_country.xml?minLng=" + map.getBoundsLatLng().minX + "&maxLng=" + map.getBoundsLatLng().maxX + "&minLat=" + map.getBoundsLatLng().minY + "&maxLat=" + map.getBoundsLatLng().maxY);
				}
			} else if (newZoomLevel >= region_level) {
				geoZoomLevel = 2;
				if (oldZoomLevel < region_level || oldZoomLevel >= country_level) {
					clearAllMarkers();
					isLoadingNewFile = true;
					loadMarkers("/user_map_region.xml?minLng=" + map.getBoundsLatLng().minX + "&maxLng=" + map.getBoundsLatLng().maxX + "&minLat=" + map.getBoundsLatLng().minY + "&maxLat=" + map.getBoundsLatLng().maxY);
				}
			} else {
				geoZoomLevel = 1;
				if (oldZoomLevel >= region_level) {
					clearAllMarkers();
					isLoadingNewFile = true;
					loadMarkers("/user_map_city.xml?minLng=" + map.getBoundsLatLng().minX + "&maxLng=" + map.getBoundsLatLng().maxX + "&minLat=" + map.getBoundsLatLng().minY + "&maxLat=" + map.getBoundsLatLng().maxY);
				}
			} 
			if (!isLoadingNewFile) {
				markersLoading(false);
			}
		});
	} 


	if (document.getElementById("lat").value.length > 0) {
			lat = document.getElementById("lat").value;
		} else {
			lat = 0.000000;
		}
		if (document.getElementById("lng").value.length > 0) {
			lng = document.getElementById("lng").value;
		} else {
			lng = 0.000000;
		}
		if (document.getElementById("geoZoomLevel").value.length > 0) {
			geoZoomLevel = parseInt(document.getElementById("geoZoomLevel").value);
		} else {
			geoZoomLevel = 3;
		}
		if (geoZoomLevel == 1) {
			mapZoomLevel = region_level - 1;
			mapToLoad = "/user_map_city.xml";
		} else if (geoZoomLevel == 2) {
			mapZoomLevel = country_level - 1;
			mapToLoad = "/user_map_region.xml";
		} else {
			mapZoomLevel = world_level;
			mapToLoad = "/user_map_country.xml";
		}
		if (document.getElementById("city").value.length > 0 || document.getElementById("region_code").value.length > 0 || document.getElementById("region").value.length > 0 || document.getElementById("country_code").value.length > 0 || document.getElementById("country").value.length > 0 ) {
			geoSearch(document.getElementById("city").value, document.getElementById("region_code").value, document.getElementById("region").value, document.getElementById("country_code").value, document.getElementById("country").value, lat, lng, geoZoomLevel);
			if (lat == 0.000000 && lng == 0.000000) {
				map.centerAndZoom(new GPoint(lng, lat), mapZoomLevel);
			}
		} else if (document.getElementById("q").value.length > 0) {
			geoSearch('', '', '', '', '', lat, lng, 4);
			if (lat == 0.000000 && lng == 0.000000) {
				map.centerAndZoom(new GPoint(lng, lat), mapZoomLevel);
			}
		} else {
			loadMarkers(mapToLoad);
			map.centerAndZoom(new GPoint(lng, lat), mapZoomLevel);
		}
/*		if (document.getElementById("q").value.length > 0 || document.getElementById("row_count").value.length > 0 || document.getElementById("offset").value.length > 0 || document.getElementById("link_user_id").value.length > 0 ) {
			var row_count;
			var offset;
			if (document.getElementById("row_count").value.length > 0 ) {
				row_count = document.getElementById("row_count").value;
			} else {
				row_count = 5;
			}
			if (document.getElementById("offset").value.length > 0 ) {
				row_count = document.getElementById("offset").value;
			} else {
				offset = 0;
			}
			textSearch(document.getElementById("q").value, row_count, offset, document.getElementById("city").value, document.getElementById("region").value, document.getElementById("country").value, document.getElementById("link_user_id").value);	
		}
*/
	pageOnResize();
}
function markersLoading(isLoading) {
	if (isLoading) {
		document.getElementById("loading").style.visibility = "visible";
		isInLoadingPeriod = true;
		window.setTimeout(function() {
  			isInLoadingPeriod = false;
		}, 3000);
	} else {
		if (isInLoadingPeriod) {
			window.setTimeout(function() {
				isInLoadingPeriod = false;
				document.getElementById("loading").style.visibility = "hidden";
			}, 1000);
		} else {
			document.getElementById("loading").style.visibility = "hidden";
		}
	}
}
function openInfoWindow(idx) {
	if (loadedMarkersIdx.inArray(idx)) {
		loadedMarkers[idx].openInfoWindowHtml(loadedMarkersHtml[idx]);
		pendingInfoWindow = false;
		pendingInfoWindowIdx = null;
	} else {
		pendingInfoWindow = true;
		pendingInfoWindowIdx = idx; 
	}
}
function clearAllMarkers() {
	map.clearOverlays();
	loadedMarkers = new Array();
	loadedMarkersHtml = new Array();
	loadedMarkersIdx = new Array();
}
function loadMarkers(url) {
	latestMarkerUrl = url;
	markersLoading(true);
	var request = GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange = function() {
	  if (request.readyState == 4) {
	    if (url == latestMarkerUrl) {
		  var xmlDoc = request.responseXML;
//		  xmlDoc.documentElement.getElementsByTagName("offset")[0].firstChild.nodeValue
		  var num_rows = xmlDoc.documentElement.getElementsByTagName("num_rows")[0].firstChild.nodeValue;
		  if (num_rows > 0) {
		    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		    for (var i = 0; i < markers.length; i++) {
			  var idx = markers[i].getAttribute("lat") + "," + markers[i].getAttribute("lng");
			  if (!loadedMarkersIdx.inArray(idx)) {
	//		    var html_elements = markers[i].getElementsByTagName("html");
	//		    var html = html_elements[0].text;
			    var country_code = markers[i].getAttribute("country_code");
			    var region_code = markers[i].getAttribute("region_code");
			    var city = markers[i].getAttribute("city");
			    var html = get_location(city, region_code, markers[i].getAttribute("region"), country_code, markers[i].getAttribute("country"), markers[i]) + "<br /><br />" + get_profile_num(markers[i].getAttribute("num_profiles"));
				html = "<div style=\"width:" + ((city.length + markers[i].getAttribute("region").length + markers[i].getAttribute("country").length + 4) * 7) + "px;\">" + html + "<\/div>"
			    var marker = createMarker(markers[i].getAttribute("lat"), markers[i].getAttribute("lng"));
			    map.addOverlay(marker);
			    loadedMarkersHtml[idx] = html;
			    loadedMarkers[idx] = marker;
			    loadedMarkersIdx[loadedMarkersIdx.length + 1] = idx;
			  }
		    }
		  }
		}
	    markersLoading(false);
		if (pendingInfoWindow) {
			openInfoWindow(pendingInfoWindowIdx); 			
		}
//		checkForInfoWindow();
	  }
	}
	request.send(null);
}
function createMarker(lat, lng) {
	var idx = lat + "," + lng;
    var point = new GPoint(parseFloat(lng),
		parseFloat(lat));
	var icon = new GIcon();
	switch (geoZoomLevel) {
		case 3:
			icon.image = "http://www.gtalkprofile.com/images/mm_20_red.png";
			break;
		case 2:
			icon.image = "http://www.gtalkprofile.com/images/mm_20_yellow.png";
			break;
		case 1:
			icon.image = "http://www.gtalkprofile.com/images/mm_20_green.png";
			break;
	}
	icon.shadow = "http://www.gtalkprofile.com/images/mm_20_shadow.png";
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	var marker = new GMarker(point, icon);
	// Show this marker's index in the info window when it is clicked
	GEvent.addListener(marker, "click", function() {
		openInfoWindow(idx);
	});
	return marker;
}
function get_location(city, region_code, region, country_code, country, marker) {
	location_str = "";
	if (city.length > 0) {
		location_str = location_str + "<a href='javascript:geoSearch(\"" + escape(city) + "\",\"" + escape(region_code) + "\",\"" + escape(region) + "\",\"" + escape(country_code) + "\",\"" + escape(country) + "\",\"" + marker.getAttribute("city_lat") + "\",\"" + marker.getAttribute("city_lng") + "\",1,false);'>";
		location_str = location_str + city;
		location_str = location_str + "<\/a>";
	}
	if (city.length > 0 && (region.length > 0 || country.length > 0)) {
		location_str = location_str + ", ";
	}
	if (region.length > 0 && region != country) {
		location_str = location_str + "<a href='javascript:geoSearch(\"\",\"" + escape(region_code) + "\",\"" + escape(region) + "\",\"" + escape(country_code) + "\",\"" + escape(country) + "\",\"" + marker.getAttribute("region_lat") + "\",\"" + marker.getAttribute("region_lng") + "\",2,false);'>";
		location_str = location_str + region;
		location_str = location_str + "<\/a>";
	}
	if (region.length > 0 && region != country && country.length > 0) {
		location_str = location_str + ", ";
	}
	if (country.length > 0) {
		location_str = location_str + "<a href='javascript:geoSearch(\"\",\"\",\"\",\"" + escape(country_code) + "\",\"" + escape(country) + "\",\"" + marker.getAttribute("country_lat") + "\",\"" + marker.getAttribute("country_lng") + "\",3,false);'>";
		location_str = location_str + country;
		location_str = location_str + "<\/a>";
	}
	return location_str;
}

function panAndZoom(theLat, theLng, zoomLevel) {
	var thePoint = new GPoint(theLng, theLat);
	if (map.getZoomLevel() != zoomLevel) {
		if (map.getCenterLatLng() != thePoint) {
			map.centerAndZoom(thePoint, zoomLevel);
		} else {
			map.zoomTo(zoomLevel);
		}
	} else {
		if (map.getCenterLatLng() != thePoint) {
			map.recenterOrPanToLatLng(thePoint);
		}
//		map.zoomTo(zoomLevel);
	}
	var idx = theLat + "," + theLng;
	openInfoWindow(idx);
//	map.centerAtLatLng(new GPoint(theLng, theLat));
}
function textSearch(q, row_count, offset, city, region_code, country_code, link_user_id) {
	markersLoading(true);
	document.getElementById("q").value = q;
	document.getElementById("row_count").value = row_count;
	document.getElementById("offset").value = offset;
	document.getElementById("city").value = city;
	document.getElementById("region_code").value = region_code;
	document.getElementById("country_code").value = country_code;
	document.getElementById("link_user_id").value = link_user_id;
	var search_url = "/search.xml?q=" + q + "&row_count=" + row_count + "&offset=" + offset + "&city=" + city + "&region_code=" + region_code + "&region=" + document.getElementById("region").value + "&country_code=" + country_code + "&country=" + document.getElementById("country").value + "&link_user_id=" + link_user_id + "&lat=" + document.getElementById("lat").value + "&lng=" + document.getElementById("lng").value + "&geoZoomLevel=" + document.getElementById("geoZoomLevel").value;
	load_search_results(search_url);
}
function geoSearch(city, region_code, region, country_code, country) {
	markersLoading(true);
	document.getElementById("city").value = city;
	document.getElementById("region_code").value = region_code;
	document.getElementById("region").value = region;
	document.getElementById("country_code").value = country_code;
	document.getElementById("country").value = country;
	document.getElementById("offset").value = 0;
	var theLat;
	var theLng;
	var gZoomLevel;
	var mapZoomLevel;
	if (geoSearch.arguments.length > 5) {
		theLat = geoSearch.arguments[5];
		document.getElementById("lat").value = theLat;
		theLng = geoSearch.arguments[6];
		document.getElementById("lng").value = theLng;
		gZoomLevel = geoSearch.arguments[7];
		geoZoomLevel = gZoomLevel;
		document.getElementById("geoZoomLevel").value = geoZoomLevel;
		if (geoZoomLevel > 3) {
			geoZoomLevel = 3;
		}
		if (gZoomLevel == 1) {
			if (map.getZoomLevel() > 0 && map.getZoomLevel() < region_level) {
				mapZoomLevel = map.getZoomLevel();
			} else {
				mapZoomLevel = region_level - 1;
			}
		} else if (gZoomLevel == 2) {
			if (map.getZoomLevel() >= region_level && map.getZoomLevel() < country_level) {
				mapZoomLevel = map.getZoomLevel();
			} else {
				mapZoomLevel = country_level - 1;
			}
		} else if (gZoomLevel == 3) {
			if (map.getZoomLevel() >= country_level) {
				mapZoomLevel = map.getZoomLevel();
			} else {
				mapZoomLevel = world_level - 1;
			}
		} else {
			mapZoomLevel = world_level;
			map.closeInfoWindow();
		}
		if (geoSearch.arguments.length != 9 && theLat.length > 0 && theLng.length > 0) { 
			panAndZoom(theLat, theLng, mapZoomLevel);
		}
	}
	buildGeoBreadCrumb(country, country_code, region, region_code, city);
	textSearch(document.getElementById("q").value, document.getElementById("row_count").value, document.getElementById("offset").value, city, region_code, country_code, document.getElementById("link_user_id").value);
}
function buildGeoBreadCrumb(country, country_code, region, region_code, city) {
	var url = "/geocode.xml" + "?country_code=" + country_code + "&region_code=" + region_code + "&city=" + city;
	var request = GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			var country_lat = xmlDoc.documentElement.getElementsByTagName("country")[0].getAttribute("lat");
			var country_lng = xmlDoc.documentElement.getElementsByTagName("country")[0].getAttribute("lng");
			var region_lat = xmlDoc.documentElement.getElementsByTagName("region")[0].getAttribute("lat");
			var region_lng = xmlDoc.documentElement.getElementsByTagName("region")[0].getAttribute("lng");
			var city_lat = xmlDoc.documentElement.getElementsByTagName("city")[0].getAttribute("lat");
			var city_lng = xmlDoc.documentElement.getElementsByTagName("city")[0].getAttribute("lng");
			var geoHtml = "";
			geoHtml = geoHtml + "<a href='javascript:geoSearch(\"\",\"\",\"\",\"\",\"\",\"0.0000\",\"0.0000\",\"4\")'>Earth<\/a>";
			if (country.length > 0) {
				geoHtml = geoHtml + " -&gt; ";		
				geoHtml = geoHtml + "<a href='javascript:geoSearch(\"\",\"\",\"\",\"" + escape(country_code) + "\",\"" + escape(country) + "\",\"" + country_lat + "\",\"" + country_lng + "\",3)'>" + country  + "<\/a>";		
			}
			if (region.length > 0) {
				geoHtml = geoHtml + " -&gt; ";		
				geoHtml = geoHtml + "<a href='javascript:geoSearch(\"\",\"" + escape(region_code) + "\",\"" + escape(region) + "\",\"" + escape(country_code) + "\",\"" + escape(country) + "\",\"" + region_lat + "\",\"" + region_lng + "\",2)'>" + region  + "<\/a>";		
			}
			if (city.length > 0) {
				geoHtml = geoHtml + " -&gt; ";
				geoHtml = geoHtml + "<a href='javascript:geoSearch(\"" + escape(city) + "\",\"" + (region_code) + "\",\"" + escape(region) + "\",\"" + escape(country_code) + "\",\"" + escape(country) + "\",\"" + city_lat + "\",\"" + city_lng + "\",1)'>" + city  + "<\/a>";
			}
			document.getElementById("geo_breadcrumb").innerHTML = geoHtml;
		}
	}
	request.send(null);
}

function load_search_results(search_url) {
	var request = GXmlHttp.create();
	request.open("GET", search_url, true);
	urchinTracker(search_url);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			var profiles = xmlDoc.documentElement.getElementsByTagName("profile");
			var html = "<div>";
			if (profiles.length > 0) {
				html = html + "<p>";
				html = html + "Showing results " + (parseInt(xmlDoc.documentElement.getElementsByTagName("offset")[0].firstChild.nodeValue) + 1) + " through " + (parseInt(xmlDoc.documentElement.getElementsByTagName("offset")[0].firstChild.nodeValue) + parseInt(xmlDoc.documentElement.getElementsByTagName("num_rows")[0].firstChild.nodeValue)) + " of " + parseInt(xmlDoc.documentElement.getElementsByTagName("total_rows")[0].firstChild.nodeValue) + " profile";
				if (parseInt(xmlDoc.documentElement.getElementsByTagName("total_rows")[0].firstChild.nodeValue) > 1) {
					html = html + "s";
				}
				html = html + ".";
				html = html + "<\/p>";
				for (var i = 0; i < profiles.length; i++) {
					var user_id = profiles[i].getAttribute("user_id");
	//				var foo;
	//				foo = profiles[i].getElementsByTagName("profile_link");
	//				var profile_link = foo[0].text;
					var profile_link = profiles[i].getElementsByTagName("profile_link")[0].firstChild.nodeValue;
					var name = profiles[i].getElementsByTagName("name")[0].firstChild.nodeValue;
					var about_summary = profiles[i].getElementsByTagName("about_summary")[0].firstChild.nodeValue;
					var email_output = profiles[i].getElementsByTagName("email_output")[0].firstChild.nodeValue;
					var location_output = profiles[i].getElementsByTagName("location_output_ajax")[0].firstChild.nodeValue;
					html = html + "<p>";
					html = html + "<a href=\"" + profile_link + "\">";
					html = html + "<strong>";
					html = html + name;
					html = html + "<\/strong>";
					html = html + "<\/a> ";
					html = html + email_output;
					html = html + "<br \/>";
					html = html + about_summary;
					html = html + "<br \/>";
					html = html + location_output;
					html = html + "<\/p>";
				}
				html = html + "<div style=\"width:100%;\">";
				if (parseInt(xmlDoc.documentElement.getElementsByTagName("offset")[0].firstChild.nodeValue) > 0) {
					html = html + "<div style=\"float:left;\"><a href='javascript:textSearch(\"" + document.getElementById("q").value + "\", \"" + document.getElementById("row_count").value + "\", \"" + (parseInt(document.getElementById("offset").value) - parseInt(document.getElementById("row_count").value)) + "\", \"" + document.getElementById("city").value + "\", \"" + document.getElementById("region_code").value + "\", \"" + document.getElementById("country_code").value + "\", \"" + document.getElementById("link_user_id").value + "\");'>&lt; &lt; previous<\/a><\/div>";
				}
				if (parseInt(xmlDoc.documentElement.getElementsByTagName("total_rows")[0].firstChild.nodeValue) > (parseInt(xmlDoc.documentElement.getElementsByTagName("offset")[0].firstChild.nodeValue) + parseInt(xmlDoc.documentElement.getElementsByTagName("num_rows")[0].firstChild.nodeValue))) {
					html = html + "<div style=\"float:right;\"><a href='javascript:textSearch(\"" + document.getElementById("q").value + "\", \"" + document.getElementById("row_count").value + "\", \"" + (parseInt(document.getElementById("offset").value) + parseInt(document.getElementById("row_count").value)) + "\", \"" + document.getElementById("city").value + "\", \"" + document.getElementById("region_code").value + "\", \"" + document.getElementById("country_code").value + "\", \"" + document.getElementById("link_user_id").value + "\");'>next &gt; &gt;<\/a><\/div>";
				}
				html = html + "<\/div>";
			} else {
				html = html + "<p>";
				html = html + "There are no results to display.";
				html = html + "<\/p>";
			}			
			html = html + "<\/div>";
			document.getElementById("results").innerHTML = html;
			markersLoading(false);
		}
	}
	request.send(null);
}

function get_profile_num(num_profiles) {
	profile_num_str = "";
	profile_num_str = profile_num_str + num_profiles;
	profile_num_str = profile_num_str + " profile";
	if (num_profiles > 1) {
		profile_num_str = profile_num_str + "s";
	}
	return profile_num_str;
}
