// hovering boxes on bios and cases
var isMobile = false;


function hoverBoxes()
{
	var $hoverLinks = $('#bioList').find('.bioname a:first-child');
	
	if( !$hoverLinks.length )
		return;
	
	var hoverTimeout = null;
	var $hoverBox = $("<div id='hoverBox'></div>").hide().appendTo('body');
	
	$hoverLinks
	.mouseover(function(e){
		
		var $this = $(this);
		$hoverBox.hide();
		clearTimeout(hoverTimeout);

		if( !$this.data('snippet') )
		{
			var snippetURL = this.href.replace('.html', ',snippet.html');
			$this.data('hoverWaiting', true);
			
			$.get(snippetURL, function(data){
				$this.data('snippet', data);
				
				if( $this.data('hoverWaiting') )
					$this.mouseover();
			});
			
			return;
		}
		
		// make the top of the hover box line up with the link
		var newTop = $this.offset().top-9;
		
		// put the fetched html into the hover box
		// and reset the background position
		$hoverBox
		.html($this.data('snippet'))
		.css({
			top: newTop,
			backgroundPosition: '0 0'
		})
		.fadeIn('fast');
		
		// see how much we're hanging over the bottom
		var newBottom = newTop + $hoverBox.outerHeight();
		var scrollTop = $(window).scrollTop();
		var overBottom = newBottom - $(window).height() - scrollTop;
		
		// if we're hanging over the bottom, figure out a new top
		if( overBottom > 0 )
		{
			oldTop = newTop;
			
			// make sure the new top does go above the viewport
			// give a 2-pixel distance from the top or bottom
			newTop = Math.max(scrollTop + 2, newTop-overBottom - 2);
			
			// move the hover box, and change the background arrow position
			$hoverBox.css({
				top: newTop,
				backgroundPosition: "0 "+ (oldTop-newTop) +"px"
				});
		}
		
	});
	
	// if you hover the box, clear the timeout
	$hoverBox.mouseover(function(){
		clearTimeout(hoverTimeout);
	});
	
	// if they mouse out of the box or the link, set a fade out
	$hoverLinks.add($hoverBox).mouseout(function(){
		
		$(this).data('hoverWaiting', false);
		hoverTimeout = setTimeout(function(){
			$hoverBox.fadeOut();
		}, 900)
		
	});
}

function getPostLink(id)
{
	output = $('#blogpost_'+id+' h1 a').attr('href');
	
	if( !output )
		output = document.location.href;
		
	return output;
}

function getPostTitle(id)
{
	return $('#blogpost_'+id+' h1').text();
}


function animateSidebars()
{
	// first, wrap those silly text nodes in a paragraph
	var sidebars = $("#expandingSidebar, #navExpandingSidebar .expandable");
	
	sidebars.contents()
	.not("[nodeType=1]")
	.wrap('<p class="textNodeWrapper" />');
	
	// now, get rid of the text nodes wrappers that are just whitespace
	$('p.textNodeWrapper', sidebars)
	.filter(function(){ return !jQuery.trim($(this).text()) })
	.remove();
	
	sidebars.children('br')
	.remove();
	
	// animate expanding sidebars
	jQuery(function(){
		
		$("#expandingSidebar h3, #navExpandingSidebar h3")
		.mouseover(function(){ $(this).addClass('hover') })
		.mouseout(function(){ $(this).removeClass('hover') })
		
		var sidebars = $("#expandingSidebar, #navExpandingSidebar .expandable");
		$('h3', sidebars)
		.click(function(event, instant){
				
				if( instant )
					speed = '1';
				else if(event.originalEvent && 
					event.originalEvent.shiftKey)
					speed = 1800;
				else
					speed = 'medium';
				
				if(event.originalEvent && 
					event.originalEvent.altKey)
		            what = $('h3', sidebars)
		        else
		        	what = $(this);
		        
		        if( what.hasClass('expanded') )
		        {
		        	what.each(function(){
		        		$(this).removeClass('expanded') // remove the expanded class
			        	.nextAll().each(function(){ 
			        		// keep going until we hit the next header
			        		if( $(this).is('h3') )
			        			return false;
			        		else
			        			$(this).slideUp(speed)
		        		});
		        	});
		        }
		        else
		        {
		        	what.each(function(){
		        		$(this).addClass('expanded') // add the expanded class
			        	.nextAll().each(function(){ 
			        		// keep going until we hit the next header
			        		if( $(this).is('h3') )
			        			return false;
			        		else
			        		{
			        			$(this).find('*').show();
			        			
			        			if( instant )
			        				$(this).show();
			        			else
				        			$(this).slideDown(speed)
			        		}	
		        		});
		        	});
		        }
		        
		        $(this).removeClass('hover')
		});
		
		$('h3 a', sidebars)
		.click(function(event){
			event.stopPropagation();
		})
		.mouseover(function(event){
			event.stopPropagation();
		});

		
		// now expand these
		$toClick = $('h3:contains(Industries):not(:contains(Associated)), '+
			'h3:contains(Practices):not(:contains(Associated)), '+
			'h3:contains(Education), '+
			'h3:contains(Press Room Contact), '+
			'h3:contains(Categories), '+
			'h3:contains(Recent Posts)',
			sidebars)
		
		// expand people only on pubs
		.add('.pressroom #expandingSidebar > h3:contains(People)')
		// expand all for inmotion
		.add('#inmotion #expandingSidebar > h3')
		// expand all on practices and industries
		.add('body.practices #expandingSidebar > h3')
		.add('body.industries #expandingSidebar > h3')
		
		// now open them
		.trigger('click', [true]);
	});
}

