﻿/*
Комментарии, обрабатываются комментарии для объектов - Article или Voting
*/

function Comments(mag) {
	// селектор, для поиска модуля
	this._moduleSelector = '#new_comment_div';
	
	this._textSelector = '#write_comment textarea';
	
	
	// сообщение об ошибке
	this._error = '#error_block';
	
	this._bind();
	
	
	this._mag = mag;
	
	// id Объекта который комментируется
	this._subjectId = null;
	
	// Название объекта, который комментируется
	this._subjectText = null;
	
	// селектор окна для написания комментариев
	this._commentWindowSelector = '#m-comment-window';
	
	// id комментария к которому пишется текущий
	this._targetCommentId = undefined;
	
	// id пользователя, которому пишется комментарий
	this._targetUserId = undefined;
	
	this._gift = false;
	this._giftEmail = 'Введите E-mail'
	    
	    
	this._lastUserLi = null;

}

Comments.prototype = {
	_bind: function() {
		var that = this;
		
		$('#show_all_comments_button_div input').live('click', function() {
		    that._showAllComments();  
		});
		
		// клик на кнопку "разместить комментарий"
		$('#article_add_comment').live('click', function() {
			that.showAddComment('');
		});
		
		
		
		$('.hide_artile_com #c_articles_col, #show_all_comments').live('click', function() {		    
		    $('#m-article').removeClass('hide_artile_com');		
		    that._hideGift();
		});
		
		$('#show_all_comments').live('click', function() {          
            $('#m-article').removeClass('hide_artile_com');
            that._showAllComments(); 
        });
		
		$('.toEnter, .toRegistration').live('click', function() {		    
		    mMessageBox.close();
		    $(that._moduleSelector).trigger('onshowenter', { 
		        id: that._subjectId, 
		        msg: $(that._textSelector).val(),
		        cid: that._targetCommentId,
		        uid: that._targetUserId,
		        email: $('#email_to_send').val()
		    });
		});
		
		$('#send_new_comment input').live('click', function() {
			var message = $(that._textSelector).val();
			if (message.length > 0) {
				if (message.length > 1000) {
					$(that._error).text('Комментарий слишком длинный');
				} else {
				    $(that._error).text('');
				    
				    var email = $('#email_to_send').val();
                    if (that._gift && (!isValidEmail(email) || email.length == 0)) {
                        $(that._error).text('Введите корректный е-mail');
                        return;
                    }
                    
				    
					if (!account.isLogin) {		
					    mMessageBox.alert('Для добавления комментария необходимо выполнить <b class="messageBoxLink toEnter pointer">вход</b> или <b class="messageBoxLink toRegistration pointer">зарегистрироваться</b>');						
					} else {	
					    
					    
					    
					    if (that._gift) {
					        
					        $.ajax({
	                            type: 'post',
	                            url: 'ajax/share_friend_from_comment/', 
	                            data: {
	                                comment_text: message,
	                                user_id: account.id,
	                                object_id: that._subjectId,
	                                cid: that._targetCommentId,
	                                email: email,
	                                link: document.location.hash.substr(1),
	                                mag: that._mag
	                            }, 
	                            success: function(data) {
	                                if (data == 0) {
	                                    alert('Необходим выполнить вход или зарегистрироваться');
	                                } else {                                
	                                    //that.show(that._subjectId);
	                                    that._reload();
	                                    that.hide();
	                                }
	                            }
	                        });
					        
					    } else {
					        
					         
					            
					            $.ajax({
		                            type: 'post',
		                            url: 'ajax/object_public_comments', 
		                            data: {
		                                comment_text: message,
		                                user_id: account.id,
		                                object_id: that._subjectId,
		                                cid: that._targetCommentId,
		                                email: email
		                            }, 
		                            success: function(data) {
		                                if (data == 0) {
		                                    alert('Необходим выполнить вход или зарегистрироваться');
		                                } else {                                
		                                    //that.show(that._subjectId);
		                                    that._reload();
		                                    that.hide();
		                                }
		                            }
		                        });
					            
					        
					        
					    }
					    
						
					}
				}
			
			} else {
			    $(that._error).text('Вы не ввели комментарий');
			}

		});
				
		// отменить отправку формы
		$('#m-comment-form').live('submit', function() {
			return false;
		});

		$('.antw', '#c_div_for_articles_content').live('click', function () {
            var data = $(this).closest('.comment_answer, li').data();
            that.showAddComment(data.username + ', ', data.uid, data.cid);
        });
		
		$('#users_wrap li').live('click', function () {
           that._selectUserLi($(this));
           return false;
        });
		
		// кнопка подписаться/отписаться
		$('.subscribe').live('click', function() {
		    if (!account.isLogin) return;
		    
		    var subs = $(this), 
		        data = subs.closest('li').data(),
		        username = subs.closest('li').find('i').text(),
		        action, 
		        title;
		        if (subs.hasClass('subscribe_a')) {
		            action = 'del';
		            title = 'Подписаться на комментарии ' + username;
		        } else {
		            action = 'add';
		            title = 'Отписаться от комментариев ' + username;
		        }
		    
	        $.post('/ajax/user_' + action + '_subscribe', data, function() {
                subs.toggleClass('subscribe_a').attr('title', title);
            });		  		    
		});
		
		$('#invite').live('click', function(event) {
		        if (that._gift) {
	                that._hideGift(); 
	            } else {
	                that._showGift();
	            }
		 	    
		});
		
		
		$.scrollArea({
		    wrap : '#users_wrap',
	        content : '#users_wrap ul',
	        DISABLED_CLASS : 'disabled_btn',
	        upButton : '#move_up_user',
	        downButton : '#move_down_user'
		});	
		
		
		$('#more_articles').live('click', function() {
		   $.ajax({
		      url: '/ajax/return_articles_rubrick',
		      type: 'get',
		      dataType: 'html',
		      data: { rub: $(this).data('rubrik-id') },
		      succes: function(html) {
	          // show html
		      }
		   }); 
		});
		
		$('#email_to_send').live({
		    focusin: function() {
		        if ($(this).val() === that._giftEmail) {
		            $(this).val("");
		        }
		    },
		    focusout: function() {
		        if ($(this).val().length === 0) {
		            $(this).val(that._giftEmail);
		        }
		    }
		}); 
		
		$('#articles_sort i').live('click', function () {
		    var i = $(this);
		    i.addClass('current');
		    $('#articles_sort i').not(i).removeClass('current');
            that._sortBy(i.data('order'));
        });
	},
	
	_sortBy: function (order) {
	    var sorter = $.noop;
	    
	    switch (order) {
        case "date":
            sorter = function(a,b) {
                return $(a).data('date') - $(b).data('date');
            }           
            break;
            
        case "rate":
            sorter = function(a,b) {
                return $(b).data('rate') - $(a).data('rate');
            }           
            break;
            
        case "com":
            sorter = function(a,b) {
                return parseInt($(b).find('.coms_for_articles').text(), 10) -  parseInt($(a).find('.coms_for_articles').text(), 10);
            }           
            break;

        default:
            break;
        }
	    
	    var ul = $("#div_for_articles_content ul");
	    var s = $("#div_for_articles_content li").toArray().sort(sorter);
	    ul.empty();

	    for (var i = 0, l = s.length; i < l; i++) {
	        ul.append(s[i]);
	    }
    },

	_showAllComments: function() {
	    var li = $('#c_div_for_articles_content li'),
	        cansw = $('#c_div_for_articles_content .comment_answer');
        if (li.last().length && li.last().is(':visible')) {
            li.filter(":gt(1)").hide();
            cansw.hide();
            $('#c_div_for_articles_content ul').animate({height: '180px'}); 
            $('#c_div_for_articles_content').animate({ height: '224px'});
        } else {
            li.show();
            cansw.show();
            var h = $(window).height() - 240;
            if (h < 180) h = 180;
            $('#c_div_for_articles_content ul').animate({height: h + 'px'});
            $('#c_div_for_articles_content').animate({ height: h + 38 + 'px'});
        }
	},
	
	_selectUserLi: function(li) {
	    if (li.not('.empty, .current')) {           
            li.addClass('current');
            this._lastUserLi = li;
            this._targetUserId = li.data('uid');
            $('#users_wrap li').not(li).removeClass('current');
        }  
	},
	
	_deSelectUserLi: function () {
	    $('#users_wrap li').removeClass('current');
    },
	
	_showGift: function() {
	    this._gift = true;
        $('#write_comment textarea').animate({'height' : '118px'});
        $('#email_to_send').slideDown(function () {
            setTimeout(function () {
                $('#email_to_send').trigger('focusout');               
            }, 1);            
        });
        this._deSelectUserLi();
	}, 
	
	_hideGift: function() {
	    this._gift = false;
	    $(this).val('');
        $('#write_comment textarea').animate({'height' : '153px'});
        $('#email_to_send').slideUp();

        this._lastUserLi && this._selectUserLi(this._lastUserLi);
	},
	
	
	showAddComment: function (msg, userId, targetCommentId, email) {
	    // показать окно для добавления
        //$(this._commentWindowSelector).css('left', $('.topPanel').offset().left + 250).show();
        //$('#m-comment-title').text('Ваш комментарий к статье: ');
	    
	    if (email) {
	        this._showGift();
	        $('#email_to_send').val(email);
	    } else {
	        this._hideGift();
	        $('#email_to_send').val(this._giftEmail);
	    }
	   
	    
        // заполнить сообщение
        $(this._textSelector).val(msg);
        
        //$('#m-comment-subject').text(this._subjectText);
        
        // переключиться на добавление комментария
        $('#m-article').addClass('hide_artile_com');
        
        if (userId) {
            this._targetUserId = userId;
            var user = $('#users_wrap li[data-uid=' + userId + ']').show().addClass('current');
            $('#users_wrap li').not(user).removeClass('current').hide();
        } else {
            this._targetUserId = undefined;
        }
        
        if (targetCommentId) {
            this._targetCommentId = targetCommentId;
        } else {
            this._targetCommentId = undefined;
        }
        
        // счётчик - клик на кнопку "разместить комментарий"
        logEvent('clicktocomment');
    },
    
	bind: function(eventType, handler) {
		$.fn.bind.apply(this._module, arguments);
	},
	
	live: function(eventType, handler) {
		$.fn.live.apply($(this._moduleSelector), arguments);
	},
	
	// установить id объекта, который комментируется
	setSubject: function(id, text) {
		this._subjectId = id;
		this._subjectText = text;
	},
	
	// перезагрузить комментарии для текущего объекта
	_reload: function() {
		var that = this;
		$.ajax({
			type: 'get',
			url: 'ajax/reload_comments', 
			dataType: 'html',
			data: {	id: that._subjectId, mag: that._mag }, 
			success: function(html) {
				$('#c_div_for_articles_content').html(html);
				$(that._moduleSelector).trigger('onreload', { subjectId : that._subjectId });
			}
		});
	},
	
    
    hide: function() {
     // скрыть окно для добавления комментария
        $('#m-article').removeClass('hide_artile_com');
        $(this._textSelector).val('');
    }
}
