//
// Undergraduate Studies
// Display-time layout modifications
// Originally by Adam Mark Finlayson, WTS
// amf%northwestern!edu
// Updated by Ethan Romba
//

// Declare a global object with default behavior settings
// All site-specific global variables belong in this object
WCAS = {
	equalizeCols: false,			// Whether or not to equalize column height in IE6/IE7
	fadeDuration: 200,				// Duration (in ms) to fade body> in/out when toggling the printer-friendly view
	slideshowSettings: {			// Settings for sidebar-slideshows (using the jQuery Cycle plugin):
		timeout: 7000,				//   The duration (in ms) to show each image
		random: 1					//   0 = show images in order, 1 = show images randomly
	},
	flickrUserId: '62495159@N03', // Any Flickr-photos slideshows on the page will display public photos from this Flickr user
	numFlickrImages: 20				// The maximum number of images to load from Flickr
};

//
// WCAS.equalizeHeight(select0, select1, ..., selectorN)
//
// Used to set heights of elements (by CSS selector) to the
// largest height of the group. Simulates table-based layouts.
//
// Example:
//     WCAS.equalizeHeight("#first-element", ".other-elements");
//
// This function differs from the version in
// /shared/js/layout.js in the following ways:
//   - Called with CSS selectors
//   - Accounts for the top- and bottom-padding of each element
//   - Does not resize the tallest element
//
WCAS.equalizeHeight = function() {
	var elements = arguments;
	var $element = null;
	var height = 0;
	var maxHeight = 0;
	var newHieght = 0;
	var tallestElem = 0;
	// Find the tallest column and record its height
	for (var i=0; i < elements.length; i++) {
		$element = $(elements[i]);
		if ($element.length != 0) {
			height =
				parseInt($element.height())
				+ parseInt($element.css('padding-top'))
				+ parseInt($element.css('padding-bottom'));
			if (height > maxHeight) {
				maxHeight = height;
				tallestElem = i;
			}
		}
	}
	// Resize the other columns to be the same height
	for (var i=0; i < elements.length; i++) {
		$element = $(elements[i]);
		if ($element.length != 0 && i != tallestElem) {
			newHeight = 
				maxHeight
				- parseInt($element.css('padding-top'))
				- parseInt($element.css('padding-bottom'));
			$element.height(newHeight);
		}
	}
};

//
// WCAS.equalizeColumns(reset)
//
// A wrapper for WCAS.equalizeHeight(), specific to this standard-site template,
// used to equalize the height of the main content columns.
//
// Arguments:
//   - reset: when true, causes the height of the columns to be reset
//            prior to their equalization
//
WCAS.equalizeColumns = function(reset) {
	if (WCAS.equalizeCols) {
		if (reset === true) {
			$('#main div[id^=col]').height('auto');
			$('#col2 div[id^=content-col]').height('auto');
		}
		if ($('#content-col1').length > 0) {
			WCAS.equalizeHeight('#content-col1', '#content-col2');
		}
		WCAS.equalizeHeight('#col1', '#col2', '#col3');
	}
};

//
// WCAS.hidePrinterFriendlyView()
//
// Used to remove printer-friendly stylesheets and
// layout modifications and return the page to standard-view
//
WCAS.hidePrinterFriendlyView = function() {
	// In IE7, the main-navigation highlight images misbehave when
	// returning from the printer-friendly view, so we refresh the page
	if ($.browser.msie && $.browser.version == '7.0') {
		location.reload();
	}
	// On all other browsers, we manipulate the existing DOM
	else {
		// Hide the page (with a fade-out on modern browsers)
		$('body').fadeOut(WCAS.fadeDuration, function() {
			// Hide printer-friendly navigation
			$('#printer-friendly-nav').hide();
			// Remove print.css and added header/footer elements
			$('#print-css, #wcas-logo, #current-url, .mmhide_nu-wcas, .mmhide_separator').remove();
			// Change header logo to the full-size version
			$('#logo img').attr('src', '/images/logo.png');
			// Restore footer elements to their original locations in the DOM
			$('#copyright').detach().appendTo('#contact-info');
			$('div.mmhide_org').detach().prependTo('.mmhide_vcard');
			// Show the page (with a fade-in on modern browsers)
			$('body').fadeIn(WCAS.fadeDuration);
			// Re-equalize columns on IE6/IE7
			WCAS.equalizeColumns();
			// Resume the sidebar slideshow
			$('#sidebar-slideshow').cycle('resume');
		});
	}
	$(document).unbind('keydown.WCAS');
}

