if (!window.navsys) { 
    window.navsys = {};
}

navsys.PersonalRelationship = function () {
	this.friendUserLogin = '';
	this.listOfFriendsOptions = {
			'page': 1,
			'label': ''
	};
	this.listOfBannedOptions = {
			'page': 1
	};
	this.listOfMyRequestsOptions = {
			'page': 1
	};	
	
}

navsys.PersonalRelationship.prototype.doBecomeFriends2 = function(){
	if ($('#inviteLogin')[0]) {
		var login = $('#inviteLogin').val().replace(/(^\s+)|(\s+$)/g, '');

		if (login!='') {
			this.doBecomeFriends(login);
		}
	}
}

navsys.PersonalRelationship.prototype.buildMessageFromResponce = function(data){
	var msg= '';
	if (data && data.message) {
		msg='<span id="errorCode">'+data.errorCode+'</span><span>'+data.message+'</span>';
	}
	return msg; 	
}

navsys.PersonalRelationship.prototype.callbackPromptToCancelBanAndBecomeFriends = function(value,m,f){
	if (value) {
		var message = $('#message').val();
		var options = {
				'login': personalRelationship.friendUserLogin,
				'message': message
			};
		$.get("/personal-relationship/cancel-ban-and-become-friends?rand="+Math.random(), options, function (response){		
			var data = eval( "(" + response + ")" );
			if ($('#listBanned')) {
				personalRelationship.refreshListOfBannedUsers();
			}
			if (data.errorCode==0) {
				$('#message').val('');
				
				if ($('#inviteLogin')[0]) {
					$('#inviteLogin').val('');					
				} else {
					$('#blockFriendRrequests').hide();
					$('#fromMeStatus').html('');
				}
			}
			var msg=personalRelationship.buildMessageFromResponce(data);
			$.prompt(msg,{ buttons: { 'Хорошо': true} });
		});	
	}
}

navsys.PersonalRelationship.prototype.doBecomeFriends = function(userLogin){
	this.friendUserLogin = userLogin;
	var message = $('#message').val();

	$.get("/personal-relationship/become-friends?rand="+Math.random(), {'login': userLogin, 'message': message}, function (response){		
		var data = eval( "(" + response + ")" );
		
		var msg=personalRelationship.buildMessageFromResponce(data);
		
		if (data.errorCode==0 && $('#inviteLogin')[0]) {
			$('#inviteLogin')[0].value = '';
			$('#message').val('');
		}
		
		if (data.errorCode==0 || data.errorCode==1) {			
			$.prompt(msg,{ buttons: { 'Хорошо': true} });
		}
		
		if (data.errorCode==2) {
			$.prompt(msg,{
				buttons: { 'Да, отправить приглашение': true, 'Отмена':false},
				callback:personalRelationship.callbackPromptToCancelBanAndBecomeFriends
			});
		}

		if (data.errorCode==3) {
			$.prompt(msg,{
				buttons: { 'Перейти на персональную страницу': true, 'Отмена':false},
				callback: function (value) {
						if (value) {
							window.location='/personal';
						}
					}
			});
		}
	});
}


// Friends
navsys.PersonalRelationship.prototype.initFriendsList = function(){
	var options = personalRelationship.listOfFriendsOptions;
	options.page='count';
	$.get("/personal-relationship/list-of-friends?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );

		if (response.list && response.list.length>0) {
			$("#pagerListFriends").pagination(response.totalCount, {
				items_per_page:response.perPage, 
				callback:personalRelationship.loadListOfFriends
			});
		}
		personalRelationship.showListOfFriends(response.list);

	});
}

navsys.PersonalRelationship.prototype.loadListOfFriends = function(pageIndex, jq){
	personalRelationship.listOfFriendsOptions.page=pageIndex+1;
	personalRelationship.refreshListOfFriends();
}

