/**
 * 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 tbody tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	};
	
	listPrep();
	tablePrep();
};

var slideshow = function() {
	if ($('div.slideshow-right').size()) {
		//var speed = 1000;
		var speed = 0;
			
		$('div.slides-menu ul li a').click(function(event) {
			event.preventDefault();
		
			// Get li's index
			var index = $('div.slides-menu ul li').index($(this).parent());
		
			// Find li with same index in slides
			var $nextSlide = $('.slides li:eq('+ index +')');
		
			// Find visible slide
			var $visibleSlide = $('.slides li:visible');
		
			// Fade out visible and fade in the new slide
			$visibleSlide.fadeOut(speed);
			$nextSlide.fadeIn(speed);
		});
	
		$('div.slides-menu').scrollable({
			next: "a.next", 
			prev: "a.previous",
			size: 3
		});
	};
};

var newsAndEvents = function() {
	$.fn.makeActive = function() {
		return this.each(function() {
			var $menu_item = $(this);
			
			// Add active and <class-name>-active class
			$menu_item.addClass(function() {
				return 'active ' + $menu_item.data('class') + '-active';
			})
			// Remove all active events-active news-active classes
			.siblings().removeClass('active').removeClass(function() {
				return $(this).data('class') + '-active';
			});
			
			// Swap out divs
			$swap_div = ($menu_item.data('class') == 'events') ? $secondDiv : $firstDiv;
			$($swap_div).fadeOut(200, function() {
				$('body#home #content-sub .news-events div.' + $menu_item.data('class')).fadeIn(200);
			});
		});		
	};
	
	if ($('body#home #content-sub .news-events .menu').size()) {
		var $menu = $('body#home #content-sub .news-events .menu');
		var $firstMenuItem = $('li.events', $menu);
		$firstMenuItem.data('class', $firstMenuItem.attr('class'));
		var $secondMenuItem = $('li.news', $menu);
		$secondMenuItem.data('class', $secondMenuItem.attr('class'));
		var $firstDiv = $('body#home #content-sub .news-events div.events');
		var $secondDiv = $('body#home #content-sub .news-events div.news');
		
		// Hide the headers
		$('h2', $firstDiv).hide();
		$('h2', $secondDiv).hide();
		
		// Show the menu
		$menu.show();
		
		// Hide the second div
		$secondDiv.hide();
			
		// Setup active/inactive
		$firstMenuItem.makeActive();
		
		// Create listeners
		$('li a', $menu).click(function(event) {
			event.preventDefault();
			$(this).parent().makeActive();
		});
	};
};

function LaunchColorbox(url, caption){
$.colorbox({href:url,transition:"none", title:caption});
}

function navigation_hover() {
	var hide_all = function() { $('#nav-main > li').removeClass('hover'); };
	
	$('#nav-main > li > div.dropdown').parents('li').hover(function() {
		hide_all();

		$(this).addClass('hover');
		$(this).find('.dropdown').fadeIn(200);
	}, function() {
		if ($.browser.msie) {
			$(this).find('.dropdown').hide();
			hide_all();
		} else {
			$(this).find('.dropdown').fadeOut(200, function() {
				hide_all();
			});
		};
	});
}

function PopupLg(url) {
	window.open(url, '_blank', 'scrollbars,resizable,height=600,width=950');
	return false;
}

function PopupMd(url) {
	window.open(url, '_blank', 'scrollbars,resizable,height=450,width=650');
	return false;
}

function pwiGallery(email) {
	var settings = {
	  username: email,
	  albumsPerPage: 8,
	  albumThumbSize: 72,
		thumbCss:{'float':'left'},
	  onclickAlbumThumb: function (e) {
		$("#picassa-photos").html("");
		$("#picassa-photos").pwi({
			username: email,
			thumbSize:72,
			thumbCrop:1,
			showAlbumdate:false,
			showAlbumPhotoCount:false,
			showAlbumLocation:false,
			showPhotoDate:false,
			showAlbumDescription:true,
			showAlbumdate:false,
			showSlideshow:false,
			mode: 'album',
			thumbAlign:0,
			page:1,
			maxResults:20,
			thumbCss:{'float':'left'},
			popupExt: function(photos){photos.colorbox({slideshow:true}) },
			album: e.data.gphoto$name.$t  // The ident of the selected album
		});
	  }
	};
	$("#picassa-albums").pwi(settings);
}

$(document).ready(function() {
	$('input[placeholder]').placeholder();
	$('div.image-left, div.image-right').imageWidth();
	$('span.pullquote-left, span.pullquote-right').pullQuote();
	//$("#accordion").tabs("#accordion div.pane", {tabs: 'h3', effect: 'slide', initialIndex: null});
	$("#accordion.left").tabs("#accordion.left div.pane", {tabs: 'h3', effect: 'slide', initialIndex: null});
	$("#accordion.center").tabs("#accordion.center div.pane", {tabs: 'h3', effect: 'slide', initialIndex: null});
	$("#accordion.right").tabs("#accordion.right div.pane", {tabs: 'h3', effect: 'slide', initialIndex: null});
	//$("#popout div[title]").tooltip();
	
	// colorbox
	$("a[rel='contentImg']").colorbox();
	$("a[rel='slideshowImg']").colorbox({slideshow:true});
	
	$(".box-html").colorbox();
	$(".box-video").colorbox({iframe:true, innerWidth:650, innerHeight:400});
	$(".box-form").colorbox({iframe:true, innerWidth:600, innerHeight:500, overlayClose:false});
	$(".box-apply").colorbox({iframe:true, innerWidth:660, height:"90%"});
	$(".box-iframe-lg").colorbox({width:"85%", height:"85%", iframe:true});
	$(".box-iframe-md").colorbox({width:"70%", height:"75%", iframe:true});

	newsAndEvents();
	slideshow();
	markupPrep();
	
	navigation_hover();
	
	//home_flash();
	
	// faculty link disclaimer
	$('.facultylink').filter(function() {
		return this.hostname && this.hostname !== location.hostname;
	}).click(function () { 
		var x=window.confirm('This is a personal page created and maintained solely by individual authors, and not endorsed or actively monitored by Prescott College. Individual authors have been made aware of copyright law and other guidelines they are required to follow.  Prescott College accepts no responsibility for the content of this page.');
		var val = false;
		if (x)
			val = true;
		else
			val = false;
		return val;
	});
	// end disclaimer

	// anchor scroll begin
	$(".scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();

		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;

		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];

		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
	// end anchor scroll
	
});
