	// Global AgencyLocatorMap (GoogleMap) object.
	var ALocMap = dataObj = null;
	var ALocMapMarkers = [];

	// Google Maps Functionality
	gmaps = {
		setup: function(){
			var latlng = new google.maps.LatLng(42.358431,-71.059773);
			var myOptions = {
				zoom: 10,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: false,
				panControlOptions: {
					position: google.maps.ControlPosition.TOP_RIGHT
				},
				scaleControl: false,
				zoomControlOptions: {
					position: google.maps.ControlPosition.TOP_RIGHT
				},
				streetViewControl: true,
				overviewMapControl: false
			};
			ALocMap = new google.maps.Map(document.getElementById("ALocMap"), myOptions);
		},
		centerOnMarker: function( marker ){
			ALocMap.setZoom(14);
			ALocMap.setCenter(marker);
		},
		init: function(){
			this.setup();
		}
	}

	// Agency Listing
	agency = {
		markers: {
			cleanup: function(){
				for(i in ALocMapMarkers){
					ALocMapMarkers[i].setIcon(ALocMapMarkers[i].beam.iconOff);
					ALocMapMarkers[i].zIndex = ALocMapMarkers[i].beam.ozIndex;
				}
			},
			reset: function(){
				//Reset Marker Array
				for (i in ALocMapMarkers){ ALocMapMarkers[i].setMap(null); }
				ALocMapMarkers.length = 0;
			}
		},
		list: {
			cleanup: function(){
				$('.ALResultsList li.agency').each(function(i){
					$(this).removeClass('selected').css({ 'background-image': 'url('+ALocMapMarkers[(i+1)].beam.iconOff+')' });
				});
			},
			get: function(form, limit){

				var inc = 1, zi = 100, results = [], resultsListHTML = [], bounds = new google.maps.LatLngBounds();

				//Remove the Pins
				agency.markers.reset();

				$.post('/_service/need_food_search.php', form.serialize() + '&limit=' + limit, function(data) {
					dataObj = $.parseJSON(data);

					// confirm there was no error.
					if (dataObj.error.length > 0) {
						alert('There was an error processing your request: ' + dataObj.error);
						return false;
					} else if (dataObj.response.length == 0) {
						// no results.
						return false;
					}

					// Fixes Chrome issue with reordering the JSON OBJECT
					for(i in dataObj.response){ results.push(dataObj.response[i]); }
					results.sort(function(a,b){ return a.distance - b.distance });

					resultsListHTML.push('<ul>');
					var EPAN_label = $('#agencyLocatorSearchForm fieldset label').first().html();
					var ESOUP_label = $('#agencyLocatorSearchForm .form_fields fieldset.cmp label').html();

					// Combining the result list and the marker building in the same loop.
					//$.each(dataObj.response, function(location_id, location) {
					for(var i = 0, len = results.length; i < len; i++){
						var location = results[i];
						var id = location.location_id, latlng = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
						inc = ((inc <= 9)? '0'+inc : inc );

						// Build List HTML
						resultsListHTML.push('<li class="agency location'+inc+'" latitude="' + location.latitude + '" longitude="' + location.longitude + '" location_id="' + location.location_id + '" name="' + location.name + '" pos="'+(inc*1)+'">');
						resultsListHTML.push('<p class="type">' + (location.type == 'EPAN' ? EPAN_label : ESOUP_label) + '</p>');
						resultsListHTML.push('<p class="name">' + location.name + '</p><p>' + location.address1 + (location.address2.length > 0 ? ', ' + location.address2 : '') + '</p><p>' + location.city + ', ' + location.state + ' ' + location.zip + '</p>');
						resultsListHTML.push('<a href="#" class="more_info">+ More Info</a><p>' + location.distance + ' mile' + (location.distance == 1 ? '' : 's') + '</p>');

						// Build the "Additional Information" section (expands when "+More Info" is clicked).
 						var add_info = '';
						if (location.hours != null && location.hours.length > 0) {
							for(x in location.hours) {
								add_info = add_info + '<span>' + location.hours[x].weekday + '</span> ' + location.hours[x].open + ' - ' + location.hours[x].close + '<br/>';
							}
						}
						resultsListHTML.push('<p class="additional_info">' + (location.phone.length ? '<br/>' + location.phone + '<br/>' : '') + '<br/><strong>Hours of Operation</strong>' + (add_info.length > 0 ? '<br/>' + add_info : '') + (location.note.length > 0 ? '<br/>' + location.note : '') + '</p></li>');

						//Set Google Markers
						marker = new google.maps.Marker({
							position: latlng,
							icon: '/_img/needfood/marker_'+inc+'.png',
							shadow: '/_img/needfood/marker_shadow.png',
							map: ALocMap,
							title: location.name,
							zIndex: zi,
							// This isn't part of the marker spec but we're going to borrow it seeing as it already exists.
							beam: {
								iconOff: '/_img/needfood/marker_'+inc+'.png',
								iconOn: '/_img/needfood/marker_selected_'+inc+'.png',
								locationID: id,
								ozIndex: ''
							}
						});

						//Set Google Event Listeners
						google.maps.event.addListener(marker, 'click', function(event) {
							var ali = $('li[location_id='+this.beam.locationID+']');

							//Clean Up
							agency.list.cleanup();
							agency.markers.cleanup();

							//Set Marker Selected Icon
							this.setIcon(this.beam.iconOn);
							this.zIndex = 9999;

							// Move List
							$('div.ALResultsList').scrollTop(0).scrollTop(ali.position().top);

							// Highlight Selected Icon
							ali.addClass('selected').css({ 'background-image': 'url('+this.beam.iconOn+')' });
						});

						ALocMapMarkers[(inc*1)] = marker;
						bounds.extend(latlng);
						inc++;
						zi--;
					};
					// finish off the list.
					resultsListHTML.push('</ul>');

					// Don't render a "Load More" button if we have 40 agencies loaded.
					if (limit <= 30) {
						resultsListHTML.push('<button class="loadmore ir">Load More</button>');
					}

					//Build & Append HTML
					built = resultsListHTML.join('');

					$('.ALResultsList').empty().append(built);

					// center and zoom the map so all markers are visible.
					ALocMap.fitBounds(bounds);

					// map all the coordinates.
					return true;
				});
			},
			more_info: function(){

				//Expand/Collaspse of Moar Info
				$('.more_info').live('click', function(e){
					if($(this).nextAll('p.additional_info').is(':visible')){
						$(this).text('+ More Info').nextAll('p.additional_info').hide();
					}else{
						$(this).text('- Collapse').nextAll('p.additional_info').show();
					}
					return false;
				});
			},
			filters: function(){
				$('.locatorFilter').bind('change', function(e){
					var cLen = $('div.form_fields').find(':input:checked').length;
					if(cLen > 0){
						if($('div.ALResultsList').is(':not(:empty)')){
							agency.list.get($('#agencyLocatorSearchForm'), 10);
						}
					}else{
						alert('At least one filter must be checked');
						$(this).attr('checked', 'checked');
						return false;
					}
				});
			},
			init: function(){

				this.more_info();
				this.filters();

			}
		}
	}



	function sortit(a,b){
		return(a-b)
	}


	$(document).ready(function() {

		$('.jcarousel li').eq(0).show();

		// Homepage Featured Video click() events.
		$('.featured_video_overlay').click(function(e) {
			window.open($(this).parent().find('a.featured_video_link').attr('href'), '_blank');
		});

		// Agency Locator
		$('.ALResultsList').delegate('li.agency p.name', 'click', function() {
			var agency_li = $(this).closest('li.agency');
			var i = agency_li.attr('pos');
			var marker = ALocMapMarkers[i];

			//Clean UP
			agency.list.cleanup();
			agency.markers.cleanup();

			//Set Markers
			marker.setIcon(marker.beam.iconOn);
			marker.beam.ozIndex = marker.zIndex;
			marker.zIndex = 9999;

			//Set List
			agency_li.css({ 'background-image': 'url('+marker.beam.iconOn+')' });

			gmaps.centerOnMarker(marker.getPosition());
		});

		$('.ALResultsList').delegate('.loadmore', 'mouseenter', function() {
			$(this).addClass('hover');
		});
		$('.ALResultsList').delegate('.loadmore', 'mouseleave', function() {
			$(this).removeClass('hover');
		});
		$('.ALResultsList').delegate('.loadmore', 'click', function() {
			agency.list.get($('#agencyLocatorSearchForm'), $('.ALResultsList li').length + 10);
		});

		$('#module_locate_field').focusin(function() {
			if ($(this).attr('value') == 'Enter zip code') {
				$(this).attr('value', '');
			}
		}).focusout(function() {
			if ($(this).attr('value') == '') {
				$(this).attr('value', 'Enter zip code');
			}
		});



		// form field focus highlighting
		$('input, textarea, select').focus(function() {
			$(this).addClass('focused');
		});
		$('input, textarea, select').blur(function() {
			$(this).removeClass('focused');
		});
		$('input[type=radio]').click(function() {
			$(this).parent().siblings().removeClass('focused');
			$(this).parent().addClass('focused');
		});

		var t;
		$('.showLogin').click(function(e){ return false; })
		$('.showLogin, div#login').hover(
			function(e){
				clearTimeout(t);
				$('#login').show();
			},function(e){
				t = setTimeout(function(){ $('#login').hide(); }, 500);
		})

		// form validation
		$('#GBFBForm').validate({
			errorClass: 'error',
			errorLabelContainer: '#formErrors',
			wrapper: 'li',
			errorElement: 'span',
			focusInvalid: false,
			highlight: function(element, errorClass) {
				$(element).parent().addClass('error');
			},
			unhighlight: function(element, errorClass) {
				$(element).parent().removeClass('error');
			},
			showErrors: function(errorMap, errorList) {
				this.defaultShowErrors();
				//$('html, body').animate({
				//	scrollTop: $("#formErrors").offset().top - 10
				//}, "fast");
			},
			messages: {
				first_name: "FIRST NAME: Required",
				last_name: "LAST NAME: Required",
				contact_name: "CONTACT NAME: Required",
				group_name: "GROUP NAME: Required",
				school_name: "SCHOOL NAME: Required",
				donor_name: "DONOR NAME: Required",
				donor_contact: "DONOR CONTACT: Required",
				donor_address: "DONOR ADDRESS LINES: Required",
				donor_city: "DONOR CITY: Required",
				donor_state: "DONOR STATE: Required",
				subject: "SUBJECT: Required",
				message: "MESSAGE: Required",
				address: "ADDRESS LINES: Required",
				agency_address: "AGENCY ADDRESS LINES: Required",
				agency_city: "AGENCY CITY: Required",
				city: "CITY: Required",
				state: "STATE: Required",
				agency_state: "AGENCY STATE: Required",
				zip: "ZIP: Required",
				agency_zip: "AGENCY ZIP: Required",
				email: {
					required: "EMAIL: Required",
					email: "EMAIL: Is invalid"
				},
				phone: {
					required: "PHONE #: Required",
					phoneUS: "PHONE #: Is invalid"
				},
				donor_phone: {
					required: "CONTACT PHONE #: Required",
					phoneUS: "CONTACT PHONE #: Is invalid"
				},
				emergency_contact_name: "EMERGENCY CONTACT NAME: Required",
				emergency_contact_relationship: "EMERGENCY CONTACT RELATIONSHIP: Required",
				emergency_contact_phone: {
					required: "EMERGENCY CONTACT PHONE: Required",
					phoneUS: "EMERGENCY CONTACT PHONE: Is Invalid"
				},
				securities_type: "NAME/TYPE OF SECURITIES: Required",
				num_shares: "# OF SHARES: Required",
				broker_phone: {
					required: "CONTACT PHONE #: Required",
					phoneUS: "CONTACT PHONE #: Is invalid"
				},
				site_name: "SITE NAME: Required",
				reporting_period: "REPORTING PERIOD: Required"
			},
			 invalidHandler: function(form, validator) {
				$('html, body').scrollTop($("p.required").offset().top);
			}
		});


		$('#donateForm').validate({
			errorClass: 'error',
			errorLabelContainer: '#formErrors',
			wrapper: 'li',
			errorElement: 'span',
			focusInvalid: false,
			highlight: function(element, errorClass) {
				$(element).parent().addClass('error');
			},
			unhighlight: function(element, errorClass) {
				$(element).parent().removeClass('error');
			},
			showErrors: function(errorMap, errorList) {
				this.defaultShowErrors();
				//$('html, body').animate({
				//	scrollTop: $("#formErrors").offset().top - 10
				//}, "fast");
			},
			rules: {
				first_name: "required",
				last_name: "required",
				contact_name: "required",
				group_name: "required",
				country: "required",
				address: "required",
				city: "required",
				state: "required",
				zip: "required",
				email: {
					required: true,
					email: true
				},
				phone: {
					phoneUS: true
				},
				cardholder_name: "required",
				card_type: "required",
				card_number: {
					required: true,
					creditcard: true
				},
				card_exp_month: "required",
				card_exp_year: "required",
				cvv2: {
					required: true,
					integer: true
				}
			},
			messages: {
				first_name: "FIRST NAME: Required",
				last_name: "LAST NAME: Required",
				contact_name: "CONTACT NAME: Required",
				group_name: "GROUP NAME: Required",
				country: "COUNTRY: Required",
				address: "ADDRESS LINES: Required",
				city: "CITY: Required",
				state: "STATE: Required",
				zip: "ZIP: Required",
				email: {
					required: "EMAIL: Required",
					email: "EMAIL: Is invalid"
				},
				phone: {
					phoneUS: "PHONE #: Is invalid"
				},
				cardholder_name: "CARDHOLDER NAME: Required",
				card_type: "CARD TYPE: Required",
				card_number: {
					required: "CREDIT CARD #: Required",
					creditcard: "CREDIT CARD #: Is Invalid"
				},
				card_exp_month: "CARD EXPIRATION MONTH: Required",
				card_exp_year: "CARD EXPIRATION YEAR: Required",
				cvv2: {
					required: "CARD SECURITY CODE: Required",
					integer: "CARD SECURITY CODE: Invalid"
				}
			}
		});

		$( ".accordion" ).accordion({ "collapsible" : true, "active" : false, "autoHeight" : false });

		$( ".crosslinks li").hover(function() {
			$(this).addClass('hovering');
		}, function() {
			$(this).removeClass('hovering');
		}).bind('click', function(event) {
			window.location = $(this).find('h3').find('a').attr('href');
			event.preventDefault();
		});

		$('.events_accordion_trigger').click(function() {
			//Call back prevents a bouncing issue in IE 7
			$(this).toggleClass('expanded').prev().slideToggle('slow', function(){ if($(this).css('display') === 'block'){ $(this).css({'display':'inline-block'}); }});
			if( $(this).hasClass('expanded') ) {
				$(this).html('Collapse details');
			} else {
				$(this).html('Expand details');
			}
			return false;
		});

		$('.events_accordion_trigger_noicon').click(function(e) {
			$(this).prev().slideToggle('slow');
			return false;
		});


		$('.events_accordion').find('h4').find('a').click(function() {
			var event_tiny_link = $(this).closest('.events_accordion').find('.events_accordion_trigger');
			event_tiny_link.toggleClass('expanded').prev().slideToggle('fast');
			if( event_tiny_link.hasClass('expanded') ) {
				event_tiny_link.html('Collapse details');
			} else {
				event_tiny_link.html('Expand details');
			}
			return false;
		});


		if($('body').attr('id') == "home") {
			$(".jcarousel").jcarousel({
				scroll: 1,
				auto: 4,
				wrap: 'circular',
				initCallback: carouselSetup,
				itemLoadCallback: carouselNext,
				buttonNextHTML: null,
				buttonPrevHTML: null
			});
		} else {
			$(".jcarousel").jcarousel({
				scroll: 1,
				wrap: 'circular',
				initCallback: carouselSetup,
				itemLoadCallback: carouselNext,
				buttonNextHTML: null,
				buttonPrevHTML: null
			});
		}



		$(".jcarousel_sm").jcarousel({
			scroll: 1,
			wrap: 'circular',
			initCallback: sideCarouselSetup,
			buttonNextHTML: null,
			buttonPrevHTML: null
		});

		if($("#module_newsletter_field").length) {
			var defaultText = $("#module_newsletter_field").attr("value");
			$("#module_newsletter_field").bind('focus', function(event) {
				if( $("#module_newsletter_field").attr("value") == defaultText ) {
					$("#module_newsletter_field").attr("value", "");
				}
			});

			$("#module_newsletter_field").bind('blur', function(event) {
				if( $("#module_newsletter_field").attr("value") == "" ) {
					$("#module_newsletter_field").attr("value", defaultText);
				}
			});
		}


		// Agency Locator Map
		if($('#agencyLocatorSearchForm').length > 0){
			gmaps.init();
			agency.list.init();
		}

		$('.eh').equalHeights();


		$('.meal_pulldown').change(function(){
			var num = $(this).attr('num');
			switch($(this).val()) {
				case 'Breakfast':
					$('#meal_item_'+num).html('<option value="Cheerios">Cheerios</option><option value="Wheaties">Wheaties</option>');
					$('#meal_item_'+num).parent().removeClass('hidden');
					break;
				case 'Lunch':
					$('#meal_item_'+num).html('<option value="Cheese Sandwich">Cheese Sandwich</option><option value="Hamburger Patty">Hamburger Patty</option><option value="Tuna Salad Sandwich">Tuna Salad Sandwich</option><option value="Turkey and Cheese Sandwich">Turkey &amp; Cheese Sandwich</option>');
					$('#meal_item_'+num).parent().removeClass('hidden');
					break;
				case 'Dinner':
					$('#meal_item_'+num).html('<option value="BBQ Chicken">BBQ Chicken</option><option value="Chicken Broccoli and Ziti">Chicken Broccoli and Ziti</option><option value="Chicken Hot Dog">Chicken Hot Dog</option><option value="Chicken Noodle Soup">Chicken Noodle Soup</option><option value="Oven Fried Chicken">Oven Fried Chicken</option><option value="Oven Fried Fish">Oven Fried Fish</option><option value="Ravioli">Ravioli</option><option value="Taco Pie">Taco Pie</option><option value="Tuna Mac Casserole">Tuna Mac Casserole</option><option value="Turkey Meatloaf">Turkey Meatloaf</option>');
					$('#meal_item_'+num).parent().removeClass('hidden');
					break;
				default:
					if (!$('#meal_item_'+num).parent().hasClass('hidden')) {
						$('#meal_item_'+num).parent().addClass('hidden');
					}
			}
		});

	});

	function carouselSetup(carousel) {

		$('.carousel li').show();

		var slider = carousel.list.closest('.carousel');

		slider.find('.jcarousel-control').find('li:eq(0)').addClass('currentSlide');

		slider.find('.jcarousel-control').find('a').bind('click', function(event) {
			slider.find('.jcarousel-control').find('li').each(function(index) {
				$(this).removeClass('currentSlide');
			});

			$(this).closest('li').addClass('currentSlide');

			carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
			event.preventDefault();
	    });

		/*	Uses jCarousel's next() function call because we want the transition to always be circular. Previously, we
			were having the carousel "rewind" to the beginning -to the first item. That's why we used scroll(). See
			SVN log for details on how this used to work. */
	    slider.find('.next').bind('click', function(event) {
			carousel.next();
			event.preventDefault();
	    });

	    slider.find('.prev').bind('click', function(event) {
			carousel.prev();
			event.preventDefault();
	    });
	};

	function carouselNext(carousel) {
		var slider = carousel.list.closest('.carousel');
		// mod by the size of the carousel to keep the position accurate (otherwise is continues incrementally).
		var sliderPos = (carousel.first - 1) % carousel.size();
		var newCaption = slider.find('.jcarousel').find('li:eq(' + sliderPos + ')').find('.caption').html();

		slider.find('.jcarousel-control').find('li').each(function(index) {
			$(this).removeClass('currentSlide');
		});

		slider.find('.jcarousel-control').find('li:eq(' + sliderPos + ')').addClass('currentSlide');

		slider.find(".caption_display").fadeOut(250, function() {
			$(this).html(newCaption).fadeIn(250);
		});
	}

	function sideCarouselSetup(carousel) {
		var slider = carousel.list.closest('.carousel_side');

	    slider.find('.next').bind('click', function(event) {
			carousel.next();
			event.preventDefault();
	    });

	    slider.find('.prev').bind('click', function(event) {
			carousel.prev();
			event.preventDefault();
	    });
	}

