


$(document).ready(function(){
	
	$('form.formClass').hide();
	
	// tiny mce config
	var configArray = [{
		theme : "advanced",
		mode : "none",
		cleanup: true,
		cleanup_on_startup : true,
		force_br_newlines: false,
		entity_encoding : "named",
		theme_advanced_layout_manager : "SimpleLayout",
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_buttons1 : "bold,italic,|,undo,redo,|,link,unlink,bullist",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		invalid_elements : "script,span,font,color,div,style",
		language : "en",
		height:"200",
		width:"100%"
	}];
		
	jQuery.listen('click','.loginNotice_toggle_top', function(e) {
		e.preventDefault();
		$('#loginNotice_box_top').slideToggle('fast');
		
	});
	
	jQuery.listen('click','.loginNotice_toggle_bottom', function(e) {
		e.preventDefault();
		$('#loginNotice_box_bottom').slideToggle('fast');
		
	});
	
	//make a comment
	//
	jQuery.listen('click','.commentLink', function(e) {
		e.preventDefault();
		
		if($(this).attr('id') == 'bottomCommentForm_toggle') {
			var target_id = $('#mainCommentForm_bottom');
		} else {
			var target_id = $('#mainCommentForm_top');	
		}
		
		closeOrphan(target_id);
		formViewControl(target_id, '#commentForm');
		
		$(".cancelButton").click(function (event) {
			event.preventDefault();
			formViewControl(target_id, '#commentForm')
		});
	});
	
	//reply to a comment
	//
	jQuery.listen('click','.replyLink', function(e) {
		e.preventDefault();
		var target_id = $('#sub_commentForm_' + this.id);
		closeOrphan(target_id);
		formViewControl(target_id, '#commentForm');
		$('.replyLink', target_id.parent()).hide();
		
		$(".cancelButton").click(function (event) {
			event.preventDefault();
			formViewControl(target_id, '#commentForm')
			$('.replyLink', target_id.parent()).show();
		});
	});
	
	
	//edit a comment
	//
	jQuery.listen('click','.editLink', function(e) {
		e.preventDefault();
		
		var target_id = $('#edit_commentForm_' + this.id);
		var container= target_id.parent(); 
		var commentText = $('.commentBody', container).html();
		var editLink = $('.editLink', container);
		
		closeOrphan(target_id);
		formViewControl(target_id, '#editForm', commentText)
		$('.commentBody', container).toggle();
		editLink.hide();
		
		$(".cancelButton").click(function (event) {
			event.preventDefault();
			closeMCE(target_id);
			$('.commentBody', container).toggle();
			editLink.show();
		});
		
	});
	
	// helper functions 
	// toggle forms, add text editor or remove it based on current status, clear out innerHTML when done
	function formViewControl(target_id, formId, commentText) {
		if(isEmpty(target_id)) {
			var commentForm = $(formId).html();
			$(target_id).html(commentForm);
			var textarea = $(target_id).find('textarea');
			textarea.attr('id','activeTextarea');
			if(commentText != undefined) {
				textarea.text(commentText);
			}
			$(target_id).toggle();
			
			tinyMCE.settings = configArray[0];
			tinyMCE.execCommand('mceAddControl', true, "activeTextarea");
		} else {
			$(target_id).toggle(function(){
				if(commentText != ''){ $('textarea', formId).html(''); }
				tinyMCE.execCommand('mceRemoveControl', true, "activeTextarea");
				$(target_id).html('');
				
			});		
		}
	}
	
	// check to see if any other forms are open before opening a new one.
	function closeOrphan(target_id) {
		var allForms = $('.formClass');
		allForms.each(function() {
			if( ($(this).is(":visible")) && ($(this).attr('id') != $(target_id).attr('id')) ) {
				closeMCE($(this));
			}
		});
	}
	
	function closeMCE(element) {
		$(element).toggle();
		tinyMCE.execCommand('mceRemoveControl', true, "activeTextarea");
		$(element).html('');
	}
	
	function isEmpty(element) {
		if($(element).html() == false) {
			return true;
		} else {
			return false;
		}
	}


	

	// form submit listener - updates db and determines ui based on new comment or edit exisiting
	//
	jQuery.listen('click','input.submitButton', function(e) {
		
		$(this).attr("disabled", true);
		$(this).css({'color' : '#aaa'});
		e.preventDefault();
		
		var new_reply = true;
		var current_form = $(this).parents(".formClass");
		
		var content = tinyMCE.triggerSave();
		queryString = current_form.serialize();

		var comment_id = current_form.attr('id');
	
		// which form - new reply or edit existing?
		if(current_form.attr('action').indexOf('edit') == -1) {
			new_reply = true;
		} else {
			new_reply = false;
		}
		
		button = this;
		
		$(this).bind("ajaxStop", function(){
		  $(this).css({'color' : '#000'});
		});
		
		$.ajax({
			url : current_form.attr('action'),
			type: "POST",
			data: queryString,
			dataType: 'json',
			success : function (data) {
				y = 0;
				jQuery.each(data, function(key, val) {
					var parent = $('#' + comment_id);
					if(key == 'errors') {
						$(button).removeAttr("disabled");
						// $('label:first', parent).html('comment: - <span style="color: red">required<\/span>');
						$(".mceLayout").css({"border" : "1px solid red"});
						message = 'Error: ' + val.comment
						$(".errorMessage", current_form).html(message);
						
						return
					} else if(y <= 1) {
						if(new_reply) {
							comment_close(parent, data[0])
						} else {
							edit_close(parent,data[0])
						}
						y++;
					}
				});
			}
			
			
		});
		
		return false;
	});
	
	
	
	
	// ajax update was successful, now close the textfield and add new comment in on client side
	//
	// edit version
	function edit_close(parent, data){
		container = parent.parent();
		$('.commentBody', container).html(data.fields.comment)
		$('.commentBody', container).toggle();
		$('.editLink', container).show();
		
		closeMCE(parent);
	}
	//
	// new reply version
	function comment_close(parent, data){
		var is_main = true;
		var hasChildren = false;
		
		$('label:first', parent).html('comment:');
		$('textarea', parent).css({"border" : "1px solid #333333"});
		
		parent.queue(function() {
			$(this).append('<p style="display: none;"><span style="font-size: 20px; color: green">+</span> your comment has been posted</p>');
			$('p:last', this).fadeIn(function() {
				parent.slideToggle('slow', function() {
					// make new reply appear at bottom of dd elements
					element = parent.parent('dt');
					brother = element.next();
					
					user = $('#current_user').attr('value');
					newReplyForm = '<form id="edit_commentForm_c' + data.pk + '" class="formClass" method="post" action="/thinkoutloud/threadedcomments/comment/' + data.pk + '/edit/json/" style="display: none;"></form>';
					newReplyLink = '<a class="editLink" id="c' + data.pk + '" href="."><img class="replyImage" src="/thinkoutloud/media/images/TOL_icon_edit.gif"> Edit (you may edit your comment within 5 minutes of posting) </a>';
					
					// are we dealing with a main comment or a reply to a comment?
					if(parent.attr('id').indexOf('main') == -1) { // reply to comment
						if(brother.attr('class') == '') {
							hasChildren = false; // this comment has no replies yet
						} else {
							commentList = $('.' + brother.attr('class')); // get all other replies (sub comments) to this commnent
							hasChildren = true;
						}
						commentHTML = '<dd><div class="commentBody">' + data.fields.comment + '</div><div class="commentByline">' + user + '</div>' + newReplyForm + newReplyLink + '</dd>';
						is_main = false;
					} else { // user is replying to the main post
						commentHTML = '<dt><div class="commentBody">' + data.fields.comment + '</div><div class="commentByline">' + user + '</div>' + newReplyForm + newReplyLink + '</dt>';
						$('#anchor_dt').before(commentHTML); // static 'anchor' dt at bottom of comments
						is_main = true;
					}
					
					if(is_main == false) {
						// add new reply to end of existing replies
						if(hasChildren == true) {
							var i = 1;
							commentList.each(function (){
								if(i == commentList.length){
									$(this).after(commentHTML);
									return;
								}
								i++;
							});
						} else { // add new reply to a comment (no replies exist yet)
							element.after(commentHTML);
						}
						
					}
					tinyMCE.execCommand('mceRemoveControl', true, "activeTextarea");
					parent.html('');
					$('.replyLink', parent.parent()).show();
				});
			});
			parent.stop('clearQueue');
			
		});
	}
	
	
 }); 

	