/* b-linked custom JS */

$(document).ready(function () {
	
	$.datePicker.setDateFormat('ymd','-');
	$('.datepicker').datePicker();
	
	$('#teenfind').click(function(){
		//console.log("Clicked "+this);
		if ($(this).hasClass("confirm")) {
			var confirm = 1;
		}
		$("#form_err").html('&nbsp;');
		$('#check_links').fadeOut("normal", function() {
			//console.log("Fading out .check");
			$('#process').fadeIn("normal", function() {
				var q_str = $('#id_email').val();
				var url = '/membership_teen_check/' + q_str + "?callback=?";
				jQuery.getJSON(url, function(data){
					if (data.success == 1) {
						$('#process').fadeOut("normal", function() {
							if (confirm) {
								jQuery("#form_go").html(data.content);
								jQuery("#form_err").html(data.message);
								$('#check_cancel').fadeIn("normal");
							} else {
								// just submit the form
								$('#add_teen_form').submit()
							}
						});
					} else {
						$('#process').fadeOut("normal", function() {
							jQuery("#form_err").html(data.message);
							$('.check').fadeIn("normal");
						});
					}
					return false;
				}); 
			});
		
		});
		return false;
	});

	$('#add_cancel').click(function(){
		$('#change_membership_form input').attr('value', '');
		$("#form_err").empty();
		$("#form_err").html('&nbsp;');
		$("#form_go").empty();
		$('#process').fadeOut("normal", function() {
			$('#check_links').fadeIn("normal");
		});
		labels_init();
		return false;
	});
	
	
	/* when searching for a friend, add the search name to the three extra hidden fields */
	$('#friend_find').submit(function() {
		var thisName = $('#friend_find input[name=public_name]').attr("value");
		$('#friend_find input.friend_hide').attr("value", thisName);
		return;
	});
	
	/* membership form */
	$('#parent_2_expand').click(function() {
		$('#parent_2_expand').fadeOut("normal", function() {
			$('#parent_2').slideDown("normal");
		});
		return false;
	});
	
	$('#parent_2_collapse').click(function() {
		$('#parent_2').slideUp("normal", function() {
			$('#parent_2_expand').fadeIn("normal");
		});
		
		$('.p2').each(function(){ $(this).val(""); });
		
		$('select[@name=parent_2_state] option').removeAttr("selected");
		$('select[@name=parent_2_country] option').removeAttr("selected");

		return false;
	});
	
	/* membership pay form, info copier */
	$('div.payment_info a').click(function() {
		var whichParent = $(this).attr("class");
		whichParent = whichParent.replace(/use_/, '');

		$('span.'+whichParent).each(function() {
			var whatIsIt = $(this).attr("id");
			var myValue =  $(this).html();
			if (whatIsIt == 'address_1') { whatIsIt = 'address1'; }
			if (whatIsIt == 'address_2') { whatIsIt = 'address1'; }
			if (whatIsIt == 'home_phone') { whatIsIt = 'phone'; }
			
			if (whatIsIt == 'country') {
				/* Get the id needed from the select list values */
				$('#contribute select[@name=country] option').each(function() {
					var countryName = $(this).text();
					if (countryName == myValue) {
						$('#contribute select[@name=country]').val($(this).val());
					}
				});
			} else if (whatIsIt == 'state') {
				$('#contribute select[@name=state]').val(myValue);			
			} else {		
				$('#contribute input[@name='+whatIsIt+']').attr("value", myValue);
			}
		});
		
		return false;
	});
	
	
	/* membership pay form, total sum */
	$('#contribute input.checkradio').change(function() {
		$('#id_amount_other').attr('value', '');
		var radioVal = $("#contribute input.checkradio:checked").val();
		radioVal = radioVal.replace(/\$/, '');
		//radioVal = radioVal.replace(/\.\.*$/, '');
	
		addVal = $('#id_additional_donation').val();
		if (addVal) {
			addVal = addVal.replace(/\$/, '');
			addVal = addVal.replace(/[^0123456789\.]/, '');
		}

		if (addVal == '0.00') {
			$('#id_additional_donation').attr("value", '');
			addVal = 0;
		}
		
		if (addVal && radioVal) {
			fullVal = parseFloat(addVal) + parseFloat(radioVal);
		} else if (addVal && !radioVal) {
			fullVal = parseFloat(addVal);
		} else {
			fullVal = parseFloat(radioVal);
		}
		
		$('#total_line').html('$'+fullVal);
	});
	
	$('#id_additional_donation').change(function() {
		var radioVal = $("#contribute input.checkradio:checked").val();
		if (radioVal) {
			radioVal = radioVal.replace(/\$/, '');
		}

		var otherVal = $("#id_amount_other").val();
		if (otherVal) {
			otherVal = otherVal.replace(/\$/, '');
			otherVal = otherVal.replace(/[^0123456789\.]/, '');
		}
			
		addVal = $('#id_additional_donation').val();
		addVal = addVal.replace(/\$/, '');
		addVal = addVal.replace(/[^0123456789\.]/, '');
		addVal = parseFloat(addVal);
		
		if (addVal == '0.00') {
			$('#id_additional_donation').attr("value", '');
			addVal = 0;
		}
		
		if (addVal && otherVal) {
			fullVal = parseFloat(addVal) + parseFloat(otherVal);
		} else if (addVal && radioVal) {
			fullVal = parseFloat(addVal) + parseFloat(radioVal);
		} else if (addVal && !radioVal && !otherVal) {
			fullVal = parseFloat(addVal);
		} else if (radioVal) {
			fullVal = parseFloat(radioVal);
		} else if (otherVal) {
			fullVal = parseFloat(otherVal);
		} else {
			fullVal = parseFloat(0);
		}
		
		fullVal = fullVal.toFixed(2);
		
		$('#total_line').html('$'+fullVal);
	});
	
	$('#id_amount_other').change(function() {
		$("#contribute input.checkradio").attr("checked", '');
		var otherVal = $("#id_amount_other").val();
		
		otherVal = otherVal.replace(/\$/, '');
		otherVal = otherVal.replace(/[^0123456789\.]/, '');
		otherVal = parseFloat(otherVal);

		var min_max = $('#id_amount_other').attr("className");
		var minmax_array = min_max.split(/ /);
		
		for (i=0;i<2;i=i+1) {
			if (minmax_array[i] && minmax_array[i].match(/^max_/)) {
				max = minmax_array[i].replace(/max_/, '');
			} else if (minmax_array[i] && minmax_array[i].match(/^min_/)) {
				min = minmax_array[i].replace(/min_/, '');
			}
		}
		
		if (otherVal && max && parseFloat(otherVal) > parseFloat(max)) {
			otherVal = parseFloat(max);
		} else if (otherVal && min && parseFloat(otherVal) < parseFloat(min)) {
			otherVal = parseFloat(min);
		}
			
		otherVal = otherVal.toFixed(2);
		$('#id_amount_other').attr("value", otherVal);
		
		addVal = $('#id_additional_donation').val();
		if (addVal) {
			addVal = addVal.replace(/\$/, '');
			addVal = addVal.replace(/[^0123456789\.]/, '');
		}
		if (addVal == '0.00') {
			$('#id_additional_donation').attr("value", '');
			addVal = 0;
		}
		
		if (addVal && otherVal) {
			fullVal = parseFloat(addVal) + parseFloat(otherVal);
		} else if (addVal && !otherVal) {
			fullVal = parseFloat(addVal);
		} else {
			fullVal = parseFloat(otherVal);
		}
		
		fullVal = fullVal.toFixed(2);
		$('#total_line').html('$'+fullVal);
	});

	/* photo gallery codes */
	$('.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();
	});
	
	// Kill any blank amount values in contribute forms
	$('#contribute').submit(function() {
		if (!$('#id_amount_other').attr("value")) {
			$('#id_amount_other').remove();
		}	
	});
	
	$('#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;
	});
	
	
	/* 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();

}); /* end document.ready */


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');
	});
}/* Javascript related to the event submit form */
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(isSubselectOptional) {
					$('.'+child).html('<option value="" > -- Select Chapter -- </option>');
				} else {
					$('.'+child).html('');
				}
				
				if ($("#"+parent+child+" .sub_"+parentValue).length > 0) {
					$('.'+child).append($("#"+parent+child+" .sub_"+parentValue).clone());
				} else {
					$('.'+child).append('<option value="'+parentValue+' At Large">At Large</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');
	}

}