function animateMultiList()
{
	// animate multi lists sidebars
	jQuery(function(){
		
		// remove the arrow from items
		$('#contentMain > div.multiListBox li.prac_bullet_child')
		.prev('.prac_bullet_parent')
		.addClass('hasChildren')
		//.attr('title', 'hold ALT while clicking to expand/contract all items')
		.hover(function(){ $(this).addClass('hover') },
			function(){ $(this).removeClass('hover') })
		.click(function(event, instant){
				
				if( instant )
					speed = '1';
				else if(event.originalEvent && 
					event.originalEvent.shiftKey)
					speed = 1800;
				else
					speed = 'medium';
				
				if(event.originalEvent && 
					event.originalEvent.altKey)
				{
		            what = $('#contentMain > div.multiListBox li.prac_bullet_parent.hasChildren')
				}
				else
		        	what = $(this);
		        
		        if( $(this).hasClass('expanded') )
		        {
		        	what.each(function(){
		        		$(this).removeClass('expanded') // remove the expanded class
			        	.nextAll().each(function(){ 
			        		if( $(this).is('.prac_bullet_parent') )
			        			return false;
			        		else
			        			$(this).slideUp(speed)
		        		});
		        	});
		        }
		        else
		        {
		        	what.each(function(){
		        		$(this).addClass('expanded') // remove the expanded class
			        	.nextAll().each(function(){ 
			        		if( $(this).is('.prac_bullet_parent') )
			        			return false;
			        		else
			        		{
			        			if( instant )
			        				$(this).show();
			        			else
				        			$(this).slideDown(speed)
			        		}
		        		});
		        	});
		        }
		        
		        $(this).removeClass('hover')
		});
		
		$('#contentMain > div.multiListBox a')
		.click(function(event){
			event.stopPropagation();
		})
		.mouseover(function(event){
			event.stopPropagation();
		});
	});
}

// function stolen from http://blog.deconcept.com/code/qtobject/qtobject.html
// for detecting quicktime
function isQTInstalled() {
	
	var qtInstalled = false;
	qtObj = false;
	if (navigator.plugins && navigator.plugins.length) {
		for (var i=0; i < navigator.plugins.length; i++ ) {
         var plugin = navigator.plugins[i];
         if (plugin.name.indexOf("QuickTime") > -1) {
			qtInstalled = true;
         }
      }
	} else if(jQuery.browser.msie) {
		execScript('on error resume next: qtObj = IsObject(CreateObject("Quicktime.Quicktime"))','VBScript');
		qtInstalled = qtObj;
	}

	return qtInstalled;
}

