$(document).ready(function(){

	//copyrightYear();
	editMode(); // execute this before any dependent functions
	wrapZonesParts();
	//tabStrip();
	//wpTabs();
	removeToolTips();
	inputInstructions();
	//mastHeadSearch();
	hideIfEmpty();
	pageFields();
	expandCollapse();
	expandCollapseWebPartsInZone();
	//flickrFeed();
	
	/* pull into functions.js */
	
	//primaryNav();
	//megaMenus();
	tabbedZonesNav();

});

/* ##### SHAREPOINT SCRIPT OVERRIDES ##### */

// Override of FixRibbonAndWorkspaceDimensions() from out-of-the-box SharePoint init.js.
// Solution for overriding SharePoint's ribbon positioning and page scrolling, which is not standards-based.
// Extension of solution documented at http://kyleschaeffer.com/sharepoint/sharepoint-2010-scrolling/
function FixRibbonAndWorkspaceDimensions() {
	alert("FixRibbonAndWorkspaceDimensions is being called");
	ULSxSy:;
	g_frl=true;
	var elmRibbon=GetCachedElement("s4-ribbonrow");
	var elmWorkspace=GetCachedElement("s4-workspace");
	var elmWorkspaceSpacer=GetCachedElement("s4-workspace-spacer");
	var elmBodyTable=GetCachedElement("s4-bodyContainer");
	if(!elmRibbon || !elmWorkspace || !elmWorkspaceSpacer || !elmBodyTable) {
		return;
	}
	if(!g_setWidthInited) {
		var setWidth=true;
		if(elmWorkspace.className.indexOf("s4-nosetwidth") > -1) {
			setWidth=false;
		}
		g_setWidth=setWidth;
		g_setWidthInited=true;
	}
	else {
		var setWidth=g_setWidth;
	}
	var baseRibbonHeight=RibbonIsMinimized() ? 66 : 157;
	var ribbonHeight=baseRibbonHeight+g_wpadderHeight;
	if (GetCurrentEltStyle(elmRibbon, "visibility")=="hidden") {
		ribbonHeight=0;
	}
	if(elmRibbon.children.length > 0 && document.getElementsByTagName("html")[0].className.indexOf('ms-dialog-nr') == -1) {
		elmWorkspaceSpacer.style.paddingTop = ribbonHeight + 'px';
	}
}

/* ##### end SHAREPOINT SCRIPT OVERRIDES ##### */


/* ##### BASE FUNCTIONS ##### */

// Get the current date and write year value to the ID in the master page
function copyrightYear() {
	var y = new Date().getYear();
	if(y<1000){
		y=y+1900;
	}
	$("#copyrightYear").text(y);
}


// Looks for the "editMode" flag to determine if the page is in edit mode and adds a hook to the body.
// The CSS and JS can use this hook to for execptions to styling and functionality while the page is in edit mode.
// The following "editMode" flag should be placed inside an EditModePanel on each page layout used by the site: 
// <span id="editMode">true</span>
function editMode() {
	if($("#editMode").text()=="true"){
		$("body").addClass("editMode");
	}
}

// Adds a class to web part zones, which in SP2010 do not have a CSS hook.
// Also adds a class to the web part HTML based on the Chrome Type selected in the web part properties.
// This class can be used to style web parts differently by changing the Chrome Type.
function wrapZonesParts() {
	$("table.s4-wpTopTable").parent().closest("table").addClass("wpz");
	
	// For web parts with the Title and Border chrome, add the class "wpTitleBorder" to the parent web part table (table.s4-wpTopTable).
	$(".ms-WPBorder").parents("table.s4-wpTopTable").addClass("wpTitleBorder");
	
	// For web parts with the Border Only chrome, add the class "wpBorderOnly" to the parent web part table (table.s4-wpTopTable).
	$(".ms-WPBorderBorderOnly").parents("table.s4-wpTopTable").addClass("wpBorderOnly");
}

// General tab strip control
function tabStrip() {
	// Handle the click event for the tabstrip so that the proper tab is shown active and the proper tab body displays.
	$('ul.tabStrip li a').click(function(){
		if(!$(this).parent('li').hasClass('active')){
			var i=$(this).parent('li').index();
			$(this).closest('.tabStrip').find('li.active').removeClass('active');
			$(this).closest('.tabStrip').nextAll('.tabBody.active').removeClass('active');
			$(this).parent('li').addClass('active');
			$(this).closest('.tabStrip').nextAll('.tabBody').eq(i).addClass('active');
		}
		// Override the default click behavior of the link.
		return false;
	});
	
	// Set the default
	$('ul.tabStrip li:first-child a').click();
}