/* handlers for date items */
(function($){  
 $.fn.date_item = function() {  
	return this.each(function() {  
		$(this).click(function() {
			var id = $(this).attr("id");
			id = id.replace(/delete_date_/, '');
			//console.log("ID is "+id);

			// if there's an existing eid along w/this date, register it for removal
			var old_eid = $('input[name=date_event_'+id+']').attr("value");
			if (old_eid) {
				$('#dates').append('<input type="text" style="position: absolute; visibility: hidden;" name="remove_date_'+id+'" value="'+old_eid+'" />');
			}

			$('#date_'+id).slideUp("normal",
				function(){
					$('#date_'+id).remove();
				}
			);
			
			return false;
		});
	
	});  
 };

})(jQuery);  
/* End dates plugin */

/* Expandable list management item */
(function($){  
 $.fn.expandableList = function() {  
	return this.each(function() {  
		// pass me a textarea id
		var obj = $(this);
		var keyID = $(this).attr("id");
		////console.log("Calling readList at startup for "+keyID);
		obj.readList();
		
		// Make the data holder
		var myList = obj.data("values");
		
		if (!myList) {
			myList = new Array;
			obj.data("values", myList);
		}
			
		// Clicking the "expand_keyID" button should write the content of the 
		// field to the data bucket, and add a new field
		$('#expand_'+keyID).click(function() {
			myList = obj.data("values");
			var newvalue = $('input[name=newpart_'+keyID+']').attr("value");
			////console.log("Adding: "+newvalue);
			myList.push(newvalue);
			obj.data("values", myList);
			////console.log("Calling writeList from #expand click for "+keyID);
			obj.writeList();
			
			// add the new field
			var new_item_index = myList.length;
			$('input[name=newpart_'+keyID+']')
				.clone(true)
					.hide()
						.attr("name", 'part'+new_item_index+'_'+keyID)
							.addClass("existingPart")
								.appendTo('#partswrapper_'+keyID)
									.after(' <a class="delbutton" href="#" id="delete_part'+new_item_index+'_'+keyID+'">[X]</a>')
										.slideDown("normal")
											.partBehaviors(obj);
			$('input[name=newpart_'+keyID+']').attr("value", '');
		});
		
		// Update the value in the value bucket if the user edits an existing item.
		$('#partswrapper_'+keyID+' > .existingPart').partBehaviors(obj);
		
	});  
 };
 
 // Update the value in the value bucket if the user edits an existing item.
 $.fn.partBehaviors = function(obj) { 
	return this.each(function() {  
		////console.log("Adding part behaviors for "+$(this).attr("name"));
 		$(this).change(function() {
			var fullList = new Array();
			$('.existingPart').each(function() {
				fullList.push($(this).attr("value"));
			});
			obj.data("values", fullList);
			obj.writeList();
		});	
		
		$('.delbutton').click(function() {
			var keyID = obj.attr("id");
			////console.log("Delete: keyID is: "+keyID);
			var thisItem = $(this).attr("id");
			////console.log("Delete: Item is "+thisItem);
			var item_to_go = thisItem.replace(/delete_/, '');
			////console.log("Delete: Item to go is: "+item_to_go);
			$(this).remove();
			$('input[name='+item_to_go+']').fadeOut("normal", function() {
				////console.log("Delete: in remove, this is: "+this);
				$(this).remove(); 
				$(this).removeClass("existingPart"); 		
				var fullList = new Array();
				$('#partswrapper_'+keyID+' > .existingPart').each(function() {
					////console.log("Re-adding to list: "+$(this).attr("value"));
					fullList.push($(this).attr("value"));
				});	
			
				obj.data("values", fullList);
				obj.writeList();
			});
			
			return false;
		});
		
		return;
	});  
 };

 $.fn.writeList = function() {  
	return this.each(function() {  
		var obj = $(this);
		var myList = obj.data("values");

		if ( myList.length <= 0 ) {
			obj.attr("value", '');
			return;
		}

		for (thisItem in myList) {
			////console.log("Item is "+myList[thisItem]);
			if (myList[thisItem].match(/\+/)) {
				myList[thisItem] = myList[thisItem].replace(/\+/, '__PLUS__');
			} 
		}
		var listJoined = myList.join('+');
		obj.attr("value", '');
		obj.attr("value", listJoined);
	});  
 };
 		
 $.fn.readList = function() {  
	return this.each(function() {  
		var obj = $(this);
		var currentList = obj.attr("value");
		
		if (!currentList) {
			return;
		}
		var keyID = obj.attr("id");
		
		var myList = currentList.split('+');

		obj.data("values", myList); // store it first
		
		var listFields = new Array;
		for (i in myList) {
			if (myList[i].match(/__PLUS__/)) {
				myList[i] = myList[i].replace(/__PLUS__/, '+');
			}
			
			listFields.push('<input type="text" style="display: none;" class="newpart temphide existingPart" '+ 
				'value="'+ myList[i] +'" name="part'+i+'_'+keyID+'"/> <a class="delbutton" href="#" id="delete_part'+i+'_'+keyID+'">[X]</a>');
		}
		
		var keyID = $(this).attr("id");
		$('#partswrapper_'+keyID).append(listFields.join(''));
		$('.temphide').slideDown("normal").removeClass("temphide");
		
		////console.log("Calling writeList from readList for "+keyID);
		obj.writeList();
		
		return;
		
	});  
 };

})(jQuery);  
/* End exp list plugin */