function startRotatingBox( boxObj )
{
	var divToFade = $(boxObj).children('div:last');
	
	if( $(boxObj).data('started') )
	{
		divToFade.fadeOut('slow', function(){
			$(this).parent().prepend(this);
			$(this).fadeIn(0);			
		})
	}
	else
	{
		$(boxObj).data('started', true);
		$(boxObj).children('div').css('display','block');
	}
	
	divToFade.animate({opacity: 1.0}, 4000, function(){
		startRotatingBox( $(this).parent() )
	});
}

function embedVideo(selector, options)
{
	if((navigator.userAgent.match(/(iPhone|iPod)/i)))
		return;
		
	if( window.location.search == '?forcelink' )
		return;
	
	var smallBox = !!options['smallBox'];
	var bigVideo = !!options['bigVideo'];
	
	var stretching = 'exactfit';
	
	if( options['stretching'] )
		stretching = options['stretching'];
				
	
	var useqt;
	
	// magically embed Flash/Quicktime player for video links
	// using jquery, swfobject, and jquery.media
	// tested in Firefox, Safari, iPhone, Opera, IE6, and IE7
	// with and without QT/Flash/Javascript - degrades gracefully
	
	$.fn.media.defaults.flashVersion = "9.0.115";
	$.fn.media.defaults.expressInstaller = "i/expressInstall.swf";
	$.fn.media.defaults.flvPlayer = "i/player-custom.swf";
	
	// make mp4s default to playing just live FLVs
	$.fn.media.mp4 = $.fn.media.flv;
	
	// figure out which player to use
	if( window.location.search == '?forceqt' )
		useqt = true;
	else if( window.location.search == '?forceflash' )
		useqt = false;
	else if( jQuery.browser.mozilla ) // firefox has issues with qt
		useqt = false;
	else if( !swfobject.hasFlashPlayerVersion("7") )
		useqt = true;
	else
		useqt = false;
		
	// if we have quicktime, use that as the default
	if( useqt )
	{
		$.fn.media.mapFormat('mp4', 'quicktime');
		$.fn.media.mapFormat('jpg', 'quicktime');
		var theWidth = 234;
		var theHeight = 152;
		var theClass = 'qtMovie';
	}
	else
	{
		var theWidth = 234;
		var theHeight = 157;
		var theClass = 'flashMovie';
	}
	
	if( smallBox )
	{
		theWidth = 179;
		theHeight = 124;
	}
	
	if( bigVideo )
	{
		theWidth = 320;
		theHeight = 250;
	}
	
	if( options['width'] )
		theWidth = options['width'];
		
	if( options['height'] )
		theHeight = options['height'];
		
	if(smallBox)
		options['nocontrols'] = true;
		
	// remove onclick event, remove "target", and embed media
	$(selector).children('a:first-child').each(function(){
		thumbnail = $('img', this).attr('src');
		
		attrs = {
				showlogo: 'false',
				controller: !options['nocontrols'],
				enablejavascript: true,
				qtsrc: thumbnail,
				qtnext1: '<'+this.href+'> T<myself>',
				qtnext2: '<'+thumbnail+'> T<myself>',
				'class': theClass,
				onmouseup: 'playMovie(this)',
				wmode: 'transparent',
				allowfullscreen: 'true'
			}
		
		$(this)
		.unbind('click')
		.media({ 
			width: theWidth, 
			height: theHeight,
			attrs: attrs,
			params: attrs,
			autostart: !!options['autoplay'],
			flashvars: {
				autostart: !!options['autoplay'],
				image: thumbnail,
				controlbar: (options['nocontrols']) ? 'none' : 'bottom',
				showicons: false,
				displayclick: 'none',
				stretching: stretching,
				screencolor: 'ffffff',
				bufferlength: '4'
			}
		});
	});
	
	// add video controls box
	if( smallBox )
	{
		$('<a class="vidControls" />')
		.click(function(){
			$(this).prev().children('object, embed').trigger('mouseup');
		})
		.appendTo(selector);
	}
}

