// Global MomentumWW object
var MomentumWW = {

  // ------------------------------------------------------------------
  // @constants
  // ------------------------------------------------------------------
	BASE_URL:					    '',
	EXPAND_SCROLL_DUR:		800,
	EXPAND_SCROLL_EASE:		'easeInOutExpo',
	FONT_LOAD_TIMEOUT:		3000,
	WINDOW_SQUEEZE_WIDTH:	795, 
	SQUEEZED:				      '_squeezed',
	VIDEO_EMBED_TYPE:     'none',
	VIDEO_MIME_TYPE:      '', 
	VIDEO_FILE_SUFFIX:    '',
	IS_IPAD:				      false,
	HAS_FLASH:			    	false,
	IS_MODERN_BROWSER:		true,

  // ------------------------------------------------------------------
  // @events
  // ------------------------------------------------------------------
  events: {
    
		WINDOW_SQUEEZE: 'windowSqueeze',
		WINDOW_FULL: 'windowFull',
		
		SCROLL_SECTION_CHANGE: 'scrollSectionChange',
		
		ENTER_FULLSCREEN_VIDEO: 'enterFullscreenVideo',
		EXIT_FULLSCREEN_VIDEO: 'exitFullscreenVideo',
		
    REMOVE_VIDEO_COMPLETE: 'removeVideoComplete',
		
		// PreloadImg Events
		PRELOAD_COMPLETE: 'preloadimagecomplete',
		PRELOAD_PRE_COMPLETE: 'preloadimgprecomplete',

		GOTO_FEATURE: 'gotofeature',
		
		RIBBON_NAV_CLICK: 'ribbonNavClick',
		
		// Media Scroller Events
		MEDIA_SELECTED: 'mediaSelected',
		
		// Case Study Events
		CASE_STUDY_PREV_NEXT: 'caseStudyPrevNext',
		CASE_STUDY_SELECTED: 'caseStudySelected',
		CASE_STUDY_DETAIL_SELECTED: 'caseStudyDetailSelected',
		OPEN_CASE_STUDIES_LIST: 'openCaseStudiesList',
		CLOSE_CASE_STUDIES_LIST: 'closeCaseStudiesList',
		OPEN_CASE_STUDIES_GRID: 'openCaseStudiesGrid',
		
		// About Events
		OFFICE_LOCATION_SELECTED: 'officeLocationSelected',
		
		// Contact Events
		LOCATION_CONTACT_CLICK: 'locationContactClick'
  },

	isFontLoaded: false,
	fontLoadStartTime: new Date().getTime(),
	
	initPath: "",
	
	ribbonNavDepth: 150,
	
	contentScroll: null,
	
	isHomeVideoPlaying: false,
	currentSection: null,
  
  // ------------------------------------------------------------------
  // @initialize
  // ------------------------------------------------------------------
  initialize: function($) {

		// make sure jQuery address init callback gets called first
		$.address.init(function (event) {
			debug.log("jQuery address init :: $.address.value(): "+$.address.value());
	    if ($.address.value() == '/') {
	        	MomentumWW.initPath = '/home';
						$.address.value('home');
	    } else 
	    {
	      //debug.log("a value already exists in $.address on init: "+$.address.value());
				MomentumWW.initPath = $.address.value();
	    }
	
			// Kick things off.
			debug.log("initialize :: isFontLoaded: "+MomentumWW.isFontLoaded);
			if (MomentumWW.isFontLoaded) {
	    	$('html').MomentumWWInitialize();
			}	else {
				this.fontLoadStartTime = new Date().getTime();
	 			setTimeout(MomentumWW.checkFontLoad, 250, [$]);
			}
	  } ).history(true);
				
  },

	fontLoaded: function() {
		debug.log("MomentumWW :: TypeKit font loaded");
		MomentumWW.isFontLoaded = true;
	},
	
	checkFontLoad: function() {
		//debug.log("checkFontLoad :: ");
		if (MomentumWW.isFontLoaded) {
			$('html').MomentumWWInitialize();
		} else
		{
			var fontLoadTime = new Date().getTime() - MomentumWW.fontLoadStartTime;
			//debug.log("fontLoadTime :: "+fontLoadTime);
			if (fontLoadTime > MomentumWW.FONT_LOAD_TIMEOUT) { // check for timeout
				// font load timed out - go ahead and initialize the site
				$('html').MomentumWWInitialize();
			} else {
				setTimeout(MomentumWW.checkFontLoad, 100);
			}
		}
	}
  
};

// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:push
// ----------------------------------------------------------------
if(!Array.prototype.push) {
  Array.prototype.push = function( o ) {
  	this[this.length] = o;
  };
}
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:splice
// ----------------------------------------------------------------
if(!Array.prototype.splice) {
  Array.prototype.splice = function(iStart, iLength) {
  	if(iLength < 0) {
  	  iLength = 0;
    }

  	var aInsert = [];
  	if(arguments.length > 2) {
  		for(var i=2; i<arguments.length; i++) {
  			aInsert.push(arguments[i]);
  		}
  	}

  	var aHead = this.subarray(0, iStart),
  	    aDelete = this.subarr(iStart, iLength),
  	    aTail = this.subarray(iStart + iLength),
        aNew = aHead.concat(aInsert, aTail);

  	// Rebuild yourself
  	this.length = 0;
  	for(var i=0; i<aNew.length; i++) {
  		this.push(aNew[i]);
  	}

  	return aDelete;
  };
}
if(!Array.prototype.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){
        return i;
      }
    }
    return -1;
  }
}


// ====================================================================
// ---/ Begin global jQuery plugins /----------------------------------
// ====================================================================

