var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/
var IE7 = (document.all && !window.opera && window.XMLHttpRequest && navigator.userAgent.toString().toLowerCase().indexOf('Trident/4.0') == -1) ? true : false; //returns true for IE > 6

$(document).ready(function() {
	initMaps();
});

var map;
var geocoder;
var miles = "50";
var places;
var markers = new Array();
var locations = new Array();

function initMaps() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map-wrapper"));
		map.addMapType(G_PHYSICAL_MAP); 
		map.setCenter(new GLatLng(38, -100), 3, G_NORMAL_MAP);
		map.setUIToDefault();
		geocoder = new GClientGeocoder();
		
//		GEvent.addListener(map, 'zoomend', handleZoom);
	}
}

function findLocalPlaces() {
	hideError();
	map.clearOverlays();
	$("#mapStorage").html("");
	
	zip = $("#find-places-value").val();
	
	//if it's a valid zipcode
	if(/\d{5}([\-]\d{4})?/.test(zip)) {
		//extract zip from string and match only first zip found	
		zip = zip.match(/\d{5}([\-]\d{4})?/g).toString().substring(0, 5);
		$.ajax({
			type: "GET",
			url: "ZipCodes/view/" + zip,
			dataType: "xml", 
			success: function(xml) {
				lat = $(xml).find("lat").text();
				lon = $(xml).find("lon").text();
				loc = new GLatLng(lat, lon);
				map.setCenter(loc, 11, G_NORMAL_MAP);
				//var marker = new GMarker(loc)
				//map.addOverlay(marker);
				//marker.openInfoWindowHtml(zip);
				
				//getting locations in the area by lat lng
				getByLatLng(lat, lon);
			}
		});				
	} else if(/^[A-Za-z. '-]+([,])?[ ]{1}[a-zA-Z]{2}$/.test(zip)) {
		geocoder.getLatLng(zip, function(point) {
			if(!point) {
				showError();
			} else {
				//if((!lat || !lon) || (lat == '' || lon == '')) {
					//showMessage(0);
					//map.setCenter(new GLatLng(38, -100), 3, G_NORMAL_MAP);
				//}
				//alert(point);
				//var marker = new GMarker(point);
				//map.addOverlay(marker);
				//marker.openInfoWindowHtml(zip);
				
				//getting locations in the area by lat lng
				getByLatLng(point.lat(), point.lng());
			}
		});
	} else {
		showError();
	}
}

function showError() {
	$("#find-places-value").css({
		'backgroundColor': '#C00000'
	});
}

function hideError() {
	$("#find-places-value").css({
		'backgroundColor': '#FFFFFF'
	});
}

function addMapData(places) {
	var cdivOutput = "";
	var fullAddress = "";
	$(places).each(function() {			
		
		cdiv = document.createElement('div');
		cdiv.className = 'map-bubble';
		cdivOutput += "<div class=\"site-name\">" + this['site_name'] + "</div>";
		//fullAddress += this['site_name'] + ", ";
		if ( this['street'] || this['city'] || this['state'] || this['zip']) {
			cdivOutput += "<div class=\"address\">";
			if (this['street']) {
				cdivOutput += this['street'] + "<br />";
				fullAddress += this['street'] + ", ";
			}
			if (this['city']) {
				cdivOutput += this['city'] + ", ";
				fullAddress += this['city'] + ", ";
			}
			if (this['state']) {
				cdivOutput += this['state'] + " ";
				fullAddress += this['state'] + " ";
			}
			if (this['zip']) {
				cdivOutput += this['zip'];
				fullAddress += this['zip'];
			}
			if (this['phone']) {
				cdivOutput += "<br />" + this['phone'];
			}
			cdivOutput += "</div>";
		}
		cdivOutput += "<div class=\"activities\">";
		if (this['forest'] == 1) {
			cdivOutput += "<div class=\"forest\"></div>";
		}
		if (this['water'] == 1) {
			cdivOutput += "<div class=\"water\"></div>";
		}
		if (this['walk'] == 1) {
			cdivOutput += "<div class=\"hike\"></div>";
		}
		if (this['bike'] == 1) {
			cdivOutput += "<div class=\"bike\"></div>";
		}
		if (this['fish'] == 1) {
			cdivOutput += "<div class=\"fish\"></div>";
		}
		if (this['camp'] == 1) {
			cdivOutput += "<div class=\"camp\"></div>";
		}
		cdivOutput += "<div class=\"ClearFloat\"></div>";
		cdivOutput += "</div>";
		
		if (this['hasEvents'] == "true") {
			cdivOutput += "<div class=\"link-event\">";
			if (this['hasEvents'] == "true") {
				cdivOutput += "<a onclick=\"buildOverlay('/events/view/"+ this['nf_id'] +"'); return false;\" href=\"/events/view/" + this['nf_id'] + "\">";
				cdivOutput += "Events";
				cdivOutput += "</a>";
			}
			cdivOutput += " / ";
		}
		
		cdivOutput += "<a onclick=\"buildOverlay('/places/view/"+ this['nf_id'] +"'); return false;\" href=\"/places/view/" + this['nf_id'] + "\">";
		cdivOutput += "Description";
		cdivOutput += "</a>";
		cdivOutput += "</div>";
		
		cdivOutput += "<div class=\"footer-links\">";
		cdivOutput += "<a target=\"_blank\" href=\"http://maps.google.com/maps?daddr=";
		if (fullAddress != '') {
			cdivOutput  += encodeURIComponent(fullAddress);
		}
		//cdivOutput += "&daddr=" + this['latitude']+","+this['longitude'];
		cdivOutput += "\">";
		cdivOutput += "Get directions</a>";
		cdivOutput += "</div>";
		cdivOutput += "<div class=\"ClearFloat\"></div>";
		
		cdiv.innerHTML = cdivOutput;
		cdivOutput = "";
		fullAddress = "";
		//cdiv.style.width = "364px";
		cdiv.style.height = "130px";
		$(cdiv).appendTo("#mapStorage");
		
		loc = new GLatLng(this['latitude'], this['longitude']);
		locations.push(loc);
		var marker = new GMarker(loc);
		marker.bindInfoWindow(cdiv);
//		markers.push(marker);
	
		map.addOverlay(marker);
		
	});
	
	if(IE6 || IE7 && places.length > 0) {
		var elem = document.getElementById(currentID);
		if(elem != null) {
			elem.style.display = 'none';
		}
	}
}

var currentCount;
var olDiv;
var currentID;

function showMessage(count) {
	currentCount = count;
	if(isNaN(count)) {
		count = "several";
		currentCount = 0;
	}

	olDiv = document.createElement('div');
	olDiv.className = 'map-overlay';
	cbDiv = document.createElement('div');
	cbDiv.className = 'close-link';
	cbText = "close";
	var olMessage = '';
	currentCount = count;
	if(count == 0 || count == '' || count =="NaN") {
		olMessage = '<h4>We\'re Sorry!</h4><p>No locations found.</p>';
		olDiv.innerHTML = olMessage;
		
		//custom id
		olDiv.id = "mapMessage" + Math.round(Math.random() * 1000);
		currentID = olDiv.id;
		
		$(olDiv).appendTo("#map-wrapper");
	} else {
		olMessage = '<h4>Please be patient.</h4><p>We are loading ' + count + ' locations in your area</p>';
		olDiv.innerHTML = olMessage;
		$(olDiv).appendTo("#map-wrapper");
	}
	cbDiv.innerHTML = cbText;
	$(cbDiv).appendTo($(olDiv));
	
	$(olDiv).click(function(){
		$(this).remove();
	});
}

function hideMessage() {
	if(currentCount != 0) {
		//hide the message, otherwise wait for user to close it.
		$(olDiv).remove();
	}
}

function getByLatLng(lat, lng) {
	var postData = 'lat=' + lat + '&lng=' + lng + '&miles=' + $("#find-places-range").val();

	$.ajax({
		type: 'POST',
		data: postData,
		url: 'Places/getCountByLocation',
		success: function(data) {
			showMessage(parseInt(data.replace(/(\n|\r)+$/, '')));
		}
	});

	$.ajax({
		type: 'POST',
		data: postData,
		dataType: "xml",
		url: 'Places/getByLocation',
		success: function(xml) {
			locations = new Array();
//			showMessage(xml.match(/[^\n]*\n[^\n]*/gi).length);
		
			var results = $(xml).find("place");
//			showMessage($(results).size());
		
			//reset places
			places = new Array();
			$(results).each(function() {
				var place = new Array();
				//place['places_id'] = $(this).find("places_id").text();
				place['nf_id'] = $(this).find("nf_id").text();
				place['site_name'] = $(this).find("site_name").text();
				//place['description'] = $(this).find("description").text();
				//place['type'] = $(this).find("type").text();
				place['street'] = $(this).find("street").text();
				place['city'] = $(this).find("city").text();
				place['state'] = $(this).find("state").text();
				place['zip'] = $(this).find("zip").text();
				place['latitude'] = $(this).find("latitude").text();
				place['longitude'] = $(this).find("longitude").text();
				//place['url'] = $(this).find("url").text();
				place['phone'] = $(this).find("phone").text();
				//place['email'] = $(this).find("email").text();
				place['bike'] = $(this).find("bike").text();
				place['walk'] = $(this).find("walk").text();
				place['fish'] = $(this).find("fish").text();
				place['forest'] = $(this).find("forest").text();
				place['water'] = $(this).find("water").text();
				place['camp'] = $(this).find("camp").text();
				place['hasEvents'] = $(this).find("hasEvents").text();
				//console.log(place['site_name'] + ": " + place['hasEvents']);
				places.push(place);
				
				if(places.length > 199) {
					addMapData(places);
					places = new Array();
				}
			});
			
			addMapData(places);
			places = false;
		
			markers = new Array();
			
			zoomToFit(map, locations);
			
			hideMessage();
		}
	});
}

function zoomToFit(map, points) {
	if(points.length == 0) { return false; }
   var bounds = new GLatLngBounds();
   for (var i=0; i< points.length; i++) {
	  bounds.extend(points[i]);
   }
   map.setZoom(map.getBoundsZoomLevel(bounds));
   map.setCenter(bounds.getCenter());
}