if (!window.navsys) {
    window.navsys = {};
}

if (!navsys.gui) { 
    navsys.gui = {};
}

navsys.gui.CommentsManager = function (containerId, objectName, objectId) {
	this.containerId = containerId;
	this.objectName = objectName;
	this.objectId = objectId;
	this.permissions = {};
	this.wysiwygObject = null;
	this.commentIdForRemove = 0;
	this.introMessage = "Ваш комментарий...";
}

navsys.gui.CommentsManager.prototype.init = function(){
	this.loadPermissions();	
}

navsys.gui.CommentsManager.prototype.loadPermissions = function(){
	var params = {
			'objectName': this.objectName,
			'objectId': this.objectId			
	};
	
	$.get("/comment/permissions?rand="+Math.random(), params, function(response){
		var permissions = eval( "(" + response + ")" );
		commentsManager.permissions = permissions;
		
		if (permissions.view) {
			commentsManager.initUI();
			commentsManager.loadComments();
		}
	});
}

navsys.gui.CommentsManager.prototype.initUI = function(){
	$('<div id="editorComments"></div><div id="listComments"></div>').appendTo("#blockComments");
	
	if (this.permissions.add) {
		$('<div><textarea id="bodyComment" name="bodyComment" class="wysiwyg" onclick="commentsManager.initUiWysiwyg();">'+this.introMessage+'</textarea></div>').appendTo("#editorComments");
		$('<div><input type="button" id="saveComment" name="saveComment" class="button" value="Сохранить" onclick="commentsManager.saveComment();" /></div>').appendTo("#editorComments");
	} else {
		$('<div>Извините, но Вы не можете оставлять комментарии. Пожалуйста <a href="/auth">авторизируйтесь</a>. Если у Вас нет аккаунта, то Вам следует <a href="/register">зарегистрироваться</a>.</div>').appendTo("#editorComments");
	}
}


navsys.gui.CommentsManager.prototype.initUiWysiwyg = function(){
	if ($('#bodyComment').text() == this.introMessage) { $('#bodyComment').text(''); }
	$('#bodyComment').tinymce({
		language : "ru",		
		auto_focus : "bodyComment"			
	});

	this.wysiwygObject = $('#bodyComment'); 
}


navsys.gui.CommentsManager.prototype.loadComments = function(){
	if (this.permissions.view) {
		var params = {
				'objectName': this.objectName,
				'objectId': this.objectId			
		};
		$.get("/comment/list?rand="+Math.random(), params, function(response){
			$("#listComments").html('');
			if (response!='[]') {
				var data = eval(response);			
				var html='';
				if (data.length>0) {
					for (var key in data) {
						var comment = data[key];

						var date = new Date();
						date.setTime(comment.ctime*1000);
						//@todo Should be enhanced to current locale
						var timeOfComment = date.toLocaleDateString()+' '+date.toLocaleTimeString();

						var deleteLink='';
						if (commentsManager && commentsManager.permissions && 
								(commentsManager.permissions.remove=='*' || commentsManager.permissions.remove==comment.user_id)) {
							deleteLink='<div class="remove"><a class="deleteComment" href="#" onclick="commentsManager.deleteComment('+comment.id+');">удалить</a></div>';
						}

						html+='<div class="itemComments">'+
						'<div class="date">'+timeOfComment+'</div>'+
						'<div class="user">'+comment.user_name+'</div>'+
						'<div class="body">'+comment.comment+'</div>'+
						'<div class="delete">'+deleteLink+'</div>'+
						'</div>';
					}
				}
				$(html).appendTo("#listComments");
			}
		});
	}
}

navsys.gui.CommentsManager.prototype.saveComment = function(){
	var params = {
			'objectName': this.objectName,
			'objectId': this.objectId,
			'comment': this.wysiwygObject.html()
	};

    $.get("/comment/save?rand="+Math.random(), params, function(response){
    	commentsManager.wysiwygObject.html('');
    	commentsManager.loadComments();
    });
}


navsys.gui.CommentsManager.prototype.callbackOnDeleteComment = function(value, m, f){
	if (value) {
		var params = {
				'objectName': commentsManager.objectName,
				'objectId': commentsManager.objectId,
				'commentId': commentsManager.commentIdForRemove
		};

		$.get("/comment/delete?rand="+Math.random(), params, function(response){    	
			commentsManager.loadComments();
		});		
	}
}

navsys.gui.CommentsManager.prototype.deleteComment = function(commentId){
	this.commentIdForRemove = commentId;
	
	$.prompt('Вы уверены, что хотите удалить этот комментарий?',{
		buttons: {'Да, удалить': true, 'Нет, не удалять':false},
		callback:commentsManager.callbackOnDeleteComment
	});
}