// vJustify plugin
//

jQuery.fn.vjustify=function() {
    var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        $(this).height(maxHeight + "px");
        if (this.offsetHeight>maxHeight) {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
        }
    });
};

function prepProgress(formData, jqForm, options) {
 	if ($('#export_results').css('display') == 'block'){
		$('#export_results').slideUp('normal');
	}
	$('#gobutton').hide();	
	$('#spinner').show();
}

function resetResultsField (response) {
 	if ($('#export_results').css('display') == 'block'){
		$('#export_results').slideUp('normal');
		$('#export_results').empty();
	}
	$('#spinner').hide();
	$('#gobutton').show();
	$('#export_results').slideDown('normal');
}
/**
 * Get the position of the currently selected tab (no zero-based index).
 *
 * @example $('#container').activeTab();
 * @desc Get the position of the currently selected tab of an interface
 * contained in <div id="container">.
 *
 * @type Number
 *
 * @name activeTab
 * @cat Plugins/Tabs
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

$.fn.activeTab = function() {
    var selectedTabs = [];
    this.each(function() {
        var nav = $('ul.tabs-nav' , this);
        nav = nav.size() && nav || $('>ul:eq(0)', this); //fallback to default structure
        var lis = $('li', nav);
        selectedTabs.push(lis.index( lis.filter('.tabs-selected')[0] ) + 1);
    });
    return selectedTabs[0];
};


// checkboxes
/*
 * Toggle all checkboxes contained within a form
 *
 * @name     toggleCheckboxes
 * @param    filter   only toggle checkboxes matching this expression
 * @param    returnChecked   return checkboxes as jQuery object, default false
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $("#myform").toggleCheckboxes();
 * @example  $("#myform").toggleCheckboxes(".onlyme");
 * @example  $("#myform").toggleCheckboxes(":not(.notme)");
 * @example  $("#myform").toggleCheckboxes("*", true);
 *
 */
jQuery.fn.toggleCheckboxes = function(filter, returnChecked)
{
	filter = filter || "*";
	returnChecked = returnChecked || false;
	var returnWhat = jQuery([]);
	this.each(
		function()
		{
			var checked = jQuery("input[@type=checkbox]", this).filter(filter).each(
				function()
				{
					this.checked = !this.checked;
				}
			).filter(":checked");
			returnWhat = checked;
		}
	)
	if(!returnChecked)
	{
		returnWhat = this;
	}
	return returnWhat;
}





// check box swap
jQuery.fn.checkbox = function (opt) {
jQuery("input[@type='checkbox']", this).hide().each( function () {
	
		jQuery("<img>")
			.src( this.checked ? opt.checked : opt.unchecked )
			.click( function() {
				var check = jQuery(this).next()[0].checked == true;
				jQuery(this)
					.src( check ? opt.unchecked : opt.checked )
					.next()[0].checked = !check;
			})
			.insertBefore(this);
	});
}

function publishOptions(section) {

	if (section == 'news') {
		$('#queue_select').show();
		$('#groupblog_select').hide();	
		//$('#userblog_select').hide();
		if ($('#front_page_select').length) {
			$('#front_page_select').show();
		}
		$('#publish_fp').click(function() {
			// pass through to DOM for crir
			this.click();
		});
		$('#publish_userblog').click();
	} else if (section == 'user') {
		$('#queue_select').hide();
		$('#groupblog_select').hide();
		$('#userblog_select').show();
		$('#publish_userblog').click(function() {
			// pass through to DOM for crir
			this.click();
		});
		$('#publish_userblog').click();
	} else if (section == 'group') {
		$('#queue_select').hide();
		$('#userblog_select').hide();
		$('#groupblog_select').show();
		$('#publish_groupblog').click(function() {
			// pass through to DOM for crir
			this.click();
		});
		$('#publish_groupblog').click();
	}
	
	$('#publish_selector').data("mode", section);
	return;

}

