window.DEVICE = {
  isIphone: function(){ return navigator.userAgent.match(/iPhone/i); },
  isIpod: function(){ return navigator.userAgent.match(/iPod/i); },
  isIpad: function(){ return navigator.userAgent.match(/iPad/i); },
  isAndroid: function() { return navigator.userAgent.toLowerCase().indexOf('android') > -1; }
  // isFBforIphone: function() { return navigator.userAgent.toLowerCase().indexOf('fbforiphone') > -1; }
};
// create global scope object if doesn't already exist 
var TF7 = TF7 || {}; // "TF" for "24" since js vars can't start with numeral
TF7.events = {
	 // KEYBOARD 
    KEY_UP: 'keyUp',
    KEY_DOWN: 'keyDown',
    KEY_LEFT: 'keyLeft',
    KEY_RIGHT: 'keyRight',
    KEY_ENTER: 'keyEnter',
    KEY_ESC: 'keyEsc',
    KEY_RELEASE: 'keyRelease'
};
TF7.isFirstVisit = true;
TF7.navController = null; 

TF7.initialize = function($) {

	debug.log("TF7 :: initialized ");
	
	/*
	if(DEVICE.isFBforIphone()) {
	  $body.addClass('_fb');
	}
	*/
	
	if(DEVICE.isIphone() || DEVICE.isIpod() || DEVICE.isIpad() || DEVICE.isAndroid()){
	  var $body = $('body');
	  
	  $body.addClass('_mobile');
	  
	  if($('#news').length == 0 && $('#news-detail').length == 0) {
	    
  	  var bgHeight = parseInt($('#background-image').attr('height'), 10),
  	      bgWidth = parseInt($('#background-image').attr('width'), 10);
  	  
  	  // if( ! $body.hasClass('_work')) {
  	    
    	  $('#fixed-background').css({
    	    height: bgHeight + 'px',
    	    width: 1004 + 'px'
    	  });
    	  $('#background-image').css({
    	    left: Math.floor((1004 - bgWidth) / 2) + 'px',
    	    width: bgWidth + 'px'
    	  });
    	  
  	  // } else {
  	  //  $('#fixed-background').remove();
  	  // }
  	  
	  }
	}

	// use 'hasVisited' session cookie value to determine when to show page build animations - comment out for testing animations
  TF7.isFirstVisit = ($.cookie('hasVisited')  !== "true") ? true : false; 
	if (TF7.isFirstVisit) {
		$.cookie('hasVisited', 'true');
	}
    
  $('footer').footerController(); // footer plugin needs to be available to sections when they instantiate
  
	$('[data-controller]').autoInstantiate();
	
	// instantiate keyboard manager plugin
  $('body').keyboardManager();
}

jQuery.noConflict();

