Array.prototype.remove=function(s){ 
	for ( i=0; i < this.length; i++ ) {
		if(this[i] == s) {
			this.splice(i, 1);
		}
	}
};

Array.prototype.addDistinct=function(s){ 
	for ( i=0; i < this.length; i++ ) {
		if(this[i] == s) {
			return;
		}
	}
	this.push(s);
};

	

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());
				} 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');
	}

}

// 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");
        }
    });
};


/**
 * 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 browse(event) {
	if (!$(event.target).attr("value")) {
		return false;
	}
	
	var theForm = $(event.target).parent('form');
	
	var type = $(theForm).children("input[name=object_type]").attr("value");
	var field = $(theForm).children("select").attr("name");
	var choice = $(theForm).children("select[name="+field+"] option:selected").attr("value");

	window.location="/browse/"+type+"/"+field+"/"+choice;
	return false;
}

$(document).ready(function () {

	$.datePicker.setDateFormat('ymd','-');
	$('.datepicker').datePicker({startDate:'2008-02-05'});

makeSublist('region','chapter_select',true);		
	makeSublist('program_region','program_chapter_select',true);		
	
	$('#expand_signup').click(function() {
		$('#signup_form_click').slideUp("normal", function() {
			$('#program_signup_segment').slideDown("normal");
		});
	});
	
	$('#signup_form_hide').click(function() {
		$('#program_signup_segment').slideUp("normal", function() {
			$('#signup_form_click').slideDown("normal");
		});
	});

	/* Spellchecker suggestions */
	$('.suggest').hover(function() {
		word = $(this).text();
		$(this).attr("id", 'suggest_active');
	    $("#suggest_active").append('<div class="suggestions" id="suggestions" style="display: none;"><div class="suggest_words"><b>Perhaps you meant...</b> </div><div class="suggest_bg"> </div></div>');
		pos = $("#suggest_active").offset();
		top = pos.top + 14;
		$("#suggestions").css("left", pos.left);
		$("#suggestions").css("top", top);
		$("#suggestions").fadeIn("slow", function() {
			$.get('/suggest/'+word, function(response){
				$(".suggest_words").append(response);
			});
		});
	}, function() {
		$("#suggestions").fadeOut("slow", function() {
			$(".suggest_words").remove();
			$("#suggestions").empty();
			$("#suggestions").remove();	
			$("#suggest_active").removeAttr("id");
			$("html").click();
		});
	});


	/*
	$('#cancel_button').click(function () { 

		var parentFormID = $(this).parents('form').attr('id');
		//alert("Parent form is "+parentFormID);
		cancelFriend($(this).parents('form').attr('id'));
		return false; 
	});
	*/
	//$('#preview').hide();
	$('#preview').after('&nbsp;<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(); 
                }
            }
        });
        
        
    
	/* browse form submit */
	$('#aza_bbg_folds').bind("change", browse);    
 	$('#target_populations').bind("change", browse);    
	$('#participants').bind("change", browse);    
    $('#speakersearch #type').bind("change", browse);
	$('#agencysearch #type').bind("change", browse);
  
	$('#loginBox').tabs();
	
    $('#intloginBox').tabs();
    $('#pluginLoginBox').tabs({on: 2});
	$('#diaryBox').tabs();
	$('#eventsBox').tabs();
	$('#searchAll').tabs();
	$('#userPrefTabs').tabs({remote: true, loadingClass: 'progress',
		onShow: function() {
			makeSublist('region','chapter_select',true);		
		}
	});

	$('#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();
        }

	var time;
	/* new speaker / agency handler */
	var speakerform_options = {
		url: '/speaker_agency_save',
    	beforeSubmit: function() {
			//console.log('Submitting...');
			$('#working_speaker_agency #speaker_buttons').fadeOut('normal', function(){
				$('#working_speaker_agency #speaker_wait').html('<img id="spinner" src="/images/admin/indicator.white.gif"> Saving...');
				$('#working_speaker_agency #speaker_wait').fadeIn('normal');
			});

		},
		success: function(responseText) { 
			// Did it work?
			if (responseText.match(/^Saved/)) {
				var rt = responseText.split(';', 2);
				var msg = rt[0];
				var obj = rt[1];
				
				regexp = /^Saved (.*?) \".*/;
				var type = msg.replace(regexp, "$1");
				
				//console.log('Msg: '+msg+'; Obj: '+obj+'; Type: '+type);

				$('#working_speaker_agency').remove();
				$('#new_'+type+'_form').slideUp("normal", function() {
					$('#new_'+type+'_form').html(msg);
					$('#new_'+type+'_form').slideDown("normal", function() {	
						time = setTimeout(function() {
							$('#new_'+type+'_form').slideUp("normal", function() {
								$('#new_'+type+'_form').html('&nbsp;');
							});
						}, 5000);
					});
				});
				
				//add it to the select and choose it
				regexp = /^Saved.*?\"(.*?)\"/;
				var name = msg.replace(regexp, "$1");
				$('select[name='+type+'] option').each(function() {
					if ($(this).attr("value") == obj) {
						$(this).remove();
					}
				});
				
				$('select[name='+type+']').append('<option value="'+obj+'" selected="selected"> '+name+'</option>');
				$('#add_'+type).click();
			} else {
				$('#working_speaker_agency #error').fadeOut("fast", function() {
					$('#working_speaker_agency #error').html(responseText);
					$('#working_speaker_agency #error').fadeIn("normal");
					$('#working_speaker_agency #speaker_wait').fadeOut("normal", function() {
						$('#working_speaker_agency #speaker_buttons').fadeIn();
					});
					var howTall = $('#working_speaker_agency').height() + 20;
					var theForm;
					if ($('#new_speaker_form').is(':visible')) {
						theForm = 'new_speaker_form';
					} else if ($('#new_agency_form').is(':visible')) {
						theForm = 'new_agency_form';
					}
					
					$('#'+theForm).animate({
						height: howTall+'px'
					});
				});
				
			}
			//return false;
		}
	};

	/* hide / show program submit agency / speaker segment */
	$('#open_speaker').click(function() {
		//alert("Got speaker click");
		if ($('#speaker').css("display") == 'block') {
			return false;
		}
		
		if ($('#agency').css("display") == 'block') {
			if ($('#new_agency_form').css("display") == 'block') {
				$('#working_speaker_agency').hide();
				$('#new_agency_form').animate({
					height: '0px',
					opacity: 'hide'
				});
			}
			
			$('#agency').slideUp("normal", function() {
				$('#speaker').slideDown("normal");
			});
		} else {
			$('#speaker').slideDown("normal");
		}
		
		listCheck('speakers');
	});
	
	$('#open_agency').click(function() {
		//alert("Got agency click");
		if ($('#agency').css("display") == 'block') {
			return false;
		}
		
		if ($('#speaker').css("display") == 'block') {
			if ($('#new_speaker_form').css("display") == 'block') {
				$('#working_speaker_agency').hide();
				$('#new_speaker_form').animate({
					height: '0px',
					opacity: 'hide'
				});
			}
			
			$('#speaker').slideUp("normal", function() {
				$('#agency').slideDown("normal");
			});
		} else {
			$('#agency').slideDown("normal");
		}
		
		listCheck('agencies');
	});
	
	
	$('#add_agency').click(function(eventObj){
		if ($('select[name=agency]').attr("value") == 'new') {
			// need to find out how tall the new form is
			// so make it, move it offscreen, and show it
			// otherwise it doesn't have any dimensions
			$('#program_speaker_agency_form').clone(true).insertAfter('#formtmp').attr('id', 'working_speaker_agency');
			$('#working_speaker_agency').css('left', '-1000px');
			$('#working_speaker_agency').show();
			$('#working_speaker_agency #speaker_title').hide();
			$('#working_speaker_agency #agency_title').show();
			$('#working_speaker_agency #speaker_title select[name=type]').remove();
			
			$('#working_speaker_agency input[name=agency_title]').attr("name", "title");
			$('#working_speaker_agency input[name=object_type]').attr("value", "agency");
			
			var howTall = $('#working_speaker_agency').height() + 20;
			//console.log("Height is "+howTall+"px");
			$('#working_speaker_agency').hide();

			//clearTimeout(time); //just in case
			$('#new_agency_form').empty(); //just in case	
			$('#new_agency_form').css("height", "0"); //just in case	

			$('#new_agency_form').show();
			
			$('#new_agency_form').animate(
				{height: howTall+'px'},
				"normal",
				function() {
					$('#formtmp').empty();
					$('#working_speaker_agency').css('top', $('#new_agency_form').offset().top);
					$('#working_speaker_agency').css('left', $('#new_agency_form').offset().left);
					$('#working_speaker_agency').show();
					$('#working_speaker_agency').ajaxForm(speakerform_options);
			});

			return false;
		} else {
			if ($('#working_speaker_agency').is(':visible')) {
					$('#working_speaker_agency #speaker_agency_cancel').click();
			}

			// add the selection to the form.
			var agencyid = $('select[name=agency] option:selected').attr("value");
			var agencyname = $('select[name=agency] option:selected').html();
			
			if (!$('#agency_list').html()) {
				// add a title
				$('#agency_list').prepend('<h3 style="display: none;">Agencies:</h3>');
				$('#agency_list h3').slideDown("normal");
			}

			var currList = new Array();
			if ($('textarea[name=agencies]').html()) {
				currList = $('textarea[name=agencies]').html().split(",");
			}
			currList.addDistinct(agencyid);
			$('textarea[name=agencies]').html(currList.join(','));
			
			var agencyedit = '';
			if (loggedIn) {
				agencyedit = ' <a class="edit_agency" href="/speaker_agency_save/'+agencyid+'">[edit]</a>';
			}
			$('#agency_list').append('<div style="display: none;" id="agency_'+agencyid+'"> <a href="#" class="cancelbutton"><img src="/images/admin/cancel.png" style="border: 0;" alt="Remove Agency"/></a> '+agencyname+agencyedit+'</div>');
			$('#agency_'+agencyid).slideDown("normal");


			$('select[name=agency] option:selected').removeAttr('selected');
			$('select[name=agency] option[value='+agencyid+']').attr("disabled", "disabled")
			$('select[name=agency] option[value=new]').attr('selected', 'selected');

			$('.edit_agency').click(function(eventObj){
				eventObj.preventDefault();
				if ($('#working_speaker_agency').is(':visible')) {
					$('#working_speaker_agency #speaker_agency_cancel').click();
				}
				
				if (!$('#agency').is(':visible')) {
					$('#open_agency').click();
				}
				
				cancelButton(eventObj, 'agencies'); // remove the existing chosen speaker
				var loc = $(this).attr('href');
				$('#formtmp').load(loc, function(data) {
					$('#formtmp > #program_speaker_agency_form').attr('id', 'working_speaker_agency');
					$('#working_speaker_agency').insertAfter($('#formtmp'));
					$('#working_speaker_agency').css('left', '-1000px');
					$('#working_speaker_agency').show();
					$('#working_speaker_agency #speaker_title').hide();
					$('#working_speaker_agency #agency_title').show();
					$('#working_speaker_agency #speaker_title select[name=type]').remove();
					$('#working_speaker_agency input[name=agency_title]').attr("name", "title");
					$('#working_speaker_agency input[name=object_type]').attr("value", "agency");
					
					$('#working_speaker_agency #speaker_agency_cancel').bind("click", function(event) {
						var theForm;
						if ($('#new_speaker_form').is(':visible')) {
							theForm = 'new_speaker_form';
						} else if ($('#new_agency_form').is(':visible')) {
							theForm = 'new_agency_form';
						}
						
						$('#'+theForm).animate({
							height: '0px',
							opacity: 'hide'
						});
							
						$('#working_speaker_agency').remove();
						$('select[name=agency] option:selected').removeAttr("disabled");
						listCheck('agencies');
						event.stopPropagation();
					});
					
					var howTall = $('#working_speaker_agency').height() + 20;
					//console.log("Height is "+howTall+"px");
					$('#working_speaker_agency').hide();
		
					//clearTimeout(time); //just in case
					$('#new_agency_form').empty(); //just in case	
					$('#new_agency_form').css("height", "0"); //just in case	
		
					$('#new_agency_form').show();
					
					$('#new_agency_form').animate(
						{height: howTall+'px'},
						"normal",
						function() {
							$('#formtmp').empty();
							$('#working_speaker_agency').css('top', $('#new_agency_form').offset().top);
							$('#working_speaker_agency').css('left', $('#new_agency_form').offset().left);
							$('#working_speaker_agency').show();
							$('#working_speaker_agency').ajaxForm(speakerform_options);							
					});
					
				});
			
			});
			
			$('a.cancelbutton').click(function() {
				var theDiv = $(this).parent('div');
				var idParts = theDiv.attr("id").split("_", 2);
				myType = idParts[0];
				myId = idParts[1];
				theDiv.slideUp("normal", function(){
					// get rid of it from the form
					var removeList = new Array();
					removeList = $('textarea[name=agencies]').html().split(",");
					removeList.remove(myId);
					
					$('textarea[name=agencies]').html(removeList.join(','));

					theDiv.remove();
					$('select[name='+myType+'] option[value='+myId+']').removeAttr("disabled");
					$('select[name='+myType+'] option[value='+myId+']').removeAttr("disabled");
					var theList;
					if (myType == 'agency') {
						theList = 'agencies';
					} else if (myType == 'speaker') {
						theList = 'speakers';
					}
					
					listCheck(theList);
				});
				return false;
			});

			return false;
		}

	});
	
	$('#add_speaker').click(function(eventObj){
		if ($('select[name=speaker]').attr("value") == 'new') {
			// need to find out how tall the new form is
			// so make it, move it offscreen, and show it
			// otherwise it doesn't have any dimensions
			$('#program_speaker_agency_form').clone(true).insertAfter('#formtmp').attr('id', 'working_speaker_agency');
			$('#working_speaker_agency').css('left', '-1000px');
			$('#working_speaker_agency').show();
			$('#working_speaker_agency #agency_title').hide();
			$('#working_speaker_agency #speaker_title').show();
			$('#working_speaker_agency #agency_title select[name=type]').remove();
			$('#working_speaker_agency input[name=speaker_title]').attr("name", "title");
			$('#working_speaker_agency input[name=object_type]').attr("value", "speaker");
	
			var howTall = $('#working_speaker_agency').height() + 20;
			//console.log("Height is "+howTall+"px");
			$('#working_speaker_agency').hide();
			
			clearTimeout(time); //just in case
			$('#new_speaker_form').empty(); //just in case	
			$('#new_speaker_form').css("height", "0");
			$('#new_speaker_form').show();

			$('#new_speaker_form').animate(
				{height: howTall+'px'},
				"normal",
				function() {
					$('#formtmp').empty();
					$('#working_speaker_agency').css('top', $('#new_speaker_form').offset().top);
					$('#working_speaker_agency').css('left', $('#new_speaker_form').offset().left);
					$('#working_speaker_agency').show();
					$('#working_speaker_agency').ajaxForm(speakerform_options);
				}
			);	
			
			return false;
		} else {
			if ($('#working_speaker_agency').is(':visible')) {
					$('#working_speaker_agency #speaker_agency_cancel').click();
			}

			var speakerid = $('select[name=speaker] option:selected').attr("value");
			var speakername = $('select[name=speaker] option:selected').html();
			if (!$('#speaker_list').html()) {
				// add a title
				$('#speaker_list').prepend('<h3 style="display: none;">Speakers:</h3>');
				$('#speaker_list h3').slideDown("normal");
			}

			var currList = new Array();
			if ($('textarea[name=speakers]').html()) {
				currList = $('textarea[name=speakers]').html().split(",");
			}
			currList.addDistinct(speakerid);
			$('textarea[name=speakers]').html(currList.join(','));
			var speakeredit = '';
			if (loggedIn) {
				speakeredit = ' <a class="edit_speaker" href="/speaker_agency_save/'+speakerid+'">[edit]</a>';
			}
			
			$('#speaker_list').append('<div style="display: none;" id="speaker_'+speakerid+'"> <a href="#" class="cancelbutton"><img src="/images/admin/cancel.png" style="border: 0;" alt="Remove Speaker"/></a> '+speakername+speakeredit+' </div>');
			$('#speaker_'+speakerid).slideDown("normal");

			$('select[name=speaker] option:selected').removeAttr('selected');
			$('select[name=speaker] option[value='+speakerid+']').attr("disabled", "disabled")
			$('select[name=speaker] option[value=new]').attr('selected', 'selected');
			
			$('.edit_speaker').click(function(eventObj){
				eventObj.preventDefault();
				if ($('#working_speaker_agency').is(':visible')) {
					$('#working_speaker_agency #speaker_agency_cancel').click();
				}
				
				if (!$('#speaker').is(':visible')) {
					$('#open_speaker').click();
				}


				cancelButton(eventObj, 'speakers'); // remove the existing chosen speaker
				var loc = $(this).attr('href');
				$('#formtmp').load(loc, function(data) {
					$('#formtmp > #program_speaker_agency_form').attr('id', 'working_speaker_agency');
					$('#working_speaker_agency').insertAfter($('#formtmp'));
					$('#working_speaker_agency').css('left', '-1000px');
					$('#working_speaker_agency').show();
					$('#working_speaker_agency #agency_title').hide();
					$('#working_speaker_agency #speaker_title').show();
					$('#working_speaker_agency #agency_title select[name=type]').remove();
					$('#working_speaker_agency input[name=speaker_title]').attr("name", "title");
					$('#working_speaker_agency input[name=object_type]').attr("value", "speaker");
					$('#working_speaker_agency #speaker_agency_cancel').bind("click", function(event) {
						var theForm;
						if ($('#new_speaker_form').is(':visible')) {
							theForm = 'new_speaker_form';
						} else if ($('#new_agency_form').is(':visible')) {
							theForm = 'new_agency_form';
						}
						
						$('#'+theForm).animate({
							height: '0px',
							opacity: 'hide'
						});
							
						$('#working_speaker_agency').remove();
						$('select[name=speaker] option:selected').removeAttr("disabled");

						listCheck('speakers');
						event.stopPropagation();						
					});

					var howTall = $('#working_speaker_agency').height() + 20;
					//console.log("Height is "+howTall+"px");
					$('#working_speaker_agency').hide();
					
					clearTimeout(time); //just in case
					$('#new_speaker_form').empty(); //just in case	
					$('#new_speaker_form').css("height", "0");
					$('#new_speaker_form').show();
		
					$('#new_speaker_form').animate(
						{height: howTall+'px'},
						"normal",
						function() {
							$('#formtmp').empty();
							$('#working_speaker_agency').css('top', $('#new_speaker_form').offset().top);
							$('#working_speaker_agency').css('left', $('#new_speaker_form').offset().left);
							$('#working_speaker_agency').show();
			
							$('#working_speaker_agency').ajaxForm(speakerform_options);
					});	
					
				});
			});			

			$('a.cancelbutton').click(function() {
				//console.log("Clicked cancelbutton. ID: "+$(this).parent('div').attr("id"));
				var theDiv = $(this).parent('div');
				var idParts = theDiv.attr("id").split("_", 2);
				myType = idParts[0];
				myId = idParts[1];
				theDiv.slideUp("normal", function() {
					// get rid of it from the form
					var removeList = new Array();				
					removeList = $('textarea[name=speakers]').html().split(",");
					removeList.remove(myId);
					$('textarea[name=speakers]').html(removeList.join(','));

					theDiv.remove();
					$('select[name='+myType+'] option[value='+myId+']').removeAttr("disabled");
					var theList;
					if (myType == 'agency') {
						theList = 'agencies';
					} else if (myType == 'speaker') {
						theList = 'speakers';
					}
					
					listCheck(theList);

				});
				return false;
			});

			return false;
		}
	});
	
	// first load, set up speakers and agencies
	if ($('textarea[name=speakers]').html()) {
		var newList = $('textarea[name=speakers]').html().split(",");
		for (i = 0; i < newList.length; i++) {
			$('select[name=speaker] option[value='+newList[i]+']').select();
			$('#add_speaker').click();
		}
	}
	
	if ($('textarea[name=agencies]').html()) {
		var newList = $('textarea[name=agencies]').html().split(",");
		for (i = 0; i < newList.length; i++) {
			$('select[name=agency] option[value='+newList[i]+']').select();
			$('#add_agency').click();
		}
	}
	
		
		
	$('#speaker_agency_cancel').click(function() {
		var theForm;
		var theList;
		if ($('#new_speaker_form').is(':visible')) {
			theForm = 'new_speaker_form';
			theList = 'speakers';
		} else if ($('#new_agency_form').is(':visible')) {
			theForm = 'new_agency_form';
			theList = 'agencies';
		}
		
		$('#'+theForm).animate({
			height: '0px',
			opacity: 'hide'
		});
			
		$('#working_speaker_agency').remove();
		listCheck(theList);
		$('select[name=agency] option:selected').removeAttr("disabled");
	});
	
	$('.cancel_sa_add').click(function() {
		var theForm;
		var theList;
		if ($('#speaker').is(':visible')) {
			theForm = 'speaker';
			theList = 'speakers';
		} else if ($('#agency').is(':visible')) {
			theForm = 'agency';
			theList = 'agencies';
		}
		
		
		$('#working_speaker_agency #speaker_agency_cancel').click(); // in case
		listCheck(theList);
		$('#'+theForm).slideUp("normal");
	});
	
	/* Speaker display stuff */
	$('.open_speaker').click(function(eventObj) {
		var thisLink = eventObj.target;
		var thisSpeaker = $(thisLink).attr("id");
		if ($('#open_'+thisSpeaker).is(':visible')) {
			$('#open_'+thisSpeaker).slideUp("normal");
			$(thisLink).children("img").attr("src", "/images/admin/arrow_box.gif");
		} else {
			$('#open_'+thisSpeaker).slideDown("normal");
			$(thisLink).children("img").attr("src", "/images/admin/arrow_down.gif");
		}
		
		return false;
	});
	
	$('#printTemplate .open_speaker').click();
	
	/*
	if ($('#program_category').attr("value") == "Speaker" || $('#program_category').attr("value") == "Agency or Organization") {
		if ($('#program_category').attr("value") == "Speaker") {
			$('#speaker').slideDown("normal");
		} else if ($('#program_category').attr("value") == "Agency or Organization") {
			$('#program').slideUp("normal");
			$('#agency').slideDown("normal");
			$('#program input[name=title]').attr("name", "NOT_title");
			$('#agency input[name=NOT_title]').attr("name", "title");
			$('#time_required_option').slideUp("normal");
			$('#participants_option').slideUp("normal");
		}
		
		$('#speaker_agency').slideDown("normal");
	}
	
	$('#program_category').change(function(){
		if ($('#program_category').attr("value") == "Speaker" || $('#program_category').attr("value") == "Agency or Organization") {
			
			if ($('#program_category').attr("value") == "Speaker" && $('#speaker').css("display") != 'block') {
				if ($('#agency').css("display") == 'block') {
					$('#agency').slideUp("normal");
					$('#agency input[name=title]').attr("name", "NOT_title");
					$('#program input[name=NOT_title]').attr("name", "title");
					$('#program').slideDown("normal");
				}
				$('#speaker').slideDown("normal");	
				if ($('#time_required_option').css("display") != "block") {
					$('#time_required_option').slideDown("normal");
				}
				if ($('#participants_option').css("display") != "block") {
					$('#participants_option').slideDown("normal");
				}
			} else if ($('#program_category').attr("value") == "Agency or Organization") {
				if ($('#speaker').css("display") == 'block') {
					$('#speaker').slideUp("normal");	
				}
				if ($('#program').css("display") == 'block') {
					$('#program').slideUp("normal");
					$('#program input[name=title]').attr("name", "NOT_title");
				}
				$('#agency').slideDown("normal");
				$('#agency input[name=NOT_title]').attr("name", "title");
				$('#time_required_option').slideUp("normal");
				$('#participants_option').slideUp("normal");
	
			}
			
			if ($('#speaker_agency').css("display") == 'block') {
				return true;
			} else  {
				$('#speaker_agency').slideDown("normal");
			}
		} else {
			if ($('#speaker_agency').css("display") == 'block') {
				if ($('#agency').css("display") == 'block') {
					$('#agency').slideUp("normal");
					$('#agency input[name=title]').attr("name", "NOT_title");
				}
				if ($('#speaker').css("display") == 'block') {
					$('#speaker').slideUp("normal");
				}
				if ($('#program').css("display") != 'block') {
					$('#program').slideDown("normal");
					$('#program input[name=NOT_title]').attr("name", "title");
				}
				$('#speaker_agency').slideUp("normal");	
				if ($('#time_required_option').css("display") != "block") {
					$('#time_required_option').slideDown("normal");
				}
				if ($('#participants_option').css("display") != "block") {
					$('#participants_option').slideDown("normal");
				}
			} else {
				return true;
			}
		}
	}); */
	
	// Show / hide "Other Populations" in program edit form
	
	// First load
	if ($('#programsubmit select[name=target_populations] option:selected')) {
		var shown = 0;
		jQuery.each($('#programsubmit select[name=target_populations] option:selected'), function() {
			if (this.value == 'Other') {
				shown = 1;
				if (!$('#target_other').is(':visible')) {
					$('#target_other').slideDown("normal");
				}
			}
		});
		
		if ($('#target_other').is(':visible') && shown == 0) {
			$('#target_other').slideUp("normal");
		}
	}

	// On change
	$('#programsubmit select[name=target_populations]').change(function() {
		var shown = 0;
		jQuery.each($('#programsubmit select[name=target_populations] option:selected'), function() {
			if (this.value == 'Other') {
				shown = 1;
				if (!$('#target_other').is(':visible')) {
					$('#target_other').slideDown("normal");
				}
			}
		});
		
		if ($('#target_other').is(':visible') && shown == 0) {
			$('#target_other').slideUp("normal");
		}
	});
	
	$('select[name=program_scope]').change(function() {
		// Nothing showing
		if (this.value == "International") {
			if ($('#region_segment').is(':visible')) {
				$('#region_segment').slideUp("normal");
			}
			if ($('#chapter_segment').is(':visible')) {
				$('#chapter_segment').slideUp("normal");
			}
		} else if (this.value == "Regional") {
			if ($('#chapter_segment').is(':visible')) {
				$('#chapter_segment').slideUp("normal");
			}
			
			if ($('#region_segment').is(':hidden')) {
				$('#region_segment').slideDown("normal");
			}		
		} else if (this.value == "Chapter") {
			if ($('#region_segment').is(':hidden')) {
				$('#region_segment').slideDown("normal");
			}		
			if ($('#chapter_segment').is(':hidden')) {
				$('#chapter_segment').slideDown("normal");
			}		
		}
	
	});

	$('select[name=program_scope]').trigger('change');
	
	// also set default region / chapter if necessary
	
	// Search form re-sort option
	$('#sort_options select').change(function() {
		$('#programsearch').submit();
	});
	
    /* 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;
	});


	$(".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");


		$("#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;
					}

					/* set the reply handler */
					/*
					$("#submitreply").submit(function(){

						var msgID = $('input[@name=message_id]', this).val();
						var msgReplyID = "reply_"+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(){

		var msgID = $('input[@name=message_id]', this).val();
		var msgReplyID = "reply_"+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('/reload_captcha', function(response){
			setTimeout("captchaFinish('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);
	}


	/* program media upload handler */
	
	var mediaform_options = { 
        url: '/program_media_upload', 
    	beforeSubmit: function() {
			var fileName = $('#program_upload').attr('value');
			
			if (!fileName) {
				$('#upload_form').fadeOut('normal', function() {
					$('#upload_wait').html('Error: Please select a file to upload.');
					$('#upload_wait').fadeIn('normal');
				});
				setTimeout("restoreForm()", 4000);
				return false;
			}
			
			fileName = fileName.replace(/^.*[\\\/](.*?)$/, "$1");
			$('#upload_form').fadeOut('normal', function(){
				$('#upload_wait').html('Uploading '+fileName+'... <img id="spinner" src="/images/admin/indicator.white.gif">');
				$('#upload_wait').fadeIn('normal');
			});
		},
		success:    function(responseText) { 
			// What kind of file?
			if (responseText.match(/program_image/)) {
	  			if (!$('#program_media').html().match(/Pictures/)) {
	  				$('#program_media').append('<h3>Pictures:</h3>');
	  			}
	  			$('#program_media').append(responseText);
	  			// get the new value and put it in the hidden textarea
	  			var Files = new Array;
	  			if($('#attached_images').text().length > 0) {
		  			Files.push($('#attached_images').text());
		  		}
	  			Files.push($('#new_item').attr("value"));
	  			$('#attached_images').empty();
	  			$('#attached_images').text(Files.join(','));
	  			$('#new_item').remove();
			} else {
				if (!$('#program_edit_documents').html().match(/Documents/)) {
	  				$('#program_edit_documents').append('<h3>Documents:</h3>');
	  			}
				$('#program_edit_documents').append(responseText);
	  			// get the new value and put it in the hidden textarea
	  			var Files = new Array;
	  			if($('#attached_documents').text().length > 0) {
	  				Files.push($('#attached_documents').text());
	  			}
	  			Files.push($('#new_item').attr("value"));
	  			$('#attached_documents').empty();
	  			$('#attached_documents').text(Files.join(','));
	  			$('#new_item').remove();
			}
			
			$('#upload_wait').fadeOut('normal', function() {
				$('#program_upload').attr('value', '');
				$('#upload_success').fadeIn('normal', function() {
					setTimeout(function() {
						$('#upload_success').fadeOut('normal', function() {
							$('#up_new').fadeIn();
					})}, 4000);
				});
			});
			setImageBehaviors();

   		}   
    }; 
	
	$('#program_media_form').ajaxForm(mediaform_options);
	
	/* Set the location of the upoad div */
	$('#up_new').click(function(eventObj){
		$('#program_media_form').css('top', (eventObj.pageY - 10));
		$('#up_new').fadeOut('normal', function() {
			$('#upload_form').show();
			$('#program_media_form').fadeIn();
		});
		
		return false;
	});
	
	/* cancel an upload */
	$('#program_upload_cancel').click(function() {
		$('#program_media_form').fadeOut();
		$('#program_upload').attr('value', '');
		$('#up_new').fadeIn();
	});
	
	setImageBehaviors();

	// Set the first enlarged image height	
	
	var skipfirst = 0;
	$('a.program_image_enlarge').each(function() {
		//preload all images
		if (skipfirst == 1) {
			skipfirst = 0;
		} else {		
			jQuery("<img>").attr("src", $(this).attr("href"));
		}
	});
		
	$('a.program_image_enlarge').click(function() {
		var newImage = $(this).attr('href');
		
		$("#enlarge_image").append(
			'<div id="imagetest" style="display: block; position: absolute; left: -10000px;"><img src="'+newImage+'" class="image_enlarged" style="display: block;"/></div>'
		);
		
		$("#imagetest > img").load(function() {
			var newHeight = $("#imagetest > img").height();
		
			$('#imagetest').remove();
			$('#enlarge_image').fadeOut('normal', function(){
				$('#enlarge_image').empty();
				$('#enlarge_image').animate({
				 	height: newHeight
				}, "normal", 'linear', function() {
					$('#enlarge_image').html(	
						'<img src="'+newImage+'" class="image_enlarged" style="display: none;"/>'
					);
				
					$('.image_enlarged').fadeIn('slow');
				});
			});
		
		});
		
		$('img.active_thumb').removeClass("active_thumb");
		$(this).children('img').addClass("active_thumb");	
				
		return false;	
	});
	
	$('a.program_image_enlarge:first').click();

