document.observe('dom:loaded',comment_init, false);

function comment_init()
{
    var myAjax = new Ajax.Request(
        '/global/ajax/is_site_staff.php',
        {method: 'get', onComplete: comment_admin_check}
    );
}

function comment_admin_check(response)
{
	if(response.responseText != 0)
	{
		var e_list = document.getElementsByClassName('comment_options');
		for(var i = 0; i < e_list.length; i++)
		{
			comment_id = e_list[i].id.substr(16);
			new Insertion.Top(e_list[i],"<a href='javascript:delete_comment(" + comment_id + ")'>Delete</a> | ");
		}
	}
}

function comment_quote(obj)
{
	if($('comment').value != '') $('comment').value = $('comment').value + "\n\n";
	$('comment').value = $('comment').value + "[quote=" + $(obj + '_author').innerHTML + ']' + $(obj + '_body').value + '[/quote]';
}

function comment_reply(obj)
{
	if($('comment').value != '') $('comment').value = $('comment').value + "\n\n";
	$('comment').value = $('comment').value + "@" + $(obj + '_author').innerHTML + ': ';
}

function comment_preview()
{
	var d = new Date();

	output  = "<h2>Live Preview</h2>";
	output += "<div class='comment_container'>";
	output += "<div class='comment_body' id='comment_preview_body'>Loading...</div>";

	output += "<div class='comment_footer'>";
	output += "<div class='comment_byline'>";
	output += "<span class='comment_author'>" + $('comment_username').value + "</span>";
	output += " | " + d.formatDate("j M Y H:i");
	output += "</div>";

	output += "</div>";
	output += "</div>\n";

	$('preview_container').innerHTML = output;
	$('comment_preview_button').disabled = 1;
	ajax_preview();

	Event.observe('comment', 'keyup', ajax_preview_set, false);
	new PeriodicalExecuter(ajax_preview, 0.5);
}

var preview_update = 1;

function ajax_preview_set()
{
	preview_update = 1;
}

function ajax_preview()
{
	if(preview_update == 1)
	{
		url = '/global/ajax/string_parser.php';
		pars = 'string='+encodeURIComponent($('comment').value);
		target = 'comment_preview_body';
		myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onlyLatestOfClass: 'live_preview'});
		preview_update = 0;
	}
}

function delete_comment(id)
{
	if(confirm("Are you sure you want to delete this comment?"))
	{
		$('comment_options_' + id).innerHTML = 'deleting...';
		pars  = 'id=' + id;
		pars += '&site_id=' + $('comments_site_id').value;
		pars += '&unit_id=' + $('comments_unit_id').value;
		pars += '&category=' + $('comments_category').value;

		new Ajax.Request('/global/ajax/inline_comments/delete_comment.php', {method:'post', postBody:pars, onComplete:remove_comment});
	}
}

function remove_comment(response)
{
	id = parseInt(response.responseText);

	if(id > 0)
	{
		Element.remove("comment_" + id);
	}
}