var NM = {};
var kml = new GGeoXml("http://econym.googlepages.com/lancashire.kml");
var geocoder = new GClientGeocoder();
var gmarkers =[];
var to_html=[];
var from_html=[];
var htmls = [];
var lochtml="";
var loccomments =[];
//NM.map = null;
var i = 0;

var tiny = new GIcon();
tiny.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
tiny.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
tiny.iconSize = new GSize(12, 20);
tiny.shadowSize = new GSize(22, 20);
tiny.iconAnchor = new GPoint(6, 20);
tiny.infoWindowAnchor = new GPoint(5, 1);

NM.init = function() {
	//on map type change, change max resolution to 18 always
	G_NORMAL_MAP.getMaximumResolution = function () { return 18 };
	G_SATELLITE_MAP.getMaximumResolution = function () { return 18 };
	G_HYBRID_MAP.getMaximumResolution = function () { return 18 }; 
	
	NM.map = new GMap2( $("#nmMap").get(0) );
	
	NM.map.setCenter(new GLatLng(37.4419, -80.1419), 5);
	NM.map.addControl( new GLargeMapControl() );
	NM.map.addControl( new GMapTypeControl() );
	NM.map.enableContinuousZoom( true );
	NM.map.enableScrollWheelZoom( true );
	
	NM.geocoder = new GClientGeocoder();
	
	$("#nmSearchField").focus( function() {
		$(this).get(0).value = "";
	});
}

NM.query = function() {
	NM.map.clearOverlays();
	var address = $("#nmSearchField").val();
	var radius = $("#radiusDropDown").val();
	//var flag = true;
	
	if($("#nmSearchField").val() == ""){
		alert("Please Enter Address");
	}
	else {
		if(geocoder) {
			geocoder.getLatLng(address, function (point) {
				if(!point){ 
					alert(address + " not found");
				}
				else {
					if(radius == 5) {
						NM.map.setCenter(point, 13);
					}
					if (radius == 10) {
						NM.map.setCenter(point, 11);
					}
					if(radius > 10) {
						NM.map.setCenter(point, 10);
					}
					var centermarker = new GMarker(point);
					NM.map.addOverlay(centermarker);
					centermarker.openInfoWindowHtml("You are here" + "<br/>" + address);
					NM.getNearest(centermarker, address, radius);
				}
			});
		}
	}
}
NM.getNearest = function (centermarker, address, radius) {
	var temp =[];
	lochtml = "";
	GDownloadUrl("admin/results.xml", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
			var id = markers[i].getAttribute("id");
            var name = markers[i].getAttribute("name");
            var street = markers[i].getAttribute("street");
			var city = markers[i].getAttribute("city");
			var state = markers[i].getAttribute("state");
			 var zip = markers[i].getAttribute("zip");
			 var description = markers[i].getAttribute("description");
            var category = markers[i].getAttribute("categories");
			if(category == ""){
				category = "Unknown";
			}
			 var phone = markers[i].getAttribute("phone");
			  var url = markers[i].getAttribute("url");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            var distance = point.distanceFrom(centermarker.getPoint());
			var distance2 = distance * 0.000621371;
			var nearest=[];
			var count = 0;
			var searchaddress = address;
			if(distance2 < radius)
			{
				nearest.push({name: name, street: street, state:state, zip:zip, category:category, phone: phone, url:url, point:point});
				var marker= createMarker(point, name, street, city, state, zip, category, phone, url, id, address, description);
            	NM.map.addOverlay(marker);
				if(temp.length != 0){
					var found = false;
					for(var c=0; c < temp.length; c++){
						if(category == temp[c])
							found = true;
					}
					if(!found)
						temp.push(category);
				}
				else
					temp.push(category);
				
				
				count++;
			}
			//alert (distance);
			
          }
		  //alert("Found " + temp.length + " locations in the area.");
		  var cathtml="<select onChange=\"NM.categoryQuery('"+ searchaddress +"', this.value, " + radius +");\"><option selected> - Select Category - </option>";
		  $("#nmNearbyLocations").html("<ul>" + lochtml + "</ul>");
		  for(a=0; a<temp.length; a++){
			  cathtml += "<option value=\""+ temp[a] +"\">" + temp[a] + "</option>";
		  }
		  
		  $("#nmNearbyCategories").html(cathtml + "</select>");
		  //alert(distance);
	});

}
function resultsClick(i) {
	GEvent.trigger(gmarkers[i], "click");
}
function createMarker(point, name, street, city, state, zip, category, phone, url, id, address, description) {
      var marker = new GMarker(point, tiny);
      var html = "<b>" + name + "</b><br/>" + street + "<br/>" + city + ", " + state + " " + zip + "<br>" + phone + "<br>" + "<a href=\"http://"+ url + "\" target = \"_blank\">" + url + "</a>" + "<br>" + description + "<br>";
	  var html2 = "";
	  var html3 ="";

	  $.ajax({
							url: "admin/get_bubble_comments.php",
							method: "GET",
							data: {locid: id},
							success: function(o) {
								html2 = o;
							}
						});
	   to_html[i] = '<div id="directions">Get Directions: <span style="font-size:11px"><b>To here</b> - <a style="font-size:11px;" href="javascript:fromhere(' + i + ')">From here</a></span><br><form action="http://maps.google.com/maps" method="get" target="_blank">Start address:<br>' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="'+ address + ' " /><br>' +
           '<INPUT value="GO" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  // "(" + name + ")" + 
           '"/></form></div>';
        // The info window version with the "to here" form open
   	 from_html[i] = '<div id="directions">Get Directions:  <span style="font-size:11px"><a style="font-size:11px;" href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b></span>' +
           '<br><form action="http://maps.google.com/maps" method="get"" target="_blank">End address:<br>' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="'+ address +'" /><br>' +
           '<INPUT value="GO" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" + 
           '"/></form></div>';

        // The inactive version of the direction info
      html3 = html3 + to_html[i];
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowTabsHtml([new GInfoWindowTab("Description", html), new GInfoWindowTab("Comments", html2), new GInfoWindowTab("Directions", html3)]);  
	  });
	  lochtml += "<li><a href=\"#\" onclick=\"resultsClick(" + i + ")\">" + name + "</a></li>";
	  gmarkers[i] = marker;
	  i++;
      return marker;
	  

