// include


/**
* App.views.ui.Navigation
*
* Handles the animation and/or clicks for the top navigation
*
* @version 1.0
* @author Georg Fischer <g.fischer@bigspaceship.com>
* @project Star Wars
*/

App.modules.Navigation =   function( $htmlElement )
{
	// private vars
	var _self   	=	this;
	var _target 	=	null;
	var _domList	=	null;
	
	var _timer  	=	null;
	var _timer_bg  	=	null;
	var _currentIn;
	var _currentOut;
	
	var _htmlElement    =   $htmlElement;
    var _htmlRef        =   $( $htmlElement );
	
	var _show_bg = false;
	
	var _mouseoverchecker = false;
	
	var last_position = { x: 0, y: 0, time: new Date().getTime() };
	var screen = { width: $( window ).width(), height: $( window ).height() };
	var left_page = false;
	var animateTime = 200;
	
	if (App.isIE7or8){
		animateTime = 0;
	}
	
	// public vars
	this.name		=	'App.modules.Navigation';

	
// ===========================================
// ===== CALLABLE
// ===========================================

	this.bind		=	function bind()
	{
		if( ! Modernizr.touch )
		{			
			_domList
				.children( 'li' )
				.hover( _list_MOUSEENTER_handler, _list_MOUSEEXIT_handler );
			
			// set outer state
			_domList
				.children( 'li' )
				.addClass( 'out' );
				
			_main.hover( _main_MOUSEENTER_handler, _main_MOUSEEXIT_handler );
			
			if( ! $.browser.msie )
			{
				// WINDOW MOUSE OUT
				window.addEventListener(
					"mouseout",
					function( $event )
					{
						mouseX = $event.pageX;
						mouseY = $event.pageY;
				
						if(
							( $event.pageX >= 0 && $event.pageY <= window.innerHeight ) &&
							( $event.pageX >= 0 && $event.pageX <= window.innerWidth )
						)
				        
				        return;
						_show_bg = false;
						_bgHide( true );
						
						_closeSubMenu( $( '.mod.navigation ul.main .over' ) )
					},
					false
				);
			};
		
			if( $.browser.msie )
			{
				$( document ).mousemove( _mouseOutChecker );
			}
			
			else
			{
				$( window ).mousemove( _mouseOutChecker );
			}
			
			$( window ).resize( resized );
			
			resized();
		}
		
		else
		{			
			_htmlRef
				.find( '.title a' )
				.each( 
					function()
					{
						if( $( this ).closest('li').find( '.sub' ).length )
						{							
							$( this )
								.click( function( $event )
								{ 
									if( $( this ).closest( 'li' ).hasClass( 'over' ) )
									{
																			
									}
									
									else
									{
										$event.preventDefault();
									}
									
									
								}
							);
						}
					}
				);
			
			_domList
				.children( 'li' )
				.click( _list_MOUSECLICK_handler );

			
			// set outer state
			_domList
				.children( '.main > li' )
				.addClass( 'out' );
							
			document
				.addEventListener(
					'touchstart',
					function( $event )
					{
    					var touch_y = $( window ).height();
    					
    					if( $event.touches.length )
    					{
    						for( var i = 0; i < $event.touches.length; i++ )
    						{
    							if( $event.touches[i].pageY < touch_y )
    							{
    								touch_y = $event.touches[i].pageY;
    							}
    						}
    						
    						if(
    							touch_y > 250 &&
    							$( '.mod.navigation ul.main .over' ).length
    						)
    						{
    							_show_bg = false;
								_bgHide( true );
								_closeSubMenu( $( '.mod.navigation ul.main .over' ) );
    						}
    					}
					},
					false
				);
		}
	}


// ===========================================
// ===== WORKERS
// ===========================================

	function _list_MOUSEENTER_handler( $e )
	{
		_currentIn = $( this );
		_timer = setTimeout( _openSubMenu, 90 );
		
		// _openSubMenu();
		
		if(
			_currentIn.children( '.sub' ).length ||
			_currentIn.parents( '.sub' ).length
		)
		{
			_show_bg = true;
			_bgCheck();
		}
		
		else
		{
			_show_bg = false;
			_bgHide( true );
		}
	};
	
	function _list_MOUSEEXIT_handler( $e )
	{		
		clearTimeout( _timer );
		_closeSubMenu( $( this ) );

	};
	
	function _list_MOUSECLICK_handler( $event )
	{
		
		if( $( $event.target ).closest( 'ul' ).hasClass( 'main' ) )
		{
			if( $( '.mod.navigation ul.main .over' ).length )
			{
				_closeSubMenu( $( '.mod.navigation ul.main .over' ) );
			}
			
			_currentIn = $( this );
			
			_openSubMenu();
			
			if(
				_currentIn.children( '.sub' ).length ||
				_currentIn.parents( '.sub' ).length
			)
			{
				_show_bg = true;
				_bgCheck();
			}
			
			else
			{
				_show_bg = false;
				_bgHide( true );
			}
		}
	};

	function _main_MOUSEENTER_handler( $event )
	{
		
	}
	
	function _main_MOUSEEXIT_handler( $event )
	{
		_show_bg = false;
		_bgCheck( true );
		_bgHide( 100 );
	}
	
	function _openSubMenu()
	{
		_currentIn
			.addClass( 'over' )
			.removeClass( 'out' )
			.children( '.sub' )
			.animate( { opacity: 1, height: 180 }, animateTime )
		
		_currentIn	
			.find( '.sub .handle' )
			.css( { marginLeft: 300, opacity: 0 } )
			.animate( { marginLeft: 0, opacity: 1 }, animateTime );	
	}
	
	function _closeSubMenu( $element )
	{	
		$element
			.children( '.sub' )
			.css( { opacity: 0, height: 180 } )
			.parent()
			.addClass( 'out' )
			.removeClass( 'over' );
		
		$element
			.find( '.sub .handle' )
			.css( { opacity: 0, marginLeft: -300 } )
			.parent()
			.parent()
			.addClass( 'out' )
			.removeClass( 'over' );
		
		if( $element.parents().hasClass( 'over' ) )
		{
			_show_bg = true;
		}
				
		_bgCheck();		
	}
	
	function _bgCheck( $delay )
	{
		clearTimeout( _timer_bg );
		_bgMove( _show_bg, $delay );
		//_timer = setTimeout( function(){ _bgMove( _show_bg ); }, 2 );
	}
	
	function _bgMove( $direction, $delay )
	{
		if( $direction )
		{
			_bgShow( $delay );
		}
	}
	
	function _bgShow( $delay )
	{
		if( ! _subBg.hasClass( 'active' ) )
		{			
			_addMouseOverChecker();
			
			if (App.isIE7or8){
				_subBg.css({
					visibility: 'visible',
					height: 185, opacity: 1
				});
			
			}else{
				_subBg
					.stop()
					.css( { visibility: 'visible' } )
					.animate(
						{ height: 185, opacity: 1 },
						90,
						function()
						{
							$( this ).addClass( 'active' )
						}
					);
			}
		}		
	}
	
	function _bgHide( $dontcheck, $ie )
	{				
		if(
			_subBg.hasClass( 'active' ) ||
			$dontcheck
		)
		{		
			_subBg
				.stop()
				.removeClass( 'active' )
				.animate(
					{ height: 1, opacity: 1 },
					animateTime,
					function()
					{
						$( this ).css( { visibility: 'hidden' } );
					}
				);
				
			
				setTimeout(
					function()
					{
						if( $( '.mod.navigation ul.main .over' ).length )
						{
							_closeSubMenu( $( '.mod.navigation ul.main .over' ) );
						}
					},
					89
				);
			
		}
	}
	
    function _addMouseOverChecker()
    {        	
    	if( ! _mouseoverchecker )
    	{
    		//App.debug(this,  'addChecker' );
    		
    		_mouseoverchecker = true;
    		
    		$(document).bind( 'mousemove', _mousemoveHandler );
    	}
    }
    
    function _removeMouseOverChecker()
    {        	
    	if( _mouseoverchecker )
    	{
    		//App.debug(this,  'removeChecker' );
    		
    		_mouseoverchecker = false;
    		
    		$(document).unbind( 'mousemove', _mousemoveHandler );
    	}
    }
    
    function _mousemoveHandler( $event )
    {
		 	
    	if(	_subBg.hasClass( 'active' ) )
    	{
    		//App.debug(this,  $event.pageX + ' ' + $event.pageY );
    		
    		if(
    			$event.pageY < 240 &&
    			$event.pageX < $( '.starwars-navigation-out' ).offset().left        			
    		)
    		{
    			_show_bg = false;		
				_bgCheck();
				
				_mouseoverchecker = false;
				$(document).unbind( 'mousemove', _mousemoveHandler );
    		}
    		
    		if(
    			$event.pageY < 240 &&
    			$event.pageX > $( '.starwars-navigation-out' ).offset().left + 960        			
    		)
    		{
    			_show_bg = false;		
				_bgCheck();
				
				_mouseoverchecker = false;
				$(document).unbind( 'mousemove', _mousemoveHandler );
    		}
    		
    		if( ! $( 'ul.main > li.over' ).length )
    		{
    			_show_bg = false;		
				_bgCheck();
    		}
    	}
    }
    
    function _mouseOutChecker( $event )
	{		
		if(
			_dist( { x: $event.pageX, y: $event.pageY }, last_position ) > 1 &&
			! ( last_position.x === 0 && last_position.y === 0 ) &&
			! left_page &&
			new Date().getTime() - last_position.time < 200
		)
		{
			var speed = { x: $event.pageX - last_position.x, y: $event.pageY - last_position.y };
			
			if(
				$event.pageX + speed.x <= 0 ||
				$event.pageX + speed.x >= screen.width
			)
			{				
				_show_bg = false;
				_bgHide( true );
					
				_closeSubMenu( $( '.mod.navigation ul.main .over' ) )
			}
			
			if(
				$event.pageY + speed.y <= 0 ||
				$event.pageY + speed.y >= screen.height
			)
			{
				_show_bg = false;
				_bgHide( true );
					
				_closeSubMenu( $( '.mod.navigation ul.main .over' ) )
			}
		}

		else
		{
			if( left_page )
			{
				left_page = false;
			}
		}

		last_position = { x: $event.pageX, y: $event.pageY, time: new Date().getTime() };
	}    
    
    function resized()
	{
		screen = { width: $( window ).width(), height: $( window ).height() };
	}
    
    function _dist( $point_1, $point_2 )
	{
		var xs = 0;
		var ys = 0;
		
		xs = $point_2.x - $point_1.x;
		xs = xs * xs;
		
		ys = $point_2.y - $point_1.y;
		ys = ys * ys;
		
		return Math.sqrt( xs + ys );
	}

// ===========================================
// ===== CONSTRUCTOR
// ===========================================

    function Navigation()
    {    
        _target 	=   $( _htmlElement );
		_domList	=   _target.find( 'ul' );

		_domList
			.find( '.sub .inner' )
			.addClass( 'handle' );
			
		_domList
			.find( '.sub ul' )
			.addClass( 'handle' );
		
		_htmlRef.append( '<div class="sub-bg"></div>' );
		_subBg = _htmlRef.find( '.sub-bg' );
        
        _main = _htmlRef.find( 'ul.main' );
        
        _htmlRef.find( '.utility' ).hover( function(){ _show_bg = false; _bgCheck(); } );
        
        
        if( $( _htmlElement ).attr( 'data-url' ) )
        {
        	_self.widgetBaseUrl = $( _htmlElement ).attr( 'data-url' );
        }
        
        if( $( _htmlElement ).attr( 'data-link' ) )
        {
        	_self.widgetLinkUrl = $( _htmlElement ).attr( 'data-link' );
        }        
                
        _self.bind();
        
         $( '.starwars-navigation-out' ).bind( 'mouseout', function()
         	{ 
         		if( ! $( 'ul.main > li.over ' ).length )
         		{
         			_show_bg = false;
         			_bgHide( true );
         		}
         	}
         );
         
        $( 'a.phark' ).hover( function() { setTimeout( function() { _show_bg = false; _bgHide( true ); }, 2 ); } );        
		$( '.watch' ).hover( function() { setTimeout( function() {  _bgHide(); }, 50 ); } );
        $( '.shop' ).hover( function() { setTimeout( function() {  _bgHide(); }, 50 ); } );
        
        if(
			$.browser.msie && 
			$.browser.version < 9
		)
		{
			//IE NEEDS A BG COLOR B/C OF A WEIRD MASKING ISSUE. ALSO: THERE CANNOT BE A GAP BETWEEEN MAIN AND SUB NAV
			$( '.mod.navigation ul.main .sub' ).css( { background: '#1A1A1A', borderTop: '1px #444 solid' } );
		}
   	}
   	
    Navigation();
    return App.basil.create(_self);
}
