/**
 * Concertagenda.nl Google Maps/Calendar Javascript
 *
 * @copyright  BliXem Internet Services
 */

/**
 * initCalendarSlider. Initializes the slider.
 */ 

// standard width of day in calendar (+ margin) in pixels
var dayWidth = 113; 
	
function initCalendarSlider(){	
	
	$("#calendarDates").each(function () {
		var ul = $("ul", this);
		var aantalDagen = $("li",this).length;
		var ulWidth = (aantalDagen * dayWidth) - 10;
		var calendarWidth = ulWidth - $(this).outerWidth();
		$(ul).css({ width:ulWidth});
		$("ul#dates li:last a").css({margin:"0px"});	
		var slider = $(".slider", this).slider({ 
		handle: ".handle",
		minValue: 0, 
		maxValue: calendarWidth, 
		slide: function (ev, ui) {
			$(".handle").css({ backgroundPosition:"bottom" });
			ul.css("left", "-" + ui.value + "px");
		}, 
		stop: function (ev, ui) {
		   ul.stop();
		   slider.focus();  
		    $(".handle").css({ backgroundPosition:"top" }); 
		   ul.animate({ "left" : "-" + ui.value + "px" }, 2500, "easeOutElastic");
		}
		});
		});
		
		// Add actions to the buttons alongside the calendar
	
	$("#weekVerder").click(function () {
		$(".slider").slider("moveTo","+=" + 7*dayWidth);
		});
			
	$("#weekTerug").click(function () {				 
		$(".slider").slider("moveTo","-=" + 7*dayWidth);
		});	
}

	
/**
 * initGoogleMapsSlider. Initializes the GoogleMaps sliders.
 */ 
	
var mapSliderTimeValue = "86400";
var mapSliderDistanceValue = "5";
var mapLocationValue = "Amsterdam";
var city_id;
var currentCategory = "artist";
var defaultZoomFactor = 7;

function initGoogleMapsSlider(){

	var sliderDistanceValues = ["5","25","50","100","200"];
	var sliderTimeValueNames = ["Vandaag","Dit weekend","Deze week","Twee weken","Deze maand"];
	var sliderTimeValues = ["86400","604800","604800","1209600","2678400"];
				
	$(".sliderGoogle").each(function (){
		$(this).slider({ 
		  handle: ".handle",
		  handles:{start:10},
		  minValue: 0, 
		  maxValue: 4, 
		  steps: 4,
		  slide: function(ev, ui){
			var sliderId = $(this).attr("id");
			var sliderState = Math.round($(this).slider("value"));
			ui.handle.css({ backgroundPosition:"bottom" });
				if(sliderId == "sliderDistance"){
					$("#distanceInfo").html("<strong>Afstand</strong> (" + sliderDistanceValues[sliderState] + " km)");	
				} else {
					$("#timeInfo").html("<strong>Tijd</strong> (" + sliderTimeValueNames[sliderState] + ")");
				}
			  },
		  stop: function (ev, ui) {
		  	var sliderId = $(this).attr("id");
			var sliderState = Math.round($(this).slider("value"));
			ui.handle.css({ backgroundPosition:"top" });
				if(sliderId == "sliderDistance"){
					$("#distanceInfo").html("<strong>Afstand</strong> (" + sliderDistanceValues[sliderState] + " km)");
					mapSliderDistanceValue = sliderDistanceValues[sliderState];
				} else {
					$("#timeInfo").html("<strong>Tijd</strong> (" + sliderTimeValueNames[sliderState] + ")");
					mapSliderTimeValue = sliderTimeValues[sliderState];
				}
			 }
			});
	});	
}

/**
 * Update the map with the events given in the map
 */
function updateMap(){	
	if (currentCategory == 'location' && city_id) {
		$('#selectLocatieGoogle').val(mapLocationValue);
		loadMapCityVenues(city_id);
	} else {
		mapLocationValue = $('#selectLocatieGoogle').val();
		loadMapEvents(mapSliderDistanceValue, mapSliderTimeValue, $('#selectLocatieGoogle').val() + " Nederland");		
	}
}

/**
 * openCalendar. Controls the opening of the calendar. Checks if the calendar is open etc. 
 */ 
 
function openCalendar(){	
	var calendarDisplay = $("#calendarOuterContainer").css("display");
	// Is the calendar open?
	if(calendarDisplay == "none"){
		$("#calendarOuterContainer").slideDown(1000, function(){	
			$("#calendarDates").fadeIn("fast",function(){
				initCalendarSlider();
				$("#calendarDates a").fadeIn("fast");
				/* in the calendar the CURRENT or SELECTED date has a class "current" or "today" */ 
				var selectedDate = $("#dates .current .day").html();					
				var todayDate = $("#dates .today .day").html();
				if(selectedDate != null){
					 $(".slider").slider("moveTo",(selectedDate-4)*dayWidth);					
				} else if(todayDate != null){
					 $(".slider").slider("moveTo",(todayDate-4)*dayWidth);					
				} else {					
					$(".slider").slider("moveTo",1);				
				}
				
				}); 
			$("#pullDownCalendar").css({ backgroundPosition:"0px -20px" });			
			});						
	} else {
		$("#calendarDates").fadeOut("slow", function(){
			$("#calendarOuterContainer").slideUp(1000,function(){ 								   
				$("#calendarOuterContainer").css({display:"none"});
				 $("#pullDownCalendar").css({ backgroundPosition:"0px 4px" });			
				});
			}); 
	}						  
	
}

