/*
	
	Tufts Global Javascript Functions
	ISITE Design
	2.17.10

*/
// settings
var TUFTS_SETTINGS = {
	slideshowspeed 	: 7000, // speed in milliseconds between image rotation
	datestore 		: "", // for submit event
	endset			: false,
	gallery			: 	{
							"mini" 		: { mw : 170, mh : 134 }, // sizes also restricted in CSS
							"default" 	: { mw : 612, mh : 360 },
							"thumb" 	: { mw : 80, mh : 80 },
							"captions"	: { show : "Show Captions", hide : "Hide Captions" },
							"actions"	: { play : "Play", pause : "Pause" }
						}
};

jQuery.noConflict();

//start the document ready events
jQuery(document).ready(function() {

	jQuery('html').addClass('js');

	// prevent header overlap with small browser font setting
	if (parseInt(jQuery("#nav").css("top")) < 79) { jQuery("#nav").css("top", "79px"); }

	// external link handling
	jQuery("a[rel=external]").click(function() { window.open(this.href); return false; });

	// setup search field
	jQuery("#utility input, #page-home .form-facultysearch input").inputSetter();
	
	// set up the news listing
	TUFTS.facultyInit();	

	// directory listing tabs
	// TUFTS.tabsInit(".directorylisting");

	// set width on story images
	TUFTS.buildCallouts();

	// set width on story images
	TUFTS.setCalloutWidth();

	// init slideshow
	TUFTS.slideshow();
		
	// init gallery
	TUFTS.gallery();
	// TUFTS.enableSlider(".slider");	
	
	// faq expand/collapse
	TUFTS.enableExpand("dl.collapsible");
	
	// sitemap toggling
	jQuery("a.sitemap-children").live("click", function() {
		var a = jQuery(this),
			off = a.is(".off");			
		a[off ? "addClass" : "removeClass"]("on")[off ? "removeClass" : "addClass"]("off").html(off ? "-&nbsp;" : "+&nbsp;");
		a.closest("li").find(">ul")[off ? "show" : "hide"]();
	});
	jQuery("a.sitemap-children").click();

	// jump menu implementation (left nav), not calendar filter
	jQuery(".block-jumpnav input").not(".block-calendarfilter input").click(function() {
		window.location = jQuery("select", jQuery(this).parent()).val();
		return false;
	});

	// submit/edit events date automation
	jQuery(".startdate input").bind(jQuery.browser.msie? 'propertychange': 'change', TUFTS.automateDate).focusin(function() { TUFTS_SETTINGS.datestore = jQuery(this).val(); });
	jQuery(".enddate input").focusin(function() { TUFTS_SETTINGS.endset = true });

	// get bgiframe fix for ie6 z-index on select element. initialized from form server controls OnClientShow
	// hover on li's
	if (!jQuery.support.style) {
		jQuery.getScript("/Sites/Common/Resources/js/jquery.bgiframe.min.js");
		jQuery(".alphalisting li").hover(
			function() { jQuery(this).toggleClass("over"); },
			function() { jQuery(this).toggleClass("over"); }
		);
	}

	if (jQuery.browser.msie) {
		var selects = jQuery(".block-jumpnav select").not(".page-home .block-jumpnav select");
		
		selects.each(function(){							  
			var $this = jQuery(this),
				csswidth = parseInt($this.css('width')),
				width = $this.innerWidth(),
				autowidth = $this.css('width','auto').width();
			
			// reset from previous 'auto' calculation
			$this.css('width',width);			
			
			width = $this.is(".block-calendarfilter select") ? "100%" : width > 170 ? width - 33 : width;
			
			// set for later usage in wrapper events
			$this.data("returnwidth",width);
			
			$this.css("minWidth",width)
				.bind("mouseover", function() 	{ jQuery(this).css("width", autowidth < csswidth ? width : "auto"); })
				.bind("change blur", function() { jQuery(this).css("width", width); });		
		
		});
		jQuery("#tertiary .block,#content").mouseenter(function() {			
			selects.each(function(){
				jQuery(this).css("width",jQuery(this).data().returnwidth);
			});				
		});
	}

	// faces landing page
	// pull the overflow and put in a float clearer
	if(jQuery("div.faces-listing a.faces-trigger").length) {
		jQuery('.wrapper-content,#wrapper').append('<span class="clear"></span>').css("overflow","visible");
	}
	jQuery("div.faces-listing a.faces-trigger,div.faces-list-fields").bind("mouseenter mouseleave focus blur",function(e){
		var content = jQuery(this).is(".faces-list-fields") ? jQuery(this) : jQuery(this).parents(".item").find(".faces-list-fields");			
		if(e.type == "mouseenter" || e.type == "focus") {
			content.parents(".item").css("zIndex","9000");
			jQuery("div.faces-list-fields").not(content).hide().parents(".item").css("zIndex","1");
			content.show();	
		}
		if(e.type == "blur" || (e.type == "mouseleave" && jQuery(this).is(".faces-list-fields"))) {
			jQuery("div.faces-list-fields").hide().parents(".item").css("zIndex","1");
		}		
	});

}); // document ready / end jquery functions