//
// WCAS.showPrinterFriendlyView()
//
// Used to display a "printer-friendly" version of the current page.
//
// This function adds print.css as a media="screen" stylesheet and 
// performs a few DOM manipulations to optimize the page for printing.
//
WCAS.showPrinterFriendlyView = function() {
	$('body').fadeOut(WCAS.fadeDuration, function() {
		// Pause the sidebar slideshow
		$('#sidebar-slideshow').cycle('pause');
		// Add print.css (media="screen" by default)
		$('head').append('<link id="print-css" rel="stylesheet" href="/css/print.css" type="text/css" />');
		// Show printer-friendly navigation
		$('#printer-friendly-nav').show();
		// Change header image to the smaller-size version and insert Weinberg logo next to it
		$('#logo img')
			.attr('src', '/images/logo-small.gif')
			.removeAttr('height')
			.removeAttr('width');
		$('#logo').after('<img id="wcas-logo" alt="Weinberg College of Arts &amp; Sciences" src="/images/layout/weinberg-logo-small.gif" height="62" width="267" />');
		// Print the current URL after the main content
		$('#col2').append('<span id="current-url"><span>URL for this page:</span> '+window.location+'</span>');
		// Move certain footer elements around
		$('#copyright').detach().insertBefore('#contact-info');
		$('div.mmhide_org').detach().insertBefore('div.mmhide_adr');
		$('div.mmhide_vcard div').prepend('<span class="mmhide_separator">| </span>');
		$('div.mmhide_vcard').after('<p class="mmhide_nu-wcas">Northwestern University // Judd A. and Marjorie Weinberg College of Arts and Sciences</p>');
		// Remove height rules set by WCAS.equalizeColumns() on IE6/IE7
		if (WCAS.equalizeCols) {
			$('#main div[id^=col]').height('auto');
			$('#col2 div[id^=content-col]').height('auto');
		}
		// IE7 needs some extra help hiding just about everything
		if ($.browser.msie && $.browser.version == '7.0') {
			$('#nav, #col1, #col3').remove();
		}
		$('body').fadeIn(WCAS.fadeDuration);
		// Make the backspace key (used to go "back" by default)
		// return the page to standard-view. We use the keydown event
		// instead of keypress since IE does not trigger the latter
		// when modifier keys are pressed
		$(document).bind('keydown.WCAS', function(event) {
			if (event.which == 8) {
				$('#printer-friendly-back').click();
				return false;
			}
		});
	});
}

