// JavaScript Document
var geocoder;
	$(document).ready(function() {
	var stepsSaved=0;
	
		function viewTop() {
			window.scrollTo(0,0);
		}

		$("#latlng_sample").click(function(){
			$("#job_lat").val($(this).attr("lat"));
			$("#job_lng").val($(this).attr("lng"));
			
			return false;
		});
		$.ajaxSetup({
			  cache: false
			});				   
							   
		var marker;					   
		var map_services = new GMap2(document.getElementById('googleMap'));
		var map_address = new GMap2(document.getElementById('plot_address_map'));
		var mapCenter = new GLatLng(38,-94);
				
			 map_address.addControl(new GMapTypeControl());
			 map_address.addControl(new GScaleControl());
				map_address.setCenter(mapCenter, 4);
				map_address.addControl(new GLargeMapControl3D());
				var bounds = new GLatLngBounds();
				
				
			 map_services.addControl(new GMenuMapTypeControl(true,false));
			 map_services.addControl(new GScaleControl());


				map_services.setCenter(mapCenter, 4);
				map_services.addControl(new GLargeMapControl3D());
				
		var towerIcon = new GIcon();
			towerIcon.image = "images/Guyed-Tower.gif";
			towerIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
			towerIcon.iconSize = new GSize(30, 100);
			towerIcon.iconAnchor = new GPoint(15, 100);
		var hospIcon = new GIcon();
			hospIcon.image = "images/red-cross-3.png";
			hospIcon.iconSize = new GSize(32, 32);
			hospIcon.iconAnchor = new GPoint(16, 32);
		var fireIcon = new GIcon();
			fireIcon.image = "images/fire_plug.png";
			fireIcon.iconSize = new GSize(20, 36);
			fireIcon.iconAnchor = new GPoint(10, 36);

		var reasons=[];
				reasons[G_GEO_SUCCESS]            = "Success";
				reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
				reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address.";
				reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
				reasons[G_GEO_BAD_KEY]            = "Bad API Key";
				reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
				reasons[G_GEO_SERVER_ERROR]       = "Server error";

		var gdir=new GDirections(map_services, document.getElementById("directions"));
		

							   
		geocoder = new GClientGeocoder();
					var addressMessage=[];
					addressMessage[0] =      "<b>Google returned several possibilities.</b><br/><span class='hover_info'>Hover over address for more info.</span>";
					addressMessage[1] =		"The best match Google shows for the address entered is: ";
					addressMessage[2] =		"The ZIPCODE entered doesn't match Google's : ";
					addressMessage[3] =		"The STATE entered doesn't match Google's : ";

		GEvent.addListener(gdir, "error", function() {
			var code = gdir.getStatus();
			var reason="Code "+code;
			if (reasons[code]) {
			  reason = reasons[code]
			} 
	
			alert("Failed to obtain directions, "+reason);
		});
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
			
		function onGDirectionsLoad() {
			setTimeout(function(){
					$("#googleMap img").each(function() {
						var imgsrc=$(this).attr('src');
						if(imgsrc=="http://maps.gstatic.com/intl/en_us/mapfiles/marker_greenB.png" || imgsrc=="http://maps.gstatic.com/intl/en_us/mapfiles/marker_greenA.png"){
							
							$(this).hide();
						}
					 });
			},800);
			
			
		}
	
	
		var geotype,jobSiteAddr,cleanaddress,googleData,googAddressOK,createMarker;
		$("#job_lng").blur(function(){
			if($(this).val()>0){
				alert("Longitude must be entered as a negative decimal number");
			}
									
		});
		
		//  testing change this to images after
		
		$("#address_method img").click(function(){
				$("#address_method").hide('explode',1000);								
												
				var add_src=$(this).attr("rel");
				if(add_src=='Address') {
					  //   leave disable lat/lng, need autofill
					  geotype="geo";
					  $(".coordinates").css("visibility","hidden");
					  $(".address_search").show();
					  $(".form_address").addClass("required");
					  $(".form_coordinates").removeClass("required");
					
				}else{
					  //   un disable show lat long input
					  geotype="reverse";
					  $("#decimal_convert_link").show();
                      $("#coordinate_fill").hide();
					  $(".coordinates").css("visibility","visible");
					  $(".form_coordinates").addClass("required");
					  $(".form_address").removeClass("required");
					  
					 $(".address_search").hide();
				}
			$(".job_info_table").show();
		});
		
		// testing function   is duplicate of above image clicks
		$("input[name=address_source]").parent("label").andSelf().click(function(){
				var add_src=$("input[name=address_source]:checked").val();
				//log(add_src)
				if(add_src=='Address') {
					  //   leave disable lat/lng, need autofill
					  geotype="geo";
					  $(".coordinates").css("visibility","hidden");
					  $(".address_search").show();
					  $(".form_address").addClass("required");
					  $(".form_coordinates").removeClass("required");
					
				}else{
					  //   un disable show lat long input
					  geotype="reverse";
					  $("#decimal_convert_link").show();
                      $("#coordinate_fill").hide();
					  $(".coordinates").css("visibility","visible");
					  $(".form_coordinates").addClass("required");
					  $(".form_address").removeClass("required");
					  
					 $(".address_search").hide();
				}
			$(".job_info_table").show();
		});
		var $reverseGeoContainer;
		$("#test_addresses_button").click(function() {
			
			
			$(".incomplete").removeClass("incomplete");
			$("#job_info .required").each(function(){
				if($(this).val()=="") {
					$(this).addClass("incomplete");
					if($(this).is("select")) {
						$(this).parent().find("label").addClass("incomplete");
						$(this).change(function() {
							$(this).removeClass("incomplete").parent().find("label").removeClass("incomplete");					
						});
						
					}
					$(this).blur(function() {
						if(	!$(this).val()=="" ){
							$(this).removeClass("incomplete").parent().find("label").removeClass("incomplete");
						}
					});
				}
				if($(this).is("input[type=checkbox]") && !$(this).is(':checked')) {
						$(this).addClass("incomplete").siblings("span").addClass("incomplete");
						$("input[type=checkbox].incomplete").click(function(){
								$(this).removeClass("incomplete").siblings("span").removeClass("incomplete");												
								return true;
						});
					 }
			 });
			
			if(!$("#job_info .incomplete").length==0 || $("#job_lng").val() >0) {
					if($("#job_info .incomplete").length==0){
						alert("Longitude must be entered as a negative decimal number");
					}else{
						alert("Please complete all missing red fields");
						var firstIncomplete=$(".incomplete:first").offset().top-200;
						window.scroll(0,firstIncomplete);
					}
			}else{// end validation
			

				$("#address_receive").slideDown(); 
				googAddressOK=0;
				yhooGoodresult=0;
				
				$("#geo_receive, #reverse_receive div,.marker_source").empty();							   
				if(geotype=="reverse"){;
					//reverse geocode
					$reverseGeoContainer=$("#geo_receive")
					$reverseGeoContainer.html('<div class="goog_response"></div><div class="pipes_response"></div>');
					var latitude=$("#job_lat").val();
					var longitude=$("#job_lng").val();
					googLatlng=$("#job_lat").val() + "," +$("#job_lng").val();
					// add this to map
					createMarker=1;
		 			geocoder.getLocations(googLatlng, googGeoAddress);
					PipesReverseCode(latitude,longitude);
					jobSiteMarker(latitude,longitude);
				}
				if(geotype=="geo"){
					// geocode
					jobSiteAddr = $("#job_address").val() + ", " +$("#job_city").val() + ", " +$("#job_state").val();
					if($("#job_zip").val()!=""){
						jobSiteAddr+=" "+$("#job_zip").val();	
					}
					$reverseGeoContainer=$("#geo_receive");
					$reverseGeoContainer.html('<div class="goog_response"></div><div class="pipes_response"></div>');
					createMarker=0;
						//  yhoo geo triggers in geoGoog to allow test for Googl lat/long first
						
						geoGoog(jobSiteAddr,geotype);
					
					
				}
				
			}// end validation Else
			return false;
		});
		
			var yhooLatLng;
			var precision;
		function YhooGeoCode(jobSiteAddr, choiceType) {
			/*var yhooGoodresult=0;*/
			var thisClass="";
					// some tower addresses supplied using "&"
					jobSiteAddr=jobSiteAddr.replace("&","and");
					
					var yhooGeoPipesURL="http://pipes.yahoo.com/pipes/pipe.run?_id=d8d0544e40471416857addf3cf6edc6e&_render=json&_callback=?&location=";
					yhooGeoPipesURL+=jobSiteAddr;
					$reverseGeoContainer.find(".pipes_response").append('<img class="loading" src="images/loading-bar.gif" />');
					$.ajax({
						url:yhooGeoPipesURL,
						dataType: 'json',
						success: function(data, msg){
							
							//log(data);
							// this is list of possible warnings from Yahoo geocode:
							// The exact location could not be found. Here is the center of the ZIP code.
							// The exact location could not be found, here is the closest match: 1275 Nc-55 N, Coats, NC 27521
							// The street number could not be found. Here is a nearby location.
							// The Street name might have been changed
							// The exact location could not be found. Here is a nearby county.
							
							
						//if(data.value.items){
							$reverseGeoContainer.find(".loading").remove();
							
								if(data.count==0){
									//alert("NO Yahoo data");
									$reverseGeoContainer.find(".pipes_response").append('<span class="geo_error">Yahoo unable to process this address</span>');
								}
								
							$.each(data.value.items, function(i,item){
								
								
								
								var yhooPrintout="";
								if(this.Result.length>1){
									
									yhooGoodresult=1;
									
									$reverseGeoContainer.find(".pipes_response").append("<span><b>Yahoo returned several possibilities</b><br/><span class='hover_info'>Hover over address for more info.</span></span>");
									
									//parse JSON response
									$.each(this.Result, function(i){
										$info=this;	
										
										cleanYahooResults($info);
										yhooPrintout='<div class="geocode_module multiple">'+(i+1)+': <a href="#" class="address_choice">'+yhooAddress+'</a><div class="clear"></div></div>';						 
										$reverseGeoContainer.find(".pipes_response").append(yhooPrintout);	
										precision=YhooPrecisionConvert($info);
										
										//$info.precision=precision;
										$("a.address_choice:last")
												.data("addressInfo",
												{source:"Yahoo",address:$info.Address, city:$info.City ,state:$info.State  ,zip:$info.Zip ,lat:$info.Latitude  ,long:$info.Longitude, accuracy: precision})
												.click(function(){
													return false; //  keep this for browser back action on tabs			
												});
; 
										$(".multiple_address_toolbar:first").clone().appendTo(".geocode_module:last").addClass("multiple");
										if(googAddressOK!=0){
										$(".marker_source").html('<h3 style="color:red">marker no good</h3>');
										}
										
									});
											
											//  show the instructions if Google not a match address
											if(googAddressOK==0){
												
												
												$("#reverse_receive").html($(".address_options").clone());
												$("#reverse_receive .address_options").show();
											}
									
									
									
								}else{
								var $info=this.Result;
								
								cleanYahooResults($info);
								var message='<div class="geocode_module"><b>Yahoo returned an approximate address:</b>';
								
								precision=YhooPrecisionConvert($info);
								//log("Yhoo accur convert" +precision);
								
								var warning=$info.warning;
								var warnmessage="";
								if(warning){
									var warnMessage=warning.split(":");
									warning=warnMessage[0];
									warnmessage=message; 
									//warnmessage += '<span style="color:red"><br />'+ warning+'</span>'
									message=warnmessage;
								}
								
								if(precision==8 && !warning){
									yhooGoodresult=1;
									yhooLatLng=$info.Latitude+","+$info.Longitude;
									thisClass="addressMatch link";
									message="<b>Yahoo found a match. Click address to continue.</b>";
									if(googAddressOK==0){
										$reverseGeoContainer.find(".goog_response").hide();
									}
								}
									var latitude=$info.Latitude;		
									var longitude=$info.Longitude;	
									jobSiteMarker(latitude,longitude);
								var yhooPrintout='<div class="geocode_module"><span>';
									yhooPrintout += message;
									yhooPrintout += '<br /><a href="#" class="geoAddress ';
									yhooPrintout += thisClass +'">'+yhooAddress +'</a><input type="checkbox" class="save_address" /></span></div>'
								$reverseGeoContainer.find(".pipes_response").append(yhooPrintout);
								$("input.save_address:last")
										.data("addressInfo",
										{source:"Yahoo",address:$info.Address, city:$info.City ,state:$info.State  ,zip:$info.Zip ,lat:$info.Latitude  ,long:$info.Longitude, accuracy: precision}); 
								$("a.addressMatch:last").click(function(){
											var $data=$(this).parents(".geocode_module").find(".save_address").data("addressInfo");															   												acceptAddress($data);
										return false;
									});																		   

								if(yhooGoodresult==0){
									$(".address_toolbar:first").clone().appendTo(".geocode_module:last");
									$(".geocode_module:last .address_toolbar").show();
								}
								
								if($info.warning){
									var warning=$info.warning;
								}else{
									var warning="";
								}
								
								
								}// end else from multipe responses

							});
							
							if(yhooGoodresult==0 && googAddressOK==0){
								//  if not good address try Google
								
								$("#reverse_receive").html($(".address_options").clone());
								$("#reverse_receive .address_options").show();

							}
						
						
						
						},
						error: function(msg){
							// ADD YHOO ERROR
							//log("Bad");
							}
						
					});
		
		}
		var yhooAddress;
			function cleanYahooResults($info){	
									
									// clean Yhoo pipes "null"
									yhooAddress="";
									if($info.Address==null || $info.Address==""){
										$info.Address="";
									}else{
										yhooAddress+=$info.Address+", ";
									}
									if($info.City==null || $info.City==""){
										$info.City="";
									}else{
										yhooAddress+=$info.City+", ";
									}
									if($info.Zip==null || $info.Zip==""){
										$info.Zip="";
									}
									yhooAddress+=$info.State+" "+$info.Zip;
									return yhooAddress;
									// precision converter
									
									
			}
			function YhooPrecisionConvert($info){
				 precision=$info.precision;
				switch(precision){
					case "address":
						precision=8;
						break;
					case "street":
						precision=6;
						break;
					case "zip":
						precision=6;
						break;
					default:
						precision=4;
				}
				return precision;
			}
		
		
    function getMarkerAddress(overlay, latlng) {
		
		latlng=marker.getLatLng()
      if (latlng != null) {
        address = latlng;
		var coords=address.toString().replace("(","").split(",")
		var latitude=coords[0];
		var longitude=coords[1];
				$("#tower_lat").html(parseFloat(latitude).toFixed(6));
				$("#tower_lng").html(parseFloat(longitude).toFixed(6));

		//zoomToBounds(map_address,latlng);
		map_address.panTo(latlng);
		
		$reverseGeoContainer=$("#reverse_receive");
		$reverseGeoContainer.html('<h3>Where you placed the tower</h3><div class="goog_response"></div><div class="pipes_response"></div>');
        geocoder.getLocations(latlng, showMarkerAddress);
		PipesReverseCode(latitude,longitude);
		$(".viewing_now").remove();
		//  swap images
		$("#tower_move").fadeOut(300,function() {
			$("#tower_move_new_address").fadeIn(300,function(){
				$("#tower_move_new_address").animate({opacity:1},2000,function(){
					$("#tower_move_new_address").fadeOut(300,function() {																 
						$("#tower_move").fadeIn(300);									 
					});
				});
			});
		});
      }
	  //else- what to do if Google no geo code
    }
	var lastPosition="";
	
	function jobSiteMarker(latitude,longitude) {
		//var createMarker=0;
		//log("Yhoo result= "+yhooGoodresult);
		if(googAddressOK!=0) {
			latitude=googSourceLat;
			longitude=googSourceLong;
			createMarker=1;
		}
		if(yhooGoodresult!=0 && googAddressOK==0){
			
				createMarker=1;
				
		}
		if(createMarker==1){
			createTowerMarker(latitude,longitude);
		}else{
			//  setup can't place marker code here
			$(".marker_source").html('<h3 style="color:red">marker no good</h3>');
		
		}

		
}
	$("#zoom_to_address").click(function() {
		//var mapCenter = new GLatLng(latlng);alert(latlng);
		//map.setCenter(mapCenter, 15);
		//zoomToBounds(map_address,point);
		map_address.setZoom(15);
		return false;
	});

function createTowerMarker(latitude,longitude){
				var point = new GLatLng(latitude, longitude);
				map_address.clearOverlays();
				var markerOptions={draggable: true, icon:towerIcon}
				marker = new GMarker(point,markerOptions);
				$("#tower_lat").html(parseFloat(latitude).toFixed(6));
				$("#tower_lng").html(parseFloat(longitude).toFixed(6));
				//bounds.extend(marker.getPoint());
				zoomToBounds(map_address,point);
				GEvent.addListener(marker, "dragstart", function() {
						lastPosition= marker.getPoint();
					 
					});
				
				GEvent.addListener(marker, "dragend",getMarkerAddress);
				
				map_address.addOverlay(marker);
}
	
	
function showMarkerAddress(response) {
      //map_address.clearOverlays();
      if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
      } else {
		  //log(response)
        place = response.Placemark[0];
		geocode = response.Placemark[0].Point.coordinates;
		googAddress=place.address;
		precision=place.AddressDetails.Accuracy;

$reverseGeoContainer.find(".goog_response").append('<div class="geocode_module"><p><b>Google response:</b><br /><span><a href="#" class="geoAddress google">'+place.address+'</a><input type="checkbox" class="save_address google" /></span></p></div>');
		$(".address_toolbar:first").clone().appendTo(".geocode_module:last");
		$(".geocode_module:last .address_toolbar").show();
		googAddressParse(response,0);
		
		$("input.save_address:last").data("addressInfo",googleData);

      }
    }
// this is only setup for one return from Geocode.ca
function PipesReverseCode(lat,lng) {
					// set for Geocode.ca only
					var pipesURL="http://pipes.yahoo.com/pipes/pipe.run?_id=39ce2426336feda76dd1e802a8945ac8&_render=json";
					
						pipesURL+="&Latitude="+lat;
						pipesURL+="&Longitude="+lng;
						pipesURL+="&_callback=?"
					$reverseGeoContainer.find(".pipes_response").append('<img class="loading" src="images/loading-bar.gif" />');
						$.getJSON(pipesURL,function(data){
									//log(data)				
								if(	data.value.items!=0){				
									var geoCodeCA=data.value.items[0];
									
									
										var address1=	geoCodeCA.stNum;
											address1 +=   " "+geoCodeCA.address;
											address1 +=   ", " + geoCodeCA.city;
											address1 +=	  ", "+ geoCodeCA.prov;
											address1 +=	  " "+ geoCodeCA.zip;
								$reverseGeoContainer.find(".loading").remove();	
								$reverseGeoContainer.find(".pipes_response").append('<div class="geocode_module"><p><b>Third Party response:</b> <br /><span><a href="#" class="geoAddress">'+address1+'</a><input type="checkbox" class="save_address google" /></span></p></div>');
								var streetAddress=geoCodeCA.stNum+" "+geoCodeCA.address;
								$("input.save_address:last")
										.data("addressInfo",
										{source: "geoCodeCA", address:streetAddress, city:geoCodeCA.city ,state:geoCodeCA.prov  ,zip:geoCodeCA.zip ,lat:geoCodeCA.latt  ,long:geoCodeCA.longt });
								$(".address_toolbar:first").clone().appendTo(".geocode_module:last");
								$(".geocode_module:last .address_toolbar").show();
								}else{
									//alert("No Pipes")
								$reverseGeoContainer.find(".loading").remove();	
								$reverseGeoContainer.find(".pipes_response").append('<div class="geocode_module"><p><b>Third Party address service failed to respond</b> <br /></p></div>');
									
								}
						});
}
	

$(".geocode_module.multiple").live('mouseover',function(){
		$(this).find(".multiple_address_toolbar").show();									
										
});

$(".geocode_module.multiple").live('mouseout',function(){
	$(this).find(".multiple_address_toolbar").hide();	
											
	
});
$(".geoAddress").live('click',function(){
		return false;							   
});
$(".address_tool_map").live('click',function(){
											 
		showAddressMap();
		$("img.viewing_now").remove();
		$(".address_receive .selected").removeClass("selected")
		$data=$(this).parents(".geocode_module").find(".save_address").data("addressInfo");									 
		$(this).parents(".geocode_module").find(".geoAddress").addClass("selected").append('<img class="viewing_now" src="images/yes.png" />')									 
		var latitude=$data.lat;
		var longitude=$data.long;
		createTowerMarker(latitude,longitude);
	return false;										 
});
$(".multiple_address_tool_map").live('click',function(){
													  
			showAddressMap();
		$("img.viewing_now").remove();
		$(".address_receive .selected").removeClass("selected")
			var $data=$(this).parents(".geocode_module").find(".address_choice").data("addressInfo");
			$(this).parents(".geocode_module").find(".address_choice").addClass("selected").append('<img class="viewing_now" src="images/yes.png" />');
										 
			var latitude=$data.lat;
			var longitude=$data.long;
			createTowerMarker(latitude,longitude);
	return false;										 
											 
});
function showAddressMap(){
	$(".job_info_table").slideUp(function(){
		window.scroll(0,260)								  
		$("#address_map_wrap").animate({left:0},900);
		map_address.checkResize();
	});
	

}
//   save address from geocode to form 
$(".address_tool_save, .multiple_address_tool_save").live('click',function(){
		
		$(".address_receive .selected").removeClass("selected")
		if($(this).is(".address_tool_save")){
			var $data=$(this).parents(".geocode_module").find(".save_address").data("addressInfo");
		}else{
			var $data=$(this).parents(".geocode_module").find(".address_choice").data("addressInfo");
			$(this).parents(".geocode_module").find(".address_choice").addClass("selected")
		}
		//  Ajax submit gets trigegred in buildMap which is triggered in acceptAddress
		if($data.accuracy <8 ){
			
			alert(" Use our map to help improve the address. Our moveable tower marker lets you refine the address.")
	   }else{
		   acceptAddress($data);
	   }
		//alert("Accuracy= " +$data.accuracy)																   
	return false;
});

																	   

	function acceptAddress($data){
							//log($data.address)
							$(".list").empty();
							
							
							// capture company name
							
								$("#job_company2").val($("#job_company").val());
								$("#company").ajaxSubmit();
								


							jobStartDirections= "Directions from Jobsite@" + $data.lat + "," +$data.long;
							var selectedAddress=$data.address +", " + $data.city +", " + $data.state + " " + $data.zip;
							
							$("#map_address").html('<b style="color: #006699;">Jobsite Address Selected: </b><b style="color:blue">'+ selectedAddress +'</b>');
							// add zoom ability to job site
							
							$(".jobSite_zoom").click(function() {
								var mapCenter = new GLatLng($data.lat,$data.long);
								map_services.setCenter(mapCenter, 17);
								return false;
							});
							
							//add coords to form
							var cleanAddress=$data.address.replace("&","and");
							$("#job_address").val(cleanAddress);
							$("#job_city").val($data.city);
							$("#job_state").val($data.state);
							
							// database lookup not setup for long zip
							var zip=$data.zip.split("-");
							
							$("#job_zip").val(zip[0]);
							$("#job_lat").val($data.lat);
							$("#job_lng").val($data.long);
							
							var markerOptions = { icon:towerIcon };

							var marker = new GMarker(new GLatLng($data.lat,$data.long),markerOptions);
							var siteInfo="<p>JOBSITE:</p><p>";
								siteInfo+=  $data.address +", " + $data.city +", " + $data.state + " " + $data.zip;
								siteInfo+= "</p>";
							GEvent.addListener(marker, "mouseover", function(){
								showMessage(this, siteInfo);
							});
							GEvent.addListener(marker, "mouseout", function(){
								$("#message").hide();
							});
							map_services.clearOverlays();
							 map_services.addOverlay(marker);
							 
							 buildMap();
						//return false;
					}; //  end accept address click	


	function buildMap () {	
	
				bounds = new GLatLngBounds();
							

			$('#job_info').ajaxSubmit({
				
				dataType: 'json',
				success: function(json,statusText ){	 
					$("#close_zips, #fireList, #hospList, #directions").empty();
					
					if (json.errors) {
						alert(json.errors[0].error);
						//  this not being used yet, need to integrate with stop geocode
					}else{
						if (json.countyLocations.length > 0) {
							var county=json.countyLocations[0].county;
							$("#job_county").val(county);
							
						}
						
						if (json.hospitalLocations.length > 0) {
									for (i=0; i<json.hospitalLocations.length; i++) {
										var hospital=json.hospitalLocations[i]
										var hospID = hospital.id;
										var hospName = hospital.name;
										var hospLat = hospital.latitude;
										var hospLong=hospital.longitude;
										var location = {'lat':hospLat, 'lng':hospLong, 'name':hospName, 'id':hospID, 'address':hospital.address, 'city':hospital.city, 'state':hospital.state, 'zip':hospital.zip,'phone':hospital.phone};
										addLocation(location, "hospital")
										
									}
						}else { 
							alert("No hospital found in our system. This is a highly unexpected situation.\n\n If you are beta testing please let us know this occured and the address used that enabled this situation ..Thanks!");
						}
						if (json.fireLocations.length > 0) {
									for (i=0; i<json.fireLocations.length; i++) {
										var fire=json.fireLocations[i]
										var fireID = fire.id;
										var fireName = fire.dept;
										var fireLat = fire.latitude;
										var fireLong=fire.longitude;
										var location = {'lat':fireLat, 'lng':fireLong, 'name':fireName, 'id':fireID, 'address':fire.address, 'city':fire.city, 'state':fire.state, 'zip':fire.zip,'phone':fire.phone};
										addLocation(location, "fire");
										
									}
						}else { 
							alert("No fire dept found......panic!!!  call 911");
						}
						if (json.policeLocations.length > 0) {
									for (i=0; i<json.policeLocations.length; i++) {
										var police=json.policeLocations[i]
										
										var policeName = police.dept;
										var location = {'name':policeName, 'city':police.city, 'state':police.state, 'zip':police.zip,'phone':police.phone};
										addPolice(location, "police")
										
									}
						}else { 
							
							$("#policeError").show();
						}
						if (json.sheriffLocations.length > 0) {
									for (i=0; i<json.sheriffLocations.length; i++) {
										var sheriff=json.sheriffLocations[i]
										
										var sheriffName = sheriff.dept;
										var location = {'name':sheriffName, 'city':sheriff.city, 'state':sheriff.state, 'zip':sheriff.zip,'phone':sheriff.phone};
										addPolice(location, "sheriff")
										
									}
						}else { 
							$("#sheriffError").show();
							
						}
						if(json.sheriffLocations.length == 0 && json.policeLocations.length == 0){
							$("#police_save_button").css('visibility','visible');
							
						}

						
						viewTop();
					$("#dialog").dialog('open');
							map_services.setCenter(bounds.getCenter());
							map_services.setZoom(map_services.getBoundsZoomLevel(bounds));
					}
					
				},
				error: function(event, XMLHttpRequest, ajaxOptions, thrownError) { 
					//alert(" Problems connecting to server, please try again later");
					//alert(XMLHttpRequest +  thrownError);
					alert("An unexpected error has occured connecting to our Locator");
					}
			});// end ajax 
			 }//end buildMap

			var directionsToAddr;	
			function getdirections() {
				var saddr = jobStartDirections; // format as Placename@lat,long
				var directionsOptions={getSteps:true};
				
        		gdir.load("from: "+saddr+" to: "+directionsToAddr/*, opts,{ icon:directionIcon }*/);

			
			}

	var hospZoomLevel,hospMapCenter;
			function addLocation(location, type) {
					
					var $directionData='<input type="hidden" class="directionData" value="' +location.name +'@' +location.lat + ',' + location.lng + '"/>';
					if ( type=="hospital") {
							var $icon='<span class="hospIcon"><img src="images/red-cross-3.png" height="12" width="12"/></span>';
							var markerOptions = { icon:hospIcon };
							var $list = $("#hospList");		
					}else {
							var $icon='<span class="fireIcon"><img src="images/fire_plug.png" height="12" width="12"/></span>';
							var markerOptions = { icon:fireIcon };
							var $list = $("#fireList");		
					
					}


					var point = new GLatLng(location.lat, location.lng);
					var marker = new GMarker(point,markerOptions);
					map_services.addOverlay(marker);
					bounds.extend(marker.getPoint());

					var $check='<input type="checkbox" />';

					$("<li />")
						.data("location",location)
						.html($icon + $check + '<b>' + location.name +'</b>'+ $directionData )
						.hover(function(){
							showMessage(marker, location.name);
							}, function() {
							
							$("#message").hide();
						})
						.appendTo($list).click(function() {
								var $list=$(this).parents(".list");
								if($list.is("#hospList")){
									hospZoomLevel=map_services.getZoom();
									hospMapCenter=map_services.getCenter() 
								
								  }
								$list.find(".active").removeClass("active").end().find(".selected").removeClass("selected");
								$(this).toggleClass("active");
								$list.find(":checked").removeAttr("checked");
								$(this).parents(".scroll_item").find(".service_save_button").css('visibility','visible');
							if($(this).find(":checked").length==0){
								$(this).find("input[type=checkbox]").attr("checked","checked");
							}else{
								$(this).find("input[type=checkbox]").removeAttr("checked");
							}
							directionsToAddr= $(this).find(".directionData").val();
							
							getdirections();
							//return false;
						
						});
					
					GEvent.addListener(marker, "mouseover", function(){
						showMessage(this, location.name);
					});
					GEvent.addListener(marker, "mouseout", function(){
							$("#message").hide();
						});

				}
				
				function addPolice(location, type) {
					
					if ( type=="police") {
							var $list = $("#policeList");		
					var $icon='<span class="hospIcon"><img src="images/police_badge.jpg" height="12" width="12"/></span>';
					}else {
							var $list = $("#sheriffList");		
					var $icon='<span class="hospIcon"><img src="images/sheriff_badge.png" height="12" width="12"/></span>';
					}

					var $check='<input type="checkbox" />';

					$("<li />")
						.data("location",location)
						.html($icon + $check + '<b>' + location.name +'</b>')
						.appendTo($list).click(function() {
														
								var $list=$(this).parents(".list");
								$list.find(".active").removeClass("active").end().find(".selected").removeClass("selected");
								$(this).toggleClass("active");
														
								$(this).parents(".scroll_item").find(".service_save_button").css('visibility','visible');
								$list.find(":checked").removeAttr("checked");
							if($(this).find(":checked").length==0){
								$(this).find("input[type=checkbox]").attr("checked","checked");
							}else{
								$(this).find("input[type=checkbox]").removeAttr("checked");
							}
							return true;
						
						});
					
				}
				
				
				
				$("#message").appendTo( map_services.getPane(G_MAP_FLOAT_SHADOW_PANE) );
				
				function showMessage(marker, text){
					var markerOffset = map_services.fromLatLngToDivPixel(marker.getPoint());
					var messageTop=markerOffset.y-30;
					var messageLeft=markerOffset.x+15;
					$("#message").hide().fadeIn()
						.css({ top:messageTop, left: messageLeft})
						.html(text);
				}
				





		
function zoomToBounds(whichMap,point) {
	whichMap.setCenter(point/*bounds.getCenter()*/);
	whichMap.setZoom(12/*whichMap.getBoundsZoomLevel(bounds)*/);
}
		
		
function googGeoAddress(response) {
      //map.clearOverlays();
      if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
      } else {
        //place = response.Placemark[0];
		googAddress=response.Placemark[0].address;
		geocode = response.Placemark[0].Point.coordinates;
		
		$reverseGeoContainer.find(".goog_response").html('<div class="geocode_module"><p><span><b>Google response:</b><br /><a href="#" class="geoAddress google">'+ googAddress+'</a><input type="checkbox" class="save_address google" /></span></p></div>');
		googAddressParse(response,0);
		$(".address_toolbar:first").clone().appendTo(".geocode_module:last");
		$(".geocode_module:last .address_toolbar").show();
		$("input.save_address:last").data("addressInfo",googleData);
		
		$(".reverse_address_options").clone().appendTo("#reverse_receive");
		$("#reverse_receive .reverse_address_options").show();
      }
    }
		var googSourceLat,googSourceLong;
		function geoGoog(jobSiteAddr,geotype) {
					
					geocoder.getLocations(jobSiteAddr, function (response){
							//log(jobSiteAddr)
							//log(response)
						if (response.Status.code == G_GEO_SUCCESS) {
						
							// ===== If there was more than one result, "ask did you mean" on them all =====
							  if (response.Placemark.length > 1) { 
								// Loop through the results
								  
								  $reverseGeoContainer.find(".goog_response").append(addressMessage[0]);
								  
								for (var i=0; i<response.Placemark.length; i++) {
									  geocode = response.Placemark[i].Point.coordinates;
									  $reverseGeoContainer.find(".goog_response").append("<div class='geocode_module multiple'>"+(i+1)+": <a href='#' class='address_choice'>"+ response.Placemark[i].address+"</a></div>");
									  googAddressParse(response,i);
									  $("a.address_choice").eq(i)
												.data("addressInfo",googleData )
												.click(function(){
													return false; //  keep this for browser back action on tabs			
												});
										$(".multiple_address_toolbar:first").clone().appendTo(".geocode_module:last").addClass("multiple");	
									
								}
								
											
							}else{ // only one address
								
								
							geocode = response.Placemark[0].Point.coordinates;
							//jobPlot(geocode);
							var accuracylevel=response.Placemark[0].AddressDetails.Accuracy;
							
							
							googReturnGeo=response.Placemark[0]
							var googAddress=googReturnGeo.address;
							googAddressParse(response,0);
							
								$reverseGeoContainer.find(".goog_response").append('<div class="geocode_module"><span><span class="googMessage"><b>Google returned an approximate address:</b></span><br /><a href="#" class="geoAddress google">'+googAddress +'</a><input type="checkbox" class="save_address google" /></span></div>');
								
								$("input.save_address:last")
										.data("addressInfo",googleData);
							
								$googValues=$("input.save_address.google:last").data("addressInfo");

								if($googValues.city){
										if($googValues.city.toLowerCase()==$("#job_city").val().toLowerCase() && accuracylevel==8){
											googAddressOK=1;
											
											$(".geoAddress.google").addClass("addressMatch link");
											$("a.addressMatch:last").click(function(){
													var $data=$(this).parents(".geocode_module").find(".save_address").data("addressInfo");															   												acceptAddress($data);
												return false;
											});																		   

											
											googSourceLat=$googValues.lat;
											googSourceLong=$googValues.long;
											$(".googMessage:last").html("<b>Google found a match. Click address to continue</b>");
											
											$reverseGeoContainer.find(".pipes_response").hide();
										}
									}
								if(googAddressOK==0){
									$(".address_toolbar:first").clone().appendTo(".geocode_module:last");
									$(".geocode_module:last .address_toolbar").show();
								}
								
							
						 }
						} else {
							var reason="Code "+response.Status.code;
							if (reasons[response.Status.code]) {
								reason = reasons[response.Status.code]
								
								$reverseGeoContainer.find(".goog_response").append('<span class="geo_error">Google returned following failure: '+reason +'</span>');
								//alert(reason)
							} 
							
							geocode = false;
						}
					});
					YhooGeoCode(jobSiteAddr,geotype);
					
				}

			$("#decimal_converter").dialog({autoOpen:false,width:400, modal:true, buttons: { "Skip Calculator": function() { $(this).dialog("close"); } }});
	$("#decimal_convert_link").click(function(){
	 		$("#decimal_converter").load("includes/decimal-coord-converter.html");
			$("#decimal_converter").dialog('open');
			return false;
	 });
	
			 // modal for services locator Map
			$("#dialog").dialog({	
				autoOpen:false,	width: 1024, hide:'blind',	modal:true,	position: 'top',
				buttons: {	"Close": function() { 
								if(stepsSaved==4) {
									mapDone();
								}else{   var r=confirm("You haven't saved all services! \n\n Close Services Locator?")
										if (r==true) {
												$(this).dialog("close");
										  }
									}
								} // end close funct
					},
				open: function(event, ui) {
						map_services.checkResize(); 
						$(".list_wrap").prependTo("#dialog");
						
						setTimeout(function(){$(this).css("top",0);},200);
				}
			});
	
	
				/* ********** *******   Code start for directions to form*/
				
				
				var hospSave=0;
				// modify save button after a save
				function locatorRevisions(elem) {
					if(elem.is(".saved") ){
						elem.parents(".scroll_item").find(".map_success h3").text("Revision Saved").css("color","red");
					}else{
													  
						elem.addClass("saved");								  
						}								  
					elem.parents(".scroll_item").find(".list").each(function() {
							$(this).find(".active").addClass("selected");												 
						});
				}
				
				$("#hosp_save_button").click(function() {
						locatorRevisions($(this));
						
						if( $("#hosp_wrap").find(":checked").length >0 ) {
							
							$(".formDirections").remove();
							extractDirections();
							fillHospform();
							
							$(this).parents(".scroll_item").find(".map_success").slideDown();
							if(hospSave==0){
								hospSave=1;
								stepsSaved++;
							}
						}else{ 
							alert(" No hospital has been selected or put in form. \n\n Please select a hospital");
						}
					
					return false;
						
				});
				
		function fillHospform() {
			
			var $hospInfo=$("#hospList").find(":checked").parent("li").data("location");
			$("#job_hosp_name").val($hospInfo.name);
			var hospAddress = $hospInfo.address +"\n";
				hospAddress += $hospInfo.city +", ";
				hospAddress += $hospInfo.state +" ";
				hospAddress += $hospInfo.zip+ "\n"; 
				hospAddress += $hospInfo.phone;
			$("#job_hosp_info").val(hospAddress);
			$("#hosp_lat").val($hospInfo.lat);
			$("#hosp_long").val($hospInfo.lng);
			

		}
				
		function extractDirections() {
					$("#job_hosp_route").empty();
					
					var directions="";

					$("div.googledir table[jsdisplay] tr").each(function(i) {
						$('body').append('<p class="formDirections"></p>');
						var tdNum=0;
						$(this).find('td').each(function() {
							//var directionSteps=$(this).html()
							if(tdNum==2) {
							$("p.formDirections").eq(i).append(" -- " + $(this).html());	
							}else{
							$("p.formDirections").eq(i).append($(this).html());
						
							}
							tdNum++;
							
						});
					
					});
					// strip html tags from directions to insert in textarea last p has some funky html
					$("p.formDirections").not(":last").each(function() {
							$(this).find('a').each(function() {
									var text=$(this).text();
									$(text).insertBefore(this);
									
							});
							$(this).find('b').each(function() {
									var text=$(this).text();
									$(text).insertBefore(this);
							});
							directions+= $(this).text();
							directions+= "\n";
							
					});
					// adjust textarea height after insert directions
					var numdirections=$(".formDirections").length;
					var textAreaHt= (numdirections) * 20;
					$("#job_hosp_route").val(directions).css("height", textAreaHt);
					// finally empty the google directions
					$("#directions").empty();
				
		}
			// save police and sherrif info to form
			var policeSave=0;
			$("#police_save_button").click(function() {
						locatorRevisions($(this));
				var numServices=0;
				if($("#policeList li").length>0){
					numServices++;
				}
				if($("#sheriffList li").length>0){
					numServices++;
				}
				var numChecked=$("#police_wrap").find(":checked").length;
				//if( $("#police_wrap").find(":checked").length >0  ) {
				if(numChecked== numServices ) {
						if ($("#policeList li").length ) {									
							var $policeInfo=$("#policeList").find(":checked").parent("li").data("location");
							$("#job_police_name").val($policeInfo.name);
							$("#job_police_phone").val($policeInfo.phone);
						}else{
							$("#job_police_phone,#job_police_name").val("None found");
						}
						if ($("#sheriffList li").length ) {
							var $sheriffInfo=$("#sheriffList").find(":checked").parent("li").data("location");
							$("#job_sheriff_name").val($sheriffInfo.name);
							$("#job_sheriff_phone").val($sheriffInfo.phone);
						
							$(this).parents(".scroll_item").find(".map_success").slideDown();
							// for close dialog validation
						}else{
							$("#job_sheriff_name,#job_sheriff_phone ").val("None found");
						}
						if(policeSave==0){
								policeSave=1;
								stepsSaved++;
						}
						$(this).parents(".scroll_item").find(".map_success").slideDown();
						
				}else{ 
					alert(" Please select one from each category");
				}
				return false;
				
			});
			var fireSave=0;
			$("#fire_save_button").click(function() {
						locatorRevisions($(this));
				if( $("#fire_wrap").find(":checked").length >0 ) {								  
					var $fireInfo=$("#fireList").find(":checked").parent("li").data("location");
					$("#job_fire_name").val($fireInfo.name);
					$("#job_fire_phone").val($fireInfo.phone);
					$(this).parents(".scroll_item").find(".map_success").slideDown();
					// for close dialog validation
					if(fireSave==0){
							fireSave=1;
							stepsSaved++;
						}
				}else{ 
					alert(" No fire dept info has been selected or put in form."+"\n\n"+"Please select a fire dept.");
				}
				return false;
			
			});
			
			
			var intersect;
			var intersectSave=0;
			$("#intersect_save_button").click(function() {
						locatorRevisions($(this));
					intersect=$("#map_intersect").val();
					var intersectTest=intersect.split(" ");								   
					if(	intersectTest.length < 2 ){
						
								var r=confirm("You haven't entered a valid intersection! \n\n Do you really want to save and continue? \n\n ")
								if (r==true) {
									saveIntersection()
								  }
					}else{
						saveIntersection()
					}
				return false;
			});
			
			
			function saveIntersection() {
					$("#job_intersection").val(intersect);
						
					$(".map_success").slideDown();
					// for close dialog validation
					if(intersectSave==0){
							intersectSave=1;
							stepsSaved++;
						}
					if(stepsSaved==4) {
						$("#service_last_save").show();
						$("#mask_details,#mask_info").show();
					}else{
						alert("This is last step in the SERVICES LOCATOR \n\nNot all services have been saved");
					}
					
			}
		function mapDone() {
				$("#dialog").dialog("close");
				$("#serv_tab").show();
				$("#serv_tab a").trigger('click');
				

		}
			$("#map_finish").click(function() {
					mapDone();
				return false;
			});
	
	
