//consts
var DO_LOG			= true;
var SECTION_WIDTH	= 865,
	PAGES			= ['me', 'work'],
	SUBPAGE_STRING	= 'page',
	PULL_DISTANCE	= 30,
	HEADER_HEIGHT	= 50,
	TO_PAGE_TEXT	= '',
	TO_ARTICLE_TEXT	= '',
	MIN_HEIGHT		= 650,
	REGEX_TITLE_TO_URL	= new RegExp(' ', 'g'),
	REGEX_URL_TO_TITLE	= new RegExp('-', 'g'),
	CSS_TRANSFORM_PREFIXED;

var windowWidth		= 0,
	windowHeight	= 0,
	numImages,
	numImagesLoaded,
	isInid,
	allImagesLoaded,
	sectionMargin,
	sectionHolder,
	sectionArray,
	subSectionArray,
	inCurrentSection,
	currentSubs,	//like inCurrentSection but an array with an entry for every main section
	numSections,
	hashnav,
	prevBtn,
	nextBtn,
	mainNav,
	firstNavChange,
	isOpera;	//animating with translate doesnt work very well in opera, so force using margin now

window.addEvent('domready', function() {	//document ready
	var images		= $$('img');
	
	isInid			= false;
	allImagesLoaded	= false;
	numImages		= images.length;
	numImagesLoaded	= 0;
	
	$$('img').each(function(el) {
		if (!el.complete) {
			el.addEvent('load', domImageLoaded);
		} else {
			domImageLoaded();
		}
	});
	
	ini();
});

function domImageLoaded() {
	numImagesLoaded++;
	if (numImagesLoaded == numImages) {
		allImagesLoaded	= true;
		showSite();
	}
}

function ini() {
	if (navigator.appName == 'Opera') {
		isOpera			= true;
		SUPPORT_TRANSFORMS	= false;
	} else {
		isOpera			= false;
	}
	
	windowWidth			= $(window).getSize().x;
	windowHeight		= $(window).getSize().y;
	sectionMargin		= Math.round( (windowWidth - SECTION_WIDTH) / 2 );
	
	if (SUPPORT_3D_TRANSFORMS || SUPPORT_TRANSFORMS) {
		CSS_TRANSFORM_PREFIXED	= Modernizr.prefixed('transform').replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
	}
	
	setInitalOpacity();
	
	inCurrentSection	= -1;
	iniColumns();
	iniImageHovers();
	
	sectionArray	= [];
	subSectionArray	= [];
	currentSubs		= [];
	sectionHolder	= $('sitesections');
	prevBtn			= $('prevBtn');
	nextBtn			= $('nextBtn');
	mainNav			= $('mainnav');
	
	var i	= 0;
	$$('section').each(function(el){
		//sectionArray.push(el);
		var siteSection	= new SiteSection(sectionArray.length, el, PAGES[i]);
		sectionArray.push(siteSection);
		
		i++;
	});
	
	numSections	= sectionArray.length;
	
	hashnav		= new HashNav();
	
	setSection(0, '', true);
	
	//events
	$$('.navBtn').addEvent('mouseover', navBtnOver);
	
	$$('section').addEvent('mousewheel', handleScrolling);
	window.addEvent('resize', handleResize);
	window.addEvent('navchange', handleHashChange);
	window.addEvent('keyup', keyUpEvent);
	
	//for some reason height is broken on initalize
	//setTimeout(handleResize, 400);
	//handleResize();
	
	hashnav.triggerEvent();
	firstNavChange	= true;
	
	isInid			= true;
	showSite();
}

function showSite() {
	if (isInid && allImagesLoaded) {
		handleResize();
		fadeAllIn();
		setupAnimations();
	}
}

function fadeAllIn() {
	$$('body').setAnimationProperties(['opacity'], [500], ['ease-out'], [0]);
	$$('body').animateStyle('opacity', 1);
}

function keyUpEvent(e) {
	if (!lightbox.isOpen) {
		var currentSection = sectionArray[inCurrentSection];
		switch (e.code) {
			case 37:
				//left key
				gotoPreviousSection();
				break;
			case 38:
				//up key
				currentSection.gotoPrevPage();
				break;
			case 39:
				//right key
				gotoNextSection();
				break;
			case 40:
				//down key
				currentSection.gotoNextPage();
				break;
		}
	}
}

function handleScrolling(e) {
	//log(e.wheel);
	var currentSection = sectionArray[inCurrentSection];
	if (e.wheel > 0) {
		//up
		currentSection.gotoPrevPage();
	} else {
		//down
		currentSection.gotoNextPage();
	}
}

function navBtnOver(e) {
	if (this.id == 'nextBtn') {
		if (inCurrentSection < numSections-1) pullSectionsOut(-PULL_DISTANCE);
	} else if (this.id == 'prevBtn') {
		if (inCurrentSection > 0) pullSectionsOut(PULL_DISTANCE);
	}
	
	this.addEvent('mouseout', navBtnOut);
}

function navBtnOut(e) {
	moveToSection();
	this.removeEvent('mouseout', navBtnOut);
}

function handleHashChange(storedHashData) {
	//log('handleHashChange()');
//	console.log(storedHashData);
	var page	= storedHashData[1].page,
		subpage	= storedHashData[1].pathParsed[SUBPAGE_STRING];
	
	//if (!setSection(PAGES.indexOf(page)) || !firstNavChange) {
	
		setSection(PAGES.indexOf(page), subpage)
		
		// Moved this to setsection function:
		//only change subsection if main section wasnt changed
		//var currentSection = sectionArray[inCurrentSection];
		//currentSection.hashChange(subpage);
//	}
}


// SECTIONS

