$(document).ready(function() {
	addHoverClass();
	firstFocus();
	setTextSize(null);
	addCloseButtonToCLAMenu()
	addMenuEffects();
	truncateLinks();
	addClickEvents();
	fixBreadcrumbs();
//	setTestMode();
});

//------------------------------------------------------------------------
function addHoverClass() {
// Finds any non-anchor elements that have a :hover pseudoclass defined in CSS,
// and adds the "over" class to them on mouseover. This is because IE does not
// support pseudoclasses on elements other than anchors.
	
	if (document.all && document.getElementById) {
		setEvent = function(objID) {
			$(objID).hover(
				function(){$(this).addClass('over');},
				function(){$(this).removeClass('over');}
			);
		}
		setEvent('#clamenu');
	}
}

//------------------------------------------------------------------------
function firstFocus() {
	
}

//------------------------------------------------------------------------
function addClickEvents() {
//Creates additional controls on the page that use JavaScript. If JS is not enabled, these
//controls will not even exist for the user to see.

	// Text size
	$('#textsize1').append('Text size: ');
	$('#textsize1').append('<a href="javascript:setTextSize(\'small\');" class="font_select_sm"><img src="/commonfiles/images/buttons/text_sm.jpg" alt="Small"/></a>');
	$('#textsize1').append('<a href="javascript:setTextSize(\'large\');" class="font_select_lg"><img src="/commonfiles/images/buttons/text_lg.jpg" alt="Large"/></a>');
	$('#textsize1').append('<a href="javascript:setTextSize(\'jumbo\');" class="font_select_xl"><img src="/commonfiles/images/buttons/text_xl.jpg" alt="Jumbo"/></a>');

	$('#textsize2').append('Text size: ');
	$('#textsize2').append('<a href="javascript:setTextSize(\'small\');" class="font_select_sm"><img src="/commonfiles/images/buttons/text_sm.jpg" alt="Small"/></a>');
	$('#textsize2').append('<a href="javascript:setTextSize(\'large\');" class="font_select_lg"><img src="/commonfiles/images/buttons/text_lg.jpg" alt="Large"/></a>');
	$('#textsize2').append('<a href="javascript:setTextSize(\'jumbo\');" class="font_select_xl"><img src="/commonfiles/images/buttons/text_xl.jpg" alt="Jumbo"/></a>');
}

//------------------------------------------------------------------------
function runBehindCurtain(functionToRun, justKidding) {
// Fades the entire page to a black overlay, executes a function, then removes
// the overlay. Useful for switching style sheets.
	if (justKidding) functionToRun();
	else {
		$('body').append('<div id="wholepageoverlay"/>');
		$('#wholepageoverlay').fadeIn(300, function() {
			functionToRun();
			$('#wholepageoverlay').fadeOut(300, function() {$(this).remove();});
		});
	}
}

//------------------------------------------------------------------------
function setTextSize(size) {
	if (size==''||size==null) {
		var cookie=readCookie('size');
		size = cookie ? cookie : 'small';
		skipCurtain=true;
	}
	else skipCurtain=false;
	runBehindCurtain(function() {
		var title = 'text ' + size;
		var i, a, main;
		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { // Loop through all LINK elements in header
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) { //Only looking for style sheets with a title defined
				if (a.getAttribute("title").indexOf("text") != -1) { //Only looking for style sheets with "text" in the title
					a.disabled=true; //Disable every sheet. For Safari, IE, and Konqueror, this property has to be set before it can be changed.
					if(a.getAttribute("title") == title) { //Enable the matching style sheet
						a.disabled = false;
						createCookie('size', size);
					}
				}
			}
		}
	}, skipCurtain);
}

//------------------------------------------------------------------------
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		var expires = '; expires=' + date.toGMTString();
	}
	else var expires = '';
	document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,'',-1);
}



//------------------------------------------------------------------------
function addMenuEffects() {
	$('#clamenu').hover(
		function(){$('#clamenucontent').show();},
		function(){$('#clamenucontent').hide();});
}
	/*$('#clamenu').hover(
		function(){$('#clamenucontent').hide().slideDown(50);},
		function(){$('#clamenucontent').wait(500).slideUp(100);});
}*/

$.fn.wait = function(time, type) {
	time = time || 1000;
	type = type || "fx";
	return this.queue(type, function() {
		var self = this;
		setTimeout(function() {$(self).dequeue();}, time);
	});
};

