// GOOGLE MAPS API V3
var geoCoder;
var geoMap;
var geoArrMarker = [];
var geoIconOn;
var geoIconOff;
var geoInfo = [];
var geoPInfo;
var geoBounds;
var geoReBound = false;
var geoLat = 0;
var geoLon = 0;

function gLoad() {
	
	divMap = document.getElementById("map_canvas");
	
	if (!geoBounds){
		geoBounds = new google.maps.LatLngBounds ();
	}
	
	if (!geoIconOn){
		geoIconOn = new google.maps.MarkerImage('/img/geoIconOn.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(20, 38),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(5, 37));
	}

	if (!geoIconOff){
		geoIconOff = new google.maps.MarkerImage('/img/geoIconOff.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(20, 38),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(5, 37));
	}
	
	if (divMap){
		geoCoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(31.353637,168.75);
		var myOptions = {
			zoom: 2,
			center: latlng,
			scaleControl: true,
			scrollwheel: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		geoMap = new google.maps.Map(divMap, myOptions);
	}
}

function resetAddress(){

	var geoAdr = document.getElementById("address");	
	var geoHAdr = document.getElementById("haddress");
	
	var geoMsg = document.getElementById("map_message");
	var geoErr = document.getElementById("map_error");
	
	if (geoAdr){geoAdr.value = "";}
	if (geoHAdr){geoHAdr.value = "";}
	
	if (geoMsg){
		geoMsg.style.display = "none";
		geoMsg.innerHTML = "";
	}
	if (geoErr){
		geoErr.style.display = "none";
		geoErr.innerHTML = "";
	}
	geoDeleteOverlays();
	showAddress(geoLat,geoLon);
	
}

function codeAddress(strAdr) {
	
	var geoAdr = document.getElementById("address");	
	var geoHAdr = document.getElementById("haddress");
	
	var geoMsg = document.getElementById("map_message");
	var geoErr = document.getElementById("map_error");

	geoDeleteOverlays();
	
	// DEFAULT AREA
	showAddress(geoLat,geoLon);
	
	// RESET VALUES
	if (geoAdr){geoAdr.value = "";}
	if (geoHAdr){geoHAdr.value = "";}

	if (geoMsg){
		geoMsg.style.display = "none";
		geoMsg.innerHTML = "";
	}
	
	if (geoErr){
		geoErr.style.display = "none";
		geoErr.innerHTML = "";
	}
	
	if (geoMap && strAdr){
		geoCoder.geocode({'address':strAdr},function(results,status){
			if (status == google.maps.GeocoderStatus.OK) {
				if (results.length > 1){
					if (geoMsg){
						geoMsg.style.display = "block";
						geoMsg.innerHTML = "<div style=\"padding:2px;\">Did you mean:</div>";
					}
					for (var i=0; i < results.length; i++){
						if (geoMsg){
							geoMsg.innerHTML += "<div style=\"padding:2px;\" onMouseOver=\"this.style.backgroundColor='#F5F5F5';this.style.fontWeight='bold';\" onMouseOut=\"this.style.backgroundColor='';this.style.fontWeight='';\"><a href=\"JavaScript:void(0);\" onClick=\"codeAddress('" + addSlashes(results[i].formatted_address) + "');\">" + results[i].formatted_address + "</a></div>";
						}
					}
				}else{				
					// Types may return multiple, check all
					// Build error string types
					var dspTyp = "";
					var alwTyp = false;
					var strTyp = results[0].types;
					if (strTyp){
						strTyp = strTyp.toString();
						var arrTyp = strTyp.split(",");
						for (var i=0; i < arrTyp.length; i++){
							// geoType
							var txtTyp = arrTyp[i];
							// Error string
							if (dspTyp){
								dspTyp += " or " + txtTyp;
							}else{
								dspTyp = txtTyp;
							}
							// Match Type
							// Note: removed 'postal_code' because it's not granular enough
							if (txtTyp == "street_address" ||
								txtTyp == "intersection" ||
								txtTyp == "neighborhood" ||
								txtTyp == "establishment"){
								alwTyp = true;
								break;
							}
						}
					}					
					if (alwTyp){
						// Address is the right type
						var thisDistance = havDistance(geoLat,geoLon,results[0].geometry.location.lat(),results[0].geometry.location.lng());
						if (thisDistance > 0){
							if (thisDistance > 25){
								if (geoErr){
									geoErr.style.display = "block";
									geoErr.innerHTML = "Address is more than 25 miles from posted location.";
								}
							}
						}else{
							geoErr.innerHTML = "Aww crap, something happened";
						}
						if (geoAdr){geoAdr.value = results[0].formatted_address;}
						if (geoHAdr){
							geoHAdr.value = results[0].formatted_address + "|" + results[0].geometry.location.lat() + "|" + results[0].geometry.location.lng();
						}
						geoMap.setCenter(results[0].geometry.location);
						geoMap.setZoom(15);
						var geoMarker = new google.maps.Marker({
							map:geoMap, 
							position:results[0].geometry.location,
							title:results[0].formatted_address.toString()
						});
						geoArrMarker.push(geoMarker);
					}else{
						// Address not the right type
						// Display general area
						// error type fouund
						// clear haddress
						// Reset gmap center, zoom
						if (geoAdr){
							geoAdr.value = results[0].formatted_address;
						}
						if (geoErr){
							geoErr.style.display = "block";
							geoErr.innerHTML = "Address close but no banana. You've specified " + dspTyp + ".";
						}
						geoMap.setCenter(results[0].geometry.location);
						geoMap.setZoom(13);
						
						var geoMarker = new google.maps.Marker({
							map:geoMap, 
							position:results[0].geometry.location,
							title:results[0].formatted_address.toString()
						});
						geoArrMarker.push(geoMarker);
						
					}
				}				
			}else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
				// STATUS = NO RESULTS
				if (geoErr){
					geoErr.style.display = "block";
					geoErr.innerHTML = "Address could not be found. Try again";
				}
			}else {
				// STATUS = OVER_QUERY_LIMIT, REQUEST_DENIED, INVALID_REQUEST
				if (geoErr){
					geoErr.style.display = "block";
					geoErr.innerHTML = "Geocoder crapped out. Status is " + status;
				}
			}
		});
	}
}

// Show single address
function showAddress(Address_Lat, Address_Lon){
	if (geoMap){
		if (Address_Lat && Address_Lon){
			geoMap.setCenter(new google.maps.LatLng(Address_Lat, Address_Lon));
			geoMap.setZoom(13);
		}else{
			// DEFAULT GLOBAL VIEW
			geoMap.setCenter(new google.maps.LatLng(31.353637,168.75));
			geoMap.setZoom(2);
		}
	}
}

// Map Markers
function showMarker(Country, Region, City, LSub1, LSub2, AdID, Title, Description, Address, Address_Lat, Address_Lon, Price, Image, Image_Dsc){
	
	if (geoMap && Address_Lat && Address_Lon){
	
		if (AdID){
			
			var geoMarker = new google.maps.Marker({
				map:geoMap, 
				position:new google.maps.LatLng(Address_Lat, Address_Lon),
				title:URLDecode(Title),
				icon:geoIconOff
			});

			// Map
			google.maps.event.addListener(geoMap, "click", function(){
				// Remove hi-lighting from item list
				//unhilitePost(AdID);
				// Close floating infowindow
				closeInfoWindow();
			});
			google.maps.event.addListener(geoMarker, 'click', function() {
				//hilitePost(AdID);
				geoResetMarkers();
				geoMarker.setIcon(geoIconOn);
				loadInfoWindow(Country, Region, City, LSub1, LSub2, AdID, Title, Description, Address, Address_Lat, Address_Lon, Price, Image, Image_Dsc);
			});
			
			geoArrMarker[AdID] = geoMarker;
			
		}else{
			
			var geoMarker = new google.maps.Marker({
				map:geoMap, 
				position:new google.maps.LatLng(Address_Lat, Address_Lon),
				title:URLDecode(Title),
				icon:geoIconOff
			});
			
		}
		
		// EXTEND 'ZOOM TO FIT'
		// ONLY EXTEND IF MARKER IS > 10 MILES FROM CENTER
		geoBounds.extend (new google.maps.LatLng (Address_Lat, Address_Lon));
		var geoDistance = havDistance(geoLat,geoLon,Address_Lat, Address_Lon);
		if (geoDistance > 4){
			geoReBound = true;
		}
	}
}

function loadInfoWindow(Country, Region, City, LSub1, LSub2, AdID, Title, Description, Address, Address_Lat, Address_Lon, Price, Image, Image_Dsc){

	objInfoWindow = document.getElementById("infowindow");
	
	// Details
	objInfoWindow_Title = document.getElementById("infowindow_title");
	objInfoWindow_Description = document.getElementById("infowindow_description");
	objInfoWindow_Address = document.getElementById("infowindow_address");
	objInfoWindow_Price = document.getElementById("infowindow_price");
	objInfoWindow_Image = document.getElementById("infowindow_image");
	
	// Href(s)
	objInfoWindow_LinkItem = document.getElementById("infowindow_linkitem");
	objInfoWindow_MapIt = document.getElementById("infowindow_mapit");
	objInfoWindow_ZoomIn = document.getElementById("infowindow_zoomin");
	
	if (objInfoWindow){
	
		objInfoWindow.style.display = "";
		
		if (objInfoWindow_Title){
			objInfoWindow_Title.innerHTML = Title;
		}
		if (objInfoWindow_Description){
			objInfoWindow_Description.innerHTML = Description;
		}
		if (objInfoWindow_Address){
			objInfoWindow_Address.innerHTML = Address;
		}
		if (objInfoWindow_Price){
			if (Price){
				objInfoWindow_Price.innerHTML = Price;
			}else{
				objInfoWindow_Price.innerHTML = "";
			}
		}
		if (objInfoWindow_Image && Image){
			objInfoWindow_Image.style.background = "url('" + Image + "') center no-repeat";
			if (Image_Dsc){
				objInfoWindow_Image.alt = Image_Dsc;
				objInfoWindow_Image.title = Image_Dsc;
			}
		}
		
		if (objInfoWindow_LinkItem){
			objInfoWindow_LinkItem.href = "/" + Country + "/" + Region + "/" + URLEncode(City) + "/" + URLEncode(LSub1) + "/" + URLEncode(LSub2) + "/" + AdID;
		}
		if (objInfoWindow_MapIt){
			objInfoWindow_MapIt.href = "http://maps.google.com/maps?saddr=&daddr=" + URLEncode(Address);
		}
		if (objInfoWindow_ZoomIn){
			objInfoWindow_ZoomIn.href = "JavaScript:zoomMap('" + Address_Lat + "','" + Address_Lon + "');"
		}
		
	}
}

function closeInfoWindow(){
	objInfoWindow = document.getElementById("infowindow");
	if (objInfoWindow){
		objInfoWindow.style.display = "none";
	}
}

function zoomMap(Address_Lat, Address_Lon){
	geoMap.setCenter(new google.maps.LatLng(Address_Lat, Address_Lon));
	geoMap.setZoom(17);
}

function geoSetBounds(){
	if (geoMap){
		//if (geoReBound){
			geoMap.fitBounds (geoBounds);
		//}
	}
}

function geoDeleteOverlays(){
	if (geoArrMarker) {
		for (i in geoArrMarker) {
			geoArrMarker[i].setMap(null);
		}
		geoArrMarker.length = 0;
	}
	geoBounds = "";
}

function geoResetMarkers(){
	if (geoArrMarker) {
		for (i in geoArrMarker) {
			geoArrMarker[i].setIcon(geoIconOff);
			//alert(geoArrMarker[i].getIcon().url);
		}
	}
}

function geoInfoClose(){
	if (geoInfo) {
		for (i in geoInfo) {
			geoInfo[i].close();
		}
	}
}

function bEnterCity(e,objInput){
	var keyNum;
	if (window.event){
		keyNum = e.keyCode;
	}else if (e.which){
		keyNum = e.which;
	}
	if (keyNum == 13){
		if (typeof objInput == 'object'){
			if (objInput.type == 'text'){
				codeAddress(objInput.value);
			}
		}
	}
}

function havDistance(sLat,sLon,eLat,eLon) {
	var d = -1;	
	if (sLat && sLon && eLat && eLon){	
		//var R = 6378.1 // km
		var R = 3963.1676; // mi
		var dLat = (eLat - sLat) * (Math.PI / 180);		
		var dLon = (eLon - sLon) * (Math.PI / 180);		
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(sLat * (Math.PI / 180)) * Math.cos(eLat * (Math.PI / 180)) * Math.sin(dLon/2) * Math.sin(dLon/2); 
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		var d = R * c;
	}
	return d;
}