// Turns a web part zone into a tab control.
function wpTabs() {
	var t='';
	// For each web part zone...
	$('.wpz').find('h3.ms-WPTitle').filter(function(){
		// Find the web parts with titles that begin with [ and give them the wpTab class
		t=$(this).text();
		return t.substring(0,1)=='[';
	}).closest('table.s4-wpTopTable').addClass('wpTab');
	
	// For each wpTab web part, if this web part does not have the parent div class "wpz wpzTabbed" wrapping its web part zone, make it so.
	$('.wpTab').each(function(){
		if($(this).parents('.wpzTabbed').length<1){
			$(this).closest('.wpz').wrap('<div class="wpz wpzTabbed"></div>');
		}
	});
	
	// Check to see if page is in edit mode
	if(!$('body').hasClass('editMode')){
		// Remove the parent containers around the web parts
		$('.wpzTabbed').find('table.s4-wpTopTable').unwrap().unwrap().unwrap().unwrap();
		
		// Insert a tab strip list at the top of each tabbed web part zone, and for each tabbed web part zone...
		$('.wpzTabbed').prepend('<ul class="tabStrip"></ul>').each(function(zoneIndex){
			// Find each tab web part in this zone...
			$(this).find('.wpTab').each(function(tabIndex){
				// Get the trimmed web part title
				t=trimWPTabLbl($(this).find('h3.ms-WPTitle').text());
				// Then add a tab to the tab strip list and set the text of the tab to be the trimmed web part title.
				$(this).closest('.wpzTabbed').find('ul.tabStrip').append('<li><a href="#tabBodyZone'+zoneIndex+'Tab'+tabIndex+'">'+t+'</a></li>');
				// Then wrap this tab web part and all of the web parts belonging to this tab in a tab body with a unique ID.
				$(this).nextUntil('.wpTab').andSelf().wrapAll('<div id="tabBodyZone'+zoneIndex+'Tab'+tabIndex+'" class="tabBody"></div>');
			});
			// Set the first tab to be active by default.
			$(this).find('ul.tabStrip li:first').addClass('active');
			$(this).find('.tabBody:first').addClass('active');
		});
	
		// Remove the web part vertical spacer for each tab web part because it is extraneous.
		$('.wpTab').next('.ms-PartSpacingVertical').remove();
		
		// Remove the tab web parts that marked the start of a new tab.
		$('.wpTab').remove();
		
		// Handle the click event for the tab so that the proper tab is shown active and the proper tab body displays.
		$('.wpzTabbed ul.tabStrip li a').click(function(){
			if(!$(this).parent('li').hasClass('active')){
				var i=$(this).parent('li').index();
				$(this).closest('.wpzTabbed').find('li.active, .tabBody.active').removeClass('active');
				$(this).parent('li').addClass('active');
				$(this).closest('.wpzTabbed').find('.tabBody:eq('+i+')').addClass('active');
			}
			// Override the default click behavior of the link.
			return false;
		});
	}
		
	// Return the text within the brackets of the supplied string.
	function trimWPTabLbl(t) {
		var lbl=t.split('[');
		lbl=lbl[1].split(']');
		lbl=lbl[0];
		return lbl;
	}
}

// Remove the title attributes that SharePoint applies to web part header table cells.
// The title attribute values SharePoint puts in the title tags is description text about the web part, which we do not want to display to end users.
function removeToolTips() {
	$(".ms-WPHeaderTd").removeAttr("title");
}

// Handles the display of default text in an input field
function inputInstructions() {
	var val;
	var lbl;
	$(".inputInstructions").each(function(){
		val=$(this).attr("value");
		lbl=$(this).prev("label").text();
		if(val==""||val==lbl){
			$(this).attr("value",lbl).focus(function(){
				if(val==""||val==lbl){
					$(this).attr("value","");
				}
			}).blur(function(){
				val=$(this).attr("value");
				if(val==""){
					$(this).attr("value",lbl);
				}
			});
		}
	});
}