navsys.PersonalRelationship.prototype.showListOfFriends = function(list){
	$('#listFriends').html('');
	
	if (list.length>0) {
		for(var key in list) {
			var item=list[key];
			
			var friend_html = $("#htmlTemplatesOfPersonalPage > .friendItem").clone();
			friend_html.find('.containerUserInfo').attr('id', 'containerUserInfo__'+item.login);
			friend_html.find('.linkLoginFriend').attr('id', 'linkLoginFriend__'+item.friend_id)
				.attr('name', item.friend_id).text(item.login)
				.click(function () { $('#fullUserInfo__'+this.name).toggle();} );
			
			friend_html.find('.allowDenyViewMyLocation >> input:checkbox').attr('id', 'changeAccessToViewMyLocation_'+item.friend_id)
				.attr('name', item.friend_id)				
				.click( function () {
					personalRelationship.changeRightToViewMyLocation(this.name);
					} 
				);
			
			if (item.locator_view_my_location && item.locator_view_my_location=='on') {
					friend_html.find('.allowDenyViewMyLocation >> input:checkbox').attr('checked', true);
			}
			
			if (item.locator_can_i_veiw_location && item.locator_can_i_veiw_location=='on') {
				friend_html.find('.canIViewLocation >> input:checkbox').attr('checked', true);
			}
			
			friend_html.find('.fullUserInfo').attr('id', 'fullUserInfo__'+item.friend_id);
			
			if (item.labels && item.labels.length>0) {
				var labelsHtml = this.getHtmlCodeForFriendItemLabels(item.friend_id, item.labels);
				friend_html.find('.fullUserInfo > .blockLabels').html(labelsHtml);
			}
			
			friend_html.find('.reactionBrokeFriendship > a').attr('name', item.friend_id);
			
			friend_html.find('.convertUserNameToUserId').attr('title', item.login).text(item.friend_id);
			
			$('#listFriends').append(friend_html);
		}
	}
}


navsys.PersonalRelationship.prototype.changeRightToViewMyLocation = function(friend_id){	
	var options = {'toUserId': friend_id};
	
	var fnk='deny-access-to-user';
	var isHaveRight = $('#changeAccessToViewMyLocation_'+friend_id).attr('checked');
	if (isHaveRight) {
		fnk='allow-access-to-user';
	}	
	
	$.get('/locator/'+fnk+'?rand='+Math.random(), options, function (response) {
		var response = eval( "(" + response + ")" );
	});
}

navsys.PersonalRelationship.prototype.getHtmlCodeForFriendItemLabels = function(friend_id, labels){
	var html='';
	if (labels.length>0) {
		html='<div class="blockFriendLabels">';
		for(var key in labels) {
			var label=labels[key];
			var checked = '';
			if (label.marked==1) {
				checked='checked="checked"';
			}
			
			var htmlItem='<label><input type="checkbox" title="'+label.label+'" onclick="personalRelationship.doSetLabel('+friend_id+', '+label.id+', this.checked);" '+checked+'/>'+label.label+'</label>';
			html+=htmlItem;
		}
		html+='</div>';
	}	
	return html;
}


navsys.PersonalRelationship.prototype.doSetLabel = function(friend_id, labelId, checked){
	var params = {
			'friend_id': friend_id,
			'label_id': labelId,
			'checked': checked
	};
	
	$.get("/personal-label/set-label?rand="+Math.random(), params, function(response){
		var response = eval( "(" + response + ")" );
	});	
}


navsys.PersonalRelationship.prototype.refreshListOfFriends = function(){
	var options = personalRelationship.listOfFriendsOptions;
	
	$.get("/personal-relationship/list-of-friends?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );
		personalRelationship.showListOfFriends(response.list);		
	});	
}

//MyRequests
navsys.PersonalRelationship.prototype.initMyRequestsList = function(){
	var options = personalRelationship.listOfMyRequestsOptions;
	options.page='count';
	$.get("/personal-relationship/list-of-my-requests?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );
		
		if (response.list && response.list.length>0) {
			$("#pagerListRequests").pagination(response.totalCount, {
				items_per_page:response.perPage, 
				callback:personalRelationship.loadListOfMyRequests
			});
		}
		personalRelationship.showListOfMyRequests(response.list);

	});
}

navsys.PersonalRelationship.prototype.loadListOfMyRequests = function(pageIndex, jq){
	personalRelationship.listOfMyRequestsOptions.page=pageIndex+1;
	personalRelationship.refreshListOfMyRequests();
}

navsys.PersonalRelationship.prototype.showListOfMyRequests = function(list){
	$('#listRequests').html('');
	
	if (list.length>0) {
		var html='';
		for(var key in list) {
			var item=list[key];
			var htmlItem='<div id="blockBannedUser__'+item.login+'"><span>'+item.login+'</span> '				
				+'</div>';

			html+=htmlItem;
		}

		$(html).appendTo('#listRequests');
	}
}

navsys.PersonalRelationship.prototype.refreshListOfMyRequests = function(){
	var options = personalRelationship.listOfMyRequestsOptions;
	
	$.get("/personal-relationship/list-of-my-requests?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );
		personalRelationship.showListOfMyRequests(response.list);		
	});
}

//Banned
navsys.PersonalRelationship.prototype.initBannedList = function(){
	var options = personalRelationship.listOfBannedOptions;
	options.page='count';
	$.get("/personal-relationship/list-of-banned-users?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );
		
		if (response.list && response.list.length>0) {
			$("#pagerListBanned").pagination(response.totalCount, {
				items_per_page:response.perPage, 
				callback:personalRelationship.loadListOfBanned
			});
		}
		personalRelationship.showListOfBannedUsers(response.list);

	});
}

