$(document).ready(function() {
		
		//set some stuff up
		// .message-index-page == message listing page  so the next line is only applicable when these are loaded directly onto that page via the ajax version
		//$('.messages-index-page .compose, .messages-index-page .contact-list, .messages-index-page #message').hide().closer();	//closer attaches a close button
		//$('.message-type').hide();

		//autocomplete for message's to field
		recipientAutocomplete();
		
		// result handler for message to autocomplete
		recipientAutocompleteResult();

		// bulk actions other than delete require js so let's only show the buttons if js is on.
		addBulkButtons();
		
		
		//listen for stuff
		$("body").click(function(event) {

			var $target = $(event.target);

			if ($target.is('.disabled')) return;
		
			//show messages when the tr is clicked
			if($target.is('.message-list tbody td')){
				if ($target.is(".message-select, .height-hack td")){return false;} //not the check boxes
				var theLink = $target.parent("tr").find(".message-subject a").attr("href");
				window.location = theLink;
				
				//showMessage()
			}
			
			/* turn off the default action on the button 
			// needed for dropdown version
			if ($target.is('.message-compose')) {
				return false;
			}
			*/


			// message type drop down (message/po)
			//if($target.is('ul.message-type a')){
			if($target.is('.compose-toggle a')){	
				composeMessage($target);
				
				return false;
			}
			

	
			// contact list toggle can be on the main stage or in a message
			if($target.is('.contact-list-toggle')){	
				//contactList()	

				//messy but just in case.
				$('#contact-list').remove(); 
				
				//set the stage
				if($('.main').length){
					$('.main').prepend('<div id="contact-list" class="contact-list"></div>');
				} else{
					$('#primary').prepend('<div id="contact-list" class="contact-list"></div>');
				}	

				$('#contact-list').html(FH.loader);

				
				// what are we looking at here?
				var theContactUrl = $target.attr("href");
				theContactUrl = theContactUrl + " div.contact-list";
				
				// load it and run some init stuff				
				$("#contact-list").load(theContactUrl, function(){
					$(this).closer('remove');		
				});
				
				return false;
			}		

			
			if ($target.is('.contact-remove')) {
				var contactName = $target.parents('.contact').find('.name').text();
				var message = "Are you sure you want to remove "+ contactName +" from your contact list?";
				confirmIt(message, contactRemove, $target);
				return false;
			};
			
			
			// from the contact list into the message, if it's there.
			if ($target.is('.contact-actions .contact-send')) {
				
				// human readable version
				var recipient = $target.parents('.contact').find('.name').text();
				recipient = recipient + ' - ' + $target.parents('.contact').find('.org-name').text();
				
				// machine readable id to pass. grabbed from an id name of "contact-XX"
				var contactID = $target.parents('.contact').attr('id');
				contactID = contactID.slice(8); //
				
			
				// normally links directly to /messages/compose. if there's already a message though, we wanna stay right here. cozy.
				if ($('#MessageRecipientName').length) 
				{
					$('#MessageRecipientName').val(recipient);
					$('#MessageRecipientId').val(contactID);
					$('#contact-list').remove();
					$('#MessageSubject').focus();
					return false;
				} else{
					return true;
					//composeMessage()
					//return false;
				};
			};
			
			//var aaaction = $('#messages-form').attr("action");	
			//$('h1').text(aaaction);
			
			// main list of message form normally resolves to /messages/delete. 
			// if the archive button is clicked, let's archive.
			if($target.is('#bulk-archive')){
				if ($('body').is('.auto-login')) return;
				$('#messages-form').attr({action: "/messages/archive"});
				
				//var hi = $('#messages-form').attr("action");	
				//$('h1').text(hi);
				//return false;				
			};
			
			//currently tied to the body class on the Deleted Messages page. hi fragile, how are you?
			if ($target.is('.Deleted-page #bulk-delete')) {
				confirmIt('This will permanantly remove these messages from Foodhub. Are you sure?', submitBulkForm);
				return false;
			};

			return true;
			
		});//listener

		//list togglers
		$('.message-select-all').toggle(
			function(){
				$('.message-list input').attr("checked", "checked");
				$(this).text("Unselect all");
			},
			function(){
				$('.message-list input').removeAttr("checked");	
				$(this).text("Select all");
			}	
		);
		
		// IE6 and IE7 can't handle two buttons on the same form. JS trickery to fix it.'
		if(snuff == "ie ie6" || snuff == "ie ie7" ){	
			$('#MessageComposeForm button').click(function(){
				var $this = $(this),
					action = $this.find('span').text();
				$('#MessageComposeForm button').not($this).attr("disabled", "disabled");
				//return false;
			});
		}

/*
		$('#messages-form').bind("submit", function(e){
			//ajax version
			//var clicked = $(this).attr("rel")

			var clicked = e.target;
			var action  = $(this).attr("action")

			//messagesBulkAction(e, action)
			return false;	
		})
*/





	}); //ready




	

