/* Called when the page is loaded. */
var locations = [];
var point = [];
var gmarkers = [];
var marker = [];
var overlayHtml = [];
var counter = [];
var map;
var mm;
var geocoder;

function load() {

	/* Check if the users browser supports Google maps. */
	if (GBrowserIsCompatible()) {	
		
		/* Create google maps object. */
		map = new GMap2(document.getElementById("map"));

		/* Center the map exactly at this point + zoom level. */
		map.setCenter(new GLatLng(52.09198, 4.918816), 6);

		/* Create bounds objects */
//		bounds = new GLatLngBounds();

		/* Place control elements for moving in the map. */
		map.addControl(new GLargeMapControl());

		/* Set options for Google maps. */
		setMap();

		/* Create marker object for the map. */
		mm = new GMarkerManager(map);

		/* Create arrays for markers and positions. */
		//this.gmarkers = [];
		//this.locations = [];
		//this.marker = [];
		//this.point = [];
		//this.overlayHtml = [];
		//this.counter = 0;

		/* Create google maps geocoding object. */
		geocoder = new GClientGeocoder();

//		/* Create houses object. */
//		oHouses = eval('(' + sJsonHouses + ')');
//
//		/* Walk through houses. */
//		for (var i = 0; i < oHouses.length; i++) {
//
//			this.locations[i] = [];
//			this.locations[i]['title'] = 'TITEL 1';
//			this.locations[i]['text'] = 'TEXT 1';
//			this.locations[i]['coordinate1'] = oHouses[i].latitude;
//			this.locations[i]['coordinate2'] = oHouses[i].longitude;
//			this.locations[i]['html'] = '<p style="font-family: arial, verdana; font-size: 11px; line-height: 18px; width: 300px; height: 100px;"><strong>' + sPrefix + oHouses[i].house_id + '</strong><br /><img src="/image/get/sImage/' + oHouses[i]['pictures'][0]['name'] + '/iWidth/100/iHeight/76" style="float: left; padding: 1px; border: rgb(56, 123, 44); margin-right: 10px;" />' + oHouses[i]['country'] + '<br />' + oHouses[i]['region'] + '<br /><a href="javascript:this.openUrl(\'' + oHouses[i]['url'] + '\');">Bekijk details.</a></p>';
//
//		}
//		
//		/* Add circle. */
////		this.addCircle();
//
//		/* Place locations after a little while (due to loading). */
//		setTimeout('this.showLocations()',200);

	/* The browser can't display google maps. */
	} else{

		// Warn the user.
		alert('Uw browser is niet geschikt voor het weergeven van google maps.\nBezoek http://www.getfirefox.com voor een recentere browser.\n\nOnze excuses voor dit ongemak.');

	}

}

 //var xPoint = new GPoint(-83.0007, 39.9622);

//this.map.addOverlay(marker);

// Called when you click on the Submit button in the form.
// It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(country) {
  var address = document.forms[country].q.value;
  geocoder.getLocations(address, addAddressToMap);
}


function isDefined( variable)
{
    return (typeof(variable) == "undefined")?  false: true;
}


// Called when the geocoder returns an answer. It adds a
// marker to the map with a circle to indicate the 500
// mile radius.
function addAddressToMap(response) {

	// Clear search.
	locations = [];
	point = [];
	gmarkers = [];
	marker = [];
	overlayHtml = [];
	counter = [];


  map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Sorry, het adres kon niet worden gevonden.");
  } else {
    place = response.Placemark[0];
    aPoint = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    map.panTo(aPoint);
   	 
	drawCircle(place.Point.coordinates[0], place.Point.coordinates[1]);
	 
	var sUrl = "/search/ajax-get-houses/fLatitude/" + place.Point.coordinates[1] + "/fLongitude/" + place.Point.coordinates[0];
	
	// Set the url.
	XMLHttp.open("GET", sUrl);

		// Onchange function.
		XMLHttp.onreadystatechange = function() {
			
		// If the file is found.
		if (XMLHttp.readyState == 4 && XMLHttp.status == 200) {

				 /* Create houses object. */
				oHouses = eval('(' + XMLHttp.responseText + ')');
			
				/* Walk through houses. */
				for (var i = 0; i < oHouses.length; i++) {

					locations[i] = [];
					locations[i]['title'] = 'TITEL 1';
					locations[i]['text'] = 'TEXT 1';
					locations[i]['coordinate1'] = oHouses[i].latitude;
					locations[i]['coordinate2'] = oHouses[i].longitude;
					//locations[i]['html'] = '<p>Dit is content.</p>';
					
					
					

					locations[i]['html'] = '<p style="font-family: arial, verdana; font-size: 11px; line-height: 18px; width: 300px; height: 100px;"><strong>' + sPrefix + oHouses[i].house_id + '</strong><br /><img src="/image/get/sImage/' + oHouses[i]['pictures'][0]['name'] + '/iWidth/100/iHeight/76" style="float: left; padding: 1px; border: rgb(56, 123, 44); margin-right: 10px;" />' + oHouses[i]['country'] + '<br />' + oHouses[i]['region'] + '<br /><a href="javascript:this.openUrl(\'' + oHouses[i]['url'] + '\');">Bekijk details.</a></p>';
					//alert(i);
					//alert('<p style="font-family: arial, verdana; font-size: 11px; line-height: 18px; width: 300px; height: 100px;"><strong>' + sPrefix + oHouses[i].house_id + '</strong><br /><img src="/image/get/sImage/' + oHouses[i]['pictures'][0]['name'] + '/iWidth/100/iHeight/76" style="float: left; padding: 1px; border: rgb(56, 123, 44); margin-right: 10px;" />' + oHouses[i]['country'] + '<br />' + oHouses[i]['region'] + '<br /><a href="javascript:this.openUrl(\'' + oHouses[i]['url'] + '\');">Bekijk details.</a></p>');
			
				}
//alert(locations);			
				/* Place locations after a little while (due to loading). */
				setTimeout('showLocations()', 200);

		// If the file was not found.
		} else {

			// Alert the user.
//			alert('Probleem bij laden zoekresultaten.');
		}
	}

	// Send the request.
	XMLHttp.send(null);
  }
}

