if((typeof Rimory).toLowerCase() == "undefined") Rimory = {};
if((typeof Rimory.map).toLowerCase() == "undefined") Rimory.map = {};

// ИНЦИАЛИЗАЦИЯ НА КАРТАТА
Rimory.map.init = function (dom_node) {
	if (!GBrowserIsCompatible()) return Rimory.error("Несъвместим браузър", true);

	Rimory.map.geocoder	= new GClientGeocoder();
	Rimory.map.instance	= new GMap2(dom_node, { backgroundColor : "white" });

	// Конфигурация на картата
	var map = Rimory.map.instance;
	// Default център - картата ще бъде тук, ако няма Hash, Cookie Hash и IP локацията не проработи
	map.setCenter(new GLatLng(20.0,20.0), 2);
	map.addMapType(G_PHYSICAL_MAP);
	// Контрол на zoom
	map.enableScrollWheelZoom();
	map.disableDoubleClickZoom();
	var mapTypes = map.getMapTypes();
	for (var i=0; i<mapTypes.length; i++) { mapTypes[i].getMinimumResolution = function() { return 2; } };
	
	// Добавяне на интерфейса на картата
	var boxStyleOpts = { opacity: .2, border: "2px solid gray" };
	var otherOpts = {
		buttonHTML: "<img src='/_img/zoom-control-inactive.png' />",
		buttonZoomingHTML: "<img src='/_img/zoom-control-active.png' />",
		buttonStartingStyle: {width: '17px', height: '17px'},
		overlayRemoveTime: 0 
	};
	map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(27,7)));
	map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,32)));
	//map.addControl(new GOverviewMapControl ());
	map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(66,5)));
	map.addControl(new GScaleControl()); 
	// Използваме си наши прозорци
	map.disableInfoWindow();
	// Използва се за запазване на центъра при двоен клик
	Rimory.map.center = map.getCenter();
	
	// Реклами от Adsense
	//Rimory.map.ads = new GAdsManager(Rimory.map.instance, "pub-1406407145771483", { maxAdsOnMap : 50 });
	//Rimory.map.ads.enable();

	// Центриране
	if(Rimory.hash && Rimory.hash.center && Rimory.hash.zoom) {
		map.setCenter(new GLatLng(Rimory.hash.center[0],Rimory.hash.center[1]), Rimory.hash.zoom);
	}
	// Зареждаме earth API-то и позиционираме по IP
	google.load("search", "1", { "callback" : function () { 
			if((!Rimory.hash || !Rimory.hash.center || !Rimory.hash.zoom) && google.loader.ClientLocation) {
				map.setCenter(new GLatLng(google.loader.ClientLocation.latitude,google.loader.ClientLocation.longitude), 10);
			}
		}});

	// Eвенти
	GEvent.addListener(map, "click",	Rimory.map.map_click);
	GEvent.addListener(map, "moveend",	function () { Rimory.map.center = Rimory.map.instance.getCenter(); Rimory.map.getHash(); Rimory.map.view_change(); });
	GEvent.addListener(map, "dragstart",function () { Rimory.map.hide_bubble(); });
	GEvent.addListener(map, "zoomend",	function () { Rimory.map.hide_bubble(); Rimory.map.getHash(); /* Rimory.map.view_change(); */ });
	GEvent.addListener(map, "dblclick",	function (overlay, latlng) { 
		Rimory.map.instance.setCenter(Rimory.map.center); 
		Rimory.map.show_bubble(latlng, { 
			title		: latlng.lat() + "<br />" + latlng.lng(), 
			url			: "/location_summary/" + latlng.lat() + "," + latlng.lng(), 
			callback	: function () { 
				Rimory.map.geocoder.getLocations(latlng, function(data) {
					if(data.Status.code == 200) { $("#addr").html(data.Placemark[0].address); }
				}); 
			}
		});
	});
}

// Hash управление
Rimory.map.parseHash = function (str) {
	var hsh = str || $.cookie("hash") || document.location.hash ;
	if(hsh && hsh.length > 5 && hsh.charAt(1) != "/") return eval("(" +  Base64.decode(hsh) + ")");
	else return {};
}
Rimory.map.getHash = function (url) {
	// Събиране на данни (може би с клас - "hash"?)
	var str = "";
	str += "{ ";
	str += "center : [ " + Rimory.map.instance.getCenter().lat() + " , " + Rimory.map.instance.getCenter().lng() + " ], ";
	str += "zoom : " + Rimory.map.instance.getZoom() + ", ";
	if($(".context").size() > 0) {
		str += "maincat : '" + $("#categories").find("a:eq(0)").attr("class") + "', ";
		str += "cats : [ '0' ";
		$("#categories > ul").find("a.checked").each(function () { str += ", '" + $(this).attr("rel") + "' "; });
		str += "],";
		str += "maincat2 : '" + $("#my_lists").find("a:eq(0)").attr("class") + "', ";
		str += "cats2 : [ '0' ";
		$("#my_lists > ul").find("a.checked").each(function () { str += ", '" + $(this).attr("rel") + "' "; });
		str += "]";
	}
	else {
		tmp = Rimory.map.parseHash();
		str += "maincat : '" + tmp.maincat + "', ";
		str += "cats : [";
		str += tmp.cats.join(",");
		str += "],";
		str += "maincat2 : '" + tmp.maincat2 + "', ";
		str += "cats2 : [";
		str += tmp.cats2.join(",");
		str += "]";
	}
	//str += "beg : '" + parseInt($("#progress").css("left")) + "',";
	//str += "wid : '" + parseInt($("#progress").width()) + "' ";
	if(url) str += ", url : '" + url + "'";
	else {
		if(Rimory.ui && Rimory.ui.url) str += ", url : '" + Rimory.ui.url + "'";
	}
	str += " }";
	str = Base64.encode(str);

	jQuery.cookie("hash",str);

	return str;
}