function applyProfilePicOp() {
	$('.profile_choose').click(function() {
		$('.profile_chosen').removeClass("profile_chosen");
		var imgVal = $(this).children("img").attr("src");
		$(this).parent("div.profile_pic_op").addClass("profile_chosen");
		$('#user_img_value').attr("value", imgVal);
		return false;
	});
}

$(document).ready(function () {

	$('.profile_choose').click(function() {
		$('.profile_chosen').removeClass("profile_chosen");
		var imgVal = $(this).children("img").attr("src");
		$(this).parent("div.profile_pic_op").addClass("profile_chosen");
		$('#user_img_value').attr("value", imgVal);
		return false;
	});
	
	$('form').submit(function(){
		labels_uninit();
	});
	
	$('#main_picture').hover(
		function() {
			$(this).children(".edit_link").slideDown("normal");
		},
		function() {
			$(this).children(".edit_link").slideUp("normal");
		}
	);
	
	
	$('li.gallery_img').click( function() {
		var file = $(this).children("#file").html();
		var caption = $(this).children("#caption_txt").html();
		var nick = $(this).children("#nick").html();
		var id = $(this).children("#id").html();
		var edit = $(this).children("#edit_link").html();

		$('#main_picture').fadeOut("normal", function() {
			$('#throb').fadeIn("normal", function() {
				$('#main_picture').append(
					'<div id="imagetest" style="display: block; position: absolute; left: -10000px;"><img src="'+file+'" style="display: block;"/></div>'
				);
	
				$("#imagetest > img").load(function() {
					$('#imagetest').remove();
			
					$('#main_picture img#thisone').attr("src").empty;
					$('#main_picture p.caption_txt').empty;
				
					$('#main_picture #pic_link').attr('href', file);
					$('#main_picture img#thisone').attr("src", file);
					$('#main_picture img#thisone').attr("alt", caption);
					$('#main_picture p.caption_txt').html(caption);
					$('#main_picture .edit_link').remove();
					$('#main_picture').prepend(edit);
					
					$('#throb').fadeOut("normal", function() {
						$('#main_picture').fadeIn("normal");
					});
				});
			});
		});
		return false;
	});
	

	/* set the date format for picker */
	Date.format = 'mm-dd-yyyy';

	/* Saved searches */
	$('.date-pick').datePicker({
		displayClose:true,
		startDate:'06-01-2008',
		renderCallback:function($td, thisDate, month, year)
				{
					if (thisDate.getDayName() != 'Monday') {
						$td.addClass('disabled');
					}
				}
	});
    $('#saved_searches').submit(function(e) { 
    	$('#submitbutton').hide();
       	$('#working').show();
 	
    	var searchChoice = $('select[@name=search]').val();
    	if (searchChoice.substr(0, 4) != 'box:') {
   		  	if ($('#morefields').css('display') == 'block') {
   		  	  $('#morefields').slideUp('normal');
   		      $('#morefields').empty();
   		    }
   		  	$('#morefields').append("<p><b>Finding users...</b> this may take a moment.</p>");
   		  	$('#morefields').slideDown('normal');
    		return;
    	}

		// Block submit for a moment, to see if we need more.
    	e.preventDefault();
		var allArgs = $('#saved_searches').formSerialize();

    	//See if we need more form data from this box
    	$.ajax({
    		type: "Post",
    		url: "/savedsearch",
    		data: allArgs,
    		dataType: "html",
    		success: function(ret){
    		  if (ret == '') {
		   		$('#saved_searches').submit();
    		  	if ($('#morefields').css('display') == 'block') {
    		  	  $('#morefields').slideUp('normal', function() {
	      		      $('#morefields').empty();
	    		    }
	    		   );
	    		}
    		  	$('#morefields').append("<p><b>Finding users...</b> this may take a moment.</p>");
    		  	$('#morefields').slideDown('normal', function() {
					return true;
    		  	});
    		  }
    	  
    		  // otherwise, add more fields to the page
    		  if ($('#morefields').css('display') == 'block') {
    		  	  $('#morefields').slideUp('normal', function() {
	      		      $('#morefields').empty();
	    		    });
    		  }
			  $('#morefields').append(ret);
			  
    		  $('#morefields').slideDown('normal', function() {
	    		  $('#working').hide();    	
	    		  $('#submitbutton').show();
	    	  
	    	 	  $('.date-pick').datePicker({
					displayClose:true,
					startDate:'06-01-2008',
					renderCallback:function($td, thisDate, month, year)
							{
								if (thisDate.getDayName() != 'Monday') {
									$td.addClass('disabled');
								}
							}
				  }); //activate the date selector
			  	 labels_init();
    		  	 return false;
    		});

    	}
    });	
	
	});
    var expOptions = { 
    	target:        '#export_results', 
    	beforeSubmit:  prepProgress,
    	success:       resetResultsField
    };
    
    $('#export_format').submit(function() { 
		$(this).ajaxSubmit(expOptions);     
		return false; 
    }); 

	/* FP billboard switcher */
	var fadeReset = $('#home_feature').html();
	
	$('#fade').innerfade({timeout: "6000", containerheight: "303", speed: "slow", tracker: "feature_menu", trackerclass: "feature-selected", start: "1"});
	
	$('#stop').click(function(){
		clearTimeout($('#fade').data('timer'));
		$('#fade').removeData('timer');
		$('#stop').hide();
		$('#start').show();
		return false;
	});
	

	$('#start').click(function(){
		$('#start').hide();
		$('#stop').show();
		$('.feature-select').removeClass('feature-selected');
		$('#1').addClass('feature-selected');
		$('#fade').innerfade({timeout: 3000, containerheight: 303, speed: 'slow', tracker: 'feature_menu', trackerclass: 'feature-selected'});
		return false;
	});

	$('.feature-select').click(function(){
		if (this.id == 'stop' || this.id == 'start') {
			return;
		}
		
		if($('#fade').data('timer')) {
			clearTimeout($('#fade').data('timer'));
			$('#fade').removeData('timer');
			$('#stop').hide();
			$('#start').show();
		}
		
		var id = this.id;
		$('.feature-select').removeClass('feature-selected');
		$(this).addClass('feature-selected');
		$('#fade li:visible').fadeOut(1000);
		$('#bb_'+id).fadeIn(1000);
		return false;
	}); 
	
	/* Story publish options */

	$('#editstory_form').submit(function(event){
		myForm = this;
		$('input:radio[@name=section]', myForm).each(function() {
			if (this.checked) {
				if ($(this).val() == 'group_blog') {
					var oneChecked = false;
					$('input:checkbox[@name=story_group]', myForm).each(function() {
						if (this.checked) {
							oneChecked = true;
						}
					});
					if (oneChecked) { return true; }
					else {
						alert("Error: You must select at least one group forum, or choose the Main Forum or your Diary");
						event.preventDefault();
						return false;
					}
				}
			}
		});
		return true;
	});
	
	
	$('#section_selector label').click(function(){
		if ( $(this).is('#group_select') ) {
			/*if ($('#section_select_list').is(':visible')) {
				$('#section_select_list').slideUp("normal");
			}*/
			if ($('#group_select_list').is(':hidden')) {
				$('#group_select_list').slideDown("normal");
			}
			
			if ($('#publish_all').length) {
				publishOptions('user');
			}
		} else {
			if ($('#group_select_list').is(':visible')) {
				$('#group_select_list').slideUp("normal");
			}
			
			if ($(this).is('#diary_select')) {
				/*if ($('#section_select_list').is(':visible')) {
					$('#section_select_list').slideUp("normal");
				}*/
				if ($('#publish_all').length) {
					publishOptions('user');	
				}
			} else {
				if ($(this).is('#main_forum_section')) {
					/*if ($('#section_select_list').is(':hidden')) {
						$('#section_select_list').slideDown("normal");
					}*/
					if ($('#publish_all').length) {
							publishOptions('user');
					}
				}
			}
		}
	});
	$('#preview').after(' <INPUT TYPE="button" NAME="edit" VALUE="Edit" class="inputButton" id="edit">');

        
        $('#edit').click(function () {
            $('#editStoryTabs').triggerTab(1);   
        });        
       
        
        $('#editStoryTabs').tabs({
        	onClick: function() {
                var tabClicked = arguments[1];
                if (tabClicked.id.indexOf("submit_story_preview") >= 0) {
            		$('#preview').click();
                    return false;
				}
			},
            onShow: function() {
                var tabClicked = arguments[1];
                if (tabClicked.id.indexOf("submit_story_preview") >= 0) {
                    $('#preview').hide(); 
                    $('#edit').show();
                } else {
                    $('#edit').hide();
                    $('#preview').show(); 
                }
            }
        });
        
        
        
        
	$('#loginBox').tabs();
    $('#intloginBox').tabs();
    $('#pluginLoginBox').tabs({on: 2});
	$('#diaryBox').tabs();
	$('#eventsBox').tabs();
	$('#searchAll').tabs();
	$('#userPrefTabs').tabs({remote: true, loadingClass: 'progress', onShow: function() { applyProfilePicOp(); }});

	$('#menu_show_link').click(function(){
	  $('#user_menu_menu').slideToggle("normal");
	  $('#menu_show').hide();
	  $('#menu_hide').show();
	  return false;
	});
	$('#menu_hide_link').click(function(){
	  $('#user_menu_menu').slideToggle("normal");
	  $('#menu_hide').hide();
	  $('#menu_show').show();
	  return false;
	});
	$('#blog_menu_show_link').click(function(){
	  $('#blog_menu_menu').slideToggle("normal");
	  $('#blog_menu_show').hide();
	  $('#blog_menu_hide').show();
	  return false;
	});
	$('#blog_menu_hide_link').click(function(){
	  $('#blog_menu_menu').slideToggle("normal");
	  $('#blog_menu_hide').hide();
	  $('#blog_menu_show').show();
	  return false;
	});
	$('#group_points_toggle').click(function(){
	  $('#group_points').slideToggle("normal");
	 return false;
	});
	$('#group_points_toggle_label').click(function(){
	  $('#group_points').slideToggle("normal");
	 return false;
	});
	$('#view_admin_tools_link').click(function(){
	  $('#scoop_admin_form').slideToggle("normal");
	  $('#show_admin_tools').hide();
	  $('#hide_admin_tools').show();
	  return false;
	});
	$('#hide_admin_tools_link').click(function(){
	  $('#scoop_admin_form').slideToggle("normal");
	  $('#hide_admin_tools').hide();
	  $('#show_admin_tools').show();
	  return false;
	});
	
	/* hide/show preview/edit buttons upon initial page load */
	//alert("active tab is " + );
	if ($('#editStoryTabs').activeTab() == 1) {
	    $('#edit').hide();
	} else if ($('#editStoryTabs').activeTab() == 7) {
	    $('#edit').show();
	    $('#preview').hide();
        }

    /* code for private messaging interface */
	// to balance heights of #column_main and #column_right
	$(".jqColumn").vjustify(); 

	// apply fade trick to all messages
	// $("#messageCenter").find("tr").not(".action_bar").not(".column_heads").bind("mouseover",addFade);
	// $(".message").bind("mouseout",addFade);

	// $("#myform").checkbox({checked: "images/checked.gif", unchecked: "images/unchecked.gif"});

	$("div.message").click(function(event){
	  event.stopPropagation();
	  if( this.className.match(/(^|\s)openMessage(\s|$)/) ) {
    	$(this).find(".messageExpand").slideUp("slow");
     	$(this).find(".messageRecipsExpand").slideUp("slow");
   		$(this).removeClass("openMessage");		
    	//$(this).addClass("newMessage");	
		$(this).find(".messages_readless").hide();
		$(this).find(".messages_readmore").show();
	  	return false;
	  } else {
		$(this).find(".messageExpand").slideDown("slow");
		$(this).find(".messageRecipsExpand").slideDown("slow");
    	$(this).removeClass("newMessage");		
    	$(this).addClass("openMessage");	
		$(this).find(".messages_readmore").hide();
		$(this).find(".messages_readless").show();
		
		// Mark as read
		var myNick = $("#nick").val();
		var msgID = $(this).attr("id");
		$.get("/messages_read", {nick: myNick, message_id: msgID, read: "read"},
			function() { return false; });
		
	  	return false;
	  }
	  return false;
	});


	$("#messageCenterForm .masterCheckBox").click(function(){ $("#messageCenterForm").toggleCheckboxes(); });
	$("#sentMessageForm .masterCheckBox").click(function(){ $("#sentMessageForm").toggleCheckboxes(); });

	$(".checkbox").click(function(event){  event.stopPropagation( ); });
	$("span.sender_info > a").click(function(event){  event.stopPropagation( ); });
	
	// $(".composeDown").click(function(){ $("#composePane:hidden").slideDown("slow"); });
	$(".composeUp").click(function(){ 
		$("#composePane:visible").slideUp("slow"); 
    	$("#composeOpen").removeClass("hideMe");
		$("#composeClose").addClass("hideMe");
  		return false;
	});



	$("#composeOpen > a").click(function(){ 
    	$("#composePane:hidden").slideDown("slow");
    	$("#composeOpen").addClass("hideMe");
    	$("#composeClose").removeClass("hideMe");
    	return false;
	});

	$("#composeClose > a").click(function(){ 
    	$("#composePane:visible").slideUp("slow");
    	$("#composeOpen").removeClass("hideMe");
		  $("#composeClose").addClass("hideMe");
	  return false;
			});

	$("#contactsOpen > a").click(function(){ 
    	$("#contactsPane:hidden").slideDown("slow");
    	$("#contactsOpen").addClass("hideMe");
		  $("#contactsClose").removeClass("hideMe");
	  return false;
			});

	$("#contactsClose > a").click(function(){ 
    	$("#contactsPane:visible").slideUp("slow");
    	$("#contactsOpen").removeClass("hideMe");
		  $("#contactsClose").addClass("hideMe");
	  return false;
			});		

	/*Recips = new Object();

	// init with any existing recips
	var currentRecips = new Array();

	if ($("#ComposeRecipient").val()) {
		currentRecips = $("#ComposeRecipient").val().split(", ");
		for (keyVar in currentRecips) {
			Recips[currentRecips[keyVar]] = 1;
		}
	} */

	$("#contactsPane > ul > li").click(function(){
		var nick = this.id;
		
		var currentRecips = new Array();
		var Recips = new Object();
		if ($("#ComposeRecipient").val()) {
			currentRecips = $("#ComposeRecipient").val().split(", ");
			for (keyVar in currentRecips) {
				Recips[currentRecips[keyVar]] = 1;
			}
		}
		
		
		if (Recips[nick] == 1) {
			return false;
		}

		var current = $("#ComposeRecipient").val();
		if (current) { current = current + ', '; }
		$("#ComposeRecipient").val(current + nick);

		Recips[nick] = 1;
		return false;
	});

	// $(".replyLink").click(function(){
	//    $(this).append
	// $.ajax({type: "GET", url: "reply.html", dataType: "html" })

	$("#menuShow").click(function(){ $("#userMenuMenu:hidden").slideDown("slow");   return false;});
	$("#menuHide").click(function(){ $("#userMenuMenu:visible").slideUp("slow");   return false;});

	$("#menu_show").click(function(){ $("#user_menu_menu:hidden").slideDown("slow");   return false;});
	$("#menu_hide").click(function(){ $("#user_menu_menu:visible").slideUp("slow");   return false;});

	$("a.showInbox").click(function(){ 
		$("#sentMessages").fadeOut("normal", function(){ $("#receivedMessages").fadeIn("normal"); });
		return false; 
	});
	$("strong.showInbox").click(function(){ 
		$("#sentMessages").fadeOut("normal", function(){ $("#receivedMessages").fadeIn("normal"); });
		return false; 
	});

	$("a.showSent").click(function(){ 
		$("#receivedMessages").fadeOut("normal", function(){ $("#sentMessages").fadeIn("normal"); }); 
		return false; 
	});
	$("strong.showSent").click(function(){ 
		$("#receivedMessages").fadeOut("normal", function(){ $("#sentMessages").fadeIn("normal"); }); 
		return false; 
	});

	$("a.deleteLink").click(function(event){
		event.stopPropagation();
		return;
	});

	$("a.replyLink").click(function(){
		var myNick = $("#nick").val();
		var msgID = $(this).parents(".message").attr("id");
		/*console.log(msgID);*/

		$("#replyLink_"+msgID).hide();
		$("#spinner_"+msgID).show();

		
		$.get("/messages_embed", { reply: "1", nick: myNick, message_id: msgID},
			function(data){
					$("div.cell_"+msgID).fadeOut("slow");
					$("#"+msgID).before(data);
					$("div#reply_"+msgID).fadeIn("slow");

					/* set the handler for the new cancel button */
					$("#reply_"+msgID).activateReplyCancel();

					// messaging reply ajax handler
					function reportReply (msgID, msgReplyID) {
						$("div#reply_"+msgID).fadeOut("slow");
						$("#"+msgReplyID).remove();
						$("div.cell_"+msgID).fadeIn("slow");

						return false;
					}

			}
		);

		return false;
	});


	$("a.replyCancelLink").click(function(){
		var msgReplyID = $(this).parents(".message").attr("id");
		var msgID = msgReplyID.substr(6);

		$("#"+msgReplyID).fadeOut("normal", function(){ 
			$("#spinner_"+msgID).hide();
			$("#replyLink_"+msgID).show();
			$("#"+msgReplyID).remove();
			$("#"+msgID).fadeIn("normal");
		});
	
		return false;
	});


	$("#messageCenterForm .action_drop").change(function(){
		$("#messageCenterForm").submit();
		return;	
	});
	
	$("#sentMessageForm .action_drop").change(function(){
		$("#sentMessageForm").submit();
		return;	
	});
	
	/* end messaging code */

	//var nick = $("#nick").val();
	//alert("nick is "+nick);

	$('#captcha_reload').click(function(){
		$('#captcha').fadeOut("normal");

		$.get('/reload_captcha', function(response){
			setTimeout("finishAjax('captcha', '"+escape(response)+"')", 800);
	    });
    
	  	return false;
	});

	// Event submit chapter search
	$('#ajax_activity').hide();	
	$('#find_calendars').blur(function () { fetchGroups(); return false; });
	$('#zip_find_link').click(function () { fetchGroups(); $('#find_calendars')[0].blur(); return false; });
	
	$('#find_calendars').bind("keypress", function(e) {
		var code=e.charCode || e.keyCode;
		if (code==13) { fetchGroups(); $('#find_calendars')[0].blur(); return false;}
	});
	$('#proximity').change(function () { fetchGroups(); return false; });

	/* Start the new message listener. */
	if ($("#nick").val()) {
	  var t = setInterval("checkForNew(10)", 10000);
	}

});