navsys.PersonalRelationship.prototype.loadListOfBanned = function(pageIndex, jq){
	personalRelationship.listOfBannedOptions.page=pageIndex+1;
	personalRelationship.refreshListOfBannedUsers();
}

navsys.PersonalRelationship.prototype.showListOfBannedUsers = function(list){
	$('#listBanned').html('');
	
	if (list.length>0) {
		var html='';
		for(var key in list) {
			var item=list[key];
			var htmlItem='<div id="blockBannedUser__'+item.login+'"><span>'+item.login+'</span> '
				+'<span class="reactionUnban"><a href="javascript:void(0)" onclick="personalRelationship.doReactionOnRequest('+item.friend_id+', \'unban\');">Удалить пользователя из черного списка</a></span>'
				+'</div>';

			html+=htmlItem;
		}

		$(html).appendTo('#listBanned');
	}
}

navsys.PersonalRelationship.prototype.refreshListOfBannedUsers = function(){
	var options = personalRelationship.listOfBannedOptions;
	
	$.get("/personal-relationship/list-of-banned-users?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );
		personalRelationship.showListOfBannedUsers(response.list);		
	});
}

// Request to become a friends
navsys.PersonalRelationship.prototype.refresFriendshipRequests = function(){
	var options = personalRelationship.listOfBannedOptions;
	
	$.get("/personal-relationship/list-of-friendship-requests?rand="+Math.random(), options, function (response){
		var response = eval( "(" + response + ")" );
		personalRelationship.showFriendshipRequests(response);		
	});
}

navsys.PersonalRelationship.prototype.showFriendshipRequests = function(list){
	$('#blockInvitaions').hide();
	$('#listInvitations').html('');
	
	if (list.length>0) {
		$('#blockInvitaions').show();
		var html='';		

		for(var key in list) {
			var item=list[key];
			var htmlItem= this.getHtmlCodeForFriendshipRequest(item);

			html+=htmlItem;
		}

		$(html).appendTo('#listInvitations');
	}
}

navsys.PersonalRelationship.prototype.getHtmlCodeForFriendshipRequest = function(item){
	var htmlItem='<div id="blockRequest__'+item.login+'">'
	+'<div>От: '+item.login+'</div>'
	+'<div>Дата: '+item.ctime+'</div>'
	+'<div>'+item.message+'</div>'
	+' <span class="reactionAgree"><a href="javascript:void(0)" onclick="personalRelationship.doReactionOnRequest('+item.user_id+', \'agree\');">Приять приглашение</a></span>'
	+' <span class="reactionCancel"><a href="javascript:void(0)" onclick="personalRelationship.doReactionOnRequest('+item.user_id+', \'cancel\');">Отклонить приглашение</a></span>'
	+' <span class="reactionBan"><a href="javascript:void(0)" onclick="personalRelationship.doReactionOnRequest('+item.user_id+', \'ban\');">Отклонить приглашение и внести пользователя в черный список</a></span>'
	+'</div>';
	return htmlItem;
}

navsys.PersonalRelationship.prototype.doReactionOnRequest = function(userId, reaction){
	var msg='';
	if (reaction=='agree') {
		msg='Вы уверены, что хотете приять приглашение?';
	}
	if (reaction=='cancel') {
		msg='Вы уверены, что хотете отклонить приглашение?';
	}
	if (reaction=='ban') {
		msg='Вы уверены, что хотете внести пользователя в черный список?';
	}
	if (reaction=='unban') {
		msg='Вы уверены, что хотете удалить пользователя из черного списка?';
	}
	if (reaction=='brokeFriendship') {
		msg='Вы уверены, что хотете разорвать отношения?';
		reaction = 'cancel';
	}

	var options = {
			'userId': userId,
			'reaction': reaction
	}
	
	msg = msg +'<br /> Сопроводительное сообщение:<br /><textarea id="reaction_message" name="reaction_message"></textarea>';
	
	$.prompt(msg,{
		buttons: { 'Да': options, 'Отмена':false},
		callback: function(options, m, f) {
			if (options) {
				options.message=f.reaction_message;
				$.get("/personal-relationship/reaction-on-request?rand="+Math.random(), options, function (response){
					var response = eval( "(" + response + ")" );
					if (response.errorCode==0) {
						personalRelationship.refreshListOfFriends();
						personalRelationship.refresFriendshipRequests();			
						personalRelationship.initBannedList();
					}

					var message=personalRelationship.buildMessageFromResponce(response);
					$.prompt(message,{ buttons: { 'Хорошо': true} });
				});
			}
		}
	});	
	
}