/*	$("img.image_enlarged").load(function() {
		var setHeight = $(this).height();
	
		$('#enlarge_image').animate({height: setHeight}); 
	});
	$("img.image_enlarged").trigger("load");
*/

	// Rating stars
	$('.rating_box > #star').each(function(){
		$(this).rating('/rate_program/'+$(this).children(".id").html(), {maxvalue: 5, curvalue: $(this).children(".current").html()});
	});
	
	//$('#star').rating('/rate_program/'+$("#star .id").html(), {maxvalue: 5, curvalue: $("#star .current").html()});
	
	
	$('#more_help').click(function() {
		$('#search_help').slideToggle('normal', function() {
			var helptxt = $('#more_help').html();
			if (helptxt.match(/Less/)) {
				$('#more_help').html('More help...');
			} else {
				$('#more_help').html('Less help...');
			}
		});
		return false;
	});
	
	$('#expand_form').click(function() {

		$('#searchform').slideToggle('normal', function() {
			var exptxt = $('#expand_form').html();
			if (exptxt.match(/Refine/)) {
				$('#expand_form').html('&laquo; Hide Form');
			} else {
				$('#expand_form').html('&raquo; Refine or change your search');
			}
		});
		return false;
	});
	
	
	$('#program_delete').click(function(event) {
		if ($('#confirm').attr("checked")) {
			return true;
		} else {
			$('#confirm_field').animate({width: "120px", opacity: 1});
			event.stopPropagation( );
			return false;
		}
	});
	
	$('.star_rating').hover(function() {
		$(this).children("div.cancel").css("background", "url(/images/admin/cancel.gif) no-repeat scroll 0 0");
		$(this).children("div.cancel").hover(function() {
				$(this).css("background", "url(/images/admin/cancel.gif) no-repeat scroll 0 -15px");
			},function() {
				$(this).css("background", "url(/images/admin/cancel.gif) no-repeat scroll 0 0");
		});
	},function() {
		$(this).children("div.cancel").css("background", "none");
		$(this).children("div.cancel").unbind("hover");
	});
	
	$('.toolTip').hover(
		function() {
			this.tip = $(this).children(".contents").html();
			$('.toolTipWrapper').each(
				function() {
					$(this).fadeOut("normal", 
						function() { 
							$(this).remove(); 
						});
				}
			); // hide all others
			$(this).prepend(
				'<div class="toolTipWrapper">'
					+this.tip
					+'<!--[if lte IE 6.5]><iframe></iframe><![endif]-->'
					+'<br style="clear: both;" />'
				+'</div>'
			);
			this.width = $(this).width();
			$(this).css("z-index", "10");
			$(this).find('.toolTipWrapper').css({left:this.width-22})
			$('.toolTipWrapper').fadeIn(300);
		},
		function() {
			container = $(this);
			$('.toolTipWrapper').fadeOut("normal", 
				function() {
					container.children("div.toolTipWrapper").remove();
					container.css("z-index", "0");
				}
			);
		}
	);

});
/*-------------------------------------------------------------
  End document.ready
-------------------------------------------------------------*/
function listCheck(theList) {
	var selectlist;
	//console.log("Starting list check. The list is: "+theList);
	if (theList == 'speakers') {
		selectlist = 'speaker';
	} else if (theList == 'agencies') {
		selectlist = 'agency';
	}
	//console.log("The selector is: "+selectlist);
	
	$('select[name='+selectlist+'] option').removeAttr("disabled");
	
	//console.log("Enabled all");
	
	var currList = new Array();
	if ($('textarea[name='+theList+']').html()) {
		var contents = $('textarea[name='+theList+']').html();
		//console.log("Got current list: "+contents);
		currList = contents.split(",");
	} else {
		//console.log("No current list");
		return;
	}
	
	//console.log("current list is "+currList.length+" elements long");
	for (i = 0; i < currList.length; i++) {
		//console.log("Examining "+i);
		$('select[name='+selectlist+'] option[value='+currList[i]+']').attr("disabled", "disabled");
	}
	
	//console.log("Done");
	return;
}

