comments_server = 'http://arduino.cc/tools';

$(document).ready (function () {
	if ($('#commentsbox').length == 0)
		return;

	$('head').append ('<link rel="stylesheet" type="text/css" media="screen" href="' + comments_server + '/assets/comments/css/comments.css" />');
	$('head').append ('<link rel="stylesheet" type="text/css" media="screen" href="http://arduino.cc/resources/jquery/themes/base/jquery-ui.css" />');

	$.ajax ({
		url: comments_server + '/comments/extern/fetch/',

		data: {
			url: encodeURIComponent (window.location)
		},

		dataType: 'jsonp',

		success: function (data) {
			if (typeof data === 'undefined')
				return;

			var full = $('<div id="externalcomments" class="wikicomments">');

			if ($('input[name=comment_box_title]').length != 0)
				title = $('<div><h3 class="commentstitle">' + $('input[name=comment_box_title]').val () + '</h3></div>');
			else
				title = $('<div><h3 class="commentstitle">COMMENTS</h3></div>');

			full.append (title);

			if (data instanceof Array == false)
				formatTree (full, data.comments);

			if (cookieExists('arduino_sso_authorized')) {
				newpost = writeCommentBox (false);
				addSubs (full).append (newpost);
			}
			else {
				notify = $('<div id="loginalert">You must be logged in to post a comment.</div>');
				full.append (notify);
			}

			$('#commentsbox').after (full);
		}
	});

	try {
		$('.reportcomment').live ('click', function () {
			return raiseReport ($(this));
		});

		$('.replycomment').live ('click', function () {
			return onReplyStart ($(this));
		});
	}
	catch (err) {
		$('body').delegate ('.reportcomment', 'click', function () {
			return raiseReport ($(this));
		});

		$('body').delegate ('.replycomment', 'click', function () {
			return onReplyStart ($(this));
		});
	}
});

function raiseReport (a) {
	id = $(a).parent ().parent ().parent ().attr ('id');
	doReportDialog (id);
	return false;
}

function onReplyStart (a) {
	$(a).parent ().parent ().parent ().find ('.subcomments:first').prepend (writeCommentBox (true));
	return false;
}

function addSubs (parent) {
	var box = $('<div class="subcomments">');
	parent.append (box);
	return box;
}

function formatTree (parent, comments) {
	var box = addSubs (parent);

	if (comments.length == 0)
		return;

	for (var i = 0; i < comments.length; i++) {
		var d = comments [i];
		var p = formatComment (d);
		box.append (p);
		formatTree (p, d.comments);
	}
}

function cookieExists (c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf (c_name + "=");

		if (c_start != -1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);

			if (c_end==-1)
				c_end=document.cookie.length;
			return 1;
		}
	}

	return 0;
}

function formatComment (data) {
	var d = new Date (data.timestamp * 1000);

	if (cookieExists('arduino_sso_authorized'))
		options = '<p class="commentbuttons"><a href="#" class="replycomment">Reply</a> | <a href="#" class="reportcomment">Report</a></p>';
	else
		options = '<p class="commentbuttons">&nbsp;</p>';

	return $('<div class="post" id="' + data.id + '">\
			<a name="' + data.id + '"></a>\
			<div class="posthead">\
				<p class="postericon">\
					<img width="30" height="30" src="http://static.arduino.cc/avatars/' + data.author.username + '.jpg" onerror="this.onerror = null; this.src = \'' + comments_server + '/assets/comments/images/user.png\'" />\
				</p>\
				<p class="userinfo"><span class="commentauthor">' + data.author.username + '</span> <span class="commentdate">' + d.toLocaleDateString () + '</span></p>' +
				options +
			'</div>\
			<p class="commentbody">' + data.body + '</p>\
			<div class="clearer"></div>\
		</div>');
}

function doReportDialog (id) {
	rep = $('<div id="reportcommentdialog" title="Report This Comment">\
			<input type="hidden" name="commentid" value="' + id + '" />\
			<p>Please alert us about unattended contents!</p>\
			<p>Attach a comment to your report:</p>\
			<p><textarea></textarea></p>\
		</div>');

	$('#externalcomments').append (rep);

	rep.dialog ({
		autoOpen: false,
		modal: true,
		buttons: {
			"Send!": function() {
				$.ajax ({
					url: comments_server + '/comments/extern/post_report',
					data: {
						body: $('#reportcommentdialog').find ('textarea').val (),
						url: encodeURIComponent (window.location),
						id: $('#reportcommentdialog').find ('input[name=commentid]').val ()
					},

					dataType: 'jsonp',

					success: function (data) {
						/* dummy */
					}
				});

				alert ('Thanks for your feedback!');
				$(this).dialog ('close');
			},
			"Cancel": function() {
				$(this).dialog ('close');
			}
		},
		close: function() {
			$('#reportcommentdialog').find ('textarea').val ('');
		}
	});

	$('#reportcommentdialog').dialog ('open');
}

function writeCommentBox (cancellable) {
	var newpost = $('<div id="newpost">');
	newpost.append ('<p>Leave a message...</p>');
	newpost.append ('<p><textarea></textarea></p>');

	var buttons = $('<div>');
	newpost.append (buttons);

	var submitbutton = $('<input type="button" value="Post">');
	submitbutton.click (function () {
		commentbox = $(this).parent ().parent ();
		submitbutton.attr ('disabled', 'disabled');

		$.ajax ({
			url: comments_server + '/comments/extern/post_comment',
			data: {
				body: commentbox.find ('textarea').val (),
				url: encodeURIComponent (window.location),
				parentid: $(this).parent ().parent ().parent ().parent ().attr ('id')
			},

			dataType: 'jsonp',

			success: function (data) {
				var c = formatComment (data);
				addSubs (c);
				commentbox.parent ().append (c);
				commentbox.remove ();
				c.effect ("pulsate", { times: 3 }, 800);
			}
		});
	});

	buttons.append (submitbutton);

	if (cancellable == true) {
		var cancelbutton = $('<input type="button" value="Cancel">');
		cancelbutton.click (function () {
			$(this).parent ().parent ().remove ();
		});

		buttons.append (cancelbutton);
	}

	return newpost;
}