/* Mini-plugin to make changing the standard form show/hide behavior easy */
(function($){  
 $.fn.togglePretty = function() {  
	return this.each(function() {  
		var obj = $(this);
	
	 	if (obj.is(":visible")) {
			obj.hidePretty("normal");
		} else {
			obj.showPretty("normal");
		}
 
	});  
 };
 
 $.fn.showPretty = function() {  
	return this.each(function() {  
 		var obj = $(this);
		if (obj.is(":hidden")) {
			obj.slideDown("normal");
		}
	});  
 };

 $.fn.hidePretty = function() {  
	return this.each(function() {  
 		var obj = $(this);
		if (obj.is(":visible")) {
			obj.slideUp("normal");
		}
	});  
 };
    
})(jQuery);  
/* end *Pretty plugin */

/* utility: pass it a list of ids, and a hash of ids to show, and it 
will show the ones in the hash and hide the rest from the full list */
function show_hide (full_list, active_list) {
	if (!full_list) {
		return;
	}
	
	if (!active_list) {
		active_list = {};
	}
		
	for (i in full_list) {
		if (active_list[full_list[i]]) {
			$('#'+full_list[i]).showPretty();
		} else {
			$('#'+full_list[i]).hidePretty();
		}
	}
}
/* finish show_hide() */

