/****************************************************
 * Copyright (c) Legwork Studio. All Rights Reserved.
 * Updated by: Wigz + Jos, 10-Oct-2011
 *
 * Now let's get serious.
 ****************************************************
/                                                  */

var Athenos = Athenos || {};

Athenos.zone = {
	"locations": [],
	"divisions": {}
};

Athenos.products = {};

(function($, Modernizr){
	var self = this;

	self.Actions = (function(){
		var pub = {},
			$wn,
			$body,
			$wrapper,
			$mainNav,
			$mainA,
			$flyouts,
			$subZones,
			$motions,
			$socialsTop,
			$buriedAnchors,
			navLock = true,
			hashLock = false,
			keysLock = false,
			st, bodW,
			activeZone = '',
			indTimeout = 0,
			flyoutCont = {},
			currentLeft,
			collections,
			appWidth = 0,
			flyoutRel = 0,
			productOffset = 0,
			vendorPre = _supports('transitionDuration'),
			isSafari = BrowserDetect.browser.toLowerCase() == 'safari',
			isMacChrome = BrowserDetect.browser.toLowerCase() == 'chrome' && BrowserDetect.OS.toLowerCase() == 'mac',
			
			ANIMATEABLE_CLASS = 'athenos-animateable',
			CROSSWISE_CLASS = 'motion-item-crosswise';
		
			
		/****************************************************
		 * init:void
		 * 
		 * Not much to say here, how's the weather?
		 ****************************************************
		/                                                  */
		pub.init = function(){
			// unqueue
			try {
				self.unqueue();
			} 
			catch(e) {}
			
			$body = $('body');
			$wn = $(window);
			$wrapper = $('#wrapper');
			$motions = $('#motions');
			
			if(isSafari)	{ $('html').addClass('safari'); }
			if(isMacChrome) { $('html').addClass('mac-chrome'); }
			
		};
		
		/****************************************************
		 * initDeux:void
		 * 
		 * second round of inits
		 ****************************************************
		/                                                  */
		pub.initDeux = function(){
			var arr;
			
			_buildMotionObjects();
			collections = _buildProgressives();
			_buildHeaderNav();
			
			$socialsTop = $('#socials-motion');
			$buriedAnchors = $('#socials-motion-layer_5').find('a')
								.add($('#socials-motion-layer_3').find('a'))
								.add($('#socials-motion-layer_2').find('a'));
			
			$mainNav = $('nav');
			$flyouts = $('.flyout');
			$mainA = $('#main-nav').find('a');
			$subZones = $('');
			arr = $flyouts.find('a').get();
			
			arr.sort(function(a, b) {
				var compA = parseInt($(a).attr('rel'), 10);
				var compB = parseInt($(b).attr('rel'), 10);
				return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
			});
			$.each(arr, function(idx, itm) { $subZones.push($(itm)); });
			$subZones.push($('#home-btn'), $('#facebook-btn'), $('#youtube-btn'), $('#twitter-btn'), $('#locator-btn'), $('<a rel="' + Math.pow(10, 6) + '" />'));
			
			$mainNav
			.mouseenter(function(e) {
				e.preventDefault();
			})
			.click(function(e) {
				e.preventDefault();
			});
			
			_observeSomeSweetEvents();
		};
		
		/****************************************************
		 * introFinishedBinds:void
		 * 
		 * Called from Athenos.Intro when intro finishes.
		 ****************************************************
		/                                                  */
		pub.introFinishedBinds = function() {
			navLock = false;
			
			$mainNav
			.unbind()
			.mouseleave(_hideMenus)
			.click(_mainNavClick);

			$mainA.mouseenter(_showMenu);
			
			$wn.bind({
				'resize': _windowResize,
				'scroll': _scrollUpdates,
				'athenos::newActiveZone': _newActiveZone,
				'hashchange': _hashChange
			})
			.trigger('resize')
			.trigger('hashchange');
			
			// IE initally fires the event twice with trigger (real cool guys)
			// so, initial manual call to the scroll event handler
			_scrollUpdates();
			_endAnimator();
			
		};
		
		/****************************************************
		 * _observeSomeSweetEvents:void
		 * 
		 * Add event listeners.
		 ****************************************************
		/                                                  */
		function _observeSomeSweetEvents(){
			var vp = document.getElementById('tv_video-item');
			
			$('.motion-item-card a').click(function(e) {
				e.preventDefault();
				
				$('#nutrition-info').modal({
					background: ['#000', 'none', 0.85, true],
					openNow: true,
					onOpened: function() {
						var $this = $(this),
							ob = Athenos.products[$(e.currentTarget).attr('id').replace('-link', '')];
						
						// close
						$this.find('.close-btn').unbind().click(function() {
							$this.modal('close');
						});
						
						$('#nutrition-info-top').html(ob.top);
						$('#nutrition-info-content').html(ob.bottom);
					},
					onClosed: function() {
						$('#nutrition-info-top').html('');
						$('#nutrition-info-content').html('');
					}
				});
			});
			
			$('#legal-btn, #privacy-btn').click(function(e) {
				e.preventDefault();
				var m = $(this).attr('id') === 'legal-btn' ? 'legal' : 'privacy';
				
				$('#' + m + '-modal').modal({
					background: ['#000', 'none', 0.85, true],
					openNow: true,
					onOpened: function() {
						var $this = $(this),
							$cnt = $this.find('#' + m + '-content'),
							src = m + '.html #' + m;
						
						// close
						$this.find('.close-btn').unbind().click(function() {
							$this.modal('close');
						});
						
						if($cnt.children().length === 0) {
							$cnt.load(src);
						}
					}
				});
			});
				
			$socialsTop
			.click(function(e) {
				e.stopPropagation();
				var $obj = _hitTest($buriedAnchors, e.pageX, e.pageY);
				if($obj !== false) $obj.trigger('click');
			})
			.mousemove(function(e) {
				var $obj = _hitTest($buriedAnchors, e.pageX, e.pageY);
				$socialsTop.css('cursor', 'auto');
				if($obj !== false) $socialsTop.css('cursor', 'pointer');
			});
			
			$buriedAnchors.click(function(e) {
				e.stopPropagation();
				if($(e.currentTarget).attr('id') == 'yiayia-link-item'){
					_yiaYiaClick();
				} else {
					window.location.href = $(this).attr('href');
				}
			});
			
			function _yiaYiaClick(){
				$('#yiayia-link-modal').modal({
					background: ['#000', 'none', 0.85, true],
					openNow: true,
					onOpened: function() {
						var $this = $(this);
							
						// close
						$this.find('.close-btn').unbind().click(function() {
							$this.modal('close');
						});
					}
				});
			}
			
			if(Modernizr.video) {
				vp.addEventListener('canplay', _play, false);
				vp.addEventListener('ended', _play, false);
			}
			
			function _play() {
				vp.play();
			}
			
			$('.'+ANIMATEABLE_CLASS).live('athenos::animate', _animator);
			
			$(document).bind('keydown', _keydown);
			
			$body
				.bind('productsComplete', _fadeInWhenReady)
				.bind('googPageLoad', _googPageLoad)
				.image_eventer({collections: collections}, 'productsComplete');
		}
		
		/****************************************************
		 * _showMenu:void
		 * 
		 * Show subnav menu.
		 ****************************************************
		/                                                  */
		function _showMenu() {
			var $current = $('#' + $(this).attr('id').replace('-btn', '-flyout'));
			
			if($current.hasClass('open')) return;
			_hideMenus();
			$current.addClass('open').animate({'top':'78px', 'opacity':'1'}, 250, 'swing');
		}
		
		/****************************************************
		 * _hideMenus:void
		 * 
		 * Hide the subnav menus.
		 ****************************************************
		/                                                  */
		function _hideMenus() {
			$flyouts.removeClass('open').css({'top':'50px', 'opacity':'0'});
		}
		
		/****************************************************
		 * _fadeInWhenReady:void
		 * 
		 * Fade in product images once available
		 ****************************************************
		/                                                  */
		function _fadeInWhenReady(e, imgsrc){
			$('.motion-item-img-wrapper img[src="'+imgsrc.join('')+'"]').fadeIn().removeClass('hidden');
		}
		
		/****************************************************
		 * _scrollUpdates:void
		 * 
		 * Scroll goodness. Triggered on scroll
		 ****************************************************
		/                                                  */
		function _scrollUpdates() {
			var newZone;
			
			currentLeft = $wn.scrollLeft();
			newZone = _isNewActiveZone();
			
			if(typeof(newZone) !== 'undefined') {
				$('.'+ANIMATEABLE_CLASS).trigger('athenos::animate');
				if(newZone !== false) $wn.trigger('athenos::newActiveZone', [newZone]);
			} else {
				$('.'+ANIMATEABLE_CLASS).trigger('athenos::animate');
				activeZone = 'undefined';
				if($.browser.msie || isMacChrome) $('.motion-group').show();
			}
			
			clearTimeout(st);
			st = setTimeout(_scrollComplete, 250);
		}
		
		/****************************************************
		 * _scrollComplete:void
		 * 
		 * Scroll is done, son!
		 ****************************************************
		/                                                  */
		function _scrollComplete() {
			var $current,
				$relative,
				newHash,
				query_string = location.search || '';
			
			// highlight the proper section
			$subZones.each(function() {
				if(currentLeft < (parseInt($(this).attr('rel'), 10) - (appWidth / 2))) {
					$relative = $current.closest('ul').hasClass('flyout') ? $('#' + $current.closest('ul').attr('id').replace('-flyout', '-btn')) : $current;
				
					$mainA.removeClass('selected');
					$relative.addClass('selected');
					
					//You can thank IE7 for this...
					newHash = $current.attr('href').replace('#', '');
					if(newHash.indexOf(location.protocol+'//'+location.host) !== -1 ){
						newHash = newHash.replace(location.protocol+'//'+location.host, '');
					} else {
						newHash = '/'+newHash;
					}
					
					hashLock = true;
					location.hash = newHash;
					
 					//push the 'page' change
					_gaq.push(['pageTracker._trackPageview',location.pathname + query_string  + newHash]);
					
					return false;
				}
				
				$current = $(this);
			});
		}
		
		/****************************************************
		 * _isNewActiveZone:string if true || false
		 * 
		 * Checks if we have a new active zone.
		 ****************************************************
		/                                                  */
		function _isNewActiveZone(){
			var i,
				az,
				low,
				high;
                
			for(i = (Athenos.zone.locations.length - 1); i >= 0; i--){
                low = Athenos.zone.locations[i][0];
                high = Athenos.zone.locations[i][1];
                
                if(currentLeft >= (low - appWidth) && currentLeft < low) {
                	$motions.css('margin-left', Athenos.zone.locations[i][3] + (low - currentLeft) + 'px');
                	break;
                } else if(currentLeft >= low && currentLeft <= high) {                 
                    az = Athenos.zone.locations[i][2];
                    break;
                }
            }
            
            if(activeZone !== az) return az;
            else return false;
		}
		
		/****************************************************
		 * _newActiveZone:void
		 * 
		 * Triggered on custom newActiveZone
		 ****************************************************
		/                                                  */
		function _newActiveZone(e, az) {
			activeZone = az;
			_offsetZone();
			_sparkleMotion();
		}
		
		/****************************************************
		 * _offsetActiveZone:void
		 * 
		 * Set the offset of motions to the passed zone
		 ****************************************************
		/                                                  */
		function _offsetZone() {
			if(typeof(activeZone) === 'undefined' || activeZone === '') return;
			var i = 0;
			
			for(i = (Athenos.zone.locations.length - 1); i >= 0; i--){
				if(Athenos.zone.locations[i][2] === activeZone) $motions.css('margin-left', Athenos.zone.locations[i][3] + 'px');
            }
		}
		
		/****************************************************
		 * _sparkleMotion:ob
		 * 
		 * Returns the ob representation of DOM items.
		 ****************************************************
		/                                                  */
		function _sparkleMotion(){
			$('.'+ANIMATEABLE_CLASS).trigger('athenos::animate');
			$('.'+ANIMATEABLE_CLASS).removeClass(ANIMATEABLE_CLASS);
				
			if($.browser.msie || isMacChrome) {
				$('.motion-group').hide();
				$('#'+activeZone).show();
			}
			
			$('#'+activeZone).find('.motion-wrapper, .'+CROSSWISE_CLASS).addClass(ANIMATEABLE_CLASS);
			$('.'+ANIMATEABLE_CLASS).trigger('athenos::animate');
		}
		
		/****************************************************
		 * _hashChange:void
		 * 
		 * Triggered on hashchange
		 ****************************************************
		/                                                  */
		function _hashChange(e){
			e.preventDefault(); //this does nothing.
			
			if(hashLock){ hashLock = false; return;}
			
			var hash = window.location.hash.replace('/', '');
			
			if(hash !== ''){
				if(navLock) return;
				
				var $current = $('a[href='+hash+']', $('nav'));
				
				$current.trigger('click');
			}
		}
		
		/****************************************************
		 * _mainNavClick:void
		 * 
		 * Triggered on Nav anchor click
		 ****************************************************
		/                                                  */
		function _mainNavClick(e){
			e.preventDefault();
			if(navLock) return;
			
			var $current = $(e.target),
				$parent = $current.closest('ul'),
				$relative,
			 	offset = 0;
				
			// not an anchor? not invited to the party ...
			if($current[0].tagName !== 'A') return;
			
			// unactivate
			navLock = true;
			_hideMenus();
			$mainA.removeClass('selected');
			
			// see if it's the main nav or a flyout
			if($parent.hasClass('flyout')) {
				offset = parseInt($current.attr('rel'), 10);
				$relative = $('#' + $parent.attr('id').replace('-flyout', '-btn'));
				if($current.attr('rel') !== $relative.attr('rel').split(' ')[0]) offset = offset === 0 ? 0 : offset - productOffset;
				$relative.addClass('selected');
			} else if($current.attr('rel').split(' ').length > 1) {
				offset = parseInt($current.attr('rel').split(' ')[1], 10) - productOffset;
				$current.addClass('selected');
			} else {
				offset = parseInt($current.attr('rel'), 10);
				$current.addClass('selected');
			}
			
			if(offset === currentLeft) {
				navLock = false;
				return;
			}
			
			_gaq.push(['pageTracker._trackEvent', 'Main Nav Clicks', $current.attr('href'), 'click']);
			
			$wn.scrollTo(offset, 2000, {
				easing:'easeInOutExpo', 
				onAfter: function() {
					navLock = false;
				}
			});
		}
		
		/****************************************************
		 * _keydown:void
		 * 
		 * delete comment here. Well played...
		 ****************************************************
		/                                                  */
		function _keydown(e){			
			if(e.which == 39 || e.which == 37){
				e.preventDefault();
				
				var len = $mainA.length-1,
					act = $mainA.filter('.selected').parent('li').index(),
					idx;
				
				if(e.which == 37){
					idx = act-1;
					if(idx < 0) { return; }
				} else {
					idx = act+1;
					if(idx > len) { return; }
				}
				
				$mainA.parent('li').eq(idx).find('a').click();
			}
		
		}
		
		/****************************************************
		 * _animator:void
		 * 
		 * Triggered on custom animate
		 * Moves stuff based on scroll and cached vals
		 ****************************************************
		/                                                  */
		function _animator(e) {
			var $this = $(e.currentTarget),
				inf = Athenos.zone.divisions[e.currentTarget.id],
				max = inf.parentWidth - appWidth,
				relScroll = currentLeft - inf.left;
			
			if(relScroll < 0) relScroll = 0;
			if(relScroll > max) relScroll = max;
			
			if(!inf.crosswise){
				if(isSafari) $this.css(vendorPre+'transform', _cssTranslateX(_calculatePosition(inf.speed, relScroll)));
				else $this.css('margin-left', _calculatePosition(inf.speed, relScroll) + 'px');
			} else {
				if(relScroll >= inf.range1 && relScroll <= inf.range2){
					relScroll = relScroll - inf.range1;
					if(isSafari) $this.css(vendorPre+'transform', _cssTranslateY( _calculatePositions_StartAndEnd(relScroll, inf.start, inf.end, inf.selfWidth)));
					else $this.css('margin-top', _calculatePositions_StartAndEnd(relScroll, inf.start, inf.end, inf.selfWidth) + 'px');
				}
			}
		}
		
		/****************************************************
		 * _endAnimator:void
		 * 
		 * Positions dudes to the left of the activeZone
		 ****************************************************
		/                                                  */
		function _endAnimator() {
			var divisions = Athenos.zone.divisions;
						
			$.each($('#'+activeZone).prevAll().find('.motion-wrapper'), function(){
				var $this = $(this);
				
				if($this.attr('id').indexOf(activeZone) === -1){					
					var inf = divisions[$this.attr('id')],
						max = inf.parentWidth - appWidth;
					
					if(isSafari) {
						$this.css(vendorPre+'transform', _cssTranslateX(_calculatePosition(inf.speed, max)));
					}
					else { 
						$this.css('margin-left', _calculatePosition(inf.speed, max) + 'px');
					}
				}
			});
		}
		
		/****************************************************
		 * _calculatePosition:int
		 * 
		 * guess what this does?
		 ****************************************************
		/                                                  */
		function _calculatePosition(speedMod, i){
			return -(i * speedMod);
		}
		
		/****************************************************
		 * _calculatePositions_StartAndEnd:int
		 * 
		 * same as above, but by start and end points
		 ****************************************************
		/                                                  */
		function _calculatePositions_StartAndEnd(relScroll, start, end, parent){
			return start + (end - start) / parent * relScroll;
		}
		
		/****************************************************
		 * _windowResize:void
		 * 
		 * Triggered on win resize
		 ****************************************************
		/                                                  */
		function _windowResize(e) {
			$wrapper.css({
				'width':'100%',
				'margin-left':-Math.ceil($wrapper.outerWidth() / 2) + 'px'
			});
			appWidth = parseInt($wrapper.outerWidth(), 10);
			
			if($wn.width() > appWidth){
				$body.width(parseInt(($wn.width() - appWidth) + bodW, 10));
			} else {
				$body.width(bodW);
			}
			
			productOffset = ($mainNav.offset().left - $wrapper.offset().left) / 2;
			_buildZoneLocations();
			_offsetZone();
		}
		
		/****************************************************
		 * _googPageLoad:void
		 * 
		 * Report our page load to goog for tracking
		 ****************************************************
		/                                                  */
		function _googPageLoad(){
			var plend = new Date(),
				plload = plend.getTime() - plstart.getTime(),
				fn = document.location.pathname;
				
			if(plload<1000)			{ lc = "Very Fast"; }
			else if (plload<2000) 	{ lc = "Fast"; }
			else if (plload<3000)	{ lc = "Medium"; }
			else if (plload<5000)	{ lc = "Sluggish"; }
			else if (plload<10000)	{ lc = "Slow"; }
			else 					{ lc = "Very Slow"; }
			
			if( document.location.search){
				fn += document.location.search;
			}
				
			try {
				_gaq.push(['loadTracker._setAccount', 'UA-22807587-6']);
				_gaq.push(['loadTracker._trackEvent','Page Load (ms)',lc + ' Loading Pages',fn,plload]);
			} catch(err){}
		}


/*
 * Prepping the DOM by building objects and DOM nodes
 ----------------------------------------------------*/


		/****************************************************
		 * _buildMotionObjects:void
		 * 
		 * builds motion objects and appends them to the DOM
		 ****************************************************
		/                                                  */
		function _buildMotionObjects(){
			var zone,
				flyouts,
				main,
				items,
				wrappers,
				primaries,
				groups = [],
				map = Athenos.motion.map,
				priWidth,
				startPnt = 0,
				endPnt = 0;
			
			for(zone in map){
				primaries = _getPrimaryCount(map, zone);
				priWidth = _getPrimaryWrapperWidth(map, zone, primaries);
				
				//get total scroll width
				startPnt = endPnt;
				endPnt += priWidth;
				
				items = _motionItemsToFragments(map, zone, priWidth, startPnt);
				wrappers = _motionWrappersToFragments(map, zone, items, primaries, priWidth, startPnt);
				groups.push(_motionGroupsToFragment(zone, wrappers));
			}
			
			bodW = endPnt;
			
			$motions.append(groups.join(''));
			$body
				.width(endPnt)
				.image_eventer($body, 'googPageLoad');
		}
		
		/****************************************************
		 * _getPrimaryCount:ing
		 * 
		 * returns number of primary items
		 ****************************************************
		/                                                  */
		function _getPrimaryCount(map, point){
			var arr = map[point].items,
				ob = _buildObByParent(arr),
				p,
				stLen,
				primaryCount = 0;
			
			for(p in ob){
				stLen = ob[p].length-1;
				
				for(i=stLen; i>=0; i--){
					if(parseInt(p, 10) === 1){
						primaryCount++;
					}
				}
			}
			
			return primaryCount;
		}
		
		/****************************************************
		 * _motionItemsToFragments:ob
		 * 
		 * returns a formatted motion ob sorted by parent
		 *
		 * NOTE: width, height, z-index set in CSS for these.
		 ****************************************************
		/                                                  */
		function _motionItemsToFragments(map, point, priWid, left){
			var arr = map[point].items,
				ob = _buildObByParent(arr),
				fragments = {},
				fragArr,
				frag,
				i,
				p,
				stLen,
				items;
			
			for(p in ob){
				
				if(typeof fragments[p] === 'undefined'){
					fragments[p] = [];
					if(point !== 'socials-motion'){
						flyoutRel = 0;
						if(typeof flyoutCont[point] === 'undefined'){ flyoutCont[point] = []; }
					}
				}
				
				stLen = ob[p].length-1;
				
				//Format appropriately based on type
				for(i=stLen; i>=0; i--){
					
					frag = _buildAccordingToType(map, point, i, stLen, p, ob[p][i], ob[p][i].type, priWid, left);
					
					fragments[p].push(frag);
				}
			}

			return fragments;
		}
		
		/****************************************************
		 * _buildAccordingToType:string
		 * 
		 * returns a formatted fragment
		 ****************************************************
		/                                                  */
		function _buildAccordingToType(map, point, i, stLen, p, ob, type, priWid, left, isCrosswise){
			var frag,
				style = [],
				classes = ['motion-item', 'motion-item-'+type, 'no-flicker'],
				relW = 0, idMod,
				navClass = '';
			
			isCrosswise = isCrosswise || false;
			
			if(isCrosswise){ classes.push(CROSSWISE_CLASS); }
			
			//check if we are a child of layer 1 (our 'Primary' layer)
			if(parseInt(p, 10) === 1){
				style.push('width: '+map[point].itemsWidth+'px; height: '+map[point].itemsHeight+'px;');
				relW += map[point].itemsWidth;
				
				switch(i){
					case 0:
						style.push('margin: 0 '+(map[point].itemsMargins+map[point].endMarginMod)+'px 0 '+map[point].itemsMargins+'px;');
						relW += map[point].itemsMargins;
						break;						
					case stLen:
						style.push('margin: 0 '+map[point].itemsMargins+'px 0 '+(map[point].itemsMargins+map[point].endMarginMod)+'px;');
						navClass = ' last';
						relW = 0;
						break;
					case stLen-1:
						style.push('margin: 0 '+map[point].itemsMargins+'px;');
						relW += map[point].endMarginMod + map[point].itemsMargins*2;
						break;
					default:
						style.push('margin: 0 '+map[point].itemsMargins+'px;');
						relW += map[point].itemsMargins*2;
						break;
				}
				
				flyoutRel += relW;
				
				//build the subnav/flyout
				if(point !== 'socials-motion'){
					flyoutCont[point].push('<li class="'+ob.color+'-ribbon'+navClass+'"><a href="#'+ob.name+'" rel="'+(flyoutRel+left)+'">'+ob.title+'</a></li>');
				}
				
			} else {
				//non-crosswisers will get a top and left
				if(!isCrosswise){ style.push('top:'+ob.top+'px; left:'+ob.left+'px;'); }
				//crosswisers get some transform or margin-top lovin'
				else { 
					if(isSafari){
						style.push(vendorPre+'transform: '+_cssTranslateY( Athenos.zone.divisions[ob.name+"-item"].start)+';', 'left:'+ob.left+'px');
					}
					else {
						style.push('margin-top: '+( Athenos.zone.divisions[ob.name+"-item"].start)+'px;', 'left:'+ob.left+'px');
					}

				}
			}
			
			idMod = ob.name+'-item';
			
			switch(type){
				case 'img':
					classes.push(ob.name);
					frag = '<img id="'+idMod+'" src="lib/imgs/'+ob.imgsrc+'" class="'+classes.join(' ')+'" style="'+style.join(' ')+'" alt="" />';
					break;
				
				case 'video':
					classes.push(ob.name);
					// Note: Kraft servers can't support video mime types for Safari or IE9, update if this changes ...
					if((!Modernizr.video) || $.browser.webkit || $.browser.msie) {
						frag = '<img id="'+idMod+'" class="'+classes.join(' ')+'" style="'+style.join(' ')+'" src="'+ob.vidsrc+'.gif" width="280" height="220" alt ="" />';
					} else {
						frag = '<video id="'+idMod+'" class="'+classes.join(' ')+'" style="'+style.join(' ')+'" width="280" height="220" preload="auto">\
								<source src="'+ob.vidsrc+'.webm" type=\'video/webm; codecs="vp8, vorbis"\' />\
								<source src="'+ob.vidsrc+'.ogv" type=\'video/ogg; codecs="theora, vorbis"\' />\
								<source src="'+ob.vidsrc+'.mp4" />\
								</video>';
					}
					break;
				case 'link':
					classes.push(ob.name);
					frag = '<a id="'+idMod+'" class="'+classes.join(' ')+'" style="'+style.join(' ')+'" href="'+ob.href+'" target="_blank">'+ob.name.replace('-', ' ')+'</a>';
					break;
					
				case 'product':
					classes.push(ob.name);
					frag = '<div id="'+idMod+'" class="'+classes.join(' ')+'" style="'+style.join(' ')+'">\
								<div class="motion-item-card">\
									<h3>'+ob.title+'</h3>\
									<p>'+ob.copy+'</p>\
									<a id="'+ob.name+'-link" class="nutrition-links" href="'+ob.link+'">Nutrition Facts</a>\
								</div>\
								<div class="motion-item-img-wrapper">\
									<img src="lib/imgs/'+ob.imgsrc+'" class="motion-item-img hidden" alt=""/>\
								</div>\
							</div>';
							
						_buildInfoFragOb(ob, point);
					break;
					
				case 'content':
					frag = '<div id="'+idMod+'" class="'+classes.join(' ')+'" style="'+style.join(' ')+'">'+ob.content+'</div>';
					break;
					
				case 'repeater':
					frag = ' ';
					break;
					
				case 'crosswise':
					_buildCrosswiseDivisions(ob, left, priWid);
					frag = _buildAccordingToType(map, point, i, stLen, p, ob, ob.secondaryType, priWid, left, true);
					break;
			}
			
			return frag;
		}
		
		/****************************************************
		 * _motionWrappersToFragments:arr
		 * 
		 * returns a formatted motion ob sorted by parent
		 ****************************************************
		/                                                  */
		function _motionWrappersToFragments(ob, point, items, primaries, priWid, startPnt){
			var fragments = [],
				frag,
				parent,
				kids = [],
				builtId,
				tPre = vendorPre+'transform: translate',
				tPost = (Modernizr.csstransforms3d) ? '3d(0px, 0px, 0px);' : '(0px, 0px);',
				i,
				item,
				width,
				map = ob[point],
				obLen = _getObjectSize(Athenos.speed.map) - 1,
				style;
							
			for(item=obLen; item>=0; item--){
				
				if(typeof items[item] !== 'undefined'){
					for(i=obLen; i>=0; i--){
						if(parseInt(item, 10) == parseInt(i, 10)){
							builtId = point+'-layer_'+i;

							//Set the width of the wrapper
							width = priWid;

							//This is where we will build out Athenos.zone.divisions
							_buildDivisions(builtId, map.wrappers[i], Athenos.speed.map[i], priWid, width, startPnt);

							//get all the formatted children of the wrapper
							kids = items[item].join(' ');

							//Style it
							style = ''+(tPre+tPost)+' width: '+width+'px;';
							style += (map.wrappers[i] == 'y') ? 'height: '+width+'px' : '';

							//the formatted motion wrapper
							fragments.push('<div id="'+builtId+'" class="layer_'+i+' axis_'+map.wrappers[i]+' motion-wrapper no-flicker" style="'+style+'">'+kids+'</div>');

						}
					}
				}
			}

			return fragments;
		}
		
		/****************************************************
		 * _buildInfoFragOb:str
		 * 
		 * builds out Athenos.products w/ formatted fragments
		 ****************************************************
		/                                                  */
		function _buildInfoFragOb(ob, point){
			var i, stLen, fragT = [], fragB = [],
			 	w = 0, h = 0, t = 0, style, wH = '';
			
			if(typeof ob.infos !== 'undefined'){
				stLen = ob.infos.bottom.vals.length;
				
				switch(point){
					case 'pita-motion':
						w = 76;
						h = 120;
						t = 29;
						break;
					case 'hummus-motion':
						w = 120;
						h = 120;
						t = 29;
						break;
					case 'yogurt-motion':
						w = 120;
						h = 104;
						t = 40;
						break;
					case 'cheese-motion':
						w = 98;
						h = 120;
						t = 29;
						break;
				}
				
				fragT.push('<img src="lib/imgs/'+ob.imgsrc+'" width="'+w+'" height="'+h+'" alt="" style="top: '+t+'px;" />');
				fragT.push('<h2>'+ob.title+'</h2>');
				
				fragB.push('<p>');
				fragB.push('<span class="left">Serving Per  '+ob.infos.bottom.servingSize+'</span><span class="right"></span><br/>');
				fragB.push('<span class="left">Servings Per Container '+ob.infos.bottom.servings+'</span><span class="right"></span><br/><br/>');
				fragB.push('<span class="left">Amount per Serving</span><span class="right"></span><br/>');
				fragB.push('<span class="left"><b>Calories</b> '+ob.infos.bottom.calories+'</span><span class="right">Fat Cal '+ob.infos.bottom.fatCalories+'</span><br/>');
				fragB.push('<span class="left"></span><span class="right"><b>%DV*</b></span><br/>');
				fragB.push('</p>');
				
				fragB.push('<p class="values">');
				for(i=0; i<stLen; i++){
					fragB.push('<span class="left">'+ob.infos.bottom.vals[i][0]+'</span><span class="right">'+ob.infos.bottom.vals[i][1]+'</span><br/>');
				}
				fragB.push('</p><br/>');
				
				fragB.push('<p class="diet-info">');
				fragB.push('<span class="diet-top"><span class="calories">Calories:</span><span class="mid-right">2,000</span><span class="far-right">2,500</span></span>');
				fragB.push('<span class="far-left">Total Fat</span><span class="mid-left">Less Than</span><span class="mid-right">65g</span><span class="far-right">80g</span><br/>');
				fragB.push('<span class="far-left">Sat Fat</span><span class="mid-left">Less Than</span><span class="mid-right">20g</span><span class="far-right">25g</span><br/>');
				fragB.push('<span class="far-left">Cholesterol</span><span class="mid-left">Less Than</span><span class="mid-right">300mg</span><span class="far-right">300mg</span><br/>');
				fragB.push('<span class="far-left">Sodium</span><span class="mid-left">Less Than</span><span class="mid-right">2,400mg</span><span class="far-right">2,400mg</span><br/>');
				fragB.push('<span class="far-left-bt">Total Carbohydrate</span><span class="mid-right">300g</span><span class="far-right">300g</span><br/>');
				fragB.push('<span class="far-left-bt">Dietary Fiber</span><span class="mid-right">25g</span><span class="far-right">30g</span><br/>');
				fragB.push('<span class="far-left-bt">Protein</span><span class="mid-right">50g</span><span class="far-right">65g</span><br/>');
				fragB.push('</p><br/>');
				
				fragB.push('<p>'+ob.infos.bottom.ingredients+'</p><br/>');
				
			}
			
			if(typeof Athenos.products[ob.name] === 'undefined'){
				Athenos.products[ob.name] = {
					"top": fragT.join(''),
					"bottom": fragB.join('')
				};
			}
			
		};
		
		/****************************************************
		 * _motionGroupsToFragment:str
		 * 
		 * returns a formatted motion group
		 ****************************************************
		/                                                  */
		function _motionGroupsToFragment(id, wrappers){
			return '<div id="'+id+'" class="motion-group no-flicker">'+wrappers.join('')+'</div>';
		}
		
		/****************************************************
		 * _getPrimaryWrapperWidth:int
		 * 
		 * returns a Primary Wrapper's width
		 ****************************************************
		/                                                  */
		function _getPrimaryWrapperWidth(ob, point, primaries){
			return parseInt(((ob[point].itemsWidth + (ob[point].itemsMargins * 2) ) * primaries) + (ob[point].endMarginMod * 2), 10);
		}

		/****************************************************
		 * _buildProgressives:array
		 * 
		 * returns product collections to be passed to $.image_eventer
		 ****************************************************
		/                                                  */
		function _buildProgressives(){
			var collections = [];
			
			$.each($('.motion-item-img-wrapper img'), function(){
				collections.push([$(this).attr('src')]);
			});
			
			return collections;
		}

		
/*
 * Build out our Header Nav area
 ----------------------------------------------------*/


		/****************************************************
		 * _buildHeaderNav:void
		 * 
		 * build out main nav links
		 ****************************************************
		/                                                  */
		function _buildHeaderNav(){
			_buildZoneLocations(); //get the initial build of this guy;
			
			var navArr = [
					['', 'pita', 'Pita'], //li_ID, href, visible_title
					['', 'hummus', 'Hummus'],
					['', 'yogurt', 'Yogurt'],
					['', 'cheese', 'Feta'],
					['home-container', 'home', 'Athenos'],
					['', 'facebook', 'Facebook'],
					['', 'youtube', 'YiaTube'],
					['', 'twitter', 'Twitter'],
					['', 'locator', 'Locator']
				],
				i, liId, rel, rel2, navBuild = [],
				locations = Athenos.zone.locations,
				stLen = navArr.length;
			
			for(i=0; i<stLen; i++){
				liId = (navArr[i][0] !== '') ? ' id="'+navArr[i][0]+'"' : '';
				rel = (typeof locations[i] !== 'undefined') ? locations[i][0] 
															: rel+Athenos.motion.map['socials-motion']['itemsWidth'];
				// rel2 = (typeof locations[i+1] !== 'undefined') ? locations[i][1] : rel;
				
				navBuild.push('<li'+liId+'><a href="#'+navArr[i][1]+'" id="'+navArr[i][1]+'-btn" rel="'+rel+'" >'+navArr[i][2]+'</a></li>');
			}
			
			$('#main-nav').append(navBuild.join(''));
			$('#home-btn').addClass('selected');
			
			_buildSubNavs();
		}
		
		/****************************************************
		 * _buildSubNavs:void
		 * 
		 * builds the subnav/flyout dropdowns
		 ****************************************************
		/                                                  */
		function _buildSubNavs(){
			var i, subNav,
				stLen,
				subItems = [], curRel, addRel,
				transName, btnName;
			
			for(subNav in flyoutCont){
				subItems = [];
				transName = subNav.replace('motion', 'flyout');
				btnName = subNav.replace('motion', 'btn');
				stLen = flyoutCont[subNav].length-1;

				for(i=stLen; i>=0; i--){
					if(i==stLen){
						curRel = $('#'+btnName).attr('rel');
						addRel = $(flyoutCont[subNav][i]).find('a').attr('rel');
						$('#'+btnName).attr('rel', curRel+' '+addRel);
					}
					subItems.push(flyoutCont[subNav][i]);	
				}
				
				$('#'+transName).html(subItems.join(''));
			}
		}


/*
 * Build out the reference Objects
 ----------------------------------------------------*/	


		/****************************************************
		 * _buildZoneLocations:void
		 * 
		 * wipe and build out Athenos.zone.locations arr
		 ****************************************************
		/                                                  */
		function _buildZoneLocations(){
			var zone,
				items,
				primaries,
				map = Athenos.motion.map,
				priWidth,
				startPnt = 0,
				endPnt = 0,
				offset = appWidth;
			
			Athenos.zone.locations = [];
			
			for(zone in map){
				primaries = _getPrimaryCount(map, zone);
				priWidth = _getPrimaryWrapperWidth(map, zone, primaries);
				
				//build out Athenos.zone.locations
				//get total scroll width
				startPnt = endPnt;
				endPnt += priWidth;
				offset -= appWidth;

				Athenos.zone.locations.push([startPnt, endPnt - appWidth, zone, offset]);
			}
		}
		
		/****************************************************
		 * _buildDivisions:void
		 * 
		 * build help build out Athenos.zone.divisions ob
		 ****************************************************
		/                                                  */
		function _buildDivisions(builtId, axis, sM, pW, sW, left){
			if(typeof Athenos.zone.divisions[builtId] === 'undefined'){
				Athenos.zone.divisions[builtId] = {
					"axis": axis,
					"speed": sM,
					"width": sW,
					"parentWidth": pW,
					"left": left
				};
			}
		}
		
		/****************************************************
		 * _buildCrosswiseDivisions:void
		 * 
		 * build help build out Athenos.zone.divisions ob
		 ****************************************************
		/                                                  */
		function _buildCrosswiseDivisions(ob, left, priWid){
			if( typeof Athenos.zone.divisions[ob.name+'-item'] === 'undefined'){
				var rA = ob.range.split(' ');
					
				Athenos.zone.divisions[ob.name+"-item"] = {
					"start": ob.start,
					"end": ob.end,
					"range1": parseInt(rA[0], 10),
					"range2": parseInt(rA[1], 10),
					"left": left,
					"parentWidth": priWid,
					"selfWidth": Math.abs(parseInt(rA[0], 10) - parseInt(rA[1], 10)),
					"crosswise": true
				};
			}
		}


/*
 * Some Shared Utils
 ----------------------------------------------------*/


		/****************************************************
		 * _hitTest:object
		 * 
		 * Hit test the collection with the passed coords.
		 ****************************************************
		/                                                  */
		function _hitTest($col, pX, pY) {
			var t = false;
			
			$col.each(function() {
				var tX = $(this).offset().left,
					tY = $(this).offset().top,
					tW = $(this).outerWidth(),
					tH = $(this).outerHeight();
				
				if(pX > tX && pY > tY && pX < tX + tW && pY < tY + tH) t = $(this);
			});
			
			return t;
		}
		
		/****************************************************
		 * _cssTranslateX:string
		 * 
		 * Returns translate X coordinates for an item.
		 ****************************************************
		/                                                  */
		function _cssTranslateX(x) {
			return 'translate' + (Modernizr.csstransforms3d ? '3d('+x+'px,0px,0px)' : '('+x+'px,0px)');
		}
		
		/****************************************************
		 * _cssTranslateY:string
		 * 
		 * Returns translate Y coordinates for an item.
		 ****************************************************
		/                                                  */
		function _cssTranslateY(y) {
			return 'translate' + (Modernizr.csstransforms3d ? '3d(0px,'+y+'px,0px)' : '(0px,'+y+'px)');
		}
		
		/****************************************************
		 * _buildObByParent:ob
		 * 
		 * returns an unformatted ob sorted by parent
		 ****************************************************
		/                                                  */
		function _buildObByParent(arr){
			var i,
				stLen = arr.length-1,
				motions = {};
		
			for(i=stLen; i>=0; i--){
				if(typeof motions[arr[i].layer] === 'undefined'){ 
					motions[arr[i].layer] = [];
				}
				motions[arr[i].layer].push(arr[i]);				
			}
		
			return motions;
		}
		
		/****************************************************
		 * _getObjectSize:size
		 * 
		 * get the 'length' of a given object
		 ****************************************************
		/                                                  */
		function _getObjectSize(obj) {
			var size = 0,
				key;
				
			for (key in obj){
				if (obj.hasOwnProperty(key)) size++;
			}
			return size;
		}
		
		/****************************************************
		 * _supports:string
		 * 
		 * returns the appropriate CSS prefix
		 ****************************************************
		/                                                  */
		function _supports(prop) {  
			var div = document.createElement('div'),  
				vendors = 'Khtml O Moz Webkit'.split(' '),  
				len = vendors.length;  

			if(prop in div.style) return true;  

			prop = prop.replace(/^[a-z]/, function(val) {  
				return val.toUpperCase();  
			});  
				
			while(len--) {  
				 if ( vendors[len] + prop in div.style ) {  
					return '-'+vendors[len].toLowerCase()+'-';  
				 }  
			}
			
			if($.browser.msie && $('html').hasClass('ie9')){ return '-ms-'; }
			
			return false;  
		}
		
		
		return pub;
		
	})();

	self.Construct = (function(){
		$(document).ready(function(){
			if($('html').hasClass('ie6')) {
				return;
			} else {
				$('#no-js-page, #ie6-page').remove();
			}
			Athenos.Actions.init();
		});
	})();

}).call(Athenos, jQuery, Modernizr);
