var map;
var markers = [];
var infoWindow;
var geocoder;

function load() {

	// Get the last part of the URL = The store
	var myURL = window.location.pathname;
	var myStore = myURL.split( '/' );
	myStore = myStore[myStore.length-1];
	myStore = myStore.replace(/%C3%A5/g, "å").replace(/%C3%85/g, "å").replace(/%C3%A4/g, "ä").replace(/%C3%84/g, "ä").replace(/%C3%B6/g, "ö").replace(/%C3%96/g, "ö");

	// Calling the constructor, thereby initializing the map
	map = new google.maps.Map(document.getElementById("Gmap"), {
		center: new google.maps.LatLng(62.4, 17.3),
		zoom: 4,
		mapTypeId: 'roadmap',
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT},
		navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
	});
	
	// Creating an InfoWindow object with content from XML.
	infoWindow = new google.maps.InfoWindow();
	
	getLocations(myStore);

}


// Geocoder used to find out coordinates for an address
function getCoordinates(address, info) {

	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({address: address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			var latlng = results[0].geometry.location;
			createMarker(latlng, info);
		} 
		
		else {
			alert(address + ' not found');
		}
	});
 
}


// Clear all markers to avoid duplicates
function clearLocations() {

	infoWindow.close();
	for (var i = 0; i < markers.length; i++) {
		markers[i].setMap(null);
	}
 
		markers.length = 0;
		
}


// Get location from XML
function getLocations(myStore) {

	clearLocations(); 
	
	// Download stores.xml and parse it
	downloadUrl("http://www.synoptik.se/stores.xml", function(data) {

	   // Get all stores
	   var markerNodes = data.documentElement.getElementsByTagName("store");	   
		// Loops through all stores
		for (var i = 0; i < markerNodes.length; i++) {
			
			// If Store name in XML = last part of URL, get the address in correct format
			//if (myStore == markerNodes[i].getAttribute("name") || myStore == "samtliga-butiker") {
			if (myStore == markerNodes[i].getAttribute("name")) {
				
				var address = markerNodes[i].getElementsByTagName("address")[0].childNodes[0].nodeValue;
				var info = markerNodes[i].getElementsByTagName("info")[0].childNodes[0].nodeValue;
				
				map.setZoom(14);
				getCoordinates(address, info);
			}
		}
	});
}


// Create markers for each store
function createMarker(latlng, info) {

  var marker = new google.maps.Marker({
	map: map,
	position: latlng
  });
  
  infoWindow.setContent(info);
  infoWindow.open(map, marker);
  
  google.maps.event.addListener(marker, 'click', function() {
	infoWindow.setContent(info);
	infoWindow.open(map, marker);
  });

  markers.push(marker);
}


