﻿$(document).ready(function() {
	//ie6 menu stuff
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) { $('ul#primary_nav li').hoverClass("sf_hover"); }
	
	//IE wfuLogo / resolution fix :: Modeled after
	/*
	@media all and (max-width: 1080px){
		#wfuLogo { width:264px; margin-left:-20px; }
	}
	ADDED 9/10/10
	*/
	if(/MSIE ((5\.5)|6|7|8)/.test(navigator.userAgent) && navigator.platform == "Win32"){
		adjustLogo($(window).width());
		$(window).resize(function() { adjustLogo($(this).width()); });
		function adjustLogo(width){
			width = parseInt(width);
			if (width < 1080) {
				$("body").find("#wfuLogo").css("margin-left","-20px").width(264);
			}	else{
				$("body").find("#wfuLogo").css("margin-left","-63px").width(275);
			}
		}
	}


	//general site functionality
	$('body')
		.find("#search_input").val("Search the site").clearonfocus().end()
		.find("#news_search_input, #blog_search_input").val("Type and hit enter to search").clearonfocus().end()
		.find("#image_rotator").find("img:first").each(function(){
			$thisrotator=$(this).parents('#image_rotator');
			$time=7000;$t=setTimeout("jQuery.nextImage()",$time);
		}).end().hover(function(){clearTimeout($t)},function(){$t=setTimeout("jQuery.nextImage()",$time);});

	$('body')
		.find('#homepage_rotator').each(function(){
			$this = $(this);
			
			var count = $this.find('.rotator_image').length;
			//any of the following auto-advance and randomize code ADDED 9/10/10
			//now randomize
			var randomimage=Math.floor(Math.random()*count);
			//this is how we trick preloading to load proper image first, and then the rest load
			//-by flicking class 'hide' off and on with a 20 millisecond delay between toggles
			$(".rotator_wrapper, #nav_rotator_wrapper").hide().fadeIn(700);
				$this.find(".rotator_image").eq(randomimage).removeClass('hide').css('z-index','9999').delay(5).fadeIn(0,function(){
				$this.find(".rotator_image:not(:eq("+randomimage+"))").width("0").removeClass('hide').delay(5).fadeIn(0,function(){
					$(this).addClass('hide').width("100%")
					//just in case IE sometimes hides all these images by mistake
					$this.find(".rotator_image").eq(randomimage).fadeIn(200,function(){$(this).removeClass('hide')});
				})
			})
			
			$play=false;
			$time=7000;
			$t = setTimeout("jQuery.homeNext()",$time);
			$this.hover(function(){clearTimeout($t)},function(){$t=setTimeout("jQuery.homeNext()",$time);})
			$("#homepage_rotator_nav").each(function(){$thisnav = $(this);})
			.find('a').click(function(){
				if(!$play){
					var current = $this.find('.rotator_image:visible').index();
					$play=true;var gotoimage;
					if($(this).is(".prev")){if(current==1){gotoimage=count;}else{gotoimage=current-1;}}
					else{if(current==count){gotoimage=1;}else{gotoimage=current+1;}}
					$this.find('.rotator_image:visible').fadeOut(200,function(){
						$(this).addClass("hide");
						$this.find('.rotator_image:eq('+(gotoimage-1)+')').fadeIn(50,function(){$(this).removeClass("hide");$play=false;});
					});
				}
				return false;
			});
		});

	$('body')
		.find('#news_center_rotator, #academics_rotator').each(function(){
			$time=5000;$play=false;
			//assigning $thisnav for the function 'runNext' to know which nav to use
			$thisnav = $(this);$t = setTimeout("jQuery.runNext()",$time);
		})
		.hover(function(){clearTimeout($t)},function(){$t=setTimeout("jQuery.runNext()",$time);})
		.find("#news_center_nav").find('a').click(function(){
			if(!$play){
				$play=true;var count=$(this).attr("href").replace('#','')-1;
				$("#news_center_nav").find('li.selected').removeClass("selected");
				$(this).parent('li').addClass("selected");
				$thisnav
					.find(".rotator_image:visible").fadeOut(200,function(){
						$(this).addClass("hide");
						$thisnav.find('.rotator_image:eq('+count+')').fadeIn(200,function(){$(this).removeClass("hide");$play=false;});
				});
			}
			return false;
		}).end().end()
		.find("#academics_nav").find('a').click(function(){
			if(!$play){
				$play=true;var count=$(this).attr("href").replace('#','')-1;
				$("#academics_nav").find('li.selected').removeClass("selected");
				$(this).parent('li').addClass("selected");
				$thisnav
					.find(".rotator_image:visible").fadeOut(200,function(){
						$(this).addClass("hide");
						$thisnav.find('.rotator_image:eq('+count+')').fadeIn(200,function(){$(this).removeClass("hide");$play=false;});
				});
			}
			return false;
		});
		
	$('body')
		.find("#academic_directory .switcher, #administration_directory .switcher").each(function(){
			$("#administration_directory .column").addClass("hide");
			$("#administration_alpha_jump").addClass("hide");
		})
		.click(function(){
			$this = $(this);
			$this
				.parent().siblings().removeClass('selected').find('.column').addClass('hide').end().end()
				.addClass('selected').find('.column').removeClass('hide');
			if($this.parent().attr('id')=="academic_directory"){
				$('body').find('#academic_alpha_jump').each(function(){
					$('.alpha_jump').addClass('hide');
					$(this).removeClass('hide');
					var height=$this.parent().height();
					$("#global_right_sidebar").height(height);
					$(this).stickyfloat({ offsetY: 10, duration:0 });
					$(window).scroll();
				});
			}
			else{
				$('body').find('#administration_alpha_jump').each(function(){
					$('.alpha_jump').addClass('hide');
					$(this).removeClass('hide');
					var height=$this.parent().height();
					$("#global_right_sidebar").height(height);
					$(this).stickyfloat({ offsetY: 10, duration:0 });
					$(window).scroll();
				});

			}
			return false;
		}).each(function(){
			if(window.location.hash == "#administrative"){
				$("#administration_directory .switcher").click();
			}
		})
		.end()
		.find("#international_rotator").each(function(){
			//this trick helps with ie7 sometimes hiding because of the position. weirdest thing.
			var that = $(this);
			$time=5000;$play=false;
			that.css('position','relative').hide().fadeIn(200, function(){
				//assigning $thisnav for the function 'runNext' to know which nav to use
				$t = setTimeout("jQuery.runNext()",$time);$thisnav=that;
				$thisnav.removeClass("scroll");
				var number=$thisnav.find('.slide').length;
				$thisnav.find('.slide').not(":first").addClass("hide");
				var innernav="";
				for(var i=1;i<=number;i++){innernav+="<li><a href='#"+i+"'>"+i+"</a></li>";}
				$("<ul id='international_nav'>"+innernav+"</ul>").appendTo($thisnav);
				$("#international_nav li:first").addClass("selected");
			})
		})
		.hover(function(){clearTimeout($t)},function(){$t=setTimeout("jQuery.runNext()",$time);}).end()
		.find("#international_nav").find('a').live('click',function(){
			if(!$play){
				var href=$(this).attr("href");
				$play=true;var count=href.substring(href.lastIndexOf("#"),href.length).replace('#','')-1;
				$("#international_nav").find('li.selected').removeClass("selected");
				$(this).parent('li').addClass("selected");
				$thisnav
					.find(".slide:visible").fadeOut(200,function(){
						$(this).addClass("hide");
						$thisnav.find('.slide:eq('+count+')').fadeIn(200,function(){$(this).removeClass("hide");$play=false;});
					});
			}
			return false;
		});
		
		$("body").find("#ipe_map, #international_map").each(function(){
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initializeMap";
			document.body.appendChild(script);
		}).end()
		.find('#ipe_landing_video, #opcd_video').each(function(){
			var goflash = false; v = document.createElement("video"); // Are we dealing with html5 video browser?
			if( v.play ) { 
				if(!v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')){ 
					//if browser doesnt support mp4...
					$(this).find('video').remove(); goflash=true; //gogo flash. byebye video tag.
				} 
			}
			if ( goflash  || !v.play ) { 
				var script = document.createElement("script");
				script.type = "text/javascript";
				script.src = "http://www.wfu.edu/_assets/_js/swfobject_w_callback.js";
				document.body.appendChild(script);
			}
			else{
				var poster = $(this).attr("poster");
				//if it's ipe
				if($(this).is("#ipe_landing_video")){
					$(this).addClass('fresh').parent()
					.prepend("<img id='fake_poster' src='"+poster+"' style='position:absolute;top:0;right:0'>");
					$("video#ipe_landing_video").click(function(){ $("#fake_poster").remove(); })
				}
				//if it's opcd
				if($(this).is("#opcd_video")){
					$(this).addClass('fresh').parent()
					.prepend("<img id='fake_poster' src='"+poster+"' style='position:absolute;top:0;right:0'>");
					$("video#opcd_video").click(function(){ $("#fake_poster").remove(); })
				}
			}
		}).end();
		
	/* added 9/9/10 */
	$("body").find('#map_data').find('.rolloverme').hoverClass("sf_hover");
	
	/*generic window/tab/image switcher for an image with controls*/

	$.runNext = function() {
		/* assign $thisnav to whatever navigation you want to control the js rotator*/
		var count = $thisnav.find('li').length
		var a=$thisnav.find("li.selected a").attr("href").replace('#','');
		a++;if(a==(count+1)){a=1;}
		$thisnav.find("li a[href=#"+a+"]").click();
		$t=setTimeout("jQuery.runNext()",$time);
	}
	
	/*homepage controls - different than most pages -- ADDED 9/10/10 */
	$.homeNext = function(){
		if(!(badBrowser)){
			$thisnav.find('a.next').click();
			$t=setTimeout("jQuery.homeNext()",$time);
		}
	}
	
	/*generic image rotator without controls*/
	$.nextImage = function(){
		var count=$thisrotator.find('img').length;var current=$thisrotator.find('img:visible').index();
		var next=current+1;if(next==count){next=0}
		$thisrotator.find('img:visible').fadeOut(200,function(){
			$(this).addClass('hide');$thisrotator.find("img:eq("+next+")").fadeIn(200,function(){
				$(this).removeClass('hide')
			})
		});
		$t=setTimeout("jQuery.nextImage()",$time);
	}
	
	//initial setup for alpha_jump
	$('body').find('#academic_alpha_jump').each(function(){
		var height=$("#academic_directory").height();
		$("#global_right_sidebar").height(height);
		$(this).stickyfloat({ offsetY: 10, duration:0 });
		$(window).scroll();
	})
});

