// JavaScript Document

    /**
     * The concerts object, null until script loads in.
     * @type {Array}
     */
    var concerts = setConcerts();

    /** 
     *  Set the concerts variable based on the page name
     */
    function setConcerts() {
        var sPath = window.location.pathname;
        var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
        if (sPage == 'vensters.html') {
            concerts = [
                {   name: 'Grote Kerk Almelo', 
                    street: 'Kerkplein 1',
                    city: 'Almelo',
                    state: '',
                    zip: '7607 BT',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.358304, 
                    lng: 6.66571
                },
                {   name: 'Grote Kerk Emmen',
                    street: 'Ver. Prot. Centrum Grote Kerk Kerkpad',
                    city: 'Emmen',
                    state: '',
                    zip: '7811',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.791552, 
                    lng: 6.898127
                },
                {   name: 'Nicola&iuml;kerk',
                    street: 'Nicolaaskerkhof 9',
                    city: 'Utrecht',
                    state: '',
                    zip: '3512 XC',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.089791, 
                    lng: 5.129414
                }
            ];
        } else if (sPage == 'remember_me.html') {
            concerts = [
                {   name: 'Pieterskerk',
                    street: 'Pieterskerkhof 5',
                    city: 'Utrecht',
                    state: '',
                    zip: '3512 JR',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.095262, 
                    lng: 5.125186
                },
                {   name: 'Franciscus van Assisikerk',
                    street: 'Biest 43a',
                    city: 'Weert',
                    state: '',
                    zip: '6300 AP',
                    country: 'Nederland',
                    phone: '',
                    lat: 51.265245, 
                    lng: 5.717096
                },
                {   name: 'Oude Kerk',
                    street: 'Torenstraaat 1',
                    city: 'Soest',
                    state: '',
                    zip: '3764 CK',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.172984, 
                    lng: 5.311562
                },
                {   name: 'Sint Bavo',
                    street: 'Kerkplein 1',
                    city: 'Raamsdonk',
                    state: '',
                    zip: '4944 XD',
                    country: 'Nederland',
                    phone: '',
                    lat: 51.687445, 
                    lng: 4.907284
                },
                {   name: 'Oude Kerk', 
                    street: '1e Dorpsstraat 1',
                    city: 'Zeist',
                    state: '',
                    zip: '3701 HA',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.09575,
                    lng: 5.245628
                },
                {   name: 'Lambertuskerk',   
                    street: 'Helvoirtseweg 5',
                    city: 'Vught',
                    state: '',
                    zip: '5261 CA',
                    country: 'Nederland',
                    phone: '',
                    lat: 51.660722,
                    lng: 5.297744
                }
            ];
        } else if (sPage == 'hollandsche_meesters.html') {
            concerts = [
                {   name: 'Andrieskerk',
                    street: 'Hof 16',
                    city: 'Amerongen',
                    state: '',
                    zip: '3958 CH',
                    country: 'Nederland',
                    phone: '',
                    lat: 51.997784, 
                    lng: 5.461056


                },
                {   name: 'Oude Kerk',
                    street: 'Torenstraaat 1',
                    city: 'Soest',
                    state: '',
                    zip: '3764 CK',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.172984, 
                    lng: 5.311562
                },
                {   name: 'Ste. Gertrudiskathedraal',   
                    street: 'Willemsplantsoen 2',
                    city: 'Utrecht',
                    state: '',
                    zip: '3511 LA',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.094853,
                    lng: 5.120487
                }
                
            ];
        } else if (sPage == 'lamentaties_.html') {
            concerts = [
                {   name: 'Oude kerk',
                    street: 'Charloisse Kerksingel 35',
                    city: 'Rotterdam',
                    state: '',
                    zip: '3082 DA',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.469397, 
                    lng: 5.509644


                },
                {   name: 'Oude Kerk',
                    street: 'Torenstraaat 1',
                    city: 'Soest',
                    state: '',
                    zip: '3764 CK',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.172984, 
                    lng: 5.311562
                },
                {   name: 'Ste. Gertrudiskathedraal',   
                    street: 'Willemsplantsoen 2',
                    city: 'Utrecht',
                    state: '',
                    zip: '3511 LA',
                    country: 'Nederland',
                    phone: '',
                    lat: 52.094853,
                    lng: 5.120487
                }
                
            ];
        } else {
            concerts = [
                {   name: '',
                    street: '',
                    city: '',
                    state: '',
                    zip: '',
                    country: '',
                    phone: '',
                    lat: 0, 
                    lng: 0
                }
            ];
        }
        return concerts;
    }
    
	/**
	 * The map object, null until script loads in.
	 * @type {GMap2}
	 */
	var map = null;  

	/**
	 * The bounds of the markers once loaded in.
	 * @type {GLatLngBounds}
	 */
	var bounds = null;

	/**
	 * The marker with currently opened info window.
	 * @type {GMarker}
	 */
	var currentMarker = null;

	/**
	 * The dom element that the map is loaded into
	 * @type {Element}
	 */	
	var mapDiv = null;

	/**
	 * The dom element that everything is a child of.
	 * @type {Element}
	 */
	var containerDiv = null;

	/**
	 * Position of mouse click (clientX) on map div when in static mode.
	 * @type {Number}
	 */
	var clickedX = 0;
	
	/**
	 * Position of mouse click (clientY) on map div when in static mode.
	 * @type {Number}
	 */
	var clickedY = 0;

	/**
	 * Indicates whether we've created a script tag with Maps API yet
	 * @type {Boolean}
	 */
	var isLoaded = false;

	/**
	 * Icon
	 */
	var iconBlue = new GIcon();
	iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
	iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	iconBlue.iconSize = new GSize(12, 20);
	iconBlue.shadowSize = new GSize(22, 20);
	iconBlue.iconAnchor = new GPoint(6, 20);
	iconBlue.infoWindowAnchor = new GPoint(5, 1);
	
	/**
	 * Marker options
	 */
	 var options = {
		icon: iconBlue,
		draggable: false
	 };
	 
	/**
	 * Called after script is asynchronously loaded in.
	 * Creates the GMap2, GMarker objects and performs actions according to 
	 * what the user did to trigger the map load (search, zoom, click etc).
	 */
	function loadMap() {
	  if (GBrowserIsCompatible()) {
	    mapDiv.style.background = '#fff';
    	mapDiv.style.cursor = '';
	    map = new GMap2(mapDiv, {logoPassive: true});
	    bounds = new GLatLngBounds();
	    for (var i = 0; i < concerts.length; i++) {
	      bounds.extend(new GLatLng(concerts[i].lat, concerts[i].lng));
	    }
	    var latSpan = bounds.toSpan().lat();
	    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

    	// The static map server gives markers more space when calculating
	    // bounds and zoom level, so sometimes the API will give a higher
	    // zoom level than was used by the static map server.
	    // The .98 value is just a guess right now, may need tweaking.
    	var newBounds = map.getBounds();
	    var newLatSpan = newBounds.toSpan().lat();
	    if (latSpan/newLatSpan > .90) { map.zoomOut(); }

    	for (var i = 0; i < concerts.length; i++) {
	    	var marker = createMarker(i);
	    	var latlng = marker.getLatLng();
	      	var pixel = map.fromLatLngToDivPixel(latlng);
    		if (Math.abs(pixel.x - clickedX) < 12 && Math.abs(pixel.y - clickedY) < 20) {
        	  // GEvent.trigger(marker, 'click');
	    	}
			map.addOverlay(marker);
    	}
	  } 
	}

	/**
	 * Zooms to the viewport that fits all the markers.
	 */
	function zoomToAll() {
	  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	}

	/**
	 * Creates a marker for the given concert.
	 * @param {Number} ind
	 * @return {GMarker}
	 */
	function createMarker(ind) {
	  var concert = concerts[ind];
	  var marker = new GMarker(new GLatLng(concert.lat, concert.lng), options);
	  GEvent.addListener(marker, 'click', 
		function() {
			marker.html = ['<b>', concert.name, '</b><br>', 
    					concert.street, '<br> ', concert.zip, ' ',concert.city, 
    					// ',', concert.state,  
        				'<br>',
            			concert.phone, '<br>', 'Routebeschrijving: ','<br>', 
                 		'<a target="_blank" ',
                 		'href="http://maps.google.nl/maps?saddr=&daddr=',
                 		formatAddressForMaps(concert), '">hier naartoe</a> - ', 
                 		'<a target="_blank" ',
                 		'href="http://maps.google.nl/maps?saddr=',
                 		formatAddressForMaps(concert), '&daddr=', '"> hier vandaan <br> ',
                 		'<a href="javascript:zoomToAll()">Alle locaties</a>'].join('')
            ;
    		currentMarker = marker;
    		marker.openInfoWindowHtml(marker.html);
		}
	  );
  	return marker;
	}

	/**
 	 * Formats concert info into a URL-friendly version for maps url.
	 * @param {Object} concert
	 * @return {String}
	 */
	function formatAddressForMaps(concert) {
	  var address = concert.street + ' ' + concert.zip + ' ' + concert.city + ' ' + concert.state;
	  return escape(address.replace(' ', '+'));
	}

	/**
	 * Convenience function for creating an element and assigning an id to it.
	 * @param {String} elementType
	 * @param {String} id
	 * @return {Element} 
	 */
	function _cel(elementType, id) {
	  var element = document.createElement(elementType);
	  element.id = id;
	  return element;
	}

	/**
	 * Loads in the Maps API script. This is called after some sort of user interaction.
	 * The script loads asynchronously and calls loadMap once it's in.
	 */
	function loadScript() {
	  if (!isLoaded) {
	    isLoaded = true;
	    var div = document.createElement('div');
	    div.className = 'map_message';
	    div.innerHTML = 'Loading...';
    	div.style.left = (500/2 - 53) + 'px';
    	div.style.top = 500/2 + 'px'; 
	    mapDiv.appendChild(div);
	    var script = document.createElement('script');
	    script.type = 'text/javascript';
	    script.src = 'http://maps.google.nl/maps?file=api&v=2.x' + 
                    '&async=2&callback=loadMap&key=ABQIAAAAtRjxuw8jsDlnza5JmXxznRSXQYJkXEHhEmrG7pAPnKGv87IxOxTW1m59aujvy6NJ9Try7nGMGggGNw';
	    document.body.appendChild(script);
  	  }
	}

	/**
	 * Sets up the gadget by setting CSS and click events.
	 */
	function loadMapGadget() {
	  containerDiv = document.getElementById('map_container');
	  mapDiv = document.getElementById('map_canvas');

	  mapDiv.onclick = function (e) {
	    clickedX = (window.event && window.event.offsetX) || e.clientX;
	    clickedY = (window.event && window.event.offsetY) || e.clientY;
	   loadScript(); 
  	  };

  	  mapDiv.style.cursor = 'pointer';

	  var urlString = ['http://maps.google.nl/staticmap?markers='];
	  var markerString = [];
	  for (var i = 0; i < concerts.length; i++) {
	    markerString.push(concerts[i].lat + ',' + concerts[i].lng + ',red');
  	  }
	  urlString.push(markerString.join('|'));
	  urlString.push('&size=500x350');
	  urlString.push('&key=ABQIAAAAtRjxuw8jsDlnza5JmXxznRSXQYJkXEHhEmrG7pAPnKGv87IxOxTW1m59aujvy6NJ9Try7nGMGggGNw');
  	  mapDiv.style.background = 'url(\'' + urlString.join('') + '\')';
	}