function addCloseButtonToCLAMenu() {
	$('#clamenucontent').prepend('<a class="clamenuclose" href="#">X</a>');
	$('.clamenuclose').click(function() {$('#clamenucontent').hide(); $(this).blur();});
}

function setTestMode() {

	//$('#clamenucontent').show();

	$('#mainspace_3').append('<div id="switchColor">');
	$('#switchColor').css( {
		position: 'absolute',
		top: '10px',
		right: '10px' });
	$('#switchColor').append('<a href="#" id="switchColorLink" title="Switch to white">Switch to white</a>');
	var imgLoc = '../../departments/commonfiles/images/';
	$('#switchColorLink').css( {
		color: 'black' }).click( function() {
			if ($(this).attr('title')=='Switch to black') {
				$('#headbox').css('backgroundImage','url("'+imgLoc+'backgrounds/headerbar_black.jpg")');
				$('#siteheader_purdue').css('backgroundImage','url("'+imgLoc+'logos/onblack_purdue-signature.png")');
				$('#siteheader_cla').css('backgroundImage','url("'+imgLoc+'logos/onblack_cla-signature.png")');
				$(this).attr('title','Switch to white').text('Switch to white');
			}
			else {
				$('#headbox').css('backgroundImage','url("'+imgLoc+'backgrounds/headerbar.jpg")');
				$('#siteheader_purdue').css('backgroundImage','url("'+imgLoc+'logos/purdue-signature.png")');
				$('#siteheader_cla').css('backgroundImage','url("'+imgLoc+'logos/cla-signature.png")');
				$(this).attr('title','Switch to black').text('Switch to black');
			}
			$(this).blur();
		});
	
}

function sortMenu(whichMenu, hasDetails) {
//This function rearranges the side menu items by "Rank in Menus" data field from the CMS.
//If JavaScript is disabled, the menu will have all the items but not in the intended order.

	//Set variables based on which menu. The first three variables (array, current and children)
	//are set by Collage code on the page itself before this function is called.
	var menuArray = new Array();
	var menuHasCurrent;
	var menuHasChildren;
	var menuDetails = new Array();
	var menuDiv;
	if (whichMenu=='side') {
		menuArray = sidemenu;
		menuHasCurrent = sideHasCurrent;
		menuHasChildren = sideHasChildren;
		menuDiv = document.getElementById('sidebox_menu');
	}
	if (whichMenu=='index') {
		menuArray = indexmenu;
		menuHasCurrent = indexHasCurrent;
		menuHasChildren = indexHasChildren;
		menuDiv = document.getElementById('indexmenu');
	}
	if (whichMenu=='snapshot') {
		menuArray = sidemenu;
		menuHasCurrent = sideHasCurrent;
		menuHasChildren = sideHasChildren;
		menuDiv = document.getElementById('indexmenu_snapshot');
	}

	//Do nothing further if the menu doesn't need to be sorted
	if (!menuHasCurrent || !menuHasChildren) {
		findActiveMenuItem();
		return;
	}

	//Get the menu's UL element and clear its contents
	var menuUL;
	for (var d=0; d<menuDiv.childNodes.length; d++) {
		if (menuDiv.childNodes[d].nodeType==1) {
			if (menuDiv.childNodes[d].nodeName.toLowerCase()=='ul') menuUL=menuDiv.childNodes[d];
		}
	}
	while (menuUL.childNodes.length>=1) menuUL.removeChild(menuUL.firstChild);

	var menuTxt; var menuLink; var menuItem;
	var menuBold; var menuDesc; var menuBr;

	if (whichMenu=='side') {
	//Create and add the first item to the list for the section home page
		menuTxt=document.createTextNode(sidemenutop[1]);
		menuLink=document.createElement('a');
		menuLink.setAttribute('href',sidemenutop[0]);
		menuLink.appendChild(menuTxt);
		menuItem=document.createElement('li');
		menuItem.className='sidebox_sectionhome';
		menuItem.appendChild(menuLink);
		menuUL.appendChild(menuItem);
	}
	
	// Sort the menu array by Rank in Menus (the first item in each sub-array)
	function sortByRank(a,b){return((a[0]<b[0])?-1:((a[0]>b[0])?1:0));}
	menuArray.sort(sortByRank);
	
	//Go through the sorted array and add link elements to sideul
	for (var m=0; m<menuArray.length; m++) {
		menuTxt=document.createTextNode(menuArray[m][2]);
		menuItem = document.createElement('li');
		menuLink=document.createElement('a');
		menuLink.setAttribute('href',menuArray[m][1]);
		if (hasDetails) {
			menuBold=document.createElement('strong');
			menuBold.appendChild(menuTxt);
			menuLink.appendChild(menuBold);
		}
		else {
			menuLink.appendChild(menuTxt);
		}
		menuItem.appendChild(menuLink);
		if (hasDetails) {
			if (menuArray[m][3]!=' ') {
				menuBr=document.createElement('br');
				menuDesc=document.createTextNode(menuArray[m][3]);
				menuItem.appendChild(menuBr);
				menuItem.appendChild(menuDesc);
			}
		}
		menuUL.appendChild(menuItem);
	}
	
	findActiveMenuItem();

} // sortMenu