//  goog parsing utility function	
function check_for_placemark(response) {
   if(typeof(response.Placemark) == "object") {
     return true;
   } else {
     return false;
   }
}
/// Goog Address Parse
var $googGeoResponse;
function googAddressParse(response, i){
	      cleanaddress = new Array();

      // create a variable to house the response code
      var responsecode = response.Status.code;
      $googGeoResponse=response.Placemark[i].AddressDetails.Country;
      //log(response);
		var accuracy = response.Placemark[i].AddressDetails.Accuracy;
      // create a nice new array of address data
      cleanaddress['country'] = check_for_country($googGeoResponse);
      cleanaddress['state'] = check_for_state($googGeoResponse);
      cleanaddress['city'] = check_for_city($googGeoResponse);
     cleanaddress['street'] = check_for_street($googGeoResponse,accuracy);
      cleanaddress['zip'] = check_for_zip($googGeoResponse,accuracy);
      cleanaddress['lat'] = response.Placemark[i].Point.coordinates[1];
      cleanaddress['long'] = response.Placemark[i].Point.coordinates[0];
		cleanaddress['accuracy']=response.Placemark[i].AddressDetails.Accuracy;
			googleData=	{source:"google",address:cleanaddress['street'],city:cleanaddress['city'],state:cleanaddress['state'],zip:cleanaddress['zip'],lat:geocode[1]  ,long:geocode[0], accuracy: accuracy };
			
//  test function			
testgoogleParse(cleanaddress)
}

