var NewsComments = new Class({
	initialize: function(){
		
		this.expand_link = $('nc-expand-link');
		this.expanded = true;
		this.container = $('nc-container');
		
		this.input_email = $('nc-login');
		this.input_password = $('nc-password');
		this.input_password_txt = $('nc-password-txt');
		this.btn_login = $('nc-btn-login');
		this.input_captcha = $('nc-login-captcha');
		
		this.input_reg_password = $('nc-reg-password');
		this.input_reg_password_txt = $('nc-reg-password-txt');
		this.input_reg_conf_password = $('nc-reg-conf-password');
		this.input_reg_conf_password_txt = $('nc-reg-conf-password-txt');
		this.input_reg_email = $('nc-reg-login');
		this.input_reg_nickname = $('nc-nickname');
		this.input_reg_captcha = $('nc-captcha');
		this.input_reg_agree = $('nc-reg-agree');
		this.btn_reg = $('nc-btn-registration');
		
		this.edit_link_class = 'nc-edit-link';
		this.delete_link_class = 'nc-delete-link';
		
		this.inplace_editor_height = 141;
		this.show_error_timeout = 2500;
		
		this.post_link = $('nc-btn-post');
		this.post_textarea = $('nc-comment-text');
		this.textdisabler = $('textdisabler');
		this.error_container = $('nc-error-container');
		this.auth_block = $('nc-auth-block');
		this.disabler = new Disabler('nc-disabler', 'hidden');
		
		this.calendar_link = $('nc-calendar-link');
		this.thumbup_link = $('nc-thumb-up-link');
		this.thumbdown_link = $('nc-thumb-down-link');
		this.sorter = null;
		this.sort_by = 'date_asc';
		
		this.createSorter();
		this.activatePasswordFields();
		this.setActionHandlers();
	}
});

