 /*!
  * Reimer Reason 
  * misc functions 
  * Copyright 2011 Wes Reimer et al
  */

(function(window, document) { // Immediately-Invoked Function Expression to privatize vars and compress window & document refs
	
	var Reimer = {
		
		FOOTER_PADDING : 30,
		
		ajaxInProgress : false,
		
		isMobile : /iPhone|iPod|Android/i.test(navigator.userAgent),
		
		init : function() {
			
			var $homeBody = $('._home');
			if (!$homeBody.length) {
				Reimer.restoreXScroll();
				return;
			}
			//console.log(Reimer.isMobile)
			//setup for animation
			if (!Reimer.isMobile) {
				$homeBody.find('#tagline').addClass('initial');
			}
			$homeBody.find('nav').eq(0).prepend('<img id="girl" src="img/girl.jpg" />');
			
		},
		
		
		fixLinks : function() {
			var path = location.pathname.replace(/^\//, ""), // IE includes leading slash
				host = location.hostname;

			$("nav a").each( function() {
				
				var $a = $(this),
					linkPath = this.pathname.replace(/^\//, ""),
					indexPath = linkPath.replace("home.php", "");
				
				if ( $a.is('.' + document.body.className) || indexPath==path || linkPath==path ) { // || path.indexOf(linkPath) > -1) {
					$a.addClass("selected");
				}
			});
			
			// adjust footer nav widths
			$('footer a.topLevel').each( function() {
				var $link = $(this),
					linkWidth = $link.width(),
					$div = $link.parent();
				//console.log($div)	
				$div.width(linkWidth + 20);
			});
			
			$("#main a").each(function() {
				var a = this;
				// is it external or a PDF?
				if ( !a.target && 
					(a.hostname.indexOf(host) == -1 || /\.pdf$/i.test(a.pathname)) ) {
						//console.log(a.hostname, a.hostname.indexOf(hostName));
						a.target = "_blank";
						if (!a.title) {
							a.title = "Opens in new tab or window";
						}
				}
			});
		},
		
		
		
		setupEvents : function() {
			$('.more_link').click( function() { //our story page
				var $link = $(this),
					id = $link.attr('href');
				$link.parent().hide();
				$(id).show('slow');						
				return false;   
			});
			
			$("#emailLink").click(function() { //contact page
				var addr = Reimer.getAddr("web.inquiry");
				$(this).html(addr).attr("href", "mailto:" + addr).unbind();
				return false;
			}); 
		},
		
		
		setupTeamPage : function() {
			
			Reimer.animateSubLinks();
						
			var $main = $('#main'),
				$h4s = $('._team section h4'),
				$showAllLink = $('#showAll');
			
			if (!$h4s.length) {
				return;
			}
				
			$h4s.click(function() {
				var openSections,
					$heading = $(this),
					$div = $heading.next('div'); //siblings();
					
				if ($heading.is('.open')) {
					$div.hide('fast', Reimer.toggleYScroll);
				} else {
					$div.show('slow', function() {	
						// autoscroll if div out of view
						var bottomOfDiv = $div.offset().top + $div.height(),
							bottomOfViewport = $(window).height() + $('html')[0].scrollTop, //window.scrollY
							afterScroll = function() {
								Reimer.addTweets( $div.find('aside').attr('id') );	
								Reimer.toggleYScroll();
							};
						if (bottomOfDiv > bottomOfViewport) {
							Reimer.scrollToElement( $heading, afterScroll, 300 );
						} else {
							afterScroll();
						}
					});
				}
				$heading.toggleClass('open');
				openSections = $h4s.filter('.open').length;
				if (0 === openSections) {
					$main.removeClass('showAll');
					$showAllLink.html('Show all');
				} else if ($h4s.length == openSections) {
					$main.addClass('showAll');
					$showAllLink.html('Hide all');
				}
			});
			
			$showAllLink.click(function() {
				$main.toggleClass('showAll');		
				$h4s.siblings().removeAttr('style'); // style added by show()/hide()
				if ($main.is('.showAll')) {
					$h4s.addClass('open');
					$('aside').each( function() {
						Reimer.addTweets(this.id);
					});
					$showAllLink.html('Hide all');	
				} else {
					$h4s.removeClass('open');
					$showAllLink.html('Show all');		
				}
				Reimer.toggleYScroll();
				return false;
			});
			
			var scrollTarget = location.search.replace('?scrollTo=', '');
			
			if (scrollTarget)
				$('#' + scrollTarget + ' h4').click();
			
			$('#teamPhotos a').click( function() {
				var $h4 = $(this.hash + ' h4');
				Reimer.scrollToElement($h4, function() {
						$h4.not('.open').click();										   
					});
				return false;
			});

		},
		
		
		scrollToElement : function($element, callBack, delay) {
			setTimeout(function() {
				$('html, body').animate({
					scrollTop : $element.offset().top - 10
				}, 700).promise().done(callBack);
			}, delay);
		},
		
		
		setupGallery : function() {
			var $galleryLinks = $('a[rel=gallery]');
			
			if (!$galleryLinks.length) 
				return;
			
			$('dd a').each(function() {
				this.href = this.href.replace('#','?scrollTo=');
			});
		
			$galleryLinks.colorbox( {
				maxWidth	: '95%',
				maxHeight	: '95%',
				current		: '{current} of {total}',
				title		: function() {  
					var $section = $(this).parents('section');
					return $section.find('.gallerySite').html() || $(this).parent().next('.caption').html() || $section.find('.caption').html() || ' ';
				}
			});
			
			Reimer.animateSubLinks();
		},
		
		
		doHomeEffects : function() {
					
			$('#tagline').fadeIn('slow'); 
			if (!Reimer.isMobile) { 
				$('.line1').animate( { left : 646 }, { duration	: 2000 } );	
				$('.line2').animate( { left	: 694 }, { duration	: 2000, complete : Reimer.restoreXScroll } );
			}
		},
		
		
		animateSubLinks : function() {
			$('.subLinks a').animate( { 'margin-left' : 0 }, { duration	: 1000 } );
		},
		
		
		toggleYScroll : function() {
			
			// to deal with tall footer background
			var contentHeight = Reimer.getContentHeight(),
				$window = $(window),
				overflowProperty = "visible";
				
			if ( 0 == $window.scrollTop() && $window.height() > contentHeight ) {
				overflowProperty = "hidden";	
			}

			//console.log('window', $window.height(), ' content',contentHeight);
			$('body').css('overflow-y', overflowProperty);
		},
		
	
		restoreXScroll : function() {
			$('body').css('overflow-x', 'visible');
		},
	
	
		addTweets : function( twitterId ) { //@todo change this to use jquery.twitter plugin
			
			// make sure we have an id and feed is not already loaded
			if ( !twitterId || $('#' + twitterId + ' .twtr-doc').length ) {
				return;	
			}
			
			//when 'showAll' is clicked before js is ready
			if (Reimer.ajaxInProgress) {
				setTimeout( function() {
					Reimer.addTweets(twitterId);
				}, 500);
				return;
			}
			
			// load the twitter js first time on demand 
			if (typeof TWTR != 'object') {			
				Reimer.ajaxInProgress = true;
				$.ajax({ // $.get doesn't work here
 					url : 'http://widgets.twimg.com/j/2/widget.js',
					dataType : 'script',
					cache : true,
 					success : function() { //console.log('ajax success');
						Reimer.ajaxInProgress = false;
						Reimer.addTweets(twitterId); 
					}
				});
				return;
			}	
			
			var	settings = {
			  id: twitterId,
			  version: 2,
			  type: 'profile',
			  rpp: 4,
			  interval: 6000,
			  width: 250,
			  height: 300,
			  theme: {
				shell: {
				  background: '#A4918A', //'#75584E',
				  color: '#ffffff'
				},
				tweets: {
				  background: '#ffffff',
				  color: '#333333',
				  links: '#006d9b'
				}
			  },
			  features: {
				scrollbar: false,
				loop: false,
				live: false,
				hashtags: true,
				timestamp: true,
				avatars: false,
				behavior: 'all'
			  }
			};
			new TWTR.Widget(settings).setUser(twitterId).render().start();
		},
	
	
		getAddr : function(name) {
			return name + String.fromCharCode(64) + location.hostname.replace("www.","");
		},
	
	
		getContentHeight : function() {
			
			var $copyright = $("#copyright");
			
			
			//console.log( 'old',$('header').height() + $('#main').height() + $('#footerContent').height() + this.FOOTER_PADDING);
			//console.log ('$top', $copyright.offset().top , '$outerheight',$copyright.outerHeight() )
			//	console.log ('top', $copyright[0].offsetTop , 'height', $copyright[0].offsetHeight)
			return $copyright.offset().top + $copyright.outerHeight();
			
		}



	};
// end Reimer object definition


// DOM Ready

	$(Reimer.init);

	$(window).load( function() { 
		Reimer.fixLinks();
		Reimer.toggleYScroll();
		Reimer.setupEvents();
		switch(document.body.className) {
			case '_home' : setTimeout(Reimer.doHomeEffects, 500); break;
			case '_team' : Reimer.setupTeamPage(); break;
			case '_portfolio' : Reimer.setupGallery();
		}
	}).resize(Reimer.toggleYScroll);
	
	
	 
})(this, document);
	
	
if (typeof console=="undefined") {
	console = { log : function(){} };
}

