/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
	return this.each(function() {
		// Threshold is the maximum width an image plus its border and padding can be in relation to its parent container
		var threshold = (threshold) ? threshold : 2/3;
		
		// Determine the width of the image along with borders and padding
		var $image = $('img', $(this));
		var imageWidth = $image.width();
		var paddingLeft = parseInt($image.css('padding-left').replace('px', ''), 10);
		var paddingRight = parseInt($image.css('padding-right').replace('px', ''), 10);
		var borderLeft = parseInt($image.css('border-left-width').replace('px', ''), 10);
		var borderRight = parseInt($image.css('border-right-width').replace('px', ''), 10);
		
		// Calculate total edge (padding and border) width and the total width (edge and image)
		var edgeWidth = paddingLeft + paddingRight + borderLeft + borderRight;
		var totalWidth = imageWidth + edgeWidth;
		
		// Find parent and determine width
		var $parent = $(this).parent();
		var parentWidth = $parent.width();
		
		// If the image is greater then the threshold times the parent width resize the image and the container width
		// Otherwise set the image left's div to the size of the image plus the edge
		if ((threshold * parentWidth) <= totalWidth) {
			var revisedWidth = parentWidth * threshold;
			var revisedImageWidth = revisedWidth - edgeWidth;
			
			$image.width(revisedImageWidth);
			$(this).width(parseInt(revisedWidth, 10));
		} else {
			$(this).width(totalWidth);
		};
	});		
};

/**
 * Clears a text form element when it has the style 'clear-default'
 */
function clickClear() {
	if ($('input.clear-default').size() > 0) {
		$('input.clear-default').each(function(index) {
			this.defaultValue = $(this).val();
			$(this).click(function() {
				if ($(this).val() == this.defaultValue) {
					$(this).val('');
				};
			})
			.focus(function() {
				if ($(this).val() == this.defaultValue) {
					$(this).val('');
				};
			})
			.blur(function() {
				if ($(this).val() == "") {
					$(this).val(this.defaultValue);
				};
			});
		});
		
		// Clear out form defaults on submit
		$('form').submit(function(event) {
			$('input.clear-default').each(function(index) {
				if ($(this).val() == this.defaultValue) {
					$(this).val('');
				};
			});
		});
	};
}

/**
 * Builds pull quote divs assuming you've wrappted your content with a span with the class: pullquote-left or pullquote-right
 */
function buildPullQuote () {
	$('span.pullquote-left, span.pullquote-right').each(function(index) {
		var contents = $.trim($(this).html());
		var firstCharacterCode = contents.charCodeAt(0);
		if (firstCharacterCode < 65 || firstCharacterCode > 96) {
			contents = '&hellip; ' + contents;
		};
		
		var lastCharacter = contents.charAt(contents.length - 1);
		if ("?!.".search(lastCharacter) < 0) {
			contents = contents + ' &hellip;';
		};
		var $parent = $(this).parent();
		var $pullquote = $('<div>').attr('class', $(this).attr('class')).html(contents);
		$parent.before($pullquote);
	});
}

function stripeTables () {
	$('table tr:even').addClass('odd');
	$('.events table tr:even').removeClass('odd');
	
	$("#content-sub .callout-events .callout-events-content .event-list li:first").css("background-image", "none");
}

function dropdownToggle (dropdownId) {
	if ($("ul.dropdown ul#" + dropdownId +"").css("visibility") == "hidden") {
		$("ul.dropdown ul#" + dropdownId +"").css("visibility", "visible");
		$("ul.dropdown ul#" + dropdownId +" li:last").css("border-bottom", "1px solid #e0e0e0");
	} else {
		$("ul.dropdown ul#" + dropdownId +"").css("visibility", "hidden");
	};
}

function filterDropdownToggle () {
	if ($("#filter .dropdown").css("display") == "none") {
		$("#filter .dropdown").css("display", "block");
	} else {
		$("#filter .dropdown").css("display", "none");
	};
}

/**
 * Removes overlay from input fields for User ID and Password
 */
function removeOverlay () {
	$('form input').click(function () {
		$(this).parent().children('.overlay').hide();
	})
	.focus(function () {
		$(this).parent().children('.overlay').hide();
	})
	.blur(function () {
		if($(this).val() == '') {
			$(this).parent().children('.overlay').show();
		}
	});
}

$(document).ready(function() {
	$('div.image-left, div.image-right').imageWidth();
	removeOverlay();
	clickClear();
	buildPullQuote();
	stripeTables();
	$('#filter input:checkbox').change(toggleEvents); // Listen for checkbox changes on calendar filter
});


// Delete above if using standard Javascript, delete below if using jQuery

/**
 * Clears a text form element when it has the style 'clear-default'
 */
