var GS = GS || {};

GS.Navigation = (function ($){
    GS.Navigation = function (){
        // Private variables
        var displayNav              = false,
        	showToplevelNavDelay    = 200,
        	showRightNavDelay       = 200,
        	showChildNavDelay       = 40,
        	showNavTimer            = null,
        	navLimit                = -1,
		navSource               = GS.navURL;
    	this.setDisplayNav = function( res ){
    		displayNav = res;
    	}

    	this.getDisplayNav = function() {
    		return displayNav;
    	}

    	this.loadNavigation = function() {
			if(window.GS.Navigation.navSource && window.GS.Navigation.navSource !== 'undefined') {
				navSource = window.GS.Navigation.navSource;
			}

    		$('#main-nav').load(navSource + ' ul#marketing-nav',function(){
    			$('#sub-nav').load(navSource + ' ul#audience-nav',function(){
   				$('#main-nav > ul > li, #sub-nav > ul > li.wideNav').append('<span class="navCloser"></span>');
    				var pathname = window.location.pathname.substring(window.location.pathname.indexOf('/')+1);

    				if(window.GS.Navigation.parentPage && window.GS.Navigation.parentPage !== 'undefined') {
    					pathname = window.GS.Navigation.parentPage;
    				}

    				var currentNav = $('#main-nav > ul > li > a[href$="'+pathname+'"], #sub-nav > ul > li > a[href$="'+pathname+'"]');

    				currentNav.each(
						function() {
							$(this).wrap('<strong></strong>');
						}
					);

					if( $('body.top-level').length > 0 ){
						currentNav.parents('li').first().addClass('suppressNav');
					}

    				var navPath = $('header a[href="'+pathname+'"]').parents('li');
    				navPath.each(function(){
    					$(this).children('a.toplevel').addClass('active').wrap('<strong></strong>')
    				});

    				navLimit = $('#main-nav > ul > li').size();

					GS.Navigation.setSubNavPositions();

					//Primary navigation analytics
					$('#main-nav ul li a').each(function(){
						var nodeIndex = [];
						var nodeTitle = [];
						$(this).parents('li').each(function(){
							nodeIndex.push(($(this).index() + 1));
							nodeTitle.push(GS.Sitewide.analyticsEscape($('a:first', this).text()));
						});
						var datamap = {
							type: 'navigation',
							title: nodeTitle.reverse().join(':'),
							position: nodeIndex.reverse().join(':')
						};
						$(this).data('analytics',datamap).bind('click', function(e){GS.Sitewide.doAnalytics(e,$(this).data('analytics'))});
					});
					
					
					$('#main-nav > ul > li > a').each(function(){
						$(this).data('analytics').type = 'navigation-slide';
					});

					//Secondary navigation analytics
					var mainCount = $('#main-nav > ul > li').length;
					$('#sub-nav ul li a').each(function(){
						var nodeIndex = [];
						var nodeTitle = [];
						$(this).parents('li').each(function(){
							if($(this).hasClass('sidebyside')) {
								if ($(this).index() != 0) {
									$(this).prevAll('li.sidebyside').each(function(){	
										nodeIndex[nodeIndex.length-1] = nodeIndex[nodeIndex.length-1] + $('li', this).length;
									});
								}
							}
							else {
								nodeTitle.push(GS.Sitewide.analyticsEscape($('a:first', this).text()));
								nodeIndex.push(($(this).index() + 1));
							}
						});
						
						nodeIndex = nodeIndex.reverse();
						nodeIndex[0] += mainCount;
						var datamap = {
							type: 'navigation',
							title: nodeTitle.reverse().join(':'),
							position: nodeIndex.join(':')
						};
						$(this).data('analytics',datamap).bind('click', function(e){GS.Sitewide.doAnalytics(e,$(this).data('analytics'))});
					});
					
					// Append location hash
					$('ul#audience-nav > li.wideNav.hasTout').each(function(){
						if ($('a.toplevel', $(this)).text() == 'Worldwide') {
							$(this).find('li.has-children ul li a').each(function() {
								if ($(this).attr('href').indexOf('/locations/') != -1)
									$(this).attr('href', $(this).attr('href') + '#' + $(this).text());
							});
						}
					});

    			});
    		});

    		$('#main-nav > li > a, #sub-nav > ul > li > a, #main-nav > li > span.linkless, #sub-nav > ul > li > span.linkless').live({
    			'mouseenter focusin': function(){
	   				GS.Navigation.setDisplayNav(true);
    			},
    			touchend: function(){
	   				GS.Navigation.setDisplayNav(true);
    			}
    		})

    		$('#main-nav li a, #sub-nav li a, #main-nav li span.linkless, #sub-nav li span.linkless').live({
    			'mouseenter focusin': function( e ){
					$.data(this, 'hover', true);
    				GS.Navigation.setDisplayNav(true);
					var type = ($(this).parents('#sub-nav').size() > 0 && $(this).parents('li').size() == 1) ? 'toplevel-right' : ($(this).parents('#main-nav').size() > 0 && $(this).parents('li').size() == 1) ? 'toplevel' : '' ;
    				GS.Navigation.handleNavState(this,type);
    			},
    			'mouseleave focusout': function(){
					$.data(this, 'hover', false);
    				GS.Navigation.setDisplayNav(true);
    			},
    			click: function( e ) {
    				GS.Navigation.setDisplayNav(false);
    			}
    		});

			//Top-level items in main nav
    		$("#main-nav ul li a.toplevel").live({
				touchstart: function( e ){
					if($(this).parent().hasClass('active')) {
						
					} else {
						e.preventDefault();
						$.data(this, 'hover', true);
	    				GS.Navigation.setDisplayNav(true);
					}
    				GS.Navigation.handleNavState(this,'toplevel');
				},
    			'mouseenter focusin': function( e ) {
					$.data(this, 'hover', true);
    				GS.Navigation.handleNavState(this,'toplevel');
    				$('#main-nav a.toplevel').addClass('expandHitArea');
    			},
    			'mouseleave focusout':	function() {
					$.data(this, 'hover', false);
    				setTimeout(function(){
    					if($('#main-nav li.active a.toplevel').length == 0) {
    						$('#main-nav a.toplevel').removeClass('expandHitArea');
    					}
    				}, showToplevelNavDelay);
    			}
    		});
    		$("#main-nav ul li.active a.toplevel").live({
				touchstart: function( e ){
    				GS.Navigation.setDisplayNav(false);
					return true;
				}
    		});

			//Top-level items in right nav
			$('#sub-nav li a.toplevel').live({
				touchstart: function( e ){
					e.preventDefault();
					$.data(this, 'hover', true);
    				GS.Navigation.setDisplayNav(true);
    				GS.Navigation.handleNavState(this,'toplevel-right');
				},
    			'mouseenter focusin': function( e ){
    				GS.Navigation.handleNavState(this,'toplevel-right');
    			},
				click: function( e ){
    				GS.Navigation.handleNavState(this,'toplevel-right');
				}
    		});
    		$('#sub-nav ul li.active a.toplevel').live({
				touchstart: function( e ){
    				GS.Navigation.setDisplayNav(false);
					$(this).click();
					return true;
				}
    		});

    	}
    	
    	this.handleNavState = function( el, type ) {
			if (showNavTimer) {
				clearTimeout(showNavTimer);
			}
			var target = $(el);
			
			type = type || '';
			var navDelay = (type === 'toplevel-right') ? showRightNavDelay : (type !== 'toplevel') ? showChildNavDelay : showToplevelNavDelay;

			showNavTimer = setTimeout(function(){
				if (!target.data('hover')) {
					return false;
				}

				if (GS.Navigation.getDisplayNav()) {
					$('#main-nav li, #sub-nav li').each(function(){
						$(this).removeClass('active').css({
							'background-color': 'transparent'
						});
					
						target.parents('li').addClass('active');
					
					});
				}
				}, navDelay
			);
		}
		
		this.hideNav = function() {
			$('#main-nav li, #sub-nav li').removeClass('active');
			$('#main-nav a.toplevel').removeClass('expandHitArea');
			// if ($("#main-nav>ul>li>strong").length == 0 && $("#sub-nav>ul>li>strong").length == 0) {
			// 	$('.activeState').find('a').first().wrap('<strong></strong>');
			// }
		}
		
		this.navHide = function() {
			$('#wrapper').live({keydown:function(e){
				var theKey = e.which;
				if(theKey == 9 && $(e.target)[0] == $('#loginNav > ul >li').last().find('li').last().find('a')[0]){
					GS.Navigation.hideNav();
				}
			}});
			$('#main-nav, #sub-nav').live({
				mouseleave: function(){
					GS.Navigation.hideNav();
				},
				keydown: function(e) {
					var theKey = e.which;
					var liIndex = parseInt($(e.target).closest('ul').children('li').index($(e.target).parent('li')));
					var liCount = parseInt($(e.target).closest('ul').children('li').length);
			
					if(theKey == 27 || theKey == 88){
						//esc or x
						GS.Navigation.hideNav();
					}
					if(theKey == 37){
						//left arrow
						if($(e.target).hasClass('toplevel')){
							if($(e.target).parent('li').prev('li').length > 0){
								$(e.target).parent('li').prev('li').find('a').first().focus();
							}
						} else if($(e.target).parent('li').parent('ul').hasClass('narrowRight')){
							$(e.target).parent('li').parent('ul').siblings('ul.narrowLeft').children('li').first().find('a').first().focus();
						} else if($(e.target).parent('li').parent('ul').parent('li').hasClass('sidebyside')){
							$(e.target).parent('li').parent('ul').parent('li').siblings('li.sidebyside').children('ul').children('li').first().find('a').first().focus();
						} else {
							$(e.target).parent().parent().closest('li').find('a').first().focus();
						}
					}
					if(theKey == 38){
						//up arrow
						e.preventDefault();
						if($(e.target).parent('li').parent('ul').children('li').first().find('a').first()[0] == $(e.target)[0]){
							if($(e.target).parent('li').parent('ul').parent('li').hasClass('sidebyside')){
								if($('#loginNav ul li.sidebyside')[0] == $(e.target).parent('li').parent('ul').parent('li')[0]){
									$('#loginNav').find('a').first().focus();					
								} else {
									$(e.target).parent('li').parent('ul').parent('li').prev('li').children('ul').children('li').find('a').last().focus();
								}
							} else if($(e.target).parent('li').parent('ul').hasClass('narrowRight')){
								$(e.target).parent('li').parent('ul').prev('ul').children('li').last().find('a').first().focus();
							} else if($(e.target).parent('li').parent('ul').siblings('p')[0] == $(e.target).parent('li').parent('ul').prev()[0]) {
									$(e.target).parent('li').parent('ul').siblings('p').find('a').first().focus();
							} else {
								$(e.target).parent('li').parent('ul').siblings('a').first().focus();
							}		
						} else if($(e.target).parent('p').parent('section').siblings('a').hasClass('toplevel')){
							$(e.target).parent('p').parent('section').siblings('a').focus();				
						} else if(!$(e.target).hasClass('toplevel')){
							$(e.target).parent().prev().find('a').first().focus();
						} 
					}
					if(theKey == 39){
						//right arrow 
						if($(e.target).parent('li').hasClass('has-children')){
							$(e.target).siblings('ul').first().children('li').first().find('a').first().focus();
						} else if($(e.target).hasClass('toplevel')){
							if($(e.target).parent('li').next('li').length > 0){
								$(e.target).parent('li').next('li').find('a').first().focus();
							} else {
								$(e.target).parent('li').parent('ul').parent().next().find('input').first().focus();
								GS.Navigation.hideNav();
							}
						} else if($(e.target).parent('li').parent('ul').hasClass('narrowLeft')){
							$(e.target).parent('li').parent('ul').siblings('ul.narrowRight').children('li').first().find('a').first().focus();	
						} else if($(e.target).parent('li').parent('ul').parent('li').hasClass('sidebyside')){
							$(e.target).parent('li').parent('ul').parent('li').siblings('li.sidebyside').children('ul').children('li').first().find('a').first().focus();	
						} else {
							window.location = e.target;
						}
					}
					if(theKey == 40){
						//down arrow
						e.preventDefault();
						if(liIndex >= (liCount - 1)) {
							liIndex = -1;
						}
						if($(e.target).hasClass('toplevel')){
							if($(e.target).siblings('section')[0] == $(e.target).next()[0]){
								$(e.target).next().children('p').find('a').first().focus();
							} else {
								$(e.target).siblings('ul').first().children('li').first().find('a').first().focus();
							}
						} else if($(e.target).parent('li').parent('ul').parent('li').hasClass('sidebyside') && $(e.target).parent('li').parent('ul').children('li').last().find('a').first()[0] == $(e.target)[0]){
							if($('#loginNav ul li.sidebyside')[0] == $(e.target).parent('li').parent('ul').parent('li')[0]){
								$(e.target).parent('li').parent('ul').parent('li').next('li').children('ul').children('li').find('a').first().focus();
							}
						} else if($(e.target).parent('li').parent('ul').hasClass('narrowLeft') && $(e.target).parent('li').parent('ul').children('li').find('a').last()[0] == $(e.target)[0] ){
							$(e.target).parent('li').parent('ul').next('ul').children('li').first().find('a').first().focus();
						} else {
							$(e.target).parent().next().find('a').first().focus();
						}
					}
				}
			});
			$('span.navCloser').live({
				click: function(){
					GS.Navigation.hideNav();
				}
			});
			$("#main-nav > ul > li").live({
				mouseenter: function() {
					$("#main-nav>ul>li").each(function(){
						// if($(this).find('strong').eq(0).length == 1) {
						// 	$(this).addClass('activeState').find('strong a').first().unwrap();
						// }
						$(this).find('div.pullquote').first().css('z-index','511');
					});
				},
				mouseleave:	function() {
					// if ($("#main-nav>ul>li>strong").length == 0 && $("#sub-nav>ul>li>strong").length == 0) {
					// 	$('.activeState').find('a').first().wrap('<strong></strong>');
					// }
					$('.suppressNav').removeClass('suppressNav');
				}
			});

			$("#main-nav > ul > li > ul > li > a, #main-nav > ul > li > ul > li > strong > a").live({
				'mouseenter mouseover focusin': function(){
					$(this).closest('ul').siblings('div.pullquote').css('z-index','510');
				},
				'mouseleave mouseout focusout': function(){
					var el = this;
					setTimeout(function(){
						if($(el).closest('ul').find('li.active').length < 1 && $(el).parent().siblings().find('ul:visible').length < 1){
							$(el).closest('ul').siblings('div.pullquote').css('z-index','511');
						}
					}, 500);
				}
			});

			$("#sub-nav > ul > li").live({
				mouseenter: function() {
					$("#sub-nav>ul>li").each(function(){
						// if($(this).find('strong').eq(0).length == 1) {
						// 	$(this).addClass('activeState').find('strong a').first().unwrap();
						// }
					});
				},
				mouseleave:	function() {
					// if ($("#main-nav>ul>li>strong").length == 0 && $("#sub-nav>ul>li>strong").length == 0) {
					// 	$('.activeState').find('a').first().wrap('<strong></strong>');
					// }
					$('.suppressNav').removeClass('suppressNav');
				}
			});

		}
		
		this.setSubNavPositions = function() {
			$('#sub-nav > ul > li').each(function(){
				if( !$(this).hasClass('wideNav') ) {
					var nodeWidth = $(this).outerWidth();
					$(this).find('ul').each(function(){
						$(this).css('left', ( ( ( $(this).innerWidth()  - nodeWidth ) / 2 ) * -1 ) );
					});
				}
			});
		}
    }
    
    return new GS.Navigation();
})(jQuery);

GS.Page.register('*', GS.Navigation.navHide);
GS.Page.register('*', GS.Navigation.loadNavigation);
