var main_nav = "#main-nav nav,.eyebrow";
var touchbound = false;

// Pixel width where nav toggles desktop/mobile
var break_point = 1024;

// for hamburger flyout nav, which side will it be located
var flyout_side = 'right';

(function($){
	"use strict";
	var MobileMenu = function(name,options) {
		var element = $("#"+name);
		if (!element.length) {
			element = $('<nav></nav>');
			element.attr('id',name);
			$('body').append(element);
		}
		// get the DOM object if provided a jQuery object
		if (element[0] !== undefined) {
			element = element[0];
		}
		if (element.MobileNav === undefined) {
			$.extend(this, {
				root: element,
				options: {
					container: 'body',
					structure: {},
					controls: [],
					bodyClass: 'mobile-nav-open',
					ulClass: null,
					liClass: null,
					linkClass: null,
					addCloseBtn: false,
					nextLevelClass: 'level-switch level-down',
					prevLevelClass: 'level-switch level-up'
				},
				closeBtn: {},
				initialized: false,
				init: function(){
					var me = this;
					if (!this.initialized) {
						$("body").removeClass(me.options.bodyClass);
						$(me.options.controls).unbind('click').bind('click',function(){
							me.toggle();
						});
						me.initialized = true;
						me._load();
						me.hide();
						if (me.options.addCloseBtn) {
							me.closeBtn = $('<a href="javascript:;" class="nav-close"></a>');
							$(me.root).prepend(me.closeBtn);
							me.closeBtn.click(function(){
								me.hide();
							});
						}
						$(me.options.container).append($(me.root));
					}
					return me;
				},
				_load: function() {
					var me = this;
					var ul = $('<ul class="level-1"></ul>');
					$(me.root).append(ul);
					if (me.options.ulClass) {
						ul.addClass(me.options.ulClass);
					}
					$.each(me.options.structure, function(){
						var li = $('<li class="level-'+this.level+'"></li>');
						ul.append(li);
						if (me.options.liClass) {
							li.addClass(me.options.liClass);
						}
						var a = $('<a href="'+this.link+'" class="level-'+this.level+'"><span class="title">'+this.title+'</span></a>');
						li.append(a);
						if (me.options.linkClass) {
							a.addClass(me.options.linkClass);
						}
						if (this.children.length) {
							var trigger = $('<span class="level-'+this.level+'"><i class="fa fa-chevron-right"></i></span>');
							li.append(trigger);
							if (me.options.nextLevelClass) {
								trigger.addClass(me.options.nextLevelClass);
							}
							var dropdown = me._buildDropdown(this, this.children);
							li.append(dropdown);
							trigger[0]._dropdown = dropdown[0];
							trigger.click(function(e){
								e.preventDefault();
								$(this._dropdown).addClass('show');
							});
						}
					});
				},
				_buildDropdown: function(parent, children) {
					if (!children.length) {
						return null;
					}
					var me = this;
					var ul = $('<ul class="level-'+(parent.level+1)+'"></ul>');
					if (me.options.ulClass) {
						ul.addClass(me.options.ulClass);
					}
					var li = $('<li class="level-'+(parent.level+1)+'"></li>');
					ul.append(li);
					if (me.options.liClass) {
						li.addClass(me.options.liClass);
					}
					var a = $('<a class="level-'+(parent.level+1)+'"><span class="title">'+parent.title+'</span></a>');
					var trigger = $('<span class="level-'+(parent.level+1)+'"><i class="fa fa-chevron-left"></i></span>');
					li.append(trigger);
					li.append(a);
					trigger[0]._dropdown = ul[0];
					a[0]._dropdown = ul[0];
					$(a).click(function(e){
						e.preventDefault();
						$(this._dropdown).removeClass('show');
					});
					$(trigger).click(function(e){
						e.preventDefault();
						$(this._dropdown).removeClass('show');
					});
					if (me.options.linkClass) {
						a.addClass(me.options.linkClass);
					}
					if (me.options.prevLevelClass) {
						trigger.addClass(me.options.prevLevelClass);
					}
					$.each(children, function(){
						li = $('<li class="level-'+this.level+'"></li>');
						ul.append(li);
						if (me.options.liClass) {
							li.addClass(me.options.liClass);
						}
						a = $('<a href="'+this.link+'" class="level-'+this.level+'"><span class="title">'+this.title+'</span></a>');
						li.append(a);
						if (me.options.linkClass) {
							a.addClass(me.options.linkClass);
						}
						if (this.children.length) {
							trigger = $('<span class="level-'+this.level+'"><i class="fa fa-chevron-right"></i></span>');

							li.append(trigger);
							if (me.options.nextLevelClass) {
								trigger.addClass(me.options.nextLevelClass);
							}
							var dropdown = me._buildDropdown(this,this.children);
							li.append(dropdown);
							trigger[0]._dropdown = dropdown[0];
							trigger.click(function(e){
								e.preventDefault();
								$(this._dropdown).addClass('show');
							});
						}
					});
					return ul;
				},
				show: function() {
					$(this.root).removeClass('closed').addClass('open');
					$(this.options.controls).removeClass('closed').addClass('open');
					$("body").addClass(this.options.bodyClass);
					return this;
				},
				hide: function() {
					$(this.root).removeClass('open').addClass('closed');
					$(this.options.controls).removeClass('open').addClass('closed');
					$("body").removeClass(this.options.bodyClass);
					return this;
				},
				toggle: function (){
					if ($(this.root).hasClass('open')) {
						this.hide();
					} else {
						this.show();
					}
					return this;
				}
			});
			$.extend(this.options, options);
			element.MobileNav = this;
			this.init();
		}
		return element.MobileNav;
	};
	$(document).ready(function(){
		if (window._mobileMenuLinks !== undefined) {
			window._MobileMenu = new MobileMenu('mobile-nav',{
				container: 'body',
				structure: window._mobileMenuLinks,
				controls: $(".nav-toggle"),
				addCloseBtn: true
			});
		}
	});
}(jQuery));

