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
		$('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)
		.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 )
{
	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;
	
	smallBox = !!options['smallBox'];
	bigVideo = !!options['bigVideo'];
	
	// 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+' a').eq(0).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: 'exactfit',
				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 )
{
	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').removeData('playingMovie');
	}
	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).parent().next('a.vidControls').toggleClass('vidControlsPlaying');			
}


function stateTracker(event)
{ 
	//alert(obj.newstate);
	
	if( event.newstate=='COMPLETED' )
	{
		obj = $('body').data('playingMovie').sendEvent('SEEK', 0);
		obj = $('body').data('playingMovie').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='**' selected>XX</option>")	
				.prependTo(this);
			}			
			
			// get the first item and change the text
			$(this)
			.children('option[value=**]')
			.text('- '+this.title+' -')
			
			$(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 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);
		
		// fade the clicked thumbnail out to show the color underneath
		$(this).children('img').fadeTo('slow',.5);
		
		// if we have a movie playing at the moment, stop it
		if( playingMovie = $('body').data('playingMovie') )
			playMovie(playingMovie);
		
		// if this video is clicked, write the HTML to the main frame and then
		// embed the flash player there	
		$('#videoFrame').html("<a href='"+ this.href +"'></a>");
		embedVideo('#videoFrame', {width:360,height:256,nocontrols:true,autoplay:true});
		
		return false;
	})
	
	// if we have no login error, start a video
	if(  !$('#loginError').length )
	{
		$('.alumniVideo')
		.filter(':nth-child('+ Math.ceil(Math.random()*$('.alumniVideo').length) +')')
		.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 we have a movie playing at the moment, stop it
		if( playingMovie = $('body').data('playingMovie') )
			playMovie(playingMovie);
		
		// if this video is clicked, write the HTML to the main frame and then
		// embed the flash player there	
		$('#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();
}

$(alumniSpotlightGallery);

// things that get executed on every page
jQuery(function(){
	animateSidebars();
	addEmailPopup();
	
	// alumni pages
	alumniLoginVideos();
	disableLoginNav();
	alumniServiceVideos();
	
	// 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;
		});
	}
});