var Comments = new Class({
	initialize: function() {
		
		this.add_textarea = $('add-textarea');
		this.add_from = $$('input[name=from]');
		this.add_button = $('add-button');
		this.delete_btns = 'comment-delete';
		this.restore_btns = 'comment-restore';
		this.edit_btns = 'comment-edit';
		this.edit_save_btns = 'comment-edit-save';
		
		this.counter = $('comment-counter');
		this.list = $('comments-list');
		
		this.show_error_timeout = 2500;
		this.show_success_timeout = 5000;
		
		this.list_disabler = new Disabler($('list-disabler'), 'hidden');
		this.disabler = new Disabler($('add-comment-disabler'), 'hidden');
		this.textarea_disabler = new Disabler($('add-textarea-disabler'), 'hidden');
		
		this.area_msg = $('msg-row');
		this.area_current = $('button-row');
		this.bar_height = this.area_current ? this.area_current.getCoordinates().height : 0;
		
		this.auth_block = $('ap-auth-block');
		
		this.input_email = $('ap-login');
		this.input_password = $('ap-password');
		this.input_password_txt = $('ap-password-txt');
		this.input_remember = $('ap-remember');
		this.btn_login = $('ap-btn-login');
		this.input_captcha = $('ap-login-captcha');
		
		this.input_reg_password = $('ap-reg-password');
		this.input_reg_password_txt = $('ap-reg-password-txt');
		this.input_reg_conf_password = $('ap-reg-conf-password');
		this.input_reg_conf_password_txt = $('ap-reg-conf-password-txt');
		this.input_reg_email = $('ap-reg-login');
		this.input_reg_nickname = $('ap-nickname');
		this.input_reg_captcha = $('ap-captcha');
		this.input_reg_agree = $('ap-reg-agree');
		this.btn_reg = $('ap-btn-registration');
		
		this.favorite_class = 'is_favorite';
		this.not_favorite_class = 'not_favorite';
		
		this.setActionHandlers();
	},
	
	setActionHandlers: function() {
		
		var obj = this;
		
		obj.initAdd();
		obj.initDelete();
		obj.initRestore();
		obj.initEdit();
		obj.initEditSave();
		
		if(this.btn_login) {
			this.btn_login.addEvent('click', function(e){
				new Event(e).stop();
				obj.signin();
			});
		}
		
		if(this.btn_reg) {
			this.btn_reg.addEvent('click', function(e){
				new Event(e).stop();
				obj.register();
			});
		}
	},
	
	changeCount: function(delta){
		
		var obj = this;
		var delta = delta || 0;
		
		if (!obj.counter) {
			return;
		}
		
		var cnt = obj.counter.get('text').replace(/\(|\)/g, '');
		cnt = cnt ? cnt.toInt() : 0;
		
		obj.setCount(cnt + delta);
	},
	
	setCount: function(cnt){
		
		var obj = this;
		
		if (!obj.counter) {
			return;
		}
		
		if (cnt) {
			
			obj.counter.set('text', '(' + cnt + ')');
		}
		else {
			obj.counter.set('text', '');
		}
		
	},
	
	refreshPage: function(comments){
		
		var obj = this;
		
		obj.list.getChildren().dispose();
		
		if (comments.length) {
			
			for (var i = 0; i < comments.length; i++){
				
				var row = obj.generateLine(comments[i]);
				
				row.inject(obj.list);
			};
		}
		
		obj.initDelete();
		obj.initRestore();
		obj.initEdit();
		obj.initEditSave();
		
		usrp.init(); //UserPopup init
	},
	
	generateLine: function(comment){
		
		var obj = this;
		
		var html = '';
		
		html += '<div class="disabler"></div>';
		html += 	'<div class="avatar">';
		
		if (!comment.is_deleted.toInt() && !comment.from_moderator.toInt())
		{
			html += '<a href="' + comment.user_page + '"><img src="' + comment.avatar + '" alt="" /></a>';
		}
		else
		{
			html += '<img src="' + comment.avatar + '" alt="" />';
		}
		html += 	'<div class="status" style="background-color: #' +  comment.color + '">' + comment.status + '</div>';
		html += '</div>';
		html += '<div class="comment">';
		html +=		'<div class="info">';
		html +=			'<div class="left">';
		
		if (!comment.is_deleted.toInt() && !comment.from_moderator.toInt())
		{
			html +=			'<div class="nickname ' + (comment.is_online ? 'online' : '') + '">';
			html +=				'<div class="' + (comment.gender ? comment.gender : '') + ' ' + (comment.is_verified.toInt() ? 'verified' : '') + '"></div>';
			html +=				'<a href="' + comment.user_page + '">' + comment.nickname + '</a>';
			html +=			'</div>';
			html +=			'<div class="rating changed ' + (comment.rating.toInt() < 0 ? 'minus' : '') + '">' + comment.rating + '</div>';
		}
		else
		{			
			html +=			'<div class="nickname">' + (comment.is_deleted.toInt() ? comment.nickname : 'Moderator') + '</div>';
		}
		
		html +=				'<div class="time">|<span>' + comment.time + '</span></div>';
		html +=			'</div>';
		html +=			'<div class="right">';
		
		if (!comment.from_moderator.toInt())
		{	
			if (!comment.allow_vote)
			{
				html += 	'<a href="#" rel="' + comment.id + '" class="comment-changed comment-thumb-up-disabled disabled">' + comment.up_cnt.toInt() + '</a>';
				html +=		'<a href="#" rel="' + comment.id + '" class="comment-changed comment-thumb-down-disabled disabled">' + comment.down_cnt.toInt() + '</a>';		
			} 
			else
			{
				html += 	'<a href="' + (comment.my_comment ? comment.votes_href : '#') + '" rel="' + comment.id + '" class="comment-changed comment-thumb-up disabled ' + (comment.my_comment ? 'my' : '') + '">' + comment.up_cnt.toInt() + '</a>';
				html +=		'<a href="' + (comment.my_comment ? comment.votes_href : '#') + '" rel="' + comment.id + '" class="comment-changed comment-thumb-down disabled ' + (comment.my_comment ? 'my' : '') + '">' + comment.down_cnt.toInt() + '</a>';		
			}
			
		}
		
		if (comment.allow_report)
		{
			html +=			'<a href="#" rel="' + comment.id + '" class="report changed ' + (comment.allow_remove ? 'marg' : '') + '">Report</a>';
		}
		else
		{
			html +=			'<div class="reported ' + (!comment.reported ? 'hidden' : '') + (comment.allow_remove ? ' marg' : '') + '">Reported</div>';
		}
		
		if(comment.allow_edit || comment.allow_remove)
		{	
			if (comment.allow_edit)
			{
				html +=		'<a href="#" rel="' + comment.id + '" class="comment-edit">&nbsp;</a>';		
			}
			html +=			'<a href="#" rel="' + comment.id + '" class="comment-delete">&nbsp;</a>';		
		}
							
		html +=			'</div>';		
		html +=		'</div>';		
		html +=		'<div class="clear-both"></div>';		
		html +=		'<div class="comment-body ' + (comment.deleted_comment.toInt() ? ' is_deleted ' : '') + (comment.from_moderator.toInt() ? ' moderator ' : '') + '" id="comment-body-' + comment.id + '">';		
		html +=			comment.body;		
		html +=		'</div>';		
		
		if(comment.allow_edit)
		{	
			html +=	'<div class="textarea-block hidden" id="textarea-block-' + comment.id + '">';
			html +=		'<textarea id="editor-' + comment.id + '" name="editor-' + comment.id + '" cols="" rows=""></textarea>';
			html +=		'<input type="button" class="blue-btn right save-btn comment-edit-save" value="Save" id="save-comment-' + comment.id +  '" />';
			html +=	'</div>';
			html +=	'<p class="hidden msg"></p>';		
		}
								
		html +=	'</div>';		
		html +=	'<div class="clear-both"></div>';		
		
		var row = new Element('div', {
			'class': 'row ' + (comment.my_comment ? 'my-comment' : ''),
			'id': 'comment-' + comment.id,
			'html': html
		});
		
		return row;
	},
	
	addComment: function(comment){
		
		var obj = this;
		
		var line = obj.generateLine(comment);
		var start_height = obj.list.getCoordinates().height;
		
		if (obj.list.getLast() && !comment.is_moderator) {
			
			if (obj.list.getLast().getElement('.comment-edit')) {
				
				obj.list.getLast().getElement('.comment-edit').dispose();
			};
			
			if (obj.list.getLast().getElement('.comment-delete') && !comment.allow_delete) {
				
				obj.list.getLast().getElement('.comment-delete').dispose();
			};
		};
		
		
		obj.list.setStyle('height', start_height).adopt(line);
		
		var end_height = 0;
		
		obj.list.getChildren().each(function(el){
			end_height += el.getCoordinates().height.toInt() + el.getStyle('margin-top').toInt() + el.getStyle('margin-bottom').toInt();
		})
		
		new Fx.Morph(obj.list, {
			duration: 500,
			onComplete: function() {
				
				obj.list.setStyle('height', 'auto');
				
				obj.changeCount(1);
				obj.initDelete();
				obj.initRestore();
				obj.initEdit();
				obj.initEditSave();
				usrp.init(); //UserPopup init
			}
		}).start({
			height: [start_height, end_height]
		});
	},
	
	initAdd: function(){
		
		var obj = this;
			
		if (!obj.add_button) {
			return;
		};
		
		obj.add_button.addEvent('click', function(e){
			
			e.stop();
				
			obj.disabler.show();
			
			var comment = obj.add_textarea.value != obj.add_textarea.title ? obj.add_textarea.value : '';
			var from = obj.add_from.filter(':checked')[0] ? obj.add_from.filter(':checked')[0].value : '';
			var last = obj.list.getLast('.row');
			
			if (last) {
				
				var prev_id = last.id.replace('comment-', '');
			}
			
			new Request.JSON({
				url: window.location.toString(), 
				onSuccess: function(resp){
					
					if (resp.success) {
						
						obj.disabler.hide();
						
						if (!resp.comments.length){
							
							obj.changeCount(1);
							obj.showMessage(resp.message, obj.area_current, resp.success, resp.not_auth);
						}
						else {
							
							for (i = 0; i < resp.comments.length; i++) {
								
								obj.addComment(resp.comments[i]);
							}
							
							new Element('div', {
								'class': 'clear-both'
							}).inject(obj.list);
						}
						
						obj.add_textarea.set('value', obj.add_textarea.title).removeClass('filled');
					}
					else {
						
						if (resp.not_auth) {
							
							obj.showAuthForm();
						}
						
						obj.disabler.hide();
						obj.textarea_disabler.show();
						
						obj.showMessage(resp.message, obj.area_current, resp.success, resp.not_auth);
					}
				}
			}).post({
				Event: 'AddComment', 
				body: comment,
				prev_id: prev_id,
				from: from
			});
		});
		
	},
	
	initDelete: function(){
		
		var obj = this;
			
		$$('.' + obj.delete_btns).each(function(el){
			
			el.removeEvents().addEvent('click', function(e){
				
				e.stop();
				
				var id = this.rel;
				
				el.removeClass('comment-delete').addClass('loading');
				
				var l = function() {
					
					new Request.JSON({
						url: window.location.toString(), 
						onSuccess: function(resp){
							
							if (resp.success) {
								
								if (resp.is_moderator) {
									
									el.removeClass('loading').addClass('comment-restore')
									  .getParent('.comment').getElement('.comment-body').addClass('is_deleted');
									
									obj.initRestore();
									obj.setCount(resp.comments_cnt);
									
									return
								};
								
								var row = el.getParent('.row');
								var height = row.getCoordinates().height;
								
								new Fx.Morph(row, {
									duration: 300,
									onComplete: function() {
										el.getParent('.row').dispose();
										obj.setCount(resp.comments_cnt);
									}
								}).start({
									height: [height, 0]
								});
							};
						}
					}).post({
						Event: 'DeleteComment', 
						id: id
					});
				}
				
				obj.checkIsLast(el.rel, el.getParent('.comment'), l, 'delete', true);
			});
		});
	},
	
	initRestore: function(){
		
		var obj = this;
			
		$$('.' + obj.restore_btns).each(function(el){
			
			el.removeEvents().addEvent('click', function(e){
				
				e.stop();
				
				var id = this.rel;
				
				el.removeClass('comment-restore').addClass('loading');
				
				var l = function() {
					
					new Request.JSON({
						url: window.location.toString(), 
						onSuccess: function(resp){
							
							if (resp.success) {
								
								if (resp.is_moderator) {
									
									el.removeClass('loading').addClass('comment-delete')
									  .getParent('.comment').getElement('.comment-body').removeClass('is_deleted');
									
									obj.initDelete();
									obj.setCount(resp.comments_cnt);
									
									return
								};
								
								var row = el.getParent('.row');
								var height = row.getCoordinates().height;
								
								new Fx.Morph(row, {
									duration: 300,
									onComplete: function() {
										el.getParent('.row').dispose();
										obj.setCount(resp.comments_cnt);
									}
								}).start({
									height: [height, 0]
								});
							};
						}
					}).post({
						Event: 'RestoreComment', 
						id: id
					});
				}
				
				obj.checkIsLast(el.rel, el.getParent('.comment'), l, 'delete', true);
			});
		});
	},
	
	initEdit: function() {
		
		var obj = this;
		
		$$('.' + obj.edit_btns).each(function(btn) {
			
			btn.removeEvents().addEvent('click', function(e) {
				
				e.stop();
				
				var comment_disabler = new Disabler(btn.getParent('.row').getElement('.disabler'), 'hidden');
				
				if (btn.getStyle('cursor') == 'default') {
					return;
				};
				comment_disabler.show();
				
				var l = function(){
					
					btn.setStyles({
						opacity: 0.5,
						cursor: 'default'
					});
					
					var ta = $('textarea-block-' + btn.rel);
					var ta_height = 140;
					var comment_body = $('comment-body-' + btn.rel);
					
					new Fx.Morph(comment_body, {
						duration: 250,
						onComplete: function() {
							
							comment_body.addClass('hidden');
							ta.setStyles({
								'height': 0,
								'overflow': 'hidden'
							});
							
							var body = comment_body.get('html').trim().replace(/<br>/g, "\r\n");
							
							ta.removeClass('hidden').getChildren('textarea').set('value', body);
							
							new Fx.Morph(ta, {
								duration: 150,
								onComplete: function(){
									comment_disabler.hide();
								}
							}).start({
								height: [0, ta_height],
								opacity: [0, 1]
							});
						}
					}).start({
						opacity: [1, 0]
					});
				}
				
				obj.checkIsLast(btn.rel, btn.getParent('.comment'), l, 'edit', true);
				
			});
		})
	},
	
	initEditSave: function() {
		
		var obj = this;
		
		$$('.' + obj.edit_save_btns).each(function(btn) {
			
			btn.removeEvents().addEvent('click', function(e) {
				
				e.stop();
				
				var comment_disabler = new Disabler(btn.getParent('.row').getElement('.disabler'), 'hidden');
				
				comment_disabler.show();
				
				var comment_id = btn.id.replace('save-comment-', '');
					
				var l = function(){
					
					var body = btn.getParent('.row').getElement('textarea').value;
					
					new Request.JSON({
						url: window.location.toString(), 
						onSuccess: function(resp){
							
							if (resp.comment) {
								
								var pencil = btn.getParent('.comment').getElement('.comment-edit');
								
								pencil.setStyles({
									opacity: 1,
									cursor: 'pointer'
								});
								
								var comment_body = $('comment-body-' + comment_id);
								var ta = $('textarea-block-' + comment_id);
								
								comment_body.set('html', resp.comment.body);
								
								new Fx.Morph(ta, {
									duration: 250,
									onComplete: function() {
										
										var start_height = ta.getCoordinates().height.toInt();
										ta.addClass('hidden');
										
										comment_body.setStyles({
											'height': 'auto',
											'opacity': 0
										}).removeClass('hidden');
										
										var end_height = comment_body.getCoordinates().height.toInt();
										
										comment_body.setStyle('height', 0);
										
										new Fx.Morph(comment_body, {
											duration: 150,
											onComplete: function(){
												comment_disabler.hide();
											}
										}).start({
											height: [start_height, end_height],
											opacity: [0, 1]
										});
									}
								}).start({
									opacity: [1, 0]
								});
							};
						}
					}).post({
						Event: 'SaveComment', 
						body: body,
						id: comment_id
					});
				}
				
				obj.checkIsLast(comment_id, btn.getParent('.comment'), l, 'edit', true);
			});
		})
	},
	
	checkIsLast: function(comment_id, row, complete_func, operation, not_show_disabler) {
		
		var obj = this;
		var complete_func = complete_func || function(){};
		var not_show_disabler = not_show_disabler || false;
		
		if (!not_show_disabler) {
			
			obj.list_disabler.show();
		};
		
		new Request.JSON({
			url: window.location.toString(), 
			onSuccess: function(resp){
				
				if (!resp.is_last) {
					
					var comment_disabler = new Disabler(row.getParent('.row').getElement('.disabler'), 'hidden');
					
					comment_disabler.hide();
					obj.list_disabler.hide();
					obj.showInlineMsg(row, resp.msg, false, resp.comments);
					return false;
				}
				else {
					complete_func();
				}
				
				return true;
			}
		}).get({
			Event: 'CheckIsLast', 
			comment_id: comment_id,
			operation: operation
		});
	},
	
	showInlineMsg: function(row, msg, is_success, comments) {
		
		var obj = this;
		var height = 30;
		
		obj.list_disabler.hide();
		
		var p = row.getLast('p');
		
		p.setStyle('height', 0).set('text', msg);
		p.removeClass('hidden');
		
		if (is_success) {
			p.addClass('success');
		};
		
		new Fx.Morph(p, {
			duration: 250,
			onComplete: function() {
				
				setTimeout(function(){
					
					new Fx.Morph(p, {
						duration: 250,
						onComplete: function(){
							
							p.addClass('hidden').removeClass('success');
							
							if (comments) {
								
								obj.refreshPage(comments);
							};
						}
					}).start({
						height: [height, 0]
					});
					
				}, obj.show_error_timeout);
			}
		}).start({
			height: [0, height]
		});
	},
	
	showMessage: function(txt, area_return, is_success, not_return) {
		
		var obj = this;
		var not_return = not_return || false;
		
		if(!area_return) {
			area_return = this.area_current;
		}
		
		var container = this.area_msg.getFirst('p');
		
		container.innerHTML = txt;
		
		if(is_success) {
			container.addClass('msg-success');
		}
		else {
			container.removeClass('msg-success');
		}
		
		this.showArea(this.area_msg);
		
		if (!not_return) {
			
			setTimeout(function(){
				obj.showArea(area_return, obj.textarea_disabler.hide());
			}, is_success ? this.show_success_timeout : this.show_error_timeout);
		};
		
	},
	
	showArea: function(area, complete_func) {
		
		complete_func = complete_func || function(){};
		
		var obj = this;
		
		area.setStyle('top', -obj.bar_height);
		area.removeClass('hidden');
		
		new Fx.Morph(obj.area_current, {
			duration: 250,
			onComplete: function() {
				obj.area_current.addClass('hidden');
				new Fx.Morph(area, {
					duration: 250,
					onComplete: function(){
						obj.area_current = area;
						complete_func();
					}
				}).start({
					top: [-obj.bar_height, 0]
				});
			}
		}).start({
			top: [0, obj.bar_height]
		});
	},
	
	showAuthForm: function(){
		
		var obj = this;
		
		obj.disabler.hide();
		obj.textarea_disabler.show();
			
		var coord = this.auth_block.getCoordinates();
		
		if(coord.height == 0) {
			
			coord = this.auth_block.getFirst().getCoordinates();
			
			new Fx.Morph(this.auth_block, {
				duration: 500
			}).start({
				height: [0, coord.height + 10]
			});
		}
	},
	
	register: function() {
		
		var obj = this;
		var comment = obj.add_textarea.value != obj.add_textarea.title ? obj.add_textarea.value : '';
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				if(!resp.success) {
					
					captchaObj.change('ap-register-captcha-img');
					obj.showError(resp.msg);
					
					if(resp.clear_password) {
						
						obj.input_reg_password.value = '';
						obj.input_reg_conf_password.value = '';
						
						obj.input_reg_password.addClass('hidden');
						obj.input_reg_password_txt.removeClass('hidden');
						obj.input_reg_conf_password.addClass('hidden');
						obj.input_reg_conf_password_txt.removeClass('hidden');
					}
				}
				else {
					window.location = resp.redirect;
				}
			}
		}).post({
			Event: 'SignupAndPost', 
			body: comment,
			email: obj.input_reg_email.value != obj.input_reg_email.title ? obj.input_reg_email.value : '', 
			password: obj.input_reg_password.value != obj.input_reg_password.title ? obj.input_reg_password.value : '',
			conf_password: obj.input_reg_conf_password.value != obj.input_reg_conf_password.title ? obj.input_reg_conf_password.value : '',
			nickname: obj.input_reg_nickname.value != obj.input_reg_nickname.title ? obj.input_reg_nickname.value : '', 
			captcha: obj.input_reg_captcha.value,
			agree: obj.input_reg_agree.checked ? 1 : 0
		});
	},
	
	signin: function() {
		
		var obj = this;
		var comment = obj.add_textarea.value != obj.add_textarea.title ? obj.add_textarea.value : '';
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				if(!resp.success) {
					
					captchaObj.change('ap-login-captcha-img');
					obj.showError(resp.msg);
					
					if(resp.show_captcha) {
						$('ap-login-captcha-img').removeClass('hidden');
						$('ap-login-captcha').removeClass('hidden');
					}
				}
				else {
					if(resp.setcookie) {
						Cookie.write(resp.cookie.hash.name, resp.cookie.hash.value, {duration: resp.cookie.duration, path: resp.cookie.path, domain:  resp.cookie.domain});
						Cookie.write(resp.cookie.email.name, resp.cookie.email.value, {duration: resp.cookie.duration, path: resp.cookie.path, domain:  resp.cookie.domain});
					}
					
					window.location = resp.redirect;
				}
			}
		}).post({
			Event: 'SigninAndPost', 
			body: comment,
			email: obj.input_email.value, 
			password: obj.input_password.value,
			remember: obj.input_remember.checked ? 1 : 0,
			captcha: obj.input_captcha.value
		});
	},
	
	showError: function(msg) {
		
		var obj = this;
		
		new Fx.Morph(this.area_msg, {
			duration: 200, 
			onComplete: function() {
				
				obj.area_msg.getFirst('p').set('text', msg);
				
				new Fx.Morph(obj.area_msg, {
					duration: 200
				}).start({
					opacity: [0, 1]
				});
			}
		}).start({
			opacity: [1, 0]
		});
	}
});