function playMovie( obj, x )
{
	var playing = ($(obj).data('playing') == true);
	
	if( typeof(obj.sendEvent) == 'undefined' &&
		typeof(obj.Play) == 'undefined'  )
		return;

	if( playing )
	{
		if( $(obj).hasClass('qtMovie') )
			obj.Stop();
		else
			obj.sendEvent('PLAY', false);
			
		$(obj).data('playing', false);
		$('body').data('playingMovie', null);
	}
	else
	{
		// pause the currently playing movie
		if( playingMovie = $('body').data('playingMovie') )
			playMovie( playingMovie);
		
		if( $(obj).hasClass('qtMovie') )
		{
			obj.SetAutoPlay(true);
			obj.Play();
		}
		else
		{
			obj.sendEvent('PLAY', true);
			if( !$(obj).data('hasListener') )
			{
				obj.addModelListener("STATE","stateTracker");
				$(obj).data('hasListener', true);
			}
		}
		
		$(obj).data('playing', true)
		$('body').data('playingMovie', obj);
	}
	
	$(obj).siblings('.vidControls').toggleClass('vidControlsPlaying');			
}


function stateTracker(event)
{ 
	if( event.newstate=='COMPLETED' )
	{
		var obj = $('body').data('playingMovie');
		obj.sendEvent('SEEK', 1);
		obj.sendEvent('PLAY', false);
		
		$(obj).data('playing', false);
		$('body').removeData('playingMovie')
		$(obj).parent().next('a.vidControls').toggleClass('vidControlsPlaying');
	}
};

/*
	adds an "inline label" to form elements
	depends on a real label existing (use css to hide the real label)
*/
function magicInputLabel( selector )
{
	// they want to have default text for name/keyword fields
	// but we don't want that default text submitted
	jQuery(function(){
		$(selector).each(function(){
			
			// get the label text, and add it as a title for the target item
			this.title = $(this).prev('label[for='+this.id+']')
				.text().toLowerCase().replace("andrews kurth", "Andrews Kurth");
			
			// if we have no defaultValue, set one
			if( !this.defaultValue )
			{
				this.defaultValue = this.title;
				this.value = this.defaultValue;
				$(this).addClass('defaultValue');
			}
		})
		
		// add events listeners
		.blur(function(){
			// if the value is empty, set it to the label
			if( !$.trim(this.value) || (this.value == this.title) )
			{
				this.value = this.title;
				$(this).addClass('defaultValue');
			}
		})
		.focus(function(){
			if( this.value == this.title )
			{
				this.value = '';
			}
			$(this).removeClass('defaultValue');
		})
		.parents('form').submit(function() {
			$(selector).each(function(){
				if( this.value == this.title )
					this.value = '';
			});
			return true;
		});
	});
}

/*
	makes the first item of a select be an "inline label"
	depends on a real label existing (use css to hide the real label)
*/
function magicSelectLabel( selector )
{
	jQuery(function(){
		$(selector).each(function(){
			// get the label text, and add it as a title for the target item
			this.title = $(this).prev('label')
				.text().toLowerCase().replace("andrews kurth", "Andrews Kurth");

			// make sure there is an empty value
			if( !$(this).children('option[value=**]').length )
			{
				$("<option value='**'>XX</option>")	
				.prependTo(this);
			}			
			
			// get the first item and change the text
			$(this)
			.children('option[value=**]')
			.text('- '+this.title+' -')
			
			if( this.value = '' )
				this.value = '**';
			
			$(this).addClass('defaultValue');			
		})		
		
		// add events listeners
		.blur(function(){
			// if the value is the default, set the class
			if( this.value == '**' )
			{
				$(this).addClass('defaultValue');
			}
			else
				$(this).removeClass('defaultValue');
		})
	});
}

function addEmailPopup()
{
	$mailLinks = $("#content a[href^=mailto]")
	
	$mailLinks
	.click(function(){
		email = escape(unescape(this.href).substring(7));
		
		emailWindow = window.open("email-popup.html?email=" + email, "EmailNotice",
			"toolbar=no,location=no,directories=no,status=no,scrollbars=no,"+
			"menubar=no,resizable=yes,width=500,height=380");
		
		emailWindow.focus();
		
		return false;
	});	
}

