/* = CLEAR FIELD
-------------------------------------------------
	clears the value of any inpu field with the
	class name of clearDefault
-------------------------------------------------*/

function clickClear() {
	if(!document.getElementsByTagName) return false;
	
	var inputs = document.getElementsByTagName("INPUT");
	
	for ( var i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.indexOf("clearDefault") != -1)
		{
			inputs[i].onclick = function() {
				if(this.value == this.defaultValue)
				{
					this.value = "";
				}
				return 0;
			}
			inputs[i].onfocus = function() {
				if(this.value == this.defaultValue)
				{
					this.value = "";
				}
				return 0;
			}
			inputs[i].onblur = function() {
				if(this.value == "")
				{
					this.value = this.defaultValue;
				}
				return 0;
			}
		}
	}
	return 0;
}

/* = FEATURE NEWS AREA
-------------------------------------------------*/

function prepFeaturedNews() {
	if(!document.getElementById || !document.getElementsByTagName) return 0;
	if(!document.getElementById("featured-news-block") 
		|| !document.getElementById("featured-news-list") 
		|| !document.getElementById("featured-news-image")) return 0;
	
	var list = document.getElementById("featured-news-list");
	var imageBlockContainer = document.getElementById("featured-news-image");
	
	var listItem = list.getElementsByTagName("LI");
	
	for( var i = 0; i < listItem.length; i < i++ )
	{
		var link = listItem[i].getElementsByTagName("A")[0];
		if(!link) continue;
		
		listItem[i].onmouseover = function() {
			var link = this.getElementsByTagName("A")[0];
			var href = link.getAttribute("href");
			
			var imageId = href.split("#")[1];

			if(!document.getElementById(imageId)) return 0;
			var imageBlock = document.getElementById(imageId);
			hideAll(imageBlockContainer, "DIV", "photo", "hide");
			for(var j = 0; j < listItem.length; j++)
			{
				listItem[j].className = listItem[j].className.replace(/ ?active ?/g, "");
			}
			imageBlock.className = imageBlock.className.replace(/ ?hide ?/g, "");
			var activateListItem = this;
			if(activateListItem.className) {
				activateListItem.className += " active";
			}
			else {
				activateListItem.className = "active";
			}
			
			return false;
		}
	}
}

/* = HIDE ELEMENTS IN A CONTAINER OF A CERTAIN TYPE, CLASS AND HIDE THEM WITH SPECIFIED CLASS */

function hideAll(container, elementType, elementClass, hideClass) {
	if(!container || !elementType || !elementClass || !hideClass) return 0;
	
	var element = container.getElementsByTagName(elementType);
	
	for(var i = 0; i < element.length; i++)
	{
		if(!element[i].className.match(elementClass)) continue;
		if(element[i].className.match(hideClass)) continue;
		
		if(element[i].className) {
			element[i].className += " hide";
		}
		else {
			element[i].className = "hide";
		}
	}
	return 0;
}

/* = PREP INPUT TYPES
-------------------------------------------------*/

function prepInputs() {

	var inputs = document.getElementsByTagName("INPUT");
	for(var i = 0; i < inputs.length; i++)
	{
		if(inputs[i].getAttribute("type") == "checkbox")
		{
			if(inputs[i].className)
			{
				inputs[i].className += " checkBoxInput";
			}
			else {
				inputs[i].className = "checkBoxInput";
			}
			
		}
		else if(inputs[i].getAttribute("type") == "radio")
		{
			if(inputs[i].className)
			{
				inputs[i].className += " radioInput";
			}
			else {
				inputs[i].className = "radioInput";
			}
		}
		else if (inputs[i].getAttribute("type") == "image")
		{
			if(inputs[i].className)
			{
				inputs[i].className += " submitButton";
			}
			else {
				inputs[i].className = "submitButton";
			}
		}
	}
}

