var maxzoom = 12;
var markers = [];
var infoWindow;
var infopane;
var bounds;
var dragbounds;
var locbounds;
var map;
var g;

function initialize() {
	
	// set google maps shorthand
	g = google.maps;
	
	// spawn info panel
	infopane = $('<div/>')
	//.prependTo( $('div #mapcontainer') )
	.prependTo( $('div#resultaataanpassen') )
	.attr('id','info')
	.wrap(
		$('<div/>')
		.attr('id','infoholder')
		.addClass('active')
		.css({'z-index':3000})
		//
	);
	
	// load overlayscript
	/*
	var script = $("<script/>")
	.attr('type',"text/javascript")
	.attr('src',basehref+'js/ProjectedOverlay.js');
	
	$('body')
	.append(script);
	*/
	
	// set map
	var myLatlng = new g.LatLng(51.82249885013615, 5.792398437500008);
	var myOptions = {
		zoom: 8,
		center: myLatlng,
		
		backgroundColor:'#FFFFFF',
		disableDefaultUI:false,
		draggable:true,
		keyboardShortcuts:true,
		mapTypeControl:true,
		navigationControl:true,
		scaleControl:false,
		scrollwheel:true,
		mapTypeId: g.MapTypeId.ROADMAP
	}
	map = new g.Map($("#portfoliomap")[0], myOptions);
	
	// add overlay
	//overlayAdd();
	
	// add markers
	addMarkers();
}

function overlayAdd()
{	
	// wit vlak
	var ne = new g.LatLng(52.713, 6.116);
	var sw = new g.LatLng(51.607, 4.555);
	dragbounds = new g.LatLngBounds(sw,ne);
	
	// kaartje
	var ne = new g.LatLng(53.878, 8.130);
	var sw = new g.LatLng(50.380, 2.460);
	bounds = new g.LatLngBounds(sw,ne);
	
	new ProjectedOverlay(
		map,
		basehref+'gui/locations/nederland-mask.gif',
		bounds,
		{
			percentOpacity:1 //misschien later?
		}
	);
	
}

function addMarkers()
{			
	// Add markers to the map
	var image = new g.MarkerImage(basehref+'gui/locations/location.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new g.Size(32, 32),
		// The origin for this image is 0,0.
		new g.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new g.Point(0, 32));
		
	var shadow = new g.MarkerImage(basehref+'gui/locations/location-shadow.png',
		// The shadow image is larger in the horizontal dimension
		// while the position and offset are the same as for the main image.
		new g.Size(64, 32),
		new g.Point(0,0),
		new g.Point(-2, 32));
		// Shapes define the clickable region of the icon.
		// The type defines an HTML <area> element 'poly' which
		// traces out a polygon as a series of X,Y points. The final
		// coordinate closes the poly by connecting to the first
		// coordinate.
	var shape = {
		coord: [
			 0,11, 
			 8,22,
			 8,31,
			11,31,
			11,18,
			32, 8,
			24, 0
		],
		type: 'poly'
	};
	
	//  Create a new viewpoint bound
	locbounds = new g.LatLngBounds();
	
	for(var i=0;i<portfolio.length;i++){
		
		var theProj = portfolio[i];
		var latLng = new g.LatLng(theProj['coordinates']['latitude'],theProj['coordinates']['longitude']);
		
		//  And increase the bounds to take this point
		locbounds.extend (latLng);
								
		//wc(theProj['city']);
		
		var markerOptions = {
			map: map,
			clickable: true,
			shadow: shadow,
			//address:theProj['aAddress'],
			//projimg:theProj['oImage'],
			//iPortfolio:i,
			icon: image,
			id: theProj['id'],
			shape: shape,
			title: theProj['address'],
			position: latLng
		};
		var marker = new g.Marker(markerOptions);
		markers.push (marker);
		
		// marker mouseover event
		g.event.addListener(marker,'mouseover', function() {
			loadInfoPanel(this);
		});
		// marker click event
		g.event.addListener(marker,'click', function() {
			location.href = basehref+'detail/id/'+ this.id +'.html';
		});
		
	}
	
	// map move event: Add a move listener to restrict the bounds range
	//g.event.addListener(map, "drag", function() {
	//	checkBounds();
	//});
	
	//  Fit these bounds to the map
	if( portfolio.length == 1){
		map.setZoom( maxzoom );
		map.setCenter( latLng );
	} else {
		map.fitBounds(locbounds);
	}
	
	// load an infopanel
	loadInfoPanel(markers[0]);
}

 // If the map position is out of range, move it back