/**
 * openGoogleMaps. Controls the opening of the Google Maps. Checks if Google Maps is open etc. 
 */ 
 
function openGoogleMaps(){	
	var googleDisplay = $("#googleMapOuterContainer").css("display");	
	if(googleDisplay == "none"){
		$("#googleMapOuterContainer").slideDown(1000,function(){													
		   $("#googleMapControl").fadeIn("fast",function(){
		   		$("#map").fadeIn("fast");											 
				initGoogleMapsSlider();												
				$("#pullDownGoogle").css({ backgroundPosition:"0px -20px" });
				});	  					
		   });
		} else {
			$("#map").fadeOut("fast",function(){
				$("#googleMapControl").fadeOut("fast",function(){	 
					 $("#pullDownGoogle").css({ backgroundPosition:"0px 4px" });
					 $("#googleMapOuterContainer").slideUp(1000,function(){
					 	$("#googleMapOuterContainer").css({display:"none"});
						 });
					});
				})		
		}							
	}

function initFoldOuts(){
	// add the action to the calendar-tab
	$("#pullDownCalendar").click(function(){
		openCalendar();
	});		

	// add the action to the googlemaps-tab
	$("#pullDownGoogle").click(function(){					
		openGoogleMaps();
	});
}	  
	
/**
 * Code to initialize Google Maps
 */ 

var map;
  
function loadGoogle() {
     if(GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"),{size:new GSize(750,300)});
      	map.enableScrollWheelZoom();
      	map.enableContinuousZoom();
      	map.setCenter(new GLatLng(52.132633, 5.291266), defaultZoomFactor);
        map.setMapType(G_NORMAL_MAP);
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,30));
		map.addControl(new GMapTypeControl(),bottomRight);
		map.addControl(new GLargeMapControl());	
		map.addControl(new GScaleControl());
		setTimeout("map.checkResize()",2000);
      }
}


/**
 * loadMapEvents - Plot events on the map
 *
 * @param int distance Distance in kilometers
 * @param int time Time offset in seconds from now
 * @param string location Origin location 
 **/
function loadMapEvents(distance, time, location){
	
	// Determine the zoomfactor based on the sliderposition
	if(mapSliderDistanceValue == 5){
		zoom = 11;	
	} else if(mapSliderDistanceValue == 10){
		zoom = 10;
	} else if(mapSliderDistanceValue == 25){
		zoom = 9;
	} else if(mapSliderDistanceValue == 50){
		zoom = 8;
	} else {
		zoom = 7;
	}
	
	geocoder = new GClientGeocoder();
	//alert(location);
	geocoder.getLatLng(location,
		function(point){
			if(!point){
				alert("De locatie \"" + location + "\" werd niet gevonden.");
			} else {
				map.clearOverlays();
				map.setCenter(point, zoom);
				var url = "/geo/getGeoEvents/" + distance + "/" + time + "/" + point.lat() + "/" + point.lng() + "/";
				$.getJSON(url, function(data){
					$.each(data, function(i,venue){
						var balloonContent = '<strong><a href="/locaties/' + venue.province_seo_name + '/' + venue.city_seo_name + '/' + venue.venue_seo_name + '/">' + venue.venue_name + ', ' + venue.city_name + '</a></strong>';
						balloonContent += '<ul>';
						$.each(venue.events, function(j,event){
							balloonContent += '<li><a href="/agenda/' + venue.province_seo_name + '/' + venue.city_seo_name + '/' + venue.venue_seo_name + '/' + event.seo_date + '/' + event.seo_title + '">' + event.date + ': ' + event.title + '</a></li>';
						});
						balloonContent += '</ul>';
						addMarker(balloonContent, venue.latitude, venue.longitude);
					});
				});
			}
		}
	)	
}

/**
 * loadArtistEvents - Plot venues on the map
 *
 * @param int artist_id
 **/
function loadArtistEvents(artist_id){
	
	// Determine the zoomfactor based on the sliderposition
	if(mapSliderDistanceValue == 5){
		zoom = 11;	
	} else if(mapSliderDistanceValue == 10){
		zoom = 10;
	} else if(mapSliderDistanceValue == 25){
		zoom = 9;
	} else if(mapSliderDistanceValue == 50){
		zoom = 8;
	} else {
		zoom = 7;
	}
	
	map.clearOverlays();

	// get venues and place markers
	var url = "/geo/getArtistEvents/" + artist_id + "/";
	$.getJSON(url, function(data){
		alert(data);
		$.each(data, function(i,venue){
		});
	});
}
	

