/**
 * Display-time layout modifications
 * By Ethan Romba
 */

/**
 * SITE CONFIGURATION SETTINGS
 * (All site-specific global variables belong in this object)
 */
WCAS = {
  // Whether or not to apply a random "theme" class to <body>
  randomTheme: true,
  // The number of "theme" classes defined in /css/color.css (e.g. "theme1", "theme2", etc.)
  numberOfThemes: 1,
  // Duration (in ms) to fade <body> in/out when toggling the printer-friendly view
  fadeDuration: 200,
  // Settings for photo slideshows (powered by the jQuery Cycle plugin):                     
  slideshowSettings: {
	// The duration (in ms) to show each image
    timeout: 7000,
	// true = show images randomly; false = show images in the order they appear in the HTML                     
    random: true
  },
  // The default Flickr account from which to load Flickr images (http://idgettr.com/)
  defaultFlickrId: '71252033@N07',
  // Template for the caption that appears below Flickr slideshow thumbnails
  flickrThumbnailCaptions: '{{title}}',
  // Template for the caption that appears below Flickr Lightbox images
  flickrLightboxCaptions: '{{title}}' 
  // (These templates may use any combination of {{title}} and {{description}}:
  //   e.g. '{{title}}', '{{title}} // {{description}}', '{{title}} - {{description}}')
};

/**
 * WCAS.equalizeHeight(selector)
 *
 * Used to set heights of elements (by jQuery selector) to the
 * largest height of the group, simulating a table-based layout.
 * Each element's vertical padding is treated as part of its height.
 *
 * Usage:
 *     WCAS.equalizeHeight('#first-element, .other-elements');
 */
WCAS.equalizeHeight = function(selector) {
	var $elements = $(selector);
	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.eq(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.eq(i);
		if ($element.length != 0 && i != tallestElem) {
			newHeight = 
				maxHeight
				- parseInt($element.css('padding-top'))
				- parseInt($element.css('padding-bottom'));
			$element.height(newHeight);
		}
	}
};

/**
 * WCAS.resetColumnHeight()
 *
 * Resets the heights of the main content columns.
 * This function is primarily used to maintain equal-height columns
 * in IE6/IE7 after loading dynamic content on the page.
 */
WCAS.resetColumnHeight = function() {
	if (WCAS.equalizeCols) {
		$('div.column').height('auto');
	}
};

/**
 * 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) {
			WCAS.resetColumnHeight();
		}
		if ($('#inner-col1').length > 0) {
			WCAS.equalizeHeight('#inner-col1, #inner-col2');
		}
		WCAS.equalizeHeight('#col1, #col2, #col3');
		// Force the footer's location to be redrawn
		// (This fixes problems after loading dynamic content in IE7)
		$('#footer')
			.css('position', 'static')
			.css('position', 'relative');
	}
};

/**
 * WCAS.hidePrinterFriendlyView()
 * 
 * Removes printer-friendly style sheet and returns the page to standard-view.
 */
WCAS.hidePrinterFriendlyView = function() {
	// Rather than rely on IE6/7 to properly manipulate the DOM
	// and toggle style sheets, we refresh the page
	if (WCAS.equalizeCols) {
		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() {
			// Remove print.css
			$('#print-css').remove();
			// Hide printer-friendly navigation
			$('#pfv-nav').hide();
			// Show the page (with a fade-in on modern browsers)
			$('body').fadeIn(WCAS.fadeDuration);
			// Re-equalize columns on IE6/IE7
			WCAS.equalizeColumns();
			// Resume any slideshows
			$('ul.slideshow').cycle('resume');
		});
	}
	$(document).unbind('keydown.WCAS');
};

/**
 * WCAS.showPrinterFriendlyView()
 * 
 * Used to display a "printer-friendly" version of the current page.
 *
 * This works by applying our print-media style sheet as a screen-media one.
 */