function prepFormReset() {
	var forms = document.getElementsByTagName("FORM");
	for(var i = 0; i < forms.length; i++)
	{
		var links = forms[i].getElementsByTagName("A");
		for(var j = 0; j < links.length; j++)
		{
			
			if(links[j].className.match("reset-link"))
			{
				links[j].parentForm = forms[i];
				links[j].onclick = function() {
					this.parentForm.reset();
					
					return false;
				}
			}
		}
	}
	return 0;
}


/* = PRINT LINKS
-------------------------------------------------
	This function adds the javascript print
	function to the onclick event.  The href of 
	this links should be to a printer friendly page
	if possible
-------------------------------------------------*/

function prepPrintLinks() {
	var link = document.getElementsByTagName("A");
	for(var i = 0; i < link.length; i++)
	{
		if(!link[i].className.match("print-link")) continue;
		
		link[i].onclick = function() {
			print();
			return false;
		}
	}
	return 0;
}

/* = EMAIL A FRIEND LINK
-------------------------------------------------*/

function prepEmailFriend() {
	if(!document.getElementById("action-email") || !document.getElementById("emailFriendForm")) return true;
	if(!document.getElementById("emailHref")) return true;
	var emailLink = document.getElementById("action-email").getElementsByTagName("A")[0];
	var emailForm = document.getElementById("emailFriendForm");
	var hrefArea = document.getElementById("emailHref");

	emailLink.onclick = function() {
		showElement(emailForm);
		return false;
	}
	
	var href = location.href;
	var hrefText = document.createTextNode(href);
	hrefArea.appendChild(hrefText);
	
	var closeLink = emailForm.getElementsByTagName("A");
	for(var i = 0; i < closeLink.length; i++)
	{
		if(!closeLink[i].className.match("close")) continue;
		
		closeLink[i].onclick = function() {
			hideElement(emailForm);
			return false;
		}
	}
}

/* = EXPANDABLE NAVIGATION
-------------------------------------------------*/

function expandableSection(blockId, expElementType, onClickElementType) {
	if(!document.createElement) return false;
	if(!document.getElementById(blockId) || !expElementType) return false;
	
	var container = document.getElementById(blockId);
	var expElement = container.getElementsByTagName(expElementType);
	
	for(var i = 0; i < expElement.length; i++)
	{
		if(!expElement[i].getElementsByTagName("UL").length) continue;
		if(expElement[i].className) {
			expElement[i].className += " expandable";
		}
		else {
			expElement[i].className = "expandable";
		}
		var expLink = expElement[i].getElementsByTagName("A")[0];
		
		var link = document.createElement("A");
		link.setAttribute("href", "#");
		link.setAttribute("title", "Click here to expand the list");
		link.className = "expand-link";
		
		expElement[i].insertBefore(link, expLink);
		
		link.onclick = function() {
			var parentLi = this.parentNode;
			// grab the first list
			var subList = parentLi.getElementsByTagName("UL")[0];
			
			if(subList.className.match("hidden")) {
				showElement(subList);
				if(this.className) {
					this.className += " collapsed";
				}
				else {
					this.className = "collapsed";
				}
			}
			else {
				hideElement(subList)
				this.className = this.className.replace(/ ?collapsed ?/g, "");
			}
			
			return false;
		}
	}
	
	return 0;
}

/* = HIDE ELEMENT
-------------------------------------------------*/

function hideElement(element) {
	if(!element || element.className.match("hidden")) return false;
	
	if(element.className) {
		element.className += " hidden";
	}
	else {
		element.className = "hidden";
	}
	
	return 0;
}

/* = SHOW ELEMENT
-------------------------------------------------*/

function showElement(element) {
	if(!element || !element.className.match("hidden")) return false;
	
	element.className = element.className.replace(/ ?hidden ?/g, "");
	
	return 0;
}

