/* Functions to run once the DOM has loaded */
var map;
$(function() {

	$('#overlay').show();
	$('body').removeClass('no-js');
	
	// Variables
	var wrapper = $('#wrapper'),
		main = $('#main'),
		logo = $('a#logo'),
		ourWork = $('#ourwork'),
		homeWrap = $('#homewrap'),
		globalTimeout = 300;

	// Hide no JavaScript class from Body
	//$('body').removeClass('no-js');

	// Reset page scrolls on page refresh
	$('#wrapper, #clients, #homewrap, .portfolioslideshow').scrollTo(0);
	$.scrollTo(0);

	// Reset dimensions for all fullscreen page elements on page resize
	$(window).resize(function() {
		resizePanel();
	});
	
	window.onorientationchange = function() {

		var selectedclient = $('.selectedclient'), curClientpos = $('.portfolio', '.selectedclient').index($('.selectedportfolio')), curVertpos = $('.client').index($('.selectedclient'));

		// Reset panes and images, then rebuild the scrollbars for correct width/height
		resizePanel();
		resizeBg();
		buildVertScrollbar();
		buildClientScrollbars();
		repositionModal();
		
		// Move scrollbars to correct position
		var topPos = ourWork.data('verthandelheight') * curVertpos, leftPos = selectedclient.data('clienthandelwidth') * curClientpos;
		moveVertHandle(topPos, 0);
		moveClientHandle(leftPos, 0, selectedclient);

	};

	// Give page and slides correct dimensions on page load and window resize
	setPanel();
	
	// Build vertical scrollbar for our work pages
	buildVertScrollbar();
	
	// Build horizontal scrollbars for client portfolios
	buildClientScrollbars();
	
	// Remove 'no-touch' class from body to prevent iOS hover states
	if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/android/i) || navigator.userAgent.match(/blackberry/i) || navigator.userAgent.match(/symbian/i) || navigator.userAgent.match(/windows ce/i)) {
		$('body').removeClass('no-touch');
	}
	  

	/* Page scroll triggers */
	
	// Home page 'Our Work' scroll
	$('a.ourwork').click(function () {
		wrapper.scrollTo($(this).attr('href'), globalTimeout);
		selectedPanel('#ourwork');	
		return false;
	});

	// M&M logo scroll
	$('a#logo').click(function () {
		var target = $(this).attr('href');
		
		// If 'About' pane open, reset logo link back to default, else scroll back to home page
		if (target == '#home') {
			homeWrap.scrollTo(target, globalTimeout);
			$('.aboutusbutton').removeClass('exitaboutus')
			logo.attr('href', '#main');
		} else {
			wrapper.scrollTo(target, globalTimeout, {onAfter: function(){
				$('#clients').scrollTo(0).trigger('notify.serialScroll', [0]);
				resetClientPanels();
				}
			});
		}
		selectedPanel('#main');	
		return false;
	});
	
	// Open 'About' pane, update link of M&M button, scroll back to previous pane
	$('.aboutusbutton').click(function() {
		var trigger = $(this), target = trigger.attr('href');
		if (trigger.hasClass('exitaboutus')) {
			$('.home').removeClass('selectedhome');
			$('#home').addClass('selectedhome');
			wrapper.scrollTo('.selected', globalTimeout);
			homeWrap.scrollTo(target, globalTimeout);
			trigger.attr('href', '#aboutus').removeClass('exitaboutus');
			logo.attr('href', '#main');
		} else {
			$('.home').removeClass('selectedhome');
			$('#aboutus').addClass('selectedhome');
			wrapper.scrollTo('#main', globalTimeout);
			homeWrap.scrollTo(target, globalTimeout);
			trigger.attr('href', '#home').addClass('exitaboutus');
			logo.attr('href', '#home');
		}
		return false;
	});

	// Toggle the details div for each client
	//$('.clientdetailsbutton').click(function() {
		//$(this).parents('.content').find('.clientdetails').toggle(400);
		//return false;
	//});

	// Close the details div for each client
	$('.closedetails').click(function() {
		$(this).parents('.clientdetails').toggle(400);
		return false;
	});

	// Set the main client scroll
	ourWork.serialScroll({
		target:'#clients',
		items:'.client',
		prev:'#prevclient',
		next:'#nextclient',
		duration:globalTimeout,
		axis:'y',
		cycle: true,
		onUp:function(){
			// Custom method to allow the 'Prev' button to scroll back to home pane
			wrapper.scrollTo(0, globalTimeout, {onAfter: function() {
				resetClientPanels();
				}
			});
			selectedPanel('#main');	
		},
		/*onDown:function(){
			// Custom method to allow the 'Next' button to scroll back to home pane
			wrapper.scrollTo(0, globalTimeout, {onAfter: function() {
				resetClientPanels();
				}
			});
			selectedPanel('#main');	
		},*/
		onBefore:function( e, elem, $pane, $items, pos ){
			$('.clientcontrols').hide(0);
			$('.client').removeClass('selectedclient');
			$(elem).addClass('selectedclient');
			topPos = ourWork.data('verthandelheight') * pos;
			moveVertHandle(topPos, globalTimeout);
		},
		onAfter:function(){
			$('.clientcontrols').fadeIn(300);
			resetClientPanels();
		}
	});

	// Loop through each client and set the scroll through each client pane
	$('.client').each(function(){
		var clientId = '#'+$(this).attr('id');
		$(clientId).serialScrollMod({
			target:'.portfolioslideshow',
			items:'.portfolio',
			prev:'.prevslide',
			next:'.nextslide',
			duration:globalTimeout,
			axis:'x',
			cycle:false,
			onBefore:function( e, elem, $pane, $items, pos ){
				$('.portfolio').removeClass('selectedportfolio');
				$(elem).addClass('selectedportfolio');
				leftPos = $(clientId).data('clienthandelwidth') * pos;
				moveClientHandle(leftPos, globalTimeout, $(clientId));
			}
		})
	});

	// Map arrow key presses to navigate through panes
	$(document).keydown(function(e){
		switch (e.keyCode) {
			case 38:    // up
				navigatePanes('up');
				break;
			case 40:    // down
				navigatePanes('down');
				break;
			case 37:    // left
				navigatePanes('left');
				break;
			case 39:    // right
				navigatePanes('right');
		}      
	});

	// Map arrow key presses to navigate through panes
	$(document).swipe({
		threshold: 100,
		swipeLeft: function(){ navigatePanes('right'); },
		swipeRight: function(){ navigatePanes('left'); },
		swipeUp: function(){ navigatePanes('down'); },
		swipeDown: function(){ navigatePanes('up'); }
	});
		
	
	// Modal box trigger
	$('.map').live('click', function() {
							
		var overlay = $('#overlay'), target = $('div.modalbox'), maskHeight = $(document).height(), maskWidth = $(window).width(), winH = $(window).height(), winW = $(window).width();  
	
		overlay.css({'width':maskWidth+'px', 'height':maskHeight+'px', 'opacity':0.8}).fadeIn(300);    
		target.css({'top': winH/2-target.height()/2+'px','left': winW/2-target.width()/2+'px'}).fadeIn(300);
		mapinit();
		
		return false;
	});  

	$('.closemap, #overlay').live('click',function() { 
		$('#overlay, div.modalbox').fadeOut(300);
		return false;
	});


});