WCAS.showPrinterFriendlyView = function() {
	$('body').fadeOut(WCAS.fadeDuration, function() {
		// Pause any slideshows
		$('ul.slideshow').cycle('pause');
		if (WCAS.equalizeCols) {
			// Apply print.css using the non-standard Microsoft method
			document.createStyleSheet('/css/print.css');
			// Reset equalized column heights in IE6/IE7
			WCAS.resetColumnHeight();
			// IE7 needs some extra help hiding just about everything
			$('#nav, #col1, #col3').remove();
		}
		else {
			// Apply print.css using jQuery
			$('#pfv-nav-css').before('<link id="print-css" rel="stylesheet" media="screen" href="/css/print.css" type="text/css" />');
		}
		// Show printer-friendly navigation
		$('#pfv-nav').show();
		// Show the page (with a fade-in on modern browsers)
		$('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) {
				$('#pfv-back').click();
				return false;
			}
		});
	});
};

/**
 * WCAS.initPrinterFriendlyView()
 * 
 * Adds DOM elements for the "printer-friendly" version of the page.
 *
 * These elements are visible on-screen only in the "printer-friendly" view,
 * but they will be printed regardless of whether or not this view is active.
 */
WCAS.initPrinterFriendlyView = function() {
	// Add CSS that hides "printer-friendly" navigation links when printing
	$('head').append('<style id="pfv-nav-css" type="text/css" media="print">#pfv-nav { display: none !important; }</style>');
	
	// Add "printer-friendly" navigation links to the top of the page
	var backLink = '<a id="pfv-back" href="#">&larr; Back to standard view</a>';
	var printThisPageLink = '<a id="pfv-print" href="#">Print this page</a>';
	$('body').prepend('<div id="pfv-nav">' + backLink + printThisPageLink + '</div>');
	$('#pfv-back').click(function() {
		WCAS.hidePrinterFriendlyView();
		return false;
	});
	$('#pfv-print').click(function() {
		window.print();
		return false;
	});
	
	// Add a printer-friendly header containing the Weinberg logo
	// and a small version of the department logo
	var smallLogo = '<img id="small-logo" src="/images/logo-small.gif" />';
	var WCASLogo = '<img id="wcas-logo" alt="Weinberg College of Arts &amp; Sciences" src="/images/layout/weinberg-logo-small.gif" />';
	$('#logo').after('<div id="pfv-header">' + smallLogo + WCASLogo + '</div>');
	
	// Create a simplified, printer-friendly footer after the main content
	$('<div id="pfv-footer"></div>')
		.append('<span id="current-url"><span>URL for this page:</span> '+window.location+'</span>')
		.append($('#copyright').clone())
		.append($('div.vcard').clone())
		.append('<p class="nu-wcas">Northwestern University // Judd A. and Marjorie Weinberg College of Arts and Sciences</p>')
		.appendTo('#col2');
};

/**
 * WCAS.highlightLinks(selector, highlightClass)
 *
 * Highlights links to the current page and section.
 *
 * NOTE: ALL LINKS MUST BE ROOT-RELATIVE!
 *
 * Adds highlightClass to the CSS classes of links that
 * link to the current page or section (the current section
 * is the top-level directory that contains this page).
 *
 * Arguments:
 *   - containerSelector: jQuery selector that specifies
 *       the elements in which links should be highlighted
 *   - highlightClass: The CSS class to add to
 *       current-page/section links
 *
 * Example:
 *   On /section/dir/subdir/page.html, links to 
 *     the following URLs will be highlighted:
 *   - /section
 *   - /section/
 *   - /section/index.html
 *   - /section/dir/subdir/page.html
 *
 *   On /section/dir/subdir/index.html, links to 
 *     the following URLs will be highlighted:
 *   - /section
 *   - /section/
 *   - /section/index.html
 *   - /section/dir/subdir
 *   - /section/dir/subdir/
 *   - /section/dir/subdir/index.html
 */
