(function(){
	document.write('<script type="text/javascript" src="/lib/global/scripts/text-edit/text-edit.js"></script>');
	document.write('<script type="text/javascript" src="/lib/global/scripts/rating/rating.js"></script>');
})();

var comments = {
	commentMax: 2000,
	storedView: null,
	init: function() {
		if (!$('comment_container')) { return };
		window.setTimeout(function() {
			Event.observe(insert.editArea, 'keypress', comments.counter);	
		},500);
		util.removebox = util.removebox.wrap(
			function(proceed) {
				comments.toggleEdit("on");
				return proceed();
			}
		);
		comments.setRelations();
		comments.setToolTips();
		//comments.scrollToComment();
		comments.setCommentCount();
		Event.observe($$('body')[0],'click',comments.bodyClick);
	},
	
	// set tool tips for user guidance
	setToolTips: function() {
		var replyTools = $A($$('.reply-tools'));
		replyTools.each(function(listAt){
		    $A(listAt.getElementsByClassName('quote')).each(function(itemAt){
		        new Tip($(itemAt),'click to quote this post in your own', {
					style: 'darkgrey',
					hook: {target: 'topRight', tip: 'bottomLeft'},
					stem: 'bottomLeft'
				});
		    });
		    $A(listAt.getElementsByClassName('reply')).each(function(itemAt){
				new Tip($(itemAt),'click to reply to this and the thread it is in, if applicable', {
					style: 'darkgrey',
					hook: {target: 'topRight', tip: 'bottomLeft'},
					stem: 'bottomLeft'
				});
		    });
		});
		var filterTools = $A($$('.threads'));
		filterTools.each(function(listAt){
			/*
		    $A(listAt.select('.thread-get')).each(function(itemAt){
				new Tip($(itemAt),'view all posts in this thread for all time', {
					style: 'darkgrey',
					hook: {target: 'topRight', tip: 'bottomLeft'},
					stem: 'bottomLeft'
				});
				Event.observe($(itemAt), 'mouseout', function(event){
					itemAt.removeAttribute('style').defer();
				});
		    });
			*/
		    $A(listAt.select('.thread-hide')).each(function(itemAt){
				new Tip($(itemAt), 'view all posts in this thread in the current page', {
					style: 'darkgrey',
					hook: {target: 'topRight', tip: 'bottomLeft'},
					stem: 'bottomLeft'
				});
				/*
				Event.observe($(itemAt), 'mouseout', function(event){
					itemAt.removeAttribute('style').defer();						
				});
				*/
		    });
		    $A(listAt.select('.thread-show')).each(function(itemAt){
				new Tip($(itemAt),'view all posts', {
					style: 'darkgrey',
					hook: {target: 'topRight', tip: 'bottomLeft'},
					stem: 'bottomLeft'
				});
				/*
				Event.observe($(itemAt), 'mouseout', function(event){
					itemAt.removeAttribute('style').defer();
				});
				*/
		    });
		});
		var voteTools = $($$('.threads'));
	},

	// check for extra url vars and bring to correct page
	scrollToComment: function() {
		new Effect.ScrollTo('comment_container');
		return;
		var commentID = document.URL.split("comment_id:")[1];
		if (commentID) {
		    commentID = commentID.split("/")[0];
		    if ($('comment_' + commentID)) {
		        new Effect.ScrollTo('comment_' + commentID);
		    } else {
				// TODO: Jason: figure out which page the comment is on and make that app go there
		        new Effect.ScrollTo('comment_container');
		    }
		}
	},
	
	// post/reply methods
	counter: function(e) {
		var textLength = Event.element(e).value.length;
		$('comment_counter').update(textLength + " characters.");
		if (textLength < comments.commentMax) {
			$('comment_counter').update(textLength + " characters.");
			$('comment_counter').removeClassName('error');
		} else {
			$('comment_counter').update(textLength + " characters. Too many characters");
			$('comment_counter').addClassName('error');
		}
	},
	reply: function(commentID) {
		$('replyID').value = commentID;
		insert.editArea.focus();
		this.scrollToPost();
	},
	quote: function(commentID) {
		var target = $('comment_' + commentID).getElementsByClassName('comment-body')[0].innerHTML.strip();
		var author = $('comment_' + commentID).getElementsByClassName('author')[0].getElementsByTagName('a')[0].innerHTML.strip();
		var cleanText = target
		    .replace(/<p>/gi,'')
		    .replace(/<\/p>/gi,'\n\n')
			.replace(/\n\n$/gim, '');
		var quoteText = "<strong>" + author +" wrote:</strong>\n<blockquote>" + cleanText + "</blockquote>\n\n";
		insert.editArea.value = (quoteText);
		comments.setSelectionRange(insert.editArea, insert.editArea.value.length, insert.editArea.value.length);
		preview.previewTimer();
		this.scrollToPost();
	},
	cancel: function() {
		$('replyID').value = '';
		insert.editArea.value = '';
		$('comment_counter').update('');
		insert.editArea.morph('height: 150px');
		if (preview.previewParent.visible()) {
			new Effect.SlideUp(preview.previewParent, {duration: 1});
		}
	},
	setSelectionRange: function (input, selectionStart, selectionEnd) {
		if (input.setSelectionRange) {
			input.focus();
			input.setSelectionRange(selectionStart, selectionEnd);
		} else if (input.createTextRange) {
		var range = input.createTextRange();
			range.collapse(true);
			range.moveEnd('character', selectionEnd);
			range.moveStart('character', selectionStart);
			range.select();
		}
	},
	scrollToPost: function(type) {
		new Effect.ScrollTo('commentPostForm', {duration: 1});
		if (type && type == 'default') {
			insert.editArea.focus();
		}
	},

	// relationship/threading methods
	isFiltered: false,
	setRelations: function() {
		comments.getDivList().each(function(divAt) {
			var relatedList = divAt.getElementsByClassName('related_list')[0].innerHTML.split(',');
			if (relatedList[0] != '') {
				relatedList.push(divAt.id.split('_')[1]);
				Event.observe(divAt, 'click', function(e) {
					comments.highLightThread(e,relatedList);
				});
			}
		});
	},
	getDivList: function() {
		var returnDivs = [];
		$A($('comment_container').getElementsByClassName('comment')).each(function(divAt) {
			if (divAt.id) {
				returnDivs.push(divAt);
			}
		});
		return returnDivs;
	},
	highLightThread: function(e,divList) {
		var target = Event.element(e);
		while(target.parentNode) {
			if (target.className == 'comment hilite') {
				return;
			}
			target = target.parentNode;
		}
		comments.deHighlightAll();
		var divDomList = [];
		$A(divList).each(function(divAt) {
			divDomList.push($('comment_' + divAt));
		});
		$A(comments.getDivList()).each(function(divAt) {
			if (divDomList.indexOf(divAt) != -1) {
				comments.highLightPost(divAt);
			}
		});
	},
	highLightPost: function(obj) {
		obj.addClassName('hilite');
		if (!obj.select('.thread-show')[0].hasClassName('show')) {
			obj.select('.thread-hide')[0].addClassName('show');
			//obj.select('.thread-get')[0].addClassName('show');
		}
	},
	filterThread: function() {
		$A(comments.getDivList()).each(function(divAt) {
			if (!divAt.hasClassName('hilite')) {
				new Effect.BlindUp(divAt);
			} else {
				var hideTimer = window.setTimeout(function(){
					divAt.getElementsByClassName('thread-hide')[0].removeClassName('show');
					divAt.getElementsByClassName('thread-show')[0].addClassName('show');
				},100);
			}
		});
		comments.isFiltered = true;
	},
	unFilterThread: function() {
		$A(comments.getDivList()).each(function(divAt) {
			if (divAt.hasClassName('hilite')) {
				var hideTimer = window.setTimeout(function(){
					divAt.removeClassName('hilite');
					divAt.select('.thread-show')[0].removeClassName('show');
					//divAt.select('.thread-get')[0].removeClassName('show');
				},100);
			} else {
				new Effect.BlindDown(divAt);
			}
		});
		comments.isFiltered = false;
	},
	deHighlightAll: function() {
		$A(comments.getDivList()).each(function(divAt) {
			divAt.removeClassName('hilite');
			divAt.select('.thread-hide')[0].removeClassName('show');
			divAt.select('.thread-show')[0].removeClassName('show');
			//divAt.select('.thread-get')[0].removeClassName('show');
		});
	},
	bodyClick: function(e) {
		if (comments.isFiltered) { return; }
		var abort = true;
		target = Event.element(e);
		while(target.parentNode) {
			if (target.className == 'comment hilite') {
				abort = false;
			}
			target = target.parentNode;
		}
		if (abort) {
			comments.deHighlightAll();
		}
	},
	threadGet: function(commentID) {
		comments.storedView = $('comment_posts').innerHTML;
		new Ajax.Request('/comments/ajax/get_thread/', {
			method: 'post',
			parameters: {
				commentID: commentID
			},
			onSuccess: function(t) {
				_tools.ajaxBug(t);
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},

	// show / hide posts
	toggleItems: ['comment-tools','quote','reply','threads','score','hide-post'],
	showPost: function(commentID) {
		this.toggleItems.each(function(itemAt) {
			$('comment_' + commentID).getElementsByClassName(itemAt)[0].removeClassName('hide');
		});
		$('comment_' + commentID).select('.show-post')[0].removeClassName('show');
		$('comment_' + commentID).select('.hide-post')[0].addClassName('show');
		var box = $('comment_' + commentID).select('.comment-main')[0];
		if (!sniff.isFFMac) {
			new Effect.Appear(box, {duration: 1});
		} else {
			box.show();
		}
	},
	hidePost: function(commentID) {
		comments.toggleItems.each(function(itemAt) {
			if ($('comment_' + commentID).getElementsByClassName(itemAt)[0]) {
				$('comment_' + commentID).getElementsByClassName(itemAt)[0].addClassName('hide');
			}
		});
		if ($('comment_' + commentID).select('.show-post')[0]) {
			$('comment_' + commentID).getElementsByClassName('show-post')[0].addClassName('show');
			$('comment_' + commentID).getElementsByClassName('hide-post')[0].removeClassName('show');			
		} else {
			var newListItem = new Element('li').addClassName('show-post show');
			var newLinkItem = new Element('a', {onclick: 'comments.showPost('+ commentID +'); return false;', href: '#'}).addClassName('button');
			newLinkItem.appendChild(document.createTextNode('show comment'));
			newListItem.appendChild(newLinkItem);
			if ($('comment_' + commentID).getElementsByClassName('comment-tools')[0].getElementsByClassName('show-hide').length != 0) {
				$('comment_' + commentID).getElementsByClassName('comment-tools')[0].getElementsByClassName('show-hide').getElementsByTagName('ul')[0].appendChild(newListItem);
			} else {
				var showHideNode = new Element('dd').addClassName('show-hide');
				var newListParent = new Element('ul');
				newListParent.appendChild(newListItem);
				showHideNode.appendChild(newListParent);
				$('comment_' + commentID).getElementsByClassName('comment-tools')[0].appendChild(showHideNode);
			}
		}
		if ($('comment_' + commentID).select('.hide-post')[0]) {
			$('comment_' + commentID).getElementsByClassName('hide-post')[0].removeClassName('show');			
		} else {
			var newListItem = new Element('li').addClassName('hide-post hide');
			var newLinkItem = new Element('a', {onclick: 'comments.hidePost('+ commentID +'); return false;', href: '#'}).addClassName('button');
			newLinkItem.appendChild(document.createTextNode('hide comment'));
			newListItem.appendChild(newLinkItem);
			$('comment_' + commentID).getElementsByClassName('comment-tools')[0].getElementsByClassName('show-hide')[0].getElementsByTagName('ul')[0].appendChild(newListItem);
		}
		var box = $('comment_' + commentID).select('.comment-main')[0];
		if (!sniff.isFFMac) {
			new Effect.Fade(box, {duration: 1});
		} else {
			box.hide();
		}
	},

	// validation methods
	failPoint: 0,
	errorMssg: '',
	toggleEdit: function(type) {
		switch(type) {
			case "off":
				insert.editArea.disabled = true;
				insert.editArea.addClassName('disabled');
				$('commentSubmit').disabled = true;
				$('commentSubmit').addClassName('disabled');
				var loadingSpan = new Element('span', {className: 'loading'});
				loadingSpan.update('posting comment');
				$('commentSubmit').appendChild(loadingSpan);
			break;
			
			case "on":
				if (insert.editArea.disabled) {
					insert.editArea.removeAttribute('disabled');
					insert.editArea.removeClassName('disabled');
					$('commentSubmit').removeAttribute('disabled');
					$('commentSubmit').removeClassName('disabled');
					$('commentSubmit').getElementsByClassName('loading')[0].remove();
				}
			break;
		}
	},
	validatePost: function(type) {
		preview.previewText();
		this.toggleEdit('off');
		this.failPoint = 0;
		this.errorMssg = '';
		if (insert.editArea.value.length == 0) {
			this.failPoint++;
			this.errorMssg += "<li>Please enter a comment before submitting.</li>";
		}
		if (insert.editArea.value.length >= comments.commentMax) {
			this.failPoint++;
			this.errorMssg += "<li>Your comment is too long. Comments are limited to " + this.commentMax + " characters.</li>";
		}
		this.finalCheck(type);
	},
	finalCheck: function(type) {
		if (this.failPoint != 0) {
			var mssg = {
				"header" : "There is an error",
				"bodyContent": "<ol>" + this.errorMssg + "</ol><p><a href=\"#\" onclick=\"util.removebox(); return false;\">Close this window to correct errors and continue.</a></p>"
			}
			util.talkbox($H(mssg).toJSON());
		} else {
			switch(type) {
				case "update":
					comments.ajaxUpdate();
				break;
				default:
					comments.ajaxPost();
					try {
						goog.commentPost();
					} catch (error) {
						// fail
					}
				break;
			}
		}
	},
	
	// posting methods
	ajaxPost: function() {
		new Ajax.Request('/comments/ajax/post/', {
			method: 'post',
			parameters: $('commentPostForm').serialize(),
			onSuccess: function(t) {
				var reply = $H(t.responseText.evalJSON());
				reply = reply._object;
				if (reply.success) {
					// TODO: Jason: go to last page of comments before you do this when that part is ready
					var newDiv = new Element('div',{id: 'edit_box'}).addClassName('edit');
					$('comment_posts').appendChild(newDiv);
					$('edit_box').update(reply.commentData);
					new Effect.Pulsate('edit_box', {
						from: .5,
						pulses: 3	
					});
					comments.toggleEdit('on');
					comments.cancel();
					comments.addEditing(reply.lastID);
				} else {
					var mssg = {
						"header": "There is an error",
						"bodyContent": ""
					}
					switch(reply.errorType) {
						case "comment_dupe":
							mssg.bodyContent = "<p>That is a duplicate comment</p>"
						break;
						case "comment_flood":
							mssg.bodyContent = "<p>There is a 1 minute waiting period for comments from the same user.</p>"
						break;
					}
					util.talkbox($H(mssg).toJSON());
				}
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},
	editTimer: 120,
	addEditing: function(commentID) {
		var newDiv = Builder.node('div', {id: 'edit_bar'},
			[Builder.node('a',{href:"#", onclick: "comments.editComment("+commentID+"); return false;"},'edit your comment')]
		);
		var timerMssg = comments.editTimer + " seconds remaining."
		var timerDiv =  Builder.node('div',{id:'edit_timer'}, timerMssg);
	    newDiv.appendChild(timerDiv)
		$('edit_box').appendChild(newDiv);
		comments.editTicker();
	},
	editTicker: function() {
		if (comments.editTimer > 0) {
			$('edit_timer').update(comments.editTimer + " seconds remaining.");
			timerTimer = window.setTimeout(function(){
				comments.editTicker();
			},1000);
			comments.editTimer--;
		} else {
			new Effect.BlindUp('edit_bar');
		}
	},
	editComment: function(commentID) {
		$('edit_box').hide();
		var target = $('comment_' + commentID).getElementsByClassName('comment-body')[0].innerHTML.strip();
		var cleanText = target
		    .replace(/<p>/gi,'')
			.replace(/<br\/>/gi,'\n')
			.replace(/<br>/gi,'\n')
		    .replace(/<\/p>/gi,'\n\n')
			.replace(/\n\n$/gim, '');
		insert.editArea.value = (cleanText);
		comments.setSelectionRange(insert.editArea, insert.editArea.value.length, insert.editArea.value.length);
		preview.previewTimer();
		$('commentSubmit').update('save edits');
		$('commentSubmit').removeAttribute("onclick");
		Event.observe($('commentSubmit'), 'click', function(){
			comments.validatePost('update');
		});
		if (!$('commentID')) {
			var newInput = Builder.node('input',{
				type: 'hidden',
				id: 'commentID',
				name: 'commentID',
				value: commentID
			});
			$('commentPostForm').appendChild(newInput);			
		}
	},
	ajaxUpdate: function() {
		new Ajax.Request('/comments/ajax/update/', {
			method: 'post',
			parameters: $('commentPostForm').serialize(),
			onSuccess: function(t) {
				$('edit_box').getElementsByClassName('comment-body')[0].update($('bodyText').value);
				$('edit_box').show();
				comments.toggleEdit('on');
				comments.cancel();
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},
	
	//pagination
	newPage: function(urlString,id,currentPage,sortType) {
		new Ajax.Request(urlString, {
			method:'post',
			parameters:{
				commentID:id,
				currentPage:currentPage,
				sortType:'default'
			},
			onSuccess: function(t) {
				$('comment_posts').update(t.responseText);
				new Effect.Highlight('comment_posts');
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},
	
	//misc methods
	setCommentCount: function() {
		if (!$('comment-count')) {return;}
		var commentCode = $('comment_container').select('h2.main')[0].innerHTML;
		var tmp = $('comment_container').select('h2.main')[0];
		tmp = tmp.select('span')[0].innerHTML;
		tmp = tmp.split('[')[1];
		tmp = tmp.split(']')[0];
		var newLink = new Element('a',{href:'#', onclick: 'comments.scrollToComment();' }).update('<span>'+tmp+'</span>');
		$('comment-count').update(newLink);
	},
	loginError: function() {
		util.promptLogin();
	},
	reportUser: function(userID,commentID) {
		if (!confirm('Are you sure that you want to report this user for this comment?')) {return;}
		util.setSaving();
		new Ajax.Request('/report/ajax/comments/', {
			method: 'post',
			parameters: {
				userID: userID,
				objectID: commentID,
				url: window.location.href
			},
			onSuccess: function(t) {
				util.talkbox(t.responseText);
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	}
}

document.observe('dom:loaded',comments.init);