function setImageBehaviors() {
	$('a.moveup').unbind('click');
	$('a.movedown').unbind('click');
	$('a.remove').unbind('click');
	
	$('a.remove').click(function(event) {
		var val_to_remove = $(this).parents("p").children("a").attr("href");
		var what = ($(this).parents("p").hasClass("program_document")) ? 'doc' : 'img';
		Files = new Array();
		if (what == 'doc') {
			Files = $('#attached_documents').text().split(',');
		} else {
			Files = $('#attached_images').text().split(',');
		}
		
		newFiles = new Array();
		while (thisFile = Files.shift()) {
			if (thisFile != val_to_remove) {
				newFiles.push(thisFile);
			}
		}
		
		if (what == 'doc') {
			$('#attached_documents').text(newFiles.join(','));
		} else {
			$('#attached_images').text(newFiles.join(','));
		}
		
		$(this).parents("p").remove();
		return false;
	});
	
	$('a.moveup').click(function() {
		var previousItem = $(this).parents("p").prev();
		var what = ($(this).parents("p").hasClass("program_document")) ? 'doc' : 'img';
		
		if (!previousItem || (previousItem.attr("class") != 'program_image' && previousItem.attr("class") != 'program_document')) {
			return false;
		}
		
		var currentItem = $(this).parents("p");
		
		previousItem.fadeOut('normal', function() {
			var myClone = previousItem.clone(true);
			previousItem.remove();
			myClone.insertAfter(currentItem).fadeIn('normal', function() {
				Files = new Array;
				if (what == 'doc') {
					$("#program_edit_documents").children("p.program_document").each(function() {
							Files.push($(this).children("a").attr('href'));
					});
					$('#attached_documents').text(Files.join(','));
				} else {
					$("#program_media").children("p.program_image").each(function() {
							Files.push($(this).children("a").attr('href'));
					});
					$('#attached_images').text(Files.join(','));
				}
			});
		});
				
		return false;
	});
	
	$('a.movedown').click(function() {
		var nextItem = $(this).parents("p").next();
		var what = ($(this).parents("p").hasClass("program_document")) ? 'doc' : 'img';
		
		if (!nextItem || (nextItem.attr("class") != 'program_image' && nextItem.attr("class") != 'program_document')) {
			return false;
		}
		
		var currentItem = $(this).parents("p");
		
		nextItem.fadeOut('normal', function() {
			var myClone = nextItem.clone(true)
			nextItem.remove();
			myClone.insertBefore(currentItem).fadeIn('normal', function() {
				Files = new Array;
				if (what == 'doc') {
					$("#program_edit_documents").children("p.program_document").each(function() {
							Files.push($(this).children("a").attr('href'));
					});
					$('#attached_documents').text(Files.join(','));
				} else {
					$("#program_media").children("p.program_image").each(function() {
							Files.push($(this).children("a").attr('href'));
					});
					$('#attached_images').text(Files.join(','));
				}
			});
		});

		
		return false;
	});
}	

