var CM;
window.addEvent('domready', function(){
	
	CM = new commentsManage();
	
});


Native.implement([Element], {
	
	// отображаем скрытый коммент
	hiddenCommentToggle: function(){
		var tohide = this.getPrevious('div');
		tohide.toggleClass('hidden')
		
		this.getPrevious('span').toggleClass('hidden');
		
		if( tohide.hasClass('hidden') )
			this.set('text', 'раскрыть');
		else
			this.set('text', 'скрыть');
	}
});


var commentsManage = new Class({
	
	Implements: [Chain, Events, Options],
	
	options: {
		'form': 'create_comment',
		'container': 'comments'
	},
	
	//Подготавливаем форму
	initialize: function(options){
		this.setOptions(options);
		
		this.form = $(this.options.form);
		if( this.form )
			this.prepareForm();
		
	},
	
	answer: function(button){
		button = $(button);
		
		var parent = button.getParent('.comment');
		this.formInject(parent);
		
		this.parent_id.set('value', parent.get('id').replace(/^comment/, '') );
	},
	
	cancel_answer: function(nofocus){
		this.form.inject( $(this.options.container) );
		this.cancel_button.setStyle('display', 'none');
		this.parent_id.set('value', '');
		if(!nofocus)
			this.form.getElement('textarea').focus();
	},
	
	prepareForm: function(){
		this.cancel_button = new Element ('input',{
			'type': 'button',
			'class': 'cancel_answer',
			'events':{
				'click': function(){
					this.cancel_answer();
				}.bind(this)
			},
			'value': 'Отменить ответ'
		}).injectBefore( this.form.getElement('input[type=submit]') );
		
		
		this.parent_id = this.form.getElement('input[name=parent_id]');
		
		if( this.parent_id.get('value') != '' && $('comment' + this.parent_id.get('value')) )
			this.formInject( $('comment' + this.parent_id.get('value')), true );
		else
			this.cancel_answer(true);
	},
	
	formInject: function(parent, nofocus){
		this.form.inject(parent);
		this.cancel_button.setStyle('display', '');
		if(!nofocus)
			this.form.getElement('textarea').focus();
	},
	
	destroy: function(button){
		button = $(button);
		
		var parent = button.getParent('.comment');
		
		if(confirm("Вы уверены, что хотите безвозвратно \nудалить комментарий?")){
			new Request.FLASH({
				'url': button.get('href'),
				'method': 'get',
				'onSuccess': function(){
					
					parent.destroyHighlight();
					
					//parent.destroy();
				}
			}).send();
		}
			
		
		return false;
		
	}
	
});

