/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
	/**
	 * Function takes a jquery object and a css property (called dimension) and determines how many pixels the item is
	 * @param {jQuery Object} $item The jQuery object we're looking at
	 * @param {String} dimension The CSS property name to look for
	 * @returns The width or height of the CSS property with 'px' removed
	 * @type Number
	 */
	var	determineDimension = function($item, dimension) {
		$item = $($item);
		if ($item.css(dimension)) {
			return parseInt($item.css(dimension).replace('px', ''), 10);
		} else {
			return 0;
		};
		return false;
	};
	
	var	resizeImage = function($image, $parent, $container) {
		// Determine the width of the image along with borders and padding
		var imageWidth = $image.width();
		var paddingLeft = determineDimension($image, 'padding-left');
		var paddingRight = determineDimension($image, 'padding-right');
		var borderLeft = determineDimension($image, 'border-left-width');
		var borderRight = determineDimension($image, 'border-right-width');

		// Calculate total edge (padding and border) width and the total width (edge and image)
		var edgeWidth = paddingLeft + paddingRight + borderLeft + borderRight;
		var totalWidth = imageWidth + edgeWidth;

		// Determine parent width
		var parentWidth = $parent.width();

		// If the image is greater then the threshold times the parent width resize the image and the container width
		// Otherwise set the image left's div to the size of the image plus the edge
		if ((threshold * parentWidth) <= totalWidth) {
			var revisedWidth = parentWidth * threshold;
			var revisedImageWidth = revisedWidth - edgeWidth;

			$image.width(revisedImageWidth);
			$container.width(parseInt(revisedWidth, 10));
		} else {
			$container.width(totalWidth);
		};
	};

	return this.each(function() {
		// Threshold is the maximum width an image plus its border and padding can be 
		// in relation to its parent container
		var threshold = (threshold) ? threshold : 2/3;

		// Find image within div
		var $image = $('img', $(this));
		var $parent = $(this).parent();
		var $container = $(this);

		$image.each(function(index) {
			resizeImage($image, $parent, $container);
			$(this).load(function() {			
				resizeImage($image, $parent, $container);
			});
		});
	});		
};

/**
 * Builds pull quote divs assuming you've wrappted your content with a span with the class: pullquote-left or pullquote-right
 */
$.fn.pullQuote = function() {
	return this.each(function() {
		var contents = $.trim($(this).html());
		var firstCharacterCode = contents.charCodeAt(0);
		if (firstCharacterCode < 65 || firstCharacterCode > 96) {
			contents = '&hellip; ' + contents;
		};
		
		var lastCharacter = contents.charAt(contents.length - 1);
		if ("?!.".search(lastCharacter) < 0) {
			contents = contents + ' &hellip;';
		};
		var $parent = $(this).parent();
		var $pullquote = $('<div>').attr('class', $(this).attr('class')).html(contents);
		$parent.before($pullquote);
	});		
};

/**
 * Makes the placeholder attribute on input items useful by emulating the behavior
 */ 
$.fn.placeholder = function() {
	if ((this[0] && 'placeholder' in document.createElement('input')) || this.size() == 0) return this;
	
	return this
		.val($(this).attr('placeholder')).addClass('placeholder')
		.focus(function() {
			if ($(this).val() === $(this).attr('placeholder')) {
		        $(this).val('').removeClass('placeholder');
			}
		})
		.blur(function() {
			if ($(this).val() === ''){
				$(this).val($(this).attr('placeholder')).addClass('placeholder');
			}
		});
};

/**
 * Adds the class 'last' to the last list items, and the last table item in a row. 
 * Also adds alt class to odd table rows.
 */