function checkBounds() {
	
	wc(map.getCenter());
	
	// Perform the check and return if OK
	if (dragbounds.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 = dragbounds.getNorthEast().lng();
	var AmaxY = dragbounds.getNorthEast().lat();
	var AminX = dragbounds.getSouthWest().lng();
	var AminY = dragbounds.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));
}

openInfoWindow = function(marker) {

	var string = marker.getTitle();
	
	var boxHtml = '<h2 style="height:10px;">'+string+'</h2>';
	
	infoWindow.setContent(boxHtml);
	infoWindow.open(map, marker);
};

closeInfoWindow = function() {
	//infoWindow.close();
	infopane.hide();
};

loadInfoPanel = function(marker) {
	
	$.ajax({
		
		url: basehref + 'xhr.html',
		global: false,
		type: "POST",
		data: ({
			req	: 'mapinfo',
			id	: marker.id
		}),
		dataType: "html",
		async:true,
		success: function(data){
			$(infopane).html(data);
		}
   });
   
}
				
				
function spawnMap(id,location,zoom){
	
	var gmap = google.maps;
	
	var myLatlng = location; 
	var myOptions = { 
		zoom: zoom, 
		center: myLatlng, 
		disableDefaultUI: true,
		mapTypeControl: false,
		scaleControl: false,
		navigationControl: false,
		//navigationControlOptions: {
		//	style: gmap.NavigationControlStyle.SMALL
		//},
		mapTypeId: gmap.MapTypeId.ROADMAP 
	} 
	var newmap = new gmap.Map($('#'+id)[0],myOptions);
	
	var marker = new gmap.Marker({
		map: newmap, 
		position: location
	});
	
	// addListeners
	gmap.event.addListener(newmap, "tilesloaded", function() {
		//gmap.event.clearListeners(newmap,'tilesloaded');
	});
	gmap.event.addListener(newmap, "drag", function() {
		//$('#' + id + ' > div > div:eq(1)')
		//.hide()
	});
	gmap.event.addListener(newmap, "dragend", function() {
	});
	gmap.event.addListener(newmap, "bounds_changed", function() {
	});
	
	// Create the DIV to hold the control and
	// call the HomeControl() constructor passing
	// in this DIV.
	var zoomControlDiv = $('<div/>');
	var zoomControl = new ZoomControl(zoomControlDiv, newmap);
	
	// zoomcontrols in map
	newmap.controls[gmap.ControlPosition.TOP_LEFT].push( $(zoomControlDiv)[0] );
	
	function ZoomControl(controlDiv, map) {
		
		// Style control holder
		$(controlDiv)
		.css({
			'z-index':1,
			'padding': '0px'
		});
		
		// Set control holder
		var controlUI = $('<div/>')
		.addClass('zoomui')
		.appendTo(controlDiv);
		
		// Zoom in
		var zoomIn = $('<a/>')
		.click(function() {
			map.setZoom( (map.getZoom()) + 1);
		})
		.attr('title','Zoom in')
		.addClass('mapzoom zoomin')
		.html('<b>+</b>')
		.appendTo(controlUI);
		
		// Zoom out
		var zoomOut = $('<a/>')
		.click(function() {
			map.setZoom( (map.getZoom()) - 1);
		})
		.attr('title','Zoom out')
		.addClass('mapzoom zoomout')
		.html('<b>-</b>')
		.appendTo(controlUI);
		
	}

		
}