/* page refresh after specified interval */
function pageTimeout(seconds, url) {
	var msTime = (seconds * 1000);
	setTimeout(function () { window.location=url; }, msTime);
	return false;
}

/* Payment type behaviors controller */
function payment_type() {
	////console.log("Setting payment type options in payment_type()");
	var no_fee_options = new Array(
		"event_payment_options",
		"event_cost",	
		"event_deposit_amount",
		"event_final_payment_due_month",
		"event_scholarship",
		"event_apply_for_scholarship",
		"event_member_discount"
	);
	
	// "Payment Required" selected, show these
	var payment_required_options = {
		"event_payment_options":1,
		"event_cost":1,	
		"event_final_payment_due_month":1,
		"event_scholarship":1,
		"event_apply_for_scholarship":1,
		"event_member_discount":1
	};		

	// "Pay In Full" selected, show these
	var pay_in_full_options = {
		"event_cost":1,	
		"event_scholarship":1,
		"event_apply_for_scholarship":1,
		"event_final_payment_due_month":1,
		"event_member_discount":1
	};
	
	var deposit_required_options = {
		"event_cost":1,	
		"event_deposit_amount":1,
		"event_final_payment_due_month":1,
		"event_scholarship":1,
		"event_apply_for_scholarship":1,
		"event_member_discount":1
	};
	
	var payment_type_str = $('#payment_restrictions option:selected').attr("value");
	////console.log("Selected option is "+payment_type_str);
	
	if (payment_type_str == "Payment Required") {
		show_hide(no_fee_options, payment_required_options);
	} else if (payment_type_str == "Must Pay in Full") {
		show_hide(no_fee_options, pay_in_full_options);
	} else if (payment_type_str == "Deposit Required") {
		show_hide(no_fee_options, deposit_required_options);
	} else {
		show_hide(no_fee_options);
	}
	
	$('#scholarship').change();
}
/* End payment type behaviors controller */

/* organizer / staff lookup */
(function($){  
 $.fn.person_check = function() {  
	return this.each(function() {  
		$(this).change(function() {
			//console.log("Running person check");
			var address = $(this).attr('value');
			var event_prop_name = $(this).attr('name');
			//console.log("Checking "+address);
			//console.log("Event prop "+event_prop_name);

			$('#event_'+event_prop_name+' .ajax_result').load("/email_lookup/"+address); 
		 });
	});
  }
})(jQuery);  


