var SB = SB || {};

SB.SectionCarousel = (function (window, document) {
	
	var _currentSection;
	var _firstRun = true;
	var _isFallback;
	
	var self = {
		init: function($sections, initialSection) {
			_isFallback = $('html').hasClass('fallback');
			_currentSection = $($sections[initialSection]).attr('id');
			
			var $links = $sections.find('nav a');
			var $galleryItems = $sections.find('.project_descriptions li');

			var intervalIndex = 0;

			$.each($links, function(key, value) {
				$(this).data('index', key);
			});

			$.each($galleryItems, function(key, value) {
				$(this).data('index', key);
			});
			
			$(window).hashchange(function() {
				var id = location.hash.substr(1);
				
				var $fromSection;
				var $toSection;
				var $sections = SB.Portfolio.getSections();
				
				if(_isFallback) {
					_handleFallback(id);
					return;
				}
				
				if(_firstRun) {
					_handleFirstRun(id);
				} else {
					if(id == '') {
						$fromSection = $sections.filter('[class="selected"]');
						if($fromSection.attr('id') === 'about') return;
						
						$toSection = $sections.filter('[id="welcome"]');
						
						SB.Portfolio.switchSections($fromSection, $toSection, undefined);
					}
					else if(_currentSection === 'welcome' || _currentSection === 'about') {
						_handleDeeplink(id);
					}
					else
					{
						var $fromLink = $links.closest('.active[data-section="' + _currentSection + '"]');
						var $toLink = $('#link-' + id);
						
						if($fromLink === $toLink) return;
						
						var fromSection = $fromLink.data('section');
						var toSection = $toLink.data('section');
						
						if(fromSection === toSection) {
							_switchGalleryItem(
								$fromLink,
								$toLink,
								$fromGalleryItem = $galleryItems.closest('.active[data-section="' + _currentSection + '"]'),
								$toGalleryItem = $('#project-' + id)
							);
						} else {
							$toSection = $sections.filter('[id="' + toSection + '"]');
							$fromSection = $sections.filter('[id="' + fromSection + '"]');
							
							SB.Portfolio.switchSections($fromSection, $toSection, undefined);
						}
					}
				}
			});
		},
		
		setCurrentSection: function(value) {
			_currentSection = value;
		}
	}
	
	var _handleFallback = function(id) {
		SB.Portfolio.switchFallbackProject(id);
	}
	
	var _handleFirstRun = function(id) {
		_firstRun = false;
		if(id != '') _handleDeeplink(id);
	}
	
	var _handleDeeplink = function(id) {
		var $toLink = $('#link-' + id);
		var $toSection = $toLink.closest('section');
		
		SB.Portfolio.setInitialSection($toSection.data('numericIdentifier'));
		SB.Portfolio.switchSections(SB.Portfolio.getSections().filter('[class="selected"]'), $toSection, id);
	};
	
	var _switchGalleryItem = function($fromLink, $toLink, $fromGalleryItem, $toGalleryItem) {
		$fromLink.removeClass('active');
		$toLink.addClass('active');

		$fromGalleryItem.removeClass('active');
		$toGalleryItem.addClass('active');
	};
		
	return self;
})(this, this.document);