// make label into default value and clear
jQuery.fn.inputSetter = function(lower) {
	return this.each(function() {
		var $input = jQuery(this);
		var $label = jQuery("label[for='" + $input.attr("id") + "']");
		var labeltext = $input.val();
		
		if (labeltext == '') {
			labeltext = lower && lower == 1 ? $label.text().toLowerCase() : $label.text();
		}
		
		$label.hide();
		$input.val(labeltext);
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; } })
		  .blur(function() { if (!this.value.length) { this.value = labeltext; } });
	});
};

// TUFTS object
var TUFTS = {
	// set up the faculty listing
	facultyInit : function() {
		if (jQuery("#secondary ul.nav-toggle,.columns ul.nav-toggle").length == 0) return;
		jQuery("#secondary ul.nav-toggle ul,.columns ul.nav-toggle ul").hide();
		jQuery("ul.nav-toggle > li > a:first-child").prepend('<span class="showhide">Show</span>')
			.click(function(e){
				var $parentli = jQuery(this).parent("li");
				var $parentul = jQuery(this).parents("ul");
				jQuery("li", $parentul).not($parentli).find("ul").slideUp("fast").end().removeClass("opened");		
				$parentli.toggleClass("opened");
				jQuery("ul", $parentli).slideToggle("fast");
				e.preventDefault();
			}).parent("li").removeClass("opened");
		// make .opened be open on load
		// $("ul.nav-toggle li.opened a").eq(0).click().parent().toggleClass("opened");
	},
	
	// set up tabs
	tabsInit : function(selector) {

		if (jQuery(selector).length == 0) return;

		var $els =	jQuery(selector);
		var key = jQuery.browser.msie && (parseInt(jQuery.browser.version) < 7) ? "height" : "minHeight";		
		var h 		= (TUFTS.maxHeight($els)+20)+"px";

		$els.css(key,h).not(":first").hide();

		jQuery(".tabs a").click(function(e) {
			var tab = jQuery(this).attr("href").substring(1);
			$els.hide().filter("#"+tab).show();
			jQuery(".tabs a").removeClass("current");
			jQuery(this).addClass("current");
			e.preventDefault();
		}).eq(0).addClass("current");		

	},
	
	// init slideshow, either auto cycle or add prev/next buttons
	slideshow : function() {
		if (jQuery(".slideshow").length == 0) return;
		
		// wait for window to complete to be sure images are loaded for ie
		jQuery(window).load(function() {
			var imagecount = jQuery(".slideshow li img").length;
			var imageloads = 0;
			var autoheight = TUFTS.maxHeight(jQuery(".slideshow li"));

			jQuery(".slideshow li").css({ height: autoheight + "px" });
			var wrapheight = jQuery(".slideshow").height();
			jQuery(".slideshow").css({ height: wrapheight }); // prevent browser jump from DOM manipulation
			setInterval('TUFTS.autoSlideshow()',TUFTS_SETTINGS.slideshowspeed);	
		});
		
	},
	
	// start auto cycle
	autoSlideshow : function() {

		var $on = jQuery(".slideshow li:visible");
		var $toshow = $on.next().length != 0 ? $on.next() : jQuery(".slideshow li:first");
		
		TUFTS.imageFade($on,$toshow);
		
	},
	
	// start slideshow with navigation, build navigation	
  	insertSlideshowNav : function() {

  		var total = jQuery(".slideshow li").length;
  		jQuery(".slideshow ul").after('<div class="nav-slideshow"><a class="prev off" href="#">&laquo;</a> <span class="currentitem">1</span> of <span class="totalitems">' + total + '</span> <a class="next" href="#">&raquo;</a></div>');

  		jQuery(".slideshow .nav-slideshow a").click(function() {

  			if (jQuery(this).is(".off")) return false;

  			var $this = jQuery(this);
			var $parent = $this.parents(".slideshow");
			var action	= $this.attr("class").split(" ")[0];
			var $on		= $parent.find("li:visible");
			var $toshow	= action == "next" ? $on.next() : $on.prev();

			var i = jQuery.inArray($toshow.get(0), jQuery.makeArray($parent.find("li"))) + 1;
			
			TUFTS.imageFade($on,$toshow,function(){
				jQuery(".currentitem").text(i);
				$parent.find("a.prev,a.next").removeClass("off");
				if(i==$parent.find("li").length) $parent.find("a.next").addClass("off");
				if(i==1) $parent.find("a.prev").addClass("off");				
			});
						
			return false;
														
		});		
		
	},
	
	// fade between two images and execute callback
	imageFade : function(fo,fi,cb) {
	
		var callback = cb || function(){};
		
		fo.fadeOut("slow",function(){
			callback.apply();
			fi.fadeIn("slow");										 
		});
	
	},
	
	gallery : function() {
		
		// nothing to do
		if (jQuery(".gallery").length == 0) return;

		var currentscreen = 1,
			maxitems = 6,
			currentitem = 0,
			totalitems = jQuery(".gallery>li>div").length;

		// presets for cycle function actions. see cycle initialization		
		this.stopGallery = function() { jQuery('.gallery').cycle('pause').addClass('paused'); jQuery(".toggle-play").text(TUFTS_SETTINGS.gallery.actions.play).addClass("play-pause"); };
		this.setCurrent  = function(e) {
			var previousitem = currentitem;
			currentitem = jQuery(this).index() + 1;
			jQuery(this).closest(".gallery").next(".gallery-controls").find(".gallery-current").text(currentitem);
			
			if(jQuery(this).parents(".gallery-mini").length == 0 && totalitems > (maxitems+1)) { // don't do this for mini gallery or galleries that don't need  -- no slider
				if(currentitem != totalitems && currentitem != 1) {
					if(
							previousitem<currentitem
						&& 	(maxitems*currentscreen)%(currentitem-1) == 0
						&& 	(maxitems*currentscreen)%(currentitem) != 1
						&&	(currentscreen*maxitems < currentitem) 
					) {	jQuery(this).closest(".content").find(".next-slides").click(); }
					if(
							previousitem>currentitem
						&& 	(maxitems*currentscreen)%(currentitem/(currentscreen-1)) == 0
						&&	(currentscreen*maxitems > currentitem) 
					) { jQuery(this).closest(".content").find(".prev-slides").click(); }
				} else {
					if(previousitem == totalitems && currentitem == 1) {
						moveList(jQuery(this).closest(".callout").find(".prev-slides"),0);
					}
					if(previousitem == 1 && currentitem == totalitems) {
						moveList(jQuery(this).closest(".callout").find(".prev-slides"),1);
					}
				}
			}
		};
		
		var showVideo = function() {
			jQuery(this).closest('.video').removeClass('keyed');
			jQuery('.gallery').cycle('pause').addClass('paused');
			jQuery(".toggle-play").text(TUFTS_SETTINGS.gallery.actions.play).addClass("play-pause");
		};
		var hideVideo = function() {
			var it = jQuery('.gallery').find('.video');
			it.addClass('keyed');		
		};
		
		// transform links to real content
		jQuery('ul.gallery').addClass('paused').each(function() {
									  
			// for each gallery
			var gallery = jQuery(this),
				style = gallery.is(".gallery-mini") ? "mini" : "default",
				thumbs = jQuery('<ul class="gallery-thumbnails" />');
			
			// each inner content block
  			jQuery('>li>div', gallery).each(function() {
				
				// for each item
				var content = jQuery(this),
					type = content.is(".photo") ? "photo" : "video",
					thing = jQuery('a:first', content);
				
				// build slide content,
				// either a photo or video keyframe
				var show = jQuery('<img src="'+thing[0].href+'?mw='+TUFTS_SETTINGS.gallery[style].mw+'&mh='+TUFTS_SETTINGS.gallery[style].mh+'" alt= "" />');
				
				if(type == "video") {	
					var parent = content.closest(".video"),
						object = jQuery(TUFTS.setWmode(parent.find(".video-data").text())),
						playicon = jQuery('<span class="playicon">Play</span>').click(function(){ jQuery(this).closest("li").find("img").click(); });
					
					show.click(showVideo);
					parent.find(".video-data").remove();
					parent.append(playicon);
					content.addClass('keyed');
					
				} // end if video
				
				// build thumbnail
				if(style == "default") {
					var playthumb = type == "video" ? '<span class="playicon">Play</span>' : "";
					var thumb = '<a href="'+thing.attr('href')+'"><img src="'+thing.attr('href')+'?mw='+TUFTS_SETTINGS.gallery["thumb"].mw+'&mh='+TUFTS_SETTINGS.gallery["thumb"].mh+'" alt="" />'+playthumb+'</a>';
				}
				
				// insert slide	
				thing.replaceWith(show);
				content.append(object);

				// append thumb
				thumbs.append('<li>'+thumb+'</li>');
							  
				// configure special captions
				if(type == "video" && style == "default") {
					// make the caption same width as video
					var caption = jQuery(".caption", this),
						objwidth = jQuery("object", this).length ? jQuery("object", this).attr("width") : jQuery("embed", this).attr("width"),
						pad = (jQuery(this).width() - objwidth) / 2;
				
					caption.css({ width: (objwidth - parseInt(caption.css("paddingLeft")) - parseInt(caption.css("paddingRight"))) + "px", left: pad });				
				}
				
			}); // end >li>div loop
			
			// insert thumbnail nav for each gallery
			if(style == "default") {
				var fullgallery = gallery.nextAll(".gallery-nav").first().html(thumbs);
				gallery.nextAll(".gallery-controls").find("#prev,#next").click(function(){  jQuery(this).closest('.gallery-controls').prev(".gallery").find(".video img").click(); });
			}
			
			// make slideable
			initSlider(fullgallery);

		});
		
		// init cycle
 		jQuery('.gallery-mini').cycle({ 
			prev:   '.prev-mini', 
			next:   '.next-mini', 
			timeout:0,
			height:	'140px',
			before: this.setCurrent
		});
		jQuery('.gallery').not('.gallery-mini').cycle({ 
			prev:   '#prev', 
			next:   '#next', 
			timeout: 7000,
			height:	'360px',
			before: this.setCurrent,
			pager: '.gallery-thumbnails', 
			pagerAnchorBuilder: function(idx, slide) { 
				// return selector string for existing anchor 
				return '.gallery-thumbnails li:eq(' + idx + ') a'; 
			},
			pagerClick: this.stopGallery,
			prevNextClick: this.stopGallery
		});
		jQuery('.gallery').cycle('pause').find('.video img').click();
		
		// gallery controls
		jQuery('.toggle-caption').click(function() {
			// control only the nearest gallery
			var gallery = jQuery(this).closest('.gallery-controls').prev('.gallery');
			// show or hide captions and toggle text
			gallery.toggleClass('nocaptions');
			jQuery(this).text(gallery.is(".nocaptions") ? TUFTS_SETTINGS.gallery.captions.show : TUFTS_SETTINGS.gallery.captions.hide);			
			return false;
		});
		jQuery('.toggle-play').click(function() {		
			var paused = jQuery('.gallery').is('.paused');
			paused ? hideVideo() : jQuery('.gallery .video img').click(); // toggle video vs keyframe
			jQuery(this).text(paused ? TUFTS_SETTINGS.gallery.actions.pause : TUFTS_SETTINGS.gallery.actions.play)[paused ? "removeClass" : "addClass"]("play-pause");		
			jQuery('.gallery').cycle(paused ? 'resume' : 'pause',true)[paused ? "removeClass" : "addClass"]("paused");		
			return false;		
		});
		// set the thumbnail image widths all the same
		jQuery('.gallery-thumbnails').width(function() {
			var num = jQuery("li", this).length,
				li = jQuery("li", this),
				width = parseInt(li.width()) + parseInt(li.css('paddingLeft')) + parseInt(li.css('paddingRight'))  + parseInt(li.css('marginLeft')) + parseInt(li.css('marginRight'));			
				return (width*num)+"px";		
		});
		jQuery("html").addClass("active-gallery");
		jQuery("div.gallery-controls a.toggle-play").addClass("play-pause");
		
		
		//jQuery(window).load(function(){				
			var photo = parseInt(jQuery('.gallery .photo').not('.gallery-mini .photo').height());
			jQuery('.gallery .photo img').not('.gallery-mini .photo img').load(function(){			
																						//console.log("here");
				var pad = (photo-this.height) / 2;	
				jQuery(this).css("paddingTop",(pad-2)+'px');							
			});				
		//});		
		
		// slide-able
		function initSlider(el) {
			
			var obj = jQuery(el);			
			// do we need to slide at all?
			
			if(jQuery('li',obj).length > (maxitems+1)) { // +1 because without slide nav buttons able to have extra item
				// add prev and next links
				jQuery('ul',obj).wrap('<div class="gallery-clip"></div>');
				var btns = obj.addClass("slideable").append('<a class="prev-slides disabled" href="#">&lsaquo;</a> <a class="next-slides" href="#">&rsaquo;</a>');
				jQuery('.prev-slides,.next-slides').click(moveList);			
			}							

		}
			
		function moveList(obj,screen) {
			// action bound to click of prev/next buttons
			// items stored in $slider.data are set in the initialization code outside of this function			
			var $this = obj.length == 1 ? obj : jQuery(this),
				next = $this.is('.next-slides'), // bool to determine which way we are going
				$slider = $this.parents('.gallery-nav'),
				$ul = $slider.find('ul');
			
			// bail if nowhere to go or busy already
			if(!$slider.length || (!obj.length && $this.is('.disabled')) || $ul.queue().length > 0) { return false; }
			
			var width = 528,
				position = parseInt($ul.css('left')),
				gotopos; // placeholder for conditional result
				
			// set new position and current screen based on which direction moving
			if(next) {
				gotopos = (position - width)+'px';
				currentscreen++;
			} else {	
				gotopos = (position + width)+'px';
				currentscreen--;
			}
			if(screen==0) { currentscreen = 1; gotopos = 0 }
			if(screen==1) { currentscreen = Math.ceil(totalitems/maxitems); gotopos = -(width * (Math.ceil(totalitems/maxitems)-1)) }
		
			$ul.animate({left:gotopos},400,'swing');
						
			jQuery('.prev-slides')[currentscreen == 1 ? "addClass" : "removeClass"]("disabled");
			jQuery('.next-slides')[currentscreen == Math.ceil(totalitems/maxitems) ? "addClass" : "removeClass"]("disabled");	
		
			return false;		
		}
	},
	// ensure embeds have proper wmode set
	setWmode : function(text) {
		return text.replace('<embed','<param value="transparent" name="wmode"></param><embed wmode="transparent" ');

	},
	// get max height of set of $elements
	maxHeight : function($els) {
		var h = 0;
		$els.each(function(){
			h = h < parseInt(jQuery(this).height()) ? parseInt(jQuery(this).height()) : h;						   
		});		
		return h;		
	},
	
	// build callout borders
	buildCallouts : function() {
		
		var html = {
			open : '<div class="callout"><div class="content"><div class="t"></div>',
			close: '</div><div class="b"><div></div></div></div>'
		};

		//jQuery("#content img").each(function(){ /* console.log(jQuery(this).attr("src")); */ });

		jQuery("#content img").not(".news img").not("img.icon").not("img.noborder").not(".faces-list-fields img").each(function() {
			if (jQuery(this).parents(".callout").length == 0) {
				var $el = jQuery(this).parent("a") || jQuery(this);				
				var obj = $el.wrap('<div></div>').parent().html();				
				$el.parent().replaceWith(html.open + obj + html.close);							
			}		
		});
		
	},
	
	// set width of bottom corner for ie
	setCalloutWidth : function() {		
		// wait for window to complete to be sure images are loaded for ie
		jQuery(window).load(function() {
			// $("#page-newsandmedia .callout.left,#page-newsandmedia .callout.right, .wide .callout.left, .wide .callout.right")
			jQuery(".callout.left, .callout.right").not(".slideshow-news, #page-home .callout, .callout.portrait").each(function(i) {
				var imagewidth = parseInt(jQuery(this).find("img:first").width());
				jQuery(this).find(".b").css({ width: imagewidth + 20 + "px" });
				var fullwidth = jQuery(this).find(".content").css({ width: imagewidth + "px" }).outerWidth(true);
				jQuery(this).css({ width: fullwidth + "px" });												
			});
		});
	},
	
	// create open/close. receives dl.
	enableExpand : function(el) {
		
		if(!jQuery(el).length) { return; }
		// flags for animation helpers
		var moving = 0,
			allmoving = 0;
		
		jQuery(el).find("dd").hide();
		jQuery(el).find("dt").prepend('<span class="state">+</span> ').wrapInner('<a href="#"></a>').click(function(e){
			if(moving == 0) {
				if(jQuery(e.target).is("a")) { moving = 1; }
				var textinsert = jQuery("span.state",this).text() == "+" ? "-" : "+";
				jQuery(this).toggleClass("open").next("dd").slideToggle("fast",function(){
					moving = 0;
					allmoving = 0;
					updateStatus();
				}).end().find("span.state").text(textinsert);	
			}
			return false;
		});	
		
		var showtext = { show : "Show All", hide : "Hide All" };
		jQuery('<a class="revealer show" href="#">'+showtext.show+'</a>').insertBefore(el).click(function(){
			if(allmoving == 0) {
				allmoving = 1;
				var action = jQuery(this).is(".show");
				jQuery(this).next("dl.collapsible").find(action ? "dt:not(.open)" : "dt.open").click().end().end().toggleClass("show").toggleClass("action-hide").text(showtext[action ? "hide" : "show"]);	
			}
			return false;
		});
		
		var updateStatus = function(){
			
			var obj			= jQuery(el)
				count 		= obj.find('dt').length,
				countopen 	= obj.find('dt.open').length,
				visible		= countopen == count,
				hidden		= countopen == 0;
				
			if(visible || hidden) {
				var classaction = visible ? "removeClass" : "addClass",
					text		= visible ? showtext.hide : showtext.show;								
				obj.prev('a.revealer')[classaction]('show').text(text);				
			}
						
		};
		
	},
	
	// handle event date selecting
	automateDate : function() {
		if (!TUFTS_SETTINGS.endset && (TUFTS_SETTINGS.datestore == "" || TUFTS_SETTINGS.datestore == jQuery("li.enddate input").val())) {
			jQuery("li.enddate input").val(jQuery(this).val());
		}
	},
	
	// initialized by calendar control in page
	bgFix: function() { if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) { jQuery(".ajax__calendar_container").bgiframe(); } }

};
