/*--------------------------------------+
 +
 +	  Solid. http://madebysolid.com/
 +	  fjenett - 2009-2011
 +    technik@opendoors-frankfurt.de
 +
 +--------------------------------------*/

var od2011_map = null;
var od2011_marker = null;
var od2011_infoBox = null;
var od2011_center = null;
var od2011_markerLoaded = false;

var od2011_contentBox = null;
var od2011_contentNav = null;
var od2011_contentBody = null;

var od2011_kulturamtCenter = null;

var od2011_currentView = false;

var od2011_colorsByType = {
	basis: "#360186", // 2f2782
	stadt: "#ee0013", // e54421
	atelierfrankfurt: "#009fe8", // 0091d5
	privat: "#00a034",  // 009948
	grey: '#aaaaaa',
	all: '#ffffff'
};

function initOpenDoorsMap () {
    
    if ( od2011_map ) return od2011_map;
	
	var minZoom = 13;
	var maxZoom = 17;
    
	od2011_center = new google.maps.LatLng( 50.11645771146896, 8.702493724975637 );
	od2011_kulturamtCenter = new google.maps.LatLng( 50.106749550526544, 8.68719976917272 ); // Brückenstraße
    
    var il_disegno = new google.maps.ImageMapType({
            getTileUrl: function(coord, zoom) {
                return "http://opendoors-frankfurt.de/2011/tiles/" +
                       zoom + "/" + coord.x + "_" + coord.y + ".png";
            },
            tileSize: new google.maps.Size(256, 256),
            isPng: true,
    		maxZoom: maxZoom,
    		name: "IL_DISEGNO",
    		alt: "Map"
        });
    
    var mapOptions = {
        zoom: minZoom + 1,
        center: od2011_center,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        /* google.maps.MapTypeId.SATELLITE */
        mapTypeControl: false, /* hide map type control */
        navigationControl: true,
        navigationControlOptions: {
            position: google.maps.ControlPosition.TOP_LEFT,
            style: google.maps.NavigationControlStyle.SMALL
        },
        scaleControl: false,
		streetViewControl: false,
        backgroundColor: '#ffffff'
    };
    
    var map_element = $("#open-doors-map");
    
    od2011_map = new google.maps.Map( map_element.get(0), mapOptions);
	
	od2011_map.mapTypes.set( 'IL_DISEGNO', il_disegno );
	od2011_map.setMapTypeId( 'IL_DISEGNO' );
            
    google.maps.event.addListener( od2011_map, 'zoom_changed', function() {
        if ( od2011_map.getZoom() < minZoom) {
            od2011_map.setZoom( minZoom );
        } else if ( od2011_map.getZoom() > maxZoom ) {
            od2011_map.setZoom( maxZoom );
        }
		if ( od2011_map.getZoom() < 15 ) {
			for ( var i in od2011_marker ) {
				od2011_marker[i].setOptions({fillOpacity:0.0});
			}
		} else {
			for ( var i in od2011_marker ) {
				od2011_marker[i].setOptions({fillOpacity:1.0});
			}
		}
    });

	// google.maps.event.addListener( od2011_map, 'center_changed', function () {
	// 	console.log( od2011_map.getCenter() );
	// });

	var contentBox = $('<div class="map-content-overlay"></div>');
	od2011_map.controls[ google.maps.ControlPosition.TOP_RIGHT ].push( contentBox.get(0) );
	
	var mapNav = $('<div id="map-navigation">'+
	'<ul>'+
	'<li><a href="" class="info">Information</a></li>'+
	'<li><a href="" class="programm">Programm</a></li>'+
	'<li><a href="" class="artists">Teilnehmer</a></li>'+
	'<li><a href="" class="contact">Kontakt</a></li>'+
	'<li><a href="" class="facebook">Facebook</a></li>'+
	'</ul>'+
	'</div>');
	contentBox.append(mapNav);
	
	$('a.info', mapNav).bind('click',function(){
		resetActiveMapControls();
		$(this).addClass('active');
		showInfoBox( '/2011/embedded.php?step=information-short', od2011_center.lat(), od2011_center.lng(), 'all' );
		for ( var i in od2011_marker ) {
			od2011_marker[i].setOptions({fillOpacity:0.0});
		}
		od2011_map.setZoom( minZoom+1 );
		//od2011_map.setMapTypeId( 'IL_DISEGNO' );
		return false;
	}, false);

	$('a.programm', mapNav).bind('click',function(){
		resetActiveMapControls();
		$(this).addClass('active');
		showInfoBox( '/2011/embedded.php?step=programm', od2011_center.lat(), od2011_center.lng(), 'all' );
		return false;
	});

	$('a.artists', mapNav).bind('click',function(){
		resetActiveMapControls();
		$(this).addClass('active');
		showInfoBox( '/2011/embedded.php?step=teilnehmer', od2011_center.lat(), od2011_center.lng(), 'all' );
		return false;
	});

	$('a.view-toggle', mapNav).bind('click',function(){
		//toggleMapView(this);
		return false;
	});

	$('a.contact', mapNav).bind('click',function(){
		resetActiveMapControls();
		$(this).addClass('active');
		showInfoBox( '/2011/embedded.php?step=kontakt', od2011_kulturamtCenter.lat(), od2011_kulturamtCenter.lng(), 'all' );
		return false;
	});
	
	$('a.facebook', mapNav).bind('click',function(){
		resetActiveMapControls();
		$(this).addClass('active');
		showInfoBox( '/2011/embedded.php?step=facebook', null, null, 'all' );
		return false;
	});
	
	var mapContent = $('<div id="map-content"></div>');
	contentBox.append(mapContent);
	
	od2011_contentBox = contentBox;
	od2011_contentNav = mapNav;
	od2011_contentBody = mapContent;
    
    // var markerIconGrey = new google.maps.MarkerImage( '/2011/img/marker-grey.png' );
    // var markerIconBlack = new google.maps.MarkerImage( '/2011/img/marker-black.png' );
    // var markerIconRed = new google.maps.MarkerImage( '/2011/img/marker-red.png' );
    // var markerIconGreen = new google.maps.MarkerImage( '/2011/img/marker-green.png' );
    // var markerIconBlue = new google.maps.MarkerImage( '/2011/img/marker-blue.png' );
    // var markerIconLila = new google.maps.MarkerImage( '/2011/img/marker-lila.png' );
    
	od2011_marker = [];
	
    $.ajax({
        url: '/2011/marker2.php',
        data: null,
        success: function ( results ) {
            for ( var i in results ) {
				
				// var icon = markerIconGrey;
				// if ( results[i].type == 'basis' )
				// 	icon = markerIconLila;
				// else if ( results[i].type == 'atelierfrankfurt' )
				// 	icon = markerIconBlue;
				// else if (results[i].type == 'stadt' )
				// 	icon = markerIconRed;
				// else if ( results[i].status > 1 )
				// 	icon = markerIconGreen;
				
				var marker = new google.maps.Circle({
                    center: new google.maps.LatLng( results[i].lat, results[i].lng ),
					radius: 50,
					clickable: true,
					fillColor: od2011_colorsByType[results[i].type.replace('private','privat')],
					fillOpacity: 1.0,
					strokeWeight: 0,
					strokeColor: '#ffffff',
					strokeOpacity: 0,
                    map: od2011_map
                });
				google.maps.event.addListener( marker, 'mouseover', function () {
					if ( this.fillOpacity > 0 )
						this.setOptions({fillOpacity:0.5});
				});
				google.maps.event.addListener( marker, 'mouseout', function () {
					this.setOptions({fillOpacity:(od2011_map.getZoom() >= 15 ? 1.0 : 0.0)});
				});
				marker.data = results[i];
				
				attachClickEventToMarker( marker, results[i] );
				
				marker.setOptions({fillOpacity:0.0});
				od2011_marker[marker.data.mid] = marker;
            }
			od2011_markerLoaded = true;
        },
        dataType: 'json'
    });
    
    od2011_map.controls[ google.maps.ControlPosition.BOTTOM_LEFT ].push( $('#sponsors').get(0) );
    
	var loc = window.location.href;
	var fragment = loc.match(/.+#.+/) ? loc.replace( /.+#(.+)/, '$1' ) : false;
	
	if ( loc.match(/.*#[0-9.,]+/) ) {	
		var latRaw = loc.replace( /.*#([^,]+),.*/, '$1' );
		latRaw = parseFloat( latRaw );
		var lngRaw = loc.replace( /.*#[^,]*,(.*)$/, '$1' );
		lngRaw = parseFloat( lngRaw );
		
	    setTimeout( function () {
	        if ( !isNaN(latRaw) && !isNaN(lngRaw) ) {
	            od2011_map.panTo( new google.maps.LatLng( latRaw, lngRaw ) );
				od2011_map.setZoom( 16 );
	        }
	    }, 1500 );	
	} else if ( fragment ) {
		if ( fragment == 'information' ) fragment += '-short';
		var pages = ['programm','programm-stadt', 'programm-atelierffm', 'programm-basis', 
					'programm-privat', 'kontakt', 'teilnehmer', 'information-short']
		for ( var l in pages ) {
			if ( fragment == pages[l] ) {
				setTimeout( function () {
					showInfoBox( '/2011/embedded.php?step='+pages[l], null, null, '' );
			    }, 1500 );
				break;
			}
		}
	} else {
		setTimeout( function () {
			$('a.info', mapNav).click();
		}, 100 );
	}
	
	//panToAddress( 'basis, Gutleutstraße 8-12, Frankfurt' );
    
    return od2011_map;
}

function panToAddress ( adr ) {
	(new google.maps.Geocoder()).geocode(
		{
			address: adr,
			region: 'de'
		},
		function ( gcResult ) {
			if ( !gcResult || gcResult.length < 1 ) return false;
			if ( gcResult[0] && gcResult[0]['geometry'] && gcResult[0]['geometry'].location ) {
				od2011_map.panTo( gcResult[0]['geometry'].location );
				od2011_map.setZoom(17);
				//toggleMapView($('a.view-toggle'),'street');
			}
			return false;
		}
	);
}

function toggleMapView ( node, newView )
{
	if ( newView == 'studios' || (!newView && od2011_currentView) )
	{
		od2011_map.setMapTypeId( 'IL_DISEGNO' );
		for ( var i in od2011_marker )
		{
			od2011_marker[i].setOptions({fillOpacity:0.0});
		}
		od2011_currentView = false;
	}
	else
	{
		od2011_map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
		for ( var i in od2011_marker )
		{
			od2011_marker[i].setOptions({fillOpacity:1.0});
		}
		od2011_currentView = true;
	}
	
	if ( od2011_currentView ) {
		$(node).html('Ateliers');
	} else {
		$(node).html('Stadtplan');
	}
}

function attachClickEventToMarker ( marker, info )
{
	var url = "/2011/marker.php?m="+info.mid;
	
	google.maps.event.addListener( marker, 'click', function ( event ) {
		resetActiveMapControls();
		$('a.artists').addClass('active');
		showInfoBox( url, info.lat, info.lng, info.type.replace('private', 'privat') );
	});

}

function showInfoBox ( url, lat, lng, type ) {
	
	if ( !od2011_map ) return;
	
	$.ajax({
		type: "GET",
		url: url,
		success: function (result) {
			try{
				pageTracker._trackPageview( url );
			} catch ( e ) {/*ignore*/}
			var bodyContent = $(
				'<div id="close-box" style="position: absolute; right: 24px; top: 50px">'+
					'<a href="" alt="close" title="" onclick="closeInfoBox();return false"><img src="/2011/img/close.gif" /></a>'+
				'</div>'+
				result
			);
			
			od2011_contentBody.html(bodyContent);
			fixInternalLinks(od2011_contentBody);
			addAddressLinks(od2011_contentBody);
			$('.map-content-overlay').addClass('expanded');
			
			if ( lat != null && lng != null ) {
				od2011_map.panTo( new google.maps.LatLng( lat, lng ) );
			}
		}
	});
}

function fixInternalLinks ( node ) {
	
	$('a',node).each(function(i,e){
		var e = $(e);
		if ( e.attr('href').match(/^\/2011\/.*/) )
		{
			e.bind('click',function(){
				showInfoBox( e.attr('href').replace(/page\.php/, "embedded.php"), null, null, '' );
				return false;
			}, false);
		}
	});
}

function addAddressLinks ( node ) {
	
	$('span.address', node).each(function(i,e){
		var mid = $(e).attr('marker');
		if ( mid && mid.match(/[0-9]+/) ){
			//console.log( od2011_marker[mid] );
			$(e).bind('click',function(){
				od2011_map.panTo( new google.maps.LatLng( od2011_marker[mid].data.lat, od2011_marker[mid].data.lng ) );
				od2011_map.setZoom(17);
				//toggleMapView($('a.view-toggle'),'street'); // sets to opac 1.0
				od2011_marker[mid].setOptions({fillOpacity:0.5});
				showInfoBox( "/2011/embedded.php?step=marker&m="+mid, null, null, od2011_marker[mid].data.type );
				return false;
			},false);
		} else {
			var address = (e.textContent||e.innerText).replace(/[\s]*[\n\r][\s]*/, ",");
			$(e).bind('click',function(){
				panToAddress(address);
				return false;
			});
		}
		$(e).css({cursor:'pointer'});
		$(e).attr('title','Klicken Sie hier um zu diesem Ort zu gelangen.');
		$('a',e).each(function(ii,ee){
			var ee = $(ee);
			ee.attr("title","");
			ee.attr("href","");
		});
	});
}

function closeInfoBox () {
	od2011_contentBody.html("");
	//$(od2011_contentBox).css({height: 'auto'});
	$('.map-content-overlay').removeClass('expanded');
}

function resetActiveMapControls () {
	$('a',od2011_contentNav).each(function(i,e){
		$(e).removeClass('active');
	});
}

function exportMarkers () {
	closeInfoBox();
	setTimeout( exportMarkersImpl, 1000 );
}

function exportMarkersImpl () {
	if ( !od2011_markerLoaded ) {
		return setTimeout( exportMarkersImpl, 1000 );
	}
	var tileUtil = new Tile();
	var markers = [];
	for ( var m in od2011_marker ) {
		var tileCoords = tileUtil.getTileCoords( od2011_marker[m].center.lat(), od2011_marker[m].center.lng(), 17 );
		markers.push({
			tileCoords: tileCoords,
			title: od2011_marker[m].data.address,
			type: od2011_marker[m].data.type
		});
	}	
	//console.log( JSON.stringify(markers) );
}
