// vJustify plugin 
// rewrite cache

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");
        }
    });
};


/**
 * 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 makeSublist(parent,child,isSubselectOptional) {
	$("body").append("<select style='display:none' id='"+parent+child+"'></select>");
	$('#'+parent+child).html($("#"+child+" option"));
	$('.'+child).html('<option value=""> --- </option>');		
	
	$('.'+parent).change(
		function()
		{
			var parentValue = $(this).attr('value');
			if (parentValue) {
				parentValue = parentValue.replace(/ /g, "_");
				parentValue = parentValue.replace(/\./g, "_");
				
				if ($("#"+parent+child+" .sub_"+parentValue).length > 0) {
					$('.'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
					$('.'+child).prepend('<option value="'+parentValue+' At Large">At Large</option>');
				} else {
					$('.'+child).html('<option value="'+parentValue+' At Large">At Large</option>');
				}
				

				if(isSubselectOptional) {
					$('.'+child).prepend('<option value="" > -- Select Chapter -- </option>');
				}
				
				if ($('.'+child+' option:selected')) {
					$('.'+child+' option:selected').attr('selected', 'selected');
					$('.'+child).trigger('change');
				} else {
					$('.'+child+' option:first').attr('selected', 'selected');
				}
				
				
			}
		}
	);

	if ($('.'+parent+' option:selected')) {
		$('.'+parent).trigger('change');
	}
	
	if ($('.'+child+' option:selected')) {
		$('.'+child+' option:selected').attr('selected', 'selected');
		$('.'+child).trigger('change');
	}

}


$(document).ready(function () {

	makeSublist('region','chapter_select',true);		

	$('div#spread_client select').change(function () {
		var chosen = $('div#spread_client select option:selected').attr("value");
		console.log("Selected "+chosen);
		if (chosen) {
			$('div.client_form:visible').slideUp("normal").css("display", "none");
			$('div #'+chosen).slideDown("normal");
		}
	});


	/*
	$('#cancel_button').click(function () { 
		console.log(this); 
		var parentFormID = $(this).parents('form').attr('id');
		//alert("Parent form is "+parentFormID);
		cancelFriend($(this).parents('form').attr('id'));
		return false; 
	});
	*/
	//$('#preview').hide();
	$('#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'});
	
	$('#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("/destinations/messages_read", {nick: myNick, message_id: msgID, read: "read"},
			function() { return false; });
		
	  	return false;
	  }
	  return false;
	});


	$(".masterCheckBox").click(function(){ $("#messageCenterForm").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("/destinations/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;
					}

					/* set the reply handler */
					/*
					$("#submitreply").submit(function(){
						console.log(this);
						var msgID = $('input[@name=message_id]', this).val();
						var msgReplyID = "reply_"+msgID;
						console.log(msgID);

						var options = {
						  target:   ".content_"+msgID,
						  success:  reportReply(msgID, msgReplyID)
						};

		    			$(this).ajaxSubmit(options); 	

						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;
	});


	/* // Ajax reply version -- too many problems with this.
	$("#submitreply").submit(function(){
		console.log(this);
		var msgID = $('input[@name=message_id]', this).val();
		var msgReplyID = "reply_"+msgID;
		console.log(msgID);

		var options = {
		  target:   ".content_"+msgID,
		  success:  reportReply(msgID, msgReplyID)
		};

    	$(this).ajaxSubmit(options); 	

		return false;
	});
	*/
	
	$(".action_drop").change(function(){
		$("#messageCenterForm").submit();
		return;	
	});
	/* end messaging code */

	//var nick = $("#nick").val();
	//alert("nick is "+nick);

	$('#captcha_reload').click(function(){
		$('#captcha').fadeOut("normal");

		$.get('/destinations/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('/destinations/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("/destinations/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("/destinations/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;
							}

							/* set the reply handler */
							/*
							$("#submitreply").submit(function(){
								console.log(this);
								var msgID = $('input[@name=message_id]', this).val();
								var msgReplyID = "reply_"+msgID;
								console.log(msgID);

								var options = {
								  target:   ".content_"+msgID,
								  success:  reportReply(msgID, msgReplyID)
								};

				    			$(this).ajaxSubmit(options); 	

								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("/destinations/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
