/*
Author: mg12
Update: 2008/11/13
Author URI: http://www.neoease.com/
*/
window['MGJS'] = {};
window['MGJS']['$'] = $;

(function() {

function reply(authorId, commentId, commentBox) {

	var author = jQuery('#'+authorId).html();
	var insertStr = '<a href="#' + commentId + '">@' + author.replace(/\t|\n|\r\n/g, "") + '</a> \n';

	appendReply(insertStr, commentBox);
}

function quote(authorId, commentId, commentBodyId, commentBox) {
	var author = jQuery('#'+authorId).html();
	var comment = jQuery('#'+commentBodyId).html();

	var insertStr = '<blockquote cite="#' + commentBodyId + '">';
	insertStr += '\n<strong><a href="#' + commentId + '">' + author.replace(/\t|\n|\r\n/g, "") + '</a> :</strong>';
	insertStr += comment.replace(/\t/g, "");
	insertStr += '</blockquote>\n';

	insertQuote(insertStr, commentBox);
}

function appendReply(insertStr, commentBox) {
	if(jQuery('#'+commentBox) && jQuery('#'+commentBox).attr('type') == 'textarea') {
		field = jQuery('#'+commentBox);
		fieldvalue = jQuery('#'+commentBox).attr('value');

	} else {
		alert("The comment box does not exist!");
		return false;
	}

	if (fieldvalue.indexOf(insertStr) > -1) {
		alert("You've already appended this reply!");
		return false;
	}

	if (fieldvalue.replace(/\s|\t|\n/g, "") == '') {
		fieldvalue = insertStr;
	} else {
		fieldvalue = fieldvalue.replace(/[\n]*$/g, "") + '\n\n' + insertStr;
	}

	field.attr('value', fieldvalue);
	field.focus();
}

function insertQuote(insertStr, commentBox) {
	if(jQuery('#'+commentBox) && jQuery('#'+commentBox).attr('type') == 'textarea') {
		field = jQuery('#'+commentBox);
		fieldvalue = jQuery('#'+commentBox).attr('value');


	} else {
		alert("The comment box does not exist!");
		return false;
	}

	if(document.selection) {
		field.focus();
		sel = document.selection.createRange();
		sel.text = insertStr;
		field.focus();

	} else if (field.selectionStart || field.selectionStart == '0') {
		var startPos = field.selectionStart;
		var endPos = field.selectionEnd;
		var cursorPos = startPos;
		fieldvalue = fieldvalue.substring(0, startPos)
					+ insertStr
					+ fieldvalue.substring(endPos, fieldvalue.length);
		cursorPos += insertStr.length;
		field.focus();
		field.selectionStart = cursorPos;
		field.selectionEnd = cursorPos;
    field.attr('value', fieldvalue);
    
	} else {
		fieldvalue += insertStr;
		field.attr('value', fieldvalue);
		field.focus();
	}
}

window['MGJS_CMT'] = {};
window['MGJS_CMT']['reply'] = reply;
window['MGJS_CMT']['quote'] = quote;

})();