/*====================================================================
	Custom Javascript
======================================================================

	All custom javasctipt goes in this file

======================================================================*/

	// START JQUERY
	(function($) {
			
		$(document).ready( function(){
			
			
			/* ===========================================
				Variables
			=========================================== */
			
			var 
				
				menu,
				menuHeight,
				windowHeight,
				differenceHeight,
				trigger,
				topLink,
				fadeTimer,
				hash
			
			;
			
			/* ===========================================
				Functions
			=========================================== */
			
			// Set initial variables
			function init() {
				menu = $('#main-menu');
				menuHeight = menu.outerHeight();
				windowHeight = $(window).height();
				trigger = $('header').outerHeight()-menu.outerHeight();
				topLink = $('#scroll-to-top');
			}
			
			// Fade in the logo
			function fadeInStart() {
				// Fade in elements that need to be
				$('header h1').fadeTo(500,1, function(){
					$('#current-show').fadeTo(500,1, function(){
						$('html').addClass('logo-visible');
						menu.fadeTo(300,1, function(){
							return true;
						});
					});
				});
			}
			
			function loadOnClick() {
				$('#main-menu').find('a').each(function(){
					$(this).attr('onclick', '_gaq.push(["_trackEvent", "anchor", "click", "' + $(this).attr('href') + '"]);' );
				});
			}
			
			// Set the min-height of each section to that of the window height
			function setSectionHeight(callback) {
				// Set the section height to be that of the availale window height
				$('section').css('min-height',windowHeight-menuHeight);
				// Set the #top minus height allowing for the menu
				$('#top').css('height',windowHeight);
				// Allow  callback
				if (typeof callback == 'function'){
					callback.call(this);
				}
			}
			
			// Create the sticky nav
			function stickyNav() {
				// Clear the timeout to stop the function being called
				clearTimeout(fadeTimer);
				// if the page has scrolled to or past the menu
				if ($('html').hasClass('oldie')) {
					var offsetTop = document.body.scrollTop;
				} else {
					var offsetTop = window.pageYOffset;
				}
				if ( offsetTop >= trigger ) {
					// Add a sticky class
					$('body').addClass('sticky');
					
					// If the top link is hidden and not animated
					if ((topLink.is(':hidden')) && (!topLink.is(':animated'))) {
						// start the timeout
						fadeTimer = setTimeout(function () {
							// Fade in the back-to-top link
							topLink.stop(true, true).fadeIn();
						}, 100);
					}
				}
				// if the page has NOT yet scrolled to the menu or scrolled back
				if ( window.pageYOffset < trigger ){
					// if the sticky class is present
					if ( $('body').hasClass('sticky')) {
						// remove the sticky class
						$('body').removeClass('sticky');
					}
					// If the top link is visible and not animated
					if ((!topLink.is(':hidden')) && (!topLink.is(':animated'))) {
						// start the timeout
						fadeTimer = setTimeout(function () {
							// Fade out the back-to-top link
							topLink.stop(true, true).fadeOut();
						}, 100);
					}
				}		
			}
			
			// Reposition the menu after scroll on iOS devices
			function iosStickyNav() {
				// If the HTML has the class 'ios' and the body has the class '.sticky'
				if (($('html').hasClass('ios')) && ($('body').hasClass('sticky'))) {
					// Start a timer
					var scrollOffset = setInterval( function(){
						if ($('html').hasClass('oldie')) {							var top = document.documentElement.scrollTop;						} else {							var top = window.pageYOffset;						}
						// Set the 'top' value to match how far we have scrolled
						$(' #main-menu').css({
							'position' : 'absolute',
							'left' : 0,
							'top' : top
						});
					// Do this every 100ms
					},100);
				}
			}
			
			// Move labels on click of relative text inputs
			function moveLabels() {
				// Get the original position values
				var pos = $('#contact label').css('left').replace('px','');
				
				$('#contact .text').focusin( function(){
					var label = $(this).closest('.form-row').find('label');
					label.stop(true, false).animate({
						'left' : -label.width()-pos
					}, 200, 'easeInOutQuint');
				});
				
				// If the input is empty then animate it back in
				$('#contact .text').focusout( function(){
					if ($(this).attr('value') === '') {
						var label = $(this).closest('.form-row').find('label');
						label.stop(true, false).animate({
							'left' : pos
						}, 200, 'easeInOutQuint');
					}
				});
			}
			
			(function( $ ){
				$.fn.verticalCenter = function() {
					var obj = this;
						obj.parent().css({'position' : 'relative'});
						obj.css({
							'margin-top' : -this.outerHeight()/2,
							'margin-left' : -this.outerWidth()/2,
							'position' : 'absolute',
							'top' : '50%',
							'left' : '50%'
						});
				}
			})(jQuery);
			
			
			(function ($) {
				$.fn.currentScrollPos = function () {
					var obj = this.offset().top;
						if ($('html').hasClass('oldie')) {
							obj = obj - document.body.scrollTop;
						} else {
							obj = obj-window.pageYOffset;
						}
						return obj;
				}
			})(jQuery);
			
			function getThumb(file) {
				// Discover the extension
				var extension = file.substr( (file.lastIndexOf('.')) );
				// Remove the extension from the file name
				var filename = file.replace(extension,'');
				// Set the thumbnail size
				var thumbsize = '-486x600';
				// Reconstitute the file name
				var newfile = filename+thumbsize+extension;				
				// Return the new filename
				return newfile;
			}
			
			function doGallery() {
				
				$('#gallery-thumbs a').first().addClass('active');
				
				// Check if all the images have been loaded
				$('#gallery-thumbs img').imagesLoaded( function(){			
					
					// Add the large image
					$('#gallery-selected').html('<a href="'+$('#gallery-thumbs a').first().attr('href')+'"><img src="'+getThumb($('#gallery-thumbs a').first().attr('href'))+'" alt="" style="opacity:0;" /></a>');
					
					// Only fade the image in when it has loaded
					$('#gallery-selected img').imagesLoaded( function(){
						$(this).fadeTo(300,1);
					});
				
				});
			
				// Gallery Image Swap
				$('#gallery-thumbs a').click( function(e){
					var obj = $(this);
					// Remove the active class from all other images
					$('#gallery-thumbs a').not(obj).removeClass('active');
					// Add the active class to the clicked image
					$(this).addClass('active');
					// Swap the src attributes
					$('#gallery-selected img').stop(true,true).fadeTo(300,0, function(){
						$('#gallery-selected img').attr('src',getThumb($(obj).attr('href')));
						$('#gallery-selected a').attr('href',$(obj).attr('href'));
						$('#gallery-selected img').imagesLoaded( function(){
							$(this).fadeTo(300,1);
						});
					});
					// Stop the default link behaviour
					e.preventDefault();
				});
				
			}
			
			//function to get random number upto m
			function randomXToY(minVal,maxVal,floatVal) {
				var randVal = minVal+(Math.random()*(maxVal-minVal));
				return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
			}
			
				$('.show-item').hover( function() {
					$(this).addClass('pulse');
				}, function(){
					$(this).removeClass('pulse');
				});
			
			
			/* ===========================================
				Bits 'o' Code (not functions)
			=========================================== */
			
			// Position the gallery vertically centered
			$('#gallery-container').verticalCenter();
			
			$('.wpcf7-not-valid-tip-no-ajax').prev('input, textarea, select').addClass('validation-error');
			
			$('#gallery-thumbs a img, #gallery-thumbs a').attr('title','');
				
			/* ===========================================
				Scrolling Stuff
			=========================================== */
			
			if($('html').hasClass('oldie')) {
				$offset = 0;
			} else {
				$offset = -51;
			}
			
			// Scrolling from the menu links
			$('#main-menu .container_12').localScroll({
			   axis:'y',
			   hash: true,
			   offset: $offset,
			   easing:'easeInOutQuint'
			},800);
			
			// Scrolling from the back-to-top links
			$('#scroll-to-top').click( function() {
				$.scrollTo(0,800, {
					axis:'y',
			    	hash: true,
			    	offset: 0,
			    	easing:'easeInOutQuint'
				});
			});
			
			
			/* ===========================================
				Initialise Functions
			=========================================== */
			
			init();
			setSectionHeight();
			stickyNav();
			fadeInStart();
			moveLabels();
			loadOnClick();
			
			/* ===========================================
				Actions to be called on scroll
			=========================================== */
			
			$(window).scroll(function () {
					
				init();
				setSectionHeight();
				stickyNav();
				iosStickyNav();
				
				/**
				 *	Apply active classes to menu based on scroll position
				 *	Can definitely be done better
				 */
				
				if ($('header').currentScrollPos() <= 0 && $('header').currentScrollPos() >= -$('header').height()) {
					$('#main-menu a').removeClass('active');
				}
				
				if ($('#gallery').currentScrollPos() <= 52 && $('#gallery').currentScrollPos() >= -$('#gallery').height()) {
					if (!$('#scroll-to-gellery').hasClass('active')) {
						$('#main-menu a').removeClass('active');
						$('#scroll-to-gallery').addClass('active');
					}
				}
				
				if ($('#about').currentScrollPos() <= 52 && $('#about').currentScrollPos() >= -$('#about').height()) {
					if (!$('#scroll-to-about').hasClass('active')) {
						$('#main-menu a').removeClass('active');
						$('#scroll-to-about').addClass('active');
					}
				}
				
				if ($('#credits').currentScrollPos() <= 52 && $('#credits').currentScrollPos() >= -$('#credits').height()) {
					if (!$('#scroll-to-credits').hasClass('active')) {
						$('#main-menu a').removeClass('active');
						$('#scroll-to-credits').addClass('active');
					}
				}
				
				if ($('#music').currentScrollPos() <= 52 && $('#music').currentScrollPos() >= -$('#music').height()) {
					if (!$('#scroll-to-music').hasClass('active')) {
						$('#main-menu a').removeClass('active');
						$('#scroll-to-music').addClass('active');
					}
				}
				
				if ($('#cv').currentScrollPos() <= 52 && $('#cv').currentScrollPos() >= -$('#cv').height()) {
					if (!$('#scroll-to-cv').hasClass('active')) {
						$('#main-menu a').removeClass('active');
						$('#scroll-to-cv').addClass('active');
					}
				}
				
				if ($('#contact').currentScrollPos() <= 52 && $('#contact').currentScrollPos() >= -$('#contact').height()) {
					$('#main-menu a').removeClass('active');
					$('#scroll-to-contact').addClass('active');
				}
				
			});
			
			/* ===========================================
				Actions to be called on load
			=========================================== */
			
			$(window).load( function() {
				
				menu.removeClass('loading');
				menu.find('.container_12').fadeIn(500);
				
				// Add the offset on pageload to account for the menu
				$.localScroll.hash({
					axis:'y',
				    hash: true,
				    offset: -51,
				    easing:'easeInOutQuint'
				});
				
				// Add a class to indicate the page has loaded fully					 
				$('html').addClass('loaded');
				
				doGallery();
				
			});
			
			/* ===========================================
				Actions to be called on resize
			=========================================== */
			
			$(window).resize( function(){
				init();
				setSectionHeight();
				clearTimeout(this.id);
				this.id = setTimeout( function() {
					stickyNav();
				},100);

			});
										
		}); // END $(document).ready
	
	})(jQuery);
	// END JQUERY 