// Sets the text to display in the search box by default.  Also injects a label with that text in front of the input for accessibility.  Adds the "inputInstructions" class to handle the default text for the input.
function mastHeadSearch() {
	$("#mastHeadSearch input.ms-sbplain").removeAttr("title").addClass("inputInstructions").before('<label>Search</label>');
}

// Apply the "hideIfEmpty" class to elements that should be hidden if no web part (or in edit mode, web part zone) is placed within it.
function hideIfEmpty() {
	$(".hideIfEmpty").each(function(){
		if($("body").hasClass("editMode") || ($(this).find("table.s4-wpTopTable").length>0 && $(this).find(".ms-WPBody").text()!="")){
			$(this).addClass("show"); // Add the class that turns the display of the element to "block".
		}
	});
}

// This function hides page fields (label and value) when the field value is empty.
function pageFields() {
	$(".pageFieldValue").each(function(){
		if($.trim($(this).text()).length<1){
			$(this).parent(".pageField").css("display","none");
		}
	});
}

// Toggles the display list items.
function expandCollapse() {
	$(".accordionList dl dt").click(function() {
		var head = $(this);
		$(head).next("dd").toggle();
		$(head).toggleClass("expanded");
		return false;
	});
	$(".accordionList>ul>li>a").click(function() {
		var head = $(this);
		$(head).next(".expandedBody").toggle();
		$(head).toggleClass("expanded");
		return false;
	});
}

// Makes the web part title a clickable region that toggles the display of the web part body.
function expandCollapseWebPartsInZone() {
	$(".expandCollapseWebPartsInZone td.ms-WPHeaderTd").addClass("expandCollapseHead");
	$(".expandCollapseHead").parent().parent().parent().parent().parent().parent().parent().addClass("expandCollapse");
	$("table.expandCollapse .ms-WPBody").parent().parent().addClass("expandCollapseBody");
	$(".expandCollapseWebPartsInZone .ms-WPTitle a").removeAttr("href");
	
	$(".expandCollapseWebPartsInZone .expandCollapseHead").click(function() {
		var headParentRow = $(this).parent().parent().parent().parent().parent();
		if($(headParentRow).next("tr.expandCollapseBody").hasClass("expanded")) {
			$(this).removeClass("expanded");
			$(headParentRow).next("tr.expandCollapseBody").removeClass("expanded");
		}
		else {
			$(this).addClass("expanded");
			$(headParentRow).next("tr.expandCollapseBody").addClass("expanded");
		}
		return false;
	});
}

// Sets the cropped height and width of the images returned in the Flickr feed
function flickrFeed() {
	// For each Flickr Feed web part
	$(".IWFlickrFeed").each(function(){
		// If the feed is returning at least one image
		if($(this).find("a.IWFlickrFeedItem").length<1){
			// Get the width of the image that was set in the Flickr Feed web part properties
			var w = $("a.IWFlickrFeedItem:first-child img").attr("width");
			// The maximum width allowed is 75px, as the image size returned by the "square" RSS feed from Flickr is 75px x 75px
			if(w>75){
				w=75;
			}
			// Crop the height and with of the anchor tag that contains the image to be the width set in the Flickr Feed web part properties.
			// The image should be absolutely posititioned within the anchor tag in order to allow for the cropping.
			$(this).find("a.IWFlickrFeedItem").css("height",w).css("width",w);
		}
	});
}


