(function($){

	var ie7 = $.browser.msie && $.browser.version <= 7,
	    ie8 = $.browser.msie && $.browser.version <= 8;

	$.fn.splitList = function(n, options){
		settings = $.extend({
			wrapClass: false,
			splitInto: 'cols',
			collection: false
		}, options);
		return this.each(function(){
			var intoCols = (settings['splitInto'] == 'cols');
			$lis = settings['collection'] ? jQuery(this) : jQuery(this).children();
			$inc = intoCols ? parseInt(($lis.length/n) + ($lis.length % n > 0 )) : n;
			var w = '<div' + (settings['wrapClass'] ? ' class="' + settings['wrapClass'] + '"' : '' ) + '></div>';
			for(var i=0; i<(intoCols ? n : Math.ceil($lis.length/n)); i++)
				$lis.slice($inc*i, $inc*(i+1)).wrapAll(w);
		});
	};

	// Custom easing functions
	$.extend($.easing, {
		'easeOutQuart': function (x, t, b, c, d) {
			return -c * ((t=t/d-1)*t*t*t - 1) + b;
		},
		'easeInQuart': function (x, t, b, c, d) {
			return c*(t/=d)*t*t*t + b;
		}
	});

	// A null transition allows us to use the 'before' callback for transitions too complex for Cycle
	if($.fn.cycle !== undefined){
		$.fn.cycle.transitions.blank = function($cont, $slides, opts) {
			opts.cssBefore = {};
			opts.animIn = {};
			opts.animOut = {};
			opts.cssAfter = {};
		};
	}

	// Fade the just-posted comments into place with apinkish highlight
	$(window).load(function(){
		var hash = window.location.hash;
		if(hash.match(/#comment-[\d]/)){
			$(hash).delay(1000).animate({
				'background-color': '#EEE'
			}, 2000);
		}
	});

	$(function(){

		// Page setup
		$('body').addClass('js');
		$('#focus_areas .content > article').equalizeHeights();
		$('#featured_projects article').equalizeHeights();
		$('#refine_filters > section').each(function(index, element){
			var $items = $(element).find('li');
			if($items.length > 3){
				var $li = $('<li></li>').click(function(evt){
					$(this).remove();
				});
				$items.abbreviate(3, {'text': 'Show More'}).appendTo($li);
				$li.appendTo($(element).find('ul'));
			}
		});
		$('#focus_area .about_program > :not(header, footer)').abbreviate(1, {'text': 'Show More'}).insertBefore('#focus_area .about_program > footer');
		$('#funding_option .about_option > :not(header, footer)').abbreviate(1, {'text': 'Show More'}).insertBefore('#funding_option .about_option > footer');
		$('#funding_option .about_program > :not(header, footer)').abbreviate(1, {'text': 'Show More'}).insertBefore('#funding_option .about_program > footer');
		$('#community .about_community > :not(header, footer)').abbreviate(1, {'text': 'Show More'}).insertBefore('#community .about_community > footer');

        // insert placeholder if HTML5 placeholder attribute not supported
        insertPlaceholder('#search-field');

		$('.search input[type="checkbox"]').change(function(evt){
			$(this).closest('form').submit();
		});

		// Allows for <ol> bullets to be a different color than the text.
		$('.basic ol').addClass('color');
		$('.basic ol li').wrapInner('<span></span>');

		// Wraps <dt>/<dd> pairs with a <div>
		$('dl').each(function(index, element){
			var $children = $(this).children('dt, dd'),
				$definition = $();
			function wrapIt($def){
				$def.wrapAll($('<div></div>', {
					'class': 'definition'
				}));
			}
			$children.each(function(index, element){
				if(index && this.nodeName == "DT"){
					wrapIt($definition);
					$definition = $();
				}
				$definition = $definition.add(this);
			});
			wrapIt($definition);
		});
		
		if((function(){
			var e = document.createElement('div');
			var b = document.body;
			e.style.position = 'static';
			e.style.bottom = '0px';
			b.appendChild(e);
			var o = e.offsetTop;
			var r = false;
			try{
				e.style.position = 'fixed';
				if(o && typeof e.offsetTop == 'number') var r = (o != e.offsetTop);
			}catch(er){}
			b.removeChild(e);
			return r;
		})()){
			$('#beta').addClass('fixed');
		}

		if((function(){
			var mod = 'modernizr',
			    modElem = document.createElement(mod),
			    mStyle = modElem.style,
			    props = ['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform'];
			for ( var i in props ) {
				if ( mStyle[ props[i] ] !== undefined ) {
					return true;
				}
			}
		})()){
			$('#beta').addClass('transformed');
		}

		// Individual pieces of functionality, namespaced and isolated within closures.
		(function(){

			return {

				// Initialize each piece of functionality
				'initialize': function(){
					window.app = this;
					for(piece in this){
						if(piece !== 'initialize') this[piece].initialize();
					}
				},

				// Facet browser
				'facets': (function(){

					return {

						'container': $('#all_facets'),

						'initialize': function(){
							if(this.container.length){
								this.panels = this.container.children('section');
								this.subpanels = this.container.children('.has-sub');
								this.setUp();
								this.setUpSubPanels();
							}
						},

						'panelCloser': function(){
							// Returns a link used to close a panel
							return $('<a></a>', {
								'text': 'Close',
								'href': '#',
								'click': app.facets.closePanel,
								'class': 'close'
							});
						},

						'panelHeader': function(text){
							// Returns a panel header
							return $('<h4></h4>', {
								'text': 'Choose a ' + text
							});
						},

						'subPanelHeader': function(text){
							// Returns a subpanel header
							return $('<h5></h5>', {
								'text': 'Choose a ' + text + ' Sub-category'
							});
						},

						'backLink': function(){
							// Returns a subpanel back link
							return $('<a></a>', {
								'text': 'Back',
								'href': '#',
								'click': function(evt){
									evt.preventDefault();
									app.facets.hideSubpanel(evt, $(this).closest('.sub'));
								},
								'class': 'back'
							});
						},

						'allLink': function(text, href){
							// Returns a generated link to browse an entire subcategory
							var $li = $('<li></li>');
							var $a = $('<a></a>', {
								'text': 'All ' + text,
								'href': href,
								'class': 'all'
							}).appendTo($li);
							return $li;
						},

						'gridify': function($coll, wrap){
							// Takes a collection of objects and adds classes and wrappers used to place
							// it in a three-wide grid
							if(wrap !== undefined && wrap) $coll.wrapAll('<div class="wrap"></div>');
							$coll.filter(':nth-child(3n+1)').addClass('col1');
							var remainder = $coll.length%3;
							if(!remainder) remainder = 3;
							$coll.slice(-1 * remainder).addClass('last-row');
							$coll.slice(0, 3).addClass('first-row');
						},

						'showPanel': function(evt, self){
							// Shows a facet panel
							if(evt !== undefined) evt.preventDefault();
							var $group = $((self === undefined) ? this : self);
							app.facets.panels.each(function(index, object){
								$object = $(object);
								if($object !== $group){
									if($object.hasClass('open')) app.facets.closePanel(evt, $object.children('.main'));
								}
							});
							$group.addClass('open').children('.main').show().css({
								'left': '156px',
								'opacity': 0
							}).animate({
								'left': '166px',
								'opacity': 1
							}, 125, 'easeInQuart');
						},

						'togglePanel': function(evt){
							// Toggles visibility of a facet panel
							if(evt !== undefined) evt.preventDefault();
							var $link = $(this);
							var $panel = $link.closest('header').siblings('.main')
							if($panel.is(':hidden')){
								app.facets.showPanel(evt, $link.closest('section'));
							}else{
								app.facets.closePanel(evt, $panel);
							}
						},

						'closePanel': function(evt, self){
							// Closes a facet panel
							if(evt !== undefined) evt.preventDefault();
							var $panel = ((self === undefined) ? $(this).closest('.main') : self);
							$panel.closest('section').removeClass('open');
							$panel.animate({
								'left': '176px',
								'opacity': 0
							}, 125, 'easeOutQuart', function(){
								$(this).hide();
							});
						},

						'showSubpanel': function(evt, sub){
							// Shows a subpanel
							evt.preventDefault();
							var $sub = $(sub).show();
							var $panel = $sub.closest('.panel');
							$panel.animate({
								'right': $panel.outerWidth()
							}, 250);
						},

						'hideSubpanel': function(evt, sub){
							// Hides a subpanel
							evt.preventDefault();
							var $sub = $(sub);
							var $panel = $sub.closest('.panel');
							$panel.animate({
								'right': 0
							}, 250, function(){
								$sub.children('div').hide();
							});
						},

						'setUp': function(){
							// Runs setup routine for main set of categories
							this.panels.each(function(index, element){
								var $group = $(element).find('h3').wrapInner($('<a></a>', {
									'href': '#',
									'click': app.facets.togglePanel
								})).children('a');
								var $panel = $(element).children('.main');
								app.facets.panelHeader($group.text()).prependTo($panel)
								app.facets.panelCloser().appendTo($panel);
							});

							this.gridify(this.panels.filter('.community').find('li'), true);
						},

						'setUpSubPanels': function(){
							// Runs setup routine for subcategories
							this.subpanels.each(function(index, element){
								var $panel = $(element).find('.main').wrapInner('<div class="panel"></div>').children('.panel');

								// Wrap non-category items in a <div> for easy styling
								$panel.find('> ul > :not(.sub)').wrapAll('<div class="wrap"></div>')
								var $wrap = $panel.find('.wrap');

								// Case out the first three items in each wrapping <div> for easy styling
								app.facets.gridify($wrap.children(), false);

								// Setup for each subcategory
								var $subpanels = $panel.find('.sub > div');
								$subpanels.each(function(index, element){
									var $subpanel = $(element);
									var $link = $subpanel.siblings('a');
									var text = $link.text();

									$link.click(function(evt){
										app.facets.showSubpanel(evt, $(this).siblings('div'));
									});

									function get_all_link(category_link, category_anchors) {
									    // Create link where all categories are selected
									    var category_ids = [];
									    for (var i = 0; i < category_anchors.length; i++) {
    									    var subcategory_link = $(category_anchors[i]).attr('href');
    									    category_ids.push(subcategory_link.match(/subcategory=(\d+)/)[1]);
    									}
    									// Build up querystring, respecting any params that are already set
    									if (category_link.search(/\/$/) === -1) {
    									    category_link += "&";
    									} else { category_link += "?"; }
    									return category_link + "subcategory=" + category_ids.join(",");
									}

									var $all_link = get_all_link($link.attr('href'), $subpanel.find("li a"));
									$subpanel.find('ul').prepend(app.facets.allLink(text, $all_link)); // Create all link
									$subpanel.prepend(app.facets.subPanelHeader(text)); // Create header
									$subpanel.append(app.facets.backLink()); // Create back link
									$subpanel.append(app.facets.panelCloser()); // Create close link

									app.facets.gridify($subpanel.find('li'), true);
								});

							});
						}

					};

				})(),

				//
				'expandCollapse': (function(){

					return {

						'$items': $('.basic .expand_collapse'),

						'toggle': function(evt){
							var a = app.expandCollapse,
							    $e = $(this),
							    ie7img = $e.data('toggler').has(evt.target).length;
							if(evt.target == $e.data('toggler')[0] || ie7img){
								evt.preventDefault();
								if($e.data('visible'))
									a.hide(this);
								else
									a.show(this);
							}
							if(ie7){
								if($e.data('visible'))
									$e.data('toggler').find('img').attr('src', MEDIA_URL + 'images/button/minus.png');
								else
									$e.data('toggler').find('img').attr('src', MEDIA_URL + 'images/button/plus.png');
							}
						},

						'hide': function(element){
							$e = $(element);
							if(!$e.hasClass('expand_collapse')) $e = $e.parent();
							$e.data('toggler').addClass('hiding').removeClass('showing');
							$e.data('toToggle').hide();
							$e.data('visible', false);
						},

						'show': function(element){
							$e = $(element);
							if(!$e.hasClass('expand_collapse')) $e = $e.parent();
							$e.data('toggler').addClass('showing').removeClass('hiding');
							$e.data('toToggle').show();
							$e.data('visible', true);
						},

						'bindData': function(){
							this.$items.each(function(index, element){
								var $e = $(element);
								$e.data({
									'toggler': $e.children(':first-child').addClass('toggler'),
									'toToggle': $e.children(':not(:first-child)'),
									'visible': true
								});
							});
						},

						'initialize': function(){
							var a = app.expandCollapse;
							this.bindData();
							this.$items.click(this.toggle);
							this.$items.each(function(index, element){
								a.hide(element);
							});

							// IE7 doesn't support the :after pseudo-class
							if(ie7){
								this.$items.each(function(index, element){
									var $e = $(element),
									    i = $('<img />', {
									    	'src': MEDIA_URL + 'images/button/plus.png'
									    });
									i.appendTo($e.data('toggler'));
								});
							}

						}

					}

				})(),

				// Any of the many marquees across the site
				'marquee': (function(){

					return {

						'container': $('.marquee > .main'),

						'initialize': function(){
							this.slides = this.container.children();
							// Make the entire slide clickable.
							this.slides.each(function() {
							    var slide = $(this);
							    // ...unless it's a video slide.
								if (slide.hasClass("video")) {
									return;
								}
								var slide_href = slide.find("a:first").attr("href");
								slide.click(function(){ window.location=slide_href;})
									.hover(
										function() { window.status=slide_href;},
										function() { window.status="";}
									)
									.css("cursor", "pointer");
							});
							if(this.slides.length > 1){
								this.createPager();
								this.setUp();
							}
						},

						'createPager': function(){
							this.pager = $('<div></div>', {
								'class': 'pager'
							});
							this.prev = $('<a></a>', {
								'class': 'prev',
								'href': '#',
								'text': 'Previous'
							}).appendTo(this.pager);
							this.counter = $('<span></span>', {
								'html': '<em></em> of ' + this.slides.length
							}).appendTo(this.pager);
							this.count = this.counter.find('em');
							this.next = $('<a></a>', {
								'class': 'next',
								'href': '#',
								'text': 'Next'
							}).appendTo(this.pager);
							this.pager.insertBefore(this.container);
						},

						'positionPager': function($slide){
							$banner = $slide.children('a');
							this.pager.css({
								'bottom': $banner.outerHeight() + parseInt($banner.css('bottom')) - 50,
								'left': $banner.outerWidth() - this.pager.outerWidth()
							});
						},

						'updateCount': function($newSlide){
							app.marquee.count.text(app.marquee.slides.index($newSlide) + 1);
						},

						'setUp': function(){
							this.positionPager(this.slides.eq(0));
							this.cycle = this.container.cycle({
								'speed': 500,
								'timeout': 7500,
								'fx': 'blank',
								'prev': this.prev,
								'next': this.next,
								'before': function(now, next, options, forwardFlag){

									var $nextSlide = $(next),
									    $nextBanner = $nextSlide.children('a, figcaption'),
									    $prevSlide = $(now),
									    $pager = app.marquee.pager;

									if(now != next){

										// Let's start by bringing the next slide in from the left...
										$nextBanner.css('left', -495);
										$nextSlide.show().css('left', -640).animate({
											'left': 0
										}, 275);

										// ...and moving the existing slide to the right.
										$pager.animate({
											'left': '+=640'
										}, 275, function(){

											app.marquee.positionPager($nextSlide);
											app.marquee.updateCount($nextSlide);

											$pager.animate({
												'left': '-=495'
											}, 1, function(){
												$pager.animate({
													'left': '+=495'
												}, 374, 'easeOutQuart');
											});
										});
										$prevSlide.animate({
											'left': 640
										}, 275, function(){
											$prevSlide.hide();
											// Enter the new arrow, stage right.
											$nextBanner.animate({
												'left': 0
											}, 375, 'easeOutQuart');
										});
									}else{

										app.marquee.updateCount($nextSlide);

									}
								}
							});
						}

					};

				})(),

				// The tabbed 'News Feed' interface
				'newsFeed': (function(){

					return {

						'container': $('#news_feed'),

						'initialize': function(){
							if(this.container.length && !this.container.hasClass('no-js')){

								this.is_grant_feed = this.container.parents("#grant").length !== 0
								this.slideList = this.container.children('.main');
								this.footer = this.container.children('footer');
								this.horiz = this.container.hasClass('horiz');
								this.createAll();
								this.setUp();
                                if(ie8) {
                                    this.slideList.find('section').first().show();
                                    this.slideList.find('h2').first().click();
                                }
							}
						},
						// Creates and populates the 'All' tab, which highlights the newest item in
						// each of the other tabs, sorted by date.
						'createAll': function(){
							if(!ie8){
								this.allSection = $('<section></section>', {
									'class': 'all',
									'html': '<header><h2>All</h2></header><ol></ol>'
								}).prependTo(this.slideList);
								// If we're on the homepage, add a "View All Headlines" link to the pressroom to
								// the bototm of the 'All' tab.
								if (window.location.pathname === '/') {
								    var all_link = $('<a class="abbreviate">View All Headlines</a>')
								        .attr('href', window.NEWS_FEED_URL);
								    this.allSection.append(all_link);
								}
							}
							this.slides = this.slideList.children('section');
							if(!ie8){
							    // If we're on a grant page, the maximum allowed items in the "All" feed can be large.
    							var max_size = this.is_grant_feed ? 100 : 5;
								var all_items = this.scan_lists(this.slides, max_size, this.get_list_of_list_items);
								all_items = all_items.sort(function(a,b){
								    var a_date = new Date($(a).find("time").attr("datetime"));
								    var b_date = new Date($(b).find("time").attr("datetime"));
								    if (a_date < b_date) { return -1; }
								    if (a_date > b_date) { return 1; }
								    return 0;
								});
								var all_feed = $('#news_feed section.all ol');
								$(all_items).each(function () {
								    all_feed.prepend($(this));
								});
							}
						},

						 // Return a list of lists: <li>s in each <section>.
						'get_list_of_list_items': function(sections) {
							var lists = [];
							for (var i=0; i<sections.length;i++) {
								var section_list_items = $(sections[i]).find("ol > li");
								if (section_list_items.length > 0) {
									lists.push(section_list_items.clone());
								} 
							}
							return lists;
						},

						// Take objects from a list of lists, one at a time, aggregating until max_size is met.
						'scan_lists': function(lists, max_size, list_transform) {

							var all_list, list_index, list_contains_all_undefined;
							if (!!list_transform) {
								lists = list_transform(lists);
							}
							all_list = [];
							list_index = 0;
							// All objects in a list are of type 'undefined'.
							list_contains_all_undefined = function(list) {
								for (var i=0; i < list.length; i++) {
									if (typeof list[i] !== 'undefined') { return false; }
								}
								return true;
							}
							while ((all_list.length < max_size)) {
								for (var i=0; i < lists.length; i++) {
									var list = lists[i];
									if (list) {
										if (list.length < (list_index + 1)) {
											delete lists[i];
										} else {
											all_list.push(lists[i][list_index]);
										}
									}
								}
								if (list_contains_all_undefined(lists)) { break; }
								++list_index;
							}
							return all_list;
						},
						// Generates the tabs and binds appropriate event listeners to each
						'setUp': function(){
							var that = this;
							this.slides.filter(':not(.all)').hide().end().tabs('h2', {

								// Show new tab and reposition arrow on tab change
								'click': function(evt, menuItem, tab, otherTabs){
									evt.preventDefault();
									$(menuItem).closest('li').addClass('active').siblings().removeClass('active');
									otherTabs.hide();
									$(tab).show();

									if(app.newsFeed.horiz){
										app.newsFeed.arrow.animate({
											'left': $(menuItem).position().left + $(menuItem).outerWidth()/2 - app.newsFeed.arrow.outerWidth()/2
										}, 250, 'easeOutQuart');
									}else{
										app.newsFeed.arrow.animate({
											'top': $(menuItem).position().top - 13
										}, 250, 'easeOutQuart');
									}

									// $(window).scrollTo('#news_feed', 250, {'easing': 'easeOutQuart'});
								},

								// Create and position arrow indicating active tab
								'after': function(tabs, tabMenu){
									var $menuItem = tabMenu.find('li:first').addClass('active').find('a');
									app.newsFeed.arrow = $('<span></span>', {
										'class': 'arrow',
										'text': '.'
									}).appendTo(app.newsFeed.footer)
									$(window).load(function(){
										if(app.newsFeed.horiz){
											app.newsFeed.arrow.css('left', $menuItem.position().left + $menuItem.outerWidth()/2 - app.newsFeed.arrow.outerWidth()/2)
										}else{
											app.newsFeed.arrow.css('top', $menuItem.position().top - 15);
										}
									});
									// If we are on a grant page, the "All" list could be very long, and should get a "View X more links" control. Otherwise,
									// don't show the control on the "All" feed. 
									var filtered_slides = app.newsFeed.slides;
									if (!that.is_grant_feed) {
										filtered_slides = filtered_slides.filter(':not(.all)')
									}
									filtered_slides.each(function(){
										$(this).find('ol > li').abbreviate(5).insertAfter($(this).find('ol'));
									});
								},

								// Pass data-type attribute values to menu items
								'beforeAppend': function($menuItem, $tab){
									if(!$menuItem.closest('li').hasClass('all')){
										var type = $tab.find('[data-type]:eq(0)').attr('data-type');
										$menuItem.attr('data-type', type);
									}
								}

							}).prependTo(this.footer);

							this.multimediaItems = this.slides.find('li > article[data-type="multimedia"]');
							this.multimediaItems.addClass('closed').each(function(index, element){
								var $item = $(element);
								var isVideo = !!$item.find('iframe').length;
								app.newsFeed.toggler(isVideo).insertAfter($item.find('h3:eq(0)'));
							});

							this.container.find('.type').wrapInner(this.typeWrapper());
						},

						// Toggles visiblity of any videos or images
						'toggleMedia': function(evt){
							evt.preventDefault();
							$link = $(this);
							$link.closest('article').toggleClass('closed');
							$link.remove();
						},

						// Returns <a> element for toggling the visibility of <figure> element
						'toggler': function(video){
							var toggler =  $('<a></a>', {
								'class': 'toggle',
								'href': '#',
								'html': video ? 'Show&nbsp;Video' : 'Show&nbsp;Image',
								'click': this.toggleMedia
							});
							return toggler;
						},

						// Returns <a> element used to wrap update 'type' definition
						'typeWrapper': function(){
							return $('<a></a>', {
								'click': this.switchTabs,
								'href': '#'
							});
						},

						// Changes tabs to the specific
						'switchTabs': function(evt){
							evt.preventDefault();
							var type = $(this).closest('article[data-type]').attr('data-type');
							var $menuItem = app.newsFeed.container.find('footer a[data-type="' + type + '"]');
							$menuItem.click();
						}

					};

				})(),

				// The 'Explore Our Projects' module
				'explore': (function(){

					return {

						'container': $('#explore'),

						'initialize': function(){
							if($('#explore').length){
								this.slides = this.container.find('li.slide');
								this.setUp();
							}
						},

						// Initializes tabbed interface
						'setUp': function(){
							this.slides.tabs('h2', {
								'tabHref': 'header > a',

								// Expand container to height of tallest slide (done on load to ensure that all
								// Typekit fonts have been loaded when calculating heights)
								'before': function(tabs){
									$(window).load(function(){
										var heights = [],
										    first = tabs.eq(0),
										    all = first.add(first.siblings());
										all.hide().each(function(index, element){
											heights.push($(element).show().closest('#explore').height());
											$(element).hide();
										});
										$('#explore').height(Math.max.apply(Math, heights));
										$('#explore > ul li:not(.slide)').show();
									});
								},

								// Show intro slide on page load; return to intro slide when mouse leaves bounding box
								'after': function(tabs, tabMenu){
									tabs.hide().eq(0).siblings('li:not(.slide)').show().addClass('active');
									app.explore.container.bind('mouseleave', function(){
										$(tabMenu).find('li.active').removeClass('active');
										$(tabs).filter('.active').hide().removeClass('active');
										tabs.hide().eq(0).siblings('li:not(.slide)').show().addClass('active');
									});
								},

								// Show new tab on menu mouseover
								'mouseenter': function(evt, menuItem, tab, otherTabs){
									$(tab).siblings().hide().removeClass('active').end().show().addClass('active');
									$(menuItem).closest('li').siblings().removeClass('active').end().addClass('active');
								}


							}).appendTo(this.container);
						}

					}

				})(),

				// The homepage-style billboard
				'homepageBillboard': (function(){

					return {

						'container': $('#homepage-billboard'),

						'initialize': function(){
							if(this.container.length){
								this.slideList = this.container.find('> .main');
								this.slides = this.slideList.children();
								// Make the entire slide clickable.
								this.slides.each(function(){
								    var slide = $(this);
									// ...unless it's a video slide.
									if (slide.hasClass("video")) {
										return;
									}
									var slide_href = slide.find("a:first").attr("href");
									slide.click(function(){ window.location=slide_href;})
										.hover(
											function() { window.status=slide_href;},
											function() { window.status="";}
										)
										.css("cursor", "pointer");
								});
								this.createPager();
								this.setUp();
								// This function is bound to window.load as it ensures that Typekit has been fully
								// loaded (new fonts can affect heights)
								$(window).load(this.resizeAndCenter);

								// Stop the billboard when a video starts playing
								$(window).load(this.pauseOnVideoPlay);
							}
						},

						// Pause billboard when the user starts playing a video
						'pauseOnVideoPlay':function(evt){
							var vimeoSlides = window.app.homepageBillboard.container.find('.vimeo');
							vimeoSlides.each(function(index, element){
								element.addEvent('onPlay', function(){
									window.app.homepageBillboard.slideList.cycle('pause');
								});
							});
						},

						'pauseAllVideos': function(){
							if(!$.browser.msie){
								var vimeoSlides = window.app.homepageBillboard.container.find('.vimeo');
								vimeoSlides.each(function(index, element){
									element.api('pause')
								});
							}
						},

						// Creates the pager element and adds to DOM
						'createPager': function(){
							this.pager = $('<ul></ul>').appendTo($('<nav></nav>', {'class': 'pager'}).appendTo(this.container));
						},

						// Initializes Cycle
						'setUp': function(){
							this.slideList.cycle({
								'speed': 500,
								'timeout': 7500,
								'fx': 'blank',
								'pager': this.pager,

								// Creates custom pager nodes
								'pagerAnchorBuilder': function(index, DOMelement){
									var $slide = $(DOMelement);

									// Show slide's descriptive paragraph on mouseover; revert on mouseout
									if(!$slide.hasClass('video')){
										$slide.children('a').bind('mouseenter', function(){
											$(this).find('div > :not(header)').show().end().find('div > header').hide();
										}).bind('mouseleave', function(){
											$(this).find('div > :not(header)').hide().end().find('div > header').show();
										});
									}

									return $('<li />', {
										className: $slide.attr('class'),
										text: $slide.find('h1').text()
									// Switch banners on hover
									}).bind('mouseenter', function() {
										window.app.homepageBillboard.pauseAllVideos();
										$('#homepage-billboard').find('.main').cycle('pause').cycle(index);
									// Open banner link on click
									}).bind('click', function() {
										var $link = $slide.find('a'),
											url = $link.attr('href');
										window.location = url;
									}).bind('mouseleave', function() {
									    $('#homepage-billboard').find('.main').cycle('resume');
									});
								},

								// Since our transition is too complex for Cycle's facilities, we fed it a null
								// transition and are performing the transition in this callback.
								'before': function(now, next, options, forwardFlag){
									if(now != next){

										// Cases out special positionin values for video slides
										var video = $(next).hasClass('video'),
										    prevVideo = $(now).hasClass('video');
										var $nowarrow = video ? $(now).find('h2') : $(now).children('a'),
										    $nextarrow = video ? $(next).find('h2') : $(next).children('a'),
										    animStart = video ? -1257 : -1459;
										    animEnd = video ? -1000 : -960;

										// Let's start by bringing the next slide in from the left...
										$nextarrow.css('right', animStart);
										$(next).show().css('left', -940).animate({
											'left': 0
										}, 275, function(){

											// IE has problems removing the video and showing it later, so we
											// have to
											if($.browser.msie && prevVideo){
												var video = $(now).find('iframe'),
												    clone = video.clone();
												clone.insertAfter(video);
												video.remove();
											}
										});

										// ...and moving the existing slide to the right.
										$(now).animate({
											'left': 940
										}, 275, function(){
											$(now).hide();
											// Enter the new arrow, stage right.
											$nextarrow.animate({
												'right': animEnd
											}, 375, 'easeOutQuart');
										});

									}
								}

							});
						},

						// Resizes and centers items within each textual banner on the billboard.
						'resizeAndCenter': function(){
							var $slides = app.homepageBillboard.slides;
							if($slides.length){
								$slides.each(function(index, element){
									$slide = $(element);
									if(!$slide.hasClass('video')){
										$slide.show();
										var $banner = $slide.children('a');
										var $rest = $banner.find('div > header'),
										    $hover = $banner.find('div > p');
										$rest.hide(); $hover.show();
										var hoverHeight = $banner.height();
										$rest.show(); $hover.hide();
										var restHeight = $banner.height();
										$banner.height(Math.max(restHeight, hoverHeight));
										if(index != 0) $slide.hide();
										((restHeight < hoverHeight) ? $rest : $hover).css({
											'position': 'relative',
											'top': parseInt(Math.abs(restHeight-hoverHeight)/2)
										});
									}
								});
							}
						}

					}

				})(),

				// Hide/show subcategory listings (also non-resident and related grants)
				'subcategoryToggle': (function(){

					return {

						'container': $('.subcategory_list, .nonresident, .related_grants'),

						'initialize': function(){
							if(this.container.length){
								this.setUp();
							}
						},

						'toggle': function(evt){
							evt.preventDefault();
							$(this).closest('section').toggleClass('closed');
						},

						'toggler': function(){
							return $('<a></a>', {
								'class': 'toggle',
								'href': '#',
								'text': 'Toggle Visiblity',
								'click': this.toggle
							});
						},

						'setUp': function(){
							this.toggler().appendTo(this.container).click();
						}

					};

				})(),
				'projectToggle': (function() {
					return {
						'initialize': function() {
							var long_desc = $("#long_description").hide();
							$("#grant_purpose a.toggle").click(function(evt){
								evt.preventDefault();
								var el = $(this);
								if (el.hasClass("open")) {
									el.removeClass("open").html("Learn More<span></span>");
									long_desc.slideUp('fast');
									el.next().removeClass("open");
								} else {
									el.addClass("open").html("Show less<span></span>");
									el.next().addClass("open");
									long_desc.slideDown('fast');
								}
							});
						}
					};
				})(),
				// Scroller used to display listing of staff members
				'staffList': (function(){

					return {

						'container': $('.staff_list > .main'),
						'prevClicked': false,

						'initialize': function(){
							if(this.container.length){
								this.slides = this.container.children();
								this.createPager();
								this.setUp();
							}
						},

						'setUp': function(){
							this.cycle = this.container.cycle({
								'fx': 'blank',
								'timeout': 0,
								'speed': 250,
								'nowrap': true,
								'prev': this.prev.bind('click', function(){
									app.staffList.prevClicked = true;
								}),
								'next': this.next.bind('click', function(){
									app.staffList.prevClicked = false;
								}),
								'before': function(now, next, options, forwardFlag){
									app.staffList.updateCount($(next));
									if(now !== next){
										$(now).animate({
											'left': app.staffList.prevClicked ? '270px' : '-270px',
											'opacity': .25
										}, 200, function(){
											$(this).hide();
										});
										$(next).css({
											'left': app.staffList.prevClicked ? '-270px' : '270px',
											'opacity': .25
										}).show().animate({
											'left': 0,
											'opacity': 1
										}, 275);
									}

									var index = app.staffList.slides.index(next) + 1;
									if(index == app.staffList.slides.length){
										app.staffList.next.addClass('disabled');
									}else{
										app.staffList.next.removeClass('disabled');
									}

									if(index == 1){
										app.staffList.prev.addClass('disabled');
									}else{
										app.staffList.prev.removeClass('disabled');
									}
								}
							});
						},

						'createPager': function(){
							this.pager = $('<div></div>', {
								'class': 'pager'
							});
							this.prev = $('<a></a>', {
								'class': 'prev',
								'href': '#',
								'text': 'Previous'
							}).appendTo(this.pager);
							this.counter = $('<span></span>', {
								'html': '<em></em> of ' + this.slides.length
							}).appendTo(this.pager);
							this.count = this.counter.find('em');
							this.next = $('<a></a>', {
								'class': 'next',
								'href': '#',
								'text': 'Next'
							}).appendTo(this.pager);
							this.pager.insertBefore(this.container);
						},

						'updateCount': function($newSlide){
							app.staffList.count.text(app.staffList.slides.index($newSlide) + 1);
						}

					};

				})()

			};

		})().initialize();

	});

})(jQuery);

/**
* A patch for the HTML 5 Placeholder attribute found
* in the search input
*/
function testPlaceholder() {
	var i = document.createElement('input');
	return 'placeholder' in i;
}


function insertPlaceholder(el) {
	var hasPlaceholder = testPlaceholder();
	if (hasPlaceholder) {
		return;
	} else {
		$(el).each(function() {
			var helpTxt = $(this).attr("placeholder");

			$(this).val(helpTxt);

			$(this).blur(function () {
				if($(this).val() == '') { $(this).val(helpTxt) }
			});
			$(this).focus(function() {
				if($(this).val() == helpTxt) { $(this).val("") }
			});
		});
	}
}