// Draws the 50 mile circumference.
function drawCircle(lng,lat) {
    var Cradius = 50;             // mile radius
    var Ccolor = '#ff0000';    // color red
    var Cwidth = 3;             // width pixels
    var d2r = Math.PI/180;   // degrees to radians
    var r2d = 180/Math.PI;   // radians to degrees
    var Clat = (Cradius/3963)*r2d;   //  using 3963 as earths radius
    var Clng = Clat/Math.cos(lat*d2r);
    var Cpoints = [];
    for (var i=0; i < 33; i++) {
        var theta = Math.PI * (i/16);
        Cx = lng + (Clng * Math.cos(theta));
        Cy = lat + (Clat * Math.sin(theta));
        Cpoints.push(new GPoint(Cx,Cy));
    };
    map.addOverlay(new GPolyline(Cpoints,'#ff0000', 5));
}


function openUrl(sUrl) {

	document.location.href = sUrl;

}


/* Map settings. */
function setMap() {

	/* Set map type. */
//	map.addMapType(G_NORMAL_MAP);
//	map.addMapType(G_SATELLITE_MAP);
	map.setMapType(G_NORMAL_MAP);
    map.addControl(new GMapTypeControl());

//	map.addMapType(G_SATELLITE_MAP);
	// G_SATELLITE_MAP 	= Satallite images.
	// G_HYBRID_MAP 		= Satallite + street names.
	// Others at: http://code.google.com/apis/maps/documentation.

	/* Enable or disable dragging of the map. */
	map.enableDragging(); // disableDragging().

	/* Enable or disable zooming with scrollwheel. */
	map.enableScrollWheelZoom(); // disableScrollWheelZoom().

	/* Enable or disable zooming by double clicking. */
	map.enableDoubleClickZoom(); // disableDoubleClickZoom().

}


/* Open info window for the clicked marker. */
function clickMarker(oPoint) {

		var iLocationId = 0;
		for (var iPoint = 0; iPoint < point.length; iPoint++) {
			if (point[iPoint] == oPoint) {
				iLocationId = iPoint;
			}
		}

	// Go to marker point.
	map.panTo(point[iLocationId]); 

	// Open location information.
	marker[iLocationId].openInfoWindowHtml(overlayHtml[iLocationId]);

}

	
/* Display locations on map. */
function showLocations() {

	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(32,32);
	baseIcon.shadowSize=new GSize(56,32);
	baseIcon.iconAnchor=new GPoint(16,32);
	baseIcon.infoWindowAnchor=new GPoint(16,0);
	  
	var house_icon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon56.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon56s.png");

	// Set counter to 0.
	var counter = 0;

	/* Create bounds objects */
	bounds = new GLatLngBounds();

	/* Walk through all locations. */
	locations.each(function(el) {

		/* Retrieve coordinates and create a point. */
		point[counter] = new GLatLng(el['coordinate1'], el['coordinate2']);

		/* Create a marker at the previous defined point. */
		marker[counter] = new GMarker(point[counter], house_icon);
		
		bounds.extend(point[counter]);

		/* Create HTML. */
		overlayHtml[counter] = '<div style="width: 125px;">' + el['html'] + '</div>';

		/* Add the marker to map. */
		map.addOverlay(marker[counter]);

		/* Add marker to array. */
		gmarkers.push(marker[counter]); 

		/* Add to counter. */
		counter++;

	});

	map.setZoom(map.getBoundsZoomLevel(bounds));
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	map.setCenter(new GLatLng(clat,clng));


	for (var iMarkerX = 0; iMarkerX < locations.length; iMarkerX++) {

		var iMarker = parseInt(iMarkerX);

		GEvent.addListener(gmarkers[iMarker], "click", function(oPoint) {
			clickMarker(oPoint);
		});
	}
}

var circleRadius = 50; // Miles

/* Temporary function to add a cricle to Google Maps. */
function addCircle() {
	// Create and add the circle
	var circle = new CircleOverlay(map.getCenter(), circleRadius, "#336699", 1, 1, '#336699', 0.25);
	map.addOverlay(circle);
} 
