var interruptZoomChange = false;

var projectMapId = 'googleMap';

var muMapId = 'googleMuMap';

function changeZoom(){
	
	if(interruptZoomChange)return;
	//map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw[0],bounds.sw[1]),new google.maps.LatLng(bounds.ne[0],bounds.ne[1])));
	zoomIndex++;
	if(zoomIndex >= zoomSteps.length){
		zoomIndex = 0;
	}
	removeAllPhotos();
	if(typeof maps[projectMapId] != 'undefined'){
		maps[projectMapId].setZoom(zoomSteps[zoomIndex]);
	}
	
	// remove old markers
	
}

var zoomSteps = [9,10,13];


var mapOptions = {
      zoom: 2
	  ,scaleControl:true
	  ,mapTypeId:google.maps.MapTypeId.TERRAIN
	  ,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU}
    };

// container fo maps on this page
var maps = {};

function initGoogleMap(mapId,aShapes){
	
	var map;
	
	if(typeof maps[mapId] != 'undefined'){
		map = maps[mapId];
	}
	else map = new google.maps.Map(document.getElementById(mapId),mapOptions);
	
	
		
	var m = new google.maps.Marker(
		{
			position:new google.maps.LatLng(projectPoint[0]
			,projectPoint[1])
			,icon:projectIcon
			,title:projectTitle
		}
	);
	
	if (projectInfoWindow) {
		google.maps.event.addListener(m, 'click', function(){
			projectInfoWindow.open(map, m);
		});
	}
	m.setMap(map);
	map.setCenter(m.getPosition());
	
	if (aShapes) {
		for (unitId in aShapes) {
			if (typeof aShapes[unitId] != 'function') {
				for (shapeIndex in aShapes[unitId]) {
					if (typeof aShapes[unitId][shapeIndex] != 'function') {
						var shape = aShapes[unitId][shapeIndex];
						paths = [];
						if (typeof shape.points != 'undefined') {
							var polygon = createPolygon(shape);
							//polygon.setMap(map);
							aShapes[unitId][shapeIndex]['polygon'] = polygon;
						}
					}
				}
				var bounds = aShapes[unitId].bounds;
				if(typeof bounds != 'undefined'){
					var sw = new google.maps.LatLng(bounds.sw[0], bounds.sw[1]);
					var ne = new google.maps.LatLng(bounds.ne[0], bounds.ne[1]);
					// replace the arrays with the googleMap LatLng objects
					aShapes[unitId].bounds = new google.maps.LatLngBounds(sw,ne);
				}
			}
		}
	}	
	
	return map;
}

if(typeof projectShapes == 'undefined'){
	projectShapes = {};
}

function initProjectMap(){
	
	if(typeof document.getElementById(projectMapId) == 'undefined')return;
	
	var map =  initGoogleMap(projectMapId, projectShapes);
	
	var hasShapes = false;
	
	if (projectShapes[projectId]) {
	
		for (shapeIndex in projectShapes[projectId]) {
			if (typeof projectShapes[projectId][shapeIndex].polygon != 'undefined') {
				hasShapes = true;
				projectShapes[projectId][shapeIndex].polygon.setMap(map);
			}
		}
	}
	
	map.photoWrapper = document.getElementById('mapPhotoWrapper');
	
	google.maps.event.addListener(map, "zoom_changed",function(){
		if(map.getZoom() > 5) {
			removeAllPhotos();
		}
	});
	
	google.maps.event.addListener(map, 'idle', function() {
	   if (map.getZoom() > 5) {
	   	window.setTimeout('loadPhotos()', 1500);
	   }
	});
	google.maps.event.addListener(map, 'mouseover', function() {
	    interruptZoomChange = true;
	});
	google.maps.event.addListener(map, 'mouseout', function() {
	    interruptZoomChange = false;
	});
	
	if (hasShapes) {
		if (projectShapes[projectId].bounds) {
			map.fitBounds(projectShapes[projectId].bounds);
		}
	}
		
	maps[projectMapId] = map;
	
	window.setInterval('changeZoom()',7000);
}

var aUnitShapes;


function initMuMap(){
	if(typeof maps[muMapId] == 'undefined'){
		mapOptions.zoom  = 11;
		mapOptions.mapTypeId = google.maps.MapTypeId.SATELLITE;
		var map = initGoogleMap(muMapId,aUnitShapes);
		maps[muMapId] = map;
	}

	for(shapeIndex in projectShapes[projectId]){
		if(typeof projectShapes[projectId][shapeIndex].polygon != 'undefined'){
			var projectPolygon = $.extend(true, {},projectShapes[projectId][shapeIndex].polygon);
			projectPolygon.setMap(maps[muMapId]);
		}
	}
	/**
	var overlayMap = new google.maps.Map(document.getElementById('overlayMap'), {        
		mapTypeId: google.maps.MapTypeId.TERRAIN,  // Always show roadmap        
		disableDefaultUI: true  // Turn off the controls      
	});    // Set up zoom_changed listeners so that overlayMap's zoom changes to be 4    
	// less than map's and map's 4 greater than overlayMap's.    
	google.maps.event.addListener(map , 'zoom_changed', function() {      
		var newZoom = Math.max(map.getZoom() - 5, 0);      
		if (overlayMap.getZoom() != newZoom) overlayMap.setZoom(newZoom);    
	});    
	
	google.maps.event.addListener(overlayMap, 'zoom_changed', function() {      
		var newZoom = overlayMap.getZoom() + 5;      
		if (map.getZoom() != newZoom) map.setZoom(newZoom);
	});    
	
	// overlayMap's center stays in sync with map's center    
	
	overlayMap.bindTo('center', map, 'center');    // Set map's properties now that all bindings and listeners are set up.    
	
	//map.set_zoom(8);  // This will trigger a zoom_changed on the map    
	//map.set_center(new google.maps.LatLng(-34.397, 150.644));    
	//map.set_mapTypeId(google.maps.MapTypeId.ROADMAP); 
	*/
}

