/*=============================================================================

			 	 TITLE:		NetMediaOne - Core Library
		  MODIFIED:		2010.09.29
		 AUTHOR(S): 	Graham Wheeler - NetMediaOne - www.netmediaone.com
		  INCLUDED:		NMO Validation, HoverIntent, PNGFix
			
=============================================================================*/


/*
jQuery Center 2.0 // 2008-09-17
Andreas Lagerkvist
http://andreaslagerkvist.com/jquery/center/
@license: http://creativecommons.org/licenses/by/3.0/
@copyright: 2008 Andreas Lagerkvist (andreaslagerkvist.com)
*/
jQuery.fn.center=function(absolute){return this.each(function(){var t=jQuery(this);t.css({position:absolute?'absolute':'fixed',left:'50%',top:'50%'}).css({marginLeft:'-'+(t.outerWidth()/2)+'px',marginTop:'-'+(t.outerHeight()/2)+'px'});if(absolute){t.css({marginTop:parseInt(t.css('marginTop'),10)+jQuery(window).scrollTop(),marginLeft:parseInt(t.css('marginLeft'),10)+jQuery(window).scrollLeft()});}})};

//
// "pngFix" v1.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)
//
(function(a){$.fn.pngFix=function(d){d=$.extend({blankgif:"blank.gif"},d);var c=(navigator.appName=="Microsoft Internet Explorer"&&parseInt(navigator.appVersion)==4&&navigator.appVersion.indexOf("MSIE 5.5")!=-1);var b=(navigator.appName=="Microsoft Internet Explorer"&&parseInt(navigator.appVersion)==4&&navigator.appVersion.indexOf("MSIE 6.0")!=-1);if($.browser.msie&&(c||b)){$(this).find("img[src$=.png]").each(function(){$(this).attr("width",$(this).width());$(this).attr("height",$(this).height());var l="";var g="";var f=($(this).attr("id"))?'id="'+$(this).attr("id")+'" ':"";var m=($(this).attr("class"))?'class="'+$(this).attr("class")+'" ':"";var i=($(this).attr("title"))?'title="'+$(this).attr("title")+'" ':"";var j=($(this).attr("alt"))?'alt="'+$(this).attr("alt")+'" ':"";var h=($(this).attr("align"))?"float:"+$(this).attr("align")+";":"";var e=($(this).parent().attr("href"))?"cursor:hand;":"";if(this.style.border){l+="border:"+this.style.border+";";this.style.border=""}if(this.style.padding){l+="padding:"+this.style.padding+";";this.style.padding=""}if(this.style.margin){l+="margin:"+this.style.margin+";";this.style.margin=""}var k=(this.style.cssText);g+="<span "+f+m+i+j;g+='style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+h+e;g+="width:"+$(this).width()+"px;height:"+$(this).height()+"px;";g+="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$(this).attr("src")+"', sizingMethod='scale');";g+=k+'"></span>';if(l!=""){g='<span style="position:relative;display:inline-block;'+l+e+"width:"+$(this).width()+"px;height:"+$(this).height()+'px;">'+g+"</span>"}$(this).hide();$(this).after(g)});$(this).find("*").each(function(){var f=$(this).css("background-image");if(f.indexOf(".png")!=-1){var e=f.split('url("')[1].split('")')[0];$(this).css("background-image","none");$(this).get(0).runtimeStyle.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+e+"',sizingMethod='scale')"}});$(this).find("input[src$=.png]").each(function(){var e=$(this).attr("src");$(this).get(0).runtimeStyle.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+e+"', sizingMethod='scale');";$(this).attr("src",d.blankgif)})}return $}})($);



/**
* 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);


var NMO = {	version: "2.1.0" };
NMO.console = {
	outputBuffer: [],
	log: function(text) {
		this.outputBuffer.push(text);
		if (this.outputBuffer.length > 4096) {
			// Discard older entries 
			this.outputBuffer.shift();
		}
	},
	print: function(text) {
		if (text) {
			this.outputBuffer.push(text);
		}
		while( this.outputBuffer.length > 0 ) {
			try {
				window.console.log( this.outputBuffer.shift() );
			} catch(ex) { break; }
		}
	},
	toString: function(separator) {
		var sep = separator || "\n";
		return this.outputBuffer.join(sep);
	},
	clear: function() { this.outputBuffer = []; }
};
NMO.queryStringParams = {};
NMO.queryString = jQuery("script[src*=netmediaone.core.js]").get(0).src;
NMO.queryString = NMO.queryString.substring( NMO.queryString.indexOf("?") + 1 );
jQuery.each( NMO.queryString.split("&"), function(index, p){
	try {
		var kv = p.split('=');
		NMO.queryStringParams[kv[0]] = kv[1];
	} catch(ex) {}
});
NMO.rootPath = NMO.queryStringParams['rootPath'] || "/";
NMO.debug = NMO.queryStringParams['debug'] || true;
NMO.mouse = { x: 0, y: 0 };
NMO.select = jQuery;
NMO.Plugins = {
	
	Add: function(plugin) {
		this[plugin.name] = plugin;
		if ( NMO.debug ) { NMO.console.print("Detected Plugin: "+plugin.name ); }
		if ( plugin.attachToEvents !== undefined ) {
			NMO.select.each( plugin.attachToEvents.split(","), function(index, ev) {
				switch (ev) {
					case "WINDOW_LOAD": {
						NMO.select(window).load( function() {
							try {
								if ( NMO.debug ) { NMO.console.print(plugin.name+" applied to selector: 'body'" ); }
								plugin.init( NMO.select('body') );
								jQuery.event.trigger("PLUGIN_"+plugin.name+"_INIT");
							} catch (ex) {
								if ( NMO.debug ) { NMO.console.print("Unable to initialize Plugin: "+plugin.name+" ("+ex+")" ); }
							}
						});
						break;
					}
					case "PAGE_LOAD": {
						NMO.select(document).ready( function() {
							try {
								if ( NMO.debug ) { NMO.console.print(plugin.name+" applied to selector: 'body'" ); }
								plugin.init( NMO.select('body') );
								jQuery.event.trigger("PLUGIN_"+plugin.name+"_INIT");
							} catch (ex) {
								if ( NMO.debug ) { NMO.console.print("Unable to initialize Plugin: "+plugin.name+" ("+ex+")" ); }
							}
						});
						break;
					}
					default: {
						NMO.select(document).bind(ev, function(e, scope) {
							try {
								if ( NMO.debug ) { NMO.console.print(plugin.name+" applied to selector: '"+(scope.selector||scope)+"'" ); }
								plugin.init( NMO.select(scope) );
								jQuery.event.trigger("PLUGIN_"+plugin.name+"_INIT");
							} catch (ex) {
								if ( NMO.debug ) { NMO.console.print("Unable to initialize Plugin: "+plugin.name+" ("+ex+")" ); }
							}
						});
						break;
					}
				}
			});
		}
	}
	
};
	
//	NMO.require()
//	Injects a resource reference (such as a script or stylesheet) into the document
NMO.require = function( fileName, fileType ) {
	
	try {

		if ( fileType == undefined ) {
			if ( fileName.indexOf(".css") != -1 ) { fileType = "CSS"; }
			else if ( fileName.indexOf(".js") != -1 ) { fileType = "JS"; }
			else {
				throw("Invalid file type specified.");
			}
		}

		var isRemote = ( fileName.indexOf("http") == 0 );

		switch ( fileType ) {

			case "CSS": {
				
				if ( $("link[href*="+fileName+"]").length > 0 ) {
					return;
				} else {
					$("head").append('<link rel="stylesheet" type="text/css" href="'+((isRemote)?'':NMO.rootPath)+fileName+'">');
				}
				break;
				
			} 
			
			case "JS": {
	
				if ( $("script[src*="+fileName+"]").length > 0 ) {
					return;
				} else {
					$("head").append('<script type="text/javascript" src="'+((isRemote)?'':NMO.rootPath)+fileName+'"></script>');
				}
				break;
				
			} 
			
			default: {
				throw("Reached the unreachable code.");
				break;
			}
			
		}
		
	} catch(ex) {

		NMO.console.print("Error in NMO.require(): "+ex.message );
		
	}

};


NMO.findNearest = function(selector, seekFrom) {
	var target = NMO.select(seekFrom).nextAll(selector+":first");
	var seekparent = NMO.select(seekFrom).parent();
	if ( target.length == 0 && seekparent.length > 0 ) {
		target = NMO.findNearest( selector, seekparent.get(0) );
	}
	return target;
};


NMO.Plugins.Add({

	name: "ToggleNearestCollapsible",
	attachToEvents: "PAGE_LOAD",
	init: function(scope) {
		NMO.select(".toggle-nearest-collapsible", scope).live("click", function() {
			var self = NMO.select(this);
			self.parent().toggleClass("expanded");
			var col = NMO.findNearest(".collapsible", this);
			col.toggle("normal").toggleClass("collapsed");
			if ( col.hasClass("collapsed") ) {
				col.prev("dt").addClass("expanded");
			} else {
				col.prev("dt").removeClass("expanded");
			}
			if ( self.hasClass("remove-on-reveal") ) {
				self.remove();
			}
		});
	}

});


// Finds all immediate children of target elements and set an equal height
NMO.Plugins.Add({
	
	name: "EqualizeHeight",
	attachToEvents: "WINDOW_LOAD,DOM_UPDATED",
	init: function(scope) {
		NMO.select(".equal-height", scope).each( function() {
			var currentTallest = 0;
			NMO.select(this).children().each(function(i){
				if (NMO.select(this).height() > currentTallest) { currentTallest = NMO.select(this).height(); }
			});
			currentTallest += "px";
			// for ie6, set height since min-height isn't supported
			if (jQuery.browser.msie && jQuery.browser.version == 6.0) { NMO.select(this).children().css({'height': currentTallest}); }
			NMO.select(this).children().css({'min-height': currentTallest}); 
		});

	}

});


NMO.Plugins.Add({

	name: "FirstLast",
	attachToEvents: "PAGE_LOAD,DOM_UPDATED",
	init: function(scope) {
		NMO.select("*:first-child", scope ).addClass("first-child");
		NMO.select("img:first-child ~ *:header", scope ).addClass("offset-first-child");
		NMO.select("*:last-child", scope ).addClass("last-child");
	}

});


NMO.Plugins.Add({

	name: "ZebraStripes",
	attachToEvents: "PAGE_LOAD,DOM_UPDATED",
	init: function(scope) {
		NMO.select( "table.striped", scope ).each( function() {
			// Yeah, it's backwards. For whatever reason jQuery resolves the :odd selector to 
			// even-numbered items and vice-versa.
			NMO.select(this).find(" tbody > tr:odd" ).addClass("even").removeClass("odd");
			NMO.select(this).find(" tbody > tr:even" ).addClass("odd").removeClass("even");
		});
		NMO.select( "ul.striped > li:even", scope ).addClass("even").removeClass("odd");
		NMO.select( "ul.striped > li:odd", scope ).addClass("odd").removeClass("even");
	}
	
});


NMO.Plugins.Add({

	name: "ShowAlerts",
	attachToEvents: "PAGE_LOAD,DOM_UPDATED",
	showAlerts: function(scope) {
		NMO.select(".status-message:hidden", scope).each( function() { 
			var e = NMO.select(this);
			e.slideDown(500);
			e.find(".close").click(function() { 
				e.slideUp(500, function() { 
					e.remove();
				});
			});
			if ( !$.browser.msie || $.browser.version >= 7 ) {
				e.find("a").hover( function() { NMO.select(this).toggleClass('opacity-50'); }, function() { NMO.select(this).toggleClass('opacity-50'); } );
			}
			if ( !e.hasClass("sticky") ) {
				setTimeout( function() { 
					e.slideUp(500, function() { 
						e.remove();
					});	
				}, 5000 );
			}
		});
	},
	init: function(scope) {
		
		var self = this;
		
		NMO.select(document).bind( "ALERTER_UPDATED", function(e, scope) {
			self.showAlerts(scope);
		});
	
		self.showAlerts(scope);
		
	}
	
});


NMO.Plugins.Add({
	
	name: "Rotator",
	attachToEvents: "PAGE_LOAD,DOM_UPDATED",
	init: function(scope) {
	
		$(".rotator", scope).each( function() {
			
			var container = $(this);
			var items = container.find( container.attr("itemselector") || "> li" );
			var currentItem = 0;
			var delay = Number( container.attr("rotationdelay") || 5000 );
			var transitionSpeed = Math.floor( Number( container.attr("transitionspeed") || 1000 ) / 2 );
			var order = container.attr("rotationorder") || "sequential";
			var transitionType = container.attr("transitiontype") || "fadeout-fadein";
			container.startTimer = function() {
				if( NMO.debug ) { NMO.console.print("Rotator.startTimer()"); }
				setTimeout( function() { container.rotate(); }, $(items[currentItem]).attr("rotationdelay") || delay );
			};
			container.pickItem = function(oldItem) {
				if ( order == "random" ) {
					var counter = 0;
					while ( ((oldItem != null) ? (currentItem == oldItem) : (counter == 0)) && counter < 1000 ) {
						currentItem = Math.floor( Math.random() * items.length );
						counter++;
					}
				} else {
					currentItem = ( currentItem < items.length - 1 ) ? currentItem+1 : 0;
				}
			};
			container.rotate = function() {
				if( NMO.debug ) { NMO.console.print("Rotator.rotate()"); }
				var oldItem = currentItem;
				container.pickItem(oldItem);
				switch ( transitionType ) {					
					case "fadeout-fadein": {
						if( NMO.debug ) { NMO.console.print("Rotator.rotate() => transitionType = fadeout-fadein"); }
						$(items[oldItem]).removeClass("active").fadeOut(transitionSpeed, function() {
							$(items[currentItem]).addClass("active").fadeIn(transitionSpeed, function() {
								container.startTimer();
							});
						});
						break;
					}
					case "crossfade": {
						if( NMO.debug ) { NMO.console.print("Rotator.rotate() => transitionType = crossfade"); }
						$(items[oldItem]).removeClass("active").fadeOut(transitionSpeed);
						$(items[currentItem]).addClass("active").fadeIn(transitionSpeed, function() {
							container.startTimer();
						});
						break;
					}
					case "instant": {
						if( NMO.debug ) { NMO.console.print("Rotator.rotate() => transitionType = instant"); }
						$(items[oldItem]).removeClass("active").hide();
						$(items[currentItem]).addClass("active").show();
						container.startTimer();
						break;
					}
					default: break;
				}
			};
			if ( items.length > 1 ) {
				container.pickItem(null);
				items.hide().eq(currentItem).show();
				container.startTimer();
			}
			
		});
	}

});


/************************************************************\
*
*		HTML 5 Compatability for IE
*
\************************************************************/
(function(){
	var e = ("abbr,article,aside,audio,canvas,datalist,details,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video").split(',');
	for (var i = 0; i < e.length; i++) { document.createElement(e[i]); }
})();



/************************************************************\
*
*		Page Load Event - Main Script Init
*
\************************************************************/
NMO.select( function() {
						
	NMO.select("html").addClass("js-enabled");
	
	NMO.select(document).mousemove( function(e) {
		NMO.mouse.x = e.pageX || e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		NMO.mouse.y = e.pageY || e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	});
	
	NMO.select(window).resize( function() {
		NMO.select(document).trigger("VIEWPORT_CHANGED", [document]);
	});
	
	$(document).scroll( function() {
		$(document).trigger("VIEWPORT_CHANGED", [document]);
	});

	$(document).pngFix( { blankgif: NMO.rootPath+"scripts/blank.gif" } );
	
	$(document).bind( "VIEWPORT_CHANGED", function() {
		$(".center-in-viewport:visible").center(true);
	} );

	$(".HideIfJS, #sectionNav li:not(.Active) ul").hide();

});

NMO.select(window).load( function() {

	NMO.console.print();
																	
});






// Intercepts and overrides normal hyperlink behavior so that the request is made via Ajax, with 
// the response content optionally loaded into a designated target element.
NMO.Plugins.AjaxifyLinks = function(scope) {
	$("a.ajax, .ajax-links a", scope ).each( function() {
		var aTag = this;
		var $aTag = $(aTag);
		var cacheResponses = ( $aTag.hasClass("cache-ajax-responses") || $aTag.closest(".ajax-links").hasClass("cache-ajax-responses") );
		aTag.href = (aTag.href.indexOf("/action/") != -1) ? aTag.href.replace("/action/","/ajaxaction/") : aTag.href + ( (aTag.href.indexOf("?")==-1) ? "?" : "&" ) + "renderMode=ajax";
		if ( $aTag.attr("rel") != null && $aTag.attr("rel") != "" ) {
			var target = $( $aTag.attr("rel") );
			if ( target.length > 0 ) {
				$aTag.click( function(e) {
					if ( $(target).hasClass("content-loaded") && cacheResponses ) {
						return;
					}
					$(target).addClass("loading").load( aTag.href, null, function() { 
						$(target).removeClass("loading");
						$(target).addClass("content-loaded").trigger("CONTENT_CHANGED");
						NMO.runPlugins( [ 
							"FirstLast", 
							"EqualizeHeight", 
							"AjaxifyLinks", 
							"ZebraStripes" 
						], target );
					} );
					
					return false;
				});
			}
		}
	} );
};


//
//	Simple Form Validation
//	MODIFIED:	2009.01.24
//	AUTHOR(S): 	Graham Wheeler - NetMediaOne - www.netmediaone.com
//
NMO.Validator={validationPatterns:[{name:"Email",pattern:/^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/,error:"Email address not in valid format"},{name:"EmailWithSubstitutionTags",pattern:/^(([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+)|\[\w+\]$/,error:"Email address not in valid format"},{name:"IPAddress",pattern:/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/,error:"IP address not in valid format"},{name:"PhoneFax",pattern:/^(([0-9]{1})*[- .(]*([0-9a-zA-Z]{3})*[- .)]*[0-9a-zA-Z]{3}[- .]*[0-9a-zA-Z]{4})+$/,error:"Number not in valid format"},{name:"PositiveNumber",pattern:/^[1-9]+([0-9])*$/,error:"Must be a number greater than zero"}],getLabel:function(a){if(a.title!=""){return"'"+a.title+"'"}else{return"'"+a.name+"'"}},isValid:function(d){var g=[];var a=this;this.container=d;this.$c=$(d);this.notificationMethod=(this.$c.attr("notificationmethod")!=undefined)?this.$c.attr("notificationmethod"):"inline";this.notificationPosition=(this.$c.attr("notificationposition")!=undefined)?this.$c.attr("notificationposition"):"after";$(".Required",this.container).each(function(){if($(this).val()==""&&!$(this).hasClass("MatchPattern")){var h=this;g.push({field:h,message:"Must be provided"})}});$("[crosscheck]",this.container).each(function(){if($(this).val()!=$($(this).attr("crosscheck")).val()){var h=this;g.push({field:h,message:"Values do not match"})}});$(".MatchPattern",this.container).each(function(){if(($(this).hasClass("Required")&&this.value=="")||this.value!=""){for(var h=0;h<a.validationPatterns.length;h++){var k=a.validationPatterns[h];if($(this).hasClass(k.name)&&!k.pattern.test(this.value)){var j=this;g.push({field:j,message:k.error})}}}});$("select.CheckForValidSelection",this.container).each(function(){var h=this.options[this.selectedIndex];if($(h).hasClass("InvalidSelection")){var i=this;g.push({field:i,message:"Invalid option"})}});if(g.length>0){if(this.notificationMethod=="alert"){var c="Please correct the following errors:\n\n";for(var b=0;b<g.length;b++){c+=getLabel(g[b].field)+": "+g[b].message+"\n"}alert(c.toString())}else{if(this.notificationMethod=="inline"){$(".ValidationErrorMessage",this.container).remove();$(".FailedValidation",this.container).removeClass("FailedValidation");for(var b=0;b<g.length;b++){var f=$(g[b].field);$(f).addClass("FailedValidation");var e='<span class="ValidationErrorMessage">'+g[b].message+"</span>";if(this.notificationPosition=="before"){f.before(e)}else{if(this.notificationPosition=="after"){f.after(e)}}}}}return false}else{return true}}};jQuery(function(){$(document).bind("click",function(b){var a=$(b.target).attr("type");if(a=="submit"||a=="image"){if(NMO.Validator.isValid($(b.target).closest("form.Validated"))){return true}else{b.preventDefault();return false}}else{return}})});