//  test function
function testgoogleParse(cleanaddress){
	$test=$("#test_panel_content");									 
	$test.empty();
	
				var   testAddress ="Street:"+cleanaddress['street'];
						testAddress +="<br />City:"+cleanaddress['city'];
						testAddress +="<br />State:"+cleanaddress['state'];
						testAddress +="<br />Zip:"+cleanaddress['zip'];
						testAddress +="<br />Accuracy:"+cleanaddress['accuracy'];
				$test.append('<b style="color:red">Google Parse Test:</b><br/>'+testAddress);
				
	
	
}

function check_for_country($googGeoResponse) {
   if(check_for_placemark($googGeoResponse) && $googGeoResponse.CountryName) {
     return $googGeoResponse.CountryName;
   } else {
     return false;
   }
}

function check_for_state($googGeoResponse) {
   //if(check_for_placemark($googGeoResponse) && $googGeoResponse.AdministrativeArea != null) {
   if($googGeoResponse.AdministrativeArea) {
     return $googGeoResponse.AdministrativeArea.AdministrativeAreaName;
   } else {
     return "";
   }
}

function check_for_city($googGeoResponse) { 
   //if(check_for_placemark($googGeoResponse) && typeof($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality) == "object") {
	   if($googGeoResponse.AdministrativeArea){
			if($googGeoResponse.AdministrativeArea.SubAdministrativeArea) {
				  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality) {
					  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName){
							return $googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
					  }
					  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality){
							if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.DependentLocalityName){
							return $googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.DependentLocalityName;
							}
					  }
				  }
			} else {
				 if($googGeoResponse.AdministrativeArea.Locality) {
					 if($googGeoResponse.AdministrativeArea.Locality.LocalityName){
						return $googGeoResponse.AdministrativeArea.Locality.LocalityName;
					 }
				 }else{
				  //alert("this fix worked")
				 return "";
			  }
		   } 
	   }else{ return ""}
}