function blogDisclaimer(theLink)
{
	disclaimerWindow = window.open(theLink.href, "BlogNotice",
		"toolbar=no,location=no,directories=no,status=no,scrollbars=no,"+
		"menubar=no,resizable=yes,width=500,height=320");
		
	disclaimerWindow.focus();
		
	return false;
}

function playerReady(obj)
{
	var listener = '';
	
	// we only need this listener on alumni login page
	switch( document.body.id )
	{
		case 'alumni-about-login':
			 listener = "playNextLoginVid";
		break;
		
		case 'alumni-about':
			listener = "playNextServiceVid";
		break;
		
		default: 
		return;
	}
	
	var vid = $('object, embed').get(0);
	
	if( vid )
	{
		$(vid).data('playing', true)
		$('body').data('playingMovie', vid)
		
		vid.addModelListener("STATE", listener)
	}
}

function playNextLoginVid(event)
{
	// if the last video is completed
	if(event.newstate=='COMPLETED')
	{
		// get the next video
		var nextVid = $('.alumniVideo.selected').next('.alumniVideo');
		
		if( !nextVid.length )
			nextVid = $('.alumniVideo:first');
		
		// pick a random one and click it
		nextVid.click()
	}
}

function playNextServiceVid(event)
{
	// if the last video is completed
	if(event.newstate=='COMPLETED')
	{
		var lastplayed = $(window).data('lastplayed');
		
		// get the next video
		if( lastplayed == 'top' )
		{
			var nextVid = $('.alumniVidItem').eq(1);
			lastplayed = 'bottom';
		}
		else
		{
			var nextVid = $('.alumniVidItem').eq(0);
			lastplayed = 'top';
		}
			
		$(window).data('lastplayed', lastplayed);
		
		// click the next one
		nextVid.children('.alumniVideo').click();
	}
}

function alumniLoginVideos()
{
	// this function only used on services and login page
	if( $('#alumni-about-login').length == 0 )
		return;
		
	
	$('.alumniVideo')
	.click(function(){
		
		// fade in all other thumbnail images
		$('.alumniVideo img').fadeTo('fast',1);
		
		$('.alumniVideo').removeClass('selected');
		
		// fade the clicked thumbnail out to show the color underneath
		$(this)
		.addClass('selected')
		.children('img')
		.fadeTo('slow',.5);
		
		// if this video is clicked, write the HTML to the main frame and then
		// embed the flash player there	
		$('#videoFrame').children().remove();
		$('#videoFrame').html("<a href='"+ this.href +"'></a>");
		embedVideo('#videoFrame', {width:360,height:256,nocontrols:true,autoplay:true});
		
		 $('body').data('playingMovie', null)
		 $('#videoPause').removeClass('paused');
		
		return false;
	})
	
	// add play/pause control
	$('#videoPause')
	.click(function(){
		
		playingMovie = $('body').data('playingMovie')
		
		if( !playingMovie )
		{
			playingMovie = $('object, embed').get(0);
			$(playingMovie).data('playing', true);
		}
		
		if( playingMovie )
		{
			playMovie(playingMovie);
			
			if( $(this).hasClass('paused') )
			{
				$(this).fadeOut(1000, function(){
					$(this).removeClass('paused');
					$(this).fadeIn(0);	
				})
			}
			else
			{
				$(this).addClass('paused');	
			}
		}
	});
	
	// if we have no login error, start a video
	if(  !$('#loginError').length )
	{
		$('.alumniVideo:first')
		.click();
	}
}

function alumniServiceVideos()
{
	// this function only used on services and login page
	if( $('#alumni-about').length == 0 )
		return;
	
	// move the first item to the last
	$('.alumniVidItem:last').appendTo('.servicesGallery');
	
	$('.alumniVideo')
	.click(function(){
		
		// fade out all abstracts
		$('.alumniVidItem div')
		.fadeOut('fast')
		
		// hide this thumbnail
		var clickedItem = $(this).parent();
		var lastItem = $('.alumniVidItem:last');
		
		// take all the children and fade them out
		var lastChildren = lastItem.children().hide();
		
		clickedItem
		.children()
		.fadeOut('slow')
		
		clickedItem
		.animate({ dummy: 1 }, 'slow', function(){
			
			clickedItem
			.children()
			.appendTo(lastItem);
						
			lastChildren
			.appendTo(clickedItem)
			.filter('a')
			.fadeIn('slow');
			
			return false;
		});
				
		// if this video is clicked, write the HTML to the main frame and then
		// embed the flash player there	
		$('#videoFrame').children().remove();
		$('#videoFrame').html("<a href='"+ this.href +"'></a>");
		embedVideo('#videoFrame', {width:360,height:256,nocontrols:false,autoplay:true});
		
		// fade in this abstract
		$(this)
		.parent('.alumniVidItem')
		.children('div')
		.fadeIn('slow');
		
		return false;
	})	
	
	$('.alumniVidItem:last .alumniVideo')
	.click()
}