NewsComments.implement({
	setActionHandlers: function(){
		
		var obj = this;
		
		this.expand_link.addEvent('click', function(e){
			new Event(e).stop();
			obj.toggleExpand();
		});
		
		$$('a.' + this.delete_link_class).each(function(link){
			link.addEvent('click', function(e){
				new Event(e).stop();
				if(confirm('Are you sure?')) {
					obj.deleteComment(link.rel);
				}
			});
		});
		
		$$('a.' + this.edit_link_class).each(function(link){
			link.addEvent('click', function(e){
				new Event(e).stop();
				obj.activateInplaceEditor(link.rel);
			});
		});
		
		$$('.nc-post a.btn-post-edited').each(function(link){
			link.addEvent('click', function(e){
				new Event(e).stop();
				var ta = $('item-edit-text-' + link.rel);
				obj.updateComment(link.rel, ta.value);
			});
		});
		
		$(this.post_link).addEvent('click', function(e){
			new Event(e).stop();
			obj.postComment();
		});
		
		if(this.calendar_link) {
			this.calendar_link.addEvent('click', function(e){
				new Event(e).stop();
				obj.sortByDate();			
			});
		}
		
		if(this.thumbup_link) {
			this.thumbup_link.addEvent('click', function(e){
				new Event(e).stop();
				obj.sortByThumbUp();
			});
		}
		
		if(this.thumbdown_link) {
			this.thumbdown_link.addEvent('click', function(e){
				new Event(e).stop();
				obj.sortByThumbDown();
			});
		}
		
		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();
			});
		}
		
		$$('a.nci-report').each(function(link){
			link.addEvent('click', function(e){
				new Event(e).stop();
				obj.sendReport(this.rel);
			});
		});
		
		$$('a.nci-thumb-up').each(function(link){
			link.addEvent('click', function(e){
				new Event(e).stop();
				obj.vote(this.rel, 'up');
			});
		});
		
		$$('a.nci-thumb-down').each(function(link){
			link.addEvent('click', function(e){
				new Event(e).stop();
				obj.vote(this.rel, 'down');
			});
		});
	}, 
	
	vote: function(id, dir) {
		
		if(dir == 'up') {
			var Event = 'ThumbUp';
			var link = $('nci-thumb-up-' + id);
			var link_rev = $('nci-thumb-down-' + id);
			
		}
		else {
			var Event = 'ThumbDown';
			var link = $('nci-thumb-down-' + id);
			var link_rev = $('nci-thumb-up-' + id);
		}
		
		if(link.hasClass('disabled')) {
			return;
		}
		
		link_rev.addClass('disabled');
		link.addClass('disabled');
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function() {
				link.innerHTML = parseInt(link.innerHTML) + 1;
			}
		}).get({
			Event: Event, 
			id: id
		});
	},
	
	sendReport: function(id) {
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function() {
				$('rep-link-' + id).addClass('hidden');
				$('rep-sent-' + id).removeClass('hidden');
				 Cookie.write('comment_report[' + id + ']', '1', {duration: 1});
			}
		}).get({
			Event: 'Report', 
			id: id
		});
	},
	
	createSorter: function() {
		
		this.sorter = new Fx.Sort('.nc-list-items .nc-item', {transition: Fx.Transitions.Back.easeInOut});
	},
	
	register: function() {
		var obj = this;
		
		obj.disabler.show();
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				obj.disabler.hide();
				if(resp.status == 'error') {
					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 = window.location.toLocaleString() + '?Event=Post#nc-comment-area';
				}
			}
		}).get({
			Event: 'SignupAndPost', 
			text: obj.post_textarea.value != obj.post_textarea.title ? obj.post_textarea.value : '', 
			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;
		
		obj.disabler.show();
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				obj.disabler.hide();
				if(resp.status == 'error') {
					obj.showError(resp.msg);
					
					if(resp.show_captcha) {
						$('nc-login-captcha-img').removeClass('hidden');
						$('nc-login-captcha').removeClass('hidden');
					}
				}
				else {
					window.location = window.location.toString() + '?Event=Post#nc-comment-area';
				}
			}
		}).get({
			Event: 'SigninAndPost', 
			text: obj.post_textarea.value != obj.post_textarea.title ? obj.post_textarea.value : '', 
			email: obj.input_email.value, 
			password: obj.input_password.value,
			captcha: obj.input_captcha.value
		});
	},
	
	sortByThumbDown: function() {
		
		var arr = new Array();
		var arr_order = new Array();
		$$('.nc-list-items .nc-item').each(function(el, num){
			arr[num] = {
				num: num, 
				val: parseInt(el.getFirst('.nc-item-info').getFirst('a.nci-thumb-down').get('text'))
			};
		});
		
		arr.sort(function(a, b){
			if(a.val > b.val) {
				return 1;
			}
			else if(a.val < b.val) {
				return -1;
			}
			return 0;
		});
		
		if(this.sort_by == 'thumbdown_desc') {
			this.sort_by = 'thumbdown_asc';
		}
		else {
			arr.reverse();
			this.sort_by = 'thumbdown_desc';
		}
		
		for(var i = 0; i < arr.length; i++) {
			arr_order[i] = arr[i].num;
		}
		
		this.sorter.sort(arr_order).chain(this.sorter.rearrangeDOM.bind(this.sorter));
	},
	
	sortByThumbUp: function() {
		
		var arr = new Array();
		var arr_order = new Array();
		$$('.nc-list-items .nc-item').each(function(el, num){
			arr[num] = {
				num: num, 
				val: parseInt(el.getFirst('.nc-item-info').getFirst('a.nci-thumb-up').get('text'))
			};
		});
		
		arr.sort(function(a, b){
			if(a.val > b.val) {
				return 1;
			}
			else if(a.val < b.val) {
				return -1;
			}
			return 0;
		});
		
		if(this.sort_by == 'thumbup_desc') {
			this.sort_by = 'thumbup_asc';
		}
		else {
			arr.reverse();
			this.sort_by = 'thumbup_desc';
		}
		
		for(var i = 0; i < arr.length; i++) {
			arr_order[i] = arr[i].num;
		}
		
		this.sorter.sort(arr_order).chain(this.sorter.rearrangeDOM.bind(this.sorter));
	},
	
	sortByDate: function() {
		
		var arr = new Array();
		var order_str = '';
		$$('.nc-list-items .nc-item').each(function(el, num){
			arr[num] = {
				num: num, 
				val: el.lang
			};
		});
		
		var arr = new Array();
		var arr_order = new Array();
		$$('.nc-list-items .nc-item').each(function(el, num){
			arr[num] = {
				num: num, 
				val: parseInt(el.lang)
			};
		});
		
		arr.sort(function(a, b){
			if(a.val > b.val) {
				return 1;
			}
			else if(a.val < b.val) {
				return -1;
			}
			return 0;
		});
		
		if(this.sort_by == 'date_asc') {
			this.sort_by = 'date_desc';
			arr.reverse();
		}
		else {
			this.sort_by = 'date_asc';
		}
		
		for(var i = 0; i < arr.length; i++) {
			arr_order[i] = arr[i].num;
		}
		
		this.sorter.sort(arr_order).chain(this.sorter.rearrangeDOM.bind(this.sorter));
	},
	
	postComment: function() {
		
		var obj = this;
		var text = this.post_textarea.value != this.post_textarea.title ? this.post_textarea.value : '';
		
		this.disabler.show();
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				obj.disabler.hide();
				
				if(resp.status == 'error') {
					obj.showError(resp.msg);
					
					if(resp.show_auth) {
						obj.post_link.getParent().addClass('hidden');
						
						var coords = obj.post_textarea.getCoordinates();
						
						obj.textdisabler.removeClass('hidden').setStyles({
							height: coords.height,
							width: coords.width,
							opacity: 0.5
						});
						obj.showAuthArea();
					}
					
					if(resp.show_captcha) {
						$('nc-login-captcha-img').removeClass('hidden');
						$('nc-login-captcha').removeClass('hidden');
					}
				}
				else {
					
					obj.post_textarea.removeClass('filled');
					
					if(resp.hide_prev_controls) {
						$$('.nc-list .nc-item .nc-controls').each(function(el){
							el.addClass('hidden');
						});
					}
					
					var c = new Element('div', {
						'class': 'nc-item', 
						'lang': resp.comment.ts
					});
					
					/*
					 * Info
					 */
					var user_page = new Element('a', {
						'href': resp.comment.user_page
					}).inject(c);
					
					var avatar = new Element('img', {
						'class': 'avatar', 
						'src': resp.comment.avatar_src
					}).inject(user_page);
					
					var info = new Element('div', {
						'class': 'nc-item-info'
					}).inject(c);
					
					var left = new Element('div', {
						'class': 'left'
					}).inject(info);
					
					var right = new Element('div', {
						'class': 'right'
					}).inject(info);
					
					var nci_login = new Element('span', {
						'class': 'nci-login online'
					}).inject(left);
					
					new Element('a', {
						'href': resp.comment.user_page,
						'text': resp.comment.user_nickname
					}).inject(nci_login);
					
					new Element('a', {
						'href': '#', 
						'class': 'nci-report', 
						'text': 'Report', 
						'id': 'rep-link-' + resp.comment.id,
						'rel': resp.comment.id
					}).addEvent('click', function(e){
						new Event(e).stop();
						obj.sendReport(this.rel);
					}).inject(right);
					
					new Element('span', {
						'class': 'nci-report hidden', 
						'text': 'Thanks', 
						'id': 'rep-sent-' + resp.comment.id
					}).inject(right);
					
					new Element('span', {
						'class': 'nci-date', 
						'text': resp.comment.date
					}).inject(right);
					
					new Element('a', {
						'href': '#', 
						'class': 'nci-thumb-up disabled', 
						'text': '0', 
						'rel': resp.comment.id,
						'id': 'nci-thumb-up-' + resp.comment.id
					}).addEvent('click', function(e){
						new Event(e).stop();
						obj.vote(this.rel, 'up');
					}).inject(right);
					
					new Element('a', {
						'href': '#', 
						'class': 'nci-thumb-down disabled', 
						'text': '0', 
						'rel': resp.comment.id,
						'id': 'nci-thumb-down-' + resp.comment.id
					}).addEvent('click', function(e){
						new Event(e).stop();
						obj.vote(this.rel, 'down');
					}).inject(right);
					
					/*
					 * Block
					 */
					var block = new Element('div', {
						'class': 'nc-block', 
						'id': 'item-text-' + resp.comment.id 
					}).inject(c);
					
					new Element('p', {
						'text': resp.comment.body
					}).inject(block);
					
					var error = new Element('div', {
						'class': 'nc-error hidden'
					}).inject(block);
					
					new Element('p').inject(error);
					
					var controls = new Element('div', {
						'class': 'nc-controls'
					}).inject(block);
					
					new Element('a', {
						'href': '#', 
						'class': 'nc-edit-link', 
						'rel': resp.comment.id, 
						'html': '<img src="/public/images/news/content/comment-edit.gif" alt="" />'
					}).addEvent('click', function(e){
						new Event(e).stop();
						obj.activateInplaceEditor(this.rel);
					}).inject(controls);
					
					new Element('a', {
						'href': '#', 
						'class': 'nc-delete-link', 
						'rel': resp.comment.id, 
						'html': '<img src="/public/images/news/content/comment-delete.gif" alt="" />'
					}).addEvent('click', function(e){
						new Event(e).stop();
						if(confirm('Are you sure?')) {
							obj.deleteComment(this.rel);
						}
					}).inject(controls);
					
					/*
					 * Edit area
					 */
					
					var edit = new Element('div', {
						'class': 'nc-comment-area nc-edit-area hidden', 
						'id': 'item-edit-' + resp.comment.id
					}).inject(c);
					
					var e_block = new Element('div', {
						'class': 'nc-block'
					}).inject(edit);
					
					new Element('textarea', {
						'cols': 55, 
						'rows': 7, 
						'id': 'item-edit-text-' + resp.comment.id, 
						'value': resp.comment.body
					}).inject(e_block);
					
					var nc_post = new Element('div', {
						'class': 'nc-post'
					}).inject(e_block);
					
					new Element('a', {
						'class': 'custom-btn btn-post-edited', 
						'rel': resp.comment.id, 
						'href': '#', 
						'html': '<span class="left"><span class="right"><span class="txt">Post</span></span></span>'
					}).addEvent('click', function(e){
						new Event(e).stop();
						var ta = $('item-edit-text-' + this.rel);
						obj.updateComment(this.rel, ta.value);
					}).inject(nc_post);
					
					c.setStyles({
						'overflow': 'hidden', 
						'height': 0
					});
					
					c.inject($('nc-list-items'));
					
					new Fx.Morph(c, {
						'duration': 200, 
						onComplete: function(){
							c.setStyles({
								'overflow': 'auto', 
								'height': 'auto'
							});
						}
					}).start({
						'height': [0, obj.getHeightByChildren(c)]
					});
					
					obj.createSorter();
					obj.post_textarea.value = obj.post_textarea.title;
				}
			}
		}).get({
			Event: 'PostComment', 
			text: text
		});
	},
	
	showError: function(msg) {
		
		var coord = this.error_container.getCoordinates();
		var obj = this;
		
		new Fx.Morph(this.error_container, {
			duration: 200, 
			onComplete: function() {
				var msg_cont = obj.error_container.getFirst();
				msg_cont.getFirst('p').innerHTML = msg;
				var coord = msg_cont.getCoordinates();
				
				new Fx.Morph(obj.error_container, {
					duration: 200
				}).start({
					height: [0, coord.height]
				});
			}
		}).start({
			height: [coord.height, 0]
		});
	},
	
	showAuthArea: function() {
		
		var coord = this.auth_block.getCoordinates();
		if(coord.height == 0) {
			coord = this.auth_block.getFirst().getCoordinates();
			new Fx.Morph(this.auth_block, {
				duration: 200
			}).start({
				height: [0, coord.height + 10]
			});
		}
	},
	
	deleteComment: function(id) {
		
		var obj = this;
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				var text = $('item-text-' + id);
				
				if(resp.status == 'error') {
					var msg_cont = text.getFirst('.nc-error');
					var msg = msg_cont.getFirst('p');
					msg.innerHTML = resp.msg;
					msg.removeClass('success');
					
					msg_cont.setStyles({
						overflow: 'hidden', 
						height: 0
					});
					msg_cont.removeClass('hidden');
					
					var coord = msg.getCoordinates();
					var height = coord.height + 15;
					
					new Fx.Morph(msg_cont, {
						duration: 200, 
						onComplete: function() {
							setTimeout(function(){
								new Fx.Morph(msg_cont, {
									duration: 200
								}).start({
									height: [height, 0]
								});
							}, obj.show_error_timeout);
						}
					}).start({
						height: [0, height]
					});
				}
				else {
					var comment = text.getParent(); 
					var coord = comment.getCoordinates();
					comment.setStyle('overflow', 'hidden');
					new Fx.Morph(comment, {
						duration: 200, 
						onComplete: function() {
							comment.dispose();
						}
					}).start({
						height: [coord.height, 0]
					});
				}
			}
		}).get({
			Event: 'DeleteComment', 
			id: id
		});
	},
	
	updateComment: function(id, text) {
		
		var obj = this;
		
		new Request.JSON({
			url: window.location.toString(),
			onSuccess: function(resp) {
				
				var el_editor = $('item-edit-' + id);
				var el_text = $('item-text-' + id);
				var el_msg_cont = el_text.getFirst('.nc-error');
				var el_msg = el_msg_cont.getFirst('p');
				el_msg_cont.removeClass('hidden');
				el_msg_cont.setStyle('height', 'auto');
				el_msg.innerHTML = resp.msg;
				
				if(resp.status == 'success') {
					el_msg.addClass('success');
					el_text.getFirst('p').set('text', text);
				}
				else {
					el_msg.removeClass('success');
				}
				
				new Fx.Morph(el_editor, {
					duration: 200, 
					onComplete: function(){
						el_editor.addClass('hidden');
						el_text.removeClass('hidden');
						
						new Fx.Morph(el_text, {
							duration: 200, 
							onComplete: function() {
								setTimeout(function(){
									el_msg_cont.setStyle('overflow', 'hidden');
									el_text.setStyle('height', 'auto');
									var coord = el_msg_cont.getCoordinates();
									new Fx.Morph(el_msg_cont, {
										duration: 200
									}).start({
										height: [coord.height, 0]
									});
								}, obj.show_error_timeout);
							} 
						}).start({
							height: [0, obj.getHeightByChildren(el_text) + 20]
						});
					}
				}).start({
					height: [obj.inplace_editor_height, 0]
				});
			}
		}).get({
			Event: 'UpdateComment', 
			text: text, 
			id: id
		});
	},
	
	getHeightByChildren: function(el) {
		
		var height = 0;
		
		el.getChildren().each(function(ch){
			var coord = ch.getCoordinates();
			height += coord.height;
		});
		
		return height;
	},
	
	activateInplaceEditor: function(comment_id) {
		
		var text = $('item-text-' + comment_id);
		var text_coords = text.getCoordinates();
		var editor = $('item-edit-' + comment_id);
		var obj = this;
		
		new Fx.Morph(text, {
			duration: 200, 
			onComplete: function() {
				text.addClass('hidden');
				editor.setStyle('height', 0);
				editor.removeClass('hidden');
				
				new Fx.Morph(editor, {
					duration: 200
				}).start({
					height: [0, obj.inplace_editor_height]
				});
			}
		}).start({
			height: [text_coords.height, 0]
		});
	},
	
	activatePasswordFields: function() {
		new PwdSwitcher(this.input_password, this.input_password_txt, 'hidden', 'filled');
		new PwdSwitcher(this.input_reg_password, this.input_reg_password_txt, 'hidden', 'filled');
		new PwdSwitcher(this.input_reg_conf_password, this.input_reg_conf_password_txt, 'hidden', 'filled');
	},
	
	toggleExpand: function() {
		
		var coord = this.container.getFirst('div').getCoordinates();
		
		if(this.expanded) {
			height_start = coord.height;
			height_end = 0;
			this.expanded = false;
			this.expand_link.removeClass('collapsed');
		}
		else {
			height_start = 0;
			height_end = coord.height + 10;
			this.expanded = true;
			this.expand_link.addClass('collapsed');
		}
		
		new Fx.Morph(this.container, {
			duration: 300
		}).start({
			height: [height_start, height_end]
		});
	}
});