function openComments(id) {
	window.open("admin/get_comments_front.php?locid=" + id, 'Comments', 'scrollbars=yes, toolbar=no, width=610, height=400');
}

}

NM.categoryQuery = function (searchaddress, value, radius) {
	NM.map.clearOverlays();
		if(geocoder) {
			geocoder.getLatLng(searchaddress, function (point) {
				if(!point){ 
					alert(searchaddress + " not found");
				}
				else {
					if(radius == 5) {
						NM.map.setCenter(point, 13);
					}
					if (radius == 10) {
						NM.map.setCenter(point, 11);
					}
					if(radius > 10) {
						NM.map.setCenter(point, 10);
					}
					var centermarker = new GMarker(point);
					NM.map.addOverlay(centermarker);
					//Scentermarker.openInfoWindowHtml("You are here" + "<br/>" + address);
					NM.getNearestByCategory(centermarker, searchaddress, value, radius);
				}
			});
		}
}
NM.getNearestByCategory = function (centermarker, searchaddress, value, radius) {
	if(value == "Select All"){
		NM.getNearest(centermarker, (searchaddress), radius);
	}
	else{
	var temp =[];
	lochtml = "";
	GDownloadUrl("admin/results.xml", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
			var id = markers[i].getAttribute("id");
            var name = markers[i].getAttribute("name");
            var street = markers[i].getAttribute("street");
			var city = markers[i].getAttribute("city");
			var state = markers[i].getAttribute("state");
			 var zip = markers[i].getAttribute("zip");
			var description = markers[i].getAttribute("description");
            var category = markers[i].getAttribute("categories");
			if(category == ""){
				category = "Unknown";
			}
			 var phone = markers[i].getAttribute("phone");
			  var url = markers[i].getAttribute("url");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
			
            var distance = point.distanceFrom(centermarker.getPoint());
			var distance2 = distance * 0.000621371;
			var nearest=[];
			var count = 0;
		
			if(distance2 < radius)
			{
				if(temp.length != 0){
					var found = false;
					for(var c=0; c < temp.length; c++){
						if(category == temp[c])
							found = true;
					}
					if(!found)
						temp.push(category);
				}
				else
					temp.push(category);
				if(category == value){
				nearest.push({name: name, street: street, state:state, zip:zip, category:category, phone: phone, url:url, point:point});
				var marker= createMarker(point, name, street, city, state, zip, category, phone, url, id, searchaddress, description);
            	NM.map.addOverlay(marker);
				
				count++;
				}
			}
			//alert (distance);
		
		  }
		  //alert("Found " + temp.length + " locations in the area.");
		  var cathtml="<select onChange=\"NM.categoryQuery('" + searchaddress + "', this.value, "+ radius + ");\"><option selected> - Select Category - </option><option value=\"Select All\">-Show All-</option>";
		  $("#nmNearbyLocations").html("<ul>" + lochtml + "</ul>");
		  for(a=0; a<temp.length; a++){
			  cathtml += "<option value=\""+ temp[a]+"\">" + temp[a] + "</option>";
		  }
		  $("#nmNearbyCategories").html(cathtml + "</select>");
		  //alert(distance);
	});
	}
}
function tohere(i) {
        document.getElementById("directions").innerHTML =  to_html[i];
      }
	  
function fromhere(i) {
        document.getElementById("directions").innerHTML =  from_html[i];
		//$('directions').innerHTML = from_html[i];
      }
function openAddComments(id) {
	window.open("addcomments.php?locid=" + id, 'AddComments', 'scrollbars=yes, toolbar=no, width=350, height=350')
}

$(window).load( function() {
	NM.init();
});