// Управление на балони
Rimory.map.show_bubble = function (latlng, opts) {
	if(!latlng)	return false;
	if(!opts)	opts = {};
	var tmp = Rimory.map.instance.fromLatLngToContainerPixel(latlng);
	$("#tip")
		.css({ "left" : (234 + parseInt(tmp.x) - 10) + "px", "bottom" : (530 - tmp.y) + "px" })
		.html("<img class='arrow' src='/_img/bubble/arrow.gif' alt='' /><a href='#' onclick='$(\"#tip\").html(\"\").hide(); return false;' class='close'>&nbsp;</a><b id='addr'>" + opts.title + "</b><div id='details'>" + (opts.content || "") + "</div>")
		.show();
	if(opts.url) {
		Rimory.map.fix_bubble_position();
		$("#details").load(opts.url , function () { 
			Rimory.map.fix_bubble_position(); 
			if(opts.callback) opts.callback.call(); 
		});
	}
	else {
		Rimory.map.fix_bubble_position();
		if(opts.callback) opts.callback.call();
	}
};
Rimory.map.hide_bubble = function () { $("#tip").html("").hide(); };
Rimory.map.fix_bubble_position = function () {
	var bubble = $("#tip");
	var offset = bubble.offset();

	if(bubble.width() + offset.left > $("body").width()) {
		var tmp = $("body").width() - (bubble.width() + offset.left + 2);
		bubble.css({ "left" : parseInt(bubble.css("left")) + tmp }).children(".arrow").css("left", (15 - tmp) );
	}
	if(offset.top < 52) {
		var tmp = offset.top - 53;
		Rimory.map.instance.panBy( new GSize(0, tmp*-1) );
		bubble.css({ "bottom" : parseInt(bubble.css("bottom")) + tmp });
	}
};

// Маркери
Rimory.map.markers = {};
Rimory.map.add_marker_group = function (str) {
	if(!Rimory.map.markers[str])	return Rimory.map.markers[str] = [];
	else							return Rimory.error("Вече има такава група маркери");
};
Rimory.map.rem_marker_group = function (str) {
	if(Rimory.map.markers[str]) {
		for(i in Rimory.map.markers[str]) {
			try { Rimory.map.markers[str][i].remove(); } catch (e) { Rimory.error("Премахваният маркер не съществува"); }
		}
		delete Rimory.map.markers[str];
		return true;
	}
	else return Rimory.error("Няма такава група маркери");
};
Rimory.map.rem_all_markers = function () {
	for(group in Rimory.map.markers) Rimory.map.rem_marker_group(group);
};
Rimory.map.zoom_to_group = function (group, rect) {
	if(!Rimory.map.markers[group]) return Rimory.error("Няма такава група маркери");
	if(!rect) var rect = new GLatLngBounds();
	for(i in Rimory.map.markers[group]) {
		rect.extend(Rimory.map.markers[group][i].getLatLng());
	}
	Rimory.map.instance.setCenter(rect.getCenter(),Rimory.map.instance.getBoundsZoomLevel(rect));
	return rect;
};
Rimory.map.add_marker = function(lat, lng, title, icon, id, opts, group) {
	var ltl = new GLatLng(lat,lng);
	opts = jQuery.extend({}, opts, { title: title, icon: Rimory.map.icons[icon] });
	var mrk = new GMarker(ltl, opts);
	GEvent.addListener(mrk, "click", function(latlng) { Rimory.map.marker_click(lat, lng, title, icon, id, opts, group, mrk); });
	if(group) {
		if(!Rimory.map.markers[group]) Rimory.map.add_marker_group(group);
		Rimory.map.markers[group].push(mrk);
	}
	return mrk;
};