(function($){
	"use strict";	
	var touched=false;
	window._setupDesktopNav = function(){	
		$(window.main_nav).each(function(){
			$(this).find('li').each(function() {
				var li=$(this);
				var dropdown = li.children('.dropdown').first();
				var showDelay = dropdown.data('show-delay') ? dropdown.data('show-delay') : 0;
				var hideDelay = dropdown.data('hide-delay') ? dropdown.data('hide-delay') : 0;
				// First we clear off mobile click if present
				li.find('> a').unbind('click touchstart')
					.bind('touchstart',function(){
						touched=true;
						return;
					}).bind('click',function(e){
						if((touched)&&($(this).parents('li').first().find('.dropdown').length)){
							e.preventDefault();
						}
						touched=false;
						return;
					});
				li.mouseover(function() {
					if (!li[0]._isHovered) {
						li[0]._isHovered = true;
						setTimeout(function(){
							if (li[0]._isHovered) {
								window._showDesktopNavDropdown(li);
							}
						},showDelay);
					}
				}).mouseout(function() {
					if (li[0]._isHovered) {
						li[0]._isHovered = false;
						setTimeout(function(){
							if (!li[0]._isHovered) {
								window._hideDesktopNavDropdown(li);
							}
						},hideDelay);
					}
				});
			});
		});		
	};
	
	window._showDesktopNavDropdown = function(navItem){
		navItem.children('.dropdown').fadeIn(200);
	};
	
	window._hideDesktopNavDropdown = function(navItem){
		setTimeout(function(){
			if($(navItem).find(":hover").length) { return; }
			navItem.children('.dropdown').fadeOut(100);
		},100);
	};
	
	window._isTouch = function() {
		if (!touchbound)
		{
			$(main_nav).each(function(){
				$(this).find('li').each(function(){
					var li=$(this);
					li.unbind("hover");
					li.unbind("mouseover");
					li.unbind("mouseout");
					
					if ($(this).find("ul").length > 0)
					{
						$(this).unbind('mouseout');
						$(this).unbind('mouseover');
											
						$(this).find("a").first().bind('click', function(e){
							if (!$(":root").hasClass('mobile'))
							{ 
								e.preventDefault(); 
								
								if (li.attr("rel") === "open")
								{
									// clicking to close
									li.attr("rel", "closed");
									window._hideDesktopNavDropdown(li);
								}
								else
								{
									// are we clicking another top nav, or a sub nav
									if ($(this).parents('li[rel=open]').length > 0)
									{
										if (li.children('.dropdown').length === 0)
										{
											$('nav li').each(function(){
												window._hideDesktopNavDropdown($(this));
											});
											$("li[rel=open]").attr("rel", "closed");
										}							
										li.attr("rel", "open");
										window._showDesktopNavDropdown(li);	
									}
									else
									{						
										$('nav .dropdown').hide();
										$("li[rel=open]").attr("rel", "closed");
										li.attr("rel", "open");
										window._showDesktopNavDropdown(li);
									}
								}
								return false;
							}
						});
						$("body").bind('click',function(e){
							if(!$(e.target).parents().filter(li).length){
								window._hideDesktopNavDropdown(li);
							}
						});
					}
				});
			});
			
			touchbound = true;
			window._responsiveNav();
		}
	};
	
	/*
	 * Toggles nav styles
	 * {nav} variable created in dropdowns.js
	 */
	window._responsiveNav = function(force){return;
		/*
		 * DESKTOP NAV
		 */
		if($(w).width() > break_point){
			$(":root").removeClass('mobile');
			w.onBeforeSwitchToDesktop().done(function(){
				$(w.main_nav).each(function(){		
					if($(this).hasClass('mobile')){
						$(this).removeClass('mobile').addClass('desktop').removeAttr('style');
						
						/* Cleanup!
						 * 1. Remove our nav toggle link
						 * 2. Remove our cloned parent links in dropdowns
						 * 3. Run setupNav() from dropdowns.js to assign hover events
						 * 4. Hide open dropdowns
						 * 5. Run spaceNav() to space out nav items
						 */
						$(this).find('li').css('display','');
						$('nav.desktop a.open').removeClass('open');
						$('nav .dropdown').hide();
						w.setupDesktopNav();
					}
				});
			});
		/*
		 * MOBILE NAV
		 */	
		} else {
			w.onBeforeSwitchToMobile().done(function(){
				$(":root").addClass('mobile');
				$(w.main_nav).each(function(i,nav){
					if ($(nav).hasClass('desktop')||force===true){
						$(nav).removeClass('desktop').addClass('mobile').css(flyout_side,'-200%');
						$(nav).find('li').each(function(){
							$(this).unbind('mouseenter')
								.unbind('mouseleave')
								.unbind('mouseout')
								.unbind('mouseover')
								.unbind('hover');
							var a_tag = $(this).find('> a');
							// clear off desktop touch event
							a_tag.unbind('click')
								.unbind('mouseout')
								.unbind('mouseover')
								.unbind('mouseenter')
								.unbind('mouseleave')
								.unbind('hover');
							/* If a nav item has a dropdown menu we have to make it mobile friendly
							 * 1. Add a clone of the parent to the beginning of the dropdown items
							 * 2. Override parent's default action to instead open the dropdown menu
							 */
							if($(this).find('>.dropdown').length){
								a_tag.addClass('hc');
								// add the duplicate nav item as a child, but only if not heading page
								a_tag.unbind('click mouseout mouseover').click(function(e) {
									e.preventDefault();
									// reset all other nav items
									$('a').not(this).not($(this).parents('.dropdown').siblings('a')).not(".nav_toggle").each(function(){
										$(this).removeClass('open').siblings('.dropdown').slideUp();
									});
									// toggle this nav item
									$(this).toggleClass('open').siblings('.dropdown').slideToggle();
								});
							}	
						});
						w.setupMobileNav();
					}
				});
			});
		}
	};
	
	window._pageLoaded = function(){
		$(window).bind('touchstart', function(){ window._isTouch(); });
		if (navigator.msMaxTouchPoints) { $(window).bind('MSPointerDown', function(){ window._isTouch(); }); }
		window._setupDesktopNav();
//		window.addResponsiveAdjustment(window._responsiveNav);
	};
	
	$(document).ready(function(){
		window._pageLoaded();
	});

}(jQuery));