$(function(){  
	/**
	 * credits for this plugin go to brandonaaron.net
	 * 	
	 * unfortunately his site is down
	 */
	jQuery.fn.extend({
		mousewheel: function(up, down, preventDefault) {
			return this.hover(
				function() {
					jQuery.event.mousewheel.giveFocus(this, up, down, preventDefault);
				},
				function() {
					jQuery.event.mousewheel.removeFocus(this);
				}
			);
		},
		mousewheeldown: function(fn, preventDefault) {
			return this.mousewheel(function(){}, fn, preventDefault);
		},
		mousewheelup: function(fn, preventDefault) {
			return this.mousewheel(fn, function(){}, preventDefault);
		},
		unmousewheel: function() {
			return this.each(function() {
				jQuery(this).unmouseover().unmouseout();
				jQuery.event.mousewheel.removeFocus(this);
			});
		},
		unmousewheeldown: jQuery.fn.unmousewheel,
		unmousewheelup: jQuery.fn.unmousewheel
	});
	
	
	jQuery.event.mousewheel = {
		giveFocus: function(el, up, down, preventDefault) {
			if (el._handleMousewheel) jQuery(el).unmousewheel();
			
			if (preventDefault == window.undefined && down && down.constructor != Function) {
				preventDefault = down;
				down = null;
			}
			
			el._handleMousewheel = function(event) {
				if (!event) event = window.event;
				if (preventDefault)
					if (event.preventDefault) event.preventDefault();
					else event.returnValue = false;
				var delta = 0;
				if (event.wheelDelta) {
					delta = event.wheelDelta/120;
					if (window.opera) delta = -delta;
				} else if (event.detail) {
					delta = -event.detail/3;
				}
				if (up && (delta > 0 || !down))
					up.apply(el, [event, delta]);
				else if (down && delta < 0)
					down.apply(el, [event, delta]);
			};
			
			if (window.addEventListener)
				window.addEventListener('DOMMouseScroll', el._handleMousewheel, false);
			window.onmousewheel = document.onmousewheel = el._handleMousewheel;
		},
		
		removeFocus: function(el) {
			if (!el._handleMousewheel) return;
			
			if (window.removeEventListener)
				window.removeEventListener('DOMMouseScroll', el._handleMousewheel, false);
			window.onmousewheel = document.onmousewheel = null;
			el._handleMousewheel = null;
		}
	};	
	
	//intro animation
	function introAnim() {	
		$("#tagline").delay(1000).animate({opacity: 0}, 700, function() {				
			$('#tagline').attr('src', '/sites/all/themes/vso/images/bg_header_outcome.gif');
			//$('#tagline').delay(300).animate({opacity: 1.0}, 1000, function() {
				$("#header").animate({ 
				    height: "155px"
				}, { 
					duration: 1200, 
					easing: "easeInOutQuad"
				} );	
		
				$("#logo").animate({ 
				    marginTop: "1px",
				    width:	"211px"
				}, { 
					duration: 1200, 
					easing: "easeInOutQuad",
					complete: function() {
						
						$('#logo').attr('src', '/sites/all/themes/vso/images/vso_logo_sml.png');
						
						$("#tagline").css({'left': '-325px', 'bottom' : '-35px'});
						
						$("#tagline").animate({ 
						    opacity: 1.0
						}, { 
							duration: 1500, 
							easing: "easeInOutQuad"
						});
						
						$("#header .contact").animate({ 
						    opacity: 1.0
						}, { 
							duration: 1500, 
							easing: "easeInOutQuad"
						});
					}
				});
			//});
		});			
	}
	
	//switch BG images w/ animation (delay added to start fade after scroll)
	function switchBG(img) {
		if (img == undefined) { img = 'home'; }
		if( $('#bgimg').hasClass('bg_'+img+'') ){
			return;
		} else {		
			$('#bgimg').delay(1500).animate({opacity: 0}, 1000, function() {				
				$('#bgimg').removeClass();
				$('#bgimg').addClass('bg_'+img+'');						
				$('#bgimg').animate({opacity: 1.0}, 1000);
			});	
		}
	}
	
	//hide all 3rd tier menus
	function collapseMenu() {
		$('.pane-nav').each(function(){
			$(this).find('ul li ul').hide();
			$(this).find('ul li ul li ul').hide();
		});
	}
	
	// Go through all the properties of the passed-in object
	function dumpProps(obj, parent) {		
		for (var i in obj) {
		  // if a parent (2nd parameter) was passed in, then use that to
		  // build the message. Message includes i (the object's property name)
		  // then the object's property value on a new line
		  if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
		  // Display the message. If the user clicks "OK", then continue. If they
		  // click "CANCEL" then quit this level of recursion
		  if (!confirm(msg)) { return; }
		  // If this property (i) is an object, then recursively process the object
		  if (typeof obj[i] == "object") {
		     if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
		  }
		}
	}
	
	
	function showMenuTree() {	
		//based on activated lower level menu items...
		$('.pane-current').each(function(){
			//give correct state to their top level nav element
			$(this).closest('.pane').find( '.pane-header a' ).addClass('active_menu');
			
			//give correct state to parent 2nd tier nav item
			$(this).closest('ul').parent().children('a').addClass( 'pane-current' );
			
			//show 3nd teir nav if an element inside of it is activated		
			if ( $(this).closest('ul').is(':hidden') ) { 
				$(this).closest('ul').show();
			} 
			
			//if 2nd teir nav is active, and has 3rd tier children to show, show them
			if ( $(this).parent().find('ul:first').is(':hidden') ) { 
				$(this).parent().find('ul:first').show();
			} 
			
		});
	}
	
	
	//google maps
	function gm_init() {
		
		//check to make sure maps are loaded
		if ( ($("#map_canvas1").length > 0) || ($("#map_canvas2").length > 0) || ($("#map_canvas3").length > 0)) {  
			
			var latlng = new google.maps.LatLng(39.570135,-106.080658);
		    var latlng2 = new google.maps.LatLng(39.641306,-106.380851);
		    var latlng3 = new google.maps.LatLng(39.644131,-106.595578);
		    
		    var link = 'http://maps.google.com/maps?daddr=Peak+One+Drive+Suite+180%E2%80%A8+Frisco,+Colorado+80443&ie=UTF8&ei=Sth_TObZJoqksQOPz-37BA&ved=0CA0Q_AU&hq=&hnear=Peak+1+Cir,+Breckenridge,+Summit,+Colorado+80424&z=16';
			var link2 = 'http://maps.google.com/maps?daddr=108+S.+Frontage+Road+West+Suite+300%E2%80%A8+Vail,+Colorado+81657&amp;sll=39.570129,-106.080662&amp;sspn=0.012058,0.019763&amp;ie=UTF8&amp;hq=&amp;hnear=108+S+Frontage+Rd+W+%23300,+Vail,+Eagle,+Colorado+81657&amp;z=16';
			var link3 = 'http://maps.google.com/maps?daddr=Edwards+Village+B-105%E2%80%A8+Edwards,+Colorado+81632&amp;sll=39.643419,-106.38086&amp;sspn=0.012045,0.019763&amp;ie=UTF8&amp;hq=&amp;hnear=105+Edwards+Village+Blvd,+Edwards,+Eagle,+Colorado+81632&amp;z=16';
		 	
		 	var myOptions = {  zoom: 14,  center: latlng,  disableDefaultUI: true,   mapTypeId: google.maps.MapTypeId.ROADMAP };
		 	var myOptions2 = {  zoom: 14,  center: latlng2,  disableDefaultUI: true,   mapTypeId: google.maps.MapTypeId.ROADMAP };
		    var myOptions3 = {  zoom: 14,  center: latlng3,  disableDefaultUI: true,   mapTypeId: google.maps.MapTypeId.ROADMAP };
		    
		    var map = new google.maps.Map(document.getElementById("map_canvas1"), myOptions);
		    var map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions2);
		    var map3 = new google.maps.Map(document.getElementById("map_canvas3"), myOptions3);
		    
		    var marker = new google.maps.Marker({ position: latlng, map: map  });
		    var marker2 = new google.maps.Marker({ position: latlng2, map: map2  });
			var marker3 = new google.maps.Marker({ position: latlng3, map: map3  });
			
			google.maps.event.addListener(marker, 'click', function() {	  window.open(link);	});
			google.maps.event.addListener(marker2, 'click', function() {  window.open(link2);	});
			google.maps.event.addListener(marker3, 'click', function() {  window.open(link3);	});
		}
	}

	
	
	//used to define a pane other than the one the link was clicked on to load and store data
	cashe_section = '';
	//used to break out of the deep linking functionality if a pane needs to be hidden
	break_now = false;	
	//which section to scroll to
	scroll_to = '';
	
	
	
	//on init setup each panes cashe
	$('.pane').each(function(){
		$(this).data( 'pane', {	
			cache: { '': $(this).find('.pane-default') }	
		});
	});
	
	//top level link functionality
	$('.pane-header a[href^=#]').live( 'click', function(e){		
		//if this panes state is the top level and it's clicked, remove the state from deep links and hide the pane
		if ( $(this).hasClass('pane-current') ) { 
			e.preventDefault();
			$(this).parent().parent().find('.blind').slideUp('slow');
			$(this).removeClass('active_menu');
			parentID = $(this).parent().parent().attr('id');
			$.bbq.removeState(parentID);
			break_now = true;
		} else {		
			$(this).addClass('active_menu');		
			break_now = false;		
			var state = {},		  
			// Get the id of this .bbq widget.
			id = $(this).closest( '.pane' ).attr( 'id' ),			
			// Get the url from the link's href attribute, stripping any leading #.
			url = $(this).attr( 'href' ).match( /[^#]+$/).toString();
			//set the sectin to scroll to
			scroll_to = id;				  
			// Set the state!
			state[ id ] = url;
			$.bbq.pushState( state );
			//hide only expanded 2nd teir menus in this pane
			$(this).parent().parent().find('ul li ul').hide();
			//switch the background img
			switchBG(id);		
		}
		// And finally, prevent the default link click behavior by returning false.
		return false;
	});
	
	
	//pane-nav menu item link functionality
	$('.pane-nav a[href^=#]').live( 'click', function(e){		
		
		//special case for expanding/contracting news archives
		if (!$(this).hasClass('news_archive')) {		
			var state = {},		  
			// get the id of this .bbq widget.
			id = $(this).closest( '.pane' ).attr( 'id' ),		  
			// get the url from the link's href attribute, stripping any leading #.
			url = $(this).attr( 'href' ).match( /[^#]+$/).toString();		  
			// set the bbq state
			state[ id ] = url;
			$.bbq.pushState( state );
			
			//collapse 2nd tier menu of this pane, and then show the active 3rd tier portions (if there are any)
			$(this).closest('.pane-nav').find('ul li ul').hide();		
			
			//1st tier
			if ( $(this).parent().find('ul:first').is(':hidden') ) { 	$(this).parent().find('ul:first').show();	} 	
			//2nd tier
			if ( $(this).closest('ul').is(':hidden') ) { 		$(this).closest('ul').show();		}
			//3rd tier
			if ( $(this).closest('ul').parent().closest('ul').is(':hidden') ) { $(this).closest('ul').parent().closest('ul').show();  }			
			
			return false;		
		} else {
			e.preventDefault();
			$this = $(this);			
			
			//display all stories listed under this year
			$('#news_stories li').each(function(){
				if ($(this).attr('rel') == $this.html()) {
					$(this).toggle();
				}
			});
			
		}
	});	
	
	function handleInterLinks(section, e, skip) {
		//define which pane content is to be loaded into
		cashe_section = section;	
		//define state and url
		var state = {},	  
		id = section,			
		url = e.target.toString();
		url = url.match( /[^#]+$/).toString();	
		
		//skip if it's a self referencing link
		if (skip != true) {				
			//set the sectin to scroll to
			scroll_to = id;
			//switch bg
			switchBG(id);
		}
		
		//redundant scroll_to handing for cashed inter-linking
		if (scroll_to != '') {
			$('html, body').animate({ scrollTop: $('#'+scroll_to+'').offset().top }, 1500);	
			scroll_to = '';
		}
		
		//add active state to opened pane
		$('#'+id+' .pane-header a').addClass('active_menu');				
		//set the state	
		state[ id ] = url;
		$.bbq.pushState( state );
		
		//collapse 2nd tier menu of this pane, 
		//and then show the active 3rd/4th tier portions (if there are any) (on a delay to allow BBQ to add classes)
		$('#'+id+' .pane-nav').find('ul li ul').hide();		
		window.setTimeout(function() {		    
		    $('#'+id+' .pane-nav .pane-current').parent().find('ul:first').show();
		    $('#'+id+' .pane-nav .pane-current').closest('ul').show();
		    $('#'+id+' .pane-nav .pane-current').closest('ul').parent().closest('ul').show();
		    //possible tmp fix for interlinks not revealing their content
		    $('#'+id+' .blind').slideDown('slow');
		}, 100);		
	}	
	
	//links loading content into a pane other than the link origin pane - defined by their css class
	$('.outcome_link').live( 	'click', function(e){	handleInterLinks('outcome', e);		return false;	});
	$('.treatment_link').live( 	'click', function(e){	handleInterLinks('treatment', e);	return false;	});	
	$('.doctors_link').live( 	'click', function(e){	handleInterLinks('doctors', e); 	return false;	});
	$('.details_link').live( 	'click', function(e){	handleInterLinks('details', e);		return false;	});	
	$('.community_link').live( 	'click', function(e){	handleInterLinks('community', e); 	return false;	});
	$('.contact_link').live( 	'click', function(e){	handleInterLinks('contact', e); 	return false;	});
	//load a link from outside the menu into the current pane
	$('.self_link').live( 		'click', function(e){	
		curid = $(this).closest('.pane').attr('id');
		handleInterLinks(curid, e, true); 
		return false;	
	});
	
	//collapse all button
	$('.collapse_button').click(function() {	
		$('.blind').slideUp('slow');
		$( '.active_menu' ).removeClass( 'active_menu' );
		scroll_to = 'header';
		$.bbq.removeState('outcome');
		$.bbq.removeState('treatment');
		$.bbq.removeState('doctors');
		$.bbq.removeState('details');
		$.bbq.removeState('community');
		$.bbq.removeState('contact');
		break_now = true;		
		switchBG();
		Cufon.refresh();
		return false;
	});		
	
	//make listings of doctors and paitent stories clickable
	//built off of function handleInterLinks()
	$('.listing_item').live('click', function(e) {
		//aquire current section, which will be the section content is loaded in		
		cashe_section = $(this).closest('.pane').attr('id');	
		
		//define state and url
		var state = {},	  
		id = $(this).closest('.pane').attr('id'),			
		url = $(this).find('.learn').attr('href').toString();
		url = url.match( /[^#]+$/).toString();			
	
		//add active state to opened pane
		$('#'+id+' .pane-header a').addClass('active_menu');				
		//set the state	
		state[ id ] = url;
		$.bbq.pushState( state );
		
		//collapse 2nd tier menu of this pane, 
		//and then show the active 3rd/4th tier portions (if there are any) (on a delay to allow BBQ to add classes)
		$('#'+id+' .pane-nav').find('ul li ul').hide();		
		window.setTimeout(function() {		    
		    $('#'+id+' .pane-nav .pane-current').parent().find('ul:first').show();
		    $('#'+id+' .pane-nav .pane-current').closest('ul').show();
		    $('#'+id+' .pane-nav .pane-current').closest('ul').parent().closest('ul').show();
		}, 100);		
	}); 	
	
	//add hash to drupal generated menus -> hopeful backwards compatability for no JS
	$('.pane-nav a').each(function(){
		href = '#';
		href += $(this).attr('href');
		$(this).attr('href', href);
	});		
	
	//bind hashchange event 
	$(window).bind( 'hashchange', function(e) {	
		// Iterate over all .bbq widgets.
		$('.pane').each(function(){	
			
			//if content needs to be loaded into a section that the link is not currently in...
			switch(cashe_section) {
				case 'outcome': 	var that = $('#outcome');	break;
				case 'treatment':	var that = $('#treatment');	break;
				case 'doctors':		var that = $('#doctors');	break;
				case 'details':		var that = $('#details');	break;
				case 'community':	var that = $('#community');	break;
				case 'contact':		var that = $('#contact');	break;
				default:			var that = $(this);
			}
			
			//reset the pane to add cashed items to
			cashe_section = '';
			
			//get stored data	
			data = that.data( 'pane' );		
			
			// Get the url for this .bbq widget from the hash, based on the appropriate id property. 
			url=$.bbq.getState( that.attr( 'id' ) ) || '';				
			
			// If the url hasn't changed, do nothing and skip to the next .bbq widget.
			if ( data.url === url ) { return; }		
			
			// Store the url for the next time around.
			data.url = url;
			
			// Remove .bbq-current class from any previously "current" link(s).
			that.find( 'a.pane-current' ).removeClass( 'pane-current' );
			
			// Hide any visible ajax content.
			that.find( '.pane-content' ).children( ':visible' ).hide();
			//re-show the collapse all button, for easiness sake
			that.find( '.pane-content .collapse_button' ).show();
			
			// Add .bbq-current class to "current" nav link(s), only if url isn't empty.
			url && that.find( 'a[href="#' + url + '"]' ).addClass( 'pane-current' );
			//also add current class to any parent subnav item (and subsub nav items)
			that.find( 'a[href="#' + url + '"]' ).parent().closest('ul').parent().children('a').addClass( 'pane-current' );
			that.find( 'a[href="#' + url + '"]' ).parent().closest('ul').parent().closest('ul').parent().children('a').addClass( 'pane-current' );
			
			//redundant hiding of menus to support back button
			that.find('ul li ul').hide();
			that.find('ul li ul li ul').hide();
			
			//redundant showing of 1st, 2nd, 3rd tier menu items to support back button
			that.find( 'a[href="#' + url + '"]' ).parent().find('ul:first').show();				
			that.find( 'a[href="#' + url + '"]' ).closest('ul').show();				
			that.find( 'a[href="#' + url + '"]' ).closest('ul').parent().closest('ul').show(); 			
			
			
			//show cashed content if a cashed version exists
			if ( data.cache[ url ] ) {
				data.cache[ url ].show();
				//if break_now is false then show the desired pane (it is true if a top level menu item is hiding itself)
				if ( break_now == false ) {
					that.find('.blind').slideDown('slow');
				}	
			} else {			
				// Show "loading" content while AJAX content loads.
				that.find( '.pane-loading' ).show();				
				// add container for cashed ajax items
				data.cache[ url ] = $( '<div class="pane-item"/>' )				  
				  // Append the content container to the parent container.
				  .appendTo( that.find( '.pane-content' ) )				  
				  // AJAX call
				  .load( url + " #ajax_content", {request: 'ajax'}, function(){
				    
				    //show dr tabs
				    $("ul.tabs").tabs("> .tab-pane");
				    // Content loaded, hide "loading" content and reveal content section
				    that.find( '.pane-loading' ).hide();		    
				    that.find('.blind').slideDown('slow');			    
				    
				    
				    //google maps for contact page
				    gm_init()				    
				    
				    // A custom "onReady" function for AddToAny
					function my_addtoany_onready() {
					    a2a_config.target = '.share-button';
					    a2a.init('page');
					}
					
					// Setup AddToAny "onReady" callback
					var a2a_config = {
					    tracking_callback: {ready: my_addtoany_onready}
					};
					
					// Load AddToAny script asynchronously
					(function(){
						
					    var a = document.createElement('script');
					    a.type = 'text/javascript';
					    a.async = true;
					    a.src = 'http://static.addtoany.com/menu/page.js';
					    var s = document.getElementsByTagName('script')[0];
					    s.parentNode.insertBefore(a, s);
					    //alert('');
					})();
					
				    
				    
				    
				    
				    
				    //init shadowbox for ajax items
				    Shadowbox.setup("a.procedure_video", {
				        width:  701,
				        height: 557
				    });	
				    Shadowbox.setup("a.youtube_video", {
				        width:  640,
				        height: 390
				    });				    
				  });
			}
						
			//adding compatability for forward and backward buttons to hide/show panes 
			//when their hash is removed from the query string
			if (url == '') {
				$('#'+that.attr('id')+'').find('.pane-header a').removeClass('active_menu');
				//add timeout so only visible panes will the rolled up on load
				window.setTimeout(function() {		    
				   $('#'+that.attr('id')+'').find('.blind:visible').slideUp('slow');
				}, 100);
			//forward button compatabilty
			} else {
				$('#'+that.attr('id')+'').find('.pane-header a').addClass('active_menu');
			}			
			
			//scroll window to loaded / cashed content
			if (scroll_to != '') {
				$('html, body').animate({ scrollTop: $('#'+scroll_to+'').offset().top }, 1500);	
				scroll_to = '';
			}
			Cufon.refresh();

		});
	});
	
	//trigger hash event when the window loads incase there's a hash in there
	$(window).trigger( 'hashchange' );
	
	//on page init
	$(document).ready(function(){
		Cufon.replace('h3.pane-header', {
			hover: {
				color: '#2a81d2'
			}
		});
		//Cufon.replace('#header .contact');
		//hide all panes
		$('.blind').hide();
		
		//hide header contact to allow it to animate in
		//$('#header .contact').css({ opacity: 0 });
		
		//shadowbox
		Shadowbox.init();
		
		//stop scrolling from fighting you if user mousewheels while scroll_to animation is in progress
		$('body').mousewheel(function(){
		    if ('body:animated') {
		    	$('html, body').stop();
		    }
		});		
	});
	
	$(window).load(function () {
		//preload section BG images after page has loaded
		var preloadImgs=["vso_logo_sml.png", "bg_outcome.jpg","bg_treatment.jpg", "bg_doctors.jpg", "bg_details.jpg", "bg_community.jpg", "bg_contact.jpg"];
		$.each(preloadImgs, function(key, value) {
			var img = new Image();
			img.src = '/sites/all/themes/vso/images/'+value;	
			//force firefox preload properly		
			$(document).append(img);
			//all other browsers
			return img;
		});		 
		
		//hide 3rd teir menu
		collapseMenu();		
		
		//on load give all currently open panes the correct style		
		//search through panes and give lower level menus active state - this needs to be called on load as all ajax is loaded at this point
		$('.pane').each(function(){
			var that = $(this);
			url=$.bbq.getState( that.attr( 'id' ) ) || '';
			that.find( 'a[href="#' + url + '"]' ).addClass( 'pane-current' );
		});				
		
		showMenuTree();		
		
		Cufon.refresh();
		
		//introAnim();
		/*
		//Gottlieb farewell		
		Shadowbox.open({
	        content:    '<div id="farewell"><img src=/sites/all/themes/vso/images/gottlieb_farewell.jpg alt="Gottlieb Farewell" /></div>',
	        player:     "html",
	        title:      "Congratulations Dr Gottlieb",
	        height:     793,
	        width:      1100,
	        handleOversize: 'none'
	    });		    
	    $('#farewell').live('click', function(e) {		
			Shadowbox.close();
		});	
		*/
		
	});				
		
});
	
