var Comments = Class.create({	
	initialize: function() 
	{
		this.loading = $('loading');				
		this.halt = {};
		if (!$('comment')) return;
		
		this.defaultValue = '<span class="init">Type your comment here...</span>';
		$('comment').value = this.defaultValue;
		
		var jump = Cookie.get('jump');

		if (jump == 'comments' && $('pageUp'))
		{
			Effect.ScrollTo('pageUp');
		}

		if (jump && $('commentId'+jump))
		{
			Effect.ScrollTo('commentId'+jump);
		}		
		if (jump) Cookie.erase('jump');		

		tinymce.dom.Event._wait = function() {};
		tinymce.dom.Event._pageInit();

		tinyMCE.init({
			mode : "exact",
			elements: "comment",
			theme : "comments",
			plugins : "safari",
			invalid_elements : "div,object,embed",
			init_instance_callback: this.initCommenter
		});
	},
	
	initCommenter: function(ed)
	{		
		var iframe = Prototype.Browser.Gecko ? $('comment_ifr').contentDocument : ed.getWin();
		var callback = function() {
			ed.setContent('<p></p>');
			tinymce.dom.Event.remove(iframe, 'focus', callback);
			ed.selection.select(ed.dom.select('p')[0]);
			
//			Event.observe(iframe, 'keydown', __disableBackspace.bindAsEventListener(this));
//			Event.observe(iframe, 'keypress', __disableBackspace.bindAsEventListener(this));			
		};

    	tinymce.dom.Event.add(iframe, 'focus', callback);
		ed.linkChooser = new Panel.editor.link('link', { editor: ed });
		$('comment').disabled = false;		
	},
	
	initEditor: function()
	{  
		var ed = tinyMCE.get('editComment');
		ed.focus();
		ed.linkChooser = new Panel.editor.link('editComment_link', { editor: ed });
		$('editComment').disabled = false;
	},
	
	addTopic: function(e)
	{
		Event.stop(e);
		Effect.ScrollTo('addTopic');
		new Effect.Highlight('topicName', { duration: Effect.DefaultOptions.duration * 2 });		
		
	},
	
	addComment: function(e)
	{
		Event.stop(e);
				
		var header = $$('#addComment .header').first();
				
		new Effect.Highlight(header, { duration: Effect.DefaultOptions.duration * 2 });		
		tinyMCE.get('comment').focus();		
		Effect.ScrollTo('addComment');
	},
	
	validateTopic: function(e)
	{
		var topicName = $('topicName');
		if (!topicName.value.strip() || topicName.value == topicName.defaultValue)
		{
			Event.stop(e);
			new Effect.Highlight(topicName);
			topicName.focus();
			return false;
		}
		
		this.validateComment(e);
		return true;
	},
	
	validateComment: function(e, textarea)
	{
		var ed = tinyMCE.get(textarea || 'comment');
		if (!ed) return;
		
		ed.save();
		var content = ed.getContent().strip();
		
		if (!content || content.stripTags() == this.defaultValue.stripTags() || content == '<p></p>')
		{
			Event.stop(e);
			return false;
		}
		return true;		
	},
	
	submitComment: function(e, form, id)
	{		
		// HANDLE REPLY AND NEW COMMENT
		
		var reply = form.name == 'editCommentForm';
		var container = reply ? 'commentId'+id : 'addComment';
		var textarea = reply ? 'editComment' : 'comment';
	
		if (!this.validateComment(e, textarea)) return;
		Event.stop(e);
		
		Position.clone(container, this.loading);
		this.loading.show();

		var callback = function(json)
		{
			$('comments').show();
			if (json.comment_id && $('commentId'+json.comment_id))
			{
				new Effect.Appear('commentId'+json.comment_id, { afterFinish: function() {
					if (reply) Effect.ScrollTo('commentId'+json.comment_id);					
				}});
				
				var ed = tinyMCE.get(textarea);
				if (!ed) return;
				
				ed.setContent('<p>'+window.comments.defaultValue+'</p>');				
				
				if (reply)
				{
					if (this.unbutton) this.unbutton();		
					this.closeComment(this.current);		
					delete this.current;						
				}
				this.initCommenter(ed);				
			}
		}.bind(this);

		var parameters = {
			comment: form[textarea].value
		};

		app.blockLoad(textarea, $('comments'), form.action, { 
				insertion: 'bottom',
				parameters: parameters,				
				callback: callback,
				loading: this.loading
			});		
	},
	
	deleteComment: function(e, id)
	{
		Event.stop(e);
		
		if (confirm('Are you sure you want to delete this comment?'))
		{
			if (this.current)
				this.closeComment(this.current);		
			
			new Ajax.Request('/comment/delete/'+id+'/',
				{
					method: 'get', 
					onComplete: function()
					{
						new Effect.Fade('commentId'+id, { afterFinish: function() {
							$('commentId'+id).remove();
						}});
					}
				});			
		}			
	},
	
	saveComment: function(e, f)
	{
		Event.stop(e);
		var ed = tinyMCE.get('editComment');

		Position.clone('commentId'+this.current, this.loading);
		this.loading.show();

		$$('#commentId'+this.current+' .body')[0].update(ed.getContent());
		f.editComment.value = ed.getContent();

		var callback = function()
		{
			if (this.unbutton) this.unbutton();		
			this.closeComment(this.current);		
			delete this.current;
		}.bind(this)

		var parameters = new Hash(Form.serialize(f, true));
		parameters.set('comment_id', this.current);

		app.jsonLoad('/comment/edit/', { 
			parameters: parameters,
			callback: callback,
			loading: this.loading
		});			
	},
	
	replyComment: function(e, id, said)
	{
		document.forms.editCommentForm.onsubmit = function(e, id) {
			this.submitComment(e, document.forms.editCommentForm, id);
		}.bindAsEventListener(this, id);
		
		
		if (this.unbutton) this.unbutton();		
		
		if (this.current != id)
		{
			var x = Event.element(e);
			this.button = (x.tagName == 'IMG') ? x : x.firstDescendant();
			this.button.src = this.button.src.replace(/reply.gif$/, 'replying.gif');

			this.unbutton = function() {
				this.button.src = this.button.src.replace(/replying.gif$/, 'reply.gif');
				delete this.unbutton;
			}.bind(this);
		}
		
		this.replaceComment(e, id, { pre: '<p></p><blockquote>'+'<p>'+decodeURIComponent(said)+'</p>', post: '</blockquote><p></p>' });					
	},

	editComment: function(e, id)
	{
		document.forms.editCommentForm.onsubmit = function(e) {
			this.saveComment(e, document.forms.editCommentForm);
		}.bindAsEventListener(this);
		
		if (this.unbutton) this.unbutton();
		
		if (this.current != id)
		{
			var x = Event.element(e);
			this.button = (x.tagName == 'IMG') ? x : x.firstDescendant();
			this.button.src = this.button.src.replace(/edit.gif$/, 'editing.gif');

			this.unbutton = function() {
				this.button.src = this.button.src.replace(/editing.gif$/, 'edit.gif');
				delete this.unbutton;				
			}.bind(this);			
		}
		
		this.replaceComment(e, id);		
	},
	
	replaceComment: function(e, id, wrapper)
	{
		if (e) Event.stop(e);
		
		if (this.current) this.closeComment(this.current);
		
		if (this.current == id)
		{
			delete this.current;
			return;
		}		
		
		$$('#editCommenter .mceButtonActive').each(function(x) {
			x.removeClassName('mceButtonActive');
		});
		
		$('editCommenter').style.visibility = 'hidden';
		$('commentId'+id).appendChild($('editCommenter'));
		$('editCommenter').show();
		
		var commentBody = $$('#commentId'+id+' .body')[0];
		commentBody.hide();

		var content = wrapper ? wrapper.pre +commentBody.innerHTML + wrapper.post : commentBody.innerHTML;
		$('editComment').value = content;

		tinyMCE.init({
			mode : "exact",
			elements: "editComment",
			theme : "comments",
			plugins : "safari",		
			invalid_elements : "div",	
			oninit : this.initEditor
		});
		$('editCommenter').style.visibility = '';
				
		this.current = id;
	},
	
	closeComment: function(id)
	{
		$('editCommenter').hide();

		var editor = tinyMCE.get('editComment');
		if (editor) 
		{
			var html = '<div id="editComment_container"><div id="editComment_ifr_container" class="mceIframeContainer"></div></div>';
			editor.remove();
			new Insertion.After('editComment', html);
		}
		$('editCommenterContainer').appendChild($('editCommenter'));
		$$('#commentId'+id+' .body').first().show();
		$$('#commentId'+id+' .body').first().focus();
	},
	
	recommend: function(e, id)
	{
		Event.stop(e);

		if (this.halt.recommend) return;
		this.halt.recommend = true;

		var url = 'recommend';
		var button = Event.element(e);
		var img = (button.tagName == 'IMG') ? button : button.firstDescendant();

		if (img.src.match(/recommend-comment.gif$/))
		{
			url = 'recommend';
			img.src = img.src.replace(/recommend-comment.gif$/, 'recommended-comment.gif');
		}
		else if (img.src.match(/recommended-comment.gif$/))
		{
			url = 'unrecommend';
			img.src = img.src.replace(/recommended-comment.gif$/, 'recommend-comment.gif');
		}
		else
		{
			delete this.halt.recommend;			
			return;
		}

		var commonCallback = function() {
			delete this.halt.recommend;			
		}.bind(this);

		var callback = function(json) {
			var x = $$('#commentId'+id+' .recommended');
			if (x && x.length) {
				x[0].update(json.text);
			}
		}.bind(this);

		app.jsonLoad('/'+url+'/comment/'+id+'/', {
			commonCallback: commonCallback,
			callback: callback
		});
	}	
});

window.windowOnload.push(function() {
	window.comments = new Comments();
});
