if (!window.navsys) { 
    window.navsys = {};
}

if (!navsys.gui) { 
    navsys.gui = {};
}

navsys.gui.LocatorUserList = function() {
	this.currentUser = {};
	this.usersAll = {};
	this.users = {};
	this.usersOnPage = {};
	this.usersOnMap = {};
	this.usersByLabel = {};
	this.heightOfUserItem = 20;
	this.page = 1;
	this.countOfUsers = 0;
	this.countPerPage = 0;
	this.filterByLabelId = 0;
	this.createBlocksOfListOfSelectedItems();
	
	$('#panelLocatorUserList').height($('#containerLocator').height());
}

navsys.gui.LocatorUserList.prototype.createBlocksOfListOfSelectedItems = function(){
	
	$(".blockListSelected").each(
		function() {
			var id = $(this).find('.listSelectedUsers').attr('id');
			$(this).find('.title > a.linkShowHide').attr('name', id).click(
				function () {						
					$('#'+this.name).toggle();
					arrowOpen = $(this).find('.arrowBlockOpen');
					arrowClose = $(this).find('.arrowBlockClose');
					if (arrowOpen.length) {
						arrowOpen.attr('class','arrowBlockClose');
					} else if (arrowClose.length) {
						arrowClose.attr('class','arrowBlockOpen');
					}
					locator.locatorUsersList.recreateAllLists();
				}
			)
		}
	);
}

navsys.gui.LocatorUserList.prototype.loadAllUsers = function(users){
	if (users.length>0) {
		this.usersAll = users;
		this.generateFilterByLabel();
		this.recreateAllLists();
	} else {
		$('#blockListSelectedLabel_1').hide();
		$('#blockListSelectedLabel_2').hide();
		$('#blockFilterLabel').hide();
		$('#blockListUsers').hide();
		$('#blockPagerListUsers').hide();
		$('#blockNoUsers').show();
	}
}

navsys.gui.LocatorUserList.prototype.calculateGoodParametersForPaging = function(){
	var count = 0;	
	for (var key1 in this.usersByLabel) {
		var list1 = this.usersByLabel[key1];
		var isVisibleList = $('#listSelectedUsersLabel_'+key1).is(':visible');
		if (isVisibleList) {
			for (var key2 in list1) {
				count++;
			}
		}
	}
	
	var heigth = $('#panelLocatorUserList').height() - 220;
	
	this.countPerPage = Math.round(heigth/this.heightOfUserItem) - count;
}

navsys.gui.LocatorUserList.prototype.generateFilterByLabel = function(){
	if (this.usersAll && this.usersAll[0] && this.usersAll[0].labels) {
		var labels = this.usersAll[0].labels;

		var html = '<select id="filterUsersByLabel">;'
		html+='<option value="0">-- Все --</option>';
		
		for (var key in labels) {
			var label = labels[key];
			if (label.id != 1 && label.id != 2) {				
				html+='<option value="'+label.id+'">'+label.label+'</option>';
			}
		}
		html+='</select>';
		$('#blockFilterLabel').html(html);
		
		$('#filterUsersByLabel').change(function() {
			locator.locatorUsersList.page = 1;
			locator.locatorUsersList.filterByLabelId = this.value;
			locator.locatorUsersList.recreateAllLists();
		} );
	}
}

navsys.gui.LocatorUserList.prototype.recreateAllLists = function() {
	this.buildListsOfUsers();
	this.rebuildPagination();
	
	this.createMainListOfUsers();
	this.createSubListOfUsersByLabel(1);
	this.createSubListOfUsersByLabel(2);
	this.selectUsersOnMap();	
	locator.updateLastTimeOfUsersInList();	
	$('.uid__'+locator.selected_user_id).addClass('active');
}

navsys.gui.LocatorUserList.prototype.rebuildPagination = function() {
	$('#blockPagerListUsers').html('<div id="userLocationUserListPagination" class="pagination"></div>');
	var totalCount = this.getCount(this.users);
	
	var maxPage = Math.ceil(totalCount/this.countPerPage);	
	if (this.page > maxPage && maxPage > 0) {
		this.page = maxPage;
	}

	if (totalCount > this.countPerPage) {
		$("#userLocationUserListPagination").pagination(totalCount, {
			items_per_page: this.countPerPage,
			current_page: this.page-1,
			callback: locator.locatorUsersList.changePageOfMainList
		});		
	}
}

