var base_url = $('base').attr('href');

var kmlcontroller = 'kmlcombine/2';
var loccontroller = 'locations/vbzleden.xls';

$(function(){
	
	// navigationobject
	$('.left:first').prepend( $('<div/>').addClass('navigationobject') );
		
	// doe ding:
	locationsMap(
		'#locationsmap', // div waar g-map in kompt
		'.left .navigationobject' // DOM-elem to prepend legend to
	);
	
});

function locationsMap(gMapElemID,gMapLegendPrepend){
	
	if( $(gMapElemID).length ){
		
		// load overlayscript
		$('body')
		.append(
			$("<script/>")
			.attr('type',"text/javascript")
			.attr('src',base_url+'js/ProjectedOverlay.js')
		);
		
		// preformat page / elem
		$(gMapElemID)
		//.css({'width': '440px', 'height': '400px'})
		.css({'width': '440px', 'height': '560px'})
		.after('<ul><li>zoeken op branche: gewenste branche aanklikken links in legenda</li><li>zoeken op plaatsnaam of locatie: intikken van de zoekterm in het vrije zoekveld</li></ul>');
		
		/* 
			fix hoogte verschillend (zie jquery.vbzkam.js)
		*/
		if(typeof(fixHeightDiff) !== 'undefined'){
			fixHeightDiff();
		}
	
		// locations (JSON array)	
		$.post(base_url+loccontroller, { "func": "getLocs" },
		function(data){
		
			// build map
			buildMap(data,gMapElemID,gMapLegendPrepend);
			
		},"json");
		
	}
	
}