$(document).ready(function () {
	makeSublist('region','chapter_select',true);		


	/* Event display page */
	$('#eventDisplayTabs').tabs();
	
	$('#reglink').click(function() { 
    	$('#eventDisplayTabs').triggerTab(3); // switch to third tab
	    return false;
	});
		
	$('#program_highlights').expandableList();
	$('#whats_included').expandableList();
	$('#accommodations').expandableList();
	$('#q_and_a').expandableList();

	$('#eventEditTabs').tabs({
		onClick: function(clickedThis) {
			var anchor = $(clickedThis).attr("href");
			////console.log("Clicked: "+anchor);
        	var act = $('#event_edit_form').attr("action");
        	if (act.match(/\#/)) {
        		////console.log("Matched a #");
        		act = act.replace(/\#.*$/, anchor);
        	} else {
        		act = act + anchor;
        	}
           	////console.log("act is "+act);
 	
        	$('#event_edit_form').attr("action", act);
        }
    });

	// Form removal links
	$('.remove_form').click(function() {
		var which = $(this).attr('id');
		which = parseInt(which.replace(/^form_/, ''));
		
		myForms = eval($('textarea[name=required_forms]').val());
		myForms.splice(which, '1');

		//serialize back to json
		if (myForms.length >= 1) {
			$('textarea[name=required_forms]').html($.toJSON(myForms));
		} else {
			$('textarea[name=required_forms]').html('');
		}
		//Remove the form line
		$('#form_disp_'+which).html("<i>Form removed. Please save this event to make your change permanent.</i>");
		
		return false;
	});

	// standard form display
	/*
$('#overnight_event').change(function () {
		if ($('input[name=overnight_event]:checked').attr("value") == '1') {
			$('#event_required_forms').prepend('<span class="event_edit_title standard_forms" style="display: block;">Standard Forms:</span>'+
				'<span class="standard_forms" style="display: block; float: left;">Standard teen & parent release forms, for overnight event.</span>');
		} else {
			$('.standard_forms').remove();
		}
	});
	
	// fire the change event once to set the forms display
	$('#overnight_event').change();
	*/

	$('input[name=arrival]').click(function() {
		var arrivalChecked = $('input[name=arrival]:checked').attr("value");
		
		if (arrivalChecked == 'arrival_by_plane') {
			$('#arrival_flight_info').showPretty();
		} else {
			$('#arrival_flight_info').hidePretty();
		}
		
		if (arrivalChecked == 'arrival_driven_to_program') {
			$('#arrival_driven_to_program_info').showPretty();
		} else {
			$('#arrival_driven_to_program_info').hidePretty();
		}
		
		if (arrivalChecked == 'arrival_regional') {
			$('#arrival_regional_transportation_info').showPretty();
		} else {
			$('#arrival_regional_transportation_info').hidePretty();
		}
		
		if (arrivalChecked == 'arrival_driven_to_airport') {
			$('#arrival_driven_to_airport_info').showPretty();
		} else {
			$('#arrival_driven_to_airport_info').hidePretty();
		}
	});
	
	$('input[name=departure]').click(function() {
		var departureChecked = $('input[name=departure]:checked').attr("value");
		
		if (departureChecked == 'departure_by_plane') {
			$('#departure_flight_info').showPretty();
		} else {
			$('#departure_flight_info').hidePretty();
		}
		if (departureChecked == 'departure_picked_up_at_program') {
			$('#departure_picked_up_at_program_info').showPretty();
		} else {
			$('#departure_picked_up_at_program_info').hidePretty();
		}
		
		if (departureChecked == 'departure_regional') {
			$('#departure_regional_transportation_info').showPretty();
		} else {
			$('#departure_regional_transportation_info').hidePretty();
		}
		
		if (departureChecked == 'departure_picked_up_at_airport') {
			$('#departure_picked_up_at_airport_info').showPretty();
		} else {
			$('#departure_picked_up_at_airport_info').hidePretty();
		}
	});
	
	$('input[name=departure]').change();
	$('input[name=arrival]').change();
	
	// form signoff actions
	$('.form_signoff').click(function() {
		myID = $(this).attr('id');
		myID = myID.replace(/sign_form_/, 'form_');
		$('#'+myID).showPretty();
		return false;
	});

	//$('a.lightbox').lightBox();
        ////console.log("Setting region / chapter options");
	////console.log("Event type: "+$('input[name=event_type]:checked').attr("value"));

	// Region / chapter behaviors

	$('#sitewide_cal').attr("checked", 'checked'); // to start with, by default...

	$('#teen_organizer_1').person_check();
	$('#teen_organizer_2').person_check();
	$('#staff_info_1').person_check();
	$('#staff_info_2').person_check();
	
	if ($('input[name=event_type]:checked').attr("value") == "Regional_Council" ||
		$('input[name=event_type]:checked').attr("value") == "Chapter") {
		////console.log("Showing region field");
		$('#event_region').showPretty();
		
		if ($('input[name=event_type]:checked').attr("value") == "Regional_Council") {
			$('#event_invite_other_regions').showPretty();
		} else {
			$('#event_invite_other_regions').hidePretty();
		}
		$('#sitewide_cal').attr("checked", 'checked');
	} else {
		////console.log("Hiding region field");
		$('#event_region').hidePretty();
		$('#event_invite_other_regions').hidePretty();
		$('#event_invite_other_chapters').hidePretty();
	}	
		
	if ($('input[name=event_type]:checked').attr("value") == "Chapter") {
		////console.log("Showing chapter field");
		$('#event_chapter_select').showPretty();
		$('#event_invite_other_chapters').showPretty();
		$('#sitewide_cal').attr("checked", 'checked');
	} else {
		////console.log("Hiding chapter field");
		$('#event_chapter_select').hidePretty();
		$('#event_invite_other_chapters').hidePretty();
	}	
	
	if ($('input[name=event_type]:checked').attr("value") == "International") {
		$('#event_in_israel').showPretty();
		$('#event_set_region_caps').showPretty();
		$('#sitewide_cal').attr("checked", 'checked');
	} else {
		$('#event_in_israel').hidePretty();
		$('input[name=in_israel]').attr("checked", "");
		$('#event_set_region_caps').hidePretty();
	}

	if ($('input[name=event_type]:checked').attr("value") == "Other") {
		//$('#other_cals').showPretty();
		$('#sitewide_cal').attr("checked", 'checked');
	} else {
		//$('#other_cals').hidePretty();
	}

	if ($('input[name=set_region_caps]:checked').attr("value") == "1") {
		$('#event_region_caps').showPretty();
	} else {
		$('#event_region_caps').hidePretty();
	}

	if ($('input[name=invite_other_chapters]:checked').attr("value") == "1") {
		$('#event_other_chapter_select').showPretty();
	} else {
		$('#event_other_chapter_select').hidePretty();
	}
	
	if ($('input[name=invite_other_regions]:checked').attr("value") == "1") {
		$('#event_other_region_select').showPretty();
	} else {
		$('#event_other_region_select').hidePretty();
	}
	
	$('input[name=invite_other_regions]').change(function() {
		var chosen = $('input[name=invite_other_regions]:checked').attr("value");
		if (chosen == 1) {
			$('#event_other_region_select').showPretty();
		} else {
			$('#event_other_region_select').hidePretty();
		}
	});

	
	$('input[name=invite_other_chapters]').change(function() {
		var chosen = $('input[name=invite_other_chapters]:checked').attr("value");
		if (chosen == 1) {
			$('#event_other_chapter_select').showPretty();
		} else {
			$('#event_other_chapter_select').hidePretty();
		}
	});
	
	$('input[name=set_region_caps]').change(function() {
		var chosen = $('input[name=set_region_caps]:checked').attr("value");
		if (chosen == 1) {
			$('#event_region_caps').showPretty();
		} else {
			$('#event_region_caps').hidePretty();
		}
	});
	
	$('input[name=event_type]').change(function() {
		var chosen = $('input[name=event_type]:checked').attr("value");
		////console.log("Chose event type "+chosen);
		
		if (chosen == "International") {
			$('#event_region').hidePretty();
			//$('#other_cals').hidePretty();
			$('#event_chapter_select').hidePretty();
			$('#event_in_israel').showPretty();
			$('#event_set_region_caps').showPretty();
			$('#event_invite_other_regions').hidePretty();
			$('input[name=invite_other_chapters]').attr('checked', '');
			$('input[name=invite_other_regions]').attr('checked', '');
			$('input[name=invite_other_chapters]').change();
			$('input[name=invite_other_regions]').change();
			$('#event_invite_other_chapters').hidePretty();
			$('#sitewide_cal').attr("checked", 'checked');
		} else if (chosen == "Regional_Council") {
			$('#event_in_israel').hidePretty();
			//$('#other_cals').hidePretty();
			$('input[name=in_israel]').attr("checked", "");
			$('input[name=set_region_caps]').attr("checked", "");
			$('input[name=set_region_caps]').change();			
			$('#event_set_region_caps').hidePretty();
			$('#event_region').showPretty();
			$('#event_invite_other_regions').showPretty();
			$('input[name=invite_other_chapters]').attr('checked', '');
			$('input[name=invite_other_chapters]').change();
			$('#event_invite_other_chapters').hidePretty();
			$('#event_chapter_select').hidePretty();
			$('#sitewide_cal').attr("checked", 'checked');
		} else if (chosen == "Chapter") {
			$('#event_in_israel').hidePretty();
			//$('#other_cals').hidePretty();
			$('input[name=in_israel]').attr("checked", "");
			$('input[name=set_region_caps]').attr("checked", "");
			$('input[name=set_region_caps]').change();			
			$('#event_set_region_caps').hidePretty();
			$('#event_region').showPretty();
			$('#event_chapter_select').showPretty();
			$('input[name=invite_other_regions]').attr('checked', '');
			$('input[name=invite_other_regions]').change();
			$('#event_invite_other_regions').hidePretty();
			$('#event_invite_other_chapters').showPretty();
			$('#sitewide_cal').attr("checked", 'checked');
		} else if (chosen == "Other") {
			$('#event_in_israel').hidePretty();
			$('input[name=in_israel]').attr("checked", "");
			$('input[name=set_region_caps]').attr("checked", "");
			$('input[name=set_region_caps]').change();			
			$('#event_set_region_caps').hidePretty();
			$('#event_region').hidePretty();
			$('#event_chapter_select').hidePretty();
			$('input[name=invite_other_chapters]').attr('checked', '');
			$('input[name=invite_other_regions]').attr('checked', '');
			$('input[name=invite_other_chapters]').change();
			$('input[name=invite_other_regions]').change();
			$('#event_invite_other_regions').hidePretty();
			$('#event_invite_other_chapters').hidePretty();
			//$('#other_cals').showPretty();
			$('#sitewide_cal').attr("checked", 'checked');
		} else {
			$('#event_in_israel').hidePretty();
			$('input[name=in_israel]').attr("checked", "");
			$('input[name=set_region_caps]').attr("checked", "");
			$('input[name=set_region_caps]').change();			
			$('#event_set_region_caps').hidePretty();
			$('#event_region').hidePretty();
			$('#event_chapter_select').hidePretty();
			$('input[name=invite_other_chapters]').attr('checked', '');
			$('input[name=invite_other_region]').attr('checked', '');
			$('input[name=invite_other_chapters]').change();
			$('input[name=invite_other_regions]').change();
			$('#event_invite_other_regions').hidePretty();
			$('#event_invite_other_chapters').hidePretty();
			$('textarea[name=cal_id]').attr("value", savedId);
			$('#sitewide_cal').attr("checked", 'checked');
		}
	});	
	// end region / chapter behavior
	
	// Fee behaviors
	////console.log("Setting payment options");
	
	payment_type(); // set initial state
	
	$('#payment_restrictions').bind("change", function() { 
		////console.log("In payment_restrictions change event");
		return payment_type() 
	});
	
	/* check apply for scholarship */
	$('#scholarship').bind("change", function() {
		if ($('#scholarship').is(":hidden")) {
			return false;
		}
		
		var yesno = $('#scholarship option:selected').attr("value");
		////console.log("Scholarship value is "+yesno);
		if (yesno == "1") {
			////console.log("Showing scholarship apply");
			$('#event_apply_for_scholarship').showPretty();
		} else {
			////console.log("Hiding scholarship apply");
			$('#event_apply_for_scholarship').hidePretty();
		}
		return false;
	});
		
	$('#scholarship').change();
	
	// end fee behaviors
	
	
	/* audience restriction behaviors */
	$('#audience_restriction').bind("change", function() {
		if ($('#audience_restriction option:selected').attr("value") == "Restricted") {
			$('#event_audience').showPretty();
		} else {
			$('#event_audience').hidePretty();
		}
	});
	
	$('#audience_restriction').change();
	// end audience restriction behaviors 

	/* travel info main behavior */
	$('#show_airports').bind("change", function() {
		if ($('#show_airports').is(":checked")) {
			$('#event_airports').showPretty();
		} else {
			$('#event_airports').hidePretty();
		}
	});
	
	$('#use_travel_form').bind("change", function() {
		if ($('#use_travel_form').is(":checked")) {
			$('#event_travel_info').showPretty();
			$('#event_show_airports').showPretty();
			$('#show_airports').change();
		} else {
			$('#event_travel_info').hidePretty();
			$('#event_show_airports').hidePretty();
			$('#event_airports').hidePretty();
		}
	});
	
	$('#use_travel_form').change();
	
	// write current dates into storage fields
	$('.jdate,#time_start_am_pm_new,#time_end_am_pm_new').change(function() {
		var myName = $(this).attr("name");
		var realName = myName.replace(/_new$/, '');
		var myValue = $(this+' option:selected').attr("value") || $(this).attr("value");
		console.log("Changed "+myName+" ("+realName+") to "+myValue);
		$('textarea[name='+realName+']').html(myValue);
	});
	 
	var aDate = ["date_start_month_new", "date_start_year_new", "date_start_day_new", "time_start_am_pm_new",
		"date_end_month_new", "date_end_year_new", "date_end_day_new", "time_end_am_pm_new"];
	
    $('#add_date').data("count", $('#date_start_count').attr("value"));	

	// Handle date add
	$('#add_date').click(function() {
		var curr =  $('#add_date').data("count");
		var thisDate = [];
		for (i in aDate) {
			thisDate[aDate[i]] = $('select[name='+aDate[i]+'] option:selected').attr("value") || '';
			var real = aDate[i].replace(/_new/, "");
			//console.log("Real name is "+real+", adding value "+thisDate[aDate[i]]);
			//$('textarea[name='+real+']').attr("value", thisDate[aDate[i]]);
		}
		
		thisDate["time_start_new"] = $('input[name=time_start_new]').attr("value") || '';
		thisDate["time_end_new"] = $('input[name=time_end_new]').attr("value") || '';
		
		$('textarea[name=time_start]').attr("value", thisDate["time_start"]);
		$('textarea[name=time_end_new]').attr("value", thisDate["time_end_new"]);
		
		var startdate = thisDate["date_start_year_new"]+'-'+thisDate["date_start_month_new"]+'-'+thisDate["date_start_day_new"];
		var enddate = thisDate["date_end_year_new"]+'-'+thisDate["date_end_month_new"]+'-'+thisDate["date_end_day_new"];
		
		$('#date_content').append(
		'<span id="date_'+curr+'" style="display: none; height: 18px;">'+
			thisDate["date_start_month_new"]+'/'+thisDate["date_start_day_new"]+'/'+thisDate["date_start_year_new"]+' '+
			thisDate["time_start_new"]+' '+thisDate["time_start_am_pm_new"]+
			' to '+thisDate["date_end_month_new"]+'/'+thisDate["date_end_day_new"]+'/'+thisDate["date_end_year_new"]+' '+
			thisDate["time_end_new"]+' '+thisDate["time_end_am_pm_new"]+
			'<input type="text" style="position: absolute; visibility: hidden;" name="time_end_am_pm_'+curr+'" value="'+thisDate["time_end_am_pm_new"]+'" />'+
			'<input type="text" style="position: absolute; visibility: hidden;" name="date_start_'+curr+'" value="'+startdate+'" />'+
			'<input type="text" style="position: absolute; visibility: hidden;" name="date_end_'+curr+'" value="'+enddate+'" />'+
			'<input type="text" style="position: absolute; visibility: hidden;" name="time_start_'+curr+'" value="'+thisDate["time_start_new"]+'" />'+
			'<input type="text" style="position: absolute; visibility: hidden;" name="time_end_'+curr+'" value="'+thisDate["time_end_new"]+'" />'+
			'<input type="text" style="position: absolute; visibility: hidden;" name="time_start_am_pm_'+curr+'" value="'+thisDate["time_start_am_pm_new"]+'" />'+
		' <a href="#" id="delete_date_'+curr+'" class="delete_date">[X]</a><br /></span>'
		);
		
		var old_start = $('input[name=date_start]').attr("value");
		var old_end = $('input[name=date_end]').attr("value");

		if (!old_start) {
			$('textarea[name=date_start]').attr("value", startdate);
		}
		if (!old_end) {
			$('textarea[name=date_end]').attr("value", enddate);
		}

		$('#delete_date_'+curr).date_item(); // add behaviors for delete button
		
		$('#dates').showPretty();
		$('#date_'+curr).showPretty();
		curr = curr + 1;
		$('#add_date').data("count", curr);
		
		// clear the main form
		//$('#date_section_new select, #date_section_new input').attr("value", "");
	});
	

	// date item delet button behaviors
	$('.delete_date').date_item();
	
	
	/* Compare table behavior 
	$('tr.compare_item').hover(
		function() {
			var id = $(this).attr("id");
			//console.log("ID is "+id);
			var more = $('#more_'+id).html();
			
			$('#compare_more_fill').hide().html(more).fadeIn("normal");		
		},
		function() {
			$('#compare_more_fill').fadeOut("normal", function(){
				$('#compare_more_fill').empty();
			});
		}
	); */
		
	$(".printlink").click(function(){
		// Print the DIV.
		$( ".printable" ).print();
	 
		// Cancel click event.
		return( false );
	});
	
}); /* End document.ready() */

