if (!window.navsys) { 
    window.navsys = {};
}

if (!navsys.gui) { 
    navsys.gui = {};
}

var mapstraction;
var geocoder;
var address;

navsys.gui.UserLocator = function() {
	this.refresh_interval = 5;
	this.group_id = null;
	this.map = null;
	this.users = {};
	this.locations = {};
	this.tracks = {};
	this.latlng_bounds=null;
	this.flag_for_centering_map=false;
}

navsys.gui.UserLocator.prototype.startAutoRefresh = function( refresh_interval ) {
	if (refresh_interval) {
		this.refresh_interval = refresh_interval;
	}
	setTimeout('ulocator.refresh()', 1000*this.refresh_interval);
}

navsys.gui.UserLocator.prototype.refresh = function() {
	stop_ajax_start = true;
	this.loadLocations();
	setTimeout('ulocator.refresh()', 1000*this.refresh_interval);	
}

navsys.gui.UserLocator.prototype.setGroupId = function(id) {
	this.group_id = id;
}

navsys.gui.UserLocator.prototype.getGroupId = function() {
	return this.group_id;
}

/*
navsys.gui.UserLocator.prototype.clearUsers = function() {
	this.users = {};
}

navsys.gui.UserLocator.prototype.addUser = function(id, user) {
	this.users[id] = user;
}

navsys.gui.UserLocator.prototype.getUserById = function(id) {
	if (this.users[id]) {
		return this.users[id];		
	} else {
		return null;
	}	
}
*/

navsys.gui.UserLocator.prototype.clearLocations = function() {
	this.locations = {};
	this.tracks = {};
	this.latlng_bounds=null;
}

navsys.gui.UserLocator.prototype.removeTrack = function(user_id) {
	if (this.tracks[user_id]) {
		var track = this.tracks[user_id];
		/*
		this.map.removeOverlay(track.polyline);
		this.map.removeOverlay(track.marker);
		*/
		mapstraction.removeMarker(track.marker);
		mapstraction.removePolyline(track.polyline);
	}
	delete this.tracks[user_id];
	this.latlng_bounds=null;
}


navsys.gui.UserLocator.prototype.init = function(type_of_map) {
	this.initMap(type_of_map);
	this.fillUserLocationList();
	
	if (this.group_id != null) {
		$("#userLocationShowInGroup").change(function () {
			var options = {
					g: this.value,
					a: this.checked ? "e" : "d"
			};
			$.post("/group/show-location", options, function (response) {
				// do nothing
			});
		});
	}

	$("#userLocationNameSubmit").click(function () {
		var name = $("[name=userLocationUserName]", $(this.form)).val();
		ulocator.fillUserLocationList({
			name_like: name
		});
	});	
}

navsys.gui.UserLocator.prototype.initMap = function(type_of_map) {
	/*
	this.map = new GMap2($("#userLocationMap").get(0));
	this.map.enableScrollWheelZoom();
	this.map.enableContinuousZoom();
	this.map.addControl(new GMapTypeControl());
	this.map.addControl(new GLargeMapControl());
	
	this.map.setCenter(new GLatLng(67.5484, 95.8007), 5);
	*/
	
	mapstraction = new Mapstraction('userLocationMap', type_of_map);
	mapstraction.addControls({
		pan: true,
		zoom: 'small',
		map_type: true
	});
}

navsys.gui.UserLocator.prototype.fillUserLocationList = function (options) {
	var options = options || {};
	var urlForGetUsers;	
	
	if (this.group_id != null) {
		urlForGetUsers = "/group/"+this.group_id+"/members/list.json";
	} else {
		urlForGetUsers = "/locator/get-list-of-users";
	}
	
	$.get(urlForGetUsers, options, function (response){
		var list = eval(response);

		var container = $("#blockListUsers");
		container.html("");
		container.prepend("<ul />");

		var ul = $(container.children()[0]);

		//ulocator.clearUsers();
		for (var i = 0; i < list.length; i++) {
			//ulocator.addUser(list[i].id, list[i]);
			var o = ul.append("<li class=\"uid_" + list[i].username + "\"><span>" + list[i].username + "</span></li>");
		}
	});
}

navsys.gui.UserLocator.prototype.loadLocations = function () {
	var urlForGetLocationOfUsers;
	
	if (this.group_id != null) {
		urlForGetLocationOfUsers = "/user-location/group/"+this.group_id+"/data";
	} else {
		urlForGetLocationOfUsers = "/locator/get-location-of-users";
	}
	
	$.get(urlForGetLocationOfUsers, function(responce) {
		var data = eval(responce);
		ulocator.parseLocations(data);
		ulocator.buildTracks();
		if (ulocator.flag_for_centering_map) {
			ulocator.mapBounds();
			ulocator.flag_for_centering_map = false;
		}

		stop_ajax_start = false;
	});
}

