$(document).ready(function(){
	
	$('form.formClass').hide();
	$(":checkbox").attr("autocomplete", "off");

	// tiny mce config
	var configArray = [{
		theme : "advanced",
		mode : "none",
		plugins : "paste",
		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",
		inline_styles : false,
		language : "en",
		height:"200",
		width:"100%"
	}];
		
	jQuery.listen('change','.emailAlert', function(e) {
		data = { cid: $(this).attr("value"), checked: this.checked };
		$(this).parent().load('/thinkoutloud/email_alert/', data);
	});	
		
	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') {
			target_id = $('#mainCommentForm_bottom');
		} else {
			target_id = $('#mainCommentForm_top');
		}
		
		var target_button = this
		$(this).toggle('fast');
		
		closeOrphan(target_id);
		formViewControl(target_id, '#commentForm');
		
		$(".cancelButton").click(function (event) {
			event.preventDefault();
			formViewControl(target_id, '#commentForm')
			$(target_button).toggle('fast');
		});
	});
	

	//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');
		
		// add parent id field
		target_id.append('<input id="id_parent" type="hidden" value="' + this.id.slice(1) + '" name="parent">');
		
		$('.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);
		
		// extra options (ex. email alert checkbox) that are part of form, so if form is displayed, no need to show
		var extraOptions = $(this).prevAll('.commentByline').children('.commentExtraLinks');
		var emailAlertStatus = extraOptions.children('.emailAlert').attr('checked');
		
		// show form
		closeOrphan(target_id);
		formViewControl(target_id, '#editForm', commentText);
		if(emailAlertStatus) target_id.find('#id_email_alert').attr('checked', true);
		
		// add comment id field
		target_id.append('<input id="id_edit_comment" type="hidden" value="' + this.id.slice(1) + '" name="edit_comment">');
		
		// add parent id field
		target_id.append('<input id="id_parent" type="hidden" value="' + this.id.slice(1) + '" name="parent">');
		
		// change action to edit
		target_id.attr('action','/thinkoutloud/comments/edit/');
		
		
		// hide original comment + links while user is editing
		$('.commentBody', container).toggle();
		editLink.hide();
		extraOptions.toggle();		
		
		
		$(".cancelButton").click(function (event) {
			event.preventDefault();
			closeMCE(target_id);
			$('.commentBody', container).toggle();
			editLink.show();
			extraOptions.toggle();
		});
		
	});
	
	// 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('');
				
			});		
		}
	}
	
	// closes all form instances except for target_id
	function closeOrphan(target_id) {
		var allForms = $('.formClass');
		allForms.each(function() {
			if( ($(this).is(":visible")) && ($(this).attr('id') != $(target_id).attr('id')) ) {
				$(this).prev('.replyLink').toggle(); // thread comments
				$(this).prevAll('.commentLink').toggle(); // bottom button
				$(this).prev('#TOL_current_show_detail').find('.commentLink').toggle(); // top button

				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?
		//alert(current_form.children("input[name=edit_comment]").val());
		if(current_form.children("input[name=edit_comment]").val() == undefined) {
			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");
						$(".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();
		
		$('.commentExtraLinks', container).toggle();
		$('.commentBody', container).html(data.comment)
		$('.commentBody', container).toggle();
		$('.editLink', container).show();
		
		if(data.email_alert) $('.emailAlert', container).attr('checked', true);
		else $('.emailAlert', container).attr('checked', false);
		
		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() {
					// common ajax params
					var url_string = '/thinkoutloud/get_comments';
					var data_string = { cid: data.comment_pk };
					var type_string = 'POST';
					
					// make new reply appear at bottom of dd elements
					element = parent.parent('dt');
					brother = element.next();
					
					// 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;
						}
						is_main = false;
					} else { // user is replying to the main post
						jQuery.ajax({ url: url_string, data: data_string, type: type_string,
							success: function(data) {
								$('#anchor_dt').before(data);
							}
						});
						is_main = true;
					}
					
					if(is_main == false) { // add new reply to end of existing replies
						if(hasChildren == true) {
							var i = 1;
							commentList.each(function (e, current){
								if(i == commentList.length){
									jQuery.ajax({ url: url_string, data: data_string, type: type_string,
										success: function(data) {
											$(current).after(data);
										}
									});
									return;
								}
								i++;
							});
						} else { // add new reply to a comment (no replies exist yet)							
							jQuery.ajax({ url: url_string, data: data_string, type: type_string,
								success: function(data) {
									element.after(data);
								}
							});
						}
					}
					
					tinyMCE.execCommand('mceRemoveControl', true, "activeTextarea");
					parent.html('');
					$('.replyLink', parent.parent()).show();
				});
			});
			parent.stop('clearQueue');
			
		});
	}
	
	
 }); 

	