/* Functions to run once all page elements have loaded */

$(window).load(function() {

	$('#overlay').fadeOut(200);
	
	$(window).resize(function() {
		resizeBg();
	}).trigger("resize");

});


/* Site functions */

// Set the dimensions of each fullscreen pane to that of the browser window
function setPanel() {
 
	var width = $(window).width(), height = $(window).height(), home_mask_height = height * $('.home').length, client_mask_height = height * $('.client').length;
	   
	$('#wrapper, #homewrap, #clients, #overlay, .portfolioslideshow, .slide, .client, .home, .portfolio').css({width: width, height: height});
	$('#homemask').css({width: width, height: home_mask_height});
	$('#clientmask').css({width: width, height: client_mask_height});

	$('.client').each(function(){
	
		var portfolio_mask_width = width * $('.portfolio', this).length;
		$('.portfoliomask', this).css({width: portfolio_mask_width, height: height});
	
	});
	
	setAboutPage();
	         
}

// Function to resize each fullscreen pane on window resize, also to scroll to the top of the visible pane to prevent the view being out of sync
function resizePanel() {
 
	setPanel();
	
	if (!($('#aboutus').hasClass('selectedhome'))) {
		$('#wrapper').scrollTo('.selected', 0);
	}
	$('#homewrap').scrollTo('.selectedhome', 0);
	$('#clients').scrollTo('.selectedclient', 0);
	$('.portfolioslideshow').scrollTo('.selectedportfolio', 0);
	/*$('.aboutusbutton').attr('href', '#aboutus').removeClass('exitaboutus');
	$('a#logo').attr('href', '#main');*/
         
}