WCAS.highlightLinks = function(containerSelector, highlightClass) {
	// If the current path is a directory,
	//  window.location.pathname will always have a trailing slash
	var path = window.location.pathname,
		pathParts = path.split('/'),
		section = pathParts[1],
		linkSelector = 'a[href="' + path + '"]';
	if (section === '') {
		// Home page (path = "/")
		linkSelector += ', a[href="/index.html"]';
	}
	else if (section.indexOf('.html') !== -1) {
		// Root-directory pages (path = "/*.html")
		linkSelector += ', a[href="/"]';
	}
	else {
		// All other pages
		linkSelector += ', a[href="/' + section + '"], ' +
			'a[href="/' + section + '/"], ' +
			'a[href="/' + section + '/index.html"]';
		// If we are at an index page (e.g. /section/subdir/index.html),
		// we need to look for "/section/subdir", "/section/subdir/",
		// and "section/subdir/index.html"
		if (pathParts.length > 3) {
			var lastPathPart = pathParts[pathParts.length - 1];
			var parentDirPath = path.substr(0, path.lastIndexOf('/'));
			switch (lastPathPart) {
				case '':
					// Path ends with "/"
					linkSelector += ', a[href="' + parentDirPath + '"], ' +
						'a[href="' + parentDirPath + '/index.html"]';
					break;
				case 'index.html':
					// Path ends with "/index.html"
					linkSelector += ', a[href="' + parentDirPath + '"], ' +
						'a[href="' + parentDirPath + '/"]';
					break;
			}
		}
	}
	// Add the highlight class to the appropriate links
	$(containerSelector)
		.find(linkSelector)
			.addClass(highlightClass);
}

