function initMap() {

	window.gMap = {};

	window.gMap.mapCanvas       = $('mapcanvas');
	window.gMap.mapCanvas.wpr   = $('wpr-mapcanvas');
	window.gMap.directionsPanel = $('directions-panel');
	window.gMap.filter          = $('mapfilter');
	window.gMap.pageslug        = window.location.pathname.split('/').getLast();

	// if page have tabs content move the map
	if ($('submenu').getElement('li')) {
		window.gMap.mapCanvas.inject($('wpr-page'), 'before');
		window.gMap.mapCanvas.setStyles({
			position: 'absolute',
			top: -9000
		});
	}

	// map options
	window.gMap.mapOptions = {
		mapTypeControl: false,
		navigationControl: true,
		navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
		zoom: 10,
		center: new google.maps.LatLng(52.079056, 4.773560),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false
	};

	// create map
	window.gMap.map = new google.maps.Map(window.gMap.mapCanvas, window.gMap.mapOptions);
}

function initRoute(coordinates) {

	var mapCoordinates = [];

	// save all coordinates as google maps LatLng object
	coordinates.each(function(coordinate) {
		var lat = coordinate.split(',')[0];
		var lng = coordinate.split(',')[1];
		var LatLng = new google.maps.LatLng(lat, lng);
		mapCoordinates.push(LatLng);
	});

    // check if route is a boat route else show directions route
    if (window.gMap.mapCanvas.wpr.boat == true) {
        // create google maps bounds to center map on polyline
        var bounds = new google.maps.LatLngBounds();
        mapCoordinates.each(function(coordinate) {
            bounds.extend(coordinate);
        });

    	// Polyline, used for boat routes
    	var polyline = new google.maps.Polyline({
    		path: mapCoordinates,
    		strokeColor: '#000',
    		strokeOpacity: 1.0,
    		strokeWeight: 2
    	});

    	polyline.setMap(window.gMap.map);
    	window.gMap.map.fitBounds(bounds);
    } else {
    	// start and end coordinate
    	var startCoordinate = coordinates[0];
    	var endCoordinate   = coordinates.getLast();

    	var waypoints = [];
    	var waypointsCoordinates = coordinates.erase(startCoordinate).erase(endCoordinate); // erase start and end coordinate
    	waypointsCoordinates.each(function(waypointCoordinate) {
    		waypoints.push({
    			location: waypointCoordinate,
    			stopover: false
    		});
    	});

    	var request = {
    		origin: startCoordinate,
    		destination: endCoordinate,
    		waypoints: waypoints,
    		travelMode: google.maps.DirectionsTravelMode.WALKING
    	};

    	var directionsService = new google.maps.DirectionsService();
      	var directionsDisplay = new google.maps.DirectionsRenderer();
    	directionsService.route(request, function(result, status) {
    		if (status == google.maps.DirectionsStatus.OK) {
    			directionsDisplay.setDirections(result);
    		}
    	});

    	directionsDisplay.setMap(window.gMap.map);
    	directionsDisplay.setPanel(window.gMap.directionsPanel);
    }
}

function initMarkers() {

	window.gMap.gMarkers = [];

	window.gMap.allMarkers = new Hash(participants);

	// check if you need to show filtered markers or the contact marker
	if (window.gMap.filter) {
		getFilteredMarkers();
	} else {
		getContactMarker();
	}
}

function removeAllMarkers() {

	window.gMap.gMarkers.each(function(gMarker, index) {
		gMarker.setMap(null);
	});
}

function getContactMarker() {

	window.gMap.filteredMarkers = new Hash();

	window.gMap.allMarkers.each(function(participantData, participant) {
		// filter marker on pagename
		if (participant == window.gMap.pageslug) {
			window.gMap.filteredMarkers.include(participant, participantData);
		}
	});

	addMarkers();
}

function getFilteredMarkers() {

	// loop through checkboxes and add click event
	window.gMap.filter.checkboxes = window.gMap.filter.getElements('input[type="checkbox"]');
	window.gMap.filter.checkboxes.each(function(checkbox) {
		// add on change event on all checkboxes

		if (!window.IE) {
			checkbox.addEvent('change', filterMarkers);
		} else {
			checkbox.addEvent('click', filterMarkers);
		}
	});

	filterMarkers();
}