//------------------------------------------------------------------------

function findActiveMenuItem() {
	//Note: this function is called from markup and will execute BEFORE truncateLinks, which runs on pageload
	
	//Get the menu div, the UL inside it, and the LI set inside that
	var menuDiv = document.getElementById('sidebox_menu');
	var menuUL = menuDiv.getElementsByTagName('ul')[0];
	var menuItems = new Array();
	menuItems = menuUL.getElementsByTagName('li');
	
	//Get the current URL
	currentURL = document.location.href;
	if (currentURL.indexOf('index.')>-1) currentURL=currentURL.substr(0,currentURL.lastIndexOf('\/')+1); //Remove the index.xxx name
	if (currentURL.indexOf('cms.itap.purdue.edu')>-1) currentURL=thisurl; // This means we are in the Collage editor: use thisurl, a variable written to the document by component code in the contribution document (before this function is called)
	if (currentURL.indexOf('\/cla\/') > -1) currentURL = currentURL.substr(currentURL.indexOf('\/cla\/')); //This also means we're in Collage but this line strips everything before the "real" path (all the Collage gobbledegook)


	//Loop through the LI elements and check the A tags' href property
	var menuLink; var a;
	var menuText;
	for (i=0; i<menuItems.length; i++) {
		
		//Get the link element in the LI
		menuLink = menuItems[i].getElementsByTagName('a')[0];
		
		itemURL = menuLink.href;
		if (itemURL.indexOf('\/cla\/')>-1) itemURL = itemURL.substr(itemURL.indexOf('\/cla\/'));
		if (itemURL.indexOf('index.')>-1) itemURL=itemURL.substr(0,itemURL.lastIndexOf('\/')+1); //Remove the index.xxx name
		
		if (currentURL==itemURL) {
			//Found the match, now get the text node
			menuText='';
			for (a=0; a<menuLink.childNodes.length; a++) {
				if (menuLink.childNodes[a].nodeType==3) menuText=menuLink.childNodes[a];
			}
			if (menuText=='') menuText=document.createTextNode('Use Metadata to set menu name for this page');
			//Clear the LI item, and add the text node back
			while (menuItems[i].childNodes.length>=1) menuItems[i].removeChild(menuItems[i].firstChild);
			menuItems[i].appendChild(menuText);
			menuItems[i].className+=' sidebox_current';
		}
	}
} //findActiveMenu

function truncateLinks() {
//	Looks for any URLs on the page that contain both cla.purdue.edu domain and an index.html reference,
// 	and removes the index from the URL. Because Collage won't, that's why.

	var links = document.getElementsByTagName('a');
	for (var a=0; a<links.length; a++) {
		href = links[a].href;
		//More Collage won't do: write the current URL. (Yes, I'm sure.) This is for the "report a problem" link.
		/* no longer needed due to upgrade to Ajax problem reporting ... right?
		if (href.indexOf('cla.purdue.edu')>-1 && href.indexOf('prevurl=/cla/')>-1) {
			href = href.substr(0, href.lastIndexOf('prevurl=/cla/') + 8) + document.location;
			links[a].href = href;
		}
		*/
		if (href.indexOf('cla.purdue.edu')>-1 && href.indexOf('/index.')>-1) {
			href = href.substr(0, href.lastIndexOf('/') + 1);
			links[a].href = href;
		}
	}
}

//----------------------------------------------------------------------

function fixBreadcrumbs() {
	if($('#breadcrumbs span a:first').text() == "_") {
		$('#breadcrumbs span a:first').remove();
		var fi = $('#breadcrumbs span').html().indexOf(' href=');
		var newstr = $('#breadcrumbs span').html().substring(fi-3);
		$('#breadcrumbs span').replaceWith(newstr);
	}
}