// Utility functions for event submit chapter search
var oldZip;
var oldProx
function fetchGroups() {
	if (oldZip == $('#find_calendars').val() && oldProx == $('#proximity').val()) {
		return false;
	}

	if ($('#find_calendars').val() == '') {
		return false;
	}
                
	
	oldZip = $('#find_calendars').val();
	oldProx = $('#proximity').val();
	
	$('#zip_find').hide();
	$('#ajax_activity').show();
	$.post('/embed_group_search', {
		zip: $('#find_calendars').val(),
		proximity: $('#proximity').val()
	}, function(response){
		if ($('#ajax_results').css('display') == 'block'){
			$('#ajax_results').fadeOut('normal');
		}
		setTimeout("finishAjax('ajax_results', '"+escape(response)+"')", 600);  
		$('#ajax_activity').hide();
  		$('#zip_find').show();
	});
}

jQuery.fn.activateReplyCancel = function () {
	jQuery(".replyCancel").bind("click", function(){
		var msgReplyID = jQuery(this).parents(".message").attr("id");
		var msgID = msgReplyID.substr(6);

		jQuery("div#reply_"+msgID).fadeOut("normal");
		jQuery("#"+msgReplyID).remove();
		jQuery("#spinner_"+msgID).hide();
		jQuery("#replyLink_"+msgID).show();
		jQuery("div.cell_"+msgID).fadeIn("normal");
    
		return false;
	});
}