function buildMap(locations,gMapElemID,gMapLegendPrepend){
	
	var g = google.maps;
	var map;
	
	var bounds;
	var curcategory;
	var kmlLayer = null;
	var currentLayer = null;
	var zoomChangeBoundsListener;
	
	// markers bevat de markers objecten
 	var markers = [];
 	
 	// legend bevat de legend objecten
 	var legend = [];
 	var legendwrap = $('<ul/>')
 	.prepend( 
		$('<li/>')
		.addClass('selected')
		.prepend(
			$('<a/>')
			.attr('href','')
			.css({
				'cursor': 'pointer',
				'height':'20px',
				'display':'inline-block',
				'padding':'6px 0 0 20px'
			})
			.click(function(){
				showMarkers();
				return false;
			})
			.html( 'Alle locaties' ) 
		) 
	);
	
	// zoekformulier field
 	var searchfield = $('<input/>')
 	.attr('id','locationsearchinput')
 	.keyup(function(){
 	
 		infowindow.close();
 	
 		var string = $(this).val();
 		
 		string = (string == '') ? false : string;
 		showMarkers(false,string);
 		
 	});
 	
 	// zoekformulier wrap searchform
	var searchform = $('<div/>')
	.attr('id','locationsearchholder')
	.append( 
		$('<label/>')
		.addClass('locationsearchinputlabel')
		.attr('for','locationsearchinput')
		.html('Zoek locatie:')
	)
	.append(searchfield);
	
    // map center en opties definieren
    var mapCenter = new g.LatLng(52.43881130724161, 4.880824463043232);
    var myOptions = {
        zoom: 9,
        center: mapCenter,
        pixelOffset: 5,
		panControl: false,
		backgroundColor:'#FFFFFF',
		//disableDefaultUI:true,
		//draggable:false,
		keyboardShortcuts:false,
		//mapTypeControl:false,
		//navigationControl:false,
		//scaleControl:false,
		//scrollwheel:false,
		
		mapTypeId: g.MapTypeId.TERRAIN 
    }
	// HYBRID // ROADMAP // SATELLITE // TERRAIN

    // map aanmaken
    map = new g.Map( $(gMapElemID)[0], myOptions);
    
	// map move event: Add a move listener to restrict the bounds range
	g.event.addListener(map, "drag", function() {
		checkBounds();
	});
	
	// restrict zoom-level
	g.event.addListener(map, "zoom_changed", function() {
		if (map.getZoom() < 8) { 
			map.setZoom(8); 
		}; 
	});

	// infowindow zullen pop-ups in worden getoont
	var infowindow = new g.InfoWindow({
        content: '',
        height: 200
    });
    
	// loop door de vestigingen en plaats de markers
	for(i = 0, a = locations.length; i < a; i++){
		
		locmark = locations[i];
		
		LatLng = new g.LatLng(locmark.latitude, locmark.longitude);
		
		if(!bounds){
			bounds = new g.LatLngBounds();
		}
		
		markers[i] = new g.Marker({
       		position: LatLng,
       		//noCloseOnClick:true,
       	 	map: map,
        	title: locmark.name,
        	city: locmark.city,
        	type: locmark.type,
			desc: locmark.beschrijving,
			icon: locmark.icon
			//icon: "markers/blue_small_marker.png"
    	});
    	
    	bounds.extend(LatLng);
		
		// Infowindow show met marker data
		g.event.addListener(markers[i], 'click', function(mouseEvent){
			infowindow.setContent( this.desc );
			infowindow.open(map, this );
		});
		
		// Infowindow sluit when clicking anywhere on the map.
		g.event.addListener(map, 'click', function(){
			infowindow.close();
		});
		
		// legenda
		addLegend(markers[i]);
		
	}
	
	
	// kmlLayer
	url = base_url+kmlcontroller;
	kmlLayer = new g.KmlLayer(url,{
		map: map,
		preserveViewport: false,
		suppressInfoWindows: true
	});
	
	// add overlay
	//overlayAdd();
	
	// zoom op bounds en increase zoom +1
	//Als bij KmlLayer: "preserveViewport" == false, dan kan deze uitgecomment:
	//zoomOnBounds();
  
	function addLegend(markers){
		
		var category = markers.type;
		var icon = markers.icon;
		
		if (category in legend) {
		
			legend[category] = legend[category]++;
			
		} else if( category != '') {
		
			legend[category] = 0;
			
			legendwrap
			.append( 
				$('<li/>')
				.prepend(
					$('<a/>')
					.attr('href','')
					.css({
						'cursor': 'pointer',
						'height':'20px',
						'overflow':'visible',
						'display':'inline-block',
						'padding':'6px 0 0 20px',
						'background-image': 'url('+icon+')',
						'background-repeat': 'no-repeat',
						'background-position': 'left center'
					})
					.click(function(){
						showMarkers(category);
						return false;
					})
					.html( category ) 
				) 
			);
		}
	}
	
	function showMarkers(category,searchstring){
		
		$('li',legendwrap)
		.removeClass('selected');
		
		if(category){
		
			$('a[text="'+category+'"]',legendwrap)
			.parent('li')
			.addClass('selected');
		
		} else {
			
			$('li:first',legendwrap)
			.addClass('selected');
		}
		
		bounds = new g.LatLngBounds();
		
		if(!searchstring){
		
			$(searchfield).val('');
			
		}
		
		if(category){
			
			curcategory = category;
			
			infowindow.close();
			
			for(i = 0, a = markers.length; i < a; i++){
			
				if(markers.type != category ){
					markers[i].setVisible(false);
				} 
				
				if (markers[i].type == category) {
				
					markerVisibility(markers[i],searchstring);
					
				}
			}
			
		} else {
			
			curcategory = false;
			
			for(i = 0, a = markers.length; i < a; i++){
				
				markerVisibility(markers[i],searchstring);
					
			}
			
		}
		
		// zoom op bounds en increase zoom +1
		zoomOnBounds();
	}
	
	// visibility van marker
	function markerVisibility(marker,searchstring){
		
		//wc(marker.title + ', ' + searchstring + ', ' + strpos(marker.title,searchstring,0) );
		
		if( !searchstring ){
			
			marker.setVisible(true);
			
			bounds.extend( marker.getPosition() );
			
		} else {
			
			if( strpos(marker.title,searchstring,0) || strpos(marker.city,searchstring,0) ){
			
				marker.setVisible(true);
				
				bounds.extend( marker.getPosition() );
				
			} else {
			
				marker.setVisible(false);
			}	
		
		}
	
	}
	
	// zoom op bounds en increase zoom +1
	function zoomOnBounds(plus){
	
		increase = plus ? plus : 0;
		
		map.fitBounds(bounds);
		zoomChangeBoundsListener = 
			g.event.addListener(map, 'bounds_changed', function(event) {
				if (this.getZoom()){
					if (this.getZoom() <= 11){
						this.setZoom( this.getZoom()+increase );
						//this.setZoom( this.getZoom() );
					}
				}
			g.event.removeListener(zoomChangeBoundsListener);
		});
	}
	
	function strpos (haystack, needle, offset) {
		
		/*
		var haystack = (haystack + '').toLowerCase();
		var needle = (needle + '').toLowerCase();
		var index = 0;
		
		if ((index = haystack.indexOf(needle,offset)) !== -1) {
			return index;
		}
		return false;
		*/
		
		return haystack.toLowerCase().indexOf(needle.toLowerCase())>=0;
	}
	
	
	
	function overlayAdd()
	{	
		// wit vlak
		/*
		var ne = new g.LatLng(60.0,12.0);
		var sw = new g.LatLng(40.0,0.001);
		new ProjectedOverlay(map,base_url+'gui/map/white.gif', new g.LatLngBounds(sw,ne), {percentOpacity:100}) ;
		*/
		
		// kaartje
		var ne = new g.LatLng(53.878, 8.130);
		var sw = new g.LatLng(50.380, 2.460);
		overlaybounds = new g.LatLngBounds(sw,ne);
		
		new ProjectedOverlay(
			map,base_url+'gui/map/backgroundmap-lightblue.png',
			//site_base_url+'gui/locations/backgroundmap-lightblue.bg.gif',
			overlaybounds,
			{
				percentOpacity:100
			}
		);
		
	}
	
	// If the map position is out of range, move it back
	function checkBounds() {
		
		//wc(map.getCenter());
		
		// Perform the check and return if OK
		if (bounds.contains(map.getCenter())) {
			return;
		}
		// It`s not OK, so find the nearest allowed point and move there
		var C = map.getCenter();
		var X = C.lng();
		var Y = C.lat();
		
		var AmaxX = bounds.getNorthEast().lng();
		var AmaxY = bounds.getNorthEast().lat();
		var AminX = bounds.getSouthWest().lng();
		var AminY = bounds.getSouthWest().lat();
		
		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
		
		//wc ("Restricting "+Y+" "+X);
		map.setCenter(new g.LatLng(Y,X));
	}
	
	
	
	
	
	// add searchfield to DOM
	$(gMapLegendPrepend)
	.prepend(searchform);
	
	// add legend to DOM
	$(gMapLegendPrepend)
	.prepend(legendwrap);
    
}