// Add a class to the visible pane so we know what pane is active
function selectedPanel(element) {

	$('.slide').removeClass('selected');
	$(element).addClass('selected');

}

// Build the vertical client scrollbar
function buildVertScrollbar() {

	var totalClients = $('.client').length, ourWork = $('#ourwork');
	
	if (totalClients > 1) {
	
		var wrapHeight = $('#vertscrollbarwrap').height(), verthandelHeight = wrapHeight / totalClients;
		$('#verthandle').height(verthandelHeight)
		
		ourWork.data('verthandelheight', verthandelHeight);
	}

}

// Build the horizontal scrollbar for each client
function buildClientScrollbars() {

	var totalClients = $('.client').length, portfolioItems = '', clientIndex = '', wrapWidth = '', clientHandelWidth = '';
	
	$('.client').each(function(){
	
		clientIndex = $('.client').index(this);
		portfolioItems = $('.portfolio', this).length;

		wrapWidth = $('.clientscrollbar', this).width(), clientHandelWidth = wrapWidth / portfolioItems;
		$('.clienthandle', this).width(clientHandelWidth)
		
		$(this).data('clienthandelwidth', clientHandelWidth);
	
	});
	
}

// Move the vertical scrollbar on scroll callback
function moveVertHandle(topPos,timeout) {

	$('#verthandle').animate({top: topPos+'px'}, timeout);

}

// Move the horizontal client scrollbar on scroll callback
function moveClientHandle(leftPos,timeout,context) {

	$('.clienthandle',context).animate({left: leftPos+'px'}, timeout);

}

// Reset each client scrollbar when the visible pane is scrolled
function resetClientHandles() {

	$('.clienthandle').animate({left: '0px'}, 0);

}

// Reset each client pane to the first pane on scroll
function resetClientPanels() {

	$('.portfolioslideshow').each(function() {
		$(this).scrollTo(0,0).trigger('notify.serialScrollMod', [0]);
	});
	$('.clientdetails').hide(0);
	resetClientHandles()
	
}

// Navigate through panes on key arrow and swipe events
function navigatePanes(direction) {

	switch (direction) {
		case 'up':
			$('#clients').trigger('prev.serialScroll');
			break;
		case 'down':
			if ($('#main').hasClass('selected') && $('#home').hasClass('selectedhome')) {
				$('#wrapper').scrollTo('#ourwork', 500);
				selectedPanel('#ourwork');				
			} else {
				$('#clients').trigger('next.serialScroll');
			}
			break;
		case 'left':
			if ($('#ourwork').hasClass('selected')) {
				var curId = '#'+$('.selectedclient').attr('id');
				$(curId).find('.portfolioslideshow').trigger('prev.serialScrollMod');
			}
			break;
		case 'right':
			if ($('#ourwork').hasClass('selected')) {
				var curId = '#'+$('.selectedclient').attr('id');
				$(curId).find('.portfolioslideshow').trigger('next.serialScrollMod');
			}
			break;
	}      

}

// Set the height/width of background images
function resizeBg() {

	var $bg = $('.bgimage'), winH = $(window).height(), winW = $(window).width(), aspectRatio = $bg.width() / $bg.height();

	if ((winW / winH) < aspectRatio) {
		$bg.height(winH);
	} else {
		$bg.width(winW);
	}

}

// Map modal resize
function repositionModal() {

	var target = $('div.modalbox'), winH = $(window).height(), winW = $(window).width();  
	target.css({'top': winH/2-target.height()/2+'px','left': winW/2-target.width()/2+'px'});
	map.setCenter(new google.maps.LatLng(51.5202, -0.1816));

}

// Initialise Google Map for About page
function mapinit() {

	var latlng = new google.maps.LatLng(51.5202, -0.1816);
	var myOptions = {
		zoom: 16,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map"), myOptions);
	
	var image = 'images/map-marker.png';
  	var mapMarker = new google.maps.Marker({
		position: latlng,
		map: map,
		icon: image,
		title: 'McCormack & Morrison'
	});
	
}

function setAboutPage() {

	var aboutPage = $('#aboutcontent'), winH = $(window).height(), aboutH = aboutPage.height();
	
	var top = winH/2 - aboutH/2;
	
	if (top < 120) {
		top = 120;
	}
	aboutPage.css({top: top+'px'})

}


