// Map bounds
var bounds;	

// Number of requests for markers
// Is used to prevenet multiple marker loading
// Only latest markers will be displayed
var marker_requests_num = 0;

// Custom icons for markers
var IMAGES = ["depression", "good", "happy", "anger", "love", "sad"];
var ICONS = [];

// ------------------------------------------------------------------------

function HtmlControl(_1,_2){this.html=_1;this.isVisible=true;this.isPrintable=false;this.isSelectable=false;if(_2){this.isVisible=(_2.visible===false)?false:true;this.isPrintable=(_2.printable===true)?true:false;this.isSelectable=(_2.selectable===true)?true:false;}}HtmlControl.prototype=new GControl();HtmlControl.prototype.initialize=function(_3){this.div=document.createElement("div");this.div.innerHTML=this.html;this.setVisible(this.isVisible);_3.getContainer().appendChild(this.div);return this.div;};HtmlControl.prototype.getDefaultPosition=function(){return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,7));};HtmlControl.prototype.selectable=function(){return this.isSelectable;};HtmlControl.prototype.printable=function(){return this.isPrintable;};HtmlControl.prototype.setVisible=function(_4){this.div.style.display=_4?"":"none";this.isVisible=_4;};HtmlControl.prototype.visible=function(){return this.isVisible;};

// ------------------------------------------------------------------------

// Create GMap
function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    map.enableGoogleBar();

	
    // Max min zoom        
    var minMapScale = 5;
	var maxMapScale = 14;
	
    // get array of map types	
    var mapTypes = map.getMapTypes();
	
    // overwrite the getMinimumResolution() and getMaximumResolution() methods for each map type
	for (var i=0; i<mapTypes.length; i++) {
		mapTypes[i].getMinimumResolution = function() {return minMapScale;}
		mapTypes[i].getMaximumResolution = function() {return maxMapScale;}
	}
    
	// Map position and zoom
	map.setCenter(new GLatLng(lat, lng), zoom);
            
	map.getInfoWindow();
    			
    // Get markers        
    getMarkers();				        
    
    // Set UI elements
    map.setUIToDefault();
    
    // Rounded corners    	
	html='<img src="public/img/map_corner_top_left.png" width="10" height="10" border="0" />';
	htmlControl=new HtmlControl(html);
	map.addControl(htmlControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0)));
	
    html='<img src="public/img/map_corner_top_right.png" width="10" height="10" border="0" />';
	htmlControl=new HtmlControl(html);
	map.addControl(htmlControl, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 0)));
	
	html='<img src="public/img/map_corner_bottom_left.png" width="10" height="10" border="0" />';
	htmlControl=new HtmlControl(html);
	map.addControl(htmlControl, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0, 0)));
	
	html='<img src="public/img/map_corner_bottom_right.png" width="10" height="10" border="0" />';
	htmlControl=new HtmlControl(html);
	map.addControl(htmlControl, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 0)));
	
	// Executes when we drag-drop or zoom
    GEvent.addListener(map, "dragend", function() {
		$("#description").hide();			      	
		getMarkers();  			
	});		
	GEvent.addListener(map, "zoomend", function() {
		$("#description").hide();			      	
		getMarkers();
	});		
		
  }
}

// ------------------------------------------------------------------------

// Get markers from server and put them on the map
function getMarkers()
{    	
	// Clear previous markers
	map.clearOverlays();		
	
	// Get map bounds
	bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    
    // Increment request num
    marker_requests_num++;  		          	    	
	
	// Request markers
	$.ajax({		
		type: "POST",
		url: base_url + "map/markers",
		data: "zoom="+map.getZoom()+"&minlat="+southWest.lat()+"&maxlat="+northEast.lat()+
		      "&minlng="+southWest.lng()+"&maxlng="+northEast.lng()+"&month="+selected_month,
		dataType: "xml",
		success: function(data){		
            if (marker_requests_num > 1) {
                marker_requests_num--;
                return;
            } else {
                marker_requests_num--;
            }  				
  			$(data).find("marker").each(function() {
      			var marker = $(this);          			          			
				var users_num = marker.attr("users_num");
				var moods = marker.attr("moods");
				var major_mood = marker.attr("major_mood");
				var point = new GLatLng(parseFloat(marker.attr("latitude")), parseFloat(marker.attr("longitude")));
				var marker = createMarker(point, users_num, moods, major_mood, parseFloat(marker.attr("maxlat")), parseFloat(marker.attr("minlat")), parseFloat(marker.attr("maxlon")), parseFloat(marker.attr("minlon")));
				map.addOverlay(marker);					
  			});				  	
		}
	});		
}