function createPolygon(shapeData){
	if (typeof shapeData.points != 'undefined') {
		var paths = [];
		for (i = 0; i < shapeData.points.length; i++) {
			var point = shapeData['points'][i];
			paths.push(new google.maps.LatLng(point[0], point[1]));
		}
		if(typeof shapeData.strokeColor == 'undefined'){
			shapeData.strokeColor = shapeData.color;
		}
		var polygon = new google.maps.Polygon({
			paths: paths,
			strokeColor: shapeData.strokeColor,
			fillColor: shapeData.color,
			strokeOpacity: 0.8,
			strokeWeight: 1,
			fillOpacity: 0.35
		});
		return polygon;
	}
	return false;
}



function debug(m){
	if(typeof console != 'undefined'){
		console.log(m);
	}
}

var allPhotos = {};

function addPhotos(data) {
	var new_markers = {};
	for (var i = 0; i < data.photos.length; i++) {
		var photo = data.photos[i];

		// for speed and to reduce flicker,
		// reuse existing markers rather than removing and 
		if (photo.photo_id in markers) {
			new_markers[photo.photo_id] = markers[photo.photo_id];
		} else {
			// create new marker
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(photo.latitude, photo.longitude)
				,icon: new google.maps.MarkerImage(photo.photo_file_url,new google.maps.Size(18,18))
				,map: maps[projectMapId]
			});
			marker.photoId = photo.photo_id;
			marker.setTitle(photo.photo_title);
			allPhotos[photo.photo_id] = photo.photo_file_url.replace('mini_square','medium');

			addEventHelper(marker,'<span class="mapImageWrapper"><img src="' +  allPhotos[marker.photoId] + '" /><a href="http://www.panoramio.com/photo/' + marker.photoId + '" target="_blank" title="Show image on panoramio.com"><img id="panoramioLogo" src="/img/iw_panoramio.png" /></a></span>');
			new_markers[photo.photo_id] = marker;
		}
	}

	// remove old markers
	for (var photo_id in markers) {
		if (typeof new_markers[photo_id] != 'undefined') {
			markers[photo_id].setMap(null);
			delete markers[photo_id];
		}
	}

	markers = new_markers;
}

function removeAllPhotos(){
	for (var photo_id in markers) {
		markers[photo_id].setMap(null);
	}
}

/**
 * this function is a bugfix, without it, all markers show the same picture
 * @param {Object} marker
 * @param {Object} photo
 */
function addEventHelper(marker,photo){
	google.maps.event.addListener(marker, 'click', function(event){

		var leftMargin = '0px';
		/**
		if(marker.getPosition().lng() < map.getCenter().lng()){
			leftMargin = '298px';
			
			debug('Leftt');
			$('#mapPhotoWrapper').css('text-align','right'); 
		}
		else {
			$('#mapPhotoWrapper').css('text-align','left'); 
			//$('#mapPhotoWrapper').css('width',$('#googleMap').css('width'));
			//$('#mapPhotoWrapper').css('overflow','hidden');
		}
		*/
		maps[projectMapId].photoWrapper.innerHTML =photo;
		//debug(marker.photoId);
		$('#mapPhotoWrapper').show();
		//$('#panoramioLogo').css('left',leftMargin);
	});
	google.maps.event.addListener(marker, 'mouseout', function(){
		//map.photoWrapper.innerHTML ='';
		$('#mapPhotoWrapper').hide();
	});
}

function loadPhotos() {
    var url = 'http://www.panoramio.com/map/get_panoramas.php?order=popularity&amp;set=public&amp;from=0&amp;to=20&amp;size=mini_square&amp;callback=addPhotos';
    var bounds = maps[projectMapId].getBounds();
    url += '&amp;minx=' + bounds.getSouthWest().lng().toFixed(6) + '&amp;miny=' + bounds.getSouthWest().lat().toFixed(6);
    url += '&amp;maxx=' + bounds.getNorthEast().lng().toFixed(6) + '&amp;maxy=' + bounds.getNorthEast().lat().toFixed(6);
    url += '&amp;ts=' + new Date().getTime(); // prevent caching

    // use JSONP to retrieve photo data
    // and trigger a callback to addPhotos()
    var script = document.createElement("script");
    script.setAttribute("src", url);
    script.setAttribute("type","text/javascript");
    document.body.appendChild(script);
}



