var cT = new Date()
var datenow = cT.getFullYear() + '-' + (cT.getMonth()+1) + '-' +  cT.getDate(); 

var datevalue = datenow;
var map;
var daymargin = 7;
var gmarkers = [];
var lost_icons = [];
var found_icons = [];
var institution_icons = [];
var cluster_icon_found;
var cluster_icon_lost;
var cluster_icon_multi;
var hoverLabel;
var prevzoom;
var clickedClusterLatLng;
var clickedCluster;
var timer;
var sleeping = false;
var pending = false;

function update_item_types_list()
{
	types = '';
	var all_btn = true;
	var none_btn = true;
	$(".main_tab_small_box a").each(function () {
		if($(this).hasClass("active")) {
			types = types + $(this).parent().index() + ','
			none_btn = false;
		} else {
			all_btn = false;
		}
	})
	types = types.substring(0,types.length-1);
	if (all_btn)
	{
		$('#select_all_btn').addClass("active");
	}
	else
	{
		$('#select_all_btn').removeClass("active");
	}
	if (none_btn)
	{
		$('#select_none_btn').addClass("active");
	}
	else
	{
		$('#select_none_btn').removeClass("active");		
	}
}

$(document).ready(function(){
	datenow = cT.getFullYear() + '-' + (cT.getMonth()+1) + '-' +  cT.getDate(); 
	datevalue = datenow;

	for (var i = 1; i <= 2; i++)
	{
		institution_icons[i - 1] = new GIcon();
		institution_icons[i - 1].image = "/images/map_icons/" + i.toString() + "_inst.png";
		institution_icons[i - 1].iconSize = new GSize(30, 30);
		institution_icons[i - 1].iconAnchor  = new GPoint(15, 15);
	}
	
	cluster_icon_found = new GIcon();
	cluster_icon_found.image = "/images/map_icons/cluster_found.png";
	cluster_icon_found.iconSize = new GSize(35, 35);
	cluster_icon_found.iconAnchor = new GPoint(16, 16);
	
	cluster_icon_lost = new GIcon();
	cluster_icon_lost.image = "/images/map_icons/cluster_lost.png";
	cluster_icon_lost.iconSize = new GSize(35, 35);
	cluster_icon_lost.iconAnchor = new GPoint(16, 16);
	
	cluster_icon_multi = new GIcon();
	cluster_icon_multi.image = "/images/map_icons/cluster_multi.png";
	cluster_icon_multi.iconSize = new GSize(35, 35);
	cluster_icon_multi.iconAnchor = new GPoint(16, 16);

	cluster_icon_police = new GIcon();
	cluster_icon_police.image = "/images/map_icons/2_inst_cluster.png";
	cluster_icon_police.iconSize = new GSize(35, 35);
	cluster_icon_police.iconAnchor = new GPoint(16, 16);

	
	map = new GMap2($("#map").get(0));
	map.enableScrollWheelZoom();
//	map.enableContinuousZoom();

	map.addControl(new GLargeMapControl3D(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10))); 
	
	map.setCenter(GLatLng.fromUrlValue(latlng0), zoom0);

	G_PHYSICAL_MAP.getMinimumResolution = function () { return 2 };
	G_NORMAL_MAP.getMinimumResolution = function () { return 2 };
	G_SATELLITE_MAP.getMinimumResolution = function () { return 2 };
	G_HYBRID_MAP.getMinimumResolution = function () { return 2 }; 

	G_PHYSICAL_MAP.getMaximumResolution = function () { return 19 };
	G_NORMAL_MAP.getMaximumResolution = function () { return 19 };
	G_SATELLITE_MAP.getMaximumResolution = function () { return 19 };
	G_HYBRID_MAP.getMaximumResolution = function () { return 19 }; 
	
	
	hoverLabel = new ELabel(new GLatLng(0, 0), '', "elabel", new GSize(0,-16));
	hoverLabel.hide();
	map.addOverlay(hoverLabel);

	GEvent.addListener(map, "hover", function(point, label) { 
		hoverLabel.setPoint(point);
		hoverLabel.setContents('<table><tr><td>' + htmlspecialchars(label) + '</td></tr></table>');
		hoverLabel.show();
	});
	GEvent.addListener(map, "hover-off", function(point) { 
		hoverLabel.hide();
	});

	prevzoom = map.getZoom();
	update_item_types_list();
	UpdateMap();
	
	$('#select_all_btn').click(function () {
		$('.main_tab_small_box a').each(function(){
			$(this).addClass('active');
		});
		update_item_types_list();
		UpdateMap();
		return false;
	});
	
	$('#select_none_btn').click(function () {
		$('.main_tab_small_box a').each(function(){
			$(this).removeClass('active');
		});
		update_item_types_list();
		UpdateMap();
		return false;
	});
	
	$('#option_menu ul.tabs-nav a').click(function () {
		
		if(this.hash == '#frag-all'){
			classifications = 'lost,found';
			UpdateMap();
		}
		if(this.hash == '#frag-found'){
			classifications = 'found';
			UpdateMap();
		}
		if(this.hash == '#frag-lost'){
			classifications = 'lost';
			UpdateMap();
		}

		$('#option_menu ul li a').removeClass('tabs-selected');
		$(this).addClass('tabs-selected');

		return false;

	});
	$('.main_tab_small_box a').click(function(){
		$('.main_tab_small_box a').each(function(){
			$(this).removeClass('active');
		});
		$(this).addClass('active');

		update_item_types_list();
		UpdateMap();					
	});
	
	function UpdateMap(){
		if (sleeping) {
			pending = true;
			return;
		}
		
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();

		var lng_span = (northEast.lng() - southWest.lng() + 360) % 360;
		var lat_span = northEast.lat() - southWest.lat();
		
		var max_lng = (northEast.lng() + lng_span * 0.5 + 540) % 360 - 180;
		var min_lng = (southWest.lng() - lng_span * 0.5 + 540) % 360 - 180;

		var max_lat = Math.min(85, northEast.lat() + lat_span * 0.5);
		var min_lat = Math.max(-85, southWest.lat() - lat_span * 0.5);

		if (lng_span * 2 > 360)
		{
			min_lng = -180;
			max_lng = 180;
		}

		var zoom = map.getZoom();
		if (zoom != prevzoom)
		{
			clickedCluster = 0;
			prevzoom = zoom;
		}
		var postbackURL = "/scripts/items/?min_longitude=" + min_lng + "&max_longitude=" + max_lng + "&min_latitude=" + min_lat + "&max_latitude=" + max_lat + "&types=" + types + "&classifications=" + classifications + "&date=" + datevalue + "&margin=" + daymargin + "&zoom=" + zoom + "&expand=" + clickedCluster + "&latlng=" + map.getCenter().toUrlValue() + "&format=JSON";
		$.get(postbackURL, function(strJSON) {
			var objItem = $.parseJSON(strJSON);
			var newmarkers = [];
			switch (objItem.result)
			{
				case 'zoom':
					map.setCenter(clickedClusterLatLng, Math.min(19, map.getZoom() + 2));
					return; // no timeout
				case 'ok':
					var markers = objItem.data;

					for (var i = 0; i < markers.length; i++) {

						var itemid = markers[i].id;
						var key = 'id' + '_' + markers[i].category + '_' + itemid;

						var lng = parseFloat(markers[i].longitude);
						var lat = parseFloat(markers[i].latitude);
						var point = new GLatLng(lat,lng);
						
						// insert the missing markers (new - old)
						if (typeof(gmarkers[key]) == 'undefined')
						{
							var classification = markers[i].classification;
							var type = markers[i].type;
							var category = markers[i].category;
							
							var marker;
							
							switch (category) {
							case 'c':
								marker = createCluster(itemid,point,parseInt(markers[i].count),classification);
								break;
							case 'l':
								marker = createInstitution(itemid, point, type, markers[i].name, parseInt(markers[i].count));
								break;
							case 'i':
								var name = markers[i].name;
								if (name.length > 19)
								{
									name = name.substring(0, 19) + '...';
								}
								marker = createMarker(itemid, point, type, classification, name);
								break;
							}
							

							map.addOverlay(marker);
							
							newmarkers[key] = marker;
						}
						else
						{
							newmarkers[key] = gmarkers[key];
							if (gmarkers[key].type == 'cluster')
							{
								var countLabel = getCountStr(markers[i].count);
								gmarkers[key].setLabelText(countLabel);
							}
							gmarkers[key].setPoint(point);
						}
					}
					break;
			}
			//remove the obsolete markers (old - new)
			for (var key2 in gmarkers)
			{
				if (key2 != "in_array")
				{
					if (typeof(newmarkers[key2]) == 'undefined')
					{
						map.removeOverlay(gmarkers[key2]);
						GEvent.removeListener(gmarkers[key2].listener);
					}
				}
			}
			gmarkers = newmarkers;

			sleeping = true;
			timer = setTimeout(function () {
				timeout();
			}, 500);

		});
	}
	
	function timeout()
	{
		sleeping = false;
		if (pending)
		{
			UpdateMap();
			pending = false;			
		}
	}
	
	function getCountStr(count)
	{
		if (count == 0)
		{
			return "";
		}
		if (count < 1000)
		{
			return count.toString();
		}
		if (count >= 1000)
		{
			return parseInt(count / 1000) + 'k+';
		}
	}
	
	function createCluster(id,point,count,classification) {
		var countLabel = getCountStr(count);
		var icon;

		switch (classification)
		{
			case 'lost': icon = cluster_icon_lost;break;
			case 'found': icon = (count > 0 ? cluster_icon_found : cluster_icon_police);break;
			case 'both': icon = cluster_icon_multi;break;
		}
		
		var cluster = new LabeledMarkerLight(point, icon, countLabel, "-3px", "8px", "", -20000, "white");		
		cluster.type = 'cluster';

		cluster.listener = GEvent.addDomListener(cluster, "click", function() {
			clickedClusterLatLng = point;
			clickedCluster = id;
			UpdateMap();
		});
		return cluster;
	}

	function createInstitution(id, point, type, name, count) {
		var countLabel = getCountStr(count);
		
		var marker = new LabeledMarkerLight(point, institution_icons[type - 1], countLabel, "0px", "16px", name, -20000, "white");		
		marker.type = 'cluster';
		
		marker.listener = GEvent.addListener(marker, "click", function() {
			window.location = url_prefix + '/location/' + id + '/';
		});
		return marker;
	}

	function createMarker(id,point,itemtype,classification,name) {
		var marker = new MarkerLight(point, classification == 'found' ? found_icons[itemtype] : lost_icons[itemtype], name, -10000);
		marker.type = 'marker';

		marker.listener = GEvent.addListener(marker, "click", function() {
			window.location = url_prefix + '/item/' + id + '/';
		});
		return marker;
	}
	//move event
	GEvent.addListener(map, "moveend", function() {
		UpdateMap();
	});

	var timer2;
	var geocoder = new GClientGeocoder();
	$("#map_street_search").keyup(function(event){
		if($(this).val().length < 3) return false;
		var search = $(this).val();

		clearTimeout(timer2);
		$('#loader-streetsearch-map').show();
		if ((event.which && event.which == 13))
		{
			geocoder.getLocations(search, findLatLng);				
		}
		else
		{
			timer2 = setTimeout(function () { // delayta
				geocoder.getLocations(search, findLatLng);
				}, 1000);
		}
	});

	var findLatLng = function(response) {
		$('#loader-streetsearch-map').hide();
		if (response && (response.Status.code == 200)) {
			var place = response.Placemark[0];
			try{var error_wakeup = place.AddressDetails.Country.CountryNameCode;}catch(err){return false;} //??? undefined problem			

			var latlng = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			var zoom;
			switch (place.AddressDetails.Accuracy)
			{
				case 0: zoom = 2; break;
				case 1: zoom = 4; break;
				case 2: zoom = 6; break;
				case 3: zoom = 8; break;
				case 4: zoom = 11; break;
				case 5: zoom = 13; break;
				case 6: zoom = 15; break;
				case 7: zoom = 16; break;
				case 8: zoom = 17; break;
				case 9: zoom = 17; break;
			}
			map.setCenter(latlng, zoom);
		}
	}
	
	$("#map_street_search").focus(function(){
		$(this).val("");
	});
	
});

var createIcon = function(image){
	var Icon = new GIcon();
	Icon.image = image;
	Icon.iconSize = new GSize(30, 30);
	Icon.iconAnchor = new GPoint(15, 15);
	return Icon;
}