function prepBeBlockSlideShow() {
	var prev = $('be-block-navigation').getElementsByClassName("prev")[0];
	var next = $('be-block-navigation').getElementsByClassName("next")[0];
	
	var curr = 0;
		
	$('be-block-image').setAttribute("src", beSlideShowImages[curr]);
	
	prev.onclick = function() {
		
		if( curr == 0 )
		{
			curr = beSlideShowImages.length - 1;
		}
		else {
			curr -= 1;
		}
		
		$('be-block-image').setAttribute("src", beSlideShowImages[curr]);
		
		return false;
	}
	
	next.onclick = function() {
		if ( curr == beSlideShowImages.length - 1 )
		{
			curr = 0;
		}
		else {
			curr += 1;
		}
		
		$('be-block-image').setAttribute("src", beSlideShowImages[curr]);
		
		return false;
	}
		
	$('be-block-navigation').show();
	
	return 0;
}

/* = CLEAR FIELD
-------------------------------------------------
	clears the value of any inpu field with the
	class name of clearDefault
-------------------------------------------------*/

function clickClear() {
	if(!document.getElementsByTagName) return false;
	
	var inputs = document.getElementsByTagName("INPUT");
	
	for ( var i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.indexOf("clearDefault") != -1)
		{
			inputs[i].onclick = function() {
				if(this.value == this.defaultValue)
				{
					this.value = "";
				}
				return 0;
			}
			inputs[i].onfocus = function() {
				if(this.value == this.defaultValue)
				{
					this.value = "";
				}
				return 0;
			}
			inputs[i].onblur = function() {
				if(this.value == "")
				{
					this.value = this.defaultValue;
				}
				return 0;
			}
		}
	}
	return 0;
}

/* = CALENDAR SECTION
-----------------------------------------------------------------------------------------*/

/* = ATTACH CALENDAR
-------------------------------------------------*/

function prepAttachCalendar() {

	var inputs = document.getElementsByTagName("INPUT");

	for (var i = 0; i < inputs.length; i++)
	{
		if(!inputs[i].className.match("attach-calendar"))
		{
			continue;
		}
		var span = document.createElement("SPAN");
		span.className = "popup-calendar-container";
		var parent = inputs[i].parentNode;
		var input = parent.removeChild(inputs[i]);
		
		input.onclick = function(e) {
			
			// cancels out event bubbling
			if (!e) var e = window.event;
			e.cancelBubble = true;
			if (e.stopPropagation) e.stopPropagation();
			
			// hide any other open calendars
			hideAllPopups("DIV", "popup-calendar");
			
			// EDIT THIS LINE FOR POPUP CAL AJAX URL
			var url = "/calendar/getCalendar.php";
			var parent = this.parentNode;
			var parentChildSpans = parent.getElementsByTagName("SPAN");
			var popupCalendar = parent.getElementsByTagName("DIV")[0];
			if(popupCalendar)
			{
				var haspopupCal = popupCalendar.className.match("popup-calendar");
				if(haspopupCal)
				{
					$(popupCalendar).show();
					return true;
				}
			}
			
			// if popup Calendar has not been added before
			var now = new Date();
			var month = now.getMonth();
			var postVars = "m="+month;
			var calAjax = new Ajax.Request( url, {
				method: 'post',
				postBody: postVars,
				onComplete: addPopupCalendar(parent, url)
			});
		}
		
		span.appendChild(input);
		parent.appendChild(span);

	}
	
	return 0;
}

/* = ADD POPUP CALENDAR
-------------------------------------------------
	Appends the newly created calendar to the
	containing element and call the function that
	preps the month navigation.
-------------------------------------------------*/

function addPopupCalendar(parent, url) {

	// returns anonymous function and passes parent variable using closure
	return function(transport) {
		var response = transport.responseText;
		var popupCalendar = createPopupCal(response, parent);
	
		var popupCalendarInside = "";
		var calNavigation = "";
		
		var divs = popupCalendar.getElementsByTagName("DIV");
		for (var i = 0; i < divs.length; i++)
		{
			if(divs[i].className.match("popup-calendar-inside")) {
				popupCalendarInside = divs[i];
			}
			else if(divs[i].className.match("calendar-navigation")) {
				calNavigation = divs[i];
			}
		}
		
		// passes prep function down to ajax functions for after calendar is replaced
		prepCalNavLinks(popupCalendarInside, calNavigation, url, function() {
			return prepPopupCalLinks(popupCalendar, parent);
		});
		parent.appendChild(popupCalendar);
	}
	
	return 0;
}