// ------------------------------------------------------------------------

// Create new marker	
function createMarker(point, users_num, moods, major_mood, maxlat, minlat, maxlon, minlon) {
  var marker = new GMarker(point, { icon: getMoodIcon(major_mood) });    
  
  // Executes on marker click
  GEvent.addListener(marker, 'click', function() {
  	// Infowindow inner html
  	var html = "<div class=\"event_title\">Total number: " + users_num + "</div>";
	html += "<div style=\"float:right;margin:40px 10px 0 10px; \"><a href='/region/coords/"+maxlat+"/"+minlat+"/"+maxlon+"/"+minlon+"/"+map.getZoom()+"'><img src='/public/img/more_button.png'></a></div>";

//	html += "<div style=\"float:right;margin:40px 10px 0 10px; \"><a href='/region?maxlat="+maxlat+"&minlat="+minlat+"&maxlon="+maxlon+"&minlon="+minlon+"&zoom="+map.getZoom()+"'>detail</a></div>";
	html += "<div style=\"float:right;margin-right:10px; width:120px; height:120px;\"><img src=\""+moods+"\" width=\"120\" height=\"120\" /></div>";
	
    marker.openInfoWindowHtml(html, {maxWidth:100});		     					    
  });
  
  return marker;
}

// ------------------------------------------------------------------------

// Get the name of image for the marker
function getMoodIcon(icon_id) {      
  if (!ICONS[icon_id]) {
    var icon = new GIcon();
    icon.image = base_url + "public/markers/" + IMAGES[icon_id-1] + ".png";
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 0);
    icon.iconSize = new GSize(48, 66);
    icon.shadow = base_url + "public/markers/shadow.png";
    icon.shadowSize = new GSize(56, 66);
    icon.iconAnchor = new GPoint(24, 66);
    ICONS[icon_id] = icon;
  }
  return ICONS[icon_id];
}

// ------------------------------------------------------------------------

// Request details about the point
function request_details(point, mood_id) {    
	// Check if this point and mood was requested already    	
	if (check_description(point, mood_id)) {    		
		$("#description").show();		
	} else {			
		$("#description").empty();	
		cur_lat = point.lat();
		cur_lng = point.lng();
		cur_mood = mood_id;		
	    	
		// Get map bounds		
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        
		$.ajax({
  			type: "POST",
  			url: base_url + "map/details",
  			data: "zoom="+map.getZoom()+"&minlat="+southWest.lat()+"&maxlat="+northEast.lat()+
			      "&minlng="+southWest.lng()+"&maxlng="+northEast.lng()+
				  "&lat="+point.lat()+"&lng="+point.lng()+"&mood_id="+mood_id+  
				  "&month="+selected_month,			
  			dataType: "xml",
  			success: function(data){
			  	// Major tags
				major_tags = $(data).find("major_tags").text();					                  				
      			// Create tabs
				createTabs(data);
				$("#description").show();								  	
   			}
		});
	}
	scrollDescription();
}

// ------------------------------------------------------------------------			

// Init geo before moving to page of country selection
function init_geo() {
	// check cookie for marker position
	var cookie_lat = $.cookie('my_lat');
 	var cookie_lng = $.cookie('my_lng'); 	
 	if (cookie_lat && cookie_lng) {
		my_lat = cookie_lat;
		my_lng = cookie_lng;		
	} else {
		my_lat = lat;
		my_lng = lng;	
	}	    
}

// ------------------------------------------------------------------------

function scrollDescription(){$('html, body').animate({scrollTop: $("#description").offset().top}, 2000);}

// ------------------------------------------------------------------------

// Hide or show map help message
function hideMapMessage(){		
    if($("#map_message_close_button a").text() == "Hide help"){
	    $.cookie('show_help', 'hide', {expires:30});
	    $("#map_message #help").hide("slow");
	    $("#map_message_close_button a").text("Show help");
    }else{
	    $.cookie('show_help', 'show', {expires:30});
	    $("#map_message #help").show("slow");
	    $("#map_message_close_button a").text("Hide help");
    }
}

// Event listeners
$(document).ready(function(){	
	//Hide map help if user hidded it before
	if($.cookie('show_help') == 'hide'){
	  $("#map_message #help").hide();
	  $("#map_message_close_button a").text("Show help");	
	}else{
	  $("#map_message #help").show('slow');                                      
	  //$("#map_message_close_button a").text("Show help");     
	}
	
	$("#jslider").slider({
		min: 1, 
		max: 12, 
		step: 1, 
		value: 12, 
		change: function(event, ui) {
			selected_month = $('#jslider').slider('option', 'value') - 12;
			getMarkers();
		}
	});
});