/*=============================================================================

			 	 TITLE:	NetMediaOne - Core Library
		  MODIFIED:	2010.08.17
				AUTHOR: Graham Wheeler - NetMediaOne - www.netmediaone.com
		  REQUIRES:	jQuery 1.4.2

=============================================================================*/

/**
* 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(jQuery){jQuery.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=jQuery.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){jQuery(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;jQuery(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{jQuery(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 = {
	
	Config: [],
	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 ( jQuery("link[href*="+fileName+"]").length > 0 ) {
					return;
				} else {
					jQuery("head").append('<link rel="stylesheet" type="text/css" href="'+((isRemote)?'':NMO.rootPath)+fileName+'">');
				}
				break;
				
			} 
			
			case "JS": {
	
				if ( jQuery("script[src*="+fileName+"]").length > 0 ) {
					return;
				} else {
					jQuery("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: "DropDownMenu",
	attachToEvents: "PAGE_LOAD",
	init: function(scope) {
		NMO.select(".drop-down-menu", scope).each( function() {
			var menu = NMO.select(this);
			var opts = eval( menu.attr("data-options") );
			var menuSpeed = opts.speed || 150;
			menu.find("ul").each( function() {
				var submenu = NMO.select(this);
				var submenuParent = submenu.closest("li");
				if ( opts.backgroundOpacity ) {
					var menuBG = NMO.select('<div class="menu-background opacity-'+opts.backgroundOpacity+'"></div>');
					menuBG.width(submenu.width()).height(submenu.height());
					submenuParent.append(menuBG);
				}
				submenu.find("> li").hoverIntent(
					function() { NMO.select(this).addClass("hovered"); },
					function() { NMO.select(this).removeClass("hovered"); }
				).hover(
					function() { NMO.select(this).addClass("hover"); },
					function() { NMO.select(this).removeClass("hover"); }
				);
				submenuParent.hoverIntent(
					function() {
						var li = submenuParent;
						var smw = submenu.width();
						var vw = NMO.select(window).width();
						if ( !li.parent().hasClass("drop-down-menu") ) {
							var hasRoomOnRight = (( li.width() + smw + li.offset().left ) < vw );
							var menuOffset = {
								left: (hasRoomOnRight) ? (li.width() + li.position().left) : li.position().left - submenu.width(),
								top: li.position().top
							};
							submenu.css({"left": menuOffset.left, "top": menuOffset.top});
							if ( opts.backgroundOpacity ) {
								menuBG.width(submenu.width()).height(submenu.height());
								menuBG.css({"left": menuOffset.left, "top": menuOffset.top});
							}
						}
						submenuParent.addClass("hovered");
						submenu.slideDown(menuSpeed);
						if ( opts.backgroundOpacity ) {
							menuBG.slideDown(menuSpeed);
						}
					},
					function() {
						submenuParent.removeClass("hovered");
						submenu.slideUp(menuSpeed);
						if ( opts.backgroundOpacity ) {
							menuBG.slideUp(menuSpeed);
						}
					}
				);

			});

		});
	}

});


NMO.Plugins.Add({
	
	name: "Rotator",
	attachToEvents: "PAGE_LOAD,DOM_UPDATED",
	init: function(scope) {
	
		jQuery(".rotator", scope).each( function() {
			
			var container = jQuery(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(); }, jQuery(items[currentItem]).attr("rotationdelay") || delay );
			}
			container.rotate = function() {
				if( NMO.debug ) { NMO.console.print("Rotator.rotate()"); }
				var oldItem = currentItem;
				if ( order == "random" ) {
					var counter = 0;
					while ( currentItem == oldItem && counter < 1000 ) {
						currentItem = Math.floor( Math.random() * items.length );
						counter++;
					}
				} else {
					currentItem = ( currentItem < items.length - 1 ) ? currentItem+1 : 0;
				}
				switch ( transitionType ) {					
					case "fadeout-fadein": {
						if( NMO.debug ) { NMO.console.print("Rotator.rotate() => transitionType = fadeout-fadein"); }
						jQuery(items[oldItem]).removeClass("active").fadeOut(transitionSpeed, function() {
							jQuery(items[currentItem]).addClass("active").fadeIn(transitionSpeed, function() {
								container.startTimer();
							});
						});
						break;
					}
					case "crossfade": {
						if( NMO.debug ) { NMO.console.print("Rotator.rotate() => transitionType = crossfade"); }
						jQuery(items[oldItem]).removeClass("active").fadeOut(transitionSpeed);
						jQuery(items[currentItem]).addClass("active").fadeIn(transitionSpeed, function() {
							container.startTimer();
						});
						break;
					}
					case "instant": {
						if( NMO.debug ) { NMO.console.print("Rotator.rotate() => transitionType = instant"); }
						jQuery(items[oldItem]).removeClass("active").hide();
						jQuery(items[currentItem]).addClass("active").show();
						container.startTimer();
						break;
					}
					default: break;
				}
			};
			if ( items.length > 1 ) {
				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() {
										 
	var foreground = NMO.select("#layer-foreground");
						
	NMO.select("html").addClass("js-enabled").removeClass("js-disabled");
	
	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]);
	});
	
	NMO.select(document).scroll( function() {
		jQuery(document).trigger("VIEWPORT_CHANGED", [document]);
	});
	
	NMO.select(document).trigger("VIEWPORT_CHANGED", [document]);	
	
	//NMO.select(".scrollable").scrollable();

});

NMO.select(window).load( function() {

	NMO.console.print();
																	
});