/* pull into functions.js */
function primaryNav() {
	$('#primaryNav span.menu-item-text').each(function(){
		var t=$(this).text();
		t=t.split(' ');
		$(this).html('<span class="top">'+t.shift()+'</span>'+t.join(' '));
	});
}
function megaMenus() {
	// Instantiate variables local to megaMenus() to be used by child functions
	var i,w,p,menu,t;
	// Get the left offset of the top nav container relative to the positioned parent (#logoPrimaryNavContainer)
	var listp = ($('.menu-horizontal').position()).left;
	// Get the left offset of the first top nav item relative to positioned parent (#logoPrimaryNavContainer)
	var pfirst = ($('.menu-horizontal>ul>li>ul.static>li:first-child').position()).left;
	// Top nav item hover event handler
	$('.menu-horizontal>ul>li>ul.static>li a').hover(showMega,delayHide);
	// Show the mega menu corresponding to the hovered top nav item
	function showMega(){
		// Clear the timeout to prevent excess hideMega() call, which would hide the newly-displayed mega menu.
		clearTimeout(t);
		// Hide the currently-displayed mega menu
		hideMega();
		// Get the hovered top nav item's width
		w=$(this).width();
		// Get the hovered top nav item's left offset
		p=($(this).parent().position()).left;
		// Add the class 'active' to the hovered top nav item
		$(this).addClass('active');
		// Get the index of the hovered top nav item
		i=$(this).parent('li').index();
		// Set the menu variable to the mega menu corresponding to the hovered top nav item
		menu=$('.megaMenu:eq('+i+')');
		// Set the position of the mega menu's upward-pointing arrow to be centered on the hovered top nav item.
		// Sum the top nav parent's left offset and the difference of the hovered top nav item's left offset and the first top nav item's left offset, 
		// then add that difference to half of the hovered top nav item's width.
		$('#megaArrow').css('left',((listp+p-pfirst)+(w/2))).addClass('show');
		// Show the mega menu corresponding to the hovered top nav item
		$(menu).addClass('show');
		// If CSS3 box-shadow is not supported by this browser...
		if($('html').hasClass('no-boxshadow') && $('.megaMenu.show').length>0){
			// Wrap the mega menu in divs to achieve the drop shadow through transparent PNGs
			$('#megaArrow').after('<div id="megaMenuShadow"><div id="megaMenuShadowTop"></div><div id="megaMenuShadowBtm"></div></div>');
			// Set the height of the shadow div to match the height of this mega menu
			$('#megaMenuShadowBtm').height($('.megaMenu.show').outerHeight());
		}
	}
	// Hide the currently-displayed mega menu
	function hideMega(){
		$('#megaMenuShadow').remove();
		$(menu).removeClass('show');
		$('#megaArrow').removeClass('show');
		$('.menu-horizontal>ul>li>ul.static>li:eq('+i+') a').removeClass('active');
	}
	// Delay the call of hideMega() to allow time for user to hover over mega menu in the course of mousing out of the top nav item
	function delayHide(){
		t=setTimeout(hideMega,300);
	}
	// Mega menu hover event handler
	$('.megaMenu').hover(function(){
		// Clear the timeout to prevent hideMega() from closing this mega menu.
		clearTimeout(t);
	},function(){
		// Hide the mega menu after a delay
		delayHide();
	});
}
function tabbedZonesNav() {
	if($("body").hasClass("editMode")){
		$("li.tabbedZonesNavItem>a").click(function(){
			return false;
		});
	}
	else{
$("li.tabbedZonesNavItem.active").append('<div class="arrowMarker"></div>');	
		$("li.tabbedZonesNavItem>a").click(function(){
			var ni = $(this).parent("li");
			
			if($(ni).hasClass("active")){
			}
			else{
				//$(".tabbedZones").addClass("overlay");
				$("li.tabbedZonesNavItem").removeClass("inactive");
				if($("li.tabbedZonesNavItem.active").length>0){
					$("li.tabbedZonesNavItem.active").find(".tabbedZonesNavFlyoutWrapper").hide().find(".tabbedZonesNavFlyout").hide();
					$("li.tabbedZonesNavItem.active").removeClass("active");
					$(ni).find(".tabbedZonesNavFlyoutWrapper").css("height","320px").css("top","-317px").show().find(".tabbedZonesNavFlyout").show();
				}
				else{
					$(ni).find(".tabbedZonesNavFlyoutWrapper").animate({height: '320px', top: '-317px'}, 200).find(".tabbedZonesNavFlyout").fadeIn(500);
				}
				$(ni).addClass("active");
				$("li.tabbedZonesNavItem").each(function(){
					if(!$(this).hasClass("active")){
						$(this).addClass("inactive");
					}
				});
			}
			return false;
		});
		
		$("ul#primaryNav .flyout").parents("#primaryNav").hover(function(){
			$("ul.tabbedZonesNav").slideUp();
			//$(".tabbedZones.overlay").addClass("overlayHidden").removeClass("overlay");
		},function(){
			$("ul.tabbedZonesNav").slideDown();
			//$(".tabbedZones.overlayHidden").addClass("overlay").removeClass("overlayHidden");
		});
		
		$("li.tabbedZonesNavItem:first-child>a").click();
	}

}

/* ##### end BASE FUNCTIONS ##### */


/* ##### THIRD-PARTY PLUGINS ##### */

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/* ##### end THIRD-PARTY PLUGINS ##### */