function clickClear() {
	if(!document.getElementsByTagName) return false;
	
	var inputs = document.getElementsByTagName("INPUT");
	
	for ( var i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.match("clear-default"))
		{
			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;
}

addLoadEvent(clickClear);

/**
 * Gets DOM elements by class name
 * @param {String} searchClass The name of the class to search for
 * @param {Object} node Optional - The DOM element to search under
 * @param {String} tag Optional - The type of element to search for
 * @returns The list of elements that follow the searchClass, node and tag
 * @type Array
 */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/**
 * Determines if a DOM element has a specific class
 * @param {Object} ele The DOM element to check
 * @param {String} cls The class to search for
 * @returns True or false if it has the class
 * @type Boolean
 */
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

/**
 * Adds a class to a DOM element
 * @param {Object} ele The DOM element to add a class to
 * @param {String} cls The class to add
 */
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

/**
 * Removes a class from a DOM element
 * @param {Object} ele The DOM element to remove a class from
 * @param {String} cls The class to remove
 */
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

/**
 * Queues up the function to fire onload
 * @param {string} func The function name without parenthesis
 */
function addLoadEvent(func) {
	var oldOnLoad = window.onload;
	if (typeof window.onload != 'function') 
	{
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldOnLoad();
			func();
		};
	}
}

/**
 * Shows/hides events based on their checkbox status
 */
function toggleEvents() {
	var category = $(this).val();
	var checked = this.checked;
	
	// See if there are siblings; if so, we'll disable/enable them accordingly
	var siblings = $(this).parent().find("ul li input:checkbox");
	var siblingsExist = false;
	if (siblings.length > 0) {
		siblingsExist = true;
	}
	
	switch(checked) {
		case false:
			// Hide corresponting events
			$('.'+category).addClass("hidden");
			
			//If it had siblings, enable/disable accordingly
			if (siblingsExist) { siblings.attr("disabled", true); };
			break;
		case true:
			// Determine if events have all categories turned on; if so, display the event
			if ($('.'+category).length > 0) {
				var classes = $('.'+category).attr("class").split(" ");
				var numclasses = 0;
				jQuery.each(classes, function(i, val) {
					if ($('#'+val).is(':checked')) {
						numclasses++;
					};
				})
				if (numclasses == (classes.length - 1)) { // Minus 1 to account for the "hidden" class already in place
					$('.'+category).removeClass("hidden");
				};
			};
			
			//If it had siblings, enable/disable accordingly
			if (siblingsExist) { siblings.attr("disabled", false); };
			break;
		default:
			break;
	};
	
	setCookie();
}

/**
 * Sets cookie to remember calendar filter state
 */
function setCookie() {
	var checkedString = "";
	var checkedArray = new Array();
	var i = 0;
	
	// Goes through checked checkboxes and adds them to an array to put in a cookie
	$('#filter input:checkbox').each(function(index) {
		if ($(this).is(':checked')) {
			checkedArray[i] = $(this).val();
			i++;
		};
		checkedString = checkedArray.join("|");
	});
	
	var date = new Date();
	date.setTime(date.getTime()+(7*24*60*60*1000*365)); // Cookie will last for 7 years
	var expires = date.toGMTString();
	
	// Set cookies for both calendar paths, some browsers need this
	document.cookie = "filter="+checkedString+"; expires="+expires+"; path=/events-reunions/calendar;";
	document.cookie = "filter="+checkedString+"; expires="+expires+"; path=/events-reunions/list;";
}

/**
 * Gets the cookie
 * @param {String} c_name Name of the cookie we are looking for
 * @returns String of contents if cookie is found, otherwise NULL
 */
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} else {
			return null;
		}
	}
}

/**
 * Checks cookie contents, populates calendar based on preferences, or checks all boxes if no cookie was set
 */
function loadCategories() {
	var categories = getCookie('filter');
	if (categories == null) {
		// Check all boxes if no cookie
		$('#filter input:checkbox').attr('checked', true);
	} else {
		// Split the string up, hide all events
		var categoriesArray = categories.split("|");
		$('#calendar-grid td dt').addClass("hidden");
		$('#calendar-grid td dd').addClass("hidden");
		$('#calendar-list tr').addClass("hidden");
		$('#calendar-list thead tr').removeClass("hidden");
		
		// Go through array and turn on corresponding categories, display events
		jQuery.each(categoriesArray, function(i, val) {
			$('#filter input:checkbox#'+val).attr('checked', true);
		});
		$('#filter input:checkbox').each(toggleEvents);
	};
}

/**
 * Check All/Uncheck All links for checkboxes on dynamic calendar
 * @param {String} state The state of the checkboxes desired, either "check" or "uncheck"
 */
function toggleBoxes(state) {
	switch(state) {
		case "check":
			$('#filter input:checkbox').attr('checked', true);
			$('#filter input:checkbox').each(toggleEvents);
			break;
		case "uncheck":
			$('#filter input:checkbox').attr('checked', false);
			$('#filter input:checkbox').each(toggleEvents);
			break;
		default:
			break;
	}
}