var incomingCount = 1;

function checkForNew(timeout) {
  var myNick = jQuery("#nick").val();
  jQuery.get("/messages_embed", { since: timeout, nick: myNick, check: "received" },
  	function(data) {
		if (data) {
			//console.log(data);
			jQuery("#incomingMessages_"+incomingCount).prepend(data);
			jQuery("#incomingMessages_"+incomingCount).OpenVertically(1000);
			jQuery("#incomingMessages_"+incomingCount).Pulsate(175,4);
			
			/* apply the link behaviors to new html */		

			jQuery("a.replyLink").click(function(event){
				//console.log(this);
	            event.stopPropagation();
				var myNick = $("#nick").val();
				var msgID = $(this).parents(".message").attr("id");
				//console.log(msgID);

				$("#replyLink_"+msgID).hide();
				$("#spinner_"+msgID).show();

				
				$.get("/messages_embed", { reply: "1", nick: myNick, message_id: msgID},
    				function(data){
      						$("#"+msgID).before(data);
							$("div.cell_"+msgID).fadeOut("slow");
							$("div#reply_"+msgID).fadeIn("slow");
							$("#spinner_"+msgID).hide();
							$("#replyLink_"+msgID).show();

							/* set the handler for the new cancel button */
							$("#reply_"+msgID).activateReplyCancel();

							// messaging reply ajax handler
							function reportReply (msgID, msgReplyID) {
								$("div#reply_"+msgID).fadeOut("slow");
								$("#"+msgReplyID).remove();
								$("div.cell_"+msgID).fadeIn("slow");

								return false;
							}

					}
				);

    			return false;
			});


			jQuery("a.replyCancelLink").click(function(){
				var msgReplyID = $(this).parents(".message").attr("id");
				var msgID = msgReplyID.substr(6);

				$("#"+msgReplyID).slideUp("normal", function(){ 
					$("#"+msgReplyID).fadeOut();
					$("#"+msgReplyID).remove();
					$("#"+msgID).fadeIn("normal");
				});

				return false;
			});

			jQuery("#incomingMessages_"+incomingCount+" > div.message").click(function(event){
			  event.stopPropagation();
			  if( this.className.match(/(^|\s)openMessage(\s|$)/) ) {

    			$(this).find(".messageExpand").slideUp("slow");
    			$(this).removeClass("openMessage");		
    			//$(this).addClass("newMessage");	
				$(this).find(".messages_readless").hide();
				$(this).find(".messages_readmore").show();
				return false;
			  } else {
				$(this).find(".messageExpand").slideDown("slow");
    			$(this).removeClass("newMessage");		
    			$(this).addClass("openMessage");	
				$(this).find(".messages_readmore").hide();
				$(this).find(".messages_readless").show();
		
				// Mark as read
				var myNick = $("#nick").val();
				var msgID = $(this).attr("id");
				$.get("/messages_read", {nick: myNick, message_id: msgID, read: "read"},
					function() { return false; });
								
				return false;
			  }
			  return false;
			});

			$(".checkbox").click(function(event){  event.stopPropagation( ); });
			$("span.sender_info > a").click(function(event){  event.stopPropagation( ); });


			// done updating behaviors
			// now we need to shift the empty incoming up a notch
			var newIncomingCount = (incomingCount + 1);
			$("#incomingMessages_"+incomingCount).before('<div id="incomingMessages_'+newIncomingCount+'" class="newest" style="display: none;"></div>');
			$("#incomingMessages_"+incomingCount).removeClass("newest");
			incomingCount = newIncomingCount;
		}
		//return false;
	});
  //return false;
}	

// Display an ajax result nicely
function finishAjax(id, response) {
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn('normal');
} //finishAjax