/*	 Ajax messagesBulkAction, incomplete.
		// not used. ajax version of bulk delete/archive
		function messagesBulkAction (e, clicked) {
			var checked = new Array();
			$('.message-list input:checked').each(function(){
				checked.push($(this).attr("name"))
			})
			
			
			var postURL = "/messages/" + clicked;
			
			cl("posturl: ", postURL)
			cl("checked: ", checked)
			
			$.ajax({
				type: "POST",
				url: postURL,
				data: checked,
				success: function(msg){
					if(msg == "0"){
						cl("it's 0")
					}

					if(msg == "1"){
						cl("it's 1")

					}
				},
				error: function(msg){
					cl(msg);
				}	
			});	//ajax
		}
*/

		function addBulkButtons() {
			if ($('#bulk-delete').length>0) {
				$('#bulk-delete').parents("ul.actions")
					.prepend('<li><a class="message-select-all" href="#">Select all</a></li>');

				if (!$('body').is('.Archived-page')) {	
					$('#bulk-delete').parents("ul.actions")
						.append('<li><button value="Archive Checked" id="bulk-archive" type="submit">Archive checked</button></li>');
				};	

			};
		}


		//show the message type drop down when a compose button is clicked.
		// not in use at the moment. kept here in case it was called.
		function showMessageTypes(where){
			
			return true; // disable, but keep the function for now.
			
			
			if(where.attr("class") == 'message-type' ){
				$("ul.message-type").show();
			} else{
				$("ul.message-type").insertAfter(where).show(); 
			};

		}

		function hideMessageTypes(target){
			//called from a few places.
			if($(target).is('.message-type a')){
				return;
			}
			$("ul.message-type").hide();
		}
		
		function contactList(toggle){
			
		}
				
		// initialized more than once in ajax mode. dumped to functions to keep doc.ready cleaner.
		function recipientAutocomplete(){
			$('#MessageRecipientName').autocomplete("/contacts/autocomplete", {
				matchContains: true,
				max: 50,
				minChars: 0
				//mustMatch: true
			});

			// listen for change in recipeint name
			//$('#MessageRecipientName').change(recipientChange);

		}

		function recipientChange()
		{
			$("#MessageRecipientId").val("");
		}

		function recipientAutocompleteResult(){
			$("#MessageRecipientName").result(function(event, data, formatted) {
				if (data){
					$("#MessageRecipientId").val(data[1]);
					cl("the data:" + data[1]);
				}	
			});	
		}

		function fixContainerHeight(reset) {
			if(!reset){
				// let's store the height before we go messing with stuff.
				var currentHeight = $('#messages .main').height();
				$('body').data("currentHeight",currentHeight);

				$('#messages .main').css({"height": "36em"});
			} else {
				// not currently used but could be on close or submit of compose form.
				$('#messages .main').css({"height": $('body').data("currentHeight") });
			}
		}

		function submitBulkForm(action) {
			$("#messages-form").submit();
		}
		

		function contactRemove(contact) {

			var theLink = contact.attr("href") + "/ajax-remove";
			var $parent = contact.parents('.contact');
			
			// human readable version
			var contactName = $parent.find('.name').text() + ' - ' + $parent.find('.org-name').text();
			// contactName = contactName + ' - ' + contact.parents('.contact').find('.org-name').text();
			
			// machine readable id to pass. grabbed from an id name of "contact-XX"
			var contactID = contact.parents('.contact').attr('id').slice(8);
			//contactID = contactID; //
			
			
			$.ajax({
				type: "POST",
				url: theLink,
				data: contactID,
				success: function(msg){
					if(msg == "0"){
						alertIt("oops!" + msg);
					}
					if(msg == "1"){
						$parent.fadeTo("250", "0.25", function (){ $parent.hide("slow"); });
					}
				},
				error: function(msg){
					alertIt("oops!" + msg);
				}	
			});
			return false;
		}

		function composeMessage(setter) {
			
			var $setter;
			typeof setter == "object" ?  $setter = setter : $setter = $(".message-compose");
			
			var theClass = $setter.attr("class");
			
			if($('#contact-list').length){
				buildMessage();
			}
						
			// remove any old ones.
			$('#compose, #contact-list').remove(); 
			
			// set the stage
			$('.main').append('<div id="compose" class="compose ' + theClass + ' "></div>');

			// hang on a sec
			$('#compose').html(FH.loader);

			// where is it linking to? also need to get the inner container to load instead of the whole page.
			var theUrl = $setter.attr("href") + " form#MessageComposeForm";

			// Get the button text to use as the form's legend.
			var theText = $setter.text();

			// the page may not be tall enough to accomodate the compose form.
			fixContainerHeight();
			
			// bring the magic. do some init.
			$("#compose")
				.load(theUrl, function(){
					//hideMessageTypes();
					recipientAutocomplete();
					recipientAutocompleteResult();
					widgInit();		
					$(this).closer('remove', function(){
						// 'reset' will put the main container back to its original height.
						fixContainerHeight('reset');
						IX_scrollPage('h1', 700);
						
					})
				.find("legend:first").text(theText);

					IX_scrollPage('#compose', 700);
					
				
				});
		}
		
		// allows you to add a row to a PO in the message center
		function FH_addTableRow () {
			if($('#MessageMessageWidgIframe').length){
				var $table = $("#MessageMessageWidgIframe").contents().find(".table-po tbody");

				var old = $table.html();
				var newww = "<tr><td>x</td><td>x</td><td>x</td><td>$0.00</td><td>$0.00</td></tr>";
				$table.append(newww);

				//var nw = $table.html();
			}	
		}
		
