/* Add algebraic easing for animations
* Based on jQuery Easing by George Smith
*/
jQuery.extend( jQuery.easing,
{
	snap: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	}
});

// Fix transparent PNGs in IE 6
/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( {blankgif:'ext.gif'} );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[@src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[@src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);

/* Add hover intent code; allows for delay on hover effects
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// Sets mouseOver delay to 0.25 seconds and mouseOut delay to 0.5 seconds. Interval is mouseOver delay in milliseconds. Timeout is mouseOut delay in milliseconds.
		var cfg = {
			sensitivity: 1,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			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; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

// Style text for "SES" treatment
(function($){ 
	$.fn.extend({
		highlight: function(strings) {
 			
 			function findText(node, string) {
			  	if (node.nodeType == 3)
			   		 return searchText(node, string);		
			  	else if (node.nodeType == 1 && node.childNodes && !(/(script|style)/i.test(node.tagName))) {
			   		for (var i = 0; i < node.childNodes.length; ++i) {
			    		i += findText(node.childNodes[i], string);
			   		}
			  	}
			  	return 0;
  	
 			}
 
		   	function searchText(node, string){
		  		var position = node.data.toUpperCase().indexOf(string);
		   		if (position >= 0)
		    		return highlight(node, position, string);
		    	else
		    		return 0;
		  	}
  	
		  	 function highlight(node, position, string){
		 		var spannode = document.createElement('span');
		    	spannode.className = 'ses';
		    	var middlebit = node.splitText(position);
		    	var endbit = middlebit.splitText(string.length);
		    	var middleclone = middlebit.cloneNode(true);
		    	spannode.appendChild(middleclone);
		    	middlebit.parentNode.replaceChild(spannode, middlebit);
		 		return 1;
		 	}
 
			 return this.each(function() {
			 	if(typeof strings == 'string')
			 		findText(this, strings.toUpperCase());	
			 	else
			 		for (var i = 0; i < strings.length; ++i) findText(this, strings[i].toUpperCase());	
			 });
        }
    }); 
})(jQuery);

$(document).ready(function(){

// Activate PNG Fix
$(document).pngFix(); 

// Accordion
	$(".accordionPanel ul").hide();
	$(".accordionPanel").hoverIntent(function(){
		$(this).siblings(".accordionPanel").children("ul:visible").slideUp("slow", "snap", null);
		$(this).children("ul").slideDown("slow", "snap", null)},
		function(){$(this).children("ul").slideUp("slow","snap",null);}
	);

// Home Page Carousel
	var o = $.extend({
	
	// Carousel Options ** Customize for Each Usage
	wrapID : "carousel",
	wrapClass : null,
	panelID : null,
	panelClass : "carouselPanel"
	
	}, o || {});
	
	var
	
	// Time Between Slides in Milliseconds
	time = 10000;
	
	// Speed of Fade in Milliseconds
	trans = 2000;
	
	// Show Play/Pause Controls? (leave blank for false)
	var pcontrol = "";
	
	// Function Variables **DO NOT CHANGE **
	var	wi = o.wrapID, pc = o.panelClass, wrap = $("#"+wi), panel = $("."+pc), t = $(this), i = 1, n = 1, running = false, ticking = false, count = panel.size();
	
	// Create Controls
	wrap.prepend("<ul id='control'></ul>");
   	panel.each(function (i, id) {
		i = i+1;
		id = "cp"+i;
		$(this).addClass(id);	// Assign unique, sequential ID to each panel
		$("#control").append('<li><a href="#" id="'+id+'">'+i+'</a></li>'); // Create index with equivalent class for each panel, numbered sequentially
	
		
	// Show first panel
		$("."+pc+":not(':first')").hide();
		$("#control li:first").children("a").addClass("selected");
	
	// Manual Advance
		$("#"+id).click(function() {
			if(!running) {
				running = true;
				clearInterval(timer);	// Stops Auto Advance
				fade(id, pc);			// Go to corresponding panel
			};
		});
	});
	
	// Auto Advance Timer
	timer = setInterval(function auto(i, id, pc) {go(i);}, 8000);
	
	// Auto Advance Function
	function go(to) {
		if(!running) {
			running = true;
			if(i>3) { // If last, then goto first
				i = 1;
				}
			else i = i+1;
			id = "cp"+i;
			fade(id, pc);
			};
		};
	
	// Slide Animation
	function fade(id, pc) {
			$("."+pc+":not('."+id+"')").css("z-index","9");			// Put other panels below selected slide
			$("."+id).css("z-index","10")						 	// Put selected panel on top of others
				.fadeIn(trans, function(){						// Fade selected panel in
				$("."+pc+":not('."+id+"')").hide();				// After selected panel fades in, hide others
				running = false;
				});
			$("#control a:not('#"+id+"')").removeClass("selected");	// Remove highlight from previously selected panel index
			$("#"+id).addClass("selected");						// Add highlight to newly selected panel index
		};
		
		
		
	// Auto Advance News Ticker	
	$(".newsItem").each(function (n, nid) {
		n = n+1;
		nid = "ni"+n;
		$(this).addClass(nid);	
	});
	$(".newsItem:not(':first')").hide();
	$(".newsItem a").hover(
		function(){
			ticking = true;
		},
		function(){
			ticking = false;
		}
	);
	newsTimer = setInterval(function newstick(n, nid) {tick(n)}, 8000);
	function tick(to) {
		if(!ticking) {
			ticking = true;
			if(n>=3) {
				n = 1;
				}
			else n = n+1;
			nid = "ni"+n;
			newsy(nid);
			};
		};
		
	function newsy(nid){
			$(".newsItem:not('."+nid+"')").css("z-index","9");
				$("."+nid).css("z-index","10")
					.fadeIn(2000, function(){
					$(".newsItem:not('."+nid+"')").hide();
					ticking = false;
					});
			};

// Killall Links to Nowhere
$("a[href='#'],a[href='blank.html']").click(function(){
		return false;
	});
	
// SES treatment
$("body").highlight("SES™");
	
// If no stories, remove sidebar block
$(".module").each(function(){
		count = $(this).find("ul li").size();
		if (count < 1) {$(this).remove();}
	});

// If no stories, remove news ticker
$("#news").each(function(){
		count = $(this).find("ul li").size();
		if (count < 1) {$(this).remove();}
	});
	
// Style 1st paragraph of each story
$("#story p:first").addClass("initial");

// Form validation
$("form p.req").append('<img src="http://172.16.20.170/images/form/check.gif" alt="Field OK" class="check" /><img src="http://172.16.20.170/images/form/fix.gif" alt="Field Bad" class="fix" />');
$("form p img").hide();
$("form p.req input[type=text], form p.req textarea").blur(function(){
		if ( $(this).val() != "" ) {
			$(this).siblings(".fix").hide();
			$(this).siblings(".check").fadeIn("slow", "snap");
		}
		if ( $(this).val() == "" ) {
			$(this).siblings(".check").hide();
			$(this).siblings(".fix").fadeIn("slow", "snap");
		}
	});
$("form").submit(function(){
	oops = 0;
	$(this).find("p.req input[type=text], p.req textarea").each(function(){
		if ( $(this).val() != "" ) {
			$(this).siblings(".fix").hide();
			$(this).siblings(".check").fadeIn("slow", "snap");
		}
		if ( $(this).val() == "" ) {
			$(this).siblings(".check").hide();
			$(this).siblings(".fix").fadeIn("slow", "snap");
			oops = 1;
		}		
	});
	$(".fix:visible").each(function(){
			oops = oops+1;
		});
	if ( oops > 0 ) {
		warn = $("p.warning").size();
		if ( warn == 0 ) {
				$(this).append('<p class="initial warning"><strong>Please fill out the form in its entirety before submitting.</strong></p>');
			};
		return false;
		}
	else {$(this).submit();};
	});
});