function check_for_street($googGeoResponse,accuracy) {
//   if(check_for_city($googGeoResponse) && typeof($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) == "object") {
	if(accuracy	>5 && accuracy <9 && $googGeoResponse.AdministrativeArea){
			if($googGeoResponse.AdministrativeArea.SubAdministrativeArea) {
				  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality) {
					  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare){
							return $googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
				  		}
					  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality){
							if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName){
							return $googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
							}
					  }
				  }
			 } else {
				 if($googGeoResponse.AdministrativeArea.Locality) {
					 return $googGeoResponse.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;		
				 }else{
				return "";
			 }      
		 }
	}else{
		return "";
	}
}

function check_for_zip($googGeoResponse,accuracy) {
//   if(check_for_city($googGeoResponse) && typeof($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) == "object") {
    
		if(accuracy	>4 && $googGeoResponse.AdministrativeArea){
	
			if($googGeoResponse.AdministrativeArea.SubAdministrativeArea) {
				  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality) {
					  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) {
						return $googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
					  }
					  if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality){
							if($googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode){
							return $googGeoResponse.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
							}
					  }
				  }
			 } else {
				 
				
				 if($googGeoResponse.AdministrativeArea.Locality) {
					 if($googGeoResponse.AdministrativeArea.Locality.PostalCode) {
					 	return $googGeoResponse.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
					  }else{
						  return "";
					  }
						
				 }else{
				return "";
			 }      
		  }
	}else{
		return "";
	}
		  
}
	
});