(function($){
	
	// @autoInstantiate
	$.fn.autoInstantiate = function() {
  
		return this.each(function(){

			var $this = $(this),
					_auto = $this.data('auto');
					_controller = $this.data('controller'),
					_controllers = [];

			if(_controller) {
			
				// check for mutliple controllers
				if(_controller.indexOf(',') > -1) {
					_controllers = _controller.split(',');
				} else {
					_controllers.push(_controller);
				}
			
				// make sure 'auto' is on and instatntiate the plugin
				if(_auto != 'false') {
					for (var i=0; i < _controllers.length; i++) {
						_controller = _controllers[i];
						if(typeof eval('$.fn.' + _controller) == 'function') {
							eval('$this.' + _controller + '()');
						}
					}
				}

			}
    
	  });
  
	};
	
	// @autoScrollHere
  $.fn.autoScrollHere = function(options) {
    
    options = $.extend({}, $.fn.autoScrollHere.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this), // This represents our <a> tag
          $body = $('body'),
          $scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $body,
          _delay = options.delay,
          _onCompleteCallback = options.onComplete,
          _dur = options.duration,
          _ease = options.ease,
          _dest = $this.offset().top + options.offset,
          _execScrollHere = function() {
            if(_onCompleteCallback == null) {
              $scroll.animate({scrollTop: _dest}, _dur, _ease);
            } else {
              $scroll.animate({scrollTop: _dest}, _dur, _ease, _onCompleteCallback);
            }
          };
          
      if(_delay <= 0) {
        _execScrollHere();
      } else {
        $.doTimeout(options.delay, _execScrollHere);
      }
      
    }); // each()
    
  }; // End autoScrollHere Plugin.
  
  $.fn.autoScrollHere.defaults = {
    duration: 1000,
    ease: "easeInOutExpo",
    delay: 0,
    onComplete: null,
    offset: 0
  };
	
	
	// ====================================================================
	// @NavigationController plugin
	// ====================================================================
  var NavigationController = function(options, elem) {
	    
		var $this = $(elem),
				$homeBtn = $('#home-button'),
				$navLinkList = $this.find('ul'),
				$navLinks = $navLinkList.find('a'),
				_homeBtnDestX = 0,
				_badIE = $.browser.msie == true && $.browser.version < 9,
				_navLinkListDestX = 0;
		  
    // ----------------------------------------------------------------
    
    function _init() {
				
      debug.log("NavigationController :: instantiated");
      
      debug.log(_badIE);
			
			_homeBtnDestX = parseInt($homeBtn.css('left').split('px')[0], 10);
			
			if(_badIE) {
			  $homeBtn.css({ left:-$homeBtn.outerWidth()	});
		  } else {
			  $homeBtn.css({ opacity:0, left:-$homeBtn.outerWidth()	});
		  }
			
			_navLinkListDestX = parseInt($navLinkList.css('right').split('px')[0], 10);
			if(_badIE) {
  			$navLinkList.css({ right:-$navLinkList.outerWidth() });
		  } else {
  			$navLinkList.css({ opacity:0, right:-$navLinkList.outerWidth() });
		  }
			
			var curSectionId = $('section').attr('id');
			var $link = $navLinks.filter('[data-id~="'+curSectionId+'"]');
			$link.addClass('selected');
    }; // _init()
    
    // ----------------------------------------------------------------
    
		function _transitionIn() {
			var duration = 750;
			
			// only do homeButton animation if this is the first time visiting the page or coming from home
			if (TF7.isFirstVisit || $.cookie('lastVisited') === 'home') {
			  if(_badIE) {
			    $homeBtn.stop().animate({left:_homeBtnDestX}, duration, "easeOutExpo");
			  } else {
			    $homeBtn.stop().animate({opacity:1, left:_homeBtnDestX}, duration, "easeOutExpo");
			  }
				
			} else {
			  if(_badIE) {
			    $homeBtn.css({ left:_homeBtnDestX });
		    } else {
		      $homeBtn.css({ opacity:1, left:_homeBtnDestX });
		    }
				
			}
			
			// only do navLinkList animation if this is the first time visiting the page
			if (TF7.isFirstVisit) {
			  if(_badIE) {
				  $navLinkList.stop().animate({right:_navLinkListDestX}, duration, "easeOutExpo");
			  } else {
			    $navLinkList.stop().animate({opacity:1, right:_navLinkListDestX}, duration, "easeOutExpo");
			  }
			}	else {
			  if(_badIE) {
			    $navLinkList.css({ right:_navLinkListDestX });
		    } else {
		      $navLinkList.css({ opacity:1, right:_navLinkListDestX });
		    }
				
			}
			
		};
		
    _init();
    
    return {
      transitionIn: function() {
				_transitionIn();
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.navigationController = function(options) {
    
    var pluginName = "NavigationController";
    
    options = $.extend({}, $.fn.navigationController.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this);
      
      if($this.data(pluginName)) {
        return;
      }
      
      // No JavaScript plugin instance exists, so add it as data attribute.
      var pluginInstance = new NavigationController(options, this);
      $this.data(pluginName, pluginInstance);
      
			TF7.navController = pluginInstance;

    });
    
  };
  
  // ==================================================================
  
  $.fn.navigationController.defaults = {
    
  };
	
})(jQuery);