$(document).ready(function() {
	
	/*
	 * BROWSER-SPECIFIC OPERATIONS
	 */
	
	if ($.browser.msie) {
		switch ($.browser.version) {
			case "6.0":
				// Add hover class for navigation links in IE6
				$("#nav li").each(function() {
					$(this).hover(function(){
							$(this).addClass('mmhide_ie6-hover');
						},function(){
							$(this).removeClass('mmhide_ie6-hover');
						});
				});
				$('ul.mmhide_sidebar-slideshow li:first-child').addClass('mmhide_first');
			case "7.0":
				// Equalize column-height for IE6 and IE7
				WCAS.equalizeCols = true;
			case "8.0":
				// Disable fade effects on IE6, IE7, and IE8
				WCAS.fadeDuration = 0;
			break;
		}
		// IE7 needs some extra help sizing/displaying the
		// main-navigation highlight images due to its faulty support
		// for the sibling selector (+) in dynamic content
		// (See http://quirksmode.org/css/contents.html)
		if ($.browser.version === '7.0') {
			$('#nav img.mmhide_highlight').each(function() {
				if ($(this).prev().hasClass('mmhide_current')) {
					$(this).css('display', 'block');
				}
				$(this).width( $(this).parent().width() );
			});
		}
	}
	// Normally, we wouldn't want to use JavaScript to apply basic CSS styles.
	// But because the CSS selectors we use to target Dreamweaver/Contribute
	// also affect Firefox 2, we have no choice but to fix FF2 dynamically.
	else if ($.browser.mozilla && $.browser.version.indexOf('1.8') === 0) {
		$('#nav li, #nav ul li').css('display', 'inline');
		$('#nav > li > img').css('top', '-7px');
		$('#nav > li > ul').css('top', '21px');
		$('#main').css('position', 'static');
		$('#col1, #col2, #col3, #content-col1, #content-col2').css({
			display: 'table-cell',
			float: 'none'
		});
		$('#col2 #breadcrumb').css({
			margin: '1em 0 1em',
			position: 'relative'
		});
		$('#footer').css('line-height', '1.5');
		$('#footer .mmhide_logo').css('margin-top', '-47px');
	}
	
	/*
	 * PRINTER-FRIENDLY VIEW & SOCIAL MEDIA LINKS SETUP
	 */
	
	// We do not add printer-friendly functionality
	// or social media links on the Home, News, and similar pages
	if ($('#main').hasClass('mmhide_two-col-content') === false) {

		// Add CSS that hides "printer-friendly" navigation links when printing
		$('head').append('<style type="text/css" media="print">#printer-friendly-nav { display: none !important; }</style>');
		// Add "printer-friendly" navigation links to the top of the page
		var backLink = '<a id="printer-friendly-back" href="#">&laquo;Back to standard view</a>';
		var printThisPageLink = '<a id="print-this-page" href="#">Print this page</a>';
		$('body').prepend('<div id="printer-friendly-nav">'+backLink+printThisPageLink+'</div>');
		$('#printer-friendly-back').click(function() {
			WCAS.hidePrinterFriendlyView();
			return false;
		});
		$('#print-this-page').click(function() {
			window.print();
			return false;
		});
		
		// Add "Email this page" and "Printer-friendly version" links before the page content
		$('#col2 h1').first().wrap('<div id="heading-1"></div>').before('<div id="utility-links"><span></span></div>');
		$('#utility-links span').append('<a id="email-link" href="mailto:?body='+window.location+'" title="Email this page"></a>');
		$('#utility-links span').append('<a id="print-link" href="#" title="Printer-friendly version"></a>');
		$('#print-link').click(function() {
			WCAS.showPrinterFriendlyView();
			return false;
		});
		
		// Add social-media links after the page content
		if (document.getElementById('content-col2') !== null) {
			$('#content-col2').append('<div id="share-links"></div>');
		}
		else {
			$('#col2').append('<div id="share-links"></div>');
		}
		// These links are specified in /includes/share-links.html, which we load via AJAX
		$('#share-links').load('/includes/share-links.html');

	}
	
	/*
	 * SIDEBAR SLIDESHOW / LIGHTBOX SETUP
	 */
	
	var InitSlideshows = function() {
		
		// Add "view-larger" magnifying-glass overlay image to non-empty, right-sidebar lightbox images
		var overlayImage = $('<img src="/images/layout/view-larger.gif" alt="" class="mmhide_view-larger-overlay" />');
		$('#col3 a.mmhide_lightbox:parent, #col3 a.mmhide_slideshow-lightbox:parent').append(overlayImage);

		$('#col3 ul.mmhide_sidebar-slideshow')
			// Add lightbox functionality to any sidebar-slideshows
			// We use each() here to keep each lightbox group separate
			.each(function(index, element) {
				$(element).find('a.mmhide_slideshow-lightbox').lightBox({
					// When any lightbox is open, it will pause all slideshows on the page
					onStart: function() { $('ul.mmhide_sidebar-slideshow').cycle('pause') },
					onClose: function() { $('ul.mmhide_sidebar-slideshow').cycle('resume') }
				});
			})
			// Initialize the slideshows
			.cycle(WCAS.slideshowSettings);

		// Re-equalize columns on IE6/IE7
		WCAS.equalizeColumns(true);
	};
	
	// If no flickr-photos list is found, we set up the sidebar slideshows immediately
	// Otherwise, we wait until the necessary images are loaded from Flickr
	var $flickrPhotos = $('#flickr-photos');
	if ($flickrPhotos.length === 0) {
		InitSlideshows();
	}
	else {
		// Load Flickr photos and create a slideshow with them
		$flickrPhotos.jflickrfeed({
			limit: WCAS.numFlickrImages,
			qstrings: {
				id: WCAS.flickrUserId
			},
			itemTemplate: '<li><p class="image">'
				+ '<a href="{{image_b}}" class="mmhide_slideshow-lightbox" title="{{title}}.">'
				+ '<img class="mmhide_flickr-image" src="{{image_m}}" alt="" /></a></p><p class="caption">{{title}}</p></li>'
		}, function() {
			// IE6 refuses to run the load event handler, so we initialize the slideshow
			// as soon as the Flickr image elements have been added to the page
			if ($.browser.msie && $.browser.version === '6.0') {
				InitSlideshows();
				return;
			}
			// We only initialize the slideshow once every image has been loaded
			var $images = $flickrPhotos.find('img.mmhide_flickr-image');
			var numImages = $images.length;
			$images.bind('load', function() {
				// As each image loads, we check if all of the Flickr images are ready
				var ready = true;
				for (var i=0; i < numImages; i++) {
					if ($images[i].complete === false && $images[i].readyState !== 'complete') {
						ready = false;
					}
				}
				if (ready === true) {
					InitSlideshows();
				}
			});
		});
	}

	// Add lightbox functionality to any non-slideshow images in the sidebar.
	// If any of these lightbox links are empty (ie. they have no thumbnail),
	// we also add an "All NAME photos" link after the last thumbnail
	// (where NAME is the text contained in the first H1 heading on the page).
	// The link simply launches the lightbox when clicked.
	// This functionality allows us to include more photos in the lightbox without
	// having to show all of their thumbnails in the sidebar.
	var $sidebarLightboxLinks = $('#col3 a.mmhide_lightbox');
	if ($sidebarLightboxLinks.length > 0) {
		$sidebarLightboxLinks.lightBox();
		var $emptyLinks = $sidebarLightboxLinks.filter(':empty');
		if ($emptyLinks.length > 0) {
			var linkText = $.trim($('h1').first().text());
			$emptyLinks
				.first()
				.before('<p style="text-align: right">&raquo; <a id="all-photos-link" href="#">All '+linkText+' photos</a></p>');
			$('#all-photos-link').click(function() {
				$sidebarLightboxLinks.first().click();
				return false;
			});
		}
	}

	/*
	 * MINOR DOM MANIPULATIONS
	 */

	// Add an icon after links with target="blank"
	// We do not add an icon after the social-media links
	$('#col3 a[target$="blank"]').each(function() {
		$this = $(this);
		if ($this.parent().attr('id') != 'share-links') {
			$this.after('<img class="external-link-icon" src="/images/layout/external_link.png" height="12" width="12" />');
		}
	});

	// Equalize column-height for IE6 and IE7
	$(window).bind('load', function() {
		WCAS.equalizeColumns();
	});

	// Highlight links to the current page and section
	highlightSection_RootRelative('nav', 'mmhide_current');
	addHighlight('nav', 'mmhide_current');
	addHighlight('left-nav', 'mmhide_current');

	// Make search-box clear itself when clicked
	$('#search-text')
		.bind('focus.WCAS', function() {
			if (this.value == "Search site...") {
				this.value = '';
			}
		})
		.bind('blur.WCAS', function() {
			if (this.value == '') {
				this.value = "Search site...";
			}
		});

	// Move last-updated date from the bottom of the page to the footer
	$('#last-updated').detach().prepend('|&nbsp;Last Updated: ').appendTo('#copyright');
});