// Търсене
Rimory.map.search = function (str) {
	Rimory.map.search_result = 0;

	Rimory.map.rem_marker_group("search");
	Rimory.map.hide_bubble();
	Rimory.map.geocoder.getLocations(str, function(data) {
		if(data.Status.code == 200) {
			try { pageTracker._trackPageview("/search"); } catch (err) { Rimory.error("Грешка при извикване на Analytics"); }

			if($("#view_panel > .content").children("ul").size() == 0) $("#view_panel > .content").append("<ul></ul>");

			jQuery.each(data.Placemark, function(i,item) {
				Rimory.map.instance.addOverlay(Rimory.map.add_marker(item.Point.coordinates[1],item.Point.coordinates[0],item.address,"search", false, false, "search"));

				$("#view_panel > .content > ul").append('<li class="address" onclick="/*window.parent.Rimory.map.instance.setCenter(new GLatLng(' + item.Point.coordinates[1] + ',' + item.Point.coordinates[0] + ')); window.parent.Rimory.map.max_zoom(' + item.Point.coordinates[1] + ',' + item.Point.coordinates[0] + ',2);*/ window.parent.Rimory.inst._basic.map_click(' + item.Point.coordinates[1] + ',' + item.Point.coordinates[0] + ',\'\',false,false,false,\'search\');" style="cursor: pointer;"><strong>' + item.address + '</strong><span class="latlng">' + item.Point.coordinates[1].toFixed(6) + ', ' + item.Point.coordinates[0].toFixed(6) + '</span></li>');

			});
			Rimory.map.zoom_to_group("search");
		}
		else {
			Rimory.map.search_result ++;
			if(Rimory.map.search_result == 2) Rimory.error("Няма намерени резултати", true);
		}
	});

	var q = $("#q").val().replace("Търси","");
	if(q.length > 3) {
		var url = "/search_poi/";
		var tmp = Rimory.map.instance.getBounds();
		url += tmp.getSouthWest().lat() + "," + tmp.getSouthWest().lng() + ",";
		url += tmp.getNorthEast().lat() + "," + tmp.getNorthEast().lng();
		$.ajax({
			type		: "post",
			url			: url, 
			data		: { search : q }, 
			dataType	: "json",
			success		: function (data) {

				if($("#view_panel > .content").children("ul").size() == 0) $("#view_panel > .content").append("<ul></ul>");

				for(i in data) {
					Rimory.map.instance.addOverlay(Rimory.map.add_marker(data[i].pos[1], data[i].pos[0], data[i].name, "search", data[i].id, false, "search"));

					$("#view_panel > .content > ul").prepend('<li onclick="/*window.parent.Rimory.map.max_zoom(' + data[i].pos[1] + ',' + data[i].pos[0] + ',2); */window.parent.Rimory.inst._basic.map_click(' + data[i].pos[1] + ',' + data[i].pos[0] + ',\'\',false,' + data[i].id + ');" style="cursor: pointer;"><strong>' + data[i].name + '</strong><span class="latlng">' + data[i].pos[1].toFixed(6) + ', ' + data[i].pos[0].toFixed(6) + '</span></li>');

				}
				if(data.length == 0) {
					Rimory.map.no_result ++;
					if(Rimory.map.no_result == 2) Rimory.error("Няма намерени резултати", true);
				}
				Rimory.map.zoom_to_group("search");
			} 
		});
	}
	
};

// Изчертай линия
Rimory.map.draw_line = function (group, opts) {
	opts = jQuery.extend({ color : "#0000aa", width : 3, alpha : 0.7}, opts);
	var points = [];
	for(i in Rimory.map.markers[group]) points.push(Rimory.map.markers[group][i].getLatLng());
	return new GPolyline(points, opts.color, opts.width, opts.alpha);
};
// Изчертай маршрут
Rimory.map.draw_route = function (group, opts) {
	opts = jQuery.extend({ getPolyline : true, preserveViewport : true, avoidHighways : false, travelMode : G_TRAVEL_MODE_WALKING }, opts);
	var points = [];
	for(i in Rimory.map.markers[group]) points.push(Rimory.map.markers[group][i].getLatLng());
	var poly = new GDirections(Rimory.map.instance, document.getElementById("directions"));
	GEvent.addListener(poly, "addoverlay", function() {
		for(var i = 0; i < points.length; i++) {
			poly.getMarker(i).remove();
		}
	});
	GEvent.addListener(poly, "error", function() {
		Rimory.error("Не е намерен маршрут между точките", true);
	});
	poly.loadFromWaypoints(points, opts);
	return poly;
};

// Евенти
Rimory.map.map_click	= function(overlay, point) {
	if(overlay) return true;
	Rimory.inst[Rimory.map.state].map_click.apply(Rimory.inst[Rimory.map.state], [point.lat().toFixed(6), point.lng().toFixed(6)]);
};
Rimory.map.marker_click	= function() { 
	Rimory.inst[Rimory.map.state].map_click.apply(Rimory.inst[Rimory.map.state], arguments);
};
Rimory.map.view_change	= function() { 
	Rimory.inst[Rimory.map.state].view_change.apply(Rimory.inst[Rimory.map.state], arguments);
};


Rimory.map.max_zoom = function (lat, lng, off) {
	if(!off) off = 0;
	Rimory.map.instance.setCenter(
		new GLatLng(lat,lng), 
		(Rimory.map.instance.getBoundsZoomLevel(
			new GLatLngBounds(new GLatLng(lat,lng),GLatLng(lat,lng)), 
			new GSize($(Rimory.map.instance.getContainer()).width() , $(Rimory.map.instance.getContainer()).height()) 
		) - off)
	); 
};