// ====================================================================
// @FooterController plugin
// ====================================================================
(function($){
  
  var FooterController = function(options, elem) {
    
    var $this = $(elem),
        $win = $(window),
        $body = $('body'),
        $wrapper = $('#wrapper');
    
    // ----------------------------------------------------------------
    
    function _init() {
      
      $win.bind('resize', _onResize);
      _onResize();
      
      $this.css({
        opacity:0
      });
      
      
      
    }; // _init()
    
    // ----------------------------------------------------------------
    
    function _transitionIn() {
      
      if (TF7.isFirstVisit) {
        $this.animate({ opacity:1 }, 500, "easeOutSine");
      } else {
        $this.css({
          opacity:1
        });
      }
      
    };
    
    // ----------------------------------------------------------------
    
    function _onResize() {
      
      var winW = $win.width();
      var winH = $win.height();
      var minHeight = $wrapper.outerHeight() + $this.outerHeight();
      
      if (winH > minHeight) {
        if (!$this.hasClass('anchored')) {
          $this.addClass('anchored');
        }
        
        var destX = (winW - $this.outerWidth()) * 0.5;
        $this.css({
          left: (destX >= 0 ) ? destX : 0
        });
        
      } else if ($this.hasClass('anchored')) {
          $this.removeClass('anchored');
      }
      
    };
    
    // ----------------------------------------------------------------
    
    _init();
    
    return {
      transitionIn: function() {
        _transitionIn();
      },
      
      forceResize: function() {
        _onResize();
      }
    };
    
  };
  
  // ==================================================================
  
  $.fn.footerController = function(options) {
    
    var pluginName = "FooterController";
    
    options = $.extend({}, $.fn.footerController.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this);
      
      if($this.data(pluginName)) {
        return;
      }
      
      // No JavaScript plugin instance exists, so add it as data attribute.
      var pluginInstance = new FooterController(options, this);
      $this.data(pluginName, pluginInstance);
      
      TF7.footerController = pluginInstance;
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.footerController.defaults = {
    
  };
  
})(jQuery);


// ====================================================================
// @KeyboardManager plugin
// ====================================================================
(function($){
  
  var KeyboardManager = function(options, elem) {
    
    var $this = $(elem),
        _isAltCommandDown = false;
        
    // ----------------------------------------------------------------
    
    function _init() {
      debug.log("KeyboardManager :: initialized");
      
      $(document)
        .bind('keydown', _onKeydown)
        .bind('keyup', _onKeyup);
    }; // _init()
    
    // ----------------------------------------------------------------
    
    function _onKeyup(e) {

      var key = e.which;
      
      if(key == 18 || key == 224) {
        if(_isAltCommandDown) {
          _isAltCommandDown = false;
        }
      }

      $this.triggerHandler(TF7.events.KEY_RELEASE);

    };

    // ----------------------------------------------------------------
    
    function _onKeydown(e) {

      var key = e.which;

      if(key == 18 || key == 224) {
        _isAltCommandDown = true;
      }

      switch(key) {

        case 38: //top

          $this.trigger(TF7.events.KEY_UP);
          e.preventDefault();
          break;

        case 39: //right
        
          $this.trigger(TF7.events.KEY_RIGHT);
          e.preventDefault();
          break;

        case 40: ///bottom

          $this.trigger(TF7.events.KEY_DOWN);
          e.preventDefault(); 
          break;

        case 37: //left

          $this.trigger(TF7.events.KEY_LEFT);
          e.preventDefault();
          break;

        case 13: // enter

          $this.trigger(TF7.events.KEY_ENTER);
          e.preventDefault();
          break;

        case 27: // esc

          $this.trigger(TF7.events.KEY_ESC);
          e.preventDefault();
          break;

      } //switch
        
    }; // End on_keydown()
    
    // ----------------------------------------------------------------
    
    _init();
    
    return {
      
    };
    
  };
  
  // ==================================================================
  
  $.fn.keyboardManager = function(options) {
    
    var pluginName = "KeyboardManager";
    
    options = $.extend({}, $.fn.keyboardManager.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this);
      
      if($this.data(pluginName)) {
        return;
      }
      
      // No JavaScript plugin instance exists, so add it as data attribute.
      var pluginInstance = new KeyboardManager(options, this);
      $this.data(pluginName, pluginInstance);
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.keyboardManager.defaults = {
    
  };
  
})(jQuery);

jQuery(function($) {
  
	debug.log("247 Base Ready!");
  TF7.initialize($);
	
});
