
/**
 * JavaScript class for blog-related actions.
 */
var Blog = Class.create({

	blogurl: null,

	/**
	 * Blog constructor.
	 */
	initialize: function() {

		this.blogurl = siteurl + 'blog/';

		// Open the comments section (if available)
		if ($('post-comment')) {
			$('comments-javascript').style.display = 'none';
			$('comments-form').style.display = '';
			$('comments-notes').style.display = '';

			// Enable the submit button
			$('form-submit').observe('click', (function(event) {
				this.postComment();
				event.stop();
			}).bind(this));

			// Enable the quote link
			var quotelinks = $$('a[rel="quote"]');
			for (var i = 0; i < quotelinks.length; i++) {
				var quotelink = quotelinks[i];
				quotelink.observe('click', (function(event) {
					var link = event.findElement('a');
					var href = link.href;
					var num  = href.substring(href.indexOf('-') + 1);
					this.quote(num);
					event.stop();
				}).bind(this));
			}
		}
	},

	/**
	 * Post a comment.
	 */
	postComment: function() {

		// Display message
		messagebox.show('Posting comment...', (function() {

			// Sanitize user input
			$('form-comment').value = html_sanitize($F('form-comment'), function(url) {
				if (url.match(/https?:\/\/.*/)) {
					return url;
				}
			});

			// Submit form
			new Ajax.Request(this.blogurl + 'user?action=post', {
				parameters: $('comments-form').serialize(true),
				onSuccess: function(response) {

					// Display validation errors if any
					var messages = response.responseJSON;
					if (messages) {
						messagebox.update('Posting comment... unable to post your comment.');
						var error = '';
						for (var i = 0; i < messages.length; i++) {
							error += '- ' + messages[i] + '<br/>';
						}
						messagebox.error(error);
					}

					// Reload page to show comment
					else {
						var url = window.location.toString();
						url = url.substring(0, url.indexOf('#'));
						window.location = url + '#lastcomment';
						window.location.reload(true);
					}
				},

				// Display error if unable to save
				onFailure: function(response) {
					messagebox.update('Posting comment... unable to post your comment.');
					messagebox.error('- (unknown reason/s)');
				}
			});
		}).bind(this));
	},

	/**
	 * Quote the text of a previous commenter.
	 * 
	 * @param number
	 */
	quote: function(number) {

		var commentername = $('comment-' + number + '-formname').innerHTML;
		var commentertext = $('comment-' + number + '-formtext').innerHTML.trim();
		var commentfield = $('form-comment');
		var comment = $F('form-comment');
		if (comment) {
			comment+= '\n\n';
		}
		commentfield.value = comment +
				'<b>' + commentername + '</b> wrote:\n\n' +
				'<blockquote>\n' + commentertext + '\n</blockquote>\n\n';

		Effect.ScrollTo('post-comment', {
			afterFinish: function() {
				commentfield.focus();
			}
		});
	}
});

