var wu = {
	// ! GLOBAL: current_page
	current_page: 1,
	// ! GLOBAL: total_pages
	total_pages: 1,
	// ! GLOBAL: oldscroll
	oldscroll: 0,
	// ! GLOBAL: Calendar dates
	today : new Date(),
	month : new Date().getMonth()+1,
	year : new Date().getFullYear(),
	// ! GLOBAL: Set Defaults for event/news data
	type: 'all',
	date: 'undefined',
	archive: false,
	paused: false,
	// ! GLOBAL: Mobile Nav ID
	prevnavid: 0, 
	navid: 0,
	lasttimestamp: 0,
	// ! FUNCTION: Init
	init: function() {
		document.createElement('section');
		document.createElement('header');
		document.createElement('nav');
		document.createElement('aside');
		document.createElement('footer');
		document.createElement("column");
		document.createElement("video");

		if (jQuery('.home-background-image').length > 0) {
			/*
				chose proper size based on window size
				desktop_
				tablet_
				phone_
			*/
			var container = jQuery('.home-background-image'),
				path = container.attr('data-path'),
				src = container.attr('data-img'),
				prefix = 'desktop_';
			if (window.innerWidth < 1920 && window.innerWidth >= 800) {
				prefix = 'tablet_';
			} else if (window.innerWidth < 800) {
				prefix = 'phone_';
			}
			container.css('background-image', 'url(' + path + prefix + src + ')');
		}

		if (document.location.href.indexOf('#') >= 0) {
			var anchor = '#' + document.location.href.split('#').pop();
			jQuery('html,body').animate({scrollTop:jQuery(anchor).offset().top - 200},'slow');
		}
		
		// Account for header on jump links
		$('.right-content').find('a[href^="#"]').on('click',function () {
		    var target = this.hash;
		    $('html, body').stop().animate({'scrollTop': $(target).offset().top - 190}, 500);
		});
				
		wu.google.searchEvent();
		$(".search-result-close").click(function(){
		    $(".search-result-container").animate({height: '0'}, 500, function(){
			    $(this).height('');
		    });
		    $(".search-result-container").removeClass('show-search-result'); 
		});  
		
		// ! INIT: Home page functions
		if(jQuery('.home').length > 0){
			wu.backgroundCover(jQuery('video'));
			wu.signaturePrograms();
			wu.ourStories();
		} else {
			// ! INIT: Interior page functions
			if (window.innerWidth < 651 && jQuery('.featured-image').length > 0){
				wu.backgroundCover(jQuery('.featured-image img'));
			}
		}
		
		// ! INIT: Alert bar
		if(jQuery('.alert-bar-item').length > 0){
			jQuery('.alert-bar-item .close-alert').click(function(){
				jQuery(this).closest('li').hide();
				if(jQuery('.no-top-image').length > 0){
					jQuery('.no-top-image').css({
						marginTop: jQuery('header').height()
					});
				}
			});
			if(jQuery('.no-top-image').length > 0){
				jQuery('.no-top-image').css({
					marginTop: jQuery('header').height()
				});
			}
		}
		
		// ! INIT: Smaller screen size functions
		wu.applyMenu();
		if(window.innerWidth < 1025 && jQuery('.give-apply > ul.utility').length <= 0){
			jQuery('.give-apply > ul').before( jQuery('.utility').clone() );
		}
		
		// ! INIT: Faculty functions
		if(jQuery('.faculty-sort').length > 0){
			wu.facultySort();
		}
		
		if(jQuery('.faculty').length > 0){
			//if there is an alpha cookie set (from clicking on a filter from a detail page), click that button and remove it
			if(document.cookie.indexOf('alpha=') > -1){
				var alphaclass = "#filter_" + document.cookie.split('alpha=').pop().split(';').shift();
				jQuery(alphaclass).click();
				document.cookie = "alpha=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
			} else {
				wu.getFaculty(wu.type);
			}	
		}
		
		// activates tabs on faculty detail pages
		if(jQuery('.faculty-detail').length > 0) {
			wu.facultyTabs();
			if (window.innerWidth >= 864) {
				jQuery('.faculty-tab-select li:first-child a').click();
			}
		}
		
		// ! INIT: News functions
		if(jQuery('.news').length > 0){
			wu.news.get(wu.type);
		}
		if(jQuery('.news-category').length > 0){
			wu.news.category();
		}
				
		// ! INIT: Events functions
		if(jQuery('.upcoming-events').length > 0){
			wu.events.get(wu.type);
		}
		if(jQuery('.events-category').length > 0){
			wu.events.category();
		}
		if(jQuery('.event-archive').length > 0){
			wu.archive = true;
			wu.events.get(wu.type, false, 'undefined');
		}
		// ! INIT: Events Calendar
		if(jQuery('.calendar').length > 0){
			wu.calendar.get(wu.month, wu.year);
		}
		
		 //	switch success stories to use inset image source for the background of it's parent
        if ($('.wu-profile').length > 0) {
            $('.wu-profile-image').each(function (index, element) {
                $(element).css('background-image', 'url(' + $(element).find('img').attr('src') + ')');
            });
        }
		
		// ! INIT: On scroll, autoload more
		wu.scroll.start();
		
		jQuery(window).resize(function(){
			wu.resize();
		});
		
		if(jQuery('#bgvid').length > 0 && wu.paused == false && $(window).scrollTop() > 300){
			var vid = jQuery('#bgvid');
			vid.pause();
			wu.paused = true;
		}

		// ! push all external facing URLs to new window
		var links = jQuery('a[href^="http"]'),
			domain = document.location.host;
		links.each(function(index,link){
			if (!jQuery(link).attr('href').match(domain)) {
				jQuery(link).attr('target','_blank');
			}
		});
		
		// ! fix for IE not showing "search" in search box
		if ($('#search-value').length > 0 && Modernizr.csscolumns === false) {
			$('#search-value').val($('#search-value').attr('placeholder'));
			$('#search-value').focus(function(){
				if ($(this).val() == 'SEARCH') {
					$(this).val('');
				}
			});
			$('#search-value').blur(function(){
				if ($(this).val() == '') {
					$(this).val('SEARCH');
				}
			});
		}
		
		// Touching on mobile
		if(jQuery('.touch').length > 0 && $(".delaware-way-block").length > 0){
			var checkAndPreventDuplicatedEvent = function (e) {
			    if (e.timeStamp === wu.lasttimestamp) return true;
			    else wu.lasttimestamp = e.timeStamp;
			    return false;
			}
			$(".delaware-way-block").unbind('tap').on("tap",function(e){
				if (checkAndPreventDuplicatedEvent(e)) {
					return; 
				} else {
					$(this).toggleClass('tapped');
				}	
			});
		}
		wu.mobileMenu.init();
		
		if(jQuery('.right-content table').length > 0){
			wu.mobileTables();
		}

		wu.iconSliderInit();
	},
	/* ! wu.iconSlideWidth */ 
	iconSlideWidth: 230,
	/* ! wu.iconSliderInit */ 
	iconSliderInit: function(){
		var mask = $('.carousel-mask'),
			maskWidth = mask.width(),
			iconCount = Math.floor(maskWidth / wu.iconSlideWidth);
		mask.css('width',(iconCount * wu.iconSlideWidth) + 'px');
		$('.carousel-arrow-left, .carousel-arrow-right').click(wu.iconSliderAction);
	},

	/* ! wu.iconSliderAction */
	iconSliderAction: function(event) {

		var element = $(event.target),
			carousel = $('.carousel-container'),
			mask = $('.carousel-mask'),
			maskWidth = $('.carousel-constrain').width() - 160,
			iconCount = Math.floor(maskWidth / wu.iconSlideWidth),
			leftPosOld = carousel.position().left;
		mask.css('width',(iconCount * wu.iconSlideWidth) + 'px');
		if (element.hasClass('carousel-arrow-left')) {
			if (Math.abs(leftPosOld) < wu.iconSlideWidth) {
				return false;
			} else {
				$('.carousel-arrow-left, .carousel-arrow-right').off('click');
				carousel.css('left','+=' + wu.iconSlideWidth + 'px');
			}
		} else {
			if (($('.carousel-container').width() - $('.carousel-mask').width()) > Math.abs(leftPosOld)) {
				$('.carousel-arrow-left, .carousel-arrow-right').off('click');
				carousel.css('left','-=' + wu.iconSlideWidth + 'px');
			} else {
				return false;
			}
		}
        setTimeout(function() {
			$('.carousel-arrow-left, .carousel-arrow-right').click(wu.iconSliderAction);
        }, 500);
		return false;
	},
	// ! UTILITY: Vertical Center
	// Parameter: an array of items to vertically center their child elements.
	verticalCenter: function(elements){
		jQuery(elements).each(function(){
			var div = jQuery(this),
				height = div.outerHeight(),
				children = div.children(),
				childheight = 0,
				space = 0;
			children.each(function(){
				var child = jQuery(this);
				childheight	+= child.outerHeight(true);
			});
			space = (height-childheight)/2;
			div.css({
				paddingTop: space +'px'
			});
		});
	},
	//background size cover on the grid images
	backgroundCover: function(images){
		images.each(function(){
			//if the parent box height is larger than its width
			if(jQuery(this).parent().height() > jQuery(this).parent().width()){
				jQuery(this).addClass('imghigh');
			} //otherwise
			else {
				jQuery(this).removeClass('imghigh');
			}
			//if the image height is greater than the parent box height
			if(jQuery(this).height() > jQuery(this).parent().height()){
				var padtop = -((jQuery(this).height() - jQuery(this).parent().height()) / 2);
				jQuery(this).css({
					'marginTop': padtop +'px'
				});
			} //otherwise
			else {
				jQuery(this).css({
					'marginTop': 'auto' 
				});
			}
			//if the width of the img is greater than the parent width
			if(jQuery(this).width() > jQuery(this).parent().width()){
				var padleft = -((jQuery(this).width() - jQuery(this).parent().width()) / 2);
				jQuery(this).css({
					'marginLeft': padleft +'px'
				});
			} //otherwise 
			else {
				jQuery(this).css({
					'marginLeft': 'auto' 
				});
			}
		});
	},
	// ! FUNCTION: Home Page: Signature Programs
	signaturePrograms: function(){
		var slides = 0;
		jQuery('.signature .slide').each(function(){
			slides++;
		});
		var wholewidth = 100 * slides,
			slidewidth = 100/slides;
		jQuery('.signature .long-slider').width(wholewidth+'%');
		jQuery('.signature .slide').each(function(){
			jQuery(this).width(slidewidth+'%');
		});
		jQuery('.signature .dot').each(function(){
			jQuery(this).click(function(){
				jQuery('.signature .dot').each(function(){
					jQuery(this).removeClass('active');
				});
				jQuery(this).addClass('active');
				
				var slide = '.signature .slide.' + jQuery(this).attr('class').split(' ').shift(),
					left = -(parseInt(slide.split('-').pop())-1) * 100;
				jQuery('.signature .slide').each(function(){
					jQuery(this).removeClass('active');
				});
				jQuery(slide).addClass('active');
				jQuery('.signature .long-slider').css('left', left+'%');
			});
		});
		// Swiping through on mobile
		if(jQuery('.touch').length > 0 ){
			jQuery('.signature').bind("swiperight",function(){
				var current = jQuery('.dot.active').attr('class').split(' ').shift().split('-').pop(),
					prev = parseInt(current)-1,
					max = jQuery('.slide').length;
				if(prev < 1){
					prev = max;
				}
				jQuery('.signature .dot').each(function(){
					jQuery(this).removeClass('active');
				});
				var slide = '.signature .slide.slide-'+prev,
					dot = '.signature .dot.slide-'+prev,
					left = -(parseInt(slide.split('-').pop())-1) * 100;
				jQuery('.signature .slide').each(function(){
					jQuery(this).removeClass('active');
				});
				jQuery(dot).addClass('active');
				jQuery(slide).addClass('active');
				jQuery('.signature .long-slider').css('left', left+'%');
			});
			jQuery('.signature').bind("swipeleft",function(){
				var current = jQuery('.dot.active').attr('class').split(' ').shift().split('-').pop(),
					next = parseInt(current)+1,
					max = jQuery('.slide').length;
				if(next > max){
					next = 1;
				}
				jQuery('.signature .dot').each(function(){
					jQuery(this).removeClass('active');
				});
				var slide = '.signature .slide.slide-'+next,
					dot = '.signature .dot.slide-'+next,
					left = -(parseInt(slide.split('-').pop())-1) * 100;
				jQuery('.signature .slide').each(function(){
					jQuery(this).removeClass('active');
				});
				jQuery(dot).addClass('active');
				jQuery(slide).addClass('active');
				jQuery('.signature .long-slider').css('left', left+'%');
			});
		}
	},
	ourStories: function(){
		var h3padding = jQuery('.quote h3').css('padding-left').split('p').shift(),
			newquotewidth = jQuery('.students > div').outerWidth()*2,
			ppadding = jQuery('.who p').css('padding-left').split('p').shift(),
			newattributionwidth = jQuery('.students > div').outerWidth();
		jQuery('.quote > h3').width(newquotewidth-h3padding*2);
		jQuery('.who > p').width(newattributionwidth-ppadding*2);
		if(window.innerWidth < 1025){
			jQuery('.quote > h3,.who > p').css({width:'', 'padding-top': ''});
			jQuery('.quote,.who').css({'padding-top': ''});
		} else {
			wu.verticalCenter(jQuery('.quote, .who'));	
		}
		// Touching on mobile
		if(jQuery('.touch').length > 0 ){
			$(".our-stories .students > div").on("tap",function(){
				$(this).toggleClass('tapped');
			});
		}
	},
	// ! FUNCTION: Half Menu Toggle
	applyMenu: function(){
		jQuery('.open-apply-menu').click(function(){
			jQuery(this).parent().toggleClass('open');
		});
	},
	/**
		wu.mobileMenu
	*/
	mobileMenu: {
		init: function(){
			/* show back button if we're inside the site */
			if (jQuery('.main-menu li.active').length > 0) {
				jQuery('.mobile-back').addClass('show-back');
				// use built in "active" nav class to pull current path
				var li = jQuery('.main-menu .active').last();
				if (li.children('ul').toArray().length == 0) {
					var newli = jQuery(li.parents('li')[0]);
					newli.addClass('show-children');
					newli.children('ul').addClass('open')
					newli.parents('ul').each(function(index,element){
						switch (index) {
							case 0:
								jQuery(element).addClass('open show-one');
								break;
							default:
		 						jQuery(element).addClass('open show-none');
								break;
						}
					});
				} else {
					li.addClass('show-children');
					li.children('ul').addClass('open')
					li.parents('ul').each(function(index,element){
						switch (index) {
							case 0:
								jQuery(element).addClass('open show-one');
								break;
							default:
		 						jQuery(element).addClass('open show-none');
								break;
						}
					});
				}
			}
			/* add click action to all nav items */
			jQuery('.main-menu li:not(.mobile-back) a').click(wu.mobileMenu.clickAction);
			/* add click action for back button */
			jQuery('.main-menu li.mobile-back a').click(wu.mobileMenu.clickBack);
			jQuery('.open-menu').click(function(){
				/* show mobile menu */
				jQuery('.main-menu').toggleClass('open');
			});
		},

		/**
			@version 2015-05-12	initial creation to simplify processing of forward navigation movement
		*/
		clickAction: function(event) {
			if ($('nav.main-menu').hasClass('open')) {
				var li = jQuery(event.target).closest('li'),
					children = li.children('ul').toArray();
				/* check if this nav item has children, if so show kids, if not, allow normal click action to run */
				if (children.length > 0 && !li.hasClass('show-children')) {
					event.preventDefault();
					if (!jQuery('.mobile-back').hasClass('show-back')) {
						jQuery('.mobile-back').addClass('show-back');
					}
					li.addClass('show-children');
					li.closest('ul').addClass('show-one');
					li.closest('ul').parents('ul').removeClass('show-one').addClass('show-none');
					li.parents().removeClass('show-children');
					li.children('ul').addClass('open');
				}
			}
		},

		/**
			@version 2015-05-12	initial creation to simplify processing of back buttons in mobile navigation
		*/
		clickBack: function(event){
			event.preventDefault();
			var li = jQuery('.show-children').closest('li');
			li.children('ul').removeClass('open');
			li.removeClass('show-children');
			li.parentsUntil('div').each(function(index,element){
				switch (index) {
					case 0:
						jQuery(element).removeClass('show-one');
						break;
					case 1:
						jQuery(element).addClass('show-children');
						break;
					case 2:
 						jQuery(element).addClass('show-one').removeClass('show-none');
						break;
				}
			});
			if (li.closest('ul').hasClass('maxwidth')) {
				jQuery('.mobile-back').removeClass('show-back');
			}
		},
	},
	// ! FUNCTION: Get Faculty AJAX
	getFaculty: function(type, alpha, scroll) {
		if(scroll !== true){
			scroll = false;
			wu.current_page = 1;
			wu.oldscroll = 0;
		} else {
			wu.current_page++;
		}
		if(jQuery('#faculty_type').length > 0 && jQuery('#faculty_type').val() !== ''){
			wu.type = jQuery('#faculty_type').val();
		}
		jQuery.ajax({
			'url': baseurl + '/ajax/faculty',
			'type': 'post',
			'data': 'p=' + wu.current_page + '&type=' + wu.type + '&alpha=' + alpha,
			success: function (data) {
				if(scroll !== true){
					$("#faculty-list").html(data);
				} else {
					$("#faculty-list").append(data);
					$("#ajaxloader").hide();
				}
				//
			},
			complete: function (){
				//make sure there is not already a scroll observer, like first load of page
				wu.scroll.stop();
				//then start observing again
				wu.scroll.start();
			},
			error: function() {
				alert('error');
			}
		});
	},
	// ! FUNCTION: Faculty Sorting
	facultySort: function(type, alpha){
		// if we are on a faculty member detail page
		if(jQuery('.faculty-sort').hasClass('detail')){
			var link = jQuery('.parent').attr('href');
			jQuery('.faculty-sort .filters a').click(function(){
				var alpha = jQuery(this).attr('id').split('_').pop();
				document.cookie = "alpha=" + alpha + "; path=/";
				window.location = link;
			});
		// otherwise we are on the main directory
		} else {
			jQuery('.faculty-sort .filters a').click(function(){
				if (jQuery(this).hasClass('active')){
					jQuery(this).removeClass('active');
					jQuery('.faculty-member').each(function(){
						wu.getFaculty(wu.type);
					});
				} else {
					jQuery('.faculty-sort .filters a').each(function(){
						jQuery(this).removeClass('active');
					});
					jQuery(this).addClass('active');
				
					var alpha = jQuery(this).attr('id').split('_').pop();
					wu.getFaculty(wu.type, alpha);
				}
			});
			jQuery('.faculty-sort .reset').click(function(){
				jQuery('.faculty-sort .filters a').each(function(){
					jQuery(this).removeClass('active');
				});
				wu.getFaculty(wu.type);
			});
		}
	},
	// ! FUNCTION: Get News AJAX
	news: {
		get: function(type, scroll, date) {
			if(scroll !== true){
				scroll = false;
				wu.current_page = 1;
				wu.oldscroll = 0;
			} else {
				wu.current_page++;
			}
			jQuery.ajax({
				'url': baseurl + '/ajax/news',
				'type': 'post',
				'data': 'p=' + wu.current_page + '&type=' + type + '&date=' + wu.date,
				success: function (data) {
					if(scroll !== true){
						$("#news-list").html(data);
					} else {
						$("#news-list").append(data);
						//$("#ajaxloader").hide();
					}
					//
				},
				complete: function (){
					//make sure there is not already a scroll observer, like first load of page
					wu.scroll.stop();
					//then start observing again
					wu.scroll.start();
				},
				error: function() {
					alert('error');
				}
			});
		},
		category: function(){
			var category = jQuery('#news-list').attr('class').split(' ').shift().split('_').pop();
			wu.type = category;
			wu.news.get(wu.type);
		}
	},
	// ! FUNCTION: Get Events AJAX
	events: {
		get: function(type, scroll, date) {
			if(scroll !== true){
				scroll = false;
				wu.current_page = 1;
				wu.oldscroll = 0;
			} else {
				wu.current_page++;
			}
			wu.date = date;
			if(jQuery('#event_cat').length > 0 && jQuery('#event_cat').val() !== ''){
				wu.type = jQuery('#event_cat').val();
			}
			jQuery.ajax({
				'url': baseurl + '/ajax/events',
				'type': 'post',
				'data': 'p=' + wu.current_page + '&type=' + wu.type + '&date=' + wu.date + '&archive=' + wu.archive,
				success: function (data) {
					if(scroll !== true){
						$("#events-list").html(data);
					} else {
						$("#events-list").append(data);
						//$("#ajaxloader").hide();
					}
					//
				},
				complete: function (){
					//make sure there is not already a scroll observer, like first load of page
					wu.scroll.stop();
					//then start observing again
					wu.scroll.start();
				},
				error: function() {
					alert('error');
				}
			});
		},
		category: function(){
			var category = jQuery('#events-list').attr('class').split(' ').shift().split('_').pop();
			wu.type = category;
			wu.events.get(wu.type);
		}
	},
	/**
     * filter events/news archive by month/year
     * 
     */
    filterList: function (page_type, obj, year, month) {

        //$("#ajaxloader").show();

        if (month == '') {
            $("#years").find('a').removeClass("active");
            $("#months").show();
        }
        $("#months").find('a').removeClass("active");
        $(obj).addClass('active');
        current_page = 1;
        if (year != '') {
            $("#year").val(year);
            $("#month").val('');
        }
        if (month != '') {
            $("#month").val(month);
        }
        var date = $("#year").val() + '-' + $("#month").val();
        wu.date = date;
        if(page_type === 'events'){
	        wu.events.get(wu.type, false, wu.date)
        }
        if(page_type === 'news'){
	        wu.news.get(wu.type, false, wu.date)
        }
    },
	// ! FUNCTION: Calendar AJAX
	calendar: {
		get: function(month, year) {
			jQuery.ajax({
				'url': baseurl + '/ajax/events/calendar',
				'type': 'post',
				'data': 'month=' + month + '&year=' + year,
				success: function (data) {
					$("#calendar").html(data);
				},
				complete: function (){
					wu.calendar.nextPrev();
					wu.calendar.calFilters();
				},
				error: function() {
					alert('error');
				}
			});
		},
		nextPrev: function(){
			jQuery('.prev-month, .next-month').click(function(){
				var id = jQuery(this).attr('id'),
					next_or_prev = id.split('_').shift(),
					month = id.split('_').pop();
				if (next_or_prev === 'next' && month === '1'){
					wu.year++;
				} else if (next_or_prev === 'prev' && month === '12') {
					wu.year--;
				}
				wu.calendar.get(month, wu.year);
			});
		},
		calFilters: function(){
			jQuery('.day > a, .month > a').click(function(){
				var id = jQuery(this).attr('id'),
					date = id.split('_').pop();
				wu.date = date;
				wu.events.get(wu.type, false, date);
			});
			jQuery('a#reset').click(function(){
				wu.date = 'undefined';
				wu.month = new Date().getMonth()+1;
				wu.year = new Date().getFullYear();
				wu.events.get(wu.type);
				wu.calendar.get(wu.month, wu.year);
			});
		}
	},
	// ! FUNCTION: Scroll observers
	scroll: {
		start: function(){
			$(window).scroll(function () {
				wu.scroll.trigger();
			});
		},
		stop: function(){
			$(window).unbind("scroll");
		},
		trigger: function(){
			var alpha = false;
			//if the top of the window is greater than the last recorded scrolltop
			if ($(window).scrollTop() > wu.oldscroll && 
				// and if we are at the top of the footer
				($(window).scrollTop() + $(window).height() >= ($(document).height() - $("footer").height())) && 
				//and we have not yet reached the last page of items
				(wu.current_page < wu.total_pages)) {
				
				wu.scroll.stop();
				
				wu.oldscroll = $(window).scrollTop();
				//news scroll
				if (jQuery('.news-list').length > 0) {
					/* $("#ajaxloader").show(); */
					wu.news.get(wu.type, true);
				}
	
				//events scroll
				if (jQuery('.events-list').length > 0) {
// 					$("#ajaxloader").show();
					wu.events.get(wu.type, true, wu.date);
				}
	
				// faculty scroll
				if (jQuery('.faculty-list').length > 0) {
						//$("#ajaxloader").show();
						jQuery('.faculty-sort .filters a').each(function(){
							if(jQuery(this).hasClass('active')){
								alpha = jQuery(this).attr('id').split('_').pop();
							}
						});
						wu.getFaculty(wu.type, alpha, true);
				}
	
			}
			if(jQuery('#bgvid').length > 0){
				var vid = jQuery('#bgvid');
				if(wu.paused == false && $(window).scrollTop() > 300){
					vid.pause();
					wu.paused = true;
				} else if (wu.paused == true && $(window).scrollTop() <= 300){
					vid.play();
					wu.paused = false;
				}
			}
		}
	},
	// ! FUNCTION: Faculty Detail Tabs
	facultyTabs: function(){
		jQuery('.faculty-tab-select a').click(function(){
			if(jQuery(this).parent('li').hasClass('active')){
				jQuery(this).parent('li').removeClass('active');
				jQuery('.faculty-tab-select div.mobile').each(function(){
					jQuery(this).removeClass('active');
				});
				jQuery('.faculty-tabs div').each(function(){
					jQuery(this).removeClass('active');
				});
			} else {
				jQuery('.faculty-tab-select a').each(function(){
					jQuery(this).parent('li').removeClass('active');
				});
				jQuery(this).parent('li').addClass('active');
				var active = jQuery('.faculty-tab-select li.active').attr('class').split(' ').shift(),
					content = '';
				jQuery('.faculty-tabs div').each(function(){
					if(jQuery(this).hasClass(active)){
						jQuery(this).addClass('active');
						content = jQuery(this).html();
					} else {
						jQuery(this).removeClass('active');
					}
				});
				var top = jQuery('.faculty-tabs').offset().top - jQuery('header').height()-20;
				if (window.innerWidth < 864) {
					jQuery('.faculty-tab-select div.mobile').each(function(){
						if(jQuery(this).hasClass(active)){
							jQuery(this).addClass('active');
							jQuery(this).html(content);
						} else {
							jQuery(this).removeClass('active');
						}
					});
					top = jQuery('.faculty-tab-select li.active').offset().top;
				}
				jQuery('html, body').animate({scrollTop: top}, 500);
			}
		});
	},
	/* 
	 * Google search
	 * 
	 */
	google : {
	    cseID: '007040696005100772280:znc3r32chzq', // dev cse id
	    cseApiKey: 'AIzaSyAMic-K5Fbg_XgB1KWU9izOUgcy8B2sJhg', // dev api key
	    cseResultNum: 5,
	    cseButton: jQuery('#search-button'),
	    cseInput: jQuery('#search-value'),
	    printable: function (keycode) {
	        return  (keycode > 47 && keycode < 58) || // number keys
	                (keycode > 64 && keycode < 91) || // alpha keys
	                (keycode > 95 && keycode < 112) || // numpad keys
	                (keycode > 185 && keycode < 193) || // ;=,-./`
	                (keycode > 218 && keycode < 223) || // [\]'
	                (keycode == 32); // spacebar & return key
	    },
	    //captures the search event and initiates search handler
	    searchEvent: function () {
	        jQuery('#search-button').click(function (event) {
	            wu.google.searchHandler(event);
	            jQuery('html, body').animate({scrollTop: 0}, 500);
	            jQuery('.search-result-container').addClass('show-search-result');
	
	            var selectedIndex = jQuery('.typeahead-suggestion.selected').index();
	
	            if (selectedIndex > -1) {
	                wu.google.cseInput.val(jQuery('.typeahead-suggestion.selected').first().attr('data-query'));
	            }
	            wu.typeahead.query(jQuery('.typeahead-suggestion.selected').first().attr('data-query'));
	        });
	        //allows user to hit "return" key to submit search
	        jQuery('#search-value').keyup(function (event) {
	            /*
	             event.preventDefault();
	             event.stopPropagation();
	             */
	            //$(".typeahead-results").show();
	            var selectedIndex = jQuery('.typeahead-suggestion.selected').index();
	
	            // arrow keys
	            if (event.keyCode >= 37 && event.keyCode <= 40) {
	                wu.typeahead.selectOptions(event.keyCode);
	
	                // printable characters	should update the typeahead
	            } else if (wu.google.printable(event.keyCode)) {
	                wu.typeahead.query(wu.google.cseInput.prop('value'));
	
	                // return key
	            } else if (event.keyCode == 13) {
	                if (selectedIndex !== -1) {
	                    wu.google.cseInput.prop(jQuery('.typeahead-suggestion.selected').first().attr('data-query'));
	
	                    wu.typeahead.query(jQuery('.typeahead-suggestion.selected').first().attr('data-query'));
	                    jQuery('html, body').animate({scrollTop: 0}, 500);
						jQuery('.search-result-container').addClass('show-search-result');
	                } else {
	                    //search.query( wu.google.cseInput.prop('value') );
	                }
	                if (jQuery('.typeahead-suggestion.selected').first().attr('data-query') !== undefined) {
	                    wu.google.query(jQuery('.typeahead-suggestion.selected').first().attr('data-query'));
	                    jQuery('html, body').animate({scrollTop: 0}, 500);
						jQuery('.search-result-container').addClass('show-search-result');
	                } else {
	                    jQuery('#search-button').trigger('click');
	                }
	            }
	        });
	        /*
	         function (event) {
	         
	         if (event.keyCode == 13) {
	         jQuery('#search-button').trigger('click');
	         }
	         });
	         */
	    },
	    //retrieves search data using google search keys and ids
	    searchHandler: function (event) {
	        var value = jQuery('#search-value').val();
	        event.stopPropagation();
	        jQuery.getJSON('https://www.googleapis.com/customsearch/v1?key=' + wu.google.cseApiKey + '&cx=' + wu.google.cseID + '&q=' + value + '&num=' + wu.google.cseResultNum + '&callback=?', function (data) {
	            wu.google.searchResultDisplay(data);
	        });
	    },
	    // if user pages through results, process that seperately (rel contains built out links for prev/next)
	    searchNextPrev: function (event) {
	        var link = jQuery(event.target).attr('rel');
	        event.stopPropagation();
	        jQuery.getJSON(link, function (data) {
	            wu.google.searchResultDisplay(data);
	        });
	    },
	    // display results from CSE search
	    searchResultDisplay: function (data) {
	        // clear previous search returns
	        wu.google.searchClear();
	        if (data.error) {
	            jQuery('#search-results').append("<p>Error: " + data.error.message + "</p>");
	            jQuery('.search-results-nav').show();
	        } else {
	            var results = data.searchInformation.totalResults,
	            	start = 0,
					end = 0;
	            if (results > 0) {
	                start = data.queries.request[0].startIndex;
	                end = data.queries.request[0].count + data.queries.request[0].startIndex  - 1;
	            }

	            jQuery('#search-results').append("<div class='search-header-footer'><h3>" + start + "-" + end + " OF ABOUT " + results + " RESULTS</h3></div>");
	            // create entry for each item returned
	            jQuery(data.items).each(function (index, entry) {
		            // remove empty parts of the url for trailing slashes
		            var url = entry.formattedUrl.split('/').filter(function(e){return e}); 
	                jQuery('#search-results').append('<div class="search-result-content"><a href="' + entry.link + '"><h4>' + entry.htmlTitle + '</h4><p>' + entry.htmlSnippet.replace('<br>', '') + '</p><p class="related-url">' + entry.displayLink + '/.../' + url.pop().split('?').shift() + '</p></a></div>');
	            });
	
	            // for mobile, display less items, set width to appropriate mobile template pixels
	            if (window.innerWidth <= 720) {
	                wu.google.cseResultNum = 3;
	            }
	
	            // build out URL and show if next/prev pages available
	            if (data.queries.nextPage != undefined && data.queries.nextPage.length > 0) {
	                jQuery('#next-results').attr('rel', 'https://www.googleapis.com/customsearch/v1?key=' + wu.google.cseApiKey + '&cx=' + wu.google.cseID + '&q=' + data.queries.request[0].searchTerms + '&num=' + wu.google.cseResultNum + '&start=' + data.queries.nextPage[0].startIndex + '&callback=?');
	                jQuery('#next-results').show();
	            }
	            if (data.queries.previousPage != undefined && data.queries.previousPage.length > 0) {
	                jQuery('#prev-results').attr('rel', 'https://www.googleapis.com/customsearch/v1?key=' + wu.google.cseApiKey + '&cx=' + wu.google.cseID + '&q=' + data.queries.request[0].searchTerms + '&num=' + wu.google.cseResultNum + '&start=' + data.queries.previousPage[0].startIndex + '&callback=?');
	                jQuery('#prev-results').show();
	            }
	            jQuery('.search-results-nav').click(function (event) {
	                jQuery('html,body').animate({
	                    scrollTop: jQuery('header').offset().top
	                }, 300);
	                setTimeout(function () {
	                    wu.google.searchNextPrev(event);
	                }, 300);
	            });
	
	            if (results == 0) {
	                jQuery('#search-results').html("<h1>No result found.</h1>");
	            }
	        }
	
	    },
	    // clear out previous returned results, hide prev/next buttons
	    searchClear: function () {
	        jQuery('#search-results').children().remove();
	        jQuery('.search-results-nav').hide();
	    },
	    //retrieves search data using google search keys and ids for autocomplete
	    query: function (searchString, si) {
	        jQuery.ajax({
	            url: 'https://www.googleapis.com/customsearch/v1?',
	            data: {
	                q: searchString,
	                num: wu.google.cseResultNum,
	                start: si ? si : 1,
	                key: wu.google.cseApiKey,
	                cx: wu.google.cseID
	                        // alt: 'json',   // response type
	                        // callback: '',  // optional for jsonp
	                        // fields: value  // optional for limititing response
	            },
	            dataType: "jsonp",
	            success: function (data) {
	                if (!data.error) {
	                    wu.google.searchResultDisplay(data);
	                } else {
	                }
	            }
	        });
	    }
	},
	typeahead : {
	    receiveSuggestions: function (data) {
	        var suggestions = [];
	        jQuery.each(data[1], function (key, val) {
	            suggestions.push(val);
	        });
	
	        suggestions.length = 5; // limit results
	
	        var addSuggestion = function (term) {
	            if (term) {
	                jQuery('ul.typeahead-results')
	                        .append(jQuery('<li/>', {class: "typeahead-suggestion", 'data-query': term})
	                                .append(jQuery('<a/>', {href: '#'})
	                                        .text(term)
	                                        .click(term, function (e) {
	                                            e.stopPropagation();
	                                            e.preventDefault();
	                                            wu.google.query(e.data);
	                                            jQuery('html, body').animate({scrollTop: 0}, 500);
	                                            jQuery('.search-result-container').addClass('show-search-result');
	                                        })));
	            }
	        },
	                populateOptions = function (data) {
	                    jQuery('ul.typeahead-results').empty();
	
	                    for (var i = 0; i < data.length; i++) {
	                        if (data[i])
	                            addSuggestion(data[i][0]);
	                    }
	                };
	
	        populateOptions(suggestions);
	
	    },
	    selectOptions: function (keyCode) {
	        var down = 40,
	                left = 37,
	                up = 38,
	                right = 40,
	                selectedItemIndex = jQuery('.typeahead-suggestion.selected').index(),
	                finalItemIndex = jQuery('.typeahead-suggestion').index(jQuery('.typeahead-suggestion').last());
	
	        // remove selected from everything now that we have the indices saved
	        jQuery('.typeahead-suggestion').removeClass('selected');
	
	        if (keyCode === down) {
	            if (selectedItemIndex === -1) {
	                jQuery('.typeahead-suggestion').first().addClass('selected');
	            } else if (selectedItemIndex !== finalItemIndex) {
	                jQuery(jQuery('.typeahead-suggestion').get(selectedItemIndex + 1)).addClass('selected');
	            } else {
	                // let it die to indicate the user is back in the search bar
	            }
	        }
	        if (keyCode === up) {
	            if (selectedItemIndex > 0) {
	                jQuery(jQuery('.typeahead-suggestion').get(selectedItemIndex - 1)).addClass('selected');
	            } else if (selectedItemIndex === -1) {
	                jQuery('.typeahead-suggestion').last().addClass('selected');
	            } else {
	                // let it die to indicate the user is back in the search bar
	            }
	        }
	    },
	    query: function (request) {
	        jQuery.ajax({
	            url: 'http://clients1.google.com/complete/search?',
	            data: {
	                q: '' + request,
	                hl: 'en',
	                client: 'partner',
	                source: 'gcsc',
	                partnerid: wu.google.cseID,
	                ds: 'cse'
	            },
	            dataType: "jsonp",
	            success: function (data) {
	                wu.typeahead.receiveSuggestions(data);
	            }
	        });
	    }
	},
	mobileTables: function(){
		// Put the footer at the bottom where it belongs
		jQuery('.right-content table').each(function(){
			var titles = [];
			if(jQuery(this).find('tfoot').length > 0){
				var footer = jQuery(this).find('tfoot'),
					body = jQuery(this).find('tbody');
				body.after(footer);		
			}
			jQuery(this).find('thead tr:last-child td').each(function(){
				var thistitle = jQuery(this).html().split('&nbsp;').pop();
				titles.push(thistitle);
			});
			if(titles !== undefined && titles.length > 0){
				jQuery(this).find('tbody tr').each(function(){
					num = 0;
					jQuery(this).find('td').each(function(){
						if(titles[num] !== undefined && num < titles.length){
							console.log(titles[num]);
							jQuery(this).prepend('<span class="table-title">' + titles[num] + ' </span>');
						}
						num++;
					});
				});
			}
		});
	},
	resize: function(){
		if(jQuery('.home').length > 0){
			wu.ourStories();
			wu.backgroundCover(jQuery('video'));
		}
		if(window.innerWidth < 1025 && jQuery('.give-apply > ul.utility').length <= 0){
			jQuery('.give-apply > ul').before( jQuery('.utility').clone() );
		}
		if (window.innerWidth < 651 && jQuery('.featured-image').length > 0){
			wu.backgroundCover(jQuery('.featured-image img'));
		} else if (jQuery('.featured-image').length > 0) {
			jQuery('.featured-image img').css({margin: ''});
		}
	}
};
jQuery(document).ready(function(){
	wu.init();
});