var isScrolling = false;

$(document).ready(function() {

	initializeMap();

	/* Create bottom margin for the last articles */
	
	$('#wrapper .footer').css('height', ($(window).height()-215-$('.article[rel=contact-form]').height()));
	$(window).resize(function() {
		$('#wrapper .footer').css('height', ($(window).height()-215-$('.article[rel=contact-form]').height()));
	});
	
	/* Navigate left and right */
	
	$('.navigation.left a').click(function(e) {
		e.preventDefault();
		var current;
		var i = 1;
		$('.article').each(function() {
			if($(this).attr('rel') == $('.article.active').attr('rel')) {
				current = i;
			} else {
				i++;
			}
		});
		var destination;
		if(current == 1) {
			destination = $('.article').length;
		} else {
			destination = current-1;
		}
		navigate($('.article::nth-child('+destination+')').attr('rel'), true);
		
	});
	$('.navigation.right a').click(function(e) {
		e.preventDefault();
		var current;
		var i = 1;
		$('.article').each(function() {
			if($(this).attr('rel') == $('.article.active').attr('rel')) {
				current = i;
			} else {
				i++;
			}
		});
		var destination;
		if(current == $('.article').length) {
			destination = 1;
		} else {
			destination = current+1;
		}
		navigate($('.article::nth-child('+destination+')').attr('rel'), true);
		
	});
	
	/* Detect hash changes */
	
	if(location.hash == '' || location.hash == '#'+$('.article::nth-child(1)').attr('rel')) {
		location.hash = '#about';
		navigate(location.hash.replace('#', ''), false);
	} else {
		navigate(location.hash.replace('#', ''), true);
	}
	$('a').bind('click', function(e) {
		if($(this).attr('href').substr(0, 7) !== 'http://') {
			e.preventDefault();
			location.hash = $(this).attr('href');
			navigate(location.hash.replace('#', ''), true);
		}
	});
	
	/* Detect scrolling to articles */
	
	$('.article').waypoint(function(event, direction) {
		navigate($(this).attr('rel'), false);
	}, {
		offset: 215
	});

});

function navigate(rel, active) {
	if(!isScrolling) {
		relParts = rel.split('-');
		$('#menu a').removeClass('active');
		$('#menu a[rel='+relParts[0]+']').addClass('active');
		$('#submenu ul').hide();
		if($('#submenu ul.'+relParts[0]).length > 0) {		
			$('#submenu ul.'+relParts[0]).show();
		}
		$('.article').removeClass('active');
		$('.article[rel='+rel+']').addClass('active');
	}
	if(active) {
		isScrolling = true;
		$.scrollTo('.article[rel='+rel+']', 500, { offset: { top: -215 }, onAfter: navigateDone } );
	}
	
}

function navigateDone() {
	isScrolling = false;
}

function initializeMap() {
	var map = new google.maps.Map($("#map")[0], { zoom: 12, center: new google.maps.LatLng(52.2634587, 4.6483576), mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel:false });
	
    var beachMarker = new google.maps.Marker({
        position: new google.maps.LatLng(52.2634587, 4.6483576),
        map: map,
        icon: 'static/img/marker.png'
    });
}