var markupPrep = function() {
	var listPrep = function() {
		$('> li:last', 'ul, ol').addClass('last');
	};
	
	var	tablePrep = function() {
		$('table tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	};
	
	listPrep();
	tablePrep();
};

var icon_hover = {
	/**
	 * Fires off the listeners
	 */
	init: function(){
		this.icon_listener();
		this.menu_listener();
	},
	
	/**
	 * Listens for hovers on the icons, fires off the icon and menu hover functions
	 */
	icon_listener: function(){
		$('li.campus ul.hotspots li').hover(function() {
			icon_hover._icon_hover($(this), 'on');
			var class_name = $(this).attr('class').split(' ')[0];
			icon_hover._menu_hover(class_name, 'on');
		}, function() {
			icon_hover._icon_hover($(this), 'off');
			var class_name = $(this).attr('class').split(' ')[0];
			icon_hover._menu_hover(class_name, 'off');
		});
		
		$('li.region ul.hotspots li').hover(function() {
			icon_hover._tooltip($(this), 'on');
		}, function() {
			icon_hover._tooltip($(this), 'off');
		});
	},
	
	/**
	 * Listens for hovers on the menu, fires off the icon hover function (normal hover is taken care of)
	 */
	menu_listener: function(){
		$('li.campus .content-sub li a').hover(function() {
			var class_name = $(this).parent().attr('class').split(' ')[0];
			icon_hover._icon_hover($('.hotspots li.' + class_name + ':first'), 'on');
		}, function() {
			var class_name = $(this).parent().attr('class').split(' ')[0];
			icon_hover._icon_hover($('.hotspots li.' + class_name + ':first'), 'off');
		});
	},
	
	/**
	 * Container function for the scale and tooltip function. 
	 * Also checks if you're hovering over the faculty houses (to scale the other faculty houses) 
	 * and checks if you're hovering over a no-border image (in which case the border image is swapped in)
	 * @private
	 * @param {jQuery Object} $icon The jQuery object of the image being hovered over
	 * @param {String} hover_state Either "on" or "off" for which part of the hover is calling it 
	 */
	_icon_hover: function($list_item, hover_state){
		// If its a no-border image, replace the image on hover with the border image
		if ($list_item.filter('.no-border').size()) {
			if (hover_state == "on") {
				$list_item.css('background-image', $list_item.css('background-image').replace('.png', '-hover.png'));
			} else if (hover_state == "off") {
				$list_item.css('background-image', $list_item.css('background-image').replace('-hover.png', '.png'));
			};
		};

		if (!$list_item.filter(".hide-tooltip").size()) { 
			icon_hover._tooltip($list_item, hover_state); 
		}
		
		if (hover_state == 'on') {
			$list_item.addClass('hover');
		} else if (hover_state == 'off') {
			$list_item.removeClass('hover');
		};	
		
		// In the case its a facutly house (one of four) hover the other four houses
		if ($list_item.filter('.faculty-houses').size()) {
			$list_item.siblings('.faculty-houses').each(function(index) {
				if (hover_state == "on") {
					$(this).addClass('hover');
				} else if (hover_state == "off") {
					$(this).removeClass('hover');
				};
			});
		};
	},
	
	/**
	 * Adds a hover class to the item in the menu (used when icons are hovered over)
	 * @private
	 * @param {String} class_name The class name of the icon being hovered over
	 * @param {String} hover_state Either "on" or "off" for which part of the hover is calling it 
	 */
	_menu_hover: function(class_name, hover_state){
		if (hover_state == "on") {
			$('li.campus .content-sub li.' + class_name + ' a').addClass('hover');
		} else if (hover_state == "off") {
			$('li.campus .content-sub li.' + class_name + ' a').removeClass('hover');
		};
	},
	
	/**
	 * Replaces the tooltip's content, positions it and displays/hides it
	 * @private
	 * @param {jQuery Object} $icon The jQuery object of the image being hovered over
	 * @param {String} hover_state Either "on" or "off" for which part of the hover is calling it
	 */
	_tooltip: function($list_item, hover_state) {
		if (hover_state == "on") {
			// Change text
			if ($list_item.parents('li.campus').size()) {
				new_content = $list_item.find('h3.title:first').text();
			} else if ($list_item.parents('li.region').size()) {
				new_content = "<span>" + $list_item.attr('city') + ",</span> " + $list_item.attr('state');
			};
			
			$('.tooltip-content').html(new_content);

			// Position tooltip
			var top_adjust;
			if ($list_item.parents('li.campus').size()) {
				var ie_adjust = ($.browser.msie) ? -4 : 0;
				top_adjust = parseInt($list_item.height(), 10) * (0.2 / 2) + ie_adjust;
			} else if ($list_item.parents('li.region').size()) {
				top_adjust = -4;
			};
			
			if ($list_item.filter('.van-voorhis').size()) {
				top_adjust = -8;
			} else if ($list_item.filter('.faculty-houses-3').size()) {
				top_adjust = -10;
			};
			var new_top = parseInt($list_item.css('top'), 10) + $list_item.height() + top_adjust;
			var new_left = parseInt($list_item.css('left'), 10) + (0.5 * $list_item.width()) - (0.5 * $('.tooltip').width());
			$('.tooltip').css({top: new_top, left: new_left});
			
			// Show the tooltip
			$('.tooltip').show();
		} else if (hover_state == "off") {
			$('.tooltip').hide();
		};
	}
};

function world_filters () {
	$('.world .content-sub li').click(function(event) {
		event.preventDefault();
		
		// Determine class name
		var class_name = $(this).attr('class').split(' ')[0];
		
		// Toggle active class for menu item
		$(this).toggleClass('active-' + class_name);
		
		// Toggle display of image
		$('.world .hotspots li.' + class_name + ' img').toggle();
	});
}


function _slideshow () {
	$('ul.media-slides:visible').innerFade({
		animate: false,
		speed: 'slow',
		indexContainer: 'ul.media-menu:visible'
	});
}

function _establish_links() {
	$('#fancybox-inner .content a[href^=#media:]').click(function(event) {
		event.preventDefault();
		
		var slide_number = parseInt($(this).attr('href').replace('#media:', ''), 10);
		
		if (slide_number < 1) {
			slide_number = 1;
		} else if (slide_number > $('ul.media-menu:visible li').size()) {
			slide_number = $('ul.media-menu:visible li').size();
		};
		
		$('.media-slides:visible').innerFadeTo(slide_number - 1);
	});
}

/**
 * Creates the lightboxes for both the icons and menu
 */
function lightbox () {	
	$('li.campus, li.region').find('ul.hotspots > li:not(.no-content)').each(function(index) {
		var class_name = $(this).attr('class').split(' ')[0];
		var content = $(this).find('div.lightbox').html();
		
		var settings = {
			content: content,
			titleShow: false,
			width: 730,
			height: 373,
			autoScale: false,
			autoDimensions: false,
			overlayOpacity: 0.7,
			overlayColor: '#000',
			scrolling: 'no',
			onComplete: function() {
				_slideshow();
				_establish_links();
				$('.content-inner').jScrollPane({showArrows:true, scrollbarWidth: 11});
			}
		};
		
		$(this).fancybox(settings);
		
		if ($(this).parents('li.campus').size()) {
			$('li.campus .content-sub li.' + class_name + ' a').fancybox(settings);
		};
	});
}

function display_campus () {
	$('li.campus').fadeIn(1000, function() {
		$(this).find('.content-sub').animate({bottom: 15}, function() {
			check_hash();	
		});
	});
}

var change_map = {
	init: function(){
		change_map.click_handler();
	},
	
	hide_content_sub: function($active, callback){
		
		var $content_sub = $active.find(' .content-sub');
		
		if ($content_sub.size()) {
			$content_sub.animate({bottom: -120}, 500, function() {
				callback.call();
			});
		} else {
			callback.call();
		};
	},
	
	show_content_sub: function($next, class_name){
		var $content_sub = $next.find('.content-sub');
		if (class_name == 'campus') {
			bottom = 15;
		} else if (class_name == 'world') {
			bottom = 19;
		} else {
			bottom = -120;
		};
		$content_sub.animate({bottom: bottom}, 500);
	},
		
	find_class: function($menu_item){
		return $menu_item.attr('class').split(' ')[0];
	},
	
	click_handler: function() {
		$('#nav-map li').click(function(event) {
			event.preventDefault();
			
			// Kill the animation if anything is still animating
			if ($('*:animated').size()) { return; };
			
			var $active_menu = $('#nav-map li.active');
			var $next_menu = $(this);
			var active_class = change_map.find_class($active_menu);
			var next_class = change_map.find_class($next_menu);
			var $next = $('#map li.' + next_class);
			var $active = $('#map li.' + active_class);
			
			
			// Put large image below small image and position it
			// Hide Content Sub
			// Hide Hotspots
			// Hide Small Image
			// Expand/Collapse large image
			// Show New Small Image
			// Show New Hotspots
			// Show Content Sub

			execute = true;
			if (active_class == 'campus' && next_class == 'region') {
				large_image = 'images/map-region-large.jpg';
				
				from_top = -590;
				from_left = -1200;
				from_height = 1693;
				from_width = 2500;
				
				to_top = 0;
				to_left = 0;
				to_height = 520;
				to_width = 768;
			} else if (active_class == 'campus' && next_class == 'world') {
				large_image = 'images/map-world-large.jpg';
				
				from_top = -3776;
				from_left = -3928;
				from_height = 11851;
				from_width = 17500;
				
				to_top = 0;
				to_left = 0;
				to_height = 520;
				to_width = 768;
			} else if (active_class == 'region' && next_class == 'world') {
				large_image = 'images/map-world-large.jpg';
				
				from_top = -3776;
				from_left = -3928;
				from_height = 11851;
				from_width = 17500;
				
				to_top = 0;
				to_left = 0;
				to_height = 520;
				to_width = 768;
			} else if (active_class == 'region' && next_class == 'campus') {
				large_image = 'images/map-region-large.jpg';
				
				from_top = 0;
				from_left = 0;
				from_height = 520;
				from_width = 768;
				
				to_top = -590;
				to_left = -1200;
				to_height = 1693;
				to_width = 2500;
			} else if (active_class == 'world' && next_class == 'region') {
				large_image = 'images/map-world-large.jpg';
				
				from_top = 0;
				from_left = 0;
				from_height = 520;
				from_width = 768;
				
				to_top = -3776;
				to_left = -3929;
				to_height = 11851;
				to_width = 17500;
			} else if (active_class == 'world' && next_class == 'campus') {
				large_image = 'images/map-world-large.jpg';
				
				from_top = 0;
				from_left = 0;
				from_height = 520;
				from_width = 768;
				
				to_top = -3776;
				to_left = -3929;
				to_height = 11851;
				to_width = 17500;
			} else if (active_class == next_class) {
				execute = false;
			};
			
			// console.log("Active Class: " + active_class + " | Next Class: " + next_class);
			// console.log("Large Image: " + large_image);
			
			if (execute == true) {
				change_map.hide_content_sub($active, function() {
					var $animated_image = $('img.animation');
					$animated_image.hide().attr('src', large_image).css({top: from_top, left: from_left, height: from_height, width: from_width});
					
					// Fade speed before zoom animation
					var out_speed = (active_class == "campus" || active_class == "region") ? 'normal' : 0;
					// Fade speed after zoom animation
					var in_speed = (next_class == 'campus' || (next_class == "region" && active_class == "world")) ? 'normal' : 0;
					
					$active.fadeOut(out_speed).find('.hotspots').hide();
					$animated_image.fadeIn(out_speed).animate(
						{top: to_top, left: to_left, height: to_height, width: to_width}, 
						'slow',
						'easeInOutExpo',
						function() {
							$animated_image.fadeOut(in_speed);
							$next.fadeIn(in_speed, function() {
								change_map.show_content_sub($next, next_class);
							}).find('.hotspots').show();
						}
					);
				});

				$active_menu.removeClass('active').removeClass('active-' + active_class);
				$next_menu.addClass('active').addClass('active-' + next_class);
				$('#nav-map li').removeClass('hover');
			};
		});
	}
};

function fix_hotspot_pngs () {
	if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
		$('ul.hotspots > li').each(function(index) {
			var background = $(this).css('background-image').replace('url\(', '').replace('\)', '').replace(/http:\/\/.*?\//, '');
			var styles = {
				'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + background + ", sizingMethod='scale')",
				'background-image': 'none'
			};
			$(this).css(styles);
		});
	};
}

function fix_embeds () {
	// Clean up video embeds
	$('.lightbox').find('object').attr({'width': 320, 'height': 240}).find('embed').attr({'width': 320, 'height': 240});
}

function check_hash () {
	var hash = window.location.hash;
	
	if (hash != '') {
		hash = hash.replace('#', '');
		$('#map li.campus ul.hotspots li.' + hash).click();
	};
}


$(document).ready(function() {
	fix_embeds();
	fix_hotspot_pngs();

	$('input[placeholder]').placeholder();

	change_map.init();
	icon_hover.init();
	markupPrep();
	lightbox();
	world_filters();
	
	display_campus();
});