/* @ >>>> для работы с комментариями */
Lib.Comment = {

    isInit:false,
    init: function(){
        if(!Lib.User.checkStatus()){
                    return false;
                }
        if(!Lib.Comment.isInit){
            Lib.Comment.commentFormBox = $('#comment-form-block');
            Lib.Comment.commentFormLink=$('#comment-form-link');
            Lib.Comment.commentForm=$('form',this.commentFormBox);
            Lib.Comment.commentHTML = '<li class="comments-item" id="comment#ID#" style="display: none;">'+
			'<dl class="clearfix">'+
				'<dt><a href="/user/id/"><img src="" alt="" /></a></dt>'+
				'<dd id="comment#ID#-content"><div>'+

					'<p></p>'+
					'<span><span class="say-text"></span> <a href="/user/id/" class="comment-nickname"></a> <span class="comment-date"></span>'+
                        '<span class="comment-answer" rel="#ID#">ответить</span>'+
                        '<span class="comment-delete" rel="#ID#">удалить</span>'+
                    '</span>'+
					'<div class="says"></div>'+
				'</div></dd>'+
			'</dl>'+
			'<ol class="nm"></ol>'+
		'</li>';

            Lib.Comment.isInit = true;
            }

            return true;


    },


     


    /**
    * выполняет ответ на комментарий
    */
    commentAnswer:function(commentId) {

            if(!Lib.Comment.init()){
                return false;
            }
            
            // подставляем данные родителя
            $('#comment-parent',Lib.Comment.commentForm).val(commentId);

            // переместить форму в нужное место
            if (commentId) {
                $('#comments #comment'+commentId+'  .nm:first').prepend(Lib.Comment.commentFormBox);
               Lib.Comment.commentFormLink.show();
            }
            else {
                // если это клик на "написать" - то в самый низ
                Lib.Comment.commentFormLink.after(Lib.Comment.commentFormBox);
                Lib.Comment.commentFormLink.hide();
            }

            Lib.Comment.commentFormBox.removeClass('with-error');
            // показать форму
            Lib.Comment.commentFormBox.show();

    },

    /**
         * прячет форму при отмене
         */
    commentHideForm:function() {
            if(!Lib.Comment.init()){
                return false;
            }
            Lib.Comment.commentFormBox.hide();
            Lib.Comment.commentFormLink.show();
            // чистим форму
            $('#comment-text',Lib.Comment.commentForm).val('');
            $('#comment-parent',Lib.Comment.commentForm).val(0);
    },

        commentArticlesDelete: function(commentId)
        {
            Lib.Comment.commentDelete(commentId,true);
        },
    

        /**
         * Выполняет удаление коммента
         */
        commentDelete:function(commentId,isArticle ) {
            if(!Lib.Comment.init()){
                return false;
            }
            // прячем форму
            Lib.Comment.commentHideForm();
            // отправляем запрос
            var url=(isArticle)?'/ajax/articles/commentdelete/c'+commentId+'/':'/ajax/user/id'+User.id+'/album/photo'+SelPhoto+'/c'+commentId+'/delete/';
                    



            var post = {
                ajax: 'ajax'
            };
            $.ajax({
                url: url,
                type: 'post',
                data: post,
                success:Lib.Comment.commentDeleteResult
            });
        },

        commentDeleteResult:function(data) {
            eval('var answer='+data);
            answer; // объект с данными

            Lib.PopupMsg.AddMessages(answer.messages);

            if (answer.isOk) {
                // делаем из коммента удаленный
                var commentContainer=$('#comment'+answer.comment_id+'-content');
                var commentContainerDiv = $('#comment'+answer.comment_id+'-content > div');
                $('p, span',commentContainer).remove();

                commentContainerDiv.prepend('<p class="del-message">комментарий удален</p>');
            }

        },

        /**
         * выполняет проверку и отправку формы
         */
       commentSend: function() {
            if(!Lib.Comment.init()){
                return false;
            }
            var commentVal=$('#comment-text',Lib.Comment.commentForm).val().trim();
            var parentVal=$('#comment-parent',Lib.Comment.commentForm).val();

            // проверить наличие текста в форме
            if (commentVal.length<2) {
                // выдать ошибку
                $('.error-text',Lib.Comment.commentFormBox).html((commentVal.length==0)?'нужно ввести комментарий':'комментарий слишком короткий');
                Lib.Comment.commentFormBox.addClass('with-error');
                return false;
            }
            Lib.Comment.commentFormBox.removeClass('with-error');

            // отправить запрос на ajax-обработчик
            var post = {
                ajax: 'ajax',
                comment: commentVal,
                parent_id: parentVal
            };
            $.ajax({
                url: '/ajax'+Lib.Comment.commentForm.attr('action'),
                type: 'post',

                data: post,
                beforeSend:function(){$('#comment-send',Lib.Comment.commentForm).attr('disabled','disabled')},
                success: Lib.Comment.commentSendResult
            });
        },

        /**
         * выполняет обработку результата добавления
         */
        commentSendResult: function(data) {
            eval('var answer='+data);
            answer; // объект с данными
            if (answer.isOk) {
                Lib.Comment.updateComments(answer.comments);
                Lib.User.updateUser(data);
                $('#comment-send',Lib.Comment.commentForm).removeAttr('disabled');
                Lib.Comment.commentHideForm();
            }
            else {
                // выдать ошибку
                $('.error-text',Lib.Comment.commentFormBox).html(answer.errorText);
                $('#comment-send',Lib.Comment.commentForm).removeAttr('disabled');
                Lib.Comment.commentFormBox.addClass('with-error');
            }

        },


         updateComments:function(comments) {
            if(!Lib.Comment.init()){
                return false;
            }
            for (var i=0;i<comments.length;i++) {
                var commentInfo=comments[i];
                // добавляем блок коммента
                var newComment=Lib.Comment.commentHTML.replace(/#ID#/ig,commentInfo.comment_id);
                if (commentInfo.parent_id==0) {
                    // добавляем на верхний уровень
                    $('#comments').append(newComment);
                }
                else {
                    // добавляем как вложеный
                    var parentCommentItem=$('#comment'+commentInfo.parent_id);
                    if (!$('ol.nm',parentCommentItem).length) {
                        // еще не было вложенных. нужно добавить блок
                        parentCommentItem.append('<ol class="nm">'+newComment+'</ol>');
                    }
                    else {
                        // вложенные есть - просто добавляем в конец
                        $('ol.nm:first',parentCommentItem).append(newComment);
                    }
                }

                // заполнить данные
                var newCommentItem=$('#comment'+commentInfo.comment_id);
                $('p',newCommentItem).html(commentInfo.text);
                $('.say-text',newCommentItem).html(commentInfo.say_text);
                $('.comment-date',newCommentItem).html(commentInfo.date);
                $('.comment-nickname',newCommentItem).html(commentInfo.user.nickname);
                $('a',newCommentItem).attr('href','/user/id'+commentInfo.user.id+'/');
                $('img',newCommentItem).attr('src',commentInfo.user.avatar_s);
                if (commentInfo.user.id == MyUser.id) {
                    $('dl',newCommentItem).addClass('my-comment');
                }
                $('.comment-answer',newCommentItem).click(function(){Lib.Comment.commentAnswer($(this).attr('rel'));});
                if (commentInfo.allowDelete) {
                    $('.comment-delete',newCommentItem).click(function(){Lib.Comment.commentDelete($(this).attr('rel'));});
                }
                else {
                    $('.comment-delete',newCommentItem).remove();
                }

                // показать
                newCommentItem.show();
            }
        }






}


