(function($){
	$.fn.extend({
		gMapit: function(){
			if (GBrowserIsCompatible()) {
				// set up the basic map
				var map = new GMap2(this[0]);
				// send dummy location to be overwritten at the function end
				map.setCenter(new GLatLng(0, 0), 0);
				map.setUIToDefault();

				// start building the marker icon
				var mapIcon = new GIcon(G_DEFAULT_ICON);
				// add the icon to the marker options
				var markerOptions = { icon:mapIcon };
				// prepare the map boundary
				var latLngBounds = new GLatLngBounds();

				// grab different vcards based on whether in individual location page or index page
				var $vcard,
					doBubble = true;
				if ((this[0].id.indexOf('sub') > 0)) {
					$vcard = $('#main.vcard');
					doBubble = false;
				} else {
					$vcard = $('.vcard');
				}

				// drop markers on the map and connect side menu to map
				$vcard.each(function() {
					var menuLink = jQuery('.m', this);

					// set up marker information
					var point = new GLatLng(parseFloat(jQuery('.latitude', this).text()), parseFloat(jQuery('.longitude', this).text()));
					var marker = new GMarker(point, markerOptions);

					if (doBubble) {
						var bubbleText = $(this).html();

						// when the map marker is clicked, pop up a text bubble
						GEvent.addListener(marker, 'click', function() {
							marker.openInfoWindowHtml(bubbleText);
						});

						// when the side menu is clicked, do the same as above
						menuLink.click(function() {
							marker.openInfoWindowHtml(bubbleText);
							return false;
						});
					}

					// attach the markers to the map
					map.addOverlay(marker);
					
					// add to the map boundary
					latLngBounds.extend(point);
				});

				// make sure we don't zoom in too close
				var mapZoom = map.getBoundsZoomLevel(latLngBounds);
				mapZoom = mapZoom < 14 ? mapZoom : 14;
				// center the map
				map.setCenter(latLngBounds.getCenter(), mapZoom);
			}
		},

		drop_down_nav: function() {
			var timeout = 500,
				closetimer = 0,
				$nested_ul = 0,
				$el = $('> li', this);

			$el
				.bind('mouseover', ddnav_open)
				.bind('mouseout', ddnav_timer);

			function ddnav_open() {
				ddnav_canceltimer();
				ddnav_close();
				$nested_ul = $('ul', this).css('visibility', 'visible');
			}

			function ddnav_close() {
				if ($nested_ul) {
					$nested_ul.css('visibility', 'hidden');
				}
			}

			function ddnav_timer() {
				closetimer = window.setTimeout(ddnav_close, timeout);
			}

			function ddnav_canceltimer() {
				if (closetimer) {
					window.clearTimeout(closetimer);
					closetimer = null;
				}
			}

			document.onclick = ddnav_close;
		},

		navigate_gallery: function(){
			var $wrap_el = $(this);

			// send all the fancy jQuery Tools stuff to the API
			window.api = $wrap_el
				.scrollable({ size:1, speed:1000 })	// show only 1 image at a time, ease transition over 1 second
				.circular() // when the slides reach the end, start over
				.autoscroll({ api:true, interval:5000 }); // auto slide show with 5 seconds per frame

			// create a container for our navigation
			var phoga_nav = $('<div id="photo_gallery_nav"></div>');
			// start adding clickable links
			$('<a class="prevPage browse left" title="go to previous image">Previous</a>').click(function(){ api.move(-1); }).appendTo(phoga_nav);
			$('<a id="phoga_play" title="play slide show">Play</a>').click(function(){ api.play(); }).appendTo(phoga_nav);
			$('<a id="phoga_pause" title="pause slide show">Pause</a>').click(function(){ api.pause(); }).appendTo(phoga_nav);
			$('<a class="nextPage browse right" title="go to next image">Next</a>').click(function(){ api.move(1); }).appendTo(phoga_nav);
			// attach our nav container to the wrapper element
			$wrap_el.after(phoga_nav);
		},

		togglefy: function(toggle_text) {
			if ( $(this).length ) {
				var $el = $(this),
					$elParent = $el.parent();

				$('p', $elParent).addClass('togglish').hide();

				$elParent.each(function(i){
					var $hid = $('p', this);

					// add a toggle to the bio name
					$(' <small class="row_trigger">[+] show ' + toggle_text + '</small>').click(function(){
							$hid.slideToggle('hide');
						}).toggle(
					        function(){
								$(this).text('[-] hide ' + toggle_text);
							},
							function(){
								$(this).text('[+] show ' + toggle_text);
							}
					    ).appendTo($el[i]);
				});
			}
		},

		toggle_forms: function() {
			// choices match the form [contact_form_]ID pattern
			var $forms_wrap	= $(this),
				$forms		= $('form', $forms_wrap),
				$menu_wrap	= $('#cf_subject'),
				$menu_ul	= $('<ul></ul>');

			// hide all forms except for our default
			$('form:not(.default)', $forms_wrap).addClass('hide');
			// hide the legends while we're at it
			$('legend', $forms).hide();

			// extract the subject from form IDs
			$forms.each(function(){
				var $menu_li = '',
					$this_form = $(this),
					// get the radio labels from the hidden legends
					legend = $('legend', $this_form).text();

				// create a radio menu to hide/show the appropriate form
				$menu_li = $('<li><input type="radio" name="subject" value="' + legend + '" /> ' + legend + '</li>')
					.click(function(){
						// hide all the forms again
						$forms.addClass('hide');
						// show the one we selected
						$this_form.toggleClass('hide');
					})
					// add it to the menu
					.appendTo($menu_ul);
			});
			// lastly, add it all to the form wrapper
			$menu_ul.appendTo($menu_wrap);
		}
	});
})(jQuery);

// load print stylesheet after DOM loads
// use1: jQuery(window).load(function(){loadStylesheet();})
// use2: setTimeout(loadStylesheet, 100);
function loadStylesheet() {
	var link = document.createElement('link');
	link.rel = 'stylesheet';
	link.type = 'text/css';
	link.media = 'print';
	link.href = '/css/print.css';
	document.getElementsByTagName('head')[0].appendChild(link);
}

// load during page render
jQuery(function(){
	// hide/show stuff
	$('.bio_name').togglefy('bio');
	$('.service_title').togglefy('description');
	$('.job_title').togglefy('description');

	// Patients photo gallery
	$('#photo_gallery_wrap').navigate_gallery();

	$('#contact_forms').toggle_forms();

	// Our Team: Clinicians: smoothly open lists
	$('#clinicians li').show('slow');
});

// load after page loads
jQuery(window).load(function(){
	// makes the drop downs work for site navigation
	$('#nav').drop_down_nav();

	// Locations page Google Maps
	if ( $('#map_canvas, #map_canvas_sub').length ) {
		$('#map_canvas, #map_canvas_sub').gMapit();
		$(window).unload(GUnload);
	}

	// Partners Case Studies folding tabs
	$("#accordion").tabs("#accordion div.pane", {tabs: 'h3', effect: 'slide', initialIndex: null});
	
	// Spanish language link tooltip
	$('#spanish_link a').tooltip({ delay:5, effect:'fade', position:'bottom center', relative:true, tip:'#spanish_link_tooltip' })

	loadStylesheet();
});