/*
 *      Comments by Ivan "CoolSpot" Koldaev (pixus.ru@gmail.com) 
 *      for AUTO.RU projects
 *
 *      v.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 alpha
 *
 *      First release: 22.01.09
 *      Last change:   6.02.09
 *
 *      Habraprivet!
 */

comments = function(){
    this.cmn = new commonFunctions();
    this.init();
};

comments.prototype = {
    'ajaxDebug':false,
    'ffDebug':false,
    'cmn':false,
    'replyForm':false,
    'lastRefresh':0,
    'commentStaticForm':false,
    'commentsWrap':false,
    'showStaticFormLink':false,
    'projectId':0,
    'subjectGroupId':0,
    'subjectId':0,
    'loadingBar':false,
    'auth':true,
    'admin':false,
    
    'init':function(){
        var cmn 				= this.cmn;
        var selfObj 			= this;
        this.commentStaticForm 	= cmn.i2e('commentStaticForm');
        this.commentsWrap 		= cmn.i2e('commentsWrap');
        this.showStaticFormLink = cmn.i2e('showStaticFormLink');
        var form           		= selfObj.commentStaticForm;
        this.projectId     		= parseInt(form.project_id.value);
        this.subjectGroupId     = parseInt(form.subject_group_id.value);
        this.subjectId     		= parseInt(form.subject_id.value);
        cmn.i2e('commentStaticSubmit').onclick = function(){
            var parent_comment_id = parseInt(form.parent_comment_id.value);
            var text              = form.comment_text.value;
            form.comment_text.value = '';
            selfObj.addCommentRequest(text, selfObj.projectId, selfObj.subjectGroupId, selfObj.subjectId, parent_comment_id, function(a, b){selfObj.addCommentCallback(a, b);}, 0);
            return false;
        };
    },
    
    'makeCommentsControlWidget':function(){
    	if (!this.auth) return false;
        var cmn 	= this.cmn;
        var selfObj = this;
        var wrap 	= cmn.createEl('div', 'commentsControlWidget', 0);
        wrap.innerHTML = 'Обновить<br />комментарии';
        wrap.onclick   = function(){
            selfObj.refreshCommentsRequest();
        };
        document.body.appendChild(wrap);
    },
    
    'makeReplyForm':function(link){
    	if (!this.auth) return false;
        var cmn = this.cmn;
        var selfObj = this;
        this.killReplyForm();
        this.hideStaticForm();
        var comment_id = link.getAttribute('comment_id');
        var commentBox    = cmn.i2e('comment-'+comment_id);
        
        var replyFormWrap = cmn.createEl('div', 0, 'replyFormWrap');
        commentBox.appendChild(replyFormWrap);

        var replyTextarea = cmn.createEl('textarea', 0, 0);
        replyFormWrap.appendChild(replyTextarea);
        
        /*
        var previewButton = cmn.createEl('input', 0, 0);
        previewButton.setAttribute('type', 'button');
        previewButton.setAttribute('value', 'Предпросмотр');
        replyFormWrap.appendChild(previewButton);
        */
        
        var submitButton  = cmn.createEl('input', 0, 0);
        submitButton.setAttribute('type', 'button');
        submitButton.setAttribute('value', 'Отправить');
        
        var project_id 		 = selfObj.projectId;
        var subject_group_id = selfObj.subjectGroupId;
        var subject_id 		 = selfObj.subjectId;
        submitButton.onclick = function(){
            selfObj.addCommentRequest(replyTextarea.value, project_id, subject_group_id, subject_id, comment_id, function(a, b){selfObj.addCommentCallback(a, b);}, 0);            
            selfObj.killReplyForm();
            selfObj.createLoadingBar(cmn.i2e('comment-'+comment_id));
        };
        replyFormWrap.appendChild(submitButton);
        
        this.replyForm = replyFormWrap;
        replyTextarea.focus();
        
        return false; // Link deactivation
    },
    
    'editComment': function(comment_id, token)
    {
    	var _obj = this;
    	var commentTextP = $('div#comment-' + comment_id + ' p.commentText');
    	
    	if(0 == $('textarea', commentTextP).length){
	    	var commentText = commentTextP.html();
	    	commentText = jQuery.trim(commentText);
	    	//commentText = commentText.split('<br>').join("\n");
	    	commentText = commentText.replace(/<br[^>]*>/gi, "\n");
	    	var textarea = document.createElement('textarea');
	    	textarea.className = 'editComment';
	    	textarea.value = commentText;
	    	commentTextP.html('');
	    	commentTextP.append(textarea);
	    	var buttonSave = document.createElement('input');
	    	buttonSave.setAttribute('type', 'button');
	    	buttonSave.value = 'Сохранить';
	    	buttonSave.onclick = function(){
	    			var newText = textarea.value;
	    			var callback = function(a,b){
	    				_obj.addCommentCallback(a,b);
	    				commentTextP.html(newText.split("\n").join('<br>'));
	    			};
	    			_obj.addCommentRequest(newText, 0, 0, 0, 0, callback, comment_id, token);
	    		};
	    	commentTextP.append(buttonSave);
	    	var buttonCancel = document.createElement('input');
	    	buttonCancel.setAttribute('type', 'button');
	    	buttonCancel.value = 'Отмена';
	    	buttonCancel.onclick = function(){
	    		commentTextP.text(commentText);
			};
	    	commentTextP.append(buttonCancel);
    	}
    },	
    
    'killReplyForm':function(){
        if(this.replyForm) {
            this.replyForm.parentNode.removeChild(this.replyForm);
            this.replyForm = false;
        }
    },
    
    'findParent':function(el){
        /* UNDER CONSTRUCTION */
        el.getAttribute('pid');
        return true;
    },
    
    'refreshCommentsRequest':function(){
        var selfObj = this;
        var url = '/comments/ajax/getComments.html';
        if (!this.ajaxDebug) url += '?debug=0'; // DEBUG        
        
        var data = {
        			'project_id'		: this.projectId,
        			'subject_group_id'	: this.subjectGroupId,
        			'subject_id'		: this.subjectId,
        			'lastRefresh'		: this.lastRefresh
        			};
        $.ajaxSetup({cache:false, error:function(XMLHttpRequest, textStatus, errorThrown){if (selfObj.ffDebug) console.log('Ашипка!', textStatus);}});
        var callback = function(xml, textStatus){
            var status = $(xml).find('status').text();
            selfObj.updateCommentsByXML(xml);
            if (selfObj.ffDebug && console.log) console.log('AJAX backend returned status:', status);
        };
        $.post(url, data, callback, 'xml');
    },
    
    'banUserConfirm': function(user_id, token){
    	var confirmed = false;
    	if(window.confirm('Пользователю будет запрещено оставлять комментарии на всех проектах, все его сообщения будут удалены.\nСогласны?')){
    		this.banUserRequest(user_id, token);
    	} else {
    		alert('Трус!!!');
    	}
    },
    
    'banUserRequest':function(user_id, token){
    	var _obj = this;
    	var comment_wrap_id = 'comment-' + user_id;
    	var url = '/comments/ajax/banUser.html';
        if (!this.ajaxDebug) url += '?debug=0'; // DEBUG
        
        var data = {'user_id':user_id, 'token':token};
        var callback = function(xml, textStatus){
        	var status = $(xml).find('status').text();
        	switch (status){
	        	case 'ok':
	        		alert('Пользователь заблокирован. Все его комментарии удалены.');
	        		break;
	        	case 'denied':
	        		alert('У вас нет прав для данной операции');
	        		break;
        	}
        }
        
        $.ajaxSetup({cache:false, error:function(XMLHttpRequest, textStatus, errorThrown){if (_obj.ffDebug && console.log) console.log('Ашипка!', textStatus);}});
        $.get(url, data, callback, 'xml');
    },
    
    'deleteCommentRequest':function(comment_id, token){
    	var _obj = this;
    	var comment_wrap_id = 'comment-' + comment_id;
    	var url = '/comments/ajax/deleteComment.html';
        if (!this.ajaxDebug) url += '?debug=0'; // DEBUG
        
        var data = {'subject_id':this.subjectId, 'comment_id':comment_id, 'token':token};
        var callback = function(xml, textStatus){
        	var status = $(xml).find('status').text();
        	switch (status){
	        	case 'ok':
	        		$('#'+comment_wrap_id).toggleClass('hidden', true);
	        		$('#'+comment_wrap_id).find('.restoreComment').css('display', '');
	        		$('#'+comment_wrap_id).find('.deleteComment').css('display', 'none');
	        		break;
	        	case 'denied':
	        		alert('У вас нет прав для данной операции');
	        		break;
        	}
        }
        
        $.ajaxSetup({cache:false, error:function(XMLHttpRequest, textStatus, errorThrown){if (_obj.ffDebug && console.log) console.log('Ашипка!', textStatus);}});
        $.get(url, data, callback, 'xml');
    },
    
    'restoreCommentRequest':function(comment_id, token){
    	var _obj = this;
    	var comment_wrap_id = 'comment-' + comment_id;
    	var url = '/comments/ajax/restoreComment.html';
        if (!this.ajaxDebug) url += '?debug=0'; // DEBUG
        
        var data = {'subject_id':this.subjectId, 'comment_id':comment_id, 'token':token};
        var callback = function(xml, textStatus){
        	var status = $(xml).find('status').text();
        	switch (status){
	        	case 'ok':
	        		$('#'+comment_wrap_id).toggleClass('hidden', false);
	        		$('#'+comment_wrap_id).find('.restoreComment').css('display', 'none');
	        		$('#'+comment_wrap_id).find('.deleteComment').css('display', '');
	        		break;
	        	case 'denied':
	        		alert('У вас нет прав для данной операции');
	        		break;
        	}
        }
        
        $.ajaxSetup({cache:false, error:function(XMLHttpRequest, textStatus, errorThrown){if (_obj.ffDebug && console.log) console.log('Ашипка!', textStatus);}});
        $.get(url, data, callback, 'xml');
    },
    
    'addCommentRequest':function(text, project_id, subject_group_id, subject_id, parent_comment_id, callback, comment_id, token){
        var selfObj = this;
        if (typeof token == 'undefined') token = false;
        if (typeof comment_id == 'undefined') comment_id = 0;
        
        var url = '/comments/ajax/addComment.html';
        if (!this.ajaxDebug) url += '?debug=0'; // DEBUG
        var data = {
        			'text'		 : text, 
        			'project_id' : project_id, 
        			'subject_group_id'	: subject_group_id, 
        			'subject_id'		: subject_id, 
        			'parent_comment_id'	: parent_comment_id, 
        			'comment_id'		: comment_id, 			// если > 0 , то выполняется редактирование комментария
        			'lastRefresh' : this.lastRefresh,
        			'token'		: token
        			};
        
        if (this.ajaxDebug) {
            var callback = function(data, textStatus){
                alert(data);
                alert(textStatus);
            };
        };
        
        $.ajaxSetup({cache:false, error:function(XMLHttpRequest, textStatus, errorThrown){if (selfObj.ffDebug && console.log) console.log('Ашипка!', textStatus);}});
        var dataType = (this.ajaxDebug)?'text':'xml'; // DEBUG
        $.post(url, data, callback, dataType);
    },
    
    'addCommentCallback': function(xml, textStatus)
    {
    	this.destroyLoadingBar();
        var status = $(xml).find('status').text();        
        this.updateCommentsByXML(xml);
        switch (status) {
            case 'ok':
            	break;
            case 'err':
            	alert('Ошибка.');
            	break;
            case 'denied':
            	alert('Операция запрещена!');
            	break;
            case 'no_auth':
            	alert('Вы не авторизованы! Пожалуйста, авторизуйтесь.');
            	break;
            case 'no_user':
            	alert('Ошибка! Пользователь не найден.');
            	break;
            case 'user_not_active':
            	alert('Ошибка! Пользователь не активирован.');
            	break;
            case 'user_blocked':
            	alert('Ошибка! Вы заблокированы.');
            	break;
            case 'too_short_comment':
            	alert('Ошибка! Слишком короткий комментарий.');
            	break;
            case 'too_fast':
            	alert('Ошибка! Перед написанием нового комментария необходимо подождать 20 секунд.');
            	break;
            default:
            	break;
        }

        if (this.ffDebug && console.log) console.log('AJAX backend returned status:', status);
    },
    
    'updateCommentsByXML':function(xml)
    {
        var selfObj = this;
        var cmn = selfObj.cmn;
        $(xml).find('comment').each(function(){
            var comment = $(this);
            var text_node = comment.find('text');
            var text = text_node.text();
            var comment_level = parseInt(comment.attr('level'));
            var comment_id = parseInt(comment.attr('self_id'));
            var comment_time = parseInt(comment.attr('timestamp'));
            var lid = parseInt(comment.attr('lid'));
            var parent_id = parseInt(comment.attr('parent_id'));
            var date = comment.attr('date');
            var hidden = parseInt(comment.attr('hidden'));
            
            selfObj.updateLastRefresh(comment_time);
            
            var author = comment.find('author');
            var user_alias = author.text();
            var user_id = author.attr('user_id');
            var avatar_url = author.attr('avatar_url');
            var showcard = author.attr('showcard');
            var commentObj = {
                'id'    :comment_id,
                'level' :comment_level,
                'lid' :lid,
                'parent_id' :parent_id,
                'date' :date,
                'time' :comment_time,
                'user_id':user_id,
                'user_alias':user_alias,
                'avatar':avatar_url,
                'showcard':showcard,
                'text':text,
                'hidden':hidden
            };
            
            if (document.getElementById('comment-'+comment_id)) {
                if (selfObj.ffDebug && console.log) console.log('Comment #', comment_id, 'already exsist! Skipped...');
                return true; // CONTINUE
            }
            
            if (comment_level > 1){
                var parent_comment = document.getElementById('comment-'+parent_id);
                var target_comment = selfObj.findLastSubChild(parent_comment);
                
                if (!target_comment) console.error('Cant resolve lastSubChild for comment #', parent_id, '. Comment #', comment_id, '(pid='+parent_id+')', 'was not attached');
                $(target_comment).after(selfObj.commentTemplate(commentObj));
                if (selfObj.ffDebug && console.log) console.log('Comment #', comment_id, '(pid=', parent_id,') successfully added after comment #', target_comment.getAttribute('self_id'));
            }else{
                $('#commentStaticForm').before(selfObj.commentTemplate(commentObj));
                if (selfObj.ffDebug && console.log) console.log('Comment #', comment_id, 'successfully attached to root.');
            }
            
            //alert('Comment "'+text+'"\nAuthor: '+user_alias);
        });        
    },
    
    'findLastSubChild':function(el)
    {
        var parent_id = parseInt(el.getAttribute('self_id'));
        var lastChild = this.findLastElementByAttribute(this.commentsWrap, 'pid', parent_id);
        if(lastChild){
            return this.findLastSubChild(lastChild);
        } else {
            return el;
        }
    },
    
    'findLastElementByAttribute':function(container, attribute, value){
        var childs = container.childNodes;
        var currNode, currValue;
        var lastNode = false;
        for(var i=0; i < childs.length; i++){
            currNode = childs[i];
            if(!(currNode.tagName == 'DIV' || currNode.tagName == 'div')) continue;
            currValue = parseInt(currNode.getAttribute(attribute));
            if (currValue == value) {
                lastNode = currNode;
            }
        }
        return lastNode;
    },
    
    'updateLastRefresh':function(value){
        return this.lastRefresh = (value > this.lastRefresh)?value:this.lastRefresh;
    },
    
    'commentTemplate':function(comment){
    	var hidden_class = (comment.hidden == 1)?' hidden':'';
        var template = '<div self_id="'+comment.id+'" time="'+comment.timestamp+'" pid="'+comment.parent_id+'" class="comment'+ hidden_class +'" style="margin-left: '+((comment.level-1)*40)+'px" id="comment-'+comment.id+'">';
        template += '<div class="user" style="background-color: #eee">';
        if(comment.showcard){
            template += '<a href="http://users.auto.ru/'+comment.user_id+'.html">';
        }
        if(comment.avatar){
            template += '<img onmousemove="commentsObj.showBigAvatar(this, event);" src="'+comment.avatar+'" />';
        } else {
            template += '<div class="no_avatar"></div>';
        }
        if(comment.showcard){
            template += '</a>';
            template += '<a href="http://users.auto.ru/'+comment.user_id+'.html">';
        }
        template += comment.user_alias;
        if(comment.showcard){
            template += '</a>';
        }
        template += '<a name="comment-'+comment.id+'"><span>'+comment.date+'</span></a>';
        if(comment.level > 1){
            template += '<a href="#comment-'+comment.parent_id+'" title="Ответ на..." class="findParent" onclick="return commentsObj.findParent(this);">&uarr;</a>';
        }
        template += '</div><p>'+comment.text+'</p>';
        if(this.auth){
        	template += '<p class="replyButtonWrap"><a href="#" onclick="javascript:commentsObj.makeReplyForm(this);return false;" comment_id="'+comment.id+'">Ответить</a></p>';
        }
        template += '</div>';
        return template;
    },
    
    'showBigAvatar':function(el, e){
    	var selfObj = this;
    	el.onmouseout = selfObj.hideBigAvatar;
    	var big_image_url = el.src;
    	big_image_url = big_image_url.replace(/small\//, '');
		var big_avatar_wrap = false;
		if (!(big_avatar_wrap = this.cmn.i2e('big_avatar_wrap'))){
			big_avatar_wrap = this.cmn.createEl('div', 'big_avatar_wrap', 0);
			document.body.appendChild(big_avatar_wrap);
			var big_avatar_image = new Image();
			big_avatar_image.id = 'big_avatar_image';
			big_avatar_image.src = big_image_url;
			big_avatar_wrap.appendChild(big_avatar_image);
		}
		var top=0;
		var left=0;
		if(document.body.scrollTop+document.documentElement.scrollTop){
		top=document.body.scrollTop+document.documentElement.scrollTop;
		if(document.body.scrollTop==document.documentElement.scrollTop){top=document.documentElement.scrollTop;}
		if(document.body.scrollLeft){left=document.body.scrollLeft;}
		}
		big_avatar_wrap.style.left=left+e.clientX+5+'px';
		big_avatar_wrap.style.top=top+e.clientY+5+'px';
    },
    
    'hideBigAvatar':function(){
    	var big_avatar_wrap = document.getElementById('big_avatar_wrap');
    	big_avatar_wrap.parentNode.removeChild(big_avatar_wrap);
    },
    
    'hideStaticForm':function(){
    	if(!this.commentStaticForm)return false;
    	this.showStaticFormLink.style.display = 'block';
    	this.commentStaticForm.style.display = 'none';
    },
    
    'showStaticForm':function(){
    	if(!this.commentStaticForm)return false;
    	this.showStaticFormLink.style.display = 'none';
    	this.killReplyForm();
    	this.commentStaticForm.style.display = 'block';
    },
    
    'createLoadingBar':function(targetEl){
    	var cmn = this.cmn;
    	var loadingDiv = cmn.createEl('div', 'loadingBar');
    	var loadingImg = new Image();
    	loadingImg.src = 'http://i.auto.ru/comments/ajax-loader.gif';
    	loadingImg.setAttribute('title', 'Обновление...');
    	loadingImg.setAttribute('alt', 'Обновление...');
    	loadingDiv.appendChild(loadingImg);
    	targetEl.appendChild(loadingDiv);
    	this.loadingBar = loadingDiv;
    },
    
    'destroyLoadingBar':function(){
    	if(this.loadingBar){
    		this.loadingBar.parentNode.removeChild(this.loadingBar);
            this.loadingBar = false;
    	}
    }
}

$(document).ready(function(){
    window.commentsObj = new comments();
    window.commentsInitCallback();
});