(function($){
  
  // @MomentumWWInitialize
  $.fn.MomentumWWInitialize = function() {
    var $this = this,
		$body = $('body'),
		$nav = $('nav'),
		$content = $('#content'),
		$footer = $('footer'),
		_currentSectionId = null,
		_pSectionScrollManager = null,
		_isScrollSectionChange = false,
		_hasAddressFirstChangeEvent = false,
		_isAutoScrolling = false,
		$sectionControllers = null,
		$content = $('#content'),
		$contentContainer = null,
		_scrollY = 0;

    function _init() {
		  debug.log("--------------------------------------------------");
	    debug.log("MomentumWWInitialize :: Page logic begin.");
	    debug.log("--------------------------------------------------");
			
			// init global vars
			MomentumWW.HAS_FLASH = swfobject.hasFlashPlayerVersion('9.0.0');
			MomentumWW.IS_IPAD = $this.hasClass('ipad');
			
			// check if older IE is being used, this flag is used mainly to determine whether animated opacity fades are used or not
			if ($this.hasClass('ie8') ||
					$this.hasClass('ie7')) 
			{
					MomentumWW.IS_MODERN_BROWSER = false;
			}
						
			_checkVideoCapabilities();
							
			_setupNavLinks();
						
			// add a div to add extra height at the top of the content scroll so it doesnt go behind nav when scrolled to top
			var navOffsetHtml = '<div class="nav-offset"></div>';
			var $navOffset = $.browser.msie ? $(innerShiv(navOffsetHtml, false)) : $(navOffsetHtml);
			$nav.after($navOffset);
			$('.nav-offset').css('height', ($nav.outerHeight()+8)+'px');
			
			// display elements now that font is loaded
			$nav.css('display','block');
			$content.css('display','block');
			$footer.css('display','block');
			
			// fade our nav, content and footer back in (do this before autoinstantiation so that element sizes are calculated correctly)
			if (MomentumWW.IS_MODERN_BROWSER) {
				$nav.animate({opacity: 1},500);
				$content.animate({opacity: 1},500);
				$footer.animate({opacity: 1},500);
			}
			
			// do scrolling setup when targeting iPad
			if (MomentumWW.IS_IPAD) {
				debug.log('-- Site is running on an iPad --');
				
				// Check screen size on orientation change
			  window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', _setMobWebkitScrollHeight, false);

			  // Prevent scrolling when dragging elements outside of the scroller (ie:header nav).
			  //document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
				
				// wrap our scrollable content in two container layers one to combine hold our actual pieces of content (need to do this since footer needs to be scrolled with content)
				// and the other outer container to define the scroll "window" area

				var $contentContainer = $.shiv('<div id="content-container"></div>');
				$content.wrap($contentContainer);
				$contentContainer = $('#content-container');
				$contentContainer.prepend($('.nav-offset'));
				$contentContainer.append($('footer'));
				
				var contentScrollAreaHtml = '<div id="content-scroll-area"></div>';
				var $contentScrollArea = $.browser.msie ? $(innerShiv(contentScrollAreaHtml, false)) : $(contentScrollAreaHtml);
				$contentContainer.wrap($contentScrollArea);
				
				_setMobWebkitScrollHeight();	
				MomentumWW.contentScroll = new iScroll('content-scroll-area', 
				  {
				    hScroll:false,
				    hScrollbar:false,
				    overflow:'hidden',
				    momentum:true,
				    hideScrollbar:false
				  });
			}
			
			// initialize background manager plugin
			$body.backgroundManager();
			
			// initialize the SectionScrollManager plugin
			_pSectionScrollManager = $body.sectionScrollManager().data('SectionScrollManager');

	    // Auto-instantiate any nodes with data-controller attributes.
	    $sectionControllers = $('[data-controller]');
						
			// instead of initting each section here we need to do each one separately
			//$sectionControllers.autoInstantiate();

			// initialize window width monitor plugin	
	    $(window).windowMonitor();

			// Bind to the jQuery address events
	    //$.address.init(function (event) {"$.address.init()"} );
	    $.address.bind('change', _onAddressChange);		
	
			// bind video fullscreen events
			$body.bind(MomentumWW.events.ENTER_FULLSCREEN_VIDEO, _onEnterFullscreenVideo);
			$body.bind(MomentumWW.events.EXIT_FULLSCREEN_VIDEO, _onExitFullscreenVideo);
			
			// set section to the initPath
			_processNewPaths(MomentumWW.initPath);
			
			if (MomentumWW.initPath != '/home') {
				// update background with default bg
				var backgroundURI = $content.data('default-background-uri');
				var backgroundColor = $content.data('default-background-color');
			
				MomentumWW.backgroundManager.updateBackground(backgroundColor, backgroundURI);
			}
			
			if (MomentumWW.IS_IPAD) 
				setTimeout(MomentumWW.contentScroll.refresh(), 33);
			
		};
		
		function _checkVideoCapabilities() {
		  
		  if (MomentumWW.HAS_FLASH) {
			  
			  MomentumWW.VIDEO_EMBED_TYPE = "flash";
			  MomentumWW.VIDEO_FILE_SUFFIX = '.f4v';
			  
			} else if ($this.hasClass("video")) {
			  
			  MomentumWW.VIDEO_EMBED_TYPE = "html";
			  
			  var v = document.createElement('video'),
			      supportedFiles = ['mp4', 'ogg'],
			      mimeTypes = {
			        'mp4': 'video/mp4; codecs="avc1.42E01E"',
			        'ogg': 'video/ogg; codecs="theora"'
			      };
			  
			  for (var i=0; i < supportedFiles.length; i++) {
			  
			    var fileType = supportedFiles[i],
			        mimeType = mimeTypes[fileType],
			        canPlayType = v.canPlayType(mimeType);
			    
			    if ((canPlayType === "maybe") ||
  			      (canPlayType === "probably")) 
  		    {
  		      MomentumWW.VIDEO_FILE_SUFFIX = '.' + fileType;
  		      MomentumWW.VIDEO_MIME_TYPE = mimeType;
  		    }
			    
			  }
			  
			}
			
			if (MomentumWW.VIDEO_EMBED_TYPE == "none") {
			  debug.log("Warning:: video playing is not supported in this browser");
		  } else {
		    debug.log("Videos will be embedded with " + MomentumWW.VIDEO_EMBED_TYPE +
		              " and play " + MomentumWW.VIDEO_FILE_SUFFIX + " files of type: " + MomentumWW.VIDEO_MIME_TYPE);
		  }
			
		}
		
		function _setupNavLinks() {
			//setup nav links
			var $links = $nav.find('li');
			$links.each( function(i) {
					var $a = $(this).find('a');
					var navBtnHtml = '<div class="nav-btn"></div>';
					$navBtn = $.browser.msie ? $(innerShiv(navBtnHtml, false)) : $(navBtnHtml);
					$a.wrapInner($navBtn);
					
					var edgeLeftClass;
					if (i == 0) {
						edgeLeftClass = "nav-btn-edge-outer-left";
					} else {
						edgeLeftClass = "nav-btn-edge-left";
					}
					
					// msie fix needed
					var edgeLeftHtml = '<div class="'+edgeLeftClass+'"></div>';
					var $edgeLeft = $.browser.msie ? $(innerShiv(edgeLeftHtml, false)) : $(edgeLeftHtml);
					$a.prepend($edgeLeft);
			
					var edgeRightClass;
					if (i == $links.length - 1) {
						edgeRightClass = "nav-btn-edge-outer-right";
					} else {
						edgeRightClass = "nav-btn-edge-right";
					}
					
					var edgeRightHtml = '<div class="'+edgeRightClass+'"></div>';
					var $edgeRight = $.browser.msie ? $(innerShiv(edgeRightHtml, false)) : $(edgeRightHtml);
					$a.append($edgeRight);
					
					var sectionId = $a.attr('href').split('.php')[0];

					//set the section-id data attribute 
					$a.attr("data-section-id", sectionId);

					$a.bind('click.navBtn', _onnavBtnClick);

					function _onnavBtnClick(e){
						e.preventDefault();
						$.address.value('/'+sectionId);
					};
			
			});
			
			$links.last().find('.nav-btn').css('padding','6px 22px 0 3px');
			
			$nav.find(".nav-social-links a").socialLink();
			
			$('#header-logo a').click(function(e){
				e.preventDefault();
				$.address.value('/home');
			});
			
		}
		
		// Change container and background height based on device orientation.
	  function _setMobWebkitScrollHeight() {
	  	var headerH = $('nav').outerHeight(),
	  	    windowH = window.innerHeight,
	  		  containerH =  windowH;

	  	$('#content-scroll-area').css('height', containerH + 'px');
	  	$('#background-container').css('height', windowH + 'px');
	  }
	 		
		// jquery address handlers
		function _onAddressInit(e) {
	   // debug.log("_onAddressInit :: path: "+$.uriMap(e.path));
	    var pathVals = $.uriMap(e.path);

	    // Check to see if we've got any path at all.
		};
		
		function _onAddressChange(e) {
			//debug.log("_onAddressChange :: "+e.path+" _hasAddressFirstChangeEvent: "+_hasAddressFirstChangeEvent);
	    
			/*if(!_hasAddressFirstChangeEvent) {
	      _hasAddressFirstChangeEvent = true;
	    } else {
	      _processNewPaths(e.path);
	    }*/
	
	 		_processNewPaths(e.path);
	
	  };
		
		function _processNewPaths(pathVal) {
			var sectionId = (pathVal == "/") ? "home" : pathVal.split('/')[1];
			_pSectionScrollManager.setSection(sectionId);	
		};
			
		function _onEnterFullscreenVideo() {
			debug.log("_onEnterFullscreenVideo :: ");
			if (!MomentumWW.IS_IPAD) {
				_scrollY = $(window).scrollTop();
			} else
			{
				_scrollY = $contentContainer.position().top;
			}
		}
			
		function _onExitFullscreenVideo() {
			debug.log("_onExitFullscreenVideo :: ");
			if (!MomentumWW.IS_IPAD) {
				$(window).scrollTop(_scrollY);
			} else
			{
			 //$contentContainer.css("-webkit-transform":"matrix()");
			}
		}
		
		_init();
		
		return this;
  };

	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
  
  // @windowMonitor
  $.fn.windowMonitor = function() {
    
    var $win = this,
        $body = $('body'),
        _isSqueezed = ($win.width() < MomentumWW.WINDOW_SQUEEZE_WIDTH);
    
    function _init() {
      if(_isSqueezed) {
        $body.addClass(MomentumWW.SQUEEZED);
        $body.triggerHandler(MomentumWW.events.WINDOW_SQUEEZE);
      } else {  
        $body.triggerHandler(MomentumWW.events.WINDOW_FULL);
      }

			$win.bind('resize.windowmonitor', _onWindowResize);
    }
    
    function _onWindowResize() {
      if($win.width() < MomentumWW.WINDOW_SQUEEZE_WIDTH) {
        if(!_isSqueezed) {
          $body.addClass(MomentumWW.SQUEEZED);
          _isSqueezed = true;
          $body.triggerHandler(MomentumWW.events.WINDOW_SQUEEZE);
        }
      } else {
        if(_isSqueezed) {
          $body.removeClass(MomentumWW.SQUEEZED);
          _isSqueezed = false;
          $body.triggerHandler(MomentumWW.events.WINDOW_FULL);
        }
      }
      
			// update all block text plugin instances
			$('.block-text').each(function () {
				var _pBlockText = $(this).data('BlockText');
				if (_pBlockText != null) {
					_pBlockText.updateRows();
				}
			});
			
    };
      
    
		_init();
    
    return this;
    
  };

  // ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
  /*
    @uriMap takes a jQuery path and parses it into a native Object
    of key-value pairs. If no path exists or if the number of path
    segments is odd, then the boolean false is returned.
  */
  $.uriMap = function(jqueryAddressPath) {
    if(jqueryAddressPath.length <= 1) {
      return false;
    }
    // Take off the first / last slashes.
    if(jqueryAddressPath.charAt(0) == '/') {
      jqueryAddressPath = jqueryAddressPath.substr(1);
    }
    if(jqueryAddressPath.charAt(jqueryAddressPath.length - 1) == '/') {
      jqueryAddressPath = jqueryAddressPath.substr(0, jqueryAddressPath.length - 1);
    }
    var pieces = jqueryAddressPath.split('/');
    if(pieces.length % 2 != 0) {
      return false;
    }
    var o = {};
    for(var i = 0; i < pieces.length; i+=2) {
      o[pieces[i]] = pieces[i+1];
    }
    return o;
  };
  
  // ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
  
  // @getWeightedAverage
  $.getWeightedAverage = function(value, dest, n) {
    return value + (dest - value) / n;
  };

	$.getCenterPos = function($target, $container) {
		return {
							top:Math.round(($container.outerHeight() - $target.outerHeight()) * 0.5), 
							left:Math.round(($container.outerWidth() - $target.outerWidth()) * 0.5)
						};
	}

  // ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
  
  // @autoInstantiate
  $.fn.autoInstantiate = function() {
    
    return this.each(function(){
      
      var $this = $(this),
          _auto = $this.data('auto');
          _controller = $this.data('controller'),
          _controllers = [];
      
      if(_controller) {
				$this.attr('id',$this.data('id')+'-section');
        if(_controller.indexOf(',') > -1) {
          _controllers = _controller.split(',');
        } else {
          _controllers.push(_controller);
        }
        
        if(_auto != 'false') {
          for (var i=0; i < _controllers.length; i++) {
            _controller = _controllers[i];
            if(typeof eval('$.fn.' + _controller) == 'function') {
              eval('$this.' + _controller + '()');
            }
          };
        }

      }
      
    });
    
  };

	// @embedVideo plugin
	$.fn.embedVideo = function(videoURL, width, height) {
	  
	  var $element = this;
	  
	  if ($element.length > 1) {
	    $element = $element.eq(0);  
	    debug.log("warning embedVideo() plugin is only meant to be used on a single jQuery element");
	  }
	  
	  videoURL = videoURL.substring(0, videoURL.lastIndexOf('.')) + MomentumWW.VIDEO_FILE_SUFFIX;  
    //debug.log("embedVideo: "+videoURL);
  	  
	  var embedTypeFunctions = {
	        'flash': _embedFlash,
    	    'html': _embedHTML,
    	    'none': _embedNone
    	  },
    	  embed = embedTypeFunctions[MomentumWW.VIDEO_EMBED_TYPE];
  	  
	  function _embedFlash() {
	    //debug.log("_embedFlash video type");
	    
	    $element.empty();
    
		  var swfElementID = 'swf-video-'+new Date().getTime(),
		      $swfElement = $.shiv('<div id="'+swfElementID+'"></div>'),
		      swfPath = media_url + "browser/swf/video-player.swf",
  		    flashVars = {
  			  	VIDEO_URL:videoURL
    			},
    	 		params = {
            wmode: 'opaque',
            bgcolor: '#000000',
            quality: 'high',
            menu: 'false',
            allowscriptaccess: 'always',
            allownetworking: 'all',
            allowfullscreen: 'true'
          },
          attributes = {
            id: swfElementID,
            name: swfElementID
          };
          
      $element.append($swfElement);
      
	  	swfobject.embedSWF(
  		  swfPath,
  		  swfElementID,
  		  '100%', '100%',
  		  '10.0.12',
  		  media_url + "browser/swf/expressInstall.swf",
  		  flashVars,
  		  params,
  		  attributes,
  		  function(result) { debug.log("embedSWF result: "+result.success); }
  		);		
  		
	  }
	
	  function _embedHTML() {
		  //debug.log("_embedHTML video type");
		  
		  $element.empty();  
		  
		  var vid = null,
		      $vid = null; //$element.find('video');
		  
		  /*/  
		  if ($vid.length > 0) { // only add the video element once, otherwise just update src attribute
		    vid = $vid.eq(0)[0];
		  } else {
		    vid = document.createElement('video');
		    vid.setAttribute('type', MomentumWW.VIDEO_MIME_TYPE);
		    vid.controls = true;
		    $vid = $(vid);
		  }
		  /*/
		  
		  vid = document.createElement('video');
	    vid.setAttribute('type', MomentumWW.VIDEO_MIME_TYPE);
	    vid.controls = true;
	    $vid = $(vid);
		  		  
  		vid.src = videoURL;
  		vid.width = width;
  		vid.height = height;
  		      
      $element.append($vid);
		}
	
		function _embedNone() {
	  
		}
	
		embed();
		
		return $element;
		
	};
	
	// ====================================================================
	// @VideoController plugin
	// ====================================================================
  var VideoController = function($element) {
    
    var $video = $element.find('video'),
        _videoElement = ($video.length > 0) ? $video.eq(0)[0] : null;
    
    // ----------------------------------------------------------------
    
    function _init() {
      
    }; // _init()
    
    // ----------------------------------------------------------------
      
    _init();
    
    return {
      
      play: function() {
        //debug.log("play video");
        if (_videoElement !== null) {
          _videoElement.play();
        }
      },
      
      pause: function() {
        //debug.log("pause video");
        if (_videoElement !== null) {
          _videoElement.pause();
        }
      },
            
      stop: function() {
        //debug.log("stop video");
        if (_videoElement !== null) {
          _videoElement.currentTime=0;
          _videoElement.pause();
        }
      },
      
      reset: function() {
        $video = $element.find('video'),
        _videoElement = ($video.length > 0) ? $video.eq(0)[0] : null;
      },
      
      destroy: function() {
        $video = null;
        _videoElement = null;
      },
      
      getVideoElement: function() {
        return _videoElement;
      }
            
    };
    
  };
  
  // ==================================================================
  
  $.fn.videoController = function() {
   
    var $element = this,
        pluginName = "videoController";

	  if ($element.length > 1) {
	    $element = $element.eq(0);  
	    debug.log("warning embedVideo() plugin is only meant to be used on a single jQuery element");
	  }
	
    if($element.data(pluginName)) {
      return $element;
    }
    
    // No JavaScript plugin instance exists, so add it as data attribute.
    var pluginInstance = new VideoController($element);
    $element.data(pluginName, pluginInstance);
    
    return $element;
    
  };
  // ==================================================================

	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
 	// @BlockText
	var BlockText = function(options, elem) {
    
    var $this = $(elem),
				$words = null,
				$rowsContainer = null,
				$textContainer = null;
    
    // ----------------------------------------------------------------
    
    function _init() {
			var srcText = _trimWhitespace($this.text()),
	        words = srcText.split(' ');
			
			$this.css('width', '100%')
			$this.empty();
			var rowsContainerHtml = '<div class="rows-container"></div>';	
			$rowsContainer = $.browser.msie ? $(innerShiv(rowsContainerHtml, false)) : $(rowsContainerHtml);
			var textContainerHtml = '<div class="text-container"></div>';
			$textContainer = $.browser.msie ? $(innerShiv(textContainerHtml, false)) : $(textContainerHtml);
			
			$this.append($rowsContainer);
			$this.append($textContainer);
			
		
			var oldTop = 0;
	    for(var i = 0; i < words.length; i++) {
	      var wordStr = words[i],
						wordHtml = '<div class="block-text-word"></div>',
	          $word = $.browser.msie ? $(innerShiv(wordHtml, false)) : $(wordHtml);
	      
				if(i < words.length - 1)
	        wordStr += '&nbsp;';

	      $word.html(wordStr).css({'display': 'inline-block'});
	      $textContainer.append($word);

	      $word.data('destLeft', $word.position().left);
	      $word.data('destTop', $word.position().top);
				
	    }
	
			$words = $textContainer.find('.block-text-word');
			
			_updateRows();
			
    }; // _init()
    
		function _updateRows() {
			$rowsContainer.empty();
			
			var oldTop = $words.eq(0).position().top;
			var curRowHtml = '<div class="row-bg"></div>';
			var $curRow = $.browser.msie ? $(innerShiv(curRowHtml, false)) : $(curRowHtml);
			$curRow.css('top', oldTop+'px');
			$rowsContainer.append($curRow);
			var curWidth = 0;
			$words.each(function (n) {
				var $word = $(this),
						top = $word.position().top,
						left = $word.position().left;
						
				if (oldTop != top) {
					// new row
					//debug.log("new row at :: "+top);
					var rowHtml = '<div class="row-bg"></div>';
					var $row = $.browser.msie ? $(innerShiv(rowHtml, false)) : $(rowHtml);
					$rowsContainer.append($row);
					$row.css('top', top+'px');
					
					// add pad to end of curRow
					$curRow.css('width', ($curRow.outerWidth()+12)+'px');
					
					// update curRow with the new one and add the current words length to the bg
					$curRow = $row;
					$curRow.css('width', (left + $word.outerWidth())+'px');
				} else {
					// just add the current words length to the curRow
					$curRow.css('width', (left + $word.outerWidth())+'px');
				}
				
				oldTop = top;
			});
			
			// make sure to add the final padding
			$curRow.css('width', ($curRow.outerWidth()+12)+'px');
			
			$this.css('height', $curRow.position().top + $curRow.outerHeight()+'px');
		}

		function _trimWhitespace(s) {
	    s = s.replace(/(^\s*)|(\s*$)/gi,"");
	    s = s.replace(/[ ]{2,}/gi," ");
	  	s = s.replace(/\n /,"\n");
	  	return s;
	  };
    // ----------------------------------------------------------------
    
    _init();
    
    return {
      updateRows: function() {
				_updateRows();
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.blockText = function(options) {
    
    var pluginName = "BlockText";
    
    options = $.extend({}, $.fn.blockText.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this);
      
      if($this.data(pluginName)) {
        return;
      }
      
			if (MomentumWW.IS_MODERN_BROWSER) {
      	// No JavaScript plugin instance exists, so add it as data attribute.
	      var pluginInstance = new BlockText(options, this);
	      $this.data(pluginName, pluginInstance);
			} else {
				var clearfixDivHtml = '<div class="clearfix"></div>';
				var $clearfixDiv = $.browser.msie ? $(innerShiv(clearfixDivHtml, false)) : $(clearfixDivHtml);
				$clearfixDiv.css('margin-bottom','2px');
				$this.wrap($clearfixDiv);
				$this.css({
					'float':'left',
					'background': '#ffffff',
					'padding': '0 12px'
				});
			}
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.blockText.defaults = {
    
  };
	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
 	// @SectionTitle - this should be called on an h1 tag wth a section-title class
	$.fn.sectionTitle = function () {
		 return this.each(function(){
	      var $this = $(this);
				
				//debug.log("sectionTitle plugin :: "+$this.html());
				var sectionTitleHtml = '<div class="section-title"></div>';
				var $sectionTitle = $.browser.msie ? $(innerShiv(sectionTitleHtml, false)) : $(sectionTitleHtml);
				$this.removeClass('section-title').wrap($sectionTitle);

				var $foreground = $this.clone();
				var underlineHtml = '<div class="section-title-underline"></div>';
				var $underline = $.browser.msie ? $(innerShiv(underlineHtml, false)) : $(underlineHtml);
				
				$this.addClass('section-title-background');
				$foreground.addClass('section-title-foreground');
				
				$this.after($foreground);
				$foreground.after($underline);
							
				var w = $this.outerWidth() + $this.position().left;
				$underline.css('width', w+'px');
				
		});
	};
	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
 	// @ListLinkTitle - this should be called on an h3 tag wth a list-link-title class
	$.fn.listLinkTitle = function () {
		 return this.each(function(){
	      var $this = $(this);
				
				var listLinkTitleHtml = '<div class="list-link-title">';
				var $listLinkTitle = $.browser.msie ? $(innerShiv(listLinkTitleHtml, false)) : $(listLinkTitleHtml);
				var $foreground = $this.removeClass('list-link-title').wrap($listLinkTitle).clone();
				$this.after($foreground);
				//.appendTo('.list-link-title');
				$this.addClass('list-link-title-background').next().addClass('list-link-title-foreground');				
		});
	};
	

	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
		
	$.fn.socialLink = function () {
		return this.each(function(){
			var $this = $(this);
			
			//$this.bind('click.socialBtn', _onSocialBtnClick);
			$this.empty();
			
			function _onSocialBtnClick(e) {
				e.preventDefault();
			};
		});
	};
	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
	// @RoundedLink
	$.fn.roundedLink = function () {
		 return this.each(function(){
	      var $this = $(this);
					
				var labelHtml = '<div class="label"></div>';
				var $label = $.browser.msie ? $(innerShiv(labelHtml, false)) : $(labelHtml);
				$this.wrapInner($label);
				var leftMkup = '<div class="left"></div>';
				var $left = $.browser.msie ? $(innerShiv(leftMkup, false)) : $(leftMkup);
				$this.prepend($left);
				var rightMkup = '<div class="right"></div>';
				var $right = $.browser.msie ? $(innerShiv(rightMkup, false)) : $(rightMkup);
				$this.append($right);
				
				$this.bind('mouseenter', function () {
					$(this).addClass('hover');
				});
				
				$this.bind('mouseleave', function () {
					$(this).removeClass('hover');
				});
		});
	};
	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
	// @BoxLink
	$.fn.boxLink = function () {
		 return this.each(function(){
	      var $this = $(this);
				
				var labelHtml = '<p class="label"></p>';
				var $label = $.browser.msie ? $(innerShiv(labelHtml, false)) : $(labelHtml);
				$this.wrapInner($label);
				var rightMkup = '<div class="right"></div>';
				var $right = $.browser.msie ? $(innerShiv(rightMkup, false)) : $(rightMkup);
				$this.append($right);
				
				$this.bind('mouseenter', function () {
					$(this).addClass('hover');
				});
				
				$this.bind('mouseleave', function () {
					$(this).removeClass('hover');
				});
		});
	};
	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
	// @BoxLinkExternal
	$.fn.boxLinkExternal = function () {
		 return this.each(function(){
	      var $this = $(this);
				
				var labelHtml = '<p class="label"></p>';
				var $label = $.browser.msie ? $(innerShiv(labelHtml, false)) : $(labelHtml);
				$this.wrapInner($label);
				var arrowMkup = '<div class="arrow-icon"></div>';
				var $arrow = $.browser.msie ? $(innerShiv(arrowMkup, false)) : $(arrowMkup);
				$this.append($arrow);
				
				$this.bind('mouseenter', function () {
					$(this).addClass('hover');
				});
				
				$this.bind('mouseleave', function () {
					$(this).removeClass('hover');
				});
		});
	};
	
	
	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	
	// @LargeCloseButton
	$.fn.largeCloseButton = function () {
		 return this.each(function(){
	      var $this = $(this);
				var closeXHtml = '<h1>X</h1><p>CLOSE</p>';
				var $closeX = $.browser.msie ? $(innerShiv(closeXHtml, false)) : $(closeXHtml);
				$this.append($closeX);				
		});
	};
	
	
  // ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
  
  // @PreloadImg
  var PreloadImg = function(options, elem) {
    var $targetImg = $(elem),
        $targetImgContainer = $targetImg.parent(),
        _isContainerPreDOM = ($.contains(document.body, $targetImgContainer[0])) ? false : true,
        $containerParent = (_isContainerPreDOM) ? $targetImgContainer.parent() : null,
        _isLoaded = false,
        _name = options.name,
        _doFade = options.doFade,
        _fadeDur = options.fadeDur,
        _origPosition = $targetImg.css('position'),
        _origContainerPosition = $targetImgContainer.css('position'),
        _showAnimation = options.showAnimation,
        _bgColor = options.bgColor == '' ? false : options.bgColor,
        $wrap = $.shiv('<div class="preloader-wrap"/>'),
        $coverup = $.shiv('<div class="preloader-coverup"/>'),
        $preloaderAnim = $.shiv('<div class="preloader ' + options.type + '"></div>'),
        $preloadImg = $.shiv('<img/>'),
        _destroyed = false;

    // ----------------------------------------------------------------

    function _init() {
      if(!_showAnimation) {
        $preloaderAnim.css({opacity: 0});
      }

      if(!_isLoaded) {

        if(_bgColor != false) {
          $coverup.css({'background-color': _bgColor});
        }

        if(_origContainerPosition != 'absolute' && _origContainerPosition != 'relative') {
          $targetImgContainer.css({position: 'relative'});
        }
        
        // temporarily attach container to body for reading height property
        if (_isContainerPreDOM) {
          $targetImgContainer.css('visibility', 'hidden');
          $('body').append($targetImgContainer);
        }
        
        $targetImgContainer.append($wrap);
        $wrap
          .append($targetImg)
          .append($coverup)
          .append($preloaderAnim)
          .css({
                position: 'relative',
                width: $targetImgContainer.css('width'),
                height: $targetImgContainer.css('height')
                });

        $targetImg.css({position: 'absolute'});
        
        $coverup.css({
          position: 'absolute', 
          top: 0, 
          left: 0, 
          width: $wrap.width(), 
          height: $wrap.height()
        });
        
        // put the container back if we had to temporarily attach to body
        if (_isContainerPreDOM) {
          if ($containerParent.length > 0) {
            $containerParent.append($targetImgContainer);
          } else {
            $targetImgContainer.detach();
          }
          
          $targetImgContainer.css('visibility', 'visible');
        }
        
        $preloadImg
          .bind('load.preloadimg', _onPreloadImageLoad)
          .attr('src', $targetImg.attr('src'));
        
      }
    }; // _init()
    
    // ----------------------------------------------------------------
    
    function _onPreloadImageLoad(){
      
      $targetImg.triggerHandler(MomentumWW.events.PRELOAD_PRE_COMPLETE);
      _isLoaded = true;

      if(_doFade == true) {
        // Fade out the coverup.
        $preloaderAnim.stop().animate({opacity: 0}, _fadeDur / 2, "easeOutQuad", function(){
          $coverup.stop().animate({opacity: 0}, _fadeDur, "easeOutQuad", _onFadeOutComplete);
        });
      } else {
        $coverup.css({opacity: 0});
        $preloaderAnim.css({opacity: 0});
        setTimeout(_onFadeOutComplete, 100);
      }
      
    }
    
    function _onFadeOutComplete() {
      
      $targetImg.detach();
      $targetImg.appendTo($targetImgContainer);

      $targetImg.css({position: _origPosition});
      $targetImgContainer.css({position: _origContainerPosition});
      
      $targetImg.triggerHandler(MomentumWW.events.PRELOAD_COMPLETE);
      
      // Destroy this plugin.
      _destroy();
    };

    // ----------------------------------------------------------------

    function _destroy() {
      if( ! _destroyed) { 
        _destroyed = true;

        $coverup.remove();
        $preloaderAnim.remove();
        $wrap.remove();
        
        $coverup = null;
        $preloaderAnim = null;
        $wrap = null;
        
        if($preloadImg) {
          $preloadImg.unbind('load.preloadimg');
          $preloadImg = null;
        }

        $targetImg.removeData('PreloadImg');
        $targetImg = null;
        $targetImgContainer = null;
        $containerParent = null;
      }    
    };

    // ----------------------------------------------------------------

    _init();

    return {
      getName: function() {
        return _name;
      },

      isLoaded: function() {
        return _isLoaded;
      },

      destroy: function(){
        _destroy();
      }
    };

  };

  // ==================================================================

  /*
    @preloadImg plugin should be used on images that are either bound to the page
    or images that are created with jQuery. It should be run on a jQuery <img> object.

    Possible options are:

    name:  String               (default is empty string)
  */
  $.fn.preloadImg = function(options) {

    var pluginName = "PreloadImg";

    options = $.extend({}, $.fn.preloadImg.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 PreloadImg(options, this);
      $this.data(pluginName, pluginInstance);

    });

  };

  // ==================================================================

  $.fn.preloadImg.defaults = {
    name: '',
    type: 'circle',
    bgColor: '',
    showAnimation: true,
    fadeDur: 600,
    doFade: true
  };


	// ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
	// @SectionScrollManager
  var SectionScrollManager = function(options, elem) {
   
    var $this = $(elem), // should be body element
				$win = $(window),
				$nav = $('nav'),
				$scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $this,
				$sections = $('[data-controller]'),
				_currentSectionId = null,
				_isScrollingSectionChange = false,
				_isAutoScrolling = false,
				_monitorScrollInt,
				_isAutoScrollTimeout = false,
				$contentContainer = null,
   				_offsetMin = 0,
				_offsetMax = 250,
				_topOffset = 99,
				_hasInitialSetSection = false;
   
    // ----------------------------------------------------------------
   
    function _init() {
     	//debug.log("SectionScrollManager :: init");
			
			if (!MomentumWW.IS_IPAD) {
				$win.bind('scroll.sectionscrollmanager', _onScroll);
			} else {
				// have to continuously watch y position on sections in an interval to determine which section is active
				_monitorScrollInt = setInterval(_monitorScroll, 100);
				$contentContainer = $('#content-container');
			}
			
			$sections.each( function(){
				var $section = $(this);
				$section.data('isLoaded', 'false');
			});

    }; // _init()
   
    // ----------------------------------------------------------------
		
		// scroll tracking specific to iPad
		function _monitorScroll() {
		
			var winHeight = $('#content-scroll-area').outerHeight();
			var containerY = $contentContainer.position().top;                  
			
			$sections.each( function(){
				var $section = $(this);
				var sectionController = $section.data('sectionController');
				var sectionId = $section.data('id');
				var sectionHeight = $section.outerHeight();
				var offsetTop = $section.offset().top;
								
				var sectionTopOffsetY = offsetTop;
		
				if (_offsetMin < sectionTopOffsetY && sectionTopOffsetY < _offsetMax ) { // section is within the "activation" area range
					if (sectionId != _currentSectionId) {
						_onScrollSectionChange(sectionId);
					}
				} 
				
				if (!_isAutoScrolling) { // do not update sections onScreen state or load new content while autoscrolling, too much cpu/load overhead only loda the destination
					if (-sectionHeight + _topOffset < sectionTopOffsetY && sectionTopOffsetY < winHeight) { // area is on screen 
						if (!$section.hasClass('onScreen')) {
							//debug.log("adding onScreen to :: "+sectionId);
							$section.addClass('onScreen');
							
							// if section plugin exists - activate it
							if (typeof sectionController !== 'undefined') {
							  sectionController.activate();  // activate the section's javascript plugin
						  }
							
							// load section content
							_loadSection($section);
						}
					} else if (	$section.hasClass('onScreen')) {
						//debug.log("removing onScreen from :: "+sectionId);
						$section.removeClass('onScreen');
						
						// if section plugin exists - deactivate it
						if (typeof sectionController !== 'undefined') {
						  sectionController.deactivate();  // deactivate the section's javascript plugin while not onScreen
					  }
					}
				}
				
			});
			
		};
		
		// ----------------------------------------------------------------
		
		function _onScroll(event) { 
				var winScrollTop = $win.scrollTop();
				var winHeight = $win.height();
				
				$sections.each( function(){
					var $section = $(this);
					var sectionController = $section.data('sectionController');
					var sectionId = $section.data('id');
					var sectionHeight = $section.outerHeight();
					var offsetTop = $section.offset().top;
					
					var sectionTopOffsetY = (offsetTop - winScrollTop);
					
					if (_offsetMin < sectionTopOffsetY && sectionTopOffsetY < _offsetMax ) { // section is within the "activation" area range
						if (sectionId != _currentSectionId) {
						
							_onScrollSectionChange(sectionId)
						}
					} 
					
					if (!_isAutoScrolling) { // do not update sections onScreen state or load new content while autoscrolling, too much cpu/load overhead only loda the destination
						if (-sectionHeight + _topOffset < sectionTopOffsetY && sectionTopOffsetY < winHeight) { // area is on screen 
							if (!$section.hasClass('onScreen')) {
								debug.log("adding onScreen to :: "+sectionId);
								$section.addClass('onScreen');
								
								// if section plugin exists - activate it
  							if (typeof sectionController !== 'undefined') {
  							  sectionController.activate();  // activate the section's javascript plugin
  						  }
  						  
								// load section content
								_loadSection($section);	
							}
						} else if (	$section.hasClass('onScreen')) {
							debug.log("removing onScreen from :: "+sectionId);
							$section.removeClass('onScreen');
							
							// if section plugin exists - deactivate it
  						if (typeof sectionController !== 'undefined') {
  						  sectionController.deactivate();  // deactivate the section's javascript plugin while not onScreen
  					  }
						}
					}
				});
				
    };
			
		function _onScrollSectionChange(sectionId) {
			// dont update jquery address if we're autoscrolling
			if (_isAutoScrolling) {
				return;
			}
			
			_isScrollingSectionChange = true;
			$.address.value('/'+sectionId);
		};
				
		function _setCurrentSection(sectionId) {
			debug.log("SectionScrollManager :: _setCurrentSection :: sectionId: " + sectionId);
			
			// remove current section's nav highlight
			if (_currentSectionId != null) {
				var $curSection = $('section[data-id="'+_currentSectionId+'"]');
				$nav.find('a[data-section-id="'+_currentSectionId+'"]').removeClass('selected');
 			}
				
			// update nav for new section 
			var $section = $('section[data-id="'+sectionId+'"]');		
			$nav.find('a[data-section-id="'+sectionId+'"]').addClass('selected');
			_currentSectionId = sectionId;
			MomentumWW.currentSection = _currentSectionId;
		};
		
		function _autoScrollToSection(sectionId) {
			_isAutoScrolling = true;
			
			var $section = $('section[data-id="'+sectionId+'"]');
			_loadSection($section)
			
			if (!MomentumWW.IS_IPAD) { // autoscroll for regular display
					
				$section.autoScrollHere({
																	onComplete:_autoScrollComplete,
																	offset:(sectionId == 'home') ? 99 : 12
																});
																							
			} else { 
				// autoscroll for iPad
				var duration = 500;

				// set destination based on section id
				var destY = -$section.position().top;
				if (sectionId != 'home') 
					destY -= 91;

				// unset autoscroll flag after the scrollTo has finished 
				// using setTimeout kludge for now
				// > ideally would have a callback to pass to the iScroll.scrollTo() function
				setTimeout(_autoscrollTimeout, duration+50);

				// scrollTo() destination on iScroll instance
				MomentumWW.contentScroll.scrollTo(0, destY, duration);
			}
		};
		
		function _jumpToSection(sectionId) {
			
			var $section = $('section[data-id="'+sectionId+'"]');
			_loadSection($section)
			
			if (!MomentumWW.IS_IPAD) { // position for regular display
				
				var dest = $section.offset().top;
				dest = (sectionId == 'home') ? dest - 99 : dest - 12;
				$scroll.scrollTop(dest);

			} else { // position for iPad
				var duration = 500;

				// set destination based on section id
				var destY = -$section.position().top;
				if (sectionId != 'home') 
					destY -= 91;

				// set position to destination on iScroll instance
				MomentumWW.contentScroll.scrollTo(0, destY, 200);
			}
		}
		
		function _autoScrollComplete() {
			_isAutoScrolling = false;
			_onScroll(); // run this so that any content that is now onscreen (but not the target actual section) will get loaded
		};
				
		// ----------------------------------------------------------------
		
		function _autoscrollTimeout() {
			_isAutoScrolling = false;
		};
		
		// ----------------------------------------------------------------
		
		function _loadSection($section) {
			if ($section.data('isLoaded') == 'true') {
				return; // don't do anything if section is already loaded
			}
			
			var sectionId = $section.data('id');
			var sectionContentURL = base_url + 'ajax/'+sectionId;
			$section.data('isLoaded', 'true');
			
			$.ajax({
			  url: sectionContentURL,
			  context: $section,
			  success: function(data) {
					this.append($.browser.msie ? $(innerShiv(data, false)) : $(data));
					var sectionController = this.data('controller');
					eval('this.'+sectionController+'()');
					
					$section.data('sectionController').activate();
					
					if (MomentumWW.IS_IPAD) {
						MomentumWW.contentScroll.refresh();
					}
			  }
			});
		};
		
    _init();
   
    return {
	
			setSection: function(sectionId) {
				debug.log("SectionScrollManager :: setSection "+sectionId);
					
					if (_isScrollingSectionChange) { // section change initiated by scrolling the page
						//debug.log("_processNewPaths :: occured from a ScrollSectionChange just reset flag to false.");
						_isScrollingSectionChange = false;
						
					} else { // section change initiated by deeplink or nav
						if (_hasInitialSetSection) {
							_autoScrollToSection(sectionId);
						} else {
							_hasInitialSetSection = true;
							_jumpToSection(sectionId);
						}
					}

					_setCurrentSection(sectionId);
			}
				
    };
   
  };
 
  // ==================================================================
 
  $.fn.sectionScrollManager = function(options) {
   
    var pluginName = "SectionScrollManager";
   
    options = $.extend({}, $.fn.sectionScrollManager.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 SectionScrollManager(options, this);
      $this.data(pluginName, pluginInstance);
     
    });
   
  };
 
  // ==================================================================
 
  $.fn.sectionScrollManager.defaults = {
   	
  };


  // ==================================================================
  // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  // ==================================================================
  
  // @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,
					_offset = options.offset,
          _dest = $this.offset().top - _offset,
          _execScrollHere = function() {
             $scroll.stop().animate({scrollTop: _dest}, _dur, _ease, _autoScrollComplete);
          };

      if(_delay <= 0) {
        _execScrollHere();
      } else {
        $.doTimeout('autoscroll-delay', _delay, _execScrollHere);
      }
      
			function _autoScrollComplete() {
								
				if(_onCompleteCallback != null) {
					_onCompleteCallback();
				}
				
				_destroy();
			}
			
			function _destroy() {
				$scroll = null;
				_onCompleteCallback = null;
				_execScrollHere = null;
			}
    }); // each()
    
  }; // End autoScrollHere Plugin.
  
  $.fn.autoScrollHere.defaults = {
    duration: MomentumWW.EXPAND_SCROLL_DUR,
    ease: MomentumWW.EXPAND_SCROLL_EASE,
    delay: 0,
    onComplete: null,
		offset:0
  };

	// ==================================================================
	// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	// ==================================================================
	// @BackgroundManager plugin 
  var BackgroundManager = function(options, elem) {
    
    var $body = $(elem),
				$nav = $('nav'),
				$bodyBackgroundContainer,
				$navBackgroundContainer,
				_isLoading = false,
				_curBackgroundURI = null,
				$newBgImage = null,
				$curBgImage = null,
				$navCoverup = null,
				$bodyCoverup = null;
    
    
    // ----------------------------------------------------------------
    
    function _init() {
			
			var navCenteringContainerHtml = '<div class="nav-centering-container">';
			var $navCenteringContainer = $.browser.msie ? $(innerShiv(navCenteringContainerHtml, false)) : $(navCenteringContainerHtml);
			$nav.wrapInner($navCenteringContainer);
			
			var bodyBackgroundContainerHtml = '<div class="body-background-container"><div class="coverup"></div></div>';
			$bodyBackgroundContainer = $.browser.msie ? $(innerShiv(bodyBackgroundContainerHtml, false)) : $(bodyBackgroundContainerHtml);
			$body.prepend($bodyBackgroundContainer);
			
			var navBackgroundContainerHtml = '<div class="nav-background-container"><div class="coverup"></div></div>';
			$navbackgroundContainer = $.browser.msie ? $(innerShiv(navBackgroundContainerHtml, false)) : $(navBackgroundContainerHtml);
			$nav.prepend($navbackgroundContainer);
			
			$bodyBackgroundContainer = $('.body-background-container');
			$navBackgroundContainer = $('.nav-background-container');
				
			$bodyCoverup = $bodyBackgroundContainer.find('.coverup');
			$navCoverup = $navBackgroundContainer.find('.coverup');
    }; // _init()
    
    // ----------------------------------------------------------------
    
		function _updateBackground(backgroundColor, backgroundURI) {
				
			if (MomentumWW.IS_IPAD) {
				backgroundURI = backgroundURI.split('.jpg')[0] + '-ipad.jpg'
			}
			
			if (backgroundURI == _curBackgroundURI) { // dont update if we already have the same image
				return;
			}
			
			_curBackgroundURI = backgroundURI;
			
			if ($curBgImage != null) {
				$bodyCoverup.detach();
				$navCoverup.detach();
				// clear current background
				$bodyBackgroundContainer.empty();
				$navBackgroundContainer.empty();
			}
			
			if (_isLoading) {
				$newBgImage.unbind('load.preloadbackground');
				$newBgImage = null;
			}
			
			$newBgImage = $('<img/>');
			_isLoading = true;
			$newBgImage.bind('load.preloadbackground', _newBackgroundLoadComplete).attr('src', backgroundURI);
			
			
			var backgroundValue = backgroundColor;//+' url("'+backgroundURI+'") no-repeat center 0';
			$bodyBackgroundContainer.css({
									'background':backgroundValue
									});
			$navBackgroundContainer.css({
									'background':backgroundValue
									});
									
			$navCoverup.css({
									'background':backgroundValue
									});
			$bodyCoverup.css({
									'background':backgroundValue
									});
			
		};
		
		function _newBackgroundLoadComplete() {
			_isLoading = false;
			$newBgImage.unbind('load.preloadbackground');
			$curBgImage = $newBgImage;
			$newBgImage = null;
			
			var $navBgImg = $('<img/>');
			$navBgImg.attr('src', $curBgImage.attr('src'));
			
			var imageW = $curBgImage.attr('width');
			var imageH = $curBgImage.attr('height');
			
			// create an image wrapper that will get centered and "masked" by container
			var imageWrapHtml = '<div class="image-wrap">';
			var $navBgImageWrap = $.browser.msie ? $(innerShiv(imageWrapHtml, false)) : $(imageWrapHtml);
			var $curBgImageWrap = $.browser.msie ? $(innerShiv(imageWrapHtml, false)) : $(imageWrapHtml);
			$navBgImg.wrap($navBgImageWrap).parent().css({"width":imageW, "height":imageH});
			$curBgImage.wrap($curBgImageWrap).parent().css({"width":imageW, "height":imageH});
			
			/*
			if (isCentered) {
				$navBgImg.parent().css({
						"margin":"0 auto"
				});
				$curBgImage.parent().css({
						"margin":"0 auto"
				});
			}*/
						
			$bodyBackgroundContainer.append($curBgImage.parent());
			$navBackgroundContainer.append($navBgImg.parent());
			
			$navCoverup.css("opacity","1"); // coverup is used for making the image appear to fade in from a solid background color that extends beyond image area
			$bodyCoverup.css("opacity","1");
			$bodyBackgroundContainer.append($bodyCoverup);
			$navBackgroundContainer.append($navCoverup);
			
			$navCoverup.stop().animate({opacity: 0}, 1000, "easeOutQuad");
			$bodyCoverup.stop().animate({opacity: 0}, 1000, "easeOutQuad");

		};

    _init();
    
    return {
      updateBackground: function(backgroundColor, backgroundURI) {
					
				_updateBackground(backgroundColor, backgroundURI); 
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.backgroundManager = function(options) {
    
    var pluginName = "BackgroundManager";
    
    options = $.extend({}, $.fn.backgroundManager.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 BackgroundManager(options, this);
      $this.data(pluginName, pluginInstance);

			// Store a reference to the backgroundManager plugin on the global namespace object so that we can use it from anywhere background updates need to be made
      MomentumWW.backgroundManager = pluginInstance;

    });
    
  };
  
  // ==================================================================
  
  $.fn.backgroundManager.defaults = {
    
  };

	// ==================================================================
	// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	// ==================================================================
	// @MediaScroll plugin  
  var MediaScroll = function(options, elem) {
    
    var $this = $(elem),
				$thumbs = $this.find('a'),
				$eventListener = options.eventListener,
				$thumbsContainer = null,
    		$mediaScroll = null,
				$mediaScrollContainer,
				$prev = null,
				$next = null,
				_thumbScrollWidth = 0,
				_thumbScrollHeight = 0,
				_thumbsDisplayed = options.thumbsDisplayed,
				_orientation = options.orientation,
				_mediaScrollIndexMax = $thumbs.length - _thumbsDisplayed,
				_thumbRightMargin = 0,
				_thumbBottomMargin = 0,
				_thumbWidth = 0,
				_thumbHeight = 0,
				
				_curScrollIndex = null,
				_curSelectedId = null;
				
    
    // ----------------------------------------------------------------
    
    function _init() {				
      // setup media scroll thumbs
			
			_thumbWidth = $this.find('img:first').attr("width");
			_thumbHeight = $this.find('img:first').attr("height");
			
			// first make a container around all the thumbs
			$thumbsContainer = $thumbs.wrapAll('<div>').parent();
			$thumbsContainer.addClass('thumbs-container clearfix');
						
			// set up each thumb with a rollover image and media icon			
			$thumbs.each(function () {
				// wrap individual thumbs in a container div
				var $thumb = $(this),
				 		thumbContainerHtml = '<div class="media-thumb"></div>',
						$thumbContainer = $.browser.msie ? $(innerShiv(thumbContainerHtml, false)) : $(thumbContainerHtml);
						
				$thumb.wrap($thumbContainer)
				$thumbContainer =  $thumb.parent();
				
				// grab media name and place in a container for rollovers
				var $mediaName = $thumb.find('.media-name');
				$mediaName.detach();
		
				// add rollover image
				var rolloverSrc = $thumb.find('img').attr('data-rollover-uri');
				var $rolloverImg = $('<img class="rollover" src="'+rolloverSrc+'" width="'+_thumbWidth+'" height="'+_thumbHeight+'">');
				$thumb.append($rolloverImg);
				
				// add media logo
				var mediaType = $thumb.data('media-type'),
						mediaIconMarkup = '<div class="media-logo '+mediaType+'"></div>';
				var $mediaIcon = $.browser.msie ? $(innerShiv(mediaIconMarkup, false)) : $(mediaIconMarkup);
				$thumb.append($mediaIcon);				
				
				// center media logo
				var pos = $.getCenterPos($mediaIcon, $thumbContainer);
				$mediaIcon.css({
					"position":"absolute",
					"top":pos.top+"px",
					"left":pos.left+"px"
				});
				
				var mediaNameRolloverHtml = '<div class="media-name-rollover"></div>';
				var $mediaNameRollover= $.browser.msie ? $(innerShiv(mediaNameRolloverHtml, false)) : $(mediaNameRolloverHtml);
				$mediaNameRollover.append($mediaName);
				$thumb.append($mediaNameRollover);
				
			}); // $thumbs.each()
			
			// wrap the thumb container with a container that it will be positioned in when scrolling with the arrows
			var mediaScrollHtml = '<div class="media-scroll"></div>';
			$mediaScroll = $.browser.msie ? $(innerShiv(mediaScrollHtml, false)) : $(mediaScrollHtml);
			$thumbsContainer.wrap($mediaScroll);
			$mediaScroll = $thumbsContainer.parent();
			
			// wrap the media scroll container with the main container for this element that will contain the prev/next buttons and the mediaScroll thumbs
			var mediaScrollContainerHtml = '<div class="media-scroll-container"></div>';
			$mediaScrollContainer = $.browser.msie ? $(innerShiv(mediaScrollContainerHtml, false)) : $(mediaScrollContainerHtml);
			$mediaScroll.wrap($mediaScrollContainer);
			$mediaScrollContainer = $mediaScroll.parent();
						
			// create the previous/next (or up/down) buttons
			var prevBtnMkup = '<div class="media-scroll-btn prev"></a>'
			var nextBtnMkup = '<div class="media-scroll-btn next"></a>'
			$prev = $.browser.msie ? $(innerShiv(prevBtnMkup, false)) : $(prevBtnMkup);
			$next = $.browser.msie ? $(innerShiv(nextBtnMkup, false)) : $(nextBtnMkup);
			
			// add the buttons to the DOM around $mediaScroll
			$mediaScrollContainer.prepend($prev);
			$mediaScrollContainer.append($next);
			
			// size elements based on orientation
			_thumbRightMargin = Number($this.find('.media-thumb:first').css("margin-right").split("px")[0]);
			_thumbBottomMargin = Number($this.find('.media-thumb:first').css("margin-bottom").split("px")[0]);
			_thumbScrollWidth = _thumbWidth + _thumbRightMargin;
			_thumbScrollHeight = _thumbHeight + _thumbBottomMargin;
			
			
			if (MomentumWW.IS_IPAD) {
				$thumbsContainer.touchSwipe({	orientation:_orientation,
																			min_move: 20,
																			swipeLeft:_scrollPrev, 
																			swipeRight:_scrollNext,
																			swipeUp:_scrollNext,
																			swipeDown:_scrollPrev
																		});
			}
			
			_updateOrientation();
			
			if (_mediaScrollIndexMax == 0) {
				$prev.addClass('hidden');
				$next.addClass('hidden');
			}
			
			_curScrollIndex = 0;
			_updatePrevNextBtns();
    }; // _init()
    
    // ----------------------------------------------------------------

		function _activate() {
			//debug.log("MediaScroll :: _activate");
			// iPad Click Controls
            if (MomentumWW.IS_IPAD) {
                var ua = navigator.userAgent,
                event = (ua.match(/iPad/i)) ? "touchstart" : "click";
                $thumbs.bind('touchstart.mediascroll', _onThumbClick);
                if (!$prev.hasClass('hidden')) {
                    $prev.bind('touchstart.mediascroll', _onPrevClick);
                    $next.bind('touchstart.mediascroll', _onNextClick);
                }
            } else {
                // Browser controls
                $thumbs.bind('mouseenter.mediascroll', _onThumbMouseOver);
                $thumbs.bind('mouseleave.mediascroll', _onThumbMouseOut);
                $thumbs.bind('click.mediascroll', _onThumbClick);
                if (!$prev.hasClass('hidden')) {
                    $prev.bind('click.mediascroll', _onPrevClick);
                    $next.bind('click.mediascroll', _onNextClick);
                }
            }
		};

		function _deactivate() {
			// iPad Click Controls
            if (MomentumWW.IS_IPAD) {
                var ua = navigator.userAgent,
                event = (ua.match(/iPad/i)) ? "touchstart" : "click";
                $thumbs.unbind('touchstart.mediascroll', _onThumbClick);
                if (!$prev.hasClass('hidden')) {
                    $prev.unbind('touchstart.mediascroll', _onPrevClick);
                    $next.unbind('touchstart.mediascroll', _onNextClick);
                }
            } else {
                // Browser controls
                $thumbs.unbind('mouseenter.mediascroll', _onThumbMouseOver);
                $thumbs.unbind('mouseleave.mediascroll', _onThumbMouseOut);
                $thumbs.unbind('click.mediascroll', _onThumbClick);
                if (!$prev.hasClass('hidden')) {
                    $prev.unbind('click.mediascroll', _onPrevClick);
                    $next.unbind('click.mediascroll', _onNextClick);
                }
            }
		};
		
		// ----------------------------------------------------------------
		
		function _updateOrientation() {
			if (MomentumWW.IS_IPAD) {
				debug.log("MediaScroll :: _updateOrientation :: orientation :: "+_orientation);
				$thumbsContainer.data('TouchSwipe').updateOrientation(_orientation);
			}
			
			if (_orientation == "horizontal") {
				if ($mediaScroll.hasClass('vertical')) {
					$mediaScroll.removeClass('vertical');
					$thumbsContainer.removeAttr('style');
					$mediaScroll.removeAttr('style');
					$mediaScrollContainer.removeAttr('style');
				}
				$mediaScroll.addClass('horizontal');
				
				var scrollWindowWidth = (_thumbWidth * _thumbsDisplayed) + ((_thumbsDisplayed - 1) * _thumbRightMargin);
				$mediaScroll.css({
															'width':  scrollWindowWidth + "px",
															'height':  _thumbHeight + "px"
														});
														
				var destLeft = -_curScrollIndex * _thumbScrollWidth;
				$thumbsContainer.css({
																"width": $thumbs.length * _thumbScrollWidth+"px",
																"left": destLeft+"px"
															});
				
				// remove vertical class if it exists
				if ($prev.hasClass('vertical')) {
					$prev.removeClass('vertical');
					$prev.removeAttr('style');
				}
				if ($next.hasClass('vertical')) {
					$next.removeClass('vertical');
					$next.removeAttr('style');
				}
				
				$prev.addClass('horizontal');
				$next.addClass('horizontal');
				$prev.css('height',  _thumbHeight + "px");
				$next.css('height',  _thumbHeight + "px");
				
			} else { // vertical orientation
				if ($mediaScroll.hasClass('horizontal')) {
					$mediaScroll.removeClass('horizontal');
					$thumbsContainer.removeAttr('style');
					$mediaScroll.removeAttr('style');
					$mediaScrollContainer.removeAttr('style');
				}
				$mediaScroll.addClass('vertical');
						
				var scrollWindowHeight = (_thumbHeight * _thumbsDisplayed) + ((_thumbsDisplayed - 1) * _thumbBottomMargin);
				$mediaScroll.css({
															'width':  _thumbWidth + "px",
															'height':  scrollWindowHeight + "px"
														});
				$mediaScrollContainer.css({
																		'width':  _thumbWidth + "px"
																	});
				var destTop = -_curScrollIndex * _thumbScrollHeight;
				$thumbsContainer.css({	
																"width": _thumbWidth+"px",
																'top': destTop+"px"
															});
				
				// remove horizontal class if it exists
				if ($prev.hasClass('horizontal')) {
					$prev.removeClass('horizontal');
					$prev.removeAttr('style');
				}
				if ($next.hasClass('horizontal')) {
					$next.removeClass('horizontal');
					$next.removeAttr('style');
				}
															
				$prev.addClass('vertical');
				$next.addClass('vertical');
				$prev.css('width',  _thumbWidth + "px");
				$next.css('width',  _thumbWidth + "px");
			}
			
			
			//Fix for home video section were the video would disaper on orientation change.
			if (MomentumWW.IS_IPAD) {		
			
				if (MomentumWW.currentSection == "home") {
					var featureWork = $("#feature-work").data("FeatureWork");
					if (featureWork) {
						featureWork.setMediaDetail(_curSelectedId);						
					}	
				}
				
			}		
			
			
		}
		
		// ----------------------------------------------------------------
				
		function _onThumbMouseOver () {
			var $thumb = $(this);
			if (!$thumb.hasClass('selected'))
				_doMouseOver($thumb);
		};
		
		function _doMouseOver($thumb) {
			$thumb.find('.rollover').stop().animate({opacity:0.5}, 250);
			$thumb.find('.media-logo').stop().animate({opacity:0}, 250);
			$thumb.find('.media-name-rollover').stop().animate({bottom:0}, 250);
		};
		
		function _onThumbMouseOut () {
			var $thumb = $(this);
			if (!$thumb.hasClass('selected'))
				_doMouseOut($thumb);
		};
		
		function _doMouseOut($thumb) {
			$thumb.find('.rollover').stop().animate({opacity:1}, 250);
			$thumb.find('.media-logo').stop().animate({opacity:1}, 250);
			$thumb.find('.media-name-rollover').stop().animate({bottom:-70}, 250);
		};
		
		function _onThumbClick(e) {
			e.preventDefault();
			var $thumb = $(this);
			_doMouseOut($thumb);
			if (!$thumb.hasClass('selected')) {
				var destId = $thumb.data('media-id');
				$eventListener.trigger(MomentumWW.events.MEDIA_SELECTED, [destId]);
			}
		};
		
		function _setThumbById(id) {
			if (_curSelectedId != id)
			{
				if (_curSelectedId != null)
				{
					// deactivaete cur selected media
					var $curThumb = $this.find('.media-thumb a[data-media-id="'+_curSelectedId+'"]');
					$curThumb.removeClass('selected');
					$curThumb.find('.media-logo').stop().animate({opacity:1}, 250);
					_doMouseOut($curThumb);
				}
				
				if (id != null) {
					// update thumb
					var $thumb = $this.find('.media-thumb a[data-media-id="'+id+'"]');
					$thumb.addClass('selected');
					$thumb.find('.rollover').stop().animate({opacity:0}, 250);
					$thumb.find('.media-logo').stop().animate({opacity:0}, 250);
				}
				
				// update stored index
				_curSelectedId = id;
			}
			
		};
		
		// ----------------------------------------------------------------
		
		function _onPrevClick(e) {
      e.preventDefault();
      _scrollPrev();
    };
		
		function _scrollPrev() {
			if (_curScrollIndex > 0) {
				_curScrollIndex--;
				
				if (_orientation == "horizontal") {
					var destLeft = -_curScrollIndex * _thumbScrollWidth;
					$thumbsContainer.stop().animate({left:destLeft}, 500, 'easeOutExpo');
				} else {
					var destTop = -_curScrollIndex * _thumbScrollHeight;
					$thumbsContainer.stop().animate({top:destTop}, 500, 'easeOutExpo');
				}

				_updatePrevNextBtns();
			}
		};

    // ----------------------------------------------------------------

    function _onNextClick(e) {
      e.preventDefault();
		 	_scrollNext();
    };

		function _scrollNext() {
			if (_curScrollIndex < _mediaScrollIndexMax) {
				_curScrollIndex++;
				
				if (_orientation == "horizontal") {
					var destLeft = -_curScrollIndex * _thumbScrollWidth;
					$thumbsContainer.stop().animate({left:destLeft}, 500, 'easeOutExpo');
				} else {
					debug.log("_scrollNext :: animate style 'top' ");
					var destTop = -_curScrollIndex * _thumbScrollHeight;
					$thumbsContainer.stop().animate({top:destTop}, 500, 'easeOutExpo');
				}
				
				_updatePrevNextBtns();
			}
		};

		// ---------------------------------------------------------------- 

		function _updatePrevNextBtns() {
			//debug.log("_updatePrevNextBtns :: _curScrollIndex: "+_curScrollIndex);
			if (_curScrollIndex == 0) {
				$prev.addClass('disabled');
			} else if ($prev.hasClass('disabled')) {
				$prev.removeClass('disabled');
			}
			
			if (_curScrollIndex == _mediaScrollIndexMax) {
				$next.addClass('disabled');
			} else if ($next.hasClass('disabled')) {
				$next.removeClass('disabled');
			}
		};

    // ----------------------------------------------------------------
		
		function _setOrientation(orientation) {
			if (_orientation != orientation) {
				_orientation = orientation;
				_updateOrientation();
			}
		}
		
		// ----------------------------------------------------------------
		
    _init();
    
    return {
			activate: function() {
				_activate();
			},
			deactivate: function() {
				_deactivate();
			},
      setThumbById: function(id) {
				_setThumbById(id);
			},
			setOrientation: function(orientation) {
				_setOrientation(orientation);
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.mediaScroll = function(options) {
    
    var pluginName = "MediaScroll";
    
    options = $.extend({}, $.fn.mediaScroll.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 MediaScroll(options, this);
      $this.data(pluginName, pluginInstance);
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.mediaScroll.defaults = {
    thumbsDisplayed: 3,
		orientation: "horizontal"
  };

	// ==================================================================
	// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	// ==================================================================

	/*
	  @RibbonNav plugin
	
		- call this plugin on the container where the ribbon nav is needed. need to passit a Jquery object containing elements for the section s that the nav buttons correspond to
		- each of the items needs to have a "data-title" attribute that will be used as the label for the buttons
	*/
	var RibbonNav = function(options, elem) {

    var $this = $(elem),
				$ribbonSections = options.ribbonSections,
				$ribbonContainer = null,
				$ribbonNav = null,
				$ribbons = null,
				_curBtnIndex = -1;

    // ----------------------------------------------------------------

    function _init() {
      var ribbonNavMkup = '<div class="ribbon-nav"></div>';
			$ribbonNav = $.browser.msie ? $(innerShiv(ribbonNavMkup, false)) : $(ribbonNavMkup);

			$ribbonSections.each(function (index) {
				$ribbonNavBtn = _createRibbonNavBtn($(this).data('title'), index);
				$ribbonNav.append($ribbonNavBtn);
				$ribbonNavBtn.find('.expanded').css('z-index', MomentumWW.ribbonNavDepth);
				_doRibbonNavMouseOut($ribbonNavBtn); // run the opacity animation to fix buttons showing up on init in IE
				MomentumWW.ribbonNavDepth--;
			});

			$this.append($ribbonNav);

			_activate();
    }; // _init()

    // ----------------------------------------------------------------

		function _createRibbonNavBtn(title, index) {
			var btnMkup = '<div class="ribbon-nav-btn ribbon'+(index+1)+' clearfix" data-index="'+index+'">'+
											'<div class="expanded">'+
												'<div class="shadow"></div>'+
												'<div class="top"></div>'+
												'<div class="left"></div>'+
												'<div class="title"><p>'+title+'</p></div>'+
												'<div class="right"></div>'+
											'</div>'
										'</div>';
			return $.browser.msie ? $(innerShiv(btnMkup, false)) : $(btnMkup);			
		};

		function _onRibbonNavClick(e) {
			var $navBtn = $(this);
			
			if (!$navBtn.hasClass('selected')) {
				var ribbonIndex = $navBtn.data('index');
				$this.trigger(MomentumWW.events.RIBBON_NAV_CLICK, [ribbonIndex]);
			}
		};

		function _onRibbonNavMouseOver(e) {
			var $navBtn = $(this);
			if (!$navBtn.hasClass('selected')) {
				_doRibbonNavMouseOver($navBtn);
			}
		};

		function _doRibbonNavMouseOver($navBtn) {
			var $expanded = $navBtn.find('.expanded');
			//$expanded.stop().animate({width:165, opacity:1}, 550, "easeInOutExpo");
			$expanded.stop().animate({opacity:1}, 550, "easeInOutExpo");
		};

		function _onRibbonNavMouseOut(e) {
			var $navBtn = $(this);

			if (!$navBtn.hasClass('selected')) {
				_doRibbonNavMouseOut($navBtn);
			}
		};

		function _doRibbonNavMouseOut($navBtn) {
			var $expanded = $navBtn.find('.expanded');
			//$expanded.stop().animate({width:34, opacity:0}, 550, "easeInOutExpo");
			$expanded.stop().animate({opacity:0}, 550, "easeInOutExpo");
		};

		function _selectBtn(index) {
			if (_curBtnIndex == index)
				return;

			if (_curBtnIndex != -1) {
				// we have a current ribbon - need to decativate it first
				var $curBtn = $ribbonNav.find('.ribbon-nav-btn[data-index="'+_curBtnIndex+'"]');
				$curBtn.removeClass('selected');
				_doRibbonNavMouseOut($curBtn);
			}

			$destBtn = $ribbonNav.find('.ribbon-nav-btn[data-index="'+index+'"]');
			$destBtn.addClass('selected');
			_doRibbonNavMouseOver($destBtn);

			_curBtnIndex = index;
		};

		function _activate() {
			$this.find('.ribbon-nav-btn')
				.bind('click.ribbonNav', _onRibbonNavClick)
				.bind('mouseenter.ribbonNav', _onRibbonNavMouseOver)
				.bind('mouseleave.ribbonNav', _onRibbonNavMouseOut);
		};

    _init();

    return {
      setSelectedBtn: function (index) {
				_selectBtn(index);
			}
    };

  };

  // ==================================================================

  $.fn.ribbonNav = function(options) {

    var pluginName = "RibbonNav";

    options = $.extend({}, $.fn.ribbonNav.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 RibbonNav(options, this);
      $this.data(pluginName, pluginInstance);

    });

  };

  // ==================================================================

  $.fn.ribbonNav.defaults = {
		ribbonSections:null
  };


  var SocialFeedScroll = function(options, elem) {

    var $this = $(elem),
				$feedDisplay = $this.find('.feed-display'),
				$feedScroll = $this.find('.feed-scroll'),
				$scrollContent = null,
				$scrollBarContainer = null,
				_scrollContentH,
				_pSroll;


    // ----------------------------------------------------------------

    function _init() {
			var scrollContentHtml = '<div class="scroll-content"></div>';
			$scrollContent = $.browser.msie ? $(innerShiv(scrollContentHtml, false)) : $(scrollContentHtml);
			$feedDisplay.wrapInner($scrollContent);
			var scrollBarContainerHtml = '<div class="scroll-bar-container"><div class="scroll-bar"></div></div>';
			$scrollBarContainer = $.browser.msie ? $(innerShiv(scrollBarContainerHtml, false)) : $(scrollBarContainerHtml);
      $feedScroll.append($scrollBarContainer);
			
			// reset references after DOM changes
			$scrollContent = $this.find('.scroll-content'); 
			$scrollBarContainer = $this.find('.scroll-bar-container');
			
			if (MomentumWW.IS_IPAD) {
				// setup touch scrolling plugin
				//debug.log("SETUP IPAD SCROLL SOCIAL :: ");
				$feedDisplay.touchSlider({content:$scrollContent});
				$scrollBarContainer.addClass('hidden');
			} else {
				$this.find('.scroll-bar').slider({
					orientation: "vertical",
					value: 100,
					slide: _onSlide
				});
			}
				
			_update();
    }; // _init()

    // ----------------------------------------------------------------

		function _update() {
			if (MomentumWW.IS_IPAD) {
				return; // dont need to show/hide the scroll bar for ipad
			}
			
			_scrollContentH = $scrollContent.outerHeight() - $feedDisplay.outerHeight();
			
			if (_scrollContentH > 0) { 
				if ($scrollBarContainer.hasClass('hidden'))
					$scrollBarContainer.removeClass('hidden');
					
			} else if (!$scrollBarContainer.hasClass('hidden')) {
					$scrollBarContainer.addClass('hidden');
			}
		}
		
		// ----------------------------------------------------------------
		
    function _onSlide( event, ui ) {

			var scrollPct = ui.value * 0.01;
			var destTop = scrollPct * _scrollContentH - _scrollContentH;
			//debug.log("SocialFeedScroll : _onSlide :: destTop: "+destTop );
			$scrollContent.css("top", destTop+"px");
		};

    _init();

    return {
			update: function() {
				_update();
			}
    };

  };

  // ==================================================================

  $.fn.socialFeedScroll = function(options) {

    var pluginName = "SocialFeedScroll";

    options = $.extend({}, $.fn.socialFeedScroll.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 SocialFeedScroll(options, this);
      $this.data(pluginName, pluginInstance);

    });

  };

  // ==================================================================

  $.fn.socialFeedScroll.defaults = {

  };
  
  // ====================================================================
  // @shiv plugin 
  // - wraps the generation of jQuery element with innerShiv needed for older IE versions 
  //   to support CSS on dynamically added html5 elements
  // ====================================================================
  $.shiv = function(html) {
    if ($.browser.msie && (parseInt($.browser.version.split(".")[0], 10) < 9) ) {
      return $(innerShiv(html, false));
    } else {
      return $(html);
    }
  };

  var TouchSlider = function(options, elem) {
    
    var $this = $(elem),
				$content = options.content,
				_currTouchID = false,
        _touchStartX = -1,
				_touchStartY = -1,
				_contentMinY = 0; //$this.outerHeight() - $content.outerHeight(),
				_contentMaxY = 0;
							    		
    
    // ----------------------------------------------------------------
    
    function _init() {
			$this.bind('touchstart.touchslider', _onTouchStart);
      $this.bind('touchend.touchslider', _onTouchEnd);
    }; // _init()
		
	 function _onTouchStart(event) {			
			if (_contentMinY == 0) {
				_contentMinY = $this.outerHeight() - $content.outerHeight();
			}
			
      // See if we've got a touch already.
      var e = event.originalEvent;
      if(_currTouchID === false) {
        e.preventDefault();
				e.stopPropagation();

				MomentumWW.contentScroll.enabled = false;
				//$('#content-scroll-area').addClass('touchfix');
				
        var touch = e.targetTouches[0];
        _currTouchID = touch.identifier;        
        _touchStartX = touch.pageX;
				_touchStartY = touch.pageY;
				
				$this.bind('touchmove.touchslider', _onTouchMove);
      }
    };

    function _onTouchMove(event) {
			
      var e = event.originalEvent;
      if(_currTouchID !== false) {
        // Find the location of this touch.
        var touch = null,
            numTouches = e.changedTouches.length;
        for(var i = 0; i < numTouches; i++) {
          if(e.changedTouches[i].identifier == _currTouchID) {
            touch = e.changedTouches[i];
            break;
          }
        }
        if(touch != null) {
          // Get the diff.
          e.preventDefault();
					e.stopPropagation();
					
					var pageX = touch.pageX;
					var pageY = touch.pageY;
          var diffX = pageX - _touchStartX;
					var diffY = pageY - _touchStartY;
          //debug.log("_onTouchMove :: "+diffX);
					
					_touchStartX = pageX;
					_touchStartY = pageY;
					
					_updateContentPos(diffX, diffY);
        }
      }
    };
		
		function _onTouchEnd(event) {
      var e = event.originalEvent;
      if(_currTouchID !== false) {
        // Find the location of this touch.
        var touch = null,
            numTouches = e.changedTouches.length;
        for(var i = 0; i < numTouches; i++) {
          if(e.changedTouches[i].identifier == _currTouchID) {
            touch = e.changedTouches[i];
            break;
          }
        }

        if(touch != null) {
          e.preventDefault();
					e.stopPropagation();

          _currTouchID = false;
          _touchStartX = -1;

					MomentumWW.contentScroll.enabled = true;
					//$('#content-scroll-area').removeClass('touchfix');
					
					$this.unbind('touchmove.touchslider', _onTouchMove);
        }
      }
    };

		function _updateContentPos(diffX, diffY) {
			var translateStr = $content.css('-webkit-transform');
			var contentY = (translateStr == "none") ? 0 : parseInt(translateStr.substring(translateStr.lastIndexOf(',')+2, translateStr.lastIndexOf(')') ), 10);
			
			var destY = contentY + diffY;
			if (destY < _contentMinY) {
				destY = _contentMinY;
			}
			
			if (destY > _contentMaxY) {
				destY = _contentMaxY;
			}
			
			$content.css('-webkit-transform', 'translate(0,'+destY+'px)');
		};
    
    // ----------------------------------------------------------------
    
    _init();
    
    return {
      
    };
    
  };
  
  // ==================================================================
  
  $.fn.touchSlider = function(options) {
    
    var pluginName = "TouchSlider";
    
    options = $.extend({}, $.fn.touchSlider.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 TouchSlider(options, this);
      $this.data(pluginName, pluginInstance);
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.touchSlider.defaults = {
    content:null
  };



	var TouchSwipe = function(options, elem) {
    
    var $this = $(elem),
				_orientation = options.orientation,
        _touchStartX = -1,
				_touchStartY = -1,
				_currTouchID = false,
        _isMoving = false;
							    		
    // ----------------------------------------------------------------
    
    function _init() {
			//debug.log("TouchSwipe :: init()");
			$this.bind('touchstart.touchswipe', _onTouchStart);
      $this.bind('touchend.touchswipe', _onTouchEnd);
			
    }; // _init()
		
	 function _onTouchStart(event) {
      // See if we've got a touch already.
      var e = event.originalEvent;
      if(_currTouchID === false) {
        e.preventDefault();
				
        var touch = e.targetTouches[0];
        _currTouchID = touch.identifier;        
        _touchStartX = touch.pageX;
				_touchStartY = touch.pageY;
				
				MomentumWW.contentScroll.enabled = false;
				_isMoving = true;
				$this.bind('touchmove.touchswipe', _onTouchMove);
      }
    };

    function _onTouchMove(event) {
      var e = event.originalEvent;
      if(_currTouchID !== false) {
        // Find the location of this touch.
        var touch = null,
            numTouches = e.changedTouches.length;
        for(var i = 0; i < numTouches; i++) {
          if(e.changedTouches[i].identifier == _currTouchID) {
            touch = e.changedTouches[i];
            break;
          }
        }

        if(touch != null) {
          // Get the diff.
          e.preventDefault();
					var touchX = touch.pageX;
					var touchY = touch.pageY;
          var diffX = touchX - _touchStartX;
					var diffY = touchY - _touchStartY;
       //   debug.log("TouchSwipe :: _orientation "+_orientation);
					
					if (_orientation == "horizontal") {
						if(Math.abs(diffX) >= options.min_move) {
							_cancelTouch();
              if(diffX > 0) {
                options.swipeLeft();
              } else {
                options.swipeRight();
              }
						}
					} else if (_orientation == "vertical") {
						if(Math.abs(diffY) >= options.min_move) {
							_cancelTouch();
              if(diffY > 0) {
                options.swipeDown();
              } else {
                options.swipeUp();
              }
						}
					}
				
        }
      }
    };
		
		function _onTouchEnd(event) {
      var e = event.originalEvent;
      if(_currTouchID !== false) {
        // Find the location of this touch.
        var touch = null,
            numTouches = e.changedTouches.length;
        for(var i = 0; i < numTouches; i++) {
          if(e.changedTouches[i].identifier == _currTouchID) {
            touch = e.changedTouches[i];
            break;
          }
        }

        if(touch != null) {
          e.preventDefault();
					_cancelTouch();
        }
      }
    };

		function _cancelTouch() {
			_currTouchID = false;
      _touchStartX = -1;
			_touchStartY = -1;
			_isMoving = false;
			$this.unbind('touchmove.touchswipe', _onTouchMove);
			MomentumWW.contentScroll.enabled = true;
		}

    // ----------------------------------------------------------------
    
    _init();
    
    return {
      updateOrientation: function(orientation) {
				_orientation = orientation;
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.touchSwipe = function(options) {
    
    var pluginName = "TouchSwipe";
    
    options = $.extend({}, $.fn.touchSwipe.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 TouchSwipe(options, this);
      $this.data(pluginName, pluginInstance);
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.touchSwipe.defaults = {
		orientation:'horizontal',
    min_move: 20,
	  swipeLeft: function() { alert("left"); },
		swipeRight: function() { alert("right"); },
		swipeUp: function() { alert("up"); },
		swipeDown: function() { alert("down"); }
  };


  // ====================================================================
  // @TouchTap plugin
  // ====================================================================
  var TouchTap = function(options, elem) {
    
    var $this = $(elem),
        _currTouchID = false;
    
    
    // ----------------------------------------------------------------
    
    function _init() {
      
    	$this.bind('touchstart.touchtap', _onTouchStart);
      $this.bind('touchend.touchtap', _onTouchEnd);

    }; // _init()

    function _onTouchStart(event) {
      var e = event.originalEvent;
      if(_currTouchID === false) {
        e.preventDefault();

        var touch = e.targetTouches[0];
        _currTouchID = touch.identifier;

    		$this.bind('touchmove.touchtap', _onTouchMove);
      }
    };
    
    function _onTouchMove(event) {
      var e = event.originalEvent;
      if(_currTouchID !== false) {
        // Find the location of this touch.
        var touch = null,
            numTouches = e.changedTouches.length;
        for(var i = 0; i < numTouches; i++) {
          if(e.changedTouches[i].identifier == _currTouchID) {
            touch = e.changedTouches[i];
            break;
          }
        }

        if(touch != null) {
          e.preventDefault();
          _cancelTouch();
        }
      }
    };
    
  	function _onTouchEnd(event) {
      var e = event.originalEvent;
      
      if(_currTouchID !== false) {
        // Find the location of this touch.
        var touch = null,
            numTouches = e.changedTouches.length;
        for(var i = 0; i < numTouches; i++) {
          if(e.changedTouches[i].identifier == _currTouchID) {
            touch = e.changedTouches[i];
            break;
          }
        }

        if(touch != null) {
          e.preventDefault();
          _touchtap();
					_cancelTouch();
        }
      }
      
    };
    
    function _touchtap() {
      $this.trigger('tap.touchtap');
    }
    
    function _cancelTouch() {
			_currTouchID = false;
			$this.unbind('touchmove.touchtap', _onTouchMove);
		};
    
    // ----------------------------------------------------------------
    
    _init();
    
    return {
      
    };
    
  };
  
  // ==================================================================
  
  $.fn.touchTap = function(options) {
    
    var pluginName = "TouchTap";
    
    options = $.extend({}, $.fn.touchTap.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 TouchTap(options, this);
      $this.data(pluginName, pluginInstance);
      
    });
    
  };
  
  // ==================================================================
  
  $.fn.touchTap.defaults = {
    tap: function(){ alert("tap"); }
  };
  
  $.fn.preventDefaultClick = function() {
    
    return this.each(function() {
      
      $(this).bind('click', function (e) {e.preventDefault();});
      
    });
  }

})(jQuery); // end global jQuery plugins

jQuery(function($){
  
  // Initialize the page on DOM ready.
  MomentumWW.initialize($);
  
});

(function ($) {

  // Log all jQuery AJAX requests to Google Analytics
  $(document).ajaxSend(function(event, xhr, settings){
    if (typeof _gaq !== "undefined" && _gaq !== null) {
      _gaq.push(['_trackPageview', settings.url]);
    }
  });

})(jQuery);
