var trackme_class = application.extend({
	init : function(p,h) {
		this.line = false;
		this.user = false;
		this.track_to = false;
		this._super(p,h);
	},
	end : function () {
		try { 
			Rimory.map.instance.removeOverlay(this.line);
			this.line = false;
		} catch (e) { };
		if(this.track_to) clearTimeout(this.track_to);
		Rimory.map.rem_marker_group("trace");
		return this._super();
	},
	map_click : function (lat, lng, title, icon, id, opts, group, mrk) {
		if(group == "trace") {
			Rimory.map.show_bubble(new GLatLng(lat,lng), { 
				title		: lat + "<br />" + lng, 
				url			: "/app/trackme/" + this.user + "/" + id, 
				callback	: function () { 
					Rimory.map.geocoder.getLocations(new GLatLng(lat,lng), function(data) {
						if(data.Status.code == 200) { $("#addr").html(data.Placemark[0].address); }
					}); 
				}
			});
		}
		else this._super(lat, lng, title, icon, id, opts, group, mrk);
	},
	trace : function(cb) {
		this.user = $('#uu').val();
		var _this = this;
		$.post("/app/trackme/" + this.user, { 'p' : $('#up').val() }, function (data) {
			if(typeof data != "object" && data == "ERROR") return Rimory.error("Login incorrect", true);
			$("#tr_tr").hide();
			$("#tr_st").show();
			$("#tr_login").slideUp();
			$("#tr_settings").slideDown();
			Rimory.map.rem_marker_group("trace");
			try { Rimory.map.instance.removeOverlay(this.line); } catch(e) { }
			this.line = false;

			var last_lng = false;
			var last_lat = false;
			var s = $("Point coordinates", data).size();
			$("Point coordinates", data).each( function (i) {
				var tmp = $(this).text().split(",");
				if(tmp[0] === last_lng && tmp[1] === last_lat) return;
				Rimory.map.instance.addOverlay(Rimory.map.add_marker(tmp[1], tmp[0], "", (i == (s - 2) ? "track_end" : "track_one"), $(this).parents("Placemark:eq(0)").children("description").text().split("|")[0].split(":")[1], {}, "trace"));
				last_lng = tmp[0];
				last_lat = tmp[1];
			});
			_this.line = Rimory.map.draw_line("trace");
			Rimory.map.instance.addOverlay(_this.line);
			_this.get_distance();
			if(!cb || $("#keep_on_screen").is(":checked")) Rimory.map.zoom_to_group("trace");
			_this.track_to = setTimeout(function() { _this.trace(true); }, 5000);
		});
	},
	stop : function () {
		$("#tr_tr").show();
		$("#tr_st").hide();
		$("#tr_settings").slideUp();
		$("#up, #uu").val("");
		$("#tr_login").slideDown();
		if(this.track_to) clearTimeout(this.track_to);
		try { Rimory.map.instance.removeOverlay(this.line); } catch(e) { }
		Rimory.map.rem_marker_group("trace");
		this.line = false;
	},
	get_distance : function (route) {
		var l = route ? this.line.getDistance().meters : this.line.getLength();
		l = (l/1000).toFixed(3);
		$("#route_length").html(l + "km");
	}
});
Rimory.inst.trackme = new trackme_class();