function insertVideo(){
	//gotta make sure that if this insertVideo thing gets called later, it only gets called for the right div
	$('body').find('#ipe_landing_video').each(function(){
		var poster = $(this).attr("poster");
		var params = { allowfullscreen: "true", allowscriptaccess: "always" };
		var flashvars = { file: "http://www.wfu.edu/_assets/_videos/pub_engage.430k.mp4", image: poster };
		swfobject.embedSWF("http://www.wfu.edu/_assets/_swf/player.swf", "ipe_landing_video", "464", "256", "9.0.0", "expressInstall.swf", flashvars, params);
	});
	$('body').find("#opcd_video").each(function(){
		var poster = $(this).attr("poster");
		var params = { allowfullscreen: "true", allowscriptaccess: "always" };
		var flashvars = { file: "http://www.wfu.edu/_assets/_videos/andychan.mp4", image: poster };
		swfobject.embedSWF("http://www.wfu.edu/_assets/_swf/mediaplayer.swf", "opcd_video", "940", "539", "9.0.0", "expressInstall.swf", flashvars, params);
	})
}

function initializeMap(){
	var myLatlng = new google.maps.LatLng(34.397, 20.644);
	var australia = new google.maps.LatLng(-24,135);

	var myOptions = {
		zoom: 2,
		scrollwheel: false,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.HYBRID
	}
	var map;
	$('body').find('#international_map').each(function(){
		map = new google.maps.Map(document.getElementById("international_map"), myOptions);
		//so, if we're on the international page, it's gonna get a little fancy. er... tricky.
		//the data points, associated with each link, will be embedded in the html, but hidden. 
		//that way it can be edited by wordpress, and the javascript can read it and do what it needs.
		//here we go:
		var coords = [];
		var titles = [];
		var markersArray = [];
		var markersClickedArray = [];
		
		$("#map_data").find('.data').each(function(){
			coords.push($(this).find('.coordinates').text());
			titles.push($(this).find('.title').text());
		});
		
		$("#show_all_points").click(function(){
			showOverlays();
			$('body').find("#map_selection span").fadeOut(100,function(){
				$(this).html("");
			});
			return false;
		})
		
		var arraysize = coords.length;
		for(var i=0; i<arraysize; i++){
			//time to extract the numbers from the string and place them
			var lat = coords[i].substring(0,coords[i].indexOf(","));
			var lon = coords[i].substring(coords[i].indexOf(",")+1,coords[i].length);
			var spot = new google.maps.LatLng(lat,lon);
			addMarker(spot, titles[i]);
		}
		//running this function gets all the title infowindows wired up (on initial load)
		showOverlays();
		
		//function to add markers
		function addMarker(location, title) {
			marker = new google.maps.Marker({
				position: location,
				map: map, 
				title: title
			});
			markersArray.push(marker);
		}
		
		//function to clear them
		function clearOverlays() {
			if (markersArray) {
				for (i in markersArray) {
					markersArray[i].setMap(null);
				}
			}
			if (markersClickedArray) {
				for (i in markersClickedArray) {
					markersClickedArray[i].setMap(null);
				}
			}
			deleteClickMarkerOverlays();
		}
		
		//function to show them all again
		function showOverlays() {
			clearOverlays();
			if (markersArray) {
				for (i in markersArray) {
					markersArray[i].setMap(map);
					attachMessage(markersArray[i], i);
				}
			}
			if (infowindow) {
				infowindow.close();
			}
		}
		
		// Deletes all markers in the array by removing references to them
		function deleteClickMarkerOverlays() {
			if (markersClickedArray) {
				for (i in markersClickedArray) {
					markersClickedArray[i].setMap(null);
				}
				markersClickedArray.length = 0;
			}
		}
		
		var infowindow = new google.maps.InfoWindow({
			maxWidth: 220
		});
		$("#map_data").find('ul li a').each(function(){
			//load up the variables
			var contentString;
			var coordinates = [], titles = [];
			$(this).click(function(){
				//clear all existing info windows:
				infowindow.close(map);
				
				var headertitle = $(this).text();
				//put some words and stuff in the selection box above the map
				$('body').find("#map_selection span").fadeOut(100,function(){
					$(this).html(headertitle);
					$(this).fadeIn();
				});
				
				//first clear all points (in both arrays)
				clearOverlays(); //also empties the markersClickedArray
				coordinates.length = 0, titles.length=0;
				
				$(this).parent().find('.data').each(function(){
					var datadivs = $(this);
					//extract the data what we want
					coordinates.push(datadivs.find('.coordinates').text());
					titles.push(datadivs.find('.title').text());
				});
				
				//then add the markers we want
				var coordinates_size = coordinates.length;
				for(var i=0; i<coordinates_size; i++){
					//time to extract the numbers from the string and place them as numbers
					var array_object = coordinates[i];
					var lat = array_object.substring(0,array_object.indexOf(","));
					var lon = array_object.substring(array_object.indexOf(",")+1,array_object.length);
					var spot = new google.maps.LatLng(lat,lon);
					marker = new google.maps.Marker({
						position: spot,
						map: map, 
						title: titles[i]
					});
					markersClickedArray.push(marker);
					attachMessage(marker, i);
				}
				
				return false;
			})
		})
		function attachMessage(marker, number) {
			google.maps.event.addListener(marker, 'click', function() {
			//this opens the infowindow
				infowindow.setContent('<h1 id="firstHeading" class="firstHeading" style="margin: 0px; padding-right:1px; padding-bottom:2px;">'+marker.title+'</h1>');
				infowindow.open(map,marker);
			});
		}
	});
}

/* Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net) 
-- thanks for letting me use this brandon. 
 */
jQuery.fn.clearonfocus=function(){return this.bind("focus",function(){if(!this.defaultValue){this.defaultValue=this.value}if(this.defaultValue&&this.defaultValue!=this.value){return }this.value=""}).bind("blur",function(){if(this.value.match(/^\s*$/)){this.value=this.defaultValue}})};

/*sucker fish for ie6 - no idea who's copyright this is*/
jQuery.fn.hoverClass = function(c) { return this.each(function(){ $(this).hover( function() { $(this).addClass(c); }, function() { $(this).removeClass(c); } );}); };

jQuery.fn.stickyfloat = function(options, lockBottom) {
	var $obj = this;
	var parentPaddingTop = parseInt($obj.parent().css('padding-top'));
	var startOffset = $obj.parent().offset().top;
	var opts = $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:true }, options);
	$obj.css({ position: 'absolute' });
	if(opts.lockBottom){
		var bottomPos = $obj.parent().height() - $obj.height() + parentPaddingTop;
		if( bottomPos < 0 )
			bottomPos = 0;
	}
	$(window).scroll(function () { 
		$obj.stop();
		var pastStartOffset	= $(document).scrollTop() > opts.startOffset;
		var objFartherThanTopPos	= $obj.offset().top > startOffset
		var objBiggerThanWindow 	= $obj.outerHeight() < $(window).height();
		if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){ 
			var newpos = ($(document).scrollTop() -startOffset + opts.offsetY );
			if ( newpos > bottomPos )
				newpos = bottomPos;
			if ( $(document).scrollTop() < opts.startOffset ) 
				newpos = parentPaddingTop;
			$obj.animate({ top: newpos }, opts.duration );
		}
	});
};