function filterMarkers() {

	window.gMap.filteredMarkers = new Hash();
	var currentCategories       = [];

    if (window.gMap.pageslug != 'kaart') {
    	// push page slug in current categories
    	currentCategories.push(window.gMap.pageslug);
    }

	// loop through all checkboxes
	window.gMap.filter.checkboxes.each(function(checkbox) {
		if (checkbox.checked && !currentCategories.contains(checkbox.value)) {
			currentCategories.push(checkbox.value);
		}
	});

	// get markers matching the categories
	window.gMap.allMarkers.each(function(participantData, participant) {
		// filter markers on category
		var addMarker = null;
		currentCategories.each(function(category) {
			if (participantData.categories.contains(category) && addMarker != false) {
				addMarker = true;
			} else {
				addMarker = false;
			}
		});

		// if participant match all categories, add marker
		if (addMarker == true || window.gMap.pageslug == 'kaart') {

    		if (window.gMap.pageslug == 'kaart' && currentCategories.length < 1) {
    		    window.gMap.filteredMarkers.include(participant, participantData);
    		} else if (addMarker == true) {
    		    window.gMap.filteredMarkers.include(participant, participantData);
    		}
		}
	});

	// remove all current markers
	removeAllMarkers();

	// set new markers
	addMarkers();
}

function addMarkers() {

	window.gMap.gMarkers = [];
	var bounds           = new google.maps.LatLngBounds();

	// get filtered markers
	window.gMap.filteredMarkers.each(function(filteredMarker, index) {
		window.gMap.infoWindow = new google.maps.InfoWindow();

		// default marker image
		var defaultMarkerImg = '/layouts/struinenenvorsen/images/marker-struinenenvorsen.png';

		// check if there is a map filter
		if (window.gMap.filter) {
			// if page slug exists in checkboxes, the page slug is the default marker image
			window.gMap.filter.checkboxes.each(function(checkbox) {
				if (window.gMap.pageslug == checkbox.value) {
					defaultMarkerImg = '/layouts/struinenenvorsen/images/marker-' + window.gMap.pageslug + '.png';
				}
			});
		}

		// get marker data
		var markerName        = filteredMarker['name'];
	    var markerLink        = filteredMarker['pagepath'];
		var markerImg         = defaultMarkerImg;
		var markerInfoContent = filteredMarker['content'];
		var markerLatLng      = new google.maps.LatLng(filteredMarker['LatLng'].split(',')[0], filteredMarker['LatLng'].split(',')[1]);

		// save LatLng of current marker to bounds
		bounds.extend(markerLatLng);

		// create Google Maps marker
		var gMarker = new google.maps.Marker({
			position: markerLatLng,
			icon: markerImg,
			map: window.gMap.map,
			title: markerName
		});
		gMarker.infoContent = '<div class="info-window"><h3><a href="' + markerLink + '>' + markerName + '</a></h3><p>' + markerInfoContent + '</p></div>';

		// save current markers
		window.gMap.gMarkers.push(gMarker);

		google.maps.event.addListener(gMarker, 'click', function() {
			window.gMap.infoWindow.open(window.gMap.map, gMarker);
			window.gMap.infoWindow.setContent(gMarker.infoContent);
		});
	});

	// fit all markers on screen if there are markers
	if (window.gMap.filteredMarkers.getLength() > 0) {
		window.gMap.map.setCenter(bounds.getCenter());
	}
}

function initSlideShow(wpr) {

	var slideShowPhotoPath = '/layouts/struinenenvorsen/images/header/';
	var photos = [
		'img-01.jpg',
		'img-02.jpg',
		'img-03.jpg',
		'img-04.jpg',
		'img-05.jpg',
		'img-06.jpg',
		'img-07.jpg',
		'img-08.jpg',
		'img-09.jpg',
		'img-10.jpg',
		'img-11.jpg',
		'img-12.jpg',
		'img-13.jpg',
		'img-14.jpg'
	];

	// create slideshow
	var slideshow = new Slideshow(wpr, photos, {
		loader: false,
		hu: slideShowPhotoPath,
		width: 995,
		height: 250,
		delay: 3000,
		duration: 1000,
		random: true
	});
}

