$(document).ready(function(){

	if(GBrowserIsCompatible){                
		// init map
		scmap = new SolarChallengeMap(document.getElementById("map"), -28.499086, 130.956258);
		scmap.map.setMapType(G_SATELLITE_MAP);
		
		// checkpoints
		scmap.plotCheckpointMarkers("/wp-content/checkpoints.json");

                // spandoeken
                //scmap.plotSpandoekMarkers("/submission_location");
		// blog
		scmap.setBlogURL("/wp-content/blog.json");
                

		// if($("#toggleBlog").attr("checked")){
			scmap.plotBlogMarkers();
		// }
		// $("#toggleBlog").click(function(){scmap.toggleBlog();});

		// flickr
		scmap.setFlickrURL("/wp-content/photos.json");
		// if($("#toggleFlickr").attr("checked")){
			scmap.plotFlickrMarkers();
		// }
		// $("#toggleFlickr").click(function(){scmap.toggleFlickr();});
		

		// add onclick behaviour to left sidebar links
		// clicking them will move the map to a new location and zoomlevel 
		$("#shortcuts a").click(function(){
    	q_string = this.href.split('?')[1].replace('coords=','');
			q_array = q_string.split(',')
			latitude  = q_array[0];
			longitude = q_array[1];
			zoomlevel = parseInt(q_array[2]);
			
			ll = new GLatLng(latitude, longitude);
			scmap.map.setZoom(zoomlevel);
			scmap.map.panTo(ll);
			return false;
		});

		// temp function for alerting current map properties
/*		GEvent.addListener(scmap.map, "click", function(marker, point) {
				ll = scmap.map.getCenter();
				
				console.log("center: "+ ll.lat() + "," + ll.lng() + ","+scmap.map.getZoom());
		});
*/


	}
});

function SolarChallengeMap(mp,lat,lng) {
	
	// init map
	this.map = new GMap2(mp);
  	this.map.setCenter(new GLatLng(lat, lng), 4);
  	this.map.addControl(new GLargeMapControl());
  	this.map.addControl(new GMapTypeControl());
  	this.map.addControl(new GScaleControl());
	this.map.addControl(new GOverviewMapControl());
	this.map.enableContinuousZoom();

	// add route
	this.plotDirections(document.getElementById("directions"));
}