/* CREATE POPUPCAL
-------------------------------------------------
	Creates the wrappers and close link for the
	ajax response (calendar)
	Calls PrepPopupCalLinks to prep calendar links
-------------------------------------------------*/

function createPopupCal(response, parent) {
	
	// create popup calendar container
	var popupCalendar = document.createElement("DIV");
	popupCalendar.className = "popup-calendar";
	
	popupCalendar.onclick = function(e) {
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
		return 0;
	}
	
	// create popup calendar inside wrapper the contents of which get replaced
	// when switching from month to month
	var popupCalendarInside = document.createElement("DIV");
	popupCalendarInside.className = "popup-calendar-inside";
	popupCalendarInside.innerHTML = response;
	popupCalendar.appendChild(popupCalendarInside);
	
	//create close link
	var closeLink = document.createElement("A");
	closeLink.setAttribute("href", "#");
	closeLink.className = "close-link";
	var closeLinkText = document.createTextNode("Close");
	closeLink.appendChild(closeLinkText);
	Event.observe(closeLink, 'click', cancelCloseLink(closeLink));
	
	// add close link
	popupCalendar.appendChild(closeLink);
	
	// add onclick events to calendar links
	prepPopupCalLinks(popupCalendar, parent);
	
	return popupCalendar;
}

/* = CANCEL CLOSE LINK
-------------------------------------------------
	Cancels the close link's default action
-------------------------------------------------*/

function cancelCloseLink(linkElement) {
	return function(e) {
		// have to use $() to extend the element for use with hide
		var linkParent = $(linkElement.parentNode);
		linkParent.hide();
		
		Event.stop(e);
	}
}

/* = PREP POPUP CALENDAR LINKS
-------------------------------------------------
	Preps all of the calendar links and assigns
	them onclick events.
-------------------------------------------------*/

function prepPopupCalLinks(popupCalendar, parent) {
	// set onclick functions for calendar links
	var calTable = popupCalendar.getElementsByTagName("TABLE")[0];
	var calLinks = calTable.getElementsByTagName("A");
	
	for ( var i = 0; i < calLinks.length; i++)
	{
		if(!calLinks[i].getAttribute("href")) return false;
		var href = calLinks[i].getAttribute("href");
		href = href.split("#")[1];
		
		// EDIT THIS IF YOU HAVE A DIFFERENT FORMAT
		var regexp = new RegExp("[0-3][0-9]-[0-1][0-9]-[0-9][0-9][0-9][0-9]");
		var matches = regexp.exec(href);
		
		if(matches)
		{
			Event.observe(calLinks[i], 'click', pickDate(calLinks[i], parent, popupCalendar));
		}
		else {
			Event.observe(calLinks[i], 'click', function(e) {
				Event.stop(e);
			});
		}
	}
	
	return 0;
}

/* = PICK DATE
-------------------------------------------------
	This event fires when a link with a date is
	clicked and puts the link's date into the input
-------------------------------------------------*/

function pickDate(linkElement, parent, popupCalendar) {
	return function(e) {
		var inputField = parent.getElementsByTagName("INPUT")[0];
		var href = linkElement.getAttribute("href");
		var date = href.split("#")[1];
		
		inputField.setAttribute("value", date);
		inputField.value = date;
		
		$(popupCalendar).hide();
		
		Event.stop(e);
	}
}

/* = PREP CALENDAR NAV
-------------------------------------------------
	Find the Navigation links and sets the url
	for the ajax call. Then calls prepCalNavLinks()
-------------------------------------------------*/