navsys.gui.LocatorUserList.prototype.changePageOfMainList = function(pageIndex, jq){
	locator.locatorUsersList.page=pageIndex+1;
	locator.locatorUsersList.createMainListOfUsers();
}

navsys.gui.LocatorUserList.prototype.selectUsersOnMap = function() {
	this.usersOnMap = {};
	this.addUsersToListOfUsersOnMapFrom(this.usersOnPage);
	this.addUsersToListOfUsersOnMapFrom(this.usersByLabel[1]);
	this.addUsersToListOfUsersOnMapFrom(this.usersByLabel[2]);
	
	if ($('#switchShowOwnLocation').attr('checked')) {
		this.usersOnMap[this.currentUser.id] = this.currentUser;
	}
	
	locator.setUsers(this.usersOnMap);
}

navsys.gui.LocatorUserList.prototype.addUsersToListOfUsersOnMapFrom = function(list) {
	for (var key in list) {
		var issetUser = false;
		var user = list[key];
		if (user.allow == 't') {

			for (var key2 in this.usersOnMap) {
				var userOnMap = this.usersOnMap[key2];
				if (user.id == userOnMap.id) {
					issetUser = true;
					break;
				}
			}

			if (!issetUser) {
				this.usersOnMap[user.id] = user;
			}
		}
	}	
}

navsys.gui.LocatorUserList.prototype.createMainListOfUsers = function() {
	var container = $("#blockListUsers");
	container.html("");
	container.prepend("<ul />");
	var ul = $(container.children()[0]);

	var count = 0;
	var startNumber = (this.page - 1) * this.countPerPage;
	var endNumber = startNumber + this.countPerPage;
	this.usersOnPage = {};
	
	for (var key in this.users) {
		if (count >= startNumber && count < endNumber) {
			var user = this.users[key];
			this.usersOnPage[count] = user;
		}
		count++;
	}
	this.selectUsersOnMap();
	
	
	for (var key in this.usersOnPage) {
		var user = this.usersOnPage[key];
		var userHtmlItem = this.createHtmlObjectOfUserItem(user);

		if (this.issetLabel(user, 1)) {
			userHtmlItem.find(".locatorLabels >> input[@name='1']:checkbox").attr('checked', true);
		}
		if (this.issetLabel(user, 2)) {
			userHtmlItem.find(".locatorLabels >> input[@name='2']:checkbox").attr('checked', true);
		}

		userHtmlItem.find(".locatorLabels >> input:checkbox").attr('value', user.id).click(
				function () {
					locator.locatorUsersList.doSetLabel(this.value, this.name, !this.checked);
				}
		);

		ul.append(userHtmlItem);
	}

	$("li > .userNameLink", ul).click(function () {
		locator.selectUser( this.name );
	});
	
    $('.label_1 input', ul).checkbox({
        cls:'chk-star',
        empty: '/js/jquery.checkbox/empty.png'
    });
    $('.label_2 input', ul).checkbox({
        cls:'chk-eye',
        empty: '/js/jquery.checkbox/empty.png'
    });
}


navsys.gui.LocatorUserList.prototype.createSubListOfUsersByLabel = function(labelId) {
	var users = this.usersByLabel[labelId];
	var container = $('#listSelectedUsersLabel_'+labelId);

	if (container && users) {
		container.html("");
		container.prepend("<ul />");
		var ul = $(container.children()[0]);

		for (var key in users) {
			var user = users[key];
			var userHtmlItem = this.createHtmlObjectOfUserItem(user);
			userHtmlItem.find('.removeFromSelected').css('display', 'inline-block');
			userHtmlItem.find('.locatorLabels').css('display', 'none');
			
			userHtmlItem.find("a.removeLink").attr('name', user.id).attr('type', labelId).click(
					function () {
						locator.locatorUsersList.doSetLabel(this.name, this.type, false);
					}
				);
			
			ul.append(userHtmlItem);
		}
		
		$("li > .userNameLink", ul).click(function () {
			locator.selectUser( this.name );
		});		
	}
	
	if (this.getCount(users)==0) {
		$('#blockListSelectedLabel_'+labelId).css('display', 'none');
	} else {
		$('#blockListSelectedLabel_'+labelId).css('display', 'block');
	}
}