SolarChallengeMap.prototype = {

	map:null,
	baseIcon:null,
	locations:null,

	//FROM:"Darwin, NT 0801, 74 Cavenagh Street",
	//TO:"Victoria Square, Adelaide",
	TO:"-34.928658, 138.59999",
	FROM:"-12.464916, 130.84286",
	LOCALE:"en_AU",
	
	openWindows:0,

	flickrMarkers:new Array(),
	flickrURL:null,
	showFlickr:false,

	blogMarkers:new Array(),
	blogURL:null,
	showBlog:false,

	allMarkers:new Array(),
	bounds:null,
	
	plotCheckpointMarkers:function(url){
		var self = this;
		$.getJSON(url, function(locations){		
			$.merge(self.allMarkers,locations);
			$.each(locations, function(i, n){

				var infoHtml = '<div class="cpballoon"><h3>'+n.attributes.name+'</h3>';
				infoHtml += '<div>'+n.attributes.km+' kilometer</div>';
				infoHtml += '<img src="/wp-content/themes/nuonsolar/static/images/google/checkpoints/'+n.attributes.number+'.jpg" /><br clear="all" />';
				infoHtml += '</div>'
				

				var icon = new GIcon();

				if(i == 0 || i == locations.length-1) {
					icon.shadow = "/wp-content/themes/nuonsolar/static/images/google/icons/start-shadow.png";
					icon.shadowSize = new GSize(34, 25);
					icon.iconSize = new GSize(17, 25);
					icon.iconAnchor = new GPoint(8, 25);
					icon.infoWindowAnchor = new GPoint(4, 2);
					if(i == 0) {
						icon.image = "/wp-content/themes/nuonsolar/static/images/google/icons/start.png";						
					} else if (i == locations.length-1) {
						icon.image = "/wp-content/themes/nuonsolar/static/images/google/icons/end.png";						
					}
				} else {
					icon.image = "/wp-content/themes/nuonsolar/static/images/google/icons/checkpoint.png";
					icon.iconSize = new GSize(11, 11);
					icon.iconAnchor = new GPoint(5, 11);
					icon.infoWindowAnchor = new GPoint(8, 2);
				}
                                
				var marker = new GMarker(new GLatLng(n.attributes.latitude, n.attributes.longitude), icon);
				self.addMarker(marker,infoHtml);
		    });
		});
	},

	plotSpandoekMarkers:function(url){
		var self = this;
		$.getJSON(url, function(locations){		
			$.merge(self.allMarkers,locations);
			$.each(locations, function(i, n){
				var infoHtml = '<div class="spandoekballoon"><h3>'+n.submission.attributes.text+'</h3>';                                                                
				var infoHtml = '<img src="/wp-content/themes/nuonsolar/static/images/google/spandoek/background.jpg"/>';
                                //var infoHtml = '<div class="spandoektext">'+n.submission.attributes.text+'</div>"/>';
                                //var infoHtml = '<img src="/wp-content/themes/nuonsolar/static/images/google/spandoek/button.jpg"/>';
                                //infoHtml += '<div>'+n.submission.attributes.fname+' '+n.submission.attributes.mname+' '+n.submission.attributes.lname+'</div>';
				//infoHtml += '<div>'+n.submission.attributes.city+'</div>';
                                //infoHtml += '<div><a href=/actie?id='+n.submission.attributes.id+'>Check het spandoek!</a></div>';                                
				infoHtml += '</div>'				
				var icon = new GIcon();
				icon.image = "/wp-content/themes/nuonsolar/static/images/google/icons/spandoek_icon.png";
				icon.iconSize = new GSize(11, 11);
				icon.iconAnchor = new GPoint(5, 11);
				icon.infoWindowAnchor = new GPoint(8, 2);
				var marker = new GMarker(new GLatLng(n.attributes.longitude, n.attributes.latitude), icon);
				self.addMarker(marker,infoHtml);
		    });
		});
	},

	setBlogURL:function(url){
		this.blogURL = url;		
	},

	plotBlogMarkers:function(){
		if(!this.blogURL) return;
		var self = this;
		$.getJSON(this.blogURL, function(items){
			$.merge(self.allMarkers,items);
			$.each(items, function(i, n){				
				var infoHtml = '<div class="blogballoon"><h3>'+n.title+'</h3>';
				infoHtml += n.description;
				infoHtml += '<a href="'+n.link+'">lees meer ...</a></div>';
				
				var icon = new GIcon();
				icon.shadow = "/wp-content/themes/nuonsolar/static/images/google/icons/blog-shadow.png";
				icon.image = "/wp-content/themes/nuonsolar/static/images/google/icons/blog.png";
				icon.iconSize = new GSize(25, 23);
				icon.shadowSize = new GSize(39, 23);
				icon.iconAnchor = new GPoint(12, 25);
				icon.infoWindowAnchor = new GPoint(8, 2);
				icon.infoShadowAnchor = new GPoint(8, 2);
								
				var marker = new GMarker(new GLatLng(n.latitude, n.longitude), icon);				
				self.addMarker(marker,infoHtml);
				//self.blogMarkers[self.blogMarkers.length-1] = marker;
				self.blogMarkers.push(marker);
				self.showBlog = true;
		    });
		});
	},

	toggleBlog:function(){
		if(this.showBlog && this.blogMarkers.length > 0) {
			this.removeMarkers(this.blogMarkers);
			this.showBlog = false;
		} else if (!this.showBlog && this.blogMarkers.length > 0){
			this.addMarkers(this.blogMarkers);
			this.showBlog = true;
		} else if(!this.showBlog && this.blogMarkers.length <= 0){
			this.plotBlogMarkers();
		}
	},
	
	setFlickrURL:function(url){
		this.flickrURL = url;
	},

	plotFlickrMarkers:function(){
		if(!this.flickrURL) return;
		var self = this;
		$.getJSON(this.flickrURL, function(items){
			$.merge(self.allMarkers,items);
			$.each(items, function(i, n){				
				var infoHtml = '<div class="flickrballoon"><h3>'+n.title + '</h3>' + self.flickrThumbnail(n);
				infoHtml += '<br clear="all" /> <a target="_blank" href="http://www.flickr.com/photos/nuonsolarteam">flickr.com/photos/nuonsolarteam</a></div>';
				
				var icon = new GIcon();
				icon.shadow = "/wp-content/themes/nuonsolar/static/images/google/icons/blog-shadow.png";
				icon.image = "/wp-content/themes/nuonsolar/static/images/google/icons/flickr.png";
				icon.iconSize = new GSize(25, 23);
				icon.shadowSize = new GSize(39, 23);
				icon.iconAnchor = new GPoint(12, 25);
				icon.infoWindowAnchor = new GPoint(8, 2);
				icon.infoShadowAnchor = new GPoint(0, 0);

				var marker = new GMarker(new GLatLng(n.latitude, n.longitude), icon);
				self.addMarker(marker,infoHtml);
				self.flickrMarkers.push(marker);
				//self.flickrMarks(self.flickrMarkers.length) = marker;
				self.showFlickr = true;
		    });
		});
	},

	toggleFlickr:function(){
		if(this.showFlickr && this.flickrMarkers.length > 0) {
			this.removeMarkers(this.flickrMarkers);
			this.showFlickr = false;
		} else if (!this.showFlickr && this.flickrMarkers.length > 0){
			this.addMarkers(this.flickrMarkers);
			this.showFlickr = true;
		} else if(!this.showFlickr && this.flickrMarkers.length <= 0){
			this.plotFlickrMarkers();
			this.showFlickr = true;
		}
	},

	addMarker:function(m,h){
			// restore old position after closing info window
			var self = this;
      var old_pos = null;

      GEvent.addListener(m, 'click', function() {
				self.openWindows++;
				old_pos = self.map.getCenter();
      	m.openInfoWindowHtml(h);
    	});

      GEvent.addListener(m, 'infowindowclose', function() {
				self.openWindows--;
				// only restore old position if all windows are closed
				if (self.openWindows == 0) {
					self.map.panTo(old_pos);
				}
			});
			
		this.map.addOverlay(m);
		//this.zoomShowAll(this.allMarkers);
	},
	
	addMarkers:function(markers){
		var map = this.map;
		$.each(markers, function(i, n){
			map.addOverlay(n);
		});
	},

	removeMarkers:function(markers){
		var map = this.map;
		$.each(markers, function(i, n){
			map.removeOverlay(n);
		});
	},
   
	// Creates a marker whose info window displays the letter corresponding
	// to the given index.
	createMarker:function(point, index){
		// Create a lettered icon for this point using our icon class
		var letter = String.fromCharCode("A".charCodeAt(0) + index);
		var icon = new GIcon(this.baseIcon);
		icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
		var marker = new GMarker(point, icon);
		return marker;
	},
	
	zoomShowAll:function(locations) {
	    var bounds = new GLatLngBounds();
	    this.map.setCenter(new GLatLng(0,0),0);    
			$.each(locations, function(i, n){
				var lat = locations[i].latitude ? locations[i].latitude : locations[i].attributes.latitude;
				var lng = locations[i].longitude ? locations[i].longitude : locations[i].attributes.longitude;
	      bounds.extend(new GLatLng(lat, lng));
	    });
	    this.map.setZoom(this.map.getBoundsZoomLevel(bounds));
	    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	    this.map.setCenter(new GLatLng(clat,clng));
	},	

	flickrThumbnail:function(photo){
		var url = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_m.jpg';
		return '<img src="' + url + '" />';
	},

	plotGeoXml:function(xml){		
		var geoXML = new GGeoXml(xml);
		this.map.addOverlay(geoXML);
	},

	plotDirections:function(n){
		var directions = new GDirections(this.map, n);
		var fromAddress = this.FROM;
		var toAddress = this.TO;
		var locale = this.LOCALE;		
    	directions.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
		GEvent.addListener(directions, "addoverlay", this.removeDirectionIcons);
	},
	
	removeDirectionIcons:function(){
		//console.log($("img.gmnoprint"));
		$("img.gmnoprint").hide();
	}
}

function moveMapTo(index) {
    map.panTo(new GLatLng(locations[index].latitude, locations[index].longitude));
}