function prepCalNav() {
	if(!document.getElementById("calendar-block") || !document.getElementById("calendar-block-inside")) return false;
	var calBlock = document.getElementById("calendar-block");
	var calBlockInside = document.getElementById("calendar-block-inside");
	
	var divs = calBlock.getElementsByTagName("DIV");
	for (var i = 0; i < divs.length; i++)
	{
		if(divs[i].className.match("calendar-navigation")) break;
	}
	
	var calNavigation = divs[i];
	
	// EDIT THIS LINE FOR NON POPUP CALENDAR AJAX CALL
	var url = "/calendar/getCalendar.php";
	
	prepCalNavLinks(calBlockInside, calNavigation, url, null);
	
	return 0;
}

/* = NEXT MONTH
-------------------------------------------------
	Determines next month
-------------------------------------------------*/

function nextMonth(currMonth) {
	if(currMonth == 12) {
		return 1;
	}
	else {
		if(currMonth + 1 == 0) {
			return 1;
		}
		else {
			return currMonth + 1;
		}
	}
}

/* = previous MONTH
-------------------------------------------------
	Determines previous month
-------------------------------------------------*/

function prevMonth(currMonth) {
	if(currMonth == 1) {
		return 12;
	}
	else {
		if (currMonth - 1 == 0) {
			return 12;
		}
		else {
			return currMonth - 1;
		}
	}
}

/* = PREP CALENDAR NAV LINKS
-------------------------------------------------
	Sets the onclick events for the calendar
	navigation links.
-------------------------------------------------*/

function prepCalNavLinks(calBlockInside, calNavigation, url, prepFunction) {
	return; // added PP to stop Javascript errors
	var calNavLinks = calNavigation.getElementsByTagName("A");
	
	for ( var j = 0; j < calNavLinks.length; j++)
	{
		if(calNavLinks[j].className.match("prev"))
		{
			var prevCalNavLink = calNavLinks[j];
		}
		else if (calNavLinks[j].className.match("next"))
		{
			var nextCalNavLink = calNavLinks[j];
		}
	}
	
	if(prevCalNavLink.nodeName == "A" && nextCalNavLink.nodeName == "A")
	{
		// set onclick event
		Event.observe(prevCalNavLink, 'click', prevCalendar(prevCalNavLink, nextCalNavLink, calBlockInside, calNavigation, url, prepFunction));
		
		// set onclick event
		Event.observe(nextCalNavLink, 'click', nextCalendar(prevCalNavLink, nextCalNavLink, calBlockInside, calNavigation, url, prepFunction));
	}
	
	return 0;
}

/* = PREVIOUS CALENDAR
-------------------------------------------------
	Calls the previous calendar ajax and resets
	navigation links.
-------------------------------------------------*/

function prevCalendar(prevCalNavLink, nextCalNavLink, calBlockInside, calNavigation, url, prepFunction) {
	
	return function(e) {
		var href = Number(prevCalNavLink.getAttribute("href").split("#")[1]);
		var newCurrMonth = href;
		href = prevMonth(href);
		prevCalNavLink.setAttribute("href", "#"+href);
		
		var nextHref = Number(nextCalNavLink.getAttribute("href").split("#")[1]);
		nextHref = prevMonth(nextHref);
		nextCalNavLink.setAttribute("href", "#"+nextHref)
		
		// POST STRING
		var postVars = "m="+newCurrMonth;
		
		var prevMonRequest = new Ajax.Request(
			url,
			{
				method: 'post',
				postBody: postVars,
				onComplete: replaceCalendar(calBlockInside, calNavigation, url, prepFunction)
			}
			);
		Event.stop(e)
	}
}

/* = NEXT CALENDAR
-------------------------------------------------
	Calls the next calendar ajax and resets
	navigation links.
-------------------------------------------------*/

function nextCalendar(prevCalNavLink, nextCalNavLink, calBlockInside, calNavigation, url, prepFunction) {
	return function(e) {
		var href = Number(nextCalNavLink.getAttribute("href").split("#")[1]);
		var newCurrMonth = href;
		href = nextMonth(href);
		nextCalNavLink.setAttribute("href", "#"+href);
		
		var prevHref = Number(prevCalNavLink.getAttribute("href").split("#")[1]);
		prevHref = nextMonth(prevHref);
		prevCalNavLink.setAttribute("href", "#"+prevHref);
		
		// POST STRING
		var postVars = "m="+newCurrMonth;
		var prevMonRequest = new Ajax.Request(
			url,
			{
				method: 'post',
				postBody: postVars,
				onComplete: replaceCalendar(calBlockInside, calNavigation, url, prepFunction)
			}
			);
			
		Event.stop(e);
	}
}

