

$(document).ready(function(){
	
	init_pretty_ddls();
	init_trackers();
	setupOverlayWindows();
	setupStatusSetter();
	setupFlashMessage();
	setupFeedCommenting();
	
});//end document.ready


// UTILITY FUNCTIONS ////////////////////////////////////////////////

function reverse(str)
{
	var backstr = "";

	for (var i = str.length-1; i >= 0; i -= 1)
		backstr += str.charAt(i);

	return backstr;
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// END UTILITY FUNCTIONS ////////////////////////////////////////////////




function setupStatusSetter()
{
	
	if($("#current_status_setter").length > 0)
	{
	
		$("#current_status_setter").keydown(function(e){
		
			var key = e.charCode || e.keyCode || 0;  
			
			//if the enter key was pressed
			if(key == 13)
			{
				
				$val = $("#current_status_setter").val();

				$.ajax({
					data:'status=' + $val + '&authenticity_token=' + window._token, 
					dataType:'json', 
					type:'post', 
					url:'/status',
					async: true,
					complete: function(e){
						
						var ret = eval(e.responseText);
						
						$("#current_status_setter").val("");
						$("#last_status .text").html(ret[0].status_response.substring(0, 70));
						$("#last_status .timestamp").html(ret[0].date_response);
					}
				});
				
			}//end if
			
		});//end key down
	
	}//end if status setter is present
	
}//end setupStatusSetter



function setupOverlayWindows()
{
	//setup overlays
	if( $(".overlay_actuator").length > 0)
	{
		$(".overlay_actuator").each(function(){
			
			$(this).unbind("click");
			$(this).fancybox({
				'overlayShow':true,
				'overlayOpacity': 0.8,
				'frameWidth': 760,
				'frameHeight': 600
			});
		});
	
	}
	
}//end setupOverlayWindows



//function to mark items that are JS removed for real delete
function mark_for_destroy(element, css_class)
{
	$(element).next().next().attr("value", "1");
	$(element).parents(css_class).hide();
	
}//end function mark_for_destroy


function init_pretty_ddls()
{
	var ie6 = (($.browser.msie && Math.floor($.browser.version) == 6)? true : false);
	if(ie6 == true)
		return;
	
	//insert all the needed HTML elements around the pretty_ddl to make it work
	$(".pretty_ddl").each(function(){
		$(this).prev("label").before('<div class="ddl_wrapper">');
		
		if( $(this).hasClass("inline") )
			$(this).after('</div><!-- end .ddl_wrapper -->');
		else
			$(this).after('</div><!-- end .ddl_wrapper --><div class="clear"></div>');
			
		$(this).prev("label").wrap('<div class="ddl_lbl_container"></div>');
		$(this).wrap('<div class="ddl_container"></div>');
		$(this).parents(".ddl_container").before('<div class="ddl_left"></div>');
		$(this).before('<div class="ddl_content_lbl">ddl init val</div>');
	});
	
	//set the ddl container width based on its content
	$(".ddl_container").each(function(){
		$(this).width($(this).children(".pretty_ddl").width() + 25);
	});
	
	//set the ddl background based on its content &
	//set the initial label shown
	$(".pretty_ddl").each(function(){
		$(this).width($(this).width() + 24);
		if(this.options.length > 0)
			$(this).prev(".ddl_content_lbl").html(this.options[this.selectedIndex].innerHTML);
		else
			$(this).prev(".ddl_content_lbl").html("");
	});
	
	//setup the pretty_ddls mouseover & mouseout
	$(".ddl_container").mouseover(function(){
		$(this).addClass("dropdown_over");
	}).mouseout(function(){
		$(this).removeClass("dropdown_over");
	});
	
	//setup the pretty_ddl change function
	$(".pretty_ddl").change(function(){
		$(this).prev(".ddl_content_lbl").html(this.options[this.selectedIndex].innerHTML);
	});
	
}//end function init_pretty_ddls


//callback function to wrap error messages
function errorWrapper(err)
{
	return '<div class="errorMsg">'+err+'</div>';
	
}//end function errorWrapper


//array to hold any form error messages
var FORM_ERRORS = new Array();

//variable to tell if form is valid
var val_pass = true;

/**
 * Validation function, which can be for a form, or just for a 
 * container element.  Either way it validates form fields.  Each
 * form field will tell how it needs to be validated through the 'rel' tag
 * 'req' means required, 'email' means email format.
 *
 * Any error messages are put into the FORM_ERRORS array.  If the validation
 * is a form and it passes, the form will be submitted, if it is not a form,
 * or submission is not required pass in false for the 3rd arg.
 *
 * @param String frm_id - DOM id of the containing element
 * @param String error_holder - DOM id of the element to hold error messages, 'alert' will 
 *                              show them in a javascript alert box.
 * @param Boolean is_form - tells if the first arg is the ID of a form or not
 * @param String callback - call back function to be called before the final errors are displayed
 * @return null
 */
function validateForm(frm_id, error_holder, is_form, callback)
{
	if(error_holder == undefined){ var error_holder = ''; }
	if(is_form == undefined){ var is_form = true; }
	if(callback == undefined){var callback = "";}

	//clear the errors array
	FORM_ERRORS = new Array();
	val_pass = true;
	
	
	var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

	$("#"+frm_id).find("input, textarea, select").each(function(){
		
	
		//checked test for checkboxes
		if(/req/.test($(this).attr("rel")) && $(this).attr("type") == "checkbox")
		{
			if( !$(this).is(":checked") )
			{
				$(this).next("label").css("color", "red");
				log_error($(this).next("label").text() + " must be checked", $(this).attr("id"));
			}
		}
		

		//non blank test
		if(/req/.test($(this).attr("rel")) && $(this).val() == "")
		{
			
			//handle select boxes
			if( $(this).hasClass('pretty_ddl') )
			{
				$("label[for='"+ $(this).attr("id") +"']").css("color", "red");
				log_error($("label[for='"+ $(this).attr("id") +"']").text() + " can't be blank", $(this).attr("id"));
				val_pass = false;
			}
			else
			{
				$(this).prev("label").css("color", "red");
				log_error($(this).prev("label").text() + " can't be blank", $(this).attr("id"));
				val_pass = false;
			}
		}
		else
		{
			
			//email format validation
			if(/email/.test($(this).attr("rel")))
			{
				var address = $(this).val();
				if(emailReg.test(address) == false)
				{
					val_pass = false;
					$(this).prev("label").css("color", "red");
					log_error($(this).prev("label").text() + " must be in the format a@b.co", $(this).attr("id"));
				}
				else
				{
					$(this).prev("label").css("color", "white");
				}
			
			} //end email format test

			
			//numeric test
			if(/digit/.test($(this).attr("rel")))
			{
				if( !isNumeric($(this).val()) )
				{
					//log error
					$(this).prev("label").css("color", "red");
					$digit_msg = $(this).prev("label").text() + " must be a number";
					log_error($digit_msg, $(this).attr("id"));
				}
				else
				{
					//val is ok
					$(this).prev("label").css("color", "white");
				}
			}
			
			
			//check for greater_than (>) a certain value
			if(/gt_/.test($(this).attr("rel")))
			{
				$test_val = "";
				$attr_arr = $(this).attr("rel").split(" ");
				
				for($i = 0; $i < $attr_arr.length; $i++)
				{	
					if(/gt_/.test($attr_arr[$i]))
					{
						$tmp = $attr_arr[$i].split("_");
						$test_val = $tmp[1];
					}
				}
				
				
				//now do the test
				if(Number($(this).val()) <= Number($test_val))
				{
					//log error
					$(this).prev("label").css("color", "red");
					$gte_msg = $(this).prev("label").text() + " must be greater than " + $test_val;
					log_error($gte_msg, $(this).attr("id"));
				}
				else
				{
					//val is ok
					$(this).prev("label").css("color", "white");
				}
				
			} //end greater_than test
	
			
			
			//match check for confirmation txt fields
			if(/_confirmation/.test($(this).attr("id")))
			{
				$orig_id = $(this).attr("id").replace("_confirmation", "");
				if($("#"+$orig_id).val() != $(this).val())
				{
					$(this).prev("label").css("color", "red");
					log_error($(this).prev("label").text() + " does not match", $(this).attr("id"));
				}
				else
				{
					$(this).prev("label").css("color", "white");
				}
			
			} //end confirmation test
			
		
		}// end else on non-blank test
		
		
	});
	
	if(callback != "")
	{
		callback.call();
	}
	
	if(val_pass == true)
	{
		if(is_form == true)
			document.forms[frm_id].submit();
	}
	else
	{
		if(error_holder != undefined || error_holder != '')
		{	
			if(error_holder == "alert")
			{
				$output = FORM_ERRORS.join("\n");
				if($output.replace("\n", "") != "")
					alert(FORM_ERRORS.join("\n"));
			}
			else
			{
				$output = FORM_ERRORS.join("");
				if($output != "")
					$("#"+error_holder).html(FORM_ERRORS.map(errorWrapper).join("\n"));
			}
		}
	}
	
}//end validateForm


function log_error(msg, debug_info)
{
	if(msg != "")
	{
		FORM_ERRORS.push(msg);
	}
	
	
	if(window.console)
	{
		console.log( ((debug_info != undefined)? debug_info + " - " : "") + msg )
	}
	
}//end function log_error



//check for valid numeric strings	
function isNumeric(strString)
{
   var strValidChars = "0123456789.";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}


// Date Validation and Format Javascript
// copyright 11th June 2007 by Stephen Chapman
// permission to use this Javascript on your web page is granted
// provided that all of the code in this script (including these
// comments) is used without any alteration
// you may swap the 12 and 31 around if you want mm/dd instead of dd/mm
function dtval(d,e) {

	var pK = e ? e.which : window.event.keyCode;

	if (pK == 8) 
	{
		d.value = substr(0,d.value.length-1); 
		return;
	}

	var dt = d.value;

	var da = dt.split('/');

	for (var a = 0; a < da.length; a++) 
	{
		if (da[a] != +da[a])
		{
		 	da[a] = da[a].substr(0,da[a].length-1);
		}
	}

	if (da[0] > 12) 
	{
		da[1] = da[0].substr(da[0].length-1,1);
		da[0] = '0'+da[0].substr(0,da[0].length-1);
	}

	if (da[1] > 31) 
	{
		da[2] = da[1].substr(da[1].length-1,1);
		da[1] = '0'+da[1].substr(0,da[1].length-1);
	}

	if (da[2] > 9999) 
	{
		da[1] = da[2].substr(0,da[2].length-1);
	}
	
	dt = da.join('/');
	
	if (dt.length == 2 || dt.length == 5)
	{
		dt += '/';
	}
		
	d.value = dt;

}//end function



function remoteValidate(model, form, onErrorCallback)
{
	//start by clearing any previous errors
	$(form).find("label").css("color", "#BAC6C6");
	
	
	$.ajax({
		data:$.param($(form).serializeArray()) + '&model=' + model + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/validate',
		async: false,
		complete: function(e){
			
			var jsonObj = eval(e.responseText);
			
			
			if(jsonObj.length > 0)
			{
				if($("#remote_errors").length > 0)
				{
					$("#remote_error_list ul").html("");
				}
				else
				{
					//create the holder
					$("body").append(
					'<div id="remote_errors">' + 
					'	<div id="remote_errors_container">' + 
					'		<h2>The following errors were found:</h2>' + 
					'		<div id="remote_error_list">' + 
					'			<ul></ul>' + 
					'		</div>' +
					'	</div>' +  
					'</div>' + 
					'<a href="#remote_errors" id="error_viewer">-</a>');
					
					//hide it
					$("#remote_errors").hide();
					
					//setup a fancybox on the error list actuator
					$("#error_viewer").fancybox({
						'overlayShow':true,
						'overlayOpacity': 0.8,
						'frameWidth': 300,
						'frameHeight': 200
					});
					
				}//end else
				
				
				//loop over errors
				for(var i=0; i < jsonObj.length; i++)
				{
					var field = jsonObj[i][0];
					var msg = jsonObj[i][1];

					$label = $("#" + model + "_" + field).parents(".form_row").find("label").eq(0);
					$label.css("color", "red");
					var field_name = $label.text().replace(":","");
					
					if(field_name == "")
					{
						field_name = field.replace("_id", "").replace(/_/g, " ");
					}
					
					var full_error_msg = field_name + " " + msg.replace(/_/g, " ");

					//add the errors to the UI
					$("#remote_error_list ul").append("<li>" + full_error_msg + "</li>");

				}//end for loop


				//activate the fancybox to 
				//show the errors
				$("#error_viewer").click();
				
				
				
				if(onErrorCallback != undefined)
				{
					onErrorCallback.call();
					
				}//end if onErrorCallback
				
				
			}//end if there ARE errors
			else
			{
				$(form).submit();
				
			}//end else if there are NO errors
			
			
		}//end on complete function
		
	});//end $.ajax call
	
	
}//end function remoteValidate



function editActivity()
{
	var name = $('#act_sel :selected').text();
	var units = $('#act_sel :selected').attr("rel");
	var id = $('#act_sel :selected').val();
	
	$("#activity_edit_fields").find("input[type='hidden']").val(id);
	$("#activity_edit_fields").find(".log_item_name").val(name);
	$("#activity_edit_fields").find(".log_item_units").val(units);
	
	$("#log_edit_form").attr("action", "/logs/" + id + "/update_log");
	
}//end function editActivity



function updateCaloriesBurned(select)
{
	$val = $(select).val();
	
	$.ajax({
		data:'date_spec=' + $val + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/workouts/calorie_count',
		async: true,
		complete: function(e){
			
			var resp = eval(e.responseText)[0];
			
			//update the heading
			$("#calories_burned_hdr span").html(resp.title_data);
			
			//update the chart
			updateChartXML("calories_chart",resp.chart_data);
			
			//update the tracker text
			$("#calories_burned_text").html(resp.calorie_count);
			init_single_tracker( $("#calories_burned_text") );
		}
	});
	
	
}//end function updateCaloriesBurned




function updateActivityGraph(select)
{
	$val = $(select).val();
	
	$.ajax({
		data:'log_id=' + $val + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/logs/log_data',
		async: true,
		complete: function(e){
			
			var resp = eval(e.responseText)[0];
			
			//update the chart
			updateChartXML("activity_chart",resp.chart_data);

		}
	});
	
}//end function updateActivityGraph



function updateGoalPanel(select)
{
	$val = $(select).val();
	
	$.ajax({
		data:'goal_id=' + $val + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/logs/goal_data',
		async: true,
		complete: function(e){
			
			var resp = eval(e.responseText)[0];
			
			//update the HTML
			$("#goal_logged_headline").html(resp.primary_text + " <span>" + resp.secondary_text + "</span>");
		}
	});
	
}//end updateGoalPanel


function updateRoutineTasks(select)
{
	$val = $(select).val();
	
	$.ajax({
		data:'wo_schedule_id=' + $val + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/workouts/routine_tasks',
		async: true,
		complete: function(e){
			var result = eval(e.responseText);
			var wo_schedule_id = result[0].workout_schedule_id;
			var tasks = result[0].tasks.split("|");
			
			$("a#wo_schedule_view, a#wo_schedule_edit").attr("href", "/workout_routines/"+wo_schedule_id);
			
			if(tasks.length == 1){
			
				if(tasks[0] == "")
					$("h4#wo_schedule_task_disp").html("You have no tasks for today");
				else
					$("h4#wo_schedule_task_disp").html(tasks[0]);
				
			}else if(tasks.length > 1){
				
				$("h4#wo_schedule_task_disp").html(tasks[0] + " + " + tasks.length - 1 + " other tasks");
				
			}
		}
	});
	
}//end updateRoutineTasks


function updateWorkoutsLogged(select)
{
	$val = $(select).val();
	
	$.ajax({
		data:'date_spec=' + $val + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/workouts/workout_count',
		async: true,
		complete: function(e){
			$("#workouts_logged_text").html(e.responseText);
			init_single_tracker( $("#workouts_logged_text") );
		}
	});
	
}//end function updateWorkoutsLogged


function selectWorkoutExercise(sel_list)
{
	var val = $("#add_workout_ex_list").children("option:selected").attr("id");
	if(val == "")
		val = $("#add_workout_ex_list").val();
		
	$("#selected_workout_exercise_id").val(val);
	
}//end selectWorkoutExercise


function parseWorkoutExerciseList(text_field)
{
	$val = $(text_field).val();
	
	$.ajax({
		data:'term=' + $val + '&authenticity_token=' + window._token, 
		dataType:'json', 
		type:'post', 
		url:'/workouts/search_workout_exercises',
		async: true,
		complete: function(e){
			var result = eval(e.responseText);
			var output = "";
			for(var i=0; i < result.length; i++)
			{
				var ex = result[i].exercise;
				output += '<option id="' + ex.id + '">' + ex.description + '</option>';
				
			}//end for
			
			$("#add_workout_ex_list").html(output);
			
		}//end complete
	});
	
}//end function parseWorkoutExerciseList



function submitAddWorkout()
{
	if( $("#add_workout_ex_list").val() == null )
	{
		alert("You must select a workout to add.");
	}
	else
	{
		//$("#add_workout_form").submit();
		
		$.ajax({
			data:$.param($("#add_workout_form").serializeArray()) + '&authenticity_token=' + window._token,
			dataType:'plain', 
			type:'post', 
			url:'/workouts/add_exercise_user',
			complete: function(e){
			
				$res = e.responseText;
				if( $res != '0')
				{
					$("#added_exercise").html($res);
					$("#add_workout_form").hide();
					$("#add_a_workout_success").show();
				}
				
			}//end complete
		});
	}
	
}//end validateAddWorkout



function addAnotherWorkout()
{
	$("#add_workout_ex_list").val(null);
	$("#add_workout_form").show();
	$("#add_a_workout_success").hide();
	
}//end addAnotherWorkout



//function to replace text in trackers
//with odometer images
function init_trackers()
{

	$(".tracker_odometer").each(function(){
	
		init_single_tracker( $(this) );
		
	});
	
}//end init_trackers


//function to init a single tracker instance
//used by the init_trackers method to init all
//or by functions that change tracker vals & need
//to update the UI
function init_single_tracker(jquery_obj)
{
	$num = trim(jquery_obj.text());
	jquery_obj.html("");
	
	while($num.length < 5)
		$num = "0" + $num;
	
	for(var i=0; i < 5; i++)
	{
		$x = $num.charAt(i);
		jquery_obj.append('<img src="/images/counter_' + $x + '.jpg" alt="' + $x + '"/>');
		
	}//end for
	
}//end function init_single_tracker



function setupFeedPaging()
{

	$("a.feed_paging_older, a.feed_paging_newer").each(function(){
		$(this).unbind("click");
	});
	
	$(".feed_newer_older").each(function(){
	
		$older_link = $(this).children(".feed_paging_older");
		$newer_link = $(this).children(".feed_paging_newer");
		$feed_holder = $(this).parents(".feed_holder");
		var which_feed = $(feed_actuators+"[title='"+ $feed_holder.attr("id") +"']").attr("rel");
	
		var offset = Number($(this).children(".feed_offset").text());
		var limit = Number($(this).children(".feed_limit").text());
		var item_count = Number($(this).children(".feed_item_count").text());
		
	
		$older_link.click(function(e){
			e.preventDefault();
		
			if(item_count == limit)
			{
				var new_offset = offset + limit;
			
				$.ajax({
					type: "GET",
				   	url: window._base_url + 'feed/render_feed/'+which_feed + '?offset=' + new_offset,
				   	async: false,
				   	data: "",
					dataType: "text",
				   	success: function(data){
						$feed_holder.fadeOut("slow", function(){
							$feed_holder.html(data);
						
							setupFeedCommenting();
							setupFeedPaging();
						
							if(item_count < limit)
								$older_link.css("color", "#777");
							
							$feed_holder.fadeIn();
						});
				   	},
				   	error: function(xmlHttpRequest, txtStatus, error){
						alert("ERROR");
				   	}
				});
			
			}//end if
			else
			{
				//alert("count: " + item_count + " - limit: " + limit);
				if(item_count < limit)
					$(this).css("color", "#777");
			}
		
		}); //end older click

	
		if(offset == 0){
			$newer_link.css("color", "#777");
		}
		
		if(item_count < limit){
			$older_link.css("color", "#777");
		}
	
		$newer_link.click(function(e){
			e.preventDefault();
		
			if(offset > 0)
			{
				var new_offset = offset - limit;
				if(new_offset < 0){
					new_offset = 0;
				}
			
				$.ajax({
					type: "GET",
				   	url: window._base_url + 'feed/render_feed/'+which_feed + '?offset=' + new_offset,
				   	async: false,
				   	data: "",
					dataType: "text",
				   	success: function(data){
						$feed_holder.fadeOut("slow", function(){
							$feed_holder.html(data);
						
							setupFeedCommenting();
							setupFeedPaging();
						
							if(offset == 0)
								$newer_link.css("color", "#777");
							
							$feed_holder.fadeIn();
						});
				   	},
				   	error: function(xmlHttpRequest, txtStatus, error){
						alert("ERROR");
				   	}
				});
			
			}//end if

		}); //end newer click
		
	}); //end each
	
	
}//end function setupFeedPaging



function renderFeed(which_feed, onComplete, offset)
{
	
	$.ajax({
		type: "GET",
	   	url: window._base_url + 'feed/render_feed/'+which_feed,
	   	async: false,
	   	data: "",
		dataType: "text",
	   	success: function(data){
	    	onComplete.call(this, data);
	   	},
	   	error: function(xmlHttpRequest, txtStatus, error){
			onComplete.call(this, "ERROR");
	   	}
	});
	

}//end renderFeed




function setupFlashMessage()
{
	if( $("#flash_message").length > 0 )
	{
		var t = setTimeout('$("#flash_message").slideUp(1000);', 4000);
		
	}//end if
	
}//end function setupFlashMessage



function setupFeedCommenting()
{
	//setup existing forms
	setupFeedCommentForms();
	
	$("a.add_feed_comment").unbind("click");
	$("a.add_feed_comment").click(function(e){
		e.preventDefault();
		
		$feed_item = $(this).parents(".feed_item");
		var feed_item_id = $feed_item.attr("id").replace(/feed_item_/, "");
		
		var new_comment_form  = getFeedCommentForm(feed_item_id);
				
		$feed_item.append('<div class="clear"></div>' + new_comment_form);
	
		$comment_box = $("#feed_item_comment_box_"+feed_item_id);

		setupFeedCommentForms();
		
		$comment_box.focus();
		
	});//end click
	
}//end setupFeedCommenting



function setupFeedCommentForms()
{
	
	$(".feed_item").each(function(){
		
		var feed_item_id_attr = $(this).attr("id");
		
		if( $(this).find("form").length > 0 )
		{
			$comment_form = $(this).find("form");
			var comment_form_id = $comment_form.attr("id");
		}
		else
		{
			return;
		}
		
		$comment_form.unbind("submit");
		$comment_form.submit(function(e){
			return false;
		});

		$feed_item = $(this);
		var feed_item_id = $feed_item.attr("id").replace(/feed_item_/, "")
		var new_comment_form  = getFeedCommentForm(feed_item_id);
	
		$comment_field = $("#feed_item_comment_box_"+feed_item_id);

		$comment_field.unbind("focus");
		$comment_field.unbind("keyup");
		$comment_field.focus(function(){
			$(this).val("");
		});
		
		$comment_field.keyup(function(e){
			e.preventDefault();
			
			//enter key
			if(e.keyCode == 13) 
			{

				$.ajax({
					type: "POST",
				   	url: window._base_url + 'feed/add_feed_comment',
				   	async: true,
				   	data: $("#"+comment_form_id).serialize(),
					dataType: "html",
					beforeSend: function(xhr){
						
					},
				   	success: function(data){
						$fe = $("#"+feed_item_id_attr);
						$fe.effect("highlight", {}, 1000);
						$fe.find(".comment").remove();
						$fe.find("div.clear").remove();
						$fe.find("form").remove();
						$fe.append(data);
						$fe.append(new_comment_form);
						setupFeedCommentForms();
				   	},
				   	error: function(xmlHttpRequest, txtStatus, error){
						alert("Error saving comment");
				   	}
				});

			}

		});//end key up
		
	});//end each feed_item_comment form
	
}//end function setupFeedCommentForms


function getFeedCommentForm(feed_item_id)
{
	var new_comment_form  = '<form action="#" id="feed_item_comment_form_'+ feed_item_id +'">';
	new_comment_form 	 	+= '<div class="new_comment">';
	new_comment_form 			+=	'<input type="text" id="feed_item_comment_box_'+feed_item_id+'" name="feed_item_comment[comment]" class="new_comment_field" value="Write a comment..." />';
	new_comment_form 			+=	'<input type="hidden" name="feed_item_comment[feed_item_id]" value="'+ feed_item_id +'" />';
	new_comment_form 			+=	'<input type="hidden" name="feed_item_comment[user_id]" value="'+ window._cuid +'" />';
	new_comment_form 			+= 	'<input type="hidden" name="authenticity_token" value="'+window._token+'" />';
	new_comment_form 		+= '</div>';
	new_comment_form     += '</form>';
	
	return new_comment_form;
	
}//end getFeedCommentForm