// Self executing function sexiness. Keeps the site clear of unnecessary variables.
(function($) {
	if(!window.TUCK) window.TUCK = {};

	// Stubs in case I leave console calls in the code next time.
	if(!window.console) {
		console = {};
		console.log = function() {};
		console.dir = function() {};
	}


	// Add some utility code.
	$.extend(TUCK, {
		_preloads: [],
		_ie6: null,
		
		isIE6: function() {
			if(this._ie6 === null) {
				this._ie6 = ($.browser.msie && $.browser.version == '6.0');
			}
			return this._ie6;
		},
		
		// Check to see if we're on the homepage
		isHome: function() {
			return $(document.body).hasClass('home');
		},
		
		// Kind of like sprtinf but less technical
		_processString: function(str, vars) {
			for (ph in vars) {
				var re = new RegExp('{{'+ph+'}}', 'g');
				str = str.replace(re, $.trim(vars[ph]));
			}
			return str;
		},
		
		// Image preloader function
		preloadImages: function(images) {
			if(typeof images === 'string') images = [images];
			
			for(var i = 0, il = images.length; i < il; i++) {
				this._preloads[i] = new Image();
				this._preloads[i].src = images[i];
			}
		}
	});
	
	// Bind image preloader to load event
	$(window).bind('load', function() {
		TUCK.preloadImages([
			'/assets/tuck/img/bg-tab-subnav.png',
			'/assets/tuck/img/bg-tab-subnav.png'
		]);
	});
	
	$(function() { // ready() shorthand
		// Emergency Alert code
		var $ticker = $("#ticker01"), msg, start;
		if($ticker.length) {
			// $ticker.liScroll({travelocity: 0.15}); 
			// Wrap everything in front of a colon in a strong tag
			msg = $.trim($ticker.text());
			parts = msg.split(':');
			if(parts.length == 1) {
				str = '<strong>'+parts[0]+'</strong>';
			} else {
				str = '<strong>'+parts[0]+':</strong>'+parts[1];
			}
			$ticker.find('a').html(str);
			
			$ticker.liScroll();
		}
		
		var isHome = TUCK.isHome();
		
		// Apply PNG Fix
		$(document).pngFix(); 

		// Faculty Directory dropdown sort controls
		var $jm = $('#jumpMenu');
		if($jm.length) {
			$jm.change(function(e) {
				window.location = $(this).val();
			});
		}

		// For better UX, "back" links run history.back() if JS is on
		$('a.backlink').click(function(ev) {
			ev.preventDefault();
			history.back();
			return false;
		});

		// Header search
		$('.navTop li.search > a').click(function(ev) {
			ev.preventDefault();
			var $form = $(this).siblings('#headerSearch');

			if($form.is(':visible')) $form.hide();
			else $form.show();
		});

		// IE 6 Show sub nav flyout on hover "fix"
		if(TUCK.isIE6()) {
			$('.navBottom > ul > li').hover(function() {
				$(this).addClass('over');
			}, function() {
				$(this).removeClass('over');
			});
		}

		//slideshow control
		var $banner = $('#banner');
		if($banner.length) {
			if(!TUCK.isIE6()) {
				if(isHome) {
					$banner.cycle({
				        fx:      'scrollHorz',
				        timeout:  10000,
				        prev:    '#prev2',
				        next:    '#next2',
				        pager:   '#nav',
						pagerAnchorBuilder: function(idx, slide) {
							var s = idx > 2 ? ' style="display:none"' : '';
							return '<a href="#"><span>'+(idx+1)+'</span></a>';
						}
				    });
				} else {
					if($('.bannerContainer', $banner).length > 1) {
						$(document.body).addClass('bannerSlideshowEnabled');
				
						$('#nav').parent().show();
						$banner.cycle({
							fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
							speed: ((!$.browser.msie) ? 1500 : 0), 
					    	timeout: 7500,
					    	pause: 1,
					    	pager:  '#nav',
					    	fastOnEvent: 1
					    });
					}    
				}
			} else {
				// Apply slideshow styles in IE6 even though the slideshow doesn't run
				if(!isHome && $('.bannerContainer', $banner).length > 1) $(document.body).addClass('bannerSlideshowEnabled');
			}
		}
		

		var $gallery = $('#galleria');
		if($gallery.length) {

			// Load Galleria theme
		    Galleria.loadTheme(TUCK._pv_root_url+'/assets/tuck/js/themes/classic/galleria.classic.js');

		    // run galleria and add some options
		    $gallery.galleria({
		        // image_crop: true, // crop all images to fit
		        // thumb_crop: true, // crop all thumbnails to fit
		        transition: 'fade', // crossfade photos
		        transition_speed: 700, // slow down the crossfade
		        data_config: function(img) {
		            // will extract and return image captions from the source:
		            return  {
		                title: $(img).parent().next('strong').html(),
		                description: $(img).parent().next('strong').next().html()
		            };
		        }
		    });
		}
	    

		// Video toggling on homepage
		var $vm = $('.videosModule'),
			tl = $('.thumb', $vm).length;
		if($vm.length && (tl >= 2 && tl <= 4)) { // Only run if the videoModule code is present and there's between 2 and 4 thumbs
			$('.wrapperVideoThumbs .thumb a', $vm).each(function(idx, el) {
				var $t = $(this),
					vid = $t.attr('href').split('#')[1];
				
				$t.attr('href', '#'+vid).click(function(ev) {
					ev.preventDefault();

					// Get useful vars
					var vid = this.hash.substr(1), // Video ID from the link's hash
						tmp = $(this).attr('title').match(/([^:]+):?\s*([^\[]+)?/), // Break out the Caption parts from the link title attr
						parts = {
							'title': tmp[1],
							'caption': tmp[2] || '' // Blank if no caption
						},
						caption = '<span class="subject">{{title}}</span> {{caption}}' // Main video caption shell
						;

					// Update the URLs of the YT video and the caption
					$('#videoObject', $vm).get(0).cueVideoById(vid);
					$('.videoCaption', $vm).empty().append(TUCK._processString(caption, parts));

				});
			});
		}

		// Dynamically add classes to top-level nav items for custom styling to work with EE Structure
		$('.navBottom > ul > li').each(function(idx, el) {
			$el = $(el);
			navClass = $el.children('a').eq(0).attr('href').replace(/http:\/\/[^\/]+\//,'').split('/')[0];
			if(navClass) $el.addClass(navClass);
		})
	
	
		if($('.navBottom').length) {
			// Strip sub lists beyond 2nd level in main nav
			$('.navBottom ul ul ul').remove();

			// Easy List Splitter code
			$('.navBottom > ul > li > ul').easyListSplitter({colNumber:4});
		}

		// Enable footer tab functionality
		$('#footerMain .tabs a').click(function(ev) {
			// Prevent default click behavior
			ev.preventDefault();
			
			// Set up some variables and grab some resuable DOM references
			var $t = $(this), // Quick ref for the clicked link
				$fm = $('#footerMain').eq(0), // Quick ref for the containing footer div
				id = $t.attr('href').split('#')[1], // Get the id out of this link's href
				visName = $('.panel:visible', $fm).get(0).id.substr(6), // Get the name of the currently showing panel (Tuck, Centers, Corporate)
				tgtName = id.substr(6); // Get the name of the target panel to show, like above
		
			$('.tabs', $fm).removeClass('active'+visName).addClass('active'+tgtName); // Change indicator class for proper tab styling
			$('.panel', $fm).hide().siblings('#'+id).show(); // Swap which panel is visible
		});
		
		var $faq = $('#faq');
		if($faq.length) {
			$('dd', $faq).hide() // Grab all the <dd> tags inside #faq and hide them to start
				.filter(':first').show() // Get the first <dd> from all the selected ones and show it
				.prev('dt').children('a').addClass('faq-sel'); // Grab the shown <dd>'s paired <dt> and add a class to its <a>
			$('dt a', $faq).click(function(ev) { // Assign click to all <a>'s in <dt>'s
				ev.preventDefault(); // Prevent default
				$('.faq-sel', $faq).removeClass('faq-sel') // Grab all the elements with the selected class...
					.parent('dt').next('dd').hide(); // ...and hide the paired <dd>
				$(this).addClass('faq-sel') // Add the selected class to the clicked element...
					.parent('dt').next('dd').fadeIn(); // ...and show the paired <dd>
			});
			
		}
		
		// Search results pagination consistency
		var $pag = $('.pagination');
		if($pag.length) {
			$pag.each(function() {
				if($('li', this).length === 0) $(this).children().each(function() {
					var $t = $(this);
					if(/\D/.test($t.text())) $t.remove();
				});
			})
		}
		
		// SR/NSR page current class code
		var lp = location.pathname;
		if(/search/.test(lp)) {
			var url,
				media = lp.match(/(articles|videos|galleries)/);
			if(media) {
				switch(media[1]) {
					case "articles": url = "news/articles";break;
					case "videos": url = "news/video";break;
					case "galleries": url = "news/photo-galleries";break;
				}
				
				$($('.navBottom a[href*='+url+']')).parent('li').addClass('current').parents('li').addClass('parent-current');
				$($('.sidebarNav a[href*='+url+']')).parent('li').addClass('current').parents('li').addClass('parent-current');
			}
		}
		

	});
	
	
})(jQuery);

