

/**
 * Comment button widgets
 * All call functions from within the $.any.forum object
 */
$.any.ui('forum_edit_note',
{
	_init: function()
	{
		var self = this;

		$(self.element).click(function()
		{
			$.any.forum.editNote(self.element, self.options.id, self.options.lang);
		});
	}
});

$.any.ui('forum_delete_note',
{
	_init: function()
	{
		var self = this;
		$(self.element).click(function()
		{
			$.any.forum.deleteNote(self.element, self.options.id);
		});
	}
});

$.any.ui.action.js('forum_quote',
{
	init: function()
	{
		var self = this;
		self.options.require_logon = false;
	},

	callQuote: function()
	{
		var self = this;
		$.any.dialog.close();
		if ($('#comment-form').length)
		{
			$.any.forum.quoteNote(self.options.thg_id);
		}
	}
});

$.any.ui.action.js('forum_story',
{
    callStory: function()
    {
    	var self = this;
    	$.any.rest.post('forum.turn.into.story', { thg_id: self.options.thg_id }, function(result)
		{
		    window.location.href = result['edit_uri'];
		});
    }
});

/**
 * Static functions wrapper
 */
$.any.forum = {

	/**
	 * Get note DOM element by note id
	 */
	getNoteById: function(id)
	{
		return $('#comment-' + id);
	},

	/**
	 * Throbber after button
	 */
	addThrobberAfterObj: function(obj)
	{
		var self = this;

		if (typeof self.throbber == 'undefined')
		{
			self.throbber = $('<img src="http://fast.mediamatic.nl/f/sjnh/image/throbberwait.gif" width="16" height="16" class="comment-throbber left" />');
		}

		$(obj).parent().append(self.throbber);
	},

	removeThrobber: function()
    {
        $(".comment-throbber").remove();
    },

	/**
	 * Edit a note
	 * Get edit note template from database
	 */
	editNote: function(el, id, lang)
	{
		var self = this, data, html, $note;

		self.addThrobberAfterObj(el);

		// Get fig field
		data = {
			name: 'forum_note_edit',
			id: id
		};

		$.any.rest.get('anymeta.html.scomp', data, function(json)
		{
			self.editNoteDom(json, id, lang);
		});
	},

	/**
	 * Replace title, message field and buttons
	 */
	editNoteDom: function(json, id, lang)
	{
		var self = this, $note, $submitbutton;

		$note = self.getNoteById(id)
			.find('.comment-content')
			.html(json.html);

		init_widgets($note);

		$submitbutton = $note.find('.edit-comment-save');
		
		$.any.ui.getWidget($submitbutton).setCallback(function(form)
		{
			self.editNoteSave(id, lang, form.getData());
		});

		$note.find('.edit-comment-cancel').click(function()
		{
			self.refreshNote(id);
			self.addThrobberAfterObj(this);
		});
	},

	/**
	 * Save note
	 * and refresh dom
	 */
	editNoteSave: function(id, lang, formData)
	{
		var self = this, data, $button;

		$button = self.getNoteById(id).find('.edit-comment-save:first');
		self.addThrobberAfterObj($button);

		data = {
			thing_id: id,
			data	: {
				text	: {
					language	: lang,
					title		: formData.title,
					body		: formData.text
				}
			}
		};

		$.any.rest.post('anymeta.thing.update', data, function(json)
		{
			self.refreshNote(id);
		});
	},

	/**
	 * Refresh note
	 */
	refreshNote: function(id)
	{
		var self = this, data, $note;

		$note = self.getNoteById(id);

		data = {
			name	: 'forum_note',
			id		: id
		};

		$.any.rest.get('anymeta.html.scomp', data, function(json)
			{
				$note.replaceWith(json.html);
				$.any.ui.scan(self.getNoteById(id));
			});
	},

	/**
	 * Delete a note
	 * Secure delete a comment and remove comment from dom
	 */
	deleteNote: function(el, id)
	{
		var self = this, $note, data, noteTitle, confirmMsg;

		$note		= self.getNoteById(id);
		noteTitle	= $note.find('h3').text();
		confirmMsg	= 'Are you sure you want to delete: %1% ?';
		confirmMsg	= confirmMsg.replace('%1%', noteTitle);

		if (confirm(confirmMsg))
		{
			self.addThrobberAfterObj(el);

			data = {
				secure		: 1,
				thing_id	: id
			};

			$.any.rest.post('anymeta.things.delete', data, function()
			{
				$note.fadeOut(300, function()
				{
					$(this).remove();
				});
			});
		}
	},

	/**
	 * Quote note
	 */
	quoteNote: function(id)
	{
		var self = this, $note, $formTitleField, $formBodyField, noteTitle, noteBody, noteOwner;

		$note = self.getNoteById(id);

		$formTitleField = $('#forum-comment-title').val('');
		$formBodyField  = $('#forum-comment-body').val('');

		noteTitle = $.trim( $('.comment-title',  $note).text() );
		noteBody  = $.trim( $('.comment-body',   $note).text() ); // todo: also copy markup
		noteOwner = $.trim( $('.comment-author', $note).text() );

		$formTitleField.val('Re: ' + noteTitle);

		if (noteOwner)
		{
			$formBodyField[0].value += '> ' + noteOwner + ':\n';
		}

		$formBodyField[0].value += self.prefixQuoteNote(noteBody) + '\n';

		self.scrollToCommentForm(true);
	},

	/**
	 * Prefix string with >
	 */
	prefixQuoteNote: function(comment)
	{
		var self = this, prefix, lines, line, quotedComment;

		prefix	= '> ';
		quotedComment	= '';
		lines	= comment.split(/\n/);

		for ( i = 0; i < lines.length; ++i )
		{
			line = $.trim(lines[i]);
			if (line)
			{
				quotedComment += prefix + line + '\n';
			}
		}

		return quotedComment;
	},

	/**
	 * Scroll to comment form
	 * Focus, put caret at end
	 */
	scrollToCommentForm: function(focus)
	{
		var self = this, caretEnd, $forumCommentBody;

		$forumCommentBody = $('#forum-comment-body');

		$('html,body').stop().animate({scrollTop: $('#comment-form').offset().top}, 1000, 'easeOutQuart');

		if (focus)
		{
			caretEnd = $forumCommentBody.val().length;
			$forumCommentBody
				.focus()
				.caret(caretEnd, caretEnd)
				.scrollTop(9999);
		}
	},

    clearCommentForm: function(form)
    {
    	
        form.element[0].reset();
        $("#ForumFormNoteFig .sortable-item").remove();
        
    	var preview = $("#forum-preview-area");
    	
    	if (preview.length) {
    	
	    	$("#forum-preview-area").fadeOut(300, function() {
				$(this).children().remove();
			});
    	}
    },

    scrollToPreview: function ()
    {
        var tp = $('#forum-preview-area').offset().top;
        if ($(window).scrollTop() > tp)
        {
		    $('html,body').stop().animate({scrollTop: tp}, 100, 'easeOutQuart');
        }
    }
};

//