function restoreForm() {
	$('#upload_wait').fadeOut('normal', function() {
		$('#upload_form').fadeIn('normal');
	});
}
// 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) {
			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){

	            event.stopPropagation();
				var myNick = $("#nick").val();
				var msgID = $(this).parents(".message").attr("id");


				$("#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;
							}

							/* set the reply handler */
							/*
							$("#submitreply").submit(function(){

								var msgID = $('input[@name=message_id]', this).val();
								var msgReplyID = "reply_"+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("/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;
}	

function cancelButton(eventObj, type) {
	var theDiv = $(eventObj.target).parent('div');
	var idParts = $(theDiv).attr("id").split("_", 2);
	myType = idParts[0];
	myId = idParts[1];
	$(theDiv).slideUp("normal", function(){
		// get rid of it from the form
		var removeList = new Array();
		removeList = $('textarea[name='+type+']').html().split(",");
		removeList.remove(myId);
		
		$('textarea[name='+type+']').html(removeList.join(','));
	
		$(theDiv).remove();
		$('select[name='+myType+'] option[value='+myId+']').attr("selected", "selected");
	});
	return false;
}

// Display an ajax result nicely
function finishAjax(id, response) {
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn('normal');
} //finishAjax

// Display an ajax result nicely
function captchaFinish(id, response) {
  $('.'+id).html(unescape(response));
  $('.'+id).fadeIn('normal');
} //finishAjax