navsys.gui.LocatorUserList.prototype.doSetLabel = function(friend_id, labelId, checked) {
	for (var key in this.usersAll) {
		var user = this.usersAll[key];
		if (user.id==friend_id) {
			for (var key2 in user.labels) {
				var label = user.labels[key2];
				if (label.id == labelId) {
					if (checked) {
						label.marked = 1;
					} else {
						label.marked = 0;
					}
					user.labels[key2] = label;
					break;
				}
			}
			
			this.usersAll[key] = user;
			break;			
		}		
	}
	
	this.recreateAllLists();
	
	if (!locator.demo) {
		var personalRelationship = new navsys.PersonalRelationship();
		stop_ajax_start = true;
		personalRelationship.doSetLabel(friend_id, labelId, checked);
	}
}

navsys.gui.LocatorUserList.prototype.getCount = function(item) {
	var count = 0;
	for (var key in item) {
		count ++;		
	}
	return count;
}

navsys.gui.LocatorUserList.prototype.createHtmlObjectOfUserItem = function(user) {
	var userHtmlItem = $("#htmlTemplates > .listUsers > li.itemUser").clone();
	userHtmlItem.addClass('uid__'+user.id);
	userHtmlItem.find(".userNameLink").attr('name', user.id);
	userHtmlItem.find(".userName").text(user.username);
	
	if (user.allow == 't') {
		userHtmlItem.find(".userNameText").css('display', 'none');
	} else {
		userHtmlItem.find(".userNameLink").css('display', 'none');
	}
	
	return userHtmlItem;
}

navsys.gui.LocatorUserList.prototype.buildListsOfUsers = function() {
	if (this.usersAll.length>0) {
		this.buildListOfUsersByLabel(1);
		this.buildListOfUsersByLabel(2);		
		
		this.calculateGoodParametersForPaging();
		
		this.users = {};
		var count = 0;

		for (var key in this.usersAll) {
			var user = this.usersAll[key];
			
			if (this.filterByLabelId == 0 || (this.filterByLabelId != 0 && this.issetLabel(user, this.filterByLabelId))) {
				if (!this.issetUser(this.usersByLabel[1] , user.id) && !this.issetUser(this.usersByLabel[2] , user.id)) {
					this.users[count] = user;
					count++;
				}
			}
		}
	}
}

navsys.gui.LocatorUserList.prototype.buildListOfUsersByLabel = function(labelId) {
	if (this.usersAll.length>0) {
		this.usersByLabel[labelId] = {};

		for (var key in this.usersAll) {
			var user = this.usersAll[key];

			if (this.issetLabel(user, labelId)) {
				this.usersByLabel[labelId][key]=user;			
			}
		}
	}
}

navsys.gui.LocatorUserList.prototype.issetLabel = function(user, labelId) {
	var issetLabel = false;
	if (user && user.labels) {
		for (var lkey in user.labels) {
			var label = user.labels[lkey];
			if (label.id == labelId && label.marked == 1) {
				issetLabel = true;
				break;
			}
		}
	}
	return issetLabel;
}

navsys.gui.LocatorUserList.prototype.issetUser = function(users, userId) {
	var issetUser = false;
	if (users && userId) {
		for (var key in users) {
			var user = users[key];
			if (user.id == userId) {
				issetUser = true;
				break;
			}
		}
	}
	return issetUser;
}

navsys.gui.LocatorUserList.prototype.switchShowOwnLocation = function(obj) {
	this.selectUsersOnMap();
	
	if (!locator.demo) {
		var options = {
				show_own_location: obj.checked
		};
		stop_ajax_start = true;
		$.post("/locator/set-setting", options, function (response) {
			// do nothing
		});
	}
}

