// JavaScript Document

/**
 *  Initialiseer de funcitonaliteit voor dealers by distance
 */
function initDealerByDistance(){
	$("#city").change(function(){
		// als een stad is geselecteerd, de postcode leeg maken en dealers zoeken								 	
		if($(this).attr("selectedIndex") >= 0){
			$("#zipcode").val("");	
			getDealersByDistance();					
		}
	});
	
	$("#zipcode").keyup(function(){
		// als meer dan 4 cijfers zijn ingevoerd van de postcode, zoeken
		if($(this).val().length >= 4){
			// als een postcode is ingevuld, de eerste option in de steden-lijst selecteren
			$("#city").attr("selectedIndex", 0);
			getDealersByDistance();				
		}
	});
	
	$("#zipcode, #city").attr("disabled", "disabled");
	
	$("#country").change(function(){
		
		if($(this).val() == "none"){
			$("#zipcode, #city").attr("disabled", "disabled");	
			$("#city").attr("selectedIndex", 0);	
			$("#zipcode").val("");
			
		}else{
			$("#zipcode, #city").attr("disabled", "");	
						
			// haal de lijst met steden op in dit land	
			$.get("dealer_steden.php?country="+$(this).val(), function(data){
				$("#city").html(data);
			});
		}
	});
}

/**
 *  Haal de dealers op in de buurt van de opgegeven afstand (25km)
 */
function getDealersByDistance(){
	var postcode = $("#zipcode").val();
	var city = $("#city").val();
	var country = $("#country").val();
	
	var adres = "";
	if(postcode != ""){
		postcode.replace(" ", "");
		adres = adres + " " + postcode;
	}
	if(city != ""){
		adres = adres + " " + city;
	}
	
	if(country != "" && country != "none"){
		adres = adres + " " + country;
	}
	
	if(adres == ""){
		return false;	
	}
	
	//alert(adres);
	
	var geocoder;

	if (GBrowserIsCompatible()) {
		// Create new geocoding object
		geocoder = new GClientGeocoder();
		
		geocoder.getLocations(adres, function(response){
			if (!response || response.Status.code != 200) {
				// kan niet bepalen
				return false;
			}
			// coordinaten opslaan
			place = response.Placemark[0];
			
			// haal alle huidige markers van de de map af
			clearMap();
			
			// Retrieve the latitude and longitude
			var latitude = place.Point.coordinates[1];
			var longitude = place.Point.coordinates[0];
			var a = new Date();
			var dealer_typen = "&dealertypen="+$("#dealertypen").val();
			$("#dealer-data").load("dealer_mapdata.php?lat="+latitude+"&long="+longitude+"&city="+city+"&a="+a.getTime()+dealer_typen, function(){
				// centreer de kaart naar het middelpunt
				// Retrieve the latitude and longitude
				point = new GLatLng(latitude,
							  longitude);
				
				// Center the map on this point
				map.setCenter(point, 10);
			});
			
		 });
	}
}