window.addEvent('domready', function() {

	var body         = $(document.body);
	var mainmenu     = $('wpr-mainmenu');
	var searchmenus  = $$('#participants-searchmenu, #routes-searchmenu');
	var wprcontent   = $('wpr-content');
	var sidebarRight = $('sidebar-right');
	var sidebarNews  = $('sidebar-news');
	var mapcanvas    = $('wpr-mapcanvas');

	window.IE        = Browser.Engine.trident ? true : false;

	// init SlideShow header
	var headerSlideshow = $('header-slideshow');
	if (headerSlideshow) { initSlideShow(headerSlideshow); }

	// searchmenu behaviour
	if (searchmenus) {
		searchmenus.each(function(searchmenu) {
			searchmenu.items = searchmenu.getElements('li');
			searchmenu.items.each(function(item, index) {
				// check if there is a submenu
				item.submenu = item.getChildren('ul');

				if (item.submenu.length > 0) {
					item.submenu = item.submenu[0];

					// create toggle button
					item.submenu.toggleButton = new Element('a', {
						'class': 'toggle-button',
						'href': '#',
						'text': 'expand/collapse',
						'events': {
							'click': function(e) {
								this.toggleClass('expand');
								item.submenu.toggleClass('hide');

								// stop event
								e.stop();
							}
						}
					}).inject(item, 'top');

					// init submenu and toggle button
					if (!item.hasClass('current')) {
						item.submenu.addClass('hide');
					} else {
						item.submenu.toggleButton.addClass('expand');
					}
				}
			});
		});
	}

	// add print and translate buttons
	var printButton = new Element('div', {
		'id': 'print-button',
		'html': '<a href="#">Print pagina</a>',
		'events': {
			'click': function(e) {
				window.print();

				e.stop();
			}
		}
	});

	var translateButton = new Element('div', {
		'id': 'translate-button',
		'html': '<a href="http://translate.google.com/translate?hl=EN&sl=nl&tl=en&u=' + encodeURIComponent(window.location.href) + '" target="_blank">Translate page</a>'
	});

	// inject buttons
	translateButton.inject(wprcontent, 'top');
	printButton.inject(wprcontent, 'top');

	// replace search button(s)
	var submitButtons = body.getElements('input.submit');
	submitButtons.each(function(button) {
		var buttonForm = button.getParent('form');
		var styledButton = new Element('div', {
			'id': button.id,
			'class': 'styled-submit',
			'html': button.value,
			'events': {
				'click': function(e) {
					buttonForm.submit();
				}
			}
		});
		styledButton.replaces(button);
	});

	// add round corner mainmenu
	if (mainmenu) {
		var mainmenuBottom = new Element('div', { 'class': 'bottom-green' });
		mainmenuBottom.inject(mainmenu, 'after');
	}

	// add round corner sidebar right contents
	if (sidebarRight) {
		var contentsSidebarRight = sidebarRight.getElements('div.content');
		contentsSidebarRight.each(function(contentSidebarRight) {
			var topSidebarRight = new Element('div', { 'class': 'top-content' });
			topSidebarRight.inject(contentSidebarRight, 'before');
		});
	}

	// remove last border sidebar-news
	if (sidebarNews) {
		var linksSidebarNews = sidebarNews.getElements('a');
		linksSidebarNews.getLast().addClass('last');
	}

	// replace h2's for tabs on deelnemers pages
	if (body.hasClass('deelnemers') || body.hasClass('zoeken')) {

		// get all headers that should be placed in the submenu
		var headers = $$('#content h2');
		if (headers && headers.length > 0) {

			// create submenu
			var subMenu  = new Element('ul').inject($('submenu'));

			// last header (menuitem)
			var lastItem = headers.getLast();

			headers.each(function(header, index) {

				var subMenuItem = new Element('li', {
					'id': 'sub-menu-item-' + index,
					'html': '<a href="#">' + header.get('text') + '</a>'
				});

				subMenuItem.tabContent = new Element('div', {
					'id': 'tab-content-' + index,
					'class': 'tab-content'
				});

				// add classes to the menuitems
				if (index == 0) {
					subMenuItem.addClass('first current');
					subMenuItem.tabContent.addClass('current');

					// set global active tabs
					subMenu.currentMenuItem   = subMenuItem;
					subMenu.currentTabContent = subMenuItem.tabContent;
				} else {
					subMenuItem.tabContent.addClass('hide');
				}

				if (header == lastItem) {
					subMenuItem.addClass('last');
				}

				// copy content in tab container (to show / hide)
				var nextSibling = header.getNext();

				while(nextSibling != headers[index + 1] && !nextSibling.hasClass('tab-content')) {
					var currentSibling = nextSibling;
					nextSibling = nextSibling.getNext();
					currentSibling.inject(subMenuItem.tabContent);
				}

                // slide content h3's participants
                var headerText = header.get('text');

                if (headerText == 'Activiteiten' && subMenuItem) {

                    var togglers   = subMenuItem.tabContent.getElements('h3');
                    var containers = Array();

                    togglers.each(function(toggler) {

                        var content  = toggler.getNext();
                        var contents = Array();
                        toggler.addClass('accordion-toggler');

                        while (content && !togglers.contains(content)) {
                            contents.push(content);
                            content = content.getNext();
                        }

                	    toggler.wprContent = new Element('div', { 'class': 'wpr-content' });

                        contents.each(function(contentItem) {
                           contentItem.inject(toggler.wprContent);
                        });
                        toggler.wprContent.inject(toggler, 'after');

                        containers.push(toggler.wprContent);
                    });
                    var accordionFx = new Fx.Accordion(togglers, containers, {
                        'display': -1
                    });
                }

				// inject elements in dom
				header.destroy();
				subMenuItem.inject(subMenu);
				subMenuItem.tabContent.inject($('content').getElement('.content'));

				// add events
				subMenuItem.addEvent('click', function(e) {
					if (this != subMenu.currentMenuItem) {

						subMenu.currentMenuItem.removeClass('current');
						subMenu.currentTabContent.removeClass('current');
						subMenu.currentTabContent.toggleClass('hide');

						this.addClass('current');
						this.tabContent.addClass('current');
						this.tabContent.toggleClass('hide');

						subMenu.currentMenuItem   = this;
						subMenu.currentTabContent = this.tabContent;

						if (window.gMap && window.gMap.mapCanvas) {
							window.gMap.mapCanvas.inject(window.gMap.mapCanvas.wpr);
							window.gMap.mapCanvas.setStyles({
								position: 'relative',
								top: 0
							});
						}
					}

					e.stop();
				});
			});
		}
	}

	// create google maps on participants page contact tab
	if (body.hasClass('deelnemers')) {
		// get contact tab (last tab)
		var contactTab = $$('#content .tab-content').getLast();

		if (contactTab) {
			// create mapcanvas div
			mapcanvas = new Element('div', {
				'id': 'wpr-mapcanvas',
				'class': 'marker',
				'html': '<div id="mapcanvas"></div>'
			}).inject(contactTab, 'top');
		}
	}

	// create google maps on route page
	if (body.hasClass('routes')) {
		var routeContents = $$('#content .content.route');
		if (routeContents.length > 0) {
			routeContents.each(function(routeContent) {

				// create mapcanvas div
				mapcanvas = new Element('div', {
					'id': 'wpr-mapcanvas',
					'class': 'route',
					'html': '<div id="mapcanvas"></div>'
				});

                if (routeContent.hasClass('boat')) {
                    mapcanvas.boat = true;
                } else {
                    mapcanvas.boat = false;
                }

				mapcanvas.coordinates = [];

				// save all coordinates into array
				routeContent.getElements('li').each(function(listitem) {
					mapcanvas.coordinates.push(listitem.get('html'));
				});

				// empty inside content
				routeContent.empty();

				// inject mapcanvas
				mapcanvas.inject(routeContent);

                // create directions panel for route
                if (mapcanvas.boat == false) {
                    directionsPanel = new Element('div', {
    					'id': 'directions-panel'
    				}).inject(routeContent);
				}
			});
		}
	}

	// init map if mapcanvas element exists
	if (mapcanvas) {
		if (mapcanvas.hasClass('marker')) {
			new Asset.javascript('/api/custom/participant/get_list_json', {
				'onload': function() {
					initMap();
					initMarkers();
				}
			});
		}
		if (mapcanvas.hasClass('route')) {
			initMap();
			if (mapcanvas.coordinates.length > 0) {
				initRoute(mapcanvas.coordinates);
			}
		}
	}
});