/**
 * loadCityVenues - Plot venues on the map
 *
 * @param int city_id
 **/
function loadMapCityVenues(city_id){
	
	// Determine the zoomfactor based on the sliderposition
	if(mapSliderDistanceValue == 5){
		zoom = 11;	
	} else if(mapSliderDistanceValue == 10){
		zoom = 10;
	} else if(mapSliderDistanceValue == 25){
		zoom = 9;
	} else if(mapSliderDistanceValue == 50){
		zoom = 8;
	} else {
		zoom = 7;
	}
	
	map.clearOverlays();
	// get city and pan to it
	var url = "/geo/getCity/" + city_id + "/";

	$.getJSON(url, function(city){
		var point = new GLatLng(city.latitude, city.longitude);
		map.setCenter(point, 12);
		//map.setZoom(7);
	});
	
	// get venues and place markers
	var url = "/geo/getCityVenues/" + city_id + "/";
	$.getJSON(url, function(data){
		$.each(data, function(i,venue){
			var balloonContent = '<strong><a href="/locaties/' + venue.province_seo_name + '/' + venue.city_seo_name + '/' + venue.venue_seo_name + '/">' + venue.venue_name + ', ' + venue.city_name + '</a></strong>';
			addMarker(balloonContent, venue.latitude, venue.longitude);
		});
	});
}

/**
 * addMarker - Add a marker to the map
 *
 **/
function addMarker(balloonContent, latitude, longitude) {
	var point = new GLatLng(latitude, longitude);
	var icon = new GIcon();
	icon.image = "/images/marker.png";
	icon.shadow = "/images/marker_shadow.png";
	icon.iconSize = new GSize(20, 34);
	icon.iconAnchor = new GPoint(10, 34);
	icon.infoWindowAnchor = new GPoint(20, 1);
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(balloonContent);
	});
	map.addOverlay(marker);
}

/**
 * Function to init the Google map for the venue
 */

function loadGoogleMapVenue(balloonContent,latitude,longitude) {	
     if(GBrowserIsCompatible()) {
      	mapVenue = new GMap2(document.getElementById("mapVenue"));
      	mapVenue.enableScrollWheelZoom();
      	mapVenue.enableContinuousZoom();
      	var point = new GLatLng(latitude,longitude);
      	mapVenue.setCenter(point, 10);
        mapVenue.setMapType(G_NORMAL_MAP);	        	
		// plot the venue
		mapVenue.clearOverlays();	
		addMarkerVenue(balloonContent,latitude,longitude);					
     }
}

/**
 * addMarkerVenue - Add a marker to the map
 *
 **/
function addMarkerVenue(balloonContent, latitude, longitude) {
	var point = new GLatLng(latitude, longitude);
	var icon = new GIcon();
	icon.image = "/images/marker.png";
	icon.shadow = "/images/marker_shadow.png";
	icon.iconSize = new GSize(20, 34);
	icon.iconAnchor = new GPoint(10, 34);
	icon.infoWindowAnchor = new GPoint(20, 1);
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(balloonContent);
	});
	mapVenue.addOverlay(marker);
	GEvent.trigger(marker, "click");
}

/**
 * Initialize the venues in the chosen city
 */ 

function initMapSettingsLocation(province, city, cityID){
		currentCategory = 'location';
		if (city && city !== '') {
			mapLocationValue = city;
		} else if (city && city !== ''){
			mapLocationValue = provence;			
		}
		city_id = cityID;
		$('#selectLocatieGoogle').val(mapLocationValue);
		
}

/**
 * Code to initialize the above functions.
 */ 

var mapVenue;

$(document).ready(function(){

	initFoldOuts();	
	$(".pullDown").css({ display:"block" });
	
	$("#updateMap").click(function(){ 
		currentCategory = 'artist'; 
		updateMap(); 
	});
	
	$(".googleMapsLink").click(function(){ 
		var googleDisplay = $("#googleMapOuterContainer").css("display");	
		if(googleDisplay == "none"){
			openGoogleMaps();
			loadGoogle(); 
			updateMap();
		}
	});
		
	$("#pullDownGoogle").click(function(){ 
		loadGoogle(); 
		updateMap(); 
	});

	if($("#mapVenue").length == 1){		
		var venueLatitude = $("#mapVenue #latitude").html();
		var venueLongitude = $("#mapVenue #longitude").html();
		var address = $("#mapVenue").html();
		loadGoogleMapVenue(address,venueLatitude,venueLongitude);
		var point = new GLatLng(venueLatitude,venueLongitude);
		mapVenue.panTo(point);
		mapVenue.checkResize();
		mapVenue.setCenter(point);
	}
	$('#selectLocatieGoogle').val(mapLocationValue);
});