var map, cloud, bgcolor;
var counter = 0;
var WorldBounds;
var tiles = [];
var markers = [];

var infoBoxed;
var mapInfoBoxID = 'mapInfoBox';
var mapInfoBoxContent =false;
var activeDestData = [];
var centerMapLatLng = false;

var centerWorldLat = 34;
var centerWorldLng = 10;

var zoommax = 7;
var zoommin = 2;

var markerImage = 'markerImage.png';
var markerImageInact = 'markerImageBlue.png';
var markerImageBig = 'markerImageBig.gif';


// init & start
$(function() {
	// google maps as mainvisual
	initMap('#mainvisual.map');
});


/*
	functions
*/
function initMap(mapholder) {
	
	if( $(mapholder).length ){
		
		// set vars
		bgcolor = $(mapholder).css('background-color');
		
		markerImage = basehref + 'gui/maps/' + markerImage;
		markerImageInact = basehref + 'gui/maps/' + markerImageInact;
		markerImageBig = basehref + 'gui/maps/' + markerImageBig;
		
		// remove image from div
		$('img',$(mapholder)).remove();
		
		// get the active destination data (kan vast makkelijker (geen loop) als er een id is ge-embed...)
		if(locationID){
			for (var i = 0; i < locations.length; i++) {
			
				var locData = locations[i];
				wc(locData.port);
				
				if(locData.id == locationID){
					activeDestData = locData;
					wc('active center: ' + locData.lat+','+locData.lng);
					centerMapLatLng = new google.maps.LatLng(locData.lat, locData.lng);
				}
			}
		} 
		
		// geen active center, dus: world center
		if(centerMapLatLng == false){
			wc('world center: ' + centerWorldLat+','+centerWorldLng);
			centerMapLatLng = new google.maps.LatLng(centerWorldLat, centerWorldLng)
		}
		
		var dytmapstyle = [ { featureType: "water", stylers: [ { visibility: "on" }, { hue: "#007fff" }, { lightness: 1 }, { gamma: 0.47 }, { saturation: -70 } ] },{ featureType: "landscape.natural", elementType: "geometry", stylers: [ { visibility: "on" }, { gamma: 0.96 }, { lightness: -32 }, { saturation: 2 }, { hue: "#0077ff" } ] },{ featureType: "landscape.man_made", stylers: [ { visibility: "off" } ] },{ featureType: "poi.park", elementType: "geometry", stylers: [ { visibility: "off" } ] },{ featureType: "poi", elementType: "geometry", stylers: [ { visibility: "off" } ] },{ featureType: "road", stylers: [ { visibility: "off" } ] },{ featureType: "administrative.country", elementType: "labels", stylers: [ { hue: "#0011ff" }, { saturation: -47 }, { lightness: -1 }, { gamma: 1.62 }, { visibility: "on" } ] },{ featureType: "landscape.natural", elementType: "geometry", stylers: [ { visibility: "off" } ] },{ } ];
		
		var options = {
			zoom: locationID ? zoommax : zoommin,
			scrollwheel:false,
			sensor: 'true',
			noClear:true,
			center: centerMapLatLng,
			backgroundColor:bgcolor,
			disableDefaultUI:true,
			styles: dytmapstyle,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		
		// create map
		map = new google.maps.Map($(mapholder)[0], options);
		
		// add markers to map
		for (var i = 0; i < locations.length; i++) {
			makeMarker(locations[i]);
		}
		
		// bind listeners
		/*
		google.maps.event.addListener(map, "tilesloaded", function() {
			// css classes adden
			var tilesLayer = $(mapholder + ' div:first div:first > div:nth-child(8)').addClass('tiles');
			//  bugje? ALLE divs zijn nu ".notiles"....
			//$(mapholder + ' div:first div:first div[class!=tiles]').addClass('notiles');
			// define tiles
			tiles = $('div div img',$(tilesLayer));
			intercept();
		});
		google.maps.event.addListener(map, "zoom_changed", function() {
			
			wc('new zoomlevel: ' + map.getZoom() );
			
			if( !$('#page.ie6').length ){
				$(tiles).hide();//.css('display','none');
			}
			intercept();
			
		});
		google.maps.event.addListener(map, "click", function() {
			clickeventMap();
		});
		google.maps.event.addListener(map, "drag", function() {
			intercept();
		});
		google.maps.event.addListener(map, "dragend", function() {
			intercept();
		});
		google.maps.event.addListener(map, "dragstart", function() {
			intercept();
		});
		google.maps.event.addListener(map, "idle", function() {
		
			//intercept();
			animateInfoBox();

		});
		*/
		google.maps.event.addListener(map, "tilesloaded", function() {
			//
		});
		google.maps.event.addListener(map, "zoom_changed", function() {
			wc('new zoomlevel: ' + map.getZoom() );
		});
		google.maps.event.addListener(map, "click", function() {
			clickeventMap();
		});
		google.maps.event.addListener(map, "drag", function() {
			//
		});
		google.maps.event.addListener(map, "dragend", function() {
			//
		});
		google.maps.event.addListener(map, "dragstart", function() {
			//
		});
		google.maps.event.addListener(map, "idle", function() {
			animateInfoBox();
		});
		
		// centermap
		//centerMap(centerMapLatLng);
		//ColorOverlay();
	}
}
			
function animateInfoBox(){
	
	//infoBoxed.load(function(){
	
	//if('a' == 'b'){
	
		if( !$('#'+mapInfoBoxID).hasClass('animate').length ){
			
			if(!mapInfoBoxContent){
				
				mapInfoBoxContent = $('<div/>');
				
				var pageContent = $('img',$('#pagecontent'));
				
				$(pageContent)
				.appendTo(mapInfoBoxContent)
				.wrap(function(){
					
					var src =$(this).attr('src').replace('/thumb/','/full/');
					
					var anch = $('<a/>')
					.attr('rel','slide')
					.attr('href',src)
					.fancybox(fancySettings);
					//.click(function(){
					//	alert('oh HI!');
					//});
					
					return anch;
				});
				
				mapInfoBoxContent
				.cycle({
					timeout:       4000,  // milliseconds between slide transitions (0 to disable auto advance) 
					speed:         1000,  // speed of the transition (any valid fx speed value) 
					next:          null,  // id of element to use as click trigger for next slide 
					prev:          null,  // id of element to use as click trigger for previous slide 
					before:        null,  // transition callback (scope set to element to be shown) 
					after:         null,  // transition callback (scope set to element that was shown) 
					height:       'auto', // container height 
					sync:          1,     // true if in/out transitions should occur simultaneously 
					fit:           0,     // force slides to fit container 
					pause:         0,     // true to enable "pause on hover" 
					delay:         -2000,     // additional delay (in ms) for first transition (hint: can be negative) 
					slideExpr:     null   // expression for selecting slides (if something other than all children is required) 
				});
				
				wc('mapInfoBoxContent loaded from DOM');
				
			} else {
				wc('mapInfoBoxContent loaded from var');
				//wc(mapInfoBoxContent);
			}
			
			$('#'+mapInfoBoxID)
			.addClass('animate')
			.append(mapInfoBoxContent);
			
		} else {
			
			alert('er is animate');
		}
	
	//}
	//});
}

function intercept(){
	
	if( $('#page.ie6').length ){
		return false;
	}
	
	var intercepturl = basehref;
	
	var i = 0;
	
	var allowed = ['mt0','mt1','mt2','mt3','mt4'];//,'khm0','khm1','khm2','khm3','khm4'
	
	//$("img[src*='google.com']",$('div div:has(img)',$(mapholder + ' div div:first div:has(div)')))
	$(tiles)
	.filter(function(){
		
		var src = $(this).attr('src');
		
		for(var i in allowed ){
			if( src.indexOf(allowed[i]+'.google') > 1 ){
				return true;
				break;
			}
		}
		return false;
	})
	
	.each(function(){
		
		var img = $(this);
		var src = $(this).attr('src');
		
		if(base_domain){
			/* wildcards moeten wel zijn ingesteld in DNS... */
			//intercepturl = 'http://map'+ i + '.' + base_domain + base_dir;
			intercepturl = 'http://www' + '.' + base_domain + base_dir;
		}	
		
		/*
		$.ajax({
			type: "POST",
			url: intercepturl + "tiles.php?callback=?",
			dataType: "jsonp",
			jsonp:'callback',
			data:({
				src:src
			}),
			cache: 'jsonp',
			complete:function (XMLHttpRequest, textStatus) {
								
				wc(callback);	
				
				$(img)
				.attr('src',callback.tile)
				.show();
			}
		});
		*/
		
		var component = encodeURIComponent(src);
		
		$.getJSON(intercepturl + "tiles.php?src=" + component + "&format=json&callback=?",
        function(data){
			
			$(img)
			.attr('src',data.tile)
			.show();
			
        });
		
		i++;
		
	});
}

function clickeventMap(){
	
	var zoomlevel = map.getZoom();
	
	wc('zoomlevel on fire: ' + zoomlevel );
	
	if(zoomlevel == zoommin){
		
		/*
		var LatLng = mouseCoords2LatLng();
		
		wc('center on click coordinates now');
		centerMap(LatLng);
		
		wc('zoom in to: ' + zoommax);
		map.setZoom(zoommax);
		*/
	}
	
	if(zoomlevel == zoommax){
		
		if (infoBoxed) infoBoxed.close();
		
		wc('zoom out to: ' + zoommin);
		
		wc('we could center the map here?....');
		//centerMap();
		
		map.setZoom(zoommin);
	}
	
	
}

function activateDestination(marker,location){
	
	var zoomlevel = map.getZoom();
	
	wc('zoomlevel on fire: ' + zoomlevel );
	
	if(zoomlevel == zoommin){
		
		wc(location.page);
		this.location.href = location.page;
		
	}
	
	if(zoomlevel == zoommax){
		
		makeInfoBox(marker);
		//infoBoxed.open(map,marker);
		//animateInfoBox();
		
		if(activeDestData.id != location.id){
		
			if (infoBoxed) infoBoxed.close();
			
			wc(location.page);
			this.location.href = location.page;
		} 
		
		
	}
	
}

function ColorOverlay(){
	
	var position1 = new google.maps.LatLng(86,-179.99);
	var position2 = new google.maps.LatLng(-86,180);
	
	WorldBounds = new google.maps.LatLngBounds(position1,position2);

	var rectangle = new google.maps.Rectangle({
	  fillColor:bgcolor,
	  fillOpacity:0.7,
	  strokeWeight:0,
	  map: map
	});
	
	rectangle.setBounds(WorldBounds);
}

function centerMap(latLng) {
	
	if(latLng){
		map.setCenter(latLng);
	} else {
		var LatLng = new google.maps.LatLng(centerWorldLat,centerWorldLng);
		map.setCenter(LatLng);
	}
}

function makeMarker(location) {

	var LatLng = new google.maps.LatLng(location.lat, location.lng);
	
	var image = (locationID == location.id) ? markerImageBig : markerImage;
	
	if(activeArea && activeArea != location.area){
		image = markerImageInact;
	}
	
	var markerOptions = {
		map: map,
		title: location.name + ', ' + location.country,
		clickable: true,
		icon: image,
		position: LatLng
	};
	var marker = new google.maps.Marker(markerOptions);
	google.maps.event.addListener(marker, 'click', function() {
		activateDestination(marker,location);
	});
	markers.push(marker);
	
	if(locationID == location.id){
		
		var pageContent = $('img',$('#pagecontent'));
		
		if( pageContent.length ){
			//map.setCenter(LatLng);
			makeInfoBox(marker);
		}
	}
}

function makeInfoBox(marker){
	
	//wc(marker);
	
	if (infoBoxed) infoBoxed.close();
		
	var boxHtml = '<div id="'+mapInfoBoxID+'"></div>';
	
	var myOptions = {
		content: boxHtml,
		disableAutoPan: false,
		maxWidth: 0,
		pixelOffset: new google.maps.Size(-276, -168),
		zIndex: 2,
		boxStyle: { 
			background: "url('"+basehref+"gui/maps/balloon.png') no-repeat",
			opacity: 0.95,
			width: "282px",
			height: "162px"
		},
		closeBoxMargin: "6px 5px 2px 2px",
		closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
		infoBoxClearance: new google.maps.Size(1, 1),
		isHidden: false,
		pane: "floatPane",
		enableEventPropagation: false
	};

	infoBoxed = new InfoBox(myOptions);
	
	infoBoxed.open(map,marker);
	
	// The position of marker
	var center = marker.getPosition();
	
	// The new map center
	var centerX = center.lng();
	var centerY = center.lat()+0.2;
	
	// center the map to the new shifted center
	map.setCenter(new google.maps.LatLng(centerY, centerX));
	
	// shift again to force idle (animate infobox)
	centerMap(new google.maps.LatLng(centerY-0.01, centerX));
	
}