function disableLoginNav()
{
	if( $('#alumni-about-login').length == 0 )
		return;
	
	// disable main nav buttons
	$('#topBlocks a, #footer a[href*=alumni]')
	.removeAttr('onclick')
	.attr('href', '#loginForm')
	.click(function(){
		
		var speed=150;
		var level = .5;
		
		// when clicked, flash the login form by fading in and out
		$('#loginForm')
		.fadeTo(speed, level)
		.fadeTo(speed, 1)
		.fadeTo(speed, level)
		.fadeTo(speed, 1)
	})	
}

function alumniSpotlightGallery()
{
	if( !$('#spotGallery').length )
		return;
		
	$('.spotlightThumb img')
	.click(function(){
		
		// fade out all thumbs but this one
		$('.spotlightThumb img')
		.not(this)
		.fadeTo(500, 1)
		// fade out all the details for those thumbs
		.parent()
		.next('.details')
		.fadeTo(500, 0)
		.hide();
		
		// fade the clicked image out
		$(this)
		.fadeTo(500, .35)
		
		// find the next details div and fade it in
		.parent()
		.next('.details')
		.show()
		.fadeTo(500, 1)
	});
	
	$('.spotlightThumb img:first')
	.click();
}

function alumniExternalLinks()
{
	if( !$('body').hasClass('alumni') )	
		return;
	
	// make any non-alumni links open in a new window
	$("a:not([href^='alumni'])")
	.attr({target: '_blank'})
}

// things that get executed on every page
jQuery(function(){
	
	//FOR TESTING - uncomment this mobileParams and comment out the other one
	//var mobileParams = ( $(window).width() < 600 );
	var mobileParams = ( screen.width < 600 );
	
	isMobile = ( mobileParams ) ? true : false;
	
	$(document).ready(function(){
		mobile( mobileParams );
		
		if( $.browser.msie && $.browser.version < 8 )
			$('#topLinks').hide().show();
	});
	
	if( !isMobile )
	{
		animateSidebars();
	}

	addEmailPopup();
	
	// alumni pages
	alumniSpotlightGallery();
	alumniLoginVideos();
	disableLoginNav();
	alumniServiceVideos();
	alumniExternalLinks();
	
	hoverBoxes();
	
	// various form labels
	magicInputLabel('#pressSearch input.txt');
	magicInputLabel('#newsletterForm input.txt');
	magicInputLabel('#attySearch input.txt');
	magicInputLabel('#attySearch input.txt');
	magicInputLabel('#postComment input.txt, #postComment textarea');
	magicInputLabel('#mainEmail input.txt, #mainEmail textarea');
	magicInputLabel('#contactForm input.txt, #contactForm textarea');
	magicInputLabel('#loginForm input');
	magicInputLabel('#webForm input, #webForm textarea');
	magicInputLabel('#alumniSearchBox input');
	
	if( $('#alumni-profile').length )
	{
		magicInputLabel('.formBox input.txt:not(#field_highschoolyear):not(#field_schoolgradyear):not(#field_undergradyear), .formBox textarea');	
		magicSelectLabel('.formBox select');
		
		$("<a id='termsConfClose'>close</a>")
		.click(function(){
			$('#termsConf').hide();
		})
		.appendTo('#termsConf')
		
		$('.termsLink').bind('click', function(){

			var pos = $(this).position();
			
			$('#termsConf')
			.css({
				top: pos.top+18,
				left: pos.left-10
			})
			.toggle()
			
			return false;
		});
	}
});