function pullSectionsOut(_toPull) {
	var currentLeft	= -Math.round((SECTION_WIDTH + sectionMargin) * inCurrentSection);
	var newLeft		= currentLeft + _toPull;
	
	if (SUPPORT_3D_TRANSFORMS) {
		sectionHolder.setStyle(CSS_TRANSFORM_PREFIXED, 'translate3d(' + newLeft + 'px, 0, 0)');
	} else if (SUPPORT_TRANSFORMS) {
		sectionHolder.setStyle(CSS_TRANSFORM_PREFIXED, 'translate(' + newLeft + 'px, 0)');
	} else {
		sectionHolder.animateStyle('left', newLeft + 'px');
	}
	
	//sectionHolder.animateStyle('left', newLeft + 'px');
}

function gotoPreviousSection() {
	if (inCurrentSection > 0) {
		setSection(inCurrentSection - 1);
	}
}

function gotoNextSection() {
	if (inCurrentSection < sectionArray.length-1) {
		setSection(inCurrentSection + 1);
	}
}

function setSection(_i, _subpage, _first) {
	if (_i != inCurrentSection) {
	
		var links = mainNav.getElements('a');
		
		if (inCurrentSection > -1) {
			links[inCurrentSection].removeClass('selected');
		}
		links[_i].addClass('selected');
		
		inCurrentSection	= _i;
		
		if (inCurrentSection == 0) {
			prevBtn.setStyle('visibility', 'hidden');
		} else {
			prevBtn.setStyle('visibility', 'visible');
		}
		
		if (inCurrentSection == numSections-1) {
			nextBtn.setStyle('visibility', 'hidden');
		} else {
			nextBtn.setStyle('visibility', 'visible');
		}
		
		moveToSection();
		//log('setSection()');
		setNavButtonLinks();
		
		//set the url to current subpage in the new section if none is defined
		//if (!_subpage) sectionArray[inCurrentSection].isMovingIn(); //do this in hashchange() instead
		
		//return true;
	} else {
		
		//return false;
	}
	
	if (!_first) {
		var currentSection = sectionArray[inCurrentSection];
		currentSection.hashChange(_subpage);
	}
}

function moveToSection() {
	//move holder
	var toLeft	= Math.round((SECTION_WIDTH + sectionMargin) * inCurrentSection);
	//log('SECTION_WIDTH = ' + SECTION_WIDTH);
	//log('sectionMargin = ' + sectionMargin);
	//log('inCurrentSection = ' + inCurrentSection);
	
	if (SUPPORT_3D_TRANSFORMS) {
		sectionHolder.setStyle(CSS_TRANSFORM_PREFIXED, 'translate3d(-' + toLeft + 'px, 0, 0)');
	} else if (SUPPORT_TRANSFORMS) {
		sectionHolder.setStyle(CSS_TRANSFORM_PREFIXED, 'translate(-' + toLeft + 'px, 0)');
	} else {
		sectionHolder.animateStyle('left', '-' + toLeft + 'px');
	}
	
	//sectionHolder.animateStyle('left', '-' + toLeft + 'px');
}

function setNavButtonLinks() {
	var nextPage	= PAGES[inCurrentSection+1];
	var prevPage	= PAGES[inCurrentSection-1]
	
	if (nextPage > numSections-1) nextPage = numSections-1;
	if (prevPage < 0) prevPage = 0;
	
	nextBtn.set('href', '#!/' + nextPage);
	prevBtn.set('href', '#!/' + prevPage);
	if (PAGES[inCurrentSection+1]) nextBtn.set('title', TO_PAGE_TEXT + PAGES[inCurrentSection+1]);
	if (PAGES[inCurrentSection-1]) prevBtn.set('title', TO_PAGE_TEXT + PAGES[inCurrentSection-1]);
}

function positionAndResize() {
	sectionHolder.setStyle('width', Math.round( (SECTION_WIDTH * numSections) + (sectionMargin * (numSections + 1)) ) + 'px');
	$$('section').setStyle('margin-left', sectionMargin + 'px');
	
	//set height of sections
	for (var i=0, max=sectionArray.length; i<max; i++) {	
		var section	= sectionArray[i];
		section.onResize(windowWidth, windowHeight);
	}
	
	var navLeft		= Math.round((windowWidth * .5 )- (mainNav.getSize().x * .5));
	mainNav.setStyle('left', navLeft + 'px');
	
	moveToSection();
	//moveToSubsection();
	
	if (lightbox) lightbox.resize(windowWidth, windowHeight);
}

function handleResize() {
	windowWidth		= $(window).getSize().x;
	windowHeight	= $(window).getSize().y;
	sectionMargin	= Math.round( (windowWidth - SECTION_WIDTH) / 2 );
	
	positionAndResize();
}


function setInitalOpacity() {
	var selectors	= ['.imgText', '.lightbox .bg'];
	var alpha		= [0, .5];
	
	if (!SUPPORT_OPACITY) {
		for (var i=0; i<selectors.length; i++) {
			var selector	= selectors[i];
			$$(selector).setStyle('opacity', alpha[i]);
		}
	}
}

function setupAnimations() {
	
	if (SUPPORT_TRANSFORMS || SUPPORT_3D_TRANSFORMS) {
		//this.slideContainer.setAnimationProperties(['all'], [SLIDE_SPEED], [SLIDE_EASE], [0], true);
		sectionHolder.setAnimationProperties(['all'], [700], [''], [0]);
		$$('.scrollContent').setAnimationProperties(['all'], [500], [''], [0]);
	} else {
		sectionHolder.setAnimationProperties(['left'], [700], [''], [0]);
		$$('.scrollContent').setAnimationProperties(['margin-top'], [500], [''], [0]);
	}
	
	$$('.projectImage a').setAnimationProperties(['opacity'], [300], [''], [0]);
	
}
