if (typeof features === 'undefined') {
	features = {};
}

else {
	console.log('features is already defined');
}

features.nav_slider = (function($) {
	
	function init() {
		$("#top-nav").append("<li id='magic-line' class='slider'></li>");
		var $mainNav = $("#top-nav");
		var $magicLine = $("#magic-line");
		$magicLine
			.width($(".active").width())
			.height($mainNav.height())
			.css("left", $(".active").position().left)
		$("#top-nav li").on('click', function() {
			$(this).slider('click');
			return false;
		});
		
		$('#services li').on('click', 'a', function() {
			setUpScroll($(this));
			return false;
		});
	}
	
	$.fn.slider = function(eventType) {
		var leftPos, newWidth,
			$mainNav = $("#top-nav");

		var $magicLine = $("#magic-line");
		
		$magicLine
			.width($(".active").width())
			.height($mainNav.height())
			.css("left", $(".active").position().left)
		
		$('.active').removeClass('active');

		
		if ($(this).length === 0) {
			$el = $('#home');
		}
		
		else {
			$el = $(this);
		}
		
		if (eventType === 'click') {
			clearInterval(interval);
			var anchor = $el.find('a');
			setUpScroll(anchor);
		}
		
		$el.addClass('active');
		
		leftPos = $el.position().left;
		newWidth = $el.width();
		$magicLine.stop().animate({
			left: leftPos,
			width: newWidth			
		}, function() {
			if (eventType === 'click') {
				startTimeout();
			}
		});
	}
	
	var interval;
	
	var startTimeout = function() {
		interval = setInterval(section_height, 500);
	}
	
	function section_height() {
		var sections = ['artists', 'about'];
		var selector = [];
		var scrollPosition;
		$.each(sections, function(i, val) {
			scrollPosition = $(window).scrollTop();
			var sectionPosition = $('#' + val).offset().top - 480;
			
			if (scrollPosition >= sectionPosition) {
				selector.splice(0, 1);
				var listItem = $('#top-nav a[href=#' + val + ']').parent();
				selector.push(listItem);
			}
		});
		
		$(selector[0]).slider();
	}
	
	function setUpScroll(anchor) {
		var getId = anchor.attr('href');
		goToScroll(getId);
	}
	
	function goToScroll(id) {
		$('html,body').animate({
	    	scrollTop: $(id).offset().top
	  	},'slow');
	}
	
	
	$(document).ready(init);
	$(document).ready(startTimeout);
	
})(jQuery);


