//written by reborn # 11th.pl

$(document).ready(function() {
	$('#menu').after('<div id="menuSelection"></div>');
	$('#home, #works, #aboutme, #contact').css('display', 'none');
	$('#worksList').css('overflow', 'hidden');
	$('#worksList').css('height', '362px');
	$('#worksPages').css('display', 'block');
	
	adjustToScreen();
	
	var worksPages = $('#worksPages li');
	var pageSections = ['#home', '#works', '#aboutme', '#contact'];
	var currentLayer = '#none'; var activeWorksPage = 0;
	var worksSlider = $('#worksList ul:first-child');
	var anchor;
	
	function pageActivator(target) {
		if(target != currentLayer && pageSectionExists(target)) {
			if(currentLayer !== '#none') $(currentLayer).fadeOut(500);
			setTimeout(function() { $(target).fadeIn(500); currentLayer = target; }, 500);
			setTimeout(adjustToScreen, 500);
		}
	}
	function pageSectionExists(section) {
		var exists; $.each(pageSections, function(i, x) { if(x == section) { exists = true; } }); return(exists);
	}
	function mainMenuSlider(i) {
		var menuSelection = $('#menuSelection'); menuSelection.stop();
		menuSelection.animate({marginLeft: (i*250+29)+"px"}, 200);
	}
	function updateAnchor() {
		anchor = (self.document.location.hash ? (pageSectionExists(self.document.location.hash) ? self.document.location.hash : '#home') : '#home');
	}
	function setWorksPage(page) {
		$(page).attr('id', 'activeWorkPage'); $(page).animate({ border: "2px solid #fff", background: "#cfcd60" }, 100);
	}
	function unsetWorksPage(page) {
		$(page).attr('id', ''); $(page).animate({ border: 0, background: "#fff"}, 100);
	}
	function adjustToScreen() {
		if(document.getElementById('tableCellWrapper').offsetHeight < (document.documentElement.clientHeight - 260)) {
			$('#content').css('position', 'fixed');
			$('#footer').css('position', 'absolute');
			$('#footer').css('bottom', '0');
			$('#works, #aboutme, #contact').css('margin-bottom', '0px');
		}
		else {
			$('#content').css('position', 'static');
			$('#footer').css('position', 'static');
			$('#footer').css('bottom', '0');
			$('#works, #aboutme, #contact').css('margin-bottom', '80px');
		}
	}
	
	setInterval(function() { updateAnchor(); if(anchor != currentLayer) { pageActivator(anchor); } }, 200);
	$.each($('#menu li'), function(i, x) { $(this).hover(function() { mainMenuSlider(i); }, function() {}); });
	$('#worksListSlider').slider({
		orientation: 'vertical',
		animate: true,
		step: 1,
		value: 100,
		slide: function(event, ui) {
			var value = ((worksPages.length-1)*372)/100 * (100-ui.value);
			worksSlider.css('margin-top', '-'+value+'px');
		}
	});
	$.each(worksPages, function(i, x) {
		var page = i; $(x).click(function() {
			worksSlider.stop();
			worksSlider.animate({marginTop: '-'+(page*372)+'px'}, 1400);
			unsetWorksPage(worksPages[activeWorksPage]);
			setWorksPage(this);
			activeWorksPage = page;
			$('#worksListSlider').slider('value', 100-(100/(worksPages.length-1)*page));
		});
	});
});