// Map management functions

var map;
var currentBubble;
var currID;
var currImage = 1;

var markersArray = [];

function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

function initMap(){
	$('select.styled').customSelectBox();
	// Starting lat/lng (temp)
	var myLatlng = new google.maps.LatLng(-34.397, 150.644);
	var myOptions = {
	  zoom: 14,
	  scrollwheel: false,
	  mapTypeId: google.maps.MapTypeId.ROADMAP,
	  mapTypeControl: false
	};

	map = new google.maps.Map(document.getElementById("map_canvas"),
		myOptions);
	encodeAddress("Parc Ave and Duluth, Montreal, QC","map.setCenter",{});
	initLocations();
}

function encodeAddress(address,callback,params){
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
		var latlng = results[0].geometry.location;
		eval(callback + "(latlng,params);");
      } else {
        //alert("Geocode was not successful for the following reason: " + status);
      }
    });
}

/**
 * @fn addLocation
 * @brief Adds a specific location as an orange marker to the map
 * @param LatLng (use as a callback from encodeAddress)
 */
function addLocation(latlng,params,open){
	if(!latlng) return;
	var image = "img/marker.png"; 
	var marker = new google.maps.Marker({
		map: map, 
		icon: image, 
		position: latlng
	});
	
	markersArray.push(marker);
	
	marker.location_id = params.id;
	
	// Create a new information bubble to pin into the map
	var infoBubble = new InfoBubble({
      map: map,
      shadowStyle: 1, 
	  padding:0,
      borderWidth: 0,
	  borderRadius: 10,
	  borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: false,
      backgroundClassName: 'bubble',
	  backgroundColor: '#e8e8e8',
	  maxHeight: 380
    });
	
	google.maps.event.addListener(marker, 'click', function() {
		google.maps.event.clearListeners(marker,'mouseout');
		if(currentBubble) currentBubble.close();
		var id = marker.location_id;
		map.panTo(marker.position); 
		map.panBy(0,-210);
		infoBubble.setContent(loadTemplate(marker.location_id));
		infoBubble.open(map, marker);
		
		// For usage by other ajax calls
		currID = id;
		
		// Load information into the bubble
		loadDetails(id,'description');
		loadTitle(id);
		loadImage(id,1);
		currentBubble = infoBubble;
	});
	
	var currMiniBubble;
	google.maps.event.addListener(marker,'mouseover',function(){
		infoBubble.setContent(loadTooltip(marker.location_id));
		infoBubble.open(map,marker);
		currMiniBubble = infoBubble;
		google.maps.event.addListener(marker,'mouseout',function(){
			currMiniBubble.close();
		});
	});
	
	
	// Simple close action (click on map to close current infoBubble)
	google.maps.event.addListener(map, 'click', function() {
		infoBubble.close();
	});
	return marker;
}

$(".bubble a").live("click",function(){
	$(this).attr("target","_blank");	
});

/**
 * LoadTemplate
 * Loads the bubble template
 */
function loadTemplate(id){
	var tpl = $.ajax({ 
			async: false, 
			method:"POST", 
			url: "ajax/location_template.php?location_id=" + id }).responseText;
	return tpl;
}

/**
 * LoadTitle
 * Loads the tooltip title for the marker
 */
function loadTooltip(id){
	var tpl = $.ajax({ 
			async: false, 
			method:"POST", 
			data: "tab=tooltip&location_id=" + id,
			url: "ajax/location_details.php" }).responseText;
	return tpl;
}

/**
 * LoadDetails
 * Loads the details of the current marker
 */
function loadDetails(id,tab){
	if(id == null) id = currID;
	$.ajax({
	   type: "POST",
	   url: "ajax/location_details.php",
	   data: "location_id=" + id + "&tab=" + tab,
	   success: function(msg){
		$("#window_" + id + " .overall").show();
		$("#window_" + id + " .fullpane").hide();
	    var window = $("#window_" + id + " .textpane");
	    window.html(msg).show();
	    //window.scrollbar();
	    //window.update();
	   }
	 });
	return false;
}

/**
 * loadInteract
 */
function loadInteract(){
	var id = currID;
	$.ajax({
	   type: "POST",
	   url: "ajax/location_interact.php",
	   data: "location_id=" + id,
	   success: function(msg){
	    //var window = $("#window_" + id + " .textpane");
		$("#window_" + id + " .overall").hide();
	    $("#window_" + id + " .fullpane").html(msg).show();
	    //window.html(msg);
	   }
	 });
	return false;
}

function loadMedia(){ 
	var id = currID;
	$.ajax({
	   type: "POST",
	   url: "ajax/location_media.php",
	   data: "location_id=" + id,
	   success: function(msg){
	    //var window = $("#window_" + id + " .textpane");
		$("#window_" + id + " .overall").hide();
	    $("#window_" + id + " .fullpane").html(msg).show();
	    window.html(msg);
	   }
	 });
	return false;
}

/**
 * loadTitle
 * Loads the title for the current window
 */
function loadTitle(id){
	if(id == null) id = currID;
	$.ajax({
	   type: "POST",
	   url: "ajax/location_title.php",
	   data: "location_id=" + id,
	   success: function(msg){
	     $("#window_" + id + " .title").html(msg);
	   }
	 });
	return false;
}

/**
 * loadImage
 * Loads one of the images for the current window
 */
function loadImage(id,num){
	if(id == null) id = currID;
	$.ajax({
	   type: "POST",
	   url: "ajax/location_image.php",
	   data: "location_id=" + id + "&imagenum=" + num,
	   success: function(msg){
		if(msg == 0) currImage --;
		else $("#window_" + id + " .image").html(msg);
	   }
	 });
	return false;
}
function nextImage(){
	currImage ++;
	loadImage(null,currImage);
}
function prevImage(){
	if(currImage > 1){ 
		currImage --;
		loadImage(null,currImage);
	}
}
var photos = [];
function addPhoto(id,link,title){
	photos.push({'href'	: link, 'title': title});
}

function showPhoto(pos){
	$.fancybox(photos,{
		'type':'image',
		'index': pos,
		'titlePosition': 'inside'
	});
	return false;
}
function showVideo(id){
	$("#fancybox").fancybox({
		type: "iframe",
		href: "http://www.youtube.com/embed/" + id,
		width: 640,
		height: 390,
		'titlePosition': 'inside'
	}).click();
}

function closeBubble(){
	currentBubble.close();
	currMiniBubble.close();
}

function submitInteract(){
	var form = $("#submit_interact");
	$.ajax({
		'url': form.attr("action"),
		'type': "POST",
		'data': form.serialize(),
		'success': function(response){
			$.fancybox({ content: response });
		}
	});
	return false;
}

// Map filter
function filterMap(){
	$.ajax({
		url: "ajax/map_filter.php",
		data: "start=" + $("#decade_start").val() + "&end=" + $("#decade_end").val() + "&category=" + $("#category").val() + "&search=" + $("#search").val(),
		type: "POST",
		dataType: "json",
		success: function(data){
			clearOverlays();
			for(i in data){
				addLocation(new google.maps.LatLng(data[i].lat,data[i].lng),{'id':data[i].lid},true);
			}
		}
	});
}
$(document).ready(function(){
	$("#search").change(filterMap);
	$("#decade_start").change(filterMap);
	$("#decade_end").change(filterMap);
	$("#category").change(filterMap);
});