navsys.gui.UserLocator.prototype.loadLocationsAndCenterMap = function () {
	this.flag_for_centering_map = true;
	this.loadLocations();
}



navsys.gui.UserLocator.prototype.mapBounds = function () {
	/*
	if (!this.latlng_bounds) {
		this.latlng_bounds=new BoundingBox();
		
		for (var user_id in this.locations) {			
			for (var time in this.locations[user_id]) {
				var point = this.locations[user_id][time];
				var latlng = new LatLonPoint(point.latitude, point.longitude);
				this.latlng_bounds.extend(latlng);
			}
		}
		
	    var zoom = this.map.getBoundsZoomLevel(this.latlng_bounds);
	    this.map.setCenter(this.latlng_bounds.getCenter(), zoom);		
	}
	*/
	
	mapstraction.autoCenterAndZoom();
}

/*
navsys.gui.UserLocator.prototype.mapBounds = function () {
	if (!this.latlng_bounds) {
		this.latlng_bounds=new GLatLngBounds();
		
		for (var user_id in this.locations) {			
			for (var time in this.locations[user_id]) {
				var point = this.locations[user_id][time];
				var latlng = new GLatLng(point.latitude, point.longitude);
				this.latlng_bounds.extend(latlng);
			}
		}
		
	    var zoom = this.map.getBoundsZoomLevel(this.latlng_bounds);
	    this.map.setCenter(this.latlng_bounds.getCenter(), zoom);		
	}
}
*/

navsys.gui.UserLocator.prototype.buildTracks = function () {
	for (var user_id in this.locations) {
		if (!this.tracks[user_id]) {
			var track = this.buildTrack(this.locations[user_id], user_id);
			this.tracks[user_id] = track;
			/*
			this.map.addOverlay(track.polyline);
			this.map.addOverlay(track.marker);
			*/
			
			mapstraction.addMarkerWithData(track.marker);
			mapstraction.addPolyline(track.polyline);
		}
	}
}

navsys.gui.UserLocator.prototype.buildTrack = function (locations, user_id) {
	var track = {};
	var time_line = new Array();
	
	var i=0;
	for (var time in locations) {
		time_line[i]=time;
		i++;
	}
	time_line.sort();
	
	var way = new Array();
	for (i=0; i<time_line.length; i++) {
		var point = locations[time_line[i]];
		way[i] = new LatLonPoint(point.latitude, point.longitude);
	}
	
	var polyline = new Polyline(way);
	
	var point = locations[time_line[i-1]];
	var marker = this.buildMarker(point, user_id);
	
	track.polyline = polyline;
	track.marker = marker;
	
	return track;
}

navsys.gui.UserLocator.prototype.buildMarker = function (point, user_id) {
	var info_bubble='Пользователь: <strong>' + user_id + '</strong><br />' +
	'Координаты: <strong>' + point.latitude + ', ' + point.longitude + '</strong><br />' +
	'<span id="address_of_'+user_id+'"></span><br />';
	
	var marker_latlng = new LatLonPoint(point.latitude, point.longitude)
	var marker = new Marker(marker_latlng, {		
		label : user_id,
		draggable : false,
		hover : true
		});
	
	marker.setInfoBubble(info_bubble);
	marker.setLabel(user_id);

	/*
	var address = '';
	var query=point.latitude+','+point.longitude;
	var geocoder = new GClientGeocoder();
	geocoder.getLocations(
		query,
		function(response) {
		    if (!response || response.Status.code != 200) {
		    	address = 'Не удалось установить адрес';
		    } else {
		    	var place = response.Placemark[0];
		    	address = place.address;			    	
		    }
		    var address_html = 'Адрес: <strong>'+ address +'</strong><br />';
		    $('#address_of_'+user_id).html(address_html);
		}
	);
	*/
	
	return marker;
}

navsys.gui.UserLocator.prototype.parseLocations = function (data) {
	for (var key in data) {
		var item = data[key];
		var user_id=item.user_name;
		var time=item.utime;

		if (!this.locations[user_id]) {
			this.locations[user_id] = {};
		}

		if (!this.locations[user_id][time]) {
			this.locations[user_id][time] = item;
			this.removeTrack(user_id);
		}
	}
}
