(function() {

var xmlHttp;

function getXmlHttpObject() {
	var xmlHttp = null;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch(e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function change(wpurl, navigation) {
	xmlHttp = getXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Oop! Browser does not support HTTP Request.");
		return;
	}

	if (!$('cp_post_id')) {
		window.location = wpurl;
		return;
	}
	var postId = $('cp_post_id').innerHTML

	var commentPage = 1;
	if (/comment-page-/i.test(wpurl)) {
		commentPage = wpurl.split(/^.*comment-page-/)[1].split(/(\/|#|&).*$/)[0];
	} else if (/cpage=/i.test(wpurl)) {
		commentPage = wpurl.split(/^.*cpage=/)[1].split(/(\/|#|&).*$/)[0];
	}

	var url = wpurl.split(/#.*$/)[0];
	url += /\?/i.test(wpurl) ? '&' : '?';
	url += 'action=cpage_ajax&post=' + postId + '&page=' + commentPage;

	xmlHttp.onreadystatechange = function(){runChange(navigation)};
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function runChange(navigation) {
	var comments = $('comments');

	if (xmlHttp.readyState < 4) {
		//document.body.style.cursor = 'wait';
		navigation.innerHTML = '<span class="ajax-spinner">Loading...</span>';

		var opacity = 0.5;
		setStyle(comments, 'opacity', opacity);
		setStyle(comments, 'MozOpacity', opacity);
		setStyle(comments, 'KhtmlOpacity', opacity);
		setStyle(comments, 'filter', 'alpha(opacity=' + opacity * 100 + ')');

	} else if (xmlHttp.readyState == 4 || xmlHttp.readyState=="complete") {
		responses = xmlHttp.responseText.split('<!-- AJAX_COMMENT_PAGER_SEPARATOR_BY_MG12 -->');

		comments.innerHTML = responses[0];
		var opacity = 1;
		setStyle(comments, 'opacity', opacity);
		setStyle(comments, 'MozOpacity', opacity);
		setStyle(comments, 'KhtmlOpacity', opacity);
		setStyle(comments, 'filter', 'alpha(opacity=' + opacity * 100 + ')');

		gotoAnchor('commentcount');

		navigation.innerHTML = responses[1];
		init();
		//document.body.style.cursor = 'auto';
	}
}

function init() {
	var pagerList = getElementsByClassName('page-numbers', 'a', document);
	if (pagerList.length <= 0) {
		return;
	}
	var navigation = pagerList[0].parentNode;
	if (navigation) {
		for (var i = 0; i < pagerList.length; i++) {
			addEvent(pagerList[i], 'click', function(W3CEvent) {
				change(this.href.split(/(\?|&)action=cpage_ajax.*$/)[0], navigation);
				preventDefault(W3CEvent);
			});
		}
	}
}

function $(id) {
	return document.getElementById(id);
}

function setStyle(element, key, value) {
	element.style[key] = value;
}

function cumulativeOffset(element) {
	var valueT = 0, valueL = 0;
	do {
		valueT += element.offsetTop  || 0;
		valueL += element.offsetLeft || 0;
		element = element.offsetParent;
	} while (element);
	return [valueL, valueT];
}

function gotoAnchor(id) {
	var pos = cumulativeOffset($(id));
	var left = pos[0];
	var top = pos[1];
	window.scrollTo(left, top);
}

function isCompatible(other) {
	if( other===false 
		|| !Array.prototype.push
		|| !Object.hasOwnProperty
		|| !document.createElement
		|| !document.getElementsByTagName
		) {
		alert('TR- if you see this message isCompatible is failing incorrectly.');
		return false;
	}
	return true;
}

function getElementsByClassName(className, tag, parent){
	parent = parent || document;

	var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
	var matchingElements = new Array();

	className = className.replace(/\-/g, "\\-");
	var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
	
	var element;
	for(var i=0; i<allTags.length; i++){
		element = allTags[i];
		if(regex.test(element.className)){
			matchingElements.push(element);
		}
	}

	return matchingElements;
};

function addEvent( node, type, listener ) {
	if(!isCompatible()) { return false }

	if (node.addEventListener) {
		node.addEventListener( type, listener, false );
		return true;
	} else if(node.attachEvent) {
		node['e'+type+listener] = listener;
		node[type+listener] = function(){node['e'+type+listener]( window.event );}
		node.attachEvent( 'on'+type, node[type+listener] );
		return true;
	}

	return false;
};

function preventDefault(eventObject) {
	eventObject = eventObject || getEventObject(eventObject);
	if(eventObject.preventDefault) {
		eventObject.preventDefault();
	} else {
		eventObject.returnValue = false;
	}
}

String.prototype._$$split = String.prototype._$$split || String.prototype.split;
String.prototype.split = function (s, limit) {
	if (!(s instanceof RegExp))
		return String.prototype._$$split.apply(this, arguments);

	var	flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") + (s.multiline ? "m" : ""),
		s2 = new RegExp("^" + s.source + "$", flags),
		output = [],
		origLastIndex = s.lastIndex,
		lastLastIndex = 0,
		i = 0, match, lastLength;

	if (limit === undefined || +limit < 0) {
		limit = false;
	} else {
		limit = Math.floor(+limit);
		if (!limit)
			return [];
	}

	if (s.global)
		s.lastIndex = 0;
	else
		s = new RegExp(s.source, "g" + flags);

	while ((!limit || i++ <= limit) && (match = s.exec(this))) {
		var emptyMatch = !match[0].length;

		if (emptyMatch && s.lastIndex > match.index)
			s.lastIndex--;

		if (s.lastIndex > lastLastIndex) {
			if (match.length > 1) {
				match[0].replace(s2, function () {
					for (var j = 1; j < arguments.length - 2; j++) {
						if (arguments[j] === undefined)
							match[j] = undefined;
					}
				});
			}

			output = output.concat(this.slice(lastLastIndex, match.index));
			if (1 < match.length && match.index < this.length)
				output = output.concat(match.slice(1));
			lastLength = match[0].length;
			lastLastIndex = s.lastIndex;
		}

		if (emptyMatch)
			s.lastIndex++;
	}

	output = lastLastIndex === this.length ?
		(s.test("") && !lastLength ? output : output.concat("")) :
		(limit ? output : output.concat(this.slice(lastLastIndex)));
	s.lastIndex = origLastIndex;
	return output;
};

if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, false);

} else if (/MSIE/i.test(navigator.userAgent)) {
	document.write('<script id="__ie_onload_for_ajax_comment_pager" defer src="javascript:void(0)"></script>');
	var script = $('__ie_onload_for_ajax_comment_pager');
	script.onreadystatechange = function() {
		if (this.readyState == 'complete') {
			init();
		}
	}

} else if (/WebKit/i.test(navigator.userAgent)) {
	var _timer = setInterval( function() {
		if (/loaded|complete/.test(document.readyState)) {
			clearInterval(_timer);
			init();
		}
	}, 10);

} else {
	window.onload = function(e) {
		init();
	}
}

////////////////////////

function reply(author, commentId, commentBox) {
	//var insertStr = '<a href="#comment-' + commentId + '"><strong>@' + author + '</strong></a>, \n';
	//appendReply(insertStr, commentBox);
	document.getElementById('comment_parent').value = commentId;
	document.getElementById(commentBox).focus();
}

function quote(author, commentId, commentBodyId, commentBox) {
	var comment = MGJS.$(commentBodyId).innerHTML;

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

	insertQuote(insertStr, commentBox);
}

function appendReply(insertStr, commentBox) {
	if(MGJS.$(commentBox) && MGJS.$(commentBox).type == 'textarea') {
		field = MGJS.$(commentBox);
	} else {
		alert("The comment box does not exist!");
		return false;
	}

	if (field.value.indexOf(insertStr) > -1) {
		return false;
	}

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

function insertQuote(insertStr, commentBox) {
	if(MGJS.$(commentBox) && MGJS.$(commentBox).type == 'textarea') {
		field = MGJS.$(commentBox);
	} 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;
		field.value = field.value.substring(0, startPos)
					  + insertStr
					  + field.value.substring(endPos, field.value.length);
		cursorPos += insertStr.length;
		field.focus();
		field.selectionStart = cursorPos;
		field.selectionEnd = cursorPos;

	} else {
		field.value += insertStr;
		field.focus();
	}
}

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

})();

function edDoCode(v){formname='commentform';textname='comment';startv=v;endv=v;if(startv=="a"){url=prompt('Enter the link url','http://');if(url!=""){startv="a href=\""+url+"\"";};}if(document.selection){var str=document.selection.createRange().text;document.forms[formname].elements[textname].focus();var sel=document.selection.createRange();sel.text="<"+startv+">"+str+"</"+endv+">";return;}else if((typeof document.forms[formname].elements[textname].selectionStart)!='undefined'){var txtarea=document.forms[formname].elements[textname];var selLength=txtarea.textLength;var selStart=txtarea.selectionStart;var selEnd=txtarea.selectionEnd;var oldScrollTop=txtarea.scrollTop;var s1=(txtarea.value).substring(0,selStart);var s2=(txtarea.value).substring(selStart,selEnd);var s3=(txtarea.value).substring(selEnd,selLength);txtarea.value=s1+'<'+startv+'>'+s2+'</'+endv+'>'+s3;txtarea.selectionStart=s1.length;txtarea.selectionEnd=s1.length+5+s2.length+startv.length+endv.length;txtarea.scrollTop=oldScrollTop;txtarea.focus();return;}else{insert('<'+v+'></'+v+'> ',formname,textname);}}
function edSmile(){jQuery("#smileybox").toggle();}
function addQuote(comment,quote){if(document.selection){comment.focus();sel=document.selection.createRange();sel.text=quote;comment.focus();}else if(comment.selectionStart||comment.selectionStart=='0'){var startPos=comment.selectionStart;var endPos=comment.selectionEnd;var cursorPos=endPos;var scrollTop=comment.scrollTop;if(startPos!=endPos){comment.value=comment.value.substring(0,startPos)+quote+comment.value.substring(endPos,comment.value.length);cursorPos=startPos+quote.length}else{comment.value=comment.value.substring(0,startPos)+quote+comment.value.substring(endPos,comment.value.length);cursorPos=startPos+quote.length;}comment.focus();comment.selectionStart=cursorPos;comment.selectionEnd=cursorPos;comment.scrollTop=scrollTop;}else{comment.value+=quote;}}
function postQuote(alertmsg){var posttext='';if(window.getSelection){posttext=window.getSelection();}else if(document.getSelection){posttext=document.getSelection();}else if(document.selection){posttext=document.selection.createRange().text;}else{return true;}if(posttext==''){alert(alertmsg);return true;}else{var quote='<blockquote>'+posttext+'</blockquote>\n';var comment=document.getElementById('comment');addQuote(comment,quote);}return false;}
function insertEmoticon(insertStr) {
	var myField;
	if (document.getElementById('comment') && document.getElementById('comment').type == 'textarea') {
		myField = document.getElementById('comment');
	} else {
		return false;
	}

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

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

	} else {
		myField.value += insertStr;
		myField.focus();
	}
}