/*
** Javascript: website.com
** Last Updated: 3.2011
** Title: Lifescapes
** Author: j.freeman - www.intercommunications.com
*/

$(document).ready(function(){
// Eliminate FOUT for @FontFace fonts
	WebFont.load({
		custom: {
			families: ['GalatiaSILRegular'],
			urls : ['/libraries/css/lnf-main.css']
		}
	});
// Background fader
	if (!document.getElementById('introAnimationWrap') && document.getElementById('bgTempImage')) {
		$('body').prepend('<div id="backgroundFader"><img src="/libraries/images/lnf/loading.gif" alt="" /></div>');
	}
// Set global variables
	var agent=navigator.userAgent.toLowerCase(),
		isIphone=(agent.indexOf('iphone')!=-1),
		isIpad=navigator.userAgent.match(/iPad/i) != null,
		mainNavItems=$('#navMain li'),
		letDieLoad=true,
		mainNavHoverT,
		letDieT,
		introText,
		pause=0,
		newHeight,
		showTimer=false,
		animationRunning=true,
		idx,
		minHeightOfContentWrap=40,
		mainContentInitialHeight=$('#mainContentWrapOuter').height();
	if (isIE9==undefined) {
		var isIE9=true;
	}
// Change styles for iPhone
	if (isIphone || isIpad) {
		if (isIphone) {
			$('head').append('<meta name="viewport" content="width=1024; initial-scale=0.41; maximum-scale=1.0;">');
		} else if (isIpad) {
			$('head').append('<meta name="viewport" content="width=1024; initial-scale=1; maximum-scale=2.0;">');
		}
		if (document.getElementById('tempNews') || document.getElementById('tempNewsMain') || document.getElementById('tempPortCat') || document.getElementById('tempPort')) {
			$('#footer').css('display','none');
			$('#mainWrapInner').append('<div id="mobileFooter"></div>');
			$('#mobileFooter').html($('#footer').html()); 
		}
	}
// Initial settings
	$('.slideDown').css({'display':'none'});
	$('.letDie p, .letDie h1, .letDie h2, #pageTitle, #fullScreenBackgroundImage').css({'display':'none'});
	$('#navMain li').css('opacity','0').hide();
	$('#mainContent *').css('opacity','0');
	$('#trayTop').append('<a href="#" id="mainContentWrapToggleButton">Open</a>');
	$('#mainContentWrapOuter').css({'height':minHeightOfContentWrap+'px'});
	if ($.browser.msie && document.getElementById('fullScreenBackgroundImage')) {
		$('body').prepend('<div id="fauxBody">');
		$('body').append('</div>');
	}
// Homepage animation and page load animations
	if (document.getElementById('introAnimationWrap')) {
		var animationMessages=$('#introAnimationWrap ul li');
        $.each(animationMessages, function(i) {
            setTimeout(function() {
            	$(animationMessages[i-1]).stop(true,true);
            	if (i!=animationMessages.length-1) {
                	$(animationMessages[i]).fadeIn(1000).animate({
                		top:0,
                		left:275,
                		opacity:0
                	},2500, function(){
                		$(this).hide();
                	});
            	} else {
					$('#fullScreenBackgroundImage').show();
                	$(animationMessages[i]).fadeIn(1000,function(){
                		homepageAnimationEnd();
                	});
            	}
            }, i * 3500);
		});
		$('#introAnimationWrap').append('<a href="/?s=1" class="specialButton" id="skipButton"><span>Skip Intro</span></a>');
	} else {
		if (document.getElementById('bgTempImage')) {
			$('#bgTempImage').load(function(){
				$('#backgroundFader').delay(500).fadeOut('slow',function(){
				    $(this).remove();
				    $('.slideDown').slideDown(500,'swing',function(){
				        $('.slideDown p, .slideDown h1, .slideDown h2').fadeIn(1500,function(){
				        	$('.slideDown').removeClass('slideDown');
				        	animationRunning=false;
				        	letDie();
				        });
				    });
				    animateContent();
				    animateNavBar();
				});
				$('#mainContentWrapOuter').delay(1000).animate({
				    'height':mainContentInitialHeight+'px'
				},'fast','swing',function(){
				    $('#mainContentWrapInner').fadeIn('fast');
					$('#mainContentWrapToggleButton').css({'background-position':'left bottom'}).text('close');
				});
			});
			var backgroundFader=setTimeout(function(){
			  $('#backgroundFader').fadeOut('slow',function(){
			      $(this).remove();
			      $('.slideDown').slideDown(500,'swing',function(){
			          $('.slideDown p, .slideDown h1, .slideDown h2').fadeIn(1500,function(){
			          	$('.slideDown').removeClass('slideDown');
			          	animationRunning=false;
			          	letDie();
			          });
			      });
			      animateContent();
			      animateNavBar();
				$('#mainContentWrapOuter').delay(1000).animate({
				    'height':mainContentInitialHeight+'px'
				},'fast','swing',function(){
					$('#mainContentWrapToggleButton').css({'background-position':'left bottom'}).text('close');
				    $('#mainContentWrapInner').fadeIn('fast');
				});
				});
			},4000);
		} else {
			$('.slideDown').slideDown(500,'swing',function(){
			    $('.slideDown p, .slideDown h1, .slideDown h2').fadeIn(1500,function(){
			    	$('.slideDown').removeClass('slideDown');
			    	animationRunning=false;
			    	letDie();
			    });
			});
			animateContent();
			animateNavBar();
		}
	}
//Clear and replace input values on focus/blur
    var clearMePrevious = '';
    $('.valueControl').focus(function() {
    	if($(this).val()==$(this).attr('title')) {
    		clearMePrevious = $(this).val();
    		$(this).val('');
    	}
    });
    $('.valueControl').blur(function() {
    	if($(this).val()=='') {
    		var prevTitle = $(this).attr('title');
    		$(this).val(prevTitle);
    	}
    });
// Mouse events for fading content blocks
	if (isIphone || isIpad) {
	    $('#mainWrapInner').click(function(){
	    	letDie();
	    });
	} else {
	    $('body').mousemove(function(){
	    	if (animationRunning==false) {
	    		if ($('#subNav').height()==0) {
	    		    $('#subNavInner').css('opacity','0');	    	    
	    		}				
	    		letDie();
	    	}
	    });
	}
//Suckerfish menu
	$('#subNavInner ul.sf-menu').superfish({
	    animation: {height:'show'},
	    delay: 1200,
	    onBeforeShow: function(){
	    	var allLists=$('.navListWrap ul'),
	    		tallestListHeight=$('.sf-menu').height(),
	    		additionalListHeight=50;
	    	for (i=0;i<allLists.length;i++) {
	    		if (($(allLists[i]).css('display')=='block' || $(allLists).index($(this))==i) && $(allLists[i]).height()>tallestListHeight) {
	    			tallestListHeight=$(allLists[i]).height();
	    		}
	    	}
	    	$('#subNav').stop(true,true).animate({
	    		height:tallestListHeight+additionalListHeight+'px'
	    	});
	    },
	    onShow: function() {
	    	if ($(this).height()>$('#subNav').height()) {
	    		$('#subNav').animate({
	    			height:$(this).height()+50+'px'
	    		});
	    	}
	    }
	});
// Call hoverintent for main nav and drawer functionality
	$('#navMain li a').hoverIntent({
		over: function(){
			var tmpSubNavListHeight=0;
			idx = $('#navMain li').index($(this).parent());
    		if ($(this).hasClass('navThumbs') || $(this).hasClass('navList')) {
			    $('#subNavInner').stop(true,true);
			    $('#subNav').stop(true,true);
			    $('.subNavWrap').hide();
			    $('.subNavWrap').eq(idx).show();
				newHeight=$('#subNavInner').height();
			    $('#subNav').animate({
			    	height:newHeight+'px'
			    	}, 'fast','swing',function(){
			    	$('#subNavInner').fadeTo('fast',1);
			    });
	    	}		
		},    
		timeout: 500,   
		out: function(){$(this).stop();}   
	});
// Main nav drawer handling
	$('#navMain li a').mouseout(function(){
		idx = $('#navMain li').index($(this).parent());
		if ($(this).hasClass('navThumbs') || $(this).hasClass('navList')) {
	    	$('#subNavInner').delay(500).fadeTo('fast',0,function(){
	    		$('.subNavWrap').hide();
	    		$('#subNav').animate({
	    		'height':'0px'
	    		},'fast','swing');
	    	});
		}
		$('a').removeClass('navActive');		
	});
	$('#subNav').mouseover(function(){
		$('#subNavInner').clearQueue();
	});
	$('#subNav').mouseout(function(){
		$('#subNavInner').delay(500).fadeTo('fast',0,function(){
		    $('.subNavWrap').hide();
		    $('#subNav').animate({
		    'height':'0px'
		    },'fast','swing');
		});
	});
// Sub page routines
	if (!(document.getElementById('tempHome'))) {
		$('#mainContent').css('display','none');
		$('#mainContent').fadeIn('slow');
	// Sub page animated content drawer		
		if (((document.getElementById('tempContent') || document.getElementById('tempBio'))) && $('#mainContent').height()>$('#mainContentWrapInner').height()+20) {
			$('#mainContentWrap').append('<span id="scrollUp">Scroll Up</span>');
			$('#mainContentWrap').append('<span id="scrollDown">Scroll Down</span>');
		}
		$('#mainContentWrapToggleButton').click(function(){
			contentPageSlidingDrawer();
			return false;
		});
		if (isIphone || isIpad) {
			$('#scrollDown').click(function(){
				var mainCurrentPos=$('#mainContent').css('top');
				mainCurrentPos=mainCurrentPos.replace('px','');
				mainCurrentPos=parseInt(mainCurrentPos);
				if (mainCurrentPos>(($('#mainContent').height())-$('#mainContentWrapInner').height())*-1) {
					$('#scrollUp').css({
						'opacity':'1',
						'filter':'alpha(opacity=100)'
					});
				    $('#mainContent').animate({
				    	'top':mainCurrentPos-75+'px'
				    });
				} else {
					$(this).css({
						'opacity':'0.3',
						'filter':'alpha(opacity=30)'
					});
				}
				return false;
			},
			{
				duration  : 0, // starting duration
        		speed     : 0, // duration multiplier
        		min       : 0  // minimum duration
			});
			$('#scrollUp').click(function(){
				var mainCurrentPos=$('#mainContent').css('top');
				mainCurrentPos=mainCurrentPos.replace('px','');
				mainCurrentPos=parseInt(mainCurrentPos);
				if (mainCurrentPos<0 && mainCurrentPos<=-75) {
					$('#scrollDown').css({
						'opacity':'1',
						'filter':'alpha(opacity=100)'
					});
					$('#mainContent').animate({
						'top':mainCurrentPos+75+'px'
					});
				} else if  (mainCurrentPos<0 && mainCurrentPos>=-75) {
					$(this).css({
						'opacity':'0.3',
						'filter':'alpha(opacity=30)'
					});
					$('#mainContent').animate({
						'top':0+'px'
					});
				} else {
					$(this).css({
					    'opacity':'0.3',
					    'filter':'alpha(opacity=30)'
					});
				}
				return false;
			},
			{
				duration  : 0, // starting duration
        		speed     : 0, // duration multiplier
        		min       : 0  // minimum duration
			});
		} else {
			$('#scrollDown').repeatedclick(function(){
				var mainCurrentPos=$('#mainContent').css('top');
				mainCurrentPos=mainCurrentPos.replace('px','');
				mainCurrentPos=parseInt(mainCurrentPos);
				if (mainCurrentPos>((parseInt($('#mainContent').height())-$('#mainContentWrapInner').height()))*-1) {
					$('#scrollUp').css({
						'opacity':'1',
						'filter':'alpha(opacity=100)'
					});
				    $('#mainContent').css('top',mainCurrentPos-2+'px');
				} else {
					$(this).css({
						'opacity':'0.3',
						'filter':'alpha(opacity=30)'
					});
				}
				return false;
			},
			{
				duration  : 0, // starting duration
        		speed     : 0, // duration multiplier
        		min       : 0  // minimum duration
			});
			$('#scrollUp').repeatedclick(function(){
				var mainCurrentPos=$('#mainContent').css('top');
				mainCurrentPos=mainCurrentPos.replace('px','');
				mainCurrentPos=parseInt(mainCurrentPos);
				if (mainCurrentPos<0) {
					$('#scrollDown').css({
						'opacity':'1',
						'filter':'alpha(opacity=100)'
					});
					$('#mainContent').css('top',mainCurrentPos+2+'px');
				} else {
					$(this).css({
						'opacity':'0.3',
						'filter':'alpha(opacity=30)'
					});
				}
				return false;
			},
			{
				duration  : 0, // starting duration
        		speed     : 0, // duration multiplier
        		min       : 0  // minimum duration
			});
		}
	// Language flag hover state for iPad/iPod
		if (isIphone || isIpad) {
			$('#toggleLanguage').mouseenter(function(){
				clearTimeout(removeLanguageBubble);
				$('#languageHoverBubble').show();
				var removeLanguageBubble=setTimeout(function(){$('#languageHoverBubble').fadeOut('slow');},3000)
			});
			$('#toggleLanguage').mouseleave(function(){
				$('#languageHoverBubble').hide();
			});
			$('#languageHoverBubble').click(function(){
				window.location=$('toggleLanguage').attr('href')			
			});
		}
	// Portfolio thumbnail hovers
		if (isIphone || isIpad) {
			$('#tempPortCat #categoryThumbnails .subnav_group_1 .name a,#tempPortCat #categoryThumbnails .subnav_group_2 .name a,#tempPortCat #categoryThumbnails .subnav_group_3 .name a').css({'display':'block'});
		} else {
			var linkNameOriginalWidth=$('#categoryThumbnails .name').width();
			$('#categoryThumbnails .name').width(0);
			$('#categoryThumbnails .name a').css('display','none');
			$('#categoryThumbnails').children('div').mouseenter(function(){$(this).stop(true,false);portfolioThumbHover($(this))});
			$('#categoryThumbnails').children('div').mouseleave(function(){$(this).stop(true,false);portfolioThumbBlur($(this))});
		}
	}
// Slideshow
    var firstTime=true;
    if (document.getElementById('slideShowSlidesWrap')) {
        Galleria.loadTheme('/libraries/js/galleria.lifescapes.js');
        $('#slideShowSlidesWrap').galleria({
        	transition:'flash',
        	transitionSpeed:500,
        	autoplay:4000,
        	height:685,
        	width:1024,
        	crop:'width',
        	thumbCrop:true,
        	pauseOnInteraction:true,
        	showImageNav:true,
        	thumbFit:true,
        	carousel:true,
        	carouselFollow:true
        });
    }
// Functions
	function portfolioThumbHover(thisElement) {
		$(thisElement).children('.image').fadeTo('fast',0.3);
		if ($(thisElement).children('.name').children('a').text().length>35) {
			$(thisElement).children('.name').children('a').css('font-size','15px');
		}
		$(thisElement).children('.name').animate({
			width:linkNameOriginalWidth
		},'fast',function(){
			$(this).children('a').fadeIn('fast');
		});
	}

	function portfolioThumbBlur(thisElement) {
		$(thisElement).children('.image').fadeTo('fast',1);
		$(thisElement).children('.name').children('a').fadeOut('fast',function(){
			$(thisElement).children('.name').animate({
				width:0
			},'fast',function(){
				$(thisElement).children('.name').children('a').hide();
			});
		});
	}
		
	function animateContent(){
		$('#fullScreenBackgroundImage').fadeTo('slow',1,function(){
			$(this).css({
				'filter':'none'
			});
		});
		$('#pageTitle').delay(1000).fadeTo('slow',1);
		$('#mainContent *').delay(1000).each(function(i){
		    $(this).delay(50*i).fadeTo('slow',1);
		});
	}
	
	function animateNavBar(){
		$('#navMain li').delay(1000).each(function(i){
		    $(this).delay(200*i).show().fadeTo('slow',1,function(){
		    	$(this).css({
		    		'filter':'none'
		    	});
		    });
		});
	}
	
	function contentPageSlidingDrawer() {
		if ($('#mainContentWrapOuter').height()==mainContentInitialHeight) {
			$('#pageTitle').fadeOut('slow',0);
		    $('#mainContentWrapInner').fadeOut('fast',function(){
		        $('#mainContentWrapToggleButton').css({'background-position':'left top'}).text('Open');
		        $('.galleria-image').css('z-index','0');
		        $('#mainContentWrapOuter').animate({
		        	'height':minHeightOfContentWrap+'px'
		        },'fast','swing');
		    });
		} else {
			$('#mainContentWrapToggleButton').css({'background-position':'left bottom'}).text('Close');
		    $('#mainContentWrapOuter').animate({
		        'height':mainContentInitialHeight+'px'
		    },'fast','swing',function(){
				$('#pageTitle').fadeIn('slow');
		        $('#mainContentWrapInner').fadeIn('fast');
		    });
		}
	}
	
	function homepageAnimationEnd() {
		$('#skipButton').fadeOut(3000);
		$('#introAnimationWrap').fadeOut(3000,function(){
			animateNavBar();
			if ($.browser.msie && isIE9==false) {
		    	$('.slideDown').slideDown(500,'swing',function(){
		    		$('.slideDown *').customFadeIn('fast',function(){
		    			$('.slideDown').removeClass('slideDown');
		    			animationRunning=false;
		    			letDie();
		    		});
		    		if (isIE9!=false) {
		    			$('.letDie *').fadeTo('fast',1);
		    		}
		    		$('#pageTitle').css('opacity','1');
		    	});

			} else {
		    	$('.slideDown').slideDown(500,'swing',function(){
		    		$('.slideDown *').fadeTo(1500,1,function(){
		    			$('.slideDown').removeClass('slideDown');
		    			animationRunning=false;
		    			letDie();
		    		});
		    	});
			}
		})
	}
		
	function letDie() {
		if ($.browser.msie && isIE9==false) {
			if ($('.letDie').css('display')=='none' || letDieLoad==true) {
				clearTimeout(letDieT);
				$('.letDie').customFadeIn('fast',function(){
				    letDieT=setTimeout('$(".letDie").customFadeOut(2000)',13000);
				    letDieLoad=false;
				});
			} else {
				clearTimeout(letDieT);
				$('.letDie').stop(true,false).customFadeIn('fast',function(){
					letDieT=setTimeout('$(".letDie").customFadeOut(2000)',13000);
				});
			}
		} else {
			if ($('.letDie').css('display')=='none' || letDieLoad==true) {
				clearTimeout(letDieT);
				$('.letDie').css('display','block').fadeTo('fast',1,function(){
				    letDieT=setTimeout('$(".letDie").fadeTo(2000,0)',13000);
				    letDieLoad=false;
				});
			} else {
				clearTimeout(letDieT);
				$('.letDie').stop(true,false).fadeTo('fast',1,function(){
					letDieT=setTimeout('$(".letDie").fadeTo(2000,0)',13000);
				});
			}
		}
	}
	$.fn.customFadeIn = function(speed, callback) {
	    $(this).fadeIn(speed, function() {
	    	if(jQuery.browser.msie)
	    		$(this).get(0).style.removeAttribute('filter');
	    	if(callback != undefined)
	    		callback();
	    });
	};
	
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
});
