// JavaScript Document
var Virunga = {
	Google: {	
		Maps: {
			map: null,
			canvas: null,
			markers: [],
			autozoom: function () {
				var mapBounds, n, i;
				if (this.map !== null) {
					mapBounds = new google.maps.LatLngBounds();
					n = this.markers.length;
					// Extend the mapBounds with each marker
					for (i = 0; i < n; i++) {
						mapBounds.extend(this.markers[i].getPosition());
					}
					this.map.fitBounds(mapBounds);
				}
			},
			checkzoom: function () {
				if (Virunga.Google.Maps.map.getZoom() > 19) {
					Virunga.Google.Maps.map.setZoom(10);
				}
			},
			addMarker: function (marker) {
				// Make sure the marker is not inserted before
				var n, i;
				n = this.markers.length;
				for (i = 0; i < n; i++) {
					if (this.markers[i] === marker) {
						return false;
					}
				}
				this.markers.push(marker);
			},
			clearMarkers: function () {
				var n, i;
				// Delete all the markers on the map
				n = this.markers.length;
				for (i = 0; i < n; i++) {
					this.markers[i].setMap(null);
				}
				// Delete present markers
				this.markers = [];
			},
			init: function () {
				//var land, gebied, bounds, topLat, topLng, bottomLat, bottomLng;
				var start, query, country, area;
				// Check if the canvas is available
				if (document.getElementById("map_canvas")) {
					this.canvas = document.getElementById("map_canvas");
				}
				if (document.getElementById("map_canvas_small")) {
					this.canvas = document.getElementById("map_canvas_small");
				}
				if (this.canvas) {
					this.Options.center = new google.maps.LatLng(57.5259614, 15.2551187);/*(52.215545,5.589501); /*Center of NL*/
					/*(57.5259614, 15.2551187) Center of Europe*/
					this.Options.mapTypeId = google.maps.MapTypeId.ROADMAP;
					this.loadMap(this.canvas);
					if (document.location.href.indexOf('vakantiehuizen/')) {
							
						start = document.location.href.lastIndexOf('vakantiehuizen/');
						if (start > 0) {
							query = document.location.href.substr(start + 15);
							//alert(query);
							if (query.indexOf("/") === -1) {
								//document.writeln('Land : ' + query + '<br />');
								country = query;
								Virunga.Event.loadParkXML(country, null);
							} else {
								
								country = query.substring(0, query.indexOf('/'));
								//document.writeln('Land = ' + country + '<br />');
								area = query.substr(query.indexOf('/') + 1);
								//document.writeln('Gebied = ' + area + '<br />');
								Virunga.Event.loadParkXML(country, area);
							}
						} else {
							Virunga.Event.loadParkXML(null, null);
						}
					}
				}
				// Load areas
				if (document.getElementById("country")) {
					if (document.getElementById("areas")) {
						document.getElementById("country").onchange = Virunga.Event.setAreas;
					}
					if (document.getElementById("area")) {
						document.getElementById("area").onchange = Virunga.Event.redirect;
					}
				}
				// Map zoom to load markers when the mapview is changed; disabled due to markers with a top-position
				
				if (this.map !== null) {
					/*
					if (document.location.href.lastIndexOf('vakantiehuizen/') === -1) {
						google.maps.event.addListener(this.map, 'zoom_changed', this.loadMarkers);
						google.maps.event.addListener(this.map, 'dragend', this.loadMarkers);
						google.maps.event.addListener(this.map, 'tilesloaded', this.loadMarkers);
					}
					*/
					google.maps.event.addListener(this.map, 'tilesloaded', this.checkzoom);
				}
				
				if (typeof(Shadowbox.init) !== 'undefined') {
					Shadowbox.init();
				}
			},
			loadMap: function (canvas) {
				// Load the map onto the canvas
				if (canvas) {
					this.map = new google.maps.Map(canvas, this.Options);
					if (this.map === null) {
						alert("Kan map niet initialiseren.");
					}
				}
			},
			loadMarkers: function () {
				var bounds, topLat, topLng, bottomLat, bottomLng;
				if (Virunga.Google.Maps.map.getZoom() > 6) {
					bounds = Virunga.Google.Maps.map.getBounds();
					topLat = bounds.getNorthEast().lat();
					topLng = bounds.getNorthEast().lng();
					bottomLat = bounds.getSouthWest().lat();
					bottomLng = bounds.getSouthWest().lng();
					Virunga.Event.getParkXML(topLat, topLng, bottomLat, bottomLng);
				}
			},
			Options: {
				center: null,
				mapTypeId: null,
				zoom: 7, // Space 0-1, State 2-7, City 8-13, Block 14-17, Ground 18-19
				panControl: true,
				streetViewControl: false
			},
			createMarker: function (lat, lng, id, name, path, city, area, country, total) {
				var marker = new google.maps.Marker({
					map: Virunga.Google.Maps.map,
					position: new google.maps.LatLng(lat, lng),
					title: (total > 1) ? 'Bekijk accommodaties (' + total + ')' : 'Bekijk details'
				});
				if (document.getElementById("preview")) {
					google.maps.event.addListener(marker, 'mouseover', function () {
						var html;
						document.getElementById("preview").style.display = "block";
						html = '<h4>' + name + '</h4><img src="http://' + path + '" alt="' + path +  '" /><div class="info"><label>Plaats:</label><span class="value">' + city + '</span></div><div class="info"><label>Aantal:</label><span class="value">' + total;
						if (total > 1) {
							html += ' accommodaties</span></div>';
						} else {
							html += ' accommodatie</span></div>';
						}
						document.getElementById("preview").innerHTML = html;
					}); 
					google.maps.event.addListener(marker, 'mouseout', function () {
						document.getElementById("preview").style.display = "none";
					});
				}
				google.maps.event.addListener(marker, 'click', function () {
					if (total > 1) {
						target = 'http://www.vakantiewoningen-in-europa.nl/' + id + '/vakantiewoningen/' + area + '/' + country;
					} else {
						target = 'http://www.vakantiewoningen-in-europa.nl/' + id + '/vakantiewoning/' + area + '/' + country;
					}
					//target += '?id=' + id + '&gebied=' + area + '&land=' + country;
					location.href = target;
				});
				return marker
			},
			placeMarkers: function (xml) {
				var parks, park, id, name, city, area, country, total, path, target, lat, lng, marker, i, j, n, m;
				if (xml) {
					parks = xml.getElementsByTagName("park");
					n = parks.length;
					for (i = 0; i < n; i++) {
						park = parks[i].childNodes;
						if (parks.length > 0) { // Check if node is not empty
							m = park.length;
							if (m > 0) {
								for (j = 0; j < m; j++) {
									switch(park[j].nodeName) { 
										case "latitude":
											if (park[j].textContent) {
												lat = parseFloat(park[j].textContent);
											} else {
												lat = parseFloat(park[j].childNodes[0].nodeValue);
											}
											break;
										case "longitude":
											if (park[j].textContent) {
												lng = parseFloat(park[j].textContent);
											} else {
												lng = parseFloat(park[j].childNodes[0].nodeValue);
											}
											break;
										case "id":
											if (park[j].textContent) {
												id = parseInt(park[j].textContent, 10);
											} else {
												id = parseInt(park[j].childNodes[0].nodeValue, 10);
											}
											break;
										case "name":
											if (park[j].textContent) {
												name = park[j].textContent;
											} else {
												name = park[j].childNodes[0].nodeValue;
											}
											break;
										case "plaats":
											if (park[j].textContent) {
												city = park[j].textContent;
											} else {
												city = park[j].childNodes[0].nodeValue;
											}
											break;
										case "gebied":
											if (park[j].textContent) {
												area = park[j].textContent;
											} else {
												area = park[j].childNodes[0].nodeValue;
											}
											break;
										case "land":
											if (park[j].textContent) {
												country = park[j].textContent;
											} else {
												country = park[j].childNodes[0].nodeValue;
											}
											break;
										case "total":
											if (park[j].textContent) {
												total = parseInt(park[j].textContent, 10);
											} else {
												total = parseInt(park[j].childNodes[0].nodeValue, 10);
											}
											break;
										case "path":
											if (park[j].textContent) {
												path = park[j].textContent;
											} else {
												path = park[j].childNodes[0].nodeValue;
											}
											break;
										default:
											break;
									}
								}
								if (lat && lng) {
									marker = Virunga.Google.Maps.createMarker(lat, lng, id, name, path, city, area, country, total);
									Virunga.Google.Maps.addMarker(marker);
								}
							}
						}
					}
				}
			}
		}
	},
	Event: {
		redirect: function () {
			var land, gebied, target;
			land = document.getElementById("country").options[document.getElementById("country").selectedIndex].value;
			gebied = document.getElementById("area").options[document.getElementById("area").selectedIndex].value;
			//target = location.protocol + '//' + location.host + '/vakantiehuizen.php?land=' + land + '&gebied=' + gebied;
			target = location.protocol + '//' + location.host + '/vakantiehuizen/' + land + '/' + gebied;
			location.href = target;
		},
		setParkList: function (land) {
			var xhr = Virunga.AJAX.Request.create('http://www.vakantiewoningen-in-europa.nl/scripts/parklist.php?land=' + land);
			if (typeof (xhr) !== undefined) {
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4) {
						if (xhr.status === 200) {
							if (document.getElementById("lstParks")) {
								document.getElementById("lstParks").innerHTML = xhr.responseText;
							}
						} else {
							alert('XMLHttpRequest is niet gelukt (status: ' + xhr.status + ')');
						}
					}
				};
			}
		},
		setAreas: function () {
			var xhr = Virunga.AJAX.Request.create('http://www.vakantiewoningen-in-europa.nl/scripts/areas.php?land=' + this.options[this.selectedIndex].value),
			land = this.options[this.selectedIndex].value;
			if (typeof (xhr) !== undefined) {
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4) {
						if (xhr.status === 200) {
							if (document.getElementById("areas")) {
								document.getElementById("areas").innerHTML = xhr.responseText;
								if (document.getElementById("list")) {
									Virunga.Event.setAreaList();
									Virunga.Event.loadParkXML(land, null);
									Virunga.Event.setParkList(land);
								}
								if (document.getElementById("area")) {
									document.getElementById("area").onchange = Virunga.Event.redirect;
								}
							}
						} else {
							alert('XMLHttpRequest is niet gelukt (status: ' + xhr.status + ')');
						}
					}
				};
			}
		},
		setAreaList: function () {
			if (document.getElementById("list")) {
				var xhr = Virunga.AJAX.Request.create('http://www.vakantiewoningen-in-europa.nl/scripts/arealist.php?land=' + document.getElementById("country").options[document.getElementById("country").selectedIndex].value);
				if (typeof (xhr) !== undefined) {
					xhr.onreadystatechange = function () {
						if (xhr.readyState === 4) {
							if (xhr.status === 200) {
								if (document.getElementById("list")) {
									if (document.getElementById("list_title")) {
										document.getElementById("list_title").innerHTML = "Kies een regio:";
									}
									document.getElementById("list").innerHTML = xhr.responseText;
								}
							} else {
								alert('XMLHttpRequest is niet gelukt (status: ' + xhr.status + ')');
							}
						}
					};
				}
			}
		},
		loadParkXML: function (land, gebied) {
			var url = 'http://www.vakantiewoningen-in-europa.nl/scripts/loadparkxml.php',
			xhr;
			if (land !== null) {
				url += '?land=' + land;
				if (gebied !== null) {
					url += '&gebied=' + gebied;
				}
			}
			xhr = Virunga.AJAX.Request.create(url);
			if (typeof (xhr) !== undefined) {
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4) {
						if (xhr.status === 200) {
							Virunga.Google.Maps.clearMarkers(); // Remove existing markers
							Virunga.Google.Maps.placeMarkers(xhr.responseXML);
							Virunga.Google.Maps.autozoom();
						} else {
							alert('XMLHttpRequest is niet gelukt (status: ' + xhr.status + ')');
						}
					}
				};
			}
		},
		getParkXML: function (topLat, topLng, bottomLat, bottomLng) {
			//alert('scripts/getparkxml.php?toplat=' + topLat + '&toplng=' + topLng +'&bottomlat=' + bottomLat + '&bottomlng=' + bottomLng);
			var xhr = Virunga.AJAX.Request.create('http://www.vakantiewoningen-in-europa.nl/scripts/getparkxml.php?toplat=' + topLat + '&toplng=' + topLng +'&bottomlat=' + bottomLat + '&bottomlng=' + bottomLng);
			if (typeof (xhr) !== undefined) {
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4) {
						if (xhr.status === 200) {
							Virunga.Google.Maps.clearMarkers(); // Remove existing markers
							Virunga.Google.Maps.placeMarkers(xhr.responseXML);
						} else {
							alert('XMLHttpRequest is niet gelukt (status: ' + xhr.status + ')');
						}
					}
				};
			}
		}
	},
	AJAX: {
		Request: {
			create: function (url) {
				var xhr = false;
				if (window.XMLHttpRequest) {
					xhr = new XMLHttpRequest();
				} else {
					if (window.ActiveXObject) {
						try {
							xhr = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e) { }
					}
				}
				if (xhr) {
					xhr.open('GET', url, true);
					xhr.send(null);
					return xhr;
				} else {
					alert("Er is iets fout gegaan met de XMLHttpRequest");
				}
			}
		}
	}
};

function init() {
	Virunga.Google.Maps.init();
}
window.onload = init;
