var ignore_timestamp = false;

function get_event_type(reportType, reportValue)
{
	var range = "";
	switch(reportType)
	{
		case "report": return "Location Report";
		case "checkin": return "Check-In";
		case "obd_report": return "OBD Diagnostic Report";
		case "sos": return "SOS Report";
		case "crash": return "Crash Report";
		case "gprs_on": return "GPS connected to GPRS";
		case "temperature_low": return "Temperature is Low (" + reportValue +"°C)"; //todo other temperature scales
		case "temperature": return "Temperature is Normal (" + reportValue +"°C)";
		case "temperature_high": return "Temperature is High (" + reportValue +"°C)";
		case "jamming": return "GPS Jammer Warning";
		case "low_battery": return "Low Battery";
		case "low_external_battery": return "Low External Battery";
		case "external_power_voltage":
			{
				switch(reportValue)
				{
					case "0": return "External Power Failure";
					case "1": return "External Power Restored";
				}
			} break;
		case "external_power_state":
			{
				switch(reportValue)
				{
					case "1": return "External Power Connected";
					case "0": return "External Power Removed";
				}
			} break;

		case "battery_state":
			{
				switch(reportValue)
				{
					case "charging": return "Battery Charging Started";
					case "discharging": return "Battery Charging Stopped";
					case "low_battery": return "Low Battery";
				}
			} break;
		case "driving_behavior":
			{
				switch(reportValue)
				{
					case "harsh_brake": return "Harsh braking";
					case "harsh_accelerate": return "Harsh Acceleration";
					case "harsh_turn": return "Harsh Turn";
					case "harsh_brake_turn": return "Harsh Breaking and Turn";
					case "harsh_accelerate_turn": return "Harsh Acceleration and Turn";
					case "harsh_unknown": return "Unknown Harsh Behavior";
				}
			} break;
		case "device_state":
			{
				switch(reportValue)
				{
					case "start": return "Device Turned On";
					case "stop": return "Device Turned Off";
					case "reboot": return "Device Reboots";
				}
			} break;
		case "external_antenna":
			{
				switch(reportValue)
				{
					case "ok": return "GPS Antenna Ok";
					case "cut": return "GPS Antenna Cut";
					case "unknown": return "GPS Antenna Failure";
				}
			} break;
		case "ignition":
			{
				switch(reportValue)
				{
					case "0": return "Ignition Off";
					case "1": return "Ignition On";
				}
			} break;
		case "device_idle_state":
			{
				switch(reportValue)
				{
					case "0": return "GPS is Idle";
					case "1": return "GPS is Moving";
				}
			} break;
		case "obd_state":
			{
				switch(reportValue)
				{
					case "0": return "OBD connection Established";
					case "1": return "OBD connection Terminated";
				}
			} break;
		case "obd_range_inside":
			{
				range = " is in the range";
				switch(reportValue)
				{
					case "engine_rpm": return "Engine RPM" + range;
					case "vehicle_speed": return "Vehicle Speed" + range;
					case "engine_coolant_temp": return "Engine Coolant Temperature" + range;
					case "fuel_consumption": return "Fuel Consumption" + range;
					case "mil_status": return "MIL status" + range;
					case "dtc_number": return "Number of DTCs" + range;
					case "throttle_position": return "Throttle Position" + range;
					case "engine_load": return "Engine Load" + range;
					case "fuel_level_input": return "Fuel Level Input" + range;
				}
			} break;
		case "obd_range_outside":
			{
				range = " is out of range";
				switch(reportValue)
				{
					case "engine_rpm": return "Engine RPM" + range;
					case "vehicle_speed": return "Vehicle Speed" + range;
					case "engine_coolant_temp": return "Engine Coolant Temperature" + range;
					case "fuel_consumption": return "Fuel Consumption" + range;
					case "mil_status": return "MIL status" + range;
					case "dtc_number": return "Number of DTCs" + range;
					case "throttle_position": return "Throttle Position" + range;
					case "engine_load": return "Engine Load" + range;
					case "fuel_level_input": return "Fuel Level Input" + range;
				}
			} break;
		case "motion_state":
			{
				switch(reportValue)
				{
					case "start": return "Motion Started";
					case "stop": return "Motion Stopped";
					case "long_stop": return "Long Time Parking";

				}
			} break;
		case "movement_state":
			{
				switch(reportValue)
				{
					case "towing": return "Towing Report";
					case "ignition_off_rest": return "Ignition Off - Rest";
					case "ignition_off_motion": return "Ignition Off - Motion";
					case "ignition_on_rest": return "Ignition On - Rest";
					case "ignition_on_motion": return "Ignition On - Motion";
					case "sensor_rest": return "Sensor - Rest";
					case "sensor_motion": return "Sensor - Motion";
				}
			} break;
		case "gps_fix":
			{
				switch(reportValue)
				{
					case "0": return "GPS position fix failed";
					case "1": return "GPS position fixed";
				}
			} break;
		case "job_state":
			{
				switch(reportValue)
				{
					case "completed": return "Job completed";
					case "incomplete": return "Job not completed";
				}
			} break;
		case "input_1":
			{
				switch(reportValue)
				{
					case "0": return "Input 1 - Off";
					case "1": return "Input 1 - On";
				}
			} break;
		case "input_2":
			{
				switch(reportValue)
				{
					case "0": return "Input 2 - Off";
					case "1": return "Input 2 - On";
				}
			} break;
		case "input_3":
			{
				switch(reportValue)
				{
					case "0": return "Input 3 - Off";
					case "1": return "Input 3 - On";
				}
			} break;
		case "input_4":
			{
				switch(reportValue)
				{
					case "0": return "Input 4 - Off";
					case "1": return "Input 4 - On";
				}
			} break;
		case "input_5":
			{
				switch(reportValue)
				{
					case "0": return "Input 5 - Off";
					case "1": return "Input 5 - On";
				}
			} break;
		case "input_6":
			{
				switch(reportValue)
				{
					case "0": return "Input 6 - Off";
					case "1": return "Input 6 - On";
				}
			} break;
		default: return reportType + " - " +reportValue;
	}
}
function Mapping()
{
	var owner = this;

	owner.construct = function()
	{

		owner.pushpinGenerator = new PushpinGenerator();
		owner.view = new L.LatLng(0, 0);
		owner.geojson = null;
		owner.route = [];
		owner.markers = [];
		owner.max_timestamp = 0;
		owner.popup_open = -1;
		owner.autoupdate = true;

		owner.map = L.map('map');
		owner.stored_device_or_group = "";
		owner.stored_device = "";
		owner.stored_group = "";
		owner.stored_single_or_multi = "";
		owner.stored_current = "";

		/*
		owner.Bing = new L.BingLayer("ApNbJQ3u8MKDOfcxXu8_Wos_SFv3heA3NBvHpElFHiyUMYFHg9nEAW6GvOmb3V8j", {type: 'Road'});
		owner.BingSatellite = new L.BingLayer("ApNbJQ3u8MKDOfcxXu8_Wos_SFv3heA3NBvHpElFHiyUMYFHg9nEAW6GvOmb3V8j", {type: 'Aerial'});
		owner.BingHybrid = new L.BingLayer("ApNbJQ3u8MKDOfcxXu8_Wos_SFv3heA3NBvHpElFHiyUMYFHg9nEAW6GvOmb3V8j", {type: 'AerialWithLabels'});
		owner.GoogleTerrain = new L.Google("TERRAIN");
		owner.cloudMade = new L.TileLayer.CloudMade();
		owner.MapBox = new L.TileLayer.MapBox();
		owner.openCycleMap = new L.TileLayer.OpenCycleMap();
		owner.MapQuestOpenOSM = new L.TileLayer.MapQuestOpenOSM();
		owner.MapQuestOpenAerial = new L.TileLayer.MapQuestOpenAerial();
		*/

		owner.openStreetMap = new L.TileLayer.OpenStreetMap();
		owner.Google = new L.Google("ROADMAP");
		owner.GoogleSatellite = new L.Google();
		owner.GoogleHybrid = new L.Google("HYBRID");

		owner.actual_map = owner.Google;
		owner.map.addLayer(owner.actual_map);

		owner.map.setView([0,0],2);
		owner.map.on('popupopen', function(e) {
			owner.popup_open = e.popup._source.number;
			$(".leaflet-popup-close-button").click(function()
			{
				owner.popup_open = -1;
			});
		});

        /*new L.Control.GeoSearch({
            provider: new L.GeoSearch.Provider.Google()
        }).addTo(owner.map);*/
		//owner.map.fitWorld();
		owner.map.attributionControl.setPrefix(false);

		owner.polylineLayer = new L.LayerGroup();
		owner.geojsonLayer = new L.GeoJSON(null,
			{
				onEachFeature:function (feature, layer)
					{
						var content = feature.properties;
						if (content)
							{
								var units = $("#units");
								owner.eventlistGenerator.insert(content);

								var speed = (units.val() == "metric")?((content.speed).toFixed(0) + " km/h"):((content.speed*0.621371192).toFixed(0) + " mph");
								var height = (units.val() == "metric")?((content.alt).toFixed(0) + " m"):((content.alt*3.2808399).toFixed(0) + " ft");
								var popup_data = "<div class='bold uppercase'>" + jQuery.parseJSON(content.name) + "</div>"
									+ "Type:" + get_event_type(content.type)
									+  "<br />" + (new Date(content.date*1000).toLocaleString())
									+ "<br />Lat: " + content.lat
									+ " / Lng: " + content.lng
									+ " / Alt: " + height
									+ "<br />Speed: " + speed
									+ "<br />Heading: " + content.heading + "°";

								if (content.source != undefined)
									popup_data += "<br />Source: " +  ((content.source == "cell")?"wifi/cell":content.source);
								if (content.address != undefined)
									popup_data += "<br />Address: " + content.address;
								if (content.battery != -1)
									popup_data += "<br />Battery Level: " + content.battery;
								if (content.precision != -1)
									popup_data += "<br />Accuracy: " + content.precision;
								if (content.satellites != -1)
									popup_data += "<br />Satellite Count: " + content.satellites;

								layer.bindPopup(popup_data,	{autoPan: false});
							}
					},
				pointToLayer:function (feature, latlng)
					{
						feature.properties.number = owner.i;
						owner.route[owner.i] = latlng;
						owner.markers[owner.i] = owner.pushpinGenerator.get_pushpin(feature, latlng);
						return owner.markers[owner.i++];
					}
			});
	};
	owner.eventlistGenerator = new EventlistGenerator();


$(document).bind("toggle_current", null, function()
	{
		if(document.getElementById('current').value == "false")
			{
				$("#switch_autoupdate_inactive").attr("id","switch_autoupdate_on");
				owner.turn_autoupdate_on();
				document.getElementById('current').value = "true";
				$('.end').datepicker('setDate', new Date());
				$('.start').datetimepicker("option", "maxDateTime", new Date()).datetimepicker("option", "maxDate", new Date());
				$(".end_text").html("Current Time");
			}
		else
			{
				owner.turn_autoupdate_off();
				$("#autoupdate").attr("value","false");
				$("#switch_autoupdate_on, #switch_autoupdate_off").attr("id","switch_autoupdate_inactive");
				document.getElementById('current').value = "false";
				$(".end_text").html($('.end').val());
			}
	});

$("#button_map_submit").click(function()
	{
		owner.submit();
		return false;
	});

$("#switch_autoupdate_on, #switch_autoupdate_off").click(function()
	{
		if ($("#autoupdate").val() == "false")
			{
				owner.turn_autoupdate_on();
			}
		else
			{
				owner.turn_autoupdate_off();
			}
	});

	owner.set_autoupdate = function()
		{
			if(owner.update_interval != "undefined")
				{
					clearInterval(owner.update_interval);
				}

			if (owner.autoupdate == true)
				{
					owner.registerInterval();
				}
		};

	owner.turn_autoupdate_off = function()
		{
			owner.autoupdate = false;
			$("#autoupdate").attr("value","false");
			$("#switch_autoupdate_on").attr("id","switch_autoupdate_off");
			if (typeof owner.update_interval != "undefined")
				clearInterval(owner.update_interval);
		};

	owner.turn_autoupdate_on = function()
		{
			if (owner.autoupdate == false)
				{
					owner.autoupdate = true;
					$("#autoupdate").attr("value","true");
					$("#switch_autoupdate_off").attr("id","switch_autoupdate_on");
					owner.registerInterval();
				}

		};

	owner.registerInterval = function()
		{
			if (owner.stored_device_or_group == "device" || owner.stored_device_or_group == "group")
				owner.update_interval = setInterval(function ()
				{
					owner.update_map();
					var element = $("table.eventlist");
					if (element.html() != owner.eventlistGenerator.create())
						{
							var scroll = $(element).scrollTop();
							element.html(owner.eventlistGenerator.create()).scrollTop(scroll);
						}
				}, 5000);
		};

	$("#switch_focus").change( function()
	{
		if (owner.map.hasLayer(owner.geojsonLayer) || owner.map.hasLayer(owner.polylineLayer))
			{
				if (owner.focus() == "all")
					{
						var bounds = owner.geojsonLayer.getBounds();
						if (bounds.isValid(bounds))
							owner.map.whenReady(function () {

								window.setTimeout(function () {
									owner.map.fitBounds(bounds, {padding: [50, 50]});
								}.bind(this), 200);
							}, this);
					}
				else if (owner.focus() == "last")
					{
						owner.map.setView(owner.view, 16);
					}
				else if (owner.focus() == "none")
					{

					}
			}
	});

	$("#switch_map").change( function()
	{
		owner.map.hasLayer(owner.actual_map);
			owner.map.removeLayer(owner.actual_map);
		/*if (owner.getMap() == "Bing")
			owner.actual_map = owner.Bing;
		else if (owner.getMap() == "BingSatellite")
			owner.actual_map = owner.BingSatellite;
		else if (owner.getMap() == "BingHybrid")
			owner.actual_map = owner.BingHybrid;

 		else */if (owner.getMap() == "Google")
			owner.actual_map = owner.Google;
		else if (owner.getMap() == "GoogleSatellite")
			owner.actual_map = owner.GoogleSatellite;
		else if (owner.getMap() == "GoogleHybrid")
			owner.actual_map = owner.GoogleHybrid;
		/*else if (owner.getMap() == "GoogleTerrain")
			owner.actual_map = owner.GoogleTerrain;*/
		else if (owner.getMap() == "openStreetMaps")
			owner.actual_map = owner.openStreetMap;

		owner.map.addLayer(owner.actual_map);
		if ((owner.getMap() == "Bing" || owner.getMap() == "BingSatellite" || owner.getMap() == "BingHybrid") && owner.geojson == null)
			owner.map.setView(owner.view, 2);

	});

	$("#routes").change( function()
	{

		if ($("#routes").is(':checked'))
			{
				if (typeof owner.polylineLayer != "undefined")// && !owner.map.hasLayer(owner.polylineLayer))
					{
						owner.map.addLayer(owner.polylineLayer);
					}
			}
		else
			{
				if (typeof owner.polylineLayer != "undefined")  // && owner.map.hasLayer(owner.polylineLayer))
					{
						owner.map.removeLayer(owner.polylineLayer);
					}
			}
	});

	$("#pushpins").change( function()
	{
		if ($("#pushpins").is(':checked'))
			{
				if (typeof owner.geojsonLayer != "undefined")
					{
						owner.map.addLayer(owner.geojsonLayer);
					}
			}
		else
			{
				if (typeof owner.geojsonLayer != "undefined")
					{
						owner.map.removeLayer(owner.geojsonLayer);
					}
			}
	});

	owner.device = function()
		{
			if(document.getElementById('device'))
				return document.getElementById('device').value;
			else return null;
		};

	owner.focus = function()
		{
			if(document.getElementById('switch_focus'))
				return document.getElementById('switch_focus').value;
			else return null;
		};

	owner.getMap = function()
		{
			if(document.getElementById('switch_map'))
				return document.getElementById('switch_map').value;
			else return null;
		};

	owner.group = function()
		{
			if(document.getElementById('group'))
				return document.getElementById('group').value;
			else return null;
		};
	owner.device_or_group = function()
		{
			if(document.getElementById('switch_device_or_group'))
				return document.getElementById('switch_device_or_group').value;
			else return null;
		};

	owner.single_or_multi = function()
		{
			if(document.getElementById('switch_single_or_multi'))
				return document.getElementById('switch_single_or_multi').value;
			else return null;
		};

	owner.routes = function()
		{
			return $("#routes").is(':checked');
		};

	owner.pushpins = function()
		{
			return $("#pushpins").is(':checked');
		};

	owner.current = function()
		{
			if(document.getElementById('current') != undefined)
				return document.getElementById('current').value;
			else return null;
		};

    owner.report_type = function()
    {
        if(document.getElementById('report_type') != undefined)
            return document.getElementById('report_type').value;
        else return null;
    };

	owner.startDate = function ()
		{
			if (owner.single_or_multi() == "multi")
				{
					var result = new Date(document.forms["map_controls"].elements["start"].value).getTime() / 1000;
					if (check_if_number(result))
						return result;
					else return null;
				}
			else return null;
		};

	owner.endDate = function ()
		{
			var result;
			if(document.forms["map_controls"].elements["end"] != undefined)
				result = new Date(document.forms["map_controls"].elements["end"].value).getTime() / 1000;
			else
				result = new Date().getTime() / 1000;
			if (check_if_number(result))
				return result;
			else return null;
		};

	owner.update_map = function()
		{
			if (typeof owner.update_interval != "undefined")
				clearInterval(owner.update_interval);
			var sid = get_url_param("sid");
			if (sid != null )
			{
				$.ajax(
					{
						type:"POST",
						url:"./interfaces/map_interface.php",
						data:{mode: "share", sid: sid, timestamp: owner.max_timestamp},
						dataType:"json",

						success:function (data)
						{

							if (data.length != 0)
							{
								owner.geojson = data;
								owner.max_timestamp = data["extra"]["max_timestamp"];
								owner.view =  new L.LatLng(data["extra"]["last_latitude"], data["extra"]["last_longitude"]);
								owner.display_share_updates();
							}
							owner.set_autoupdate();
						}
					}
				);
			}
			else if (owner.stored_device_or_group== "device")
			{
				$.ajax(
					{
						type:"POST",
						url:"./interfaces/map_interface.php",
						data:{mode: owner.stored_device_or_group, did: owner.stored_device, single_or_multi: owner.stored_single_or_multi, end:owner.endDate()/**/, current: owner.stored_current/**/, timestamp: owner.max_timestamp, report_type: owner.stored_report_type},
						dataType:"json",

						success:function (data)
						{

							if (data.length != 0)
								{
									owner.geojson = data;
									owner.max_timestamp = data["extra"]["max_timestamp"];
									owner.view =  new L.LatLng(data["extra"]["last_latitude"], data["extra"]["last_longitude"]);
									owner.display_updates();
								}
							owner.set_autoupdate();
						}
					}
				);
			}
			else
			{
				$.ajax(
					{
						type:"POST",
						url:"./interfaces/map_interface.php",
						data:{mode: owner.stored_device_or_group, gid: owner.stored_group, single_or_multi: owner.stored_single_or_multi, group_time: owner.max_timestamp, report_type: owner.stored_report_type},
						dataType:"json",

						success:function (data)
						{
							if (data.length != 0)
								{
									owner.geojson = data;
									owner.max_timestamp = data["extra"]["max_timestamp"];
									owner.display_updates();
								}
							owner.set_autoupdate();
						}
					}
				);
			}
		};

	owner.display_share_updates = function()
	{
		if (owner.geojson != null)
		{
			if (owner.stored_single_or_multi == "single" || owner.stored_device_or_group == "group")
			{
				owner.i = 0;
				owner.markers.length = 0;
				owner.eventlistGenerator = new EventlistGenerator();
				if (owner.map.hasLayer(owner.geojsonLayer))
				{
					owner.map.removeLayer(owner.geojsonLayer);
				}
				owner.geojsonLayer.clearLayers();
			}
			if (owner.map.hasLayer(owner.polylineLayer))
			{
				owner.map.removeLayer(owner.polylineLayer);
				owner.polylineLayer.removeLayer(owner.polyline);
				owner.polylineLayer.clearLayers();
				delete owner.polyline;
			}
			owner.geojsonLayer.addData(owner.geojson);

			owner.polyline = new L.Polyline(owner.route, {color:'red', weight:3});
			owner.polylineLayer.addLayer(owner.polyline);
			if (owner.routes() == true)
			{
				owner.map.addLayer(owner.polylineLayer);
			}
			if (owner.pushpins() == true)
			{
				owner.map.addLayer(owner.geojsonLayer);
			}

			if (owner.focus() == "all")
			{
				var bounds = owner.geojsonLayer.getBounds();
				if (bounds.isValid(bounds))
					owner.map.whenReady(function () {
						window.setTimeout(function () {
							owner.map.fitBounds(bounds, {padding: [50, 50]});
						}.bind(this), 200);
					}, this);
			}
			else if (owner.focus() == "last")
			{
				owner.map.panTo(owner.view);
			}
			else if (owner.focus() == "none")
			{

			}

			var element = $("table.eventlist");
			if (element.html() != owner.eventlistGenerator.create())
			{
				var scroll = $(element).scrollTop();
				element.html(owner.eventlistGenerator.create()).scrollTop(scroll);
			}
			if (owner.popup_open != -1 && (owner.stored_single_or_multi == "single" || owner.stored_device_or_group == "group"))
			{

				console.log(owner.markers[owner.popup_open]);
				owner.markers[owner.popup_open].openPopup();
			}
		}
	};

	owner.display_updates = function()
			{
				if (owner.geojson != null)
					{
						if (owner.stored_single_or_multi == "single" || owner.stored_device_or_group == "group")
							{
								owner.i = 0;
								owner.markers.length = 0;
								owner.eventlistGenerator = new EventlistGenerator();
								if (owner.map.hasLayer(owner.geojsonLayer))
									{
										owner.map.removeLayer(owner.geojsonLayer);
									}
								owner.geojsonLayer.clearLayers();
							}
						if (owner.map.hasLayer(owner.polylineLayer))
							{
								owner.map.removeLayer(owner.polylineLayer);
								owner.polylineLayer.removeLayer(owner.polyline);
								owner.polylineLayer.clearLayers();
								delete owner.polyline;
							}
						owner.geojsonLayer.addData(owner.geojson);

						owner.polyline = new L.Polyline(owner.route, {color:'red', weight:3});
						owner.polylineLayer.addLayer(owner.polyline);
						if (owner.routes() == true)
							{
								owner.map.addLayer(owner.polylineLayer);
							}
						if (owner.pushpins() == true)
							{
								owner.map.addLayer(owner.geojsonLayer);
							}

						if (owner.focus() == "all")
							{
								var bounds = owner.geojsonLayer.getBounds();
								if (bounds.isValid(bounds))
									owner.map.whenReady(function () {
										window.setTimeout(function () {
											owner.map.fitBounds(bounds, {padding: [50, 50]});
										}.bind(this), 200);
									}, this);
							}
						else if (owner.focus() == "last")
							{
								owner.map.panTo(owner.view);
							}
						else if (owner.focus() == "none")
							{

							}

						var element = $("table.eventlist");
						if (element.html() != owner.eventlistGenerator.create())
							{
								var scroll = $(element).scrollTop();
								element.html(owner.eventlistGenerator.create()).scrollTop(scroll);
							}
						if (owner.popup_open != -1 && (owner.stored_single_or_multi == "single" || owner.stored_device_or_group == "group"))
							{

								console.log(owner.markers[owner.popup_open]);
								owner.markers[owner.popup_open].openPopup();
					}
				}
			};

	owner.submit = function()
		{
			ignore_timestamp = true;
			if (typeof owner.update_interval != "undefined")
				clearInterval(owner.update_interval);
			map_hide_advanced_controls();
			disable_map_submit();
			hide_map_overlay();
			display_centered_overlay("<div class='loader'></div>");
			owner.stored_device_or_group = owner.device_or_group();
			owner.stored_current = owner.current();
            owner.stored_report_type = owner.report_type();

			owner.eventlistGenerator = new EventlistGenerator();
			if ( owner.stored_device_or_group == "device" && owner.device() != undefined)
				{
					owner.stored_device = owner.device();
					owner.stored_single_or_multi = owner.single_or_multi();

				if (owner.stored_single_or_multi == "multi" && ((owner.startDate() && owner.endDate()) || owner.stored_current && owner.startDate()) )
					{

						$.ajax({
							type:"POST",
							url:"./interfaces/map_interface.php",
							data:{mode: owner.stored_device_or_group, did: owner.stored_device, start:owner.startDate(), end:owner.endDate(), current: owner.stored_current, report_type: owner.stored_report_type},
							dataType:"json",

							success:function (data)
							{
								owner.geojson = data;
								if (data.length != 0)
									{
										owner.view = new L.LatLng(data["extra"]["last_latitude"], data["extra"]["last_longitude"]);
										if (owner.max_timestamp < data["extra"]["max_timestamp"])
										owner.max_timestamp = data["extra"]["max_timestamp"];
									}

								owner.display_map();
								owner.set_autoupdate();
							}
						});
					}
				else if (owner.stored_single_or_multi == "single" && !owner.startDate() && (owner.endDate() || owner.stored_current))
					{
						$.ajax({
							type:"POST",
							url:"./interfaces/map_interface.php",
							data:{mode: owner.stored_device_or_group, did:owner.stored_device, end:owner.endDate(), current: owner.stored_current, report_type: owner.stored_report_type},
							dataType:"json",

							success:function (data)
							{
								owner.geojson = data;
								if (data.length != 0)
									{
										owner.view = new L.LatLng(data["extra"]["last_latitude"], data["extra"]["last_longitude"]);
										if (owner.max_timestamp < data["extra"]["max_timestamp"])
										owner.max_timestamp = data["extra"]["max_timestamp"];
									}

								owner.display_map();
								owner.set_autoupdate();
							}
						});
					}
				}
			else if (owner.stored_device_or_group == "group" && (owner.endDate() || owner.stored_current) && owner.group() != undefined)
				{
					owner.stored_group = owner.group();
					$.ajax({
						type:"POST",
						url:"./interfaces/map_interface.php",
						data:{mode: owner.stored_device_or_group, gid: owner.stored_group, group_time: owner.endDate(), current: owner.stored_current, report_type: owner.stored_report_type},
						dataType:"json",

						success:function (data)
							{
								owner.geojson = data;
								if (data.length != 0)
									{
										if (owner.max_timestamp < data["extra"]["max_timestamp"])
										owner.max_timestamp = data["extra"]["max_timestamp"];
									}
								owner.display_map();
								owner.set_autoupdate();
							}
					});
				}
			set_cookie("device_or_group", owner.stored_device_or_group);
			set_cookie("device", owner.stored_device);
			set_cookie("group", owner.stored_group);
		};

	owner.share_map = function()
	{
			var sid = get_url_param("sid");
			console.log(sid);
			if (typeof owner.update_interval != "undefined")
				clearInterval(owner.update_interval);
			hide_map_overlay();
			display_centered_overlay("<div class='loader'></div>");

			owner.eventlistGenerator = new EventlistGenerator();
			$.ajax({
				type:"POST",
				url:"./interfaces/map_interface.php",
				data:{mode: "share", sid: sid},
				dataType:"json",

				success:function (data)
				{
					console.log("ajaxpost");
					owner.geojson = data;
					if (data.length != 0)
					{
						owner.view = new L.LatLng(data["extra"]["last_latitude"], data["extra"]["last_longitude"]);
						if (owner.max_timestamp < data["extra"]["max_timestamp"])
							owner.max_timestamp = data["extra"]["max_timestamp"];
					}

					owner.display_share_map();
					owner.set_autoupdate();
					$(".loader").hide();
				}
			});

	};

	owner.display_share_map = function()
	{
		delete owner.polyline;
		var bounds;

		if (owner.map.hasLayer(owner.geojsonLayer))
		{
			owner.map.removeLayer(owner.geojsonLayer);
		}
		owner.geojsonLayer.clearLayers();

		if (owner.map.hasLayer(owner.polylineLayer))
		{
			owner.map.removeLayer(owner.polylineLayer);
		}
		owner.polylineLayer.clearLayers();

		if (typeof owner.polyline != "undefined")
		{
			owner.route.length = 0;
			owner.route = [];
			delete owner.polyline;
		}

		if (owner.geojson.length != 0)
		{
			owner.i = 0;
			owner.markers.length = 0;
			owner.route.length = 0;
			owner.geojsonLayer.addData(owner.geojson);
			owner.polyline = new L.Polyline(owner.route, {color:'red', weight:3});
			owner.polylineLayer.addLayer(owner.polyline);

			bounds = owner.geojsonLayer.getBounds();

			if (bounds.isValid(bounds))
				owner.map.whenReady(function () {

					window.setTimeout(function () {
						owner.map.fitBounds(bounds, {padding: [50, 50]});
					}.bind(this), 200);
				}, this);

			owner.map.addLayer(owner.polylineLayer);
			owner.map.addLayer(owner.geojsonLayer);

			var element = $("table.eventlist");
			if (element.html() != owner.eventlistGenerator.create())
			{
				var scroll = $(element).scrollTop();
				element.html(owner.eventlistGenerator.create()).scrollTop(scroll);
			}
		}
		hide_overlay();
		if (owner.route.length > 999)
			display_alert_overlay("<div class='limit_reached'></div>Too much location!<br />Only the last 1000 displayed.");
		if (owner.geojson.length == 0)
			display_map_overlay("<div class='alert_sign'></div>No coordinates at the chosen interval!");
	};

	owner.display_map = function()
		{
			delete owner.polyline;
			var bounds;

			if (owner.map.hasLayer(owner.geojsonLayer))
				{
					owner.map.removeLayer(owner.geojsonLayer);
				}
			owner.geojsonLayer.clearLayers();

			if (owner.map.hasLayer(owner.polylineLayer))
				{
					owner.map.removeLayer(owner.polylineLayer);
				}
			owner.polylineLayer.clearLayers();

			if (typeof owner.polyline != "undefined")
				{
					owner.route.length = 0;
					owner.route = [];
					delete owner.polyline;
				}

			if (owner.geojson.length != 0)
				{
					owner.i = 0;
					owner.markers.length = 0;
					owner.route.length = 0;
					owner.geojsonLayer.addData(owner.geojson);
					owner.polyline = new L.Polyline(owner.route, {color:'red', weight:3});
					owner.polylineLayer.addLayer(owner.polyline);
					owner.stored_pushpins = owner.pushpins();
					owner.stored_routes = owner.routes();

					if (owner.focus() == "all" || owner.focus() == "none")
						{
							bounds = owner.geojsonLayer.getBounds();
							if (bounds.isValid(bounds))
								owner.map.whenReady(function () {

									window.setTimeout(function () {
										owner.map.fitBounds(bounds, {padding: [50, 50]});
									}.bind(this), 200);
								}, this);
						}
					else if (owner.focus() == "last")
						{
							owner.map.setView(owner.view, 16);
						}
					if (owner.routes())
						{
							owner.map.addLayer(owner.polylineLayer);
						}
					if (owner.pushpins())
						{
							owner.map.addLayer(owner.geojsonLayer);
						}
					var element = $("table.eventlist");
					if (element.html() != owner.eventlistGenerator.create())
						{
							var scroll = $(element).scrollTop();
							element.html(owner.eventlistGenerator.create()).scrollTop(scroll);
						}

				}
			hide_overlay();
			if (owner.route.length > 999)
				display_alert_overlay("<div class='limit_reached'></div>Too much location!<br />Only the last 1000 displayed.");
			if (owner.geojson.length == 0)
				display_map_overlay("<div class='alert_sign'></div>No coordinates at the chosen interval!");
		};
	owner.construct();
	if (get_url_param("page") == "mapping")
		jQuery(window).load(function ()
		{
			owner.map.whenReady(function ()
			{
				window.setTimeout(function() {owner.submit();}, 1000);
			}, owner.map);
		});
}