$(document).ready(function() {
	
	$('body').removeClass('no-js');
	
	/**
	 * RANDOM HEADER BACKGROUND-IMAGE
	 */

	if (WCAS.randomTheme) {
		var num = Math.floor(Math.random() * WCAS.numberOfThemes + 1);
		$('body').addClass('theme' + num);
	}
	
	/**
	 * 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('ie6-hover');
						},function(){
							$(this).removeClass('ie6-hover');
						});
				});
				$('ul.slideshow li:first-child').addClass('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.equalizeCols = true;
				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.highlight').each(function() {
				if ($(this).prev().hasClass('current')) {
					$(this).css('display', 'block');
				}
				$(this).width( $(this).parent().width() );
			});
		}
	}
	else {
		// No need to equalize column heights in non-IE browsers
		WCAS.equalizeCols = false;
	}
	
	/**
	 * MINOR DOM MANIPULATIONS

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

	// Highlight links to the current page and section
	WCAS.highlightLinks('#nav, #left-nav', 'current');

	// Make search-box clear itself when clicked
	$('#search-input')
		.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('| Last Updated: ')
		.appendTo('#copyright');
		
	// Load random feature into the features bar
	if ($('#features-bar').length > 0) {
		$.ajax({
			url: '/includes/homepage-slideshow.html',
			dataType: 'html',
			success: function(html) {
				var $features = $(html).find('li');
				var rand = Math.floor(Math.random() * $features.length);
				var $randomFeature = $features.eq(rand);
				var href = $randomFeature.find('a').attr('href');
				var text = $randomFeature.find('p').last().text();
				$('#features-bar')
					.show()
					.find('.feature')
						.find('span.text')
							.html('<a href="' + href + '">' + text + '</a>')
						.end()
						.fadeIn();
			}
		});
	}
	
	/**
	 * 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('hide-utility') === false) {
		// Add printer-friendly elements to the page,
		// including the printer-friendly navigation and a simplified page footer
		WCAS.initPrinterFriendlyView();
		

// Add "Email this page", "Printer-friendly version" and "Facebook like" links before the page content
$('#col2 h1').first().wrap('<div id="heading-1"></div>').before('<div class="fb-like"><a target="_blank" href="https://www.facebook.com/pages/Art-History-Department-Northwestern-University/200573583338510"><img src="/images/icons/facebook-21x21.gif" alt="Facebook page" width="21" height="21"></a></div><div id="utility-links"><span></span></div>'); 
		$('#utility-links span').append('<a class="email-this-page" href="mailto:?body='+window.location+'" title="Email this page"></a>');
		$('#utility-links span').append('<a class="print-this-page" href="#" title="Printer-friendly version"></a>');
		$('.print-this-page').click(function() {
			WCAS.showPrinterFriendlyView();
			return false;
		});
		
		
		// Show share-links
		// (These links' URLs are generated dynamically on-click, so we hide the links
		// by default for graceful degradation in the case that JS is disabled.)
		$('#share-links').show();
	}
	
	/**
	 * SLIDESHOW / LIGHTBOX SETUP
	 */

	var InitSlideshows = function() {
		// Add "view-larger" magnifying-glass overlay image to non-empty slideshow lightbox images
		var overlayImage = $('<img src="/images/icons/view-larger.gif" alt="" class="view-larger-overlay" />');
		$('a.lightbox:parent, a.slideshow-lightbox:parent').append(overlayImage);
	
		$('ul.slideshow')
			// Add lightbox functionality to any slideshows on the page
			// We use each() here to keep each lightbox group separate
			.each(function(index, element) {
				$(element).find('a.slideshow-lightbox').lightBox({
					// When any lightbox is open, it will pause all slideshows on the page
					onStart: function() { $('ul.slideshow').cycle('pause') },
					onClose: function() { $('ul.slideshow').cycle('resume') }
				});
			})
			// Initialize the slideshows and make them visible
			.cycle(WCAS.slideshowSettings)
			.css('visibility', 'visible');

		// Re-equalize columns on IE6/IE7
		WCAS.equalizeColumns(true);
	};
	
	// If no flickr-photos list is found, we set up slideshows immediately
	// Otherwise, we wait until the necessary images are loaded from Flickr
	var $flickrSlideshows = $('ul.flickr-slideshow');
	var numFlickrSlideshows = $flickrSlideshows.length;
	if (numFlickrSlideshows === 0) {
		InitSlideshows();
	}
	else {
		var numReadyFlickrSlideshows = 0;
		$flickrSlideshows.each(function(index, element) {
			var $slideshow = $(element);
			// We grab tag filters and thumbnail-size parameters from the ul's HTML5 data attributes
			var flickrFeedDefaults = {
				id: WCAS.defaultFlickrId,
				tags: '',
				tagmode: 'any',
				size: ''
			};
			var flickrFeedSettings = $.extend({}, flickrFeedDefaults, $slideshow.data());
			if (flickrFeedSettings.size !== '') {
				var size = '_' + flickrFeedSettings.size;
			}
			else {
				var size = '';
			}
			// Load Flickr photos using Flickr's Public Feed API
			// (http://www.flickr.com/services/feeds/docs/photos_public/)
			// We first remove the "size" setting, since the feed takes no size argument
			delete flickrFeedSettings.size;
			$slideshow.jflickrfeed({
				qstrings: flickrFeedSettings,
				itemTemplate: '<li><p class="image">'
					+ '<a href="{{image_b}}" class="slideshow-lightbox" title="' + WCAS.flickrLightboxCaptions + '">'
					+ '<img class="flickr-image" src="{{image' + size + '}}" alt="" /></a></p>'
	
			}, 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 = $slideshow.find('img.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) {
						numReadyFlickrSlideshows++;
						// If all of the Flickr slideshows are loaded, we initialize slideshows
						if (numReadyFlickrSlideshows === numFlickrSlideshows) {
							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.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">&rarr; <a id="all-photos-link" href="#">All '+linkText+' photos</a></p>');
			$('#all-photos-link').click(function() {
				$sidebarLightboxLinks.first().click();
				return false;
			});
		}
	}
	

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

