$(document).ready(function(){
	var isawardshow = false;
	var markers = new Array();
	var winners = new Array();
	var tip = $('#map-tooltip');
	var tipcontent = $('#map-tooltip-content');
	var dataloaded = false;
	var maploaded = false;
	// custom style for the map
	var myLatlng = new google.maps.LatLng(47,8);
	var zoomlevel = 8;
	var smapStyles = [
      {
        featureType: "road",
        elementType: "all",
        stylers: [
          { hue: "#a08d5c" },
          { saturation: 100 },
          { visibility: 'on' },
          { lightness: -70 }
        ]
      },{
        featureType: "poi",
        elementType: "all",
        stylers: [
          { visibility: 'off' }
        ]
      },{
        featureType: "administrative",
        elementType: "all",
        stylers: [
          { visibility: 'off' }
        ]
      },{
        featureType: "administrative.country",
        elementType: "geometry",
        stylers: [
          { hue: "#a08d5c" },
          { saturation: 100 },
          { lightness: 20 },
          { gamma: 1 },
          { visibility: 'simplified' },
          { invert_lightness: true }
        ]
      },{
        featureType: "water",
        elementType: "geometry",
        stylers: [
          { saturation: -40 },
          { lightness: -40 }
        ]
      },{
        featureType: "all",
        elementType: "labels",
        stylers: [
          { visibility: 'off' }
        ]
      },{
        featureType: "administrative",
        elementType: "labels",
        stylers: [
          { hue: "#a08d5c" },
          { saturation: 100 },
          { lightness: 0 },
          { gamma: 1 },
          { invert_lightness: true },
          { visibility: 'on' }
        ]
      },{
        featureType: "landscape",
        elementType: "geometry",
        stylers: [
          { hue: "#a08d5c" },
          { saturation: 50 },
          { lightness: -100 },
          { gamma: 10 },
          { visibility: "on" },
        ]
      },{
        featureType: "transit",
        elementType: "all",
        stylers: [
          { visibility: "off" },
        ]
      }
    ];
    var styledMapOptions = {
    	name: "Stammplatz Map",
    	minZoom: 7
  	}
	var smapType = new google.maps.StyledMapType(smapStyles, styledMapOptions);
	var map;
	var fluster;
	var overlayhelper;
  	
	
	// set up shadowbox
	Shadowbox.init({
    	// let's skip the automatic setup because we don't have any
    	// properly configured link elements on the page
    	skipSetup: true,
		overlayOpacity: 0.9,
		animate: true,
		overlayColor: '#000',
		displayNav: false,
		initialHeight: 400,
		initialWidth: 600,
		viewportPadding: 50,
		handleOversize: 'resize'
	});
	
	// setup icons
	var image = new google.maps.MarkerImage('fileadmin/templates/images/chairicon2.png',
      // This marker is 19 pixels wide by 32 pixels tall.
      new google.maps.Size(26, 26),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image 
      new google.maps.Point(13, 13));
  	var shadow = new google.maps.MarkerImage('fileadmin/templates/images/chairshadow2.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(40, 26),
      new google.maps.Point(0,0),
      new google.maps.Point(13, 13));
	
	// show winners
	function showWinners() {
		// sort winners by rank
		if (isawardshow) {
			// ascending
			winners.sort(function(a,b) { return $(b).data('markerdata').rank - $(a).data('markerdata').rank; });
		} else {
			// descending
			winners.sort(function(a,b) { return $(a).data('markerdata').rank - $(b).data('markerdata').rank; });		
		}
		// show winners of each category
		var winnercontent = '<div id="winnercontent">';
		winnercontent += showWinnersCat('2','Film') + showWinnersCat('0','Text') + showWinnersCat('1','Foto') + showWinnersCat('3','Musik');
		winnercontent += '</div>';
		$('#content-right').html('<div id="winners"><a href="#" id="winnertitle">'+titlewinners+'</a>'+winnercontent+'</div>');
		// toggle winners
		$('#winnertitle').click(function() {
			$(this).toggleClass('open');
			$('#winnercontent').slideToggle(200);
		});
		$('#winnertitle').toggleClass('open');
		$('#winnercontent').slideToggle(200);
		
		// add click handler to all links
		$('#winners a').click(function() {
			var success = gotoWinnerFromId($(this).attr('class'));
			return false;
		});
		
		if (isawardshow) {
			awardShow();
		}
	}
	function awardShow() {
		// add button
		$('#content-right').append('<a id="awardnext" class="haha">Enth&uuml;llen!</a>');
		// show winner panel 
		$('#winnertitle').toggleClass('open');
		$('#winnercontent').slideToggle(200);
		// show winners one by one for award show		
		var counter = 0;
		$('#winnercontent a').hide();
		$('#awardnext').click(function() {
			$($('#winnercontent a').get(counter)).show();
			counter++;
			if (counter >= 12) {
				$(this).hide();
			}	
		});
	}
	// show winners of one category
	function showWinnersCat(cat,title) {
		var result = '<h2>'+title+'</h2>';
		for (var i=0; i<winners.length; i++) {
			var d = $(winners[i]).data('markerdata');
			if(d.cat == cat) {
				result += '<p>' + d.rank + '. <a href="#" class="'+d.uid+'" title="Beitrag anschauen">'+ d.name +'</a><br /></p>';
			}
		}
		return result;
	}
	// goto marker and open content based on marker id
	function gotoWinnerFromId(id) {
		for (var i=0; i<winners.length; i++) {
			var d = $(winners[i]).data('markerdata');
			if (d.uid == id) {
				// go to marker position on map
				map.setZoom(15);
				map.panTo(winners[i].getPosition());
				// open marker
				openMarker($(winners[i]));
				return true;
			}
		}
		return false;
	}
	
	// hide loader when map and markers are loaded
	function showMapIfReady() {
		if (dataloaded && maploaded) {
			google.maps.event.clearListeners(map, 'tilesloaded');
			$('#map_cover').animate({opacity:0},300,function() { $('#map_cover').hide(); });	
			showWinners();
		}
	}

	/**@private
	* In V3 it is quite hard to gain access to Projection and Panes.
	* This is a helper class
	* @param {google.maps.Map} map
	*/
	function ProjectionHelperOverlay(map) {
		google.maps.OverlayView.call(this);
		this.setMap(map);
	}
	ProjectionHelperOverlay.prototype = new google.maps.OverlayView();
	ProjectionHelperOverlay.prototype.draw = function () {
		if (!this.ready) {
		  this.ready = true;
		  google.maps.event.trigger(this, 'ready');
		}
	};
	
	// remove all markers
	function clearMarkers() {
		 while(markers[0]){
   			markers.pop().setMap(null);
  		}
	}
	
	// tooltips
	function showTooltip(marker) {
		pixelXY = overlayhelper.getProjection().fromLatLngToContainerPixel(marker.getPosition());
		var xpos = pixelXY.x-120;
		var ypos = pixelXY.y+13;
		
		tip.stop(true).show();
		tipcontent.stop(true).show();
		
		tipcontent.removeClass();
		if (ypos+164 > $(window).height()) {
			ypos-=191;
			tipcontent.addClass('up');
		}
		
		tip.css({
			'left':xpos + 'px',
			'top':ypos + 'px'
		});		
		/*
		if (xpos+220 > $(window).width()) {
			xpos-=250;
		}
		*/
		
		tipcontent.html($(marker).data('markerdata').content)
			.css({'height':0})
			.animate({height:136},200);
	}
	function hideTooltip() {
		var tipcontent = $('#map-tooltip-content');
		tipcontent.stop(true)
			.animate({height:0},200, function() {
				tip.hide();
				tipcontent.hide();
			});
	}
	
	// create marker
	function createMarker(data) {
		var markerLatlng = new google.maps.LatLng(data.lat,data.lng);
		var cat = '';
		var entryFilename = ''; 
		switch (parseInt(data.category)) {
    		case 0:
    			cat = 'Text';
    			break;
 		    case 1:
 		    	cat = 'Foto';
 		    	entryFilename = data.photo; 
 		    	break;
    		case 2: 
    			cat = 'Film';
    			entryFilename = data.film; 
 		    	break;    		
 		    case 3:
 		    	cat = 'Musik';
 		    	entryFilename = data.music;
 		    	break;
		}
		var tooltiptext = '';
		if (data.iswinner == 1) {
			tooltiptext = '<p><b>' + data.rank +'. Platz Kategorie ' + cat + '</b></p>';
		} 
		tooltiptext += '<p>'+data.title+'</p>';
		var yearofbirth = new Date(data.date_of_birth*1000).getFullYear();
		var t = '<h2>'+cat+' von '+data.first_name+' '+data.last_name+' ('+yearofbirth+')</h2>' + tooltiptext;
		
		var marker = new google.maps.Marker({
		  position: markerLatlng, 
		  shadow: shadow,
          icon: image
		});	
		
		// Add the marker to the Fluster
		fluster.addMarker(marker);
		
		$(marker).data('markerdata',{'content':t,'name':data.first_name+' '+data.last_name,'file':'uploads/tx_spsubmit/'+entryFilename, 'cat':data.category, 'uid':data.uid,'youtubelink':data.youtubelink,'iswinner':data.iswinner,'winnertext':data.winnertext,'rank':data.rank});
		
		// tooltip
		google.maps.event.addListener(marker, 'mouseover', function() {
  			showTooltip(marker);
		});
		google.maps.event.addListener(marker, 'mouseout', function() {
  			hideTooltip();
		});
		
		onFinishBox = function(el) {};
		// show shadowbox on click
		google.maps.event.addListener(marker, 'click', function() {
			openMarker(marker);
		});
		
		markers.push(marker);
		
		if (data.iswinner == 1) {
			winners.push(marker);
		}
	}
	// opens a marker (from click on map or from winners)
	function openMarker(marker) {
		var mdata = $(marker).data('markerdata');
		var player = 'html';
		var boxcontent = '';
		
		switch (parseInt(mdata.cat)) {
			case 0: 
				// text
				player = 'html';
				onFinishBox = function(el) {
					$('#sb-player')
						.load('http://stammplatz.ch/index.php?id=589&eID=spsubmit&txt=1&uid='+mdata.uid)
						.css('overflow','auto');
				};
				break;
			case 1:
				// photo
				player = 'html';
				boxcontent = '<div id="sb-imageloader"><div id="sb-imageloader-inner"></div></div>';
				onFinishBox = function(el) {
					$('#sb-player').load(
						'http://stammplatz.ch/index.php?id=589&eID=spsubmit&img='+encodeURIComponent(mdata.file),
						function() {
							// fit shadowbox to image size
							Shadowbox.skin.dynamicResize($('.bigimage').width(),$('.bigimage').height());
							$('#sb-player').css('overflow','hidden');
						}
					);
				};
				break;
			case 2:
				// film
				boxcontent = '../../../'+mdata.file;
				player = 'flv';
				onFinishBox = function(el) {
					// do nothing
				}
				/*
				onFinishBox = function(el) {
					$('#sb-player').html('<object width="500" height="298">'+
							'<param name="movie" value="'+mdata.youtubelink+'"></param>'+
							'<param name="allowFullScreen" value="true"></param>'+
							'<param name="allowscriptaccess" value="always"></param>'+
							'<embed src="'+mdata.youtubelink+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="298"></embed></object>');
				};
				*/
				break;
			case 3: 
				// mp3
				player = 'html';
				boxcontent = mdata.file;
				// load mp3 when box is open
				onFinishBox = function(el) {
					$("#sb-player").jmp3({
						backcolor: "000000",
						forecolor: "eddc0c",
						width: 500,
						showdownload: 'false',
						showfilename: 'false',
						volume: 80,
						autoplay: 'true'
					});
				};
				break;
		}
		var closelink = '<div id="closelink"><a href="#" onclick="window.parent.Shadowbox.close(); return false;"><img src="fileadmin/templates/images/close.gif" width="13" height="13" alt="Schliessen" /></a></div>';
		//console.log(boxcontent);
		Shadowbox.open({
			content:   	boxcontent,
			title:      mdata.content+closelink,
			player:		player,
			options:	{onFinish:onFinishBox}
		});
	}
	
	// load places from server
	function loadData() {
		clearMarkers();
		$.getJSON('http://stammplatz.ch/index.php?id=589&eID=spsubmit', function (data) {
			 // create all markers
			 for (var i in data) {
					createMarker(data[i]);
			 }
			 			 
			 // This will set event handlers on the map and calculate clusters the first time.
			 fluster.initialize();

			 // show map
			 dataloaded = true;
			 showMapIfReady();
		});
	}
	
	function initMap() {
		
		// ie7 does not work with 100% width 100% height.
		// set height in pixels
		if ($.browser.msie && $.browser.version == '7.0') {
			$('#map_canvas').width($(window).width());
			$('#map_canvas').height($(window).height());
		} else if ($.browser.msie && $.browser.version == '6.0') {
			alert('In Internet Explorer 6 funktioniert die Karte nur begrenzt')
		}
		
		var myOptions = {
    	  	zoom: zoomlevel,
    	  	center: myLatlng,
    	  	disableDefaultUI: true
		}
		
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		map.mapTypes.set('smap', smapType);
 		map.setMapTypeId('smap');
 		
 		// Initialize Fluster and give it a existing map (for marker clustering)
		fluster = new Fluster2(map);
		// Set styles
		fluster.styles = {
			// This style will be used for clusters with more than 0 markers
			0: {
				image: 'fileadmin/templates/images/cluster2_0.png',
				textColor: '#000',
				width: 58,
				height: 58
			},
			// This style will be used for clusters with more than 10 markers
			5: {
				image: 'fileadmin/templates/images/cluster2_5.png',
				textColor: '#000',
				width: 69,
				height: 69
			},
			10: {
				image: 'fileadmin/templates/images/cluster2_10.png',
				textColor: '#000',
				width: 81,
				height: 81
			}
		};
		
		// makes fromLatLngToContainerPixel available
		overlayhelper = new ProjectionHelperOverlay(map);
		
		// start loading data
		loadData();
		
		// show map when all tiles are loaded
		google.maps.event.addListener(map, 'tilesloaded', function() {
			maploaded = true;
			showMapIfReady();
	    });
		// controls
		// rollover
		$('.control img').hover(
			function() {
				$(this).attr('src',$(this).attr('src').replace('.png','ro.png'));
			},
			function() {
				$(this).attr('src',$(this).attr('src').replace('ro.png','.png'));
			}
		);
		// move
		$('#up').click(function() {
			map.panBy(0,-150);
		});
		$('#right').click(function() {
			map.panBy(150,0);
		});
		$('#down').click(function() {
			map.panBy(0,150);
		});
		$('#left').click(function() {
			map.panBy(-150,0);
		});
		// zoom
		$('#plus').click(function() {
			map.setZoom(map.getZoom()+1);
		});
		$('#minus').click(function() {
			map.setZoom(map.getZoom()-1);
		});
			
	}
	
	
	// try to get gps-position
    /*
    if(navigator.geolocation) {
    	navigator.geolocation.getCurrentPosition(
    		// location received
    		function(position) {
    			myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    			zoomlevel = 12;
    			initMap();
    		},
    		// error or not allowed by user
    		function(msg) {
    			console.log(typeof msg == 'string' ? msg : "error");
    			initMap();
    		}
    	);
    } else {
    	// load map with default position and zoomlevel
    	initMap();
    }
    */
    initMap();

});