/* = REPLACE CALENDAR
-------------------------------------------------
	Replaces the contents of calBlockInside with
	ajax response ( new calendar month)
-------------------------------------------------*/

function replaceCalendar(calBlockInside, calNavigation, url, prepFunction) {
	
	return function(transport) {

		calBlockInside.innerHTML = transport.responseText;
		
		var divs = calBlockInside.getElementsByTagName("DIV");
		for (var i = 0; i < divs.length; i++)
		{
			if(divs[i].className.match("calendar-navigation")) break;
		}

		var calNavigation = divs[i];
		
		prepCalNavLinks(calBlockInside, calNavigation, url, prepFunction);
		
		if(prepFunction) {
			
			prepFunction();
		}
		return false;
	}
}

/* = HIDE ALL POPUPS
-------------------------------------------------
	Hides all open "popups" of element type
	(e.g. "DIV") and element class name.
	(e.g. "popup-calendar")
-------------------------------------------------*/

function hideAllPopups(elementType, elementClass) {
	var elementsToHide = document.getElementsByTagName(elementType);

	for ( var i = 0; i < elementsToHide.length; i++)
	{
		if(!elementsToHide[i].className) continue;
		
		var classNames = elementsToHide[i].className.split(" ");

		for( var j = 0; j < classNames.length; j++) {
			if(classNames[j] == elementClass)
			{
				$(elementsToHide[i]).hide();
			}
		}
		
	}
	return 0;
}


/* = ADD QUOTES FOR IE
-----------------------------------------------------------*/


function addQuotes() {
	var quotes = document.getElementsByTagName("Q");
	for( var i = 0; i < quotes.length; i++)
	{
		var text = quotes[i].innerHTML;
		quotes[i].innerHTML = '"'+text+'"';
	}
	
	return 0;
}



/* Function to replace Flash embed objects with a replacement image. MW 2009/03/03
----------------------------------------------------------------------------------*/

function replaceFlashWithImage() {
    if (DetectFlashVer(8, 0, 0)) {
        //alert ('we have flash');
    } else {
        var replacement = document.getElementById('flash-replacement-image');
        var flash_objects = document.getElementsByTagName('embed');
        if (replacement != null && flash_objects.length > 0)
        {
            for (var i = flash_objects.length -1; i >= 0; i--) //need to work backwards because flash_objects changes
            {
                var new_replacement = replacement.cloneNode(true);
                new_replacement.style.visibility='visible';
                new_replacement.style.display='block';
                flash_objects[i].parentNode.replaceChild(new_replacement, flash_objects[i]);
            }
        }
    }
}
        
        


/* INITIALIZE ALL FUNCTION AFTER WINDOW ONLOAD
-------------------------------------------------*/

function init() {

	if(!document.getElementById || !document.getElementsByTagName) return 0;
	// prep functions
	prepFeaturedNews();
	clickClear();
	prepPrintLinks();
	expandableSection("section-nav", "LI", "IMG");
	prepEmailFriend();
	prepInputs();
	prepFormReset();
	clickClear();
	prepAttachCalendar();
	prepCalNav();
	replaceFlashWithImage();
	
	// for clearing elements like popups when you click away from them
	document.onclick = function() {
	    hideAllPopups("DIV", "popup-calendar"); 
//		return 0; //DO NOT RETURN 0 - it breaks IE
	}
}

addLoadEvent(init);

/* = ON LOAD
---------------------------------------------------------------
	add the on load events
---------------------------------------------------------------*/
function addLoadEvent(func) {
	var oldOnLoad = window.onload
	if (typeof window.onload != 'function') 
	{
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldOnLoad();
			func();
		}
	}
}
