var multX = 0;

var currentBigImageID; // id in rotation
var currentBigImages; // array of big images for rotation
var currentGallery; // gallery to rotate


var rotationInterval;
var rotationIntervals = new Array();
var countDown;
var countDownLength = 400;
var rotationEnabled = true;
var imageLoading = false;

var anchors;

var timeout;

var moving = true;
// For address
var baseURL;
var postSlug = "";
var baseTitle;
var currentPostID = -1;
var addressChange = false

// image navigation
var navigationFollowInterval;
var navX = 0;
var navY = 0;
var navTargetX = 0;
var navTargetY = 0;
var distX;
var distY;


function init(){
	baseURL = $.address.baseURL();
	baseTitle = $.address.title();
	$(window).resize(fit);
	$('#content').css('display', 'block');
	addMenuNavigation();
	$('.prev-next').css('opacity', '0');
	$('#content-holder').css('left', ($(window).width()) + "px");
	$('#content-holder').animate({
		left: '0px'
	}, 500, "easeOutQuint", function(){
		activateContent();
	});
	//activateContent();
	if($('.post-holder').length > 1){
		addKeyboardNavigation();
	}
	convertAnchorLinks();
	$('.post-holder:first').addClass('current-post');
}
function activateContent(){
	// load the first big image of every post
	loadFirstImages();
	// add the resizing listener to the window
	fit();
	setTimeout(initAddress, 400);
	$('.prev-next').animate({
		opacity: 1
	}, 200);
}
function convertAnchorLinks(){
	$('.entry a').each(function(){
		var href = $(this).attr('href');
		if(href.indexOf("#") != -1 && href.indexOf("#/") == -1){
			$(this).attr('href', href.split("#").join("#/"));
		}
	})
}
function addMenuNavigation(){
	$('a').click(function(event){
		var href = $(this).attr('href');
		if(href.indexOf(serverURL) != -1 && href.indexOf('wp-admin') == -1 && href.indexOf('mailto:') == -1){
			event.preventDefault();
			animatedURLChange($(this).attr('href'));
		}
	})
}
function animatedURLChange(_href){
	window.location.href = _href;
	/*$('#content-holder').animate({
		left: -$('#content').width() + 'px'
	}, 400, "easeInQuint", function(){
		window.location.href = _href;
	});*/
}
function loadFirstImages(){
	$('.gallery').each(function(){
		currentImageID = 0;
		if(isHome == true){
			currentImageID = Math.floor(Math.random() * getBigImages($(this)).length);
		}
		var currentGallery = $(this);
		var image = new Image();
		$(image).load(function(){
			currentGallery.prepend($(image));
			$(this).addClass("bigImage");
			fit();
			fadeInOpacity($(this), 500);
		}).attr({
			src: getBigImages($(this))[currentImageID],
			alt: getBigImages($(this))[currentImageID],
			id: "bigImage-0"
		});
	});
}
function fadeInOpacity(_target, _speed){
	_target.css('opacity', '0');
	_target.animate({
		opacity: 1
	}, _speed);
}
function getBigImages(gallery){
	var bigImages = new Array();
	gallery.find('.gallery-icon .imagelink').each(function(){
		var attachmentLink = $(this).attr('href');
		bigImages.push($(this).attr('href'));
	})
	return(bigImages);
}
///////////////////////////////////////////////////////////////////
//	image navigation / rotation
///////////////////////////////////////////////////////////////////
function startImageRotation(){
	currentGallery = $(".current-post").find(".gallery:first");
	if(currentGallery != undefined && currentGallery.length > 0){
		currentBigImages = getBigImages(currentGallery);
		if(currentBigImages.length > 1){
			// if a gallery exists and there are more than one image
			if(isHome != true){
				buildImageNavigation();
				currentGallery.after("<div class='timer-holder'><div class='timer-bar'></div></div>");
			}
			if(currentGallery.find('.bigImage').length > 0){
					currentImageID = currentGallery.find('.bigImage').attr('id').split("-")[1];
			} else {
				currentImageID = 0;
			}
			startRotationCountDown();
			fit();
		}
	}
}
function nextImage(){
	stopRotationCountDown();
	currentImageID ++;
	currentImageID >= currentBigImages.length ? currentImageID = 0 : 0;
	imageLoading = true;
	var image = new Image();
	$(image).load(function(){
		imageLoading = false;
		if(currentGallery.attr('id') == $(this).attr('alt')){
			var currentImage = $(this);
			$(this).addClass("bigImage");
			currentGallery.find(".bigImage:first").stop(true).fadeOut(200, function(){
				$(this).replaceWith(currentImage);
				fadeInOpacity(currentImage, 600);
				$('.timer-bar').css('display', 'block');
				fit();
			});
			//
			startRotationCountDown();
		} else {
			//trace("Image Rotation stopped")
		}
	}).attr({
		src: currentBigImages[currentImageID],
		alt: currentGallery.attr('id'),
		id: "bigImage-" + currentImageID
	});
}
function prevImage(){
	stopRotationCountDown();
	currentImageID --;
	currentImageID < 0 ? currentImageID = currentBigImages.length - 1 : 0;
	imageLoading = true;
	var image = new Image();
	$(image).load(function(){
		imageLoading = false;
		if(currentGallery.attr('id') == $(this).attr('alt')){
			var currentImage = $(this);
			$(this).addClass("bigImage");
			currentGallery.find(".bigImage:first").stop(true).fadeOut(200, function(){
				$(this).replaceWith(currentImage);
				fadeInOpacity(currentImage, 600);
				fit();
				startRotationCountDown();
			});
			//
			
		} else {
			//trace("Image Rotation stopped")
		}
	}).attr({
		src: currentBigImages[currentImageID],
		alt: currentGallery.attr('id'),
		id: "bigImage-" + currentImageID
	});
}
function buildImageNavigation(){
	rotationEnabled = true;
	$('.current-post .entry').append('<div class="imageNavigationHolder"><div class="imageNavigation"><a href="#" class="prevImage">«PREV</a><a href="#" class="playPause">PAUSE</a><a href="#" class="nextImage">NEXT»</a></div></div>');
	//$('.imageNavigationHolder').css('opacity', '0');
	$('.current-post .entry').unbind();
	$('.current-post .imageNavigation a').unbind();
	currentGallery.mouseenter(function(){
		//$('.imageNavigationHolder').stop(true).animate({opacity: 1}, 200);
		//navigationFollowInterval = setInterval(navigationFollowLoop, 1);
	});
	currentGallery.mousemove(function(e){
		navTargetX = e.pageX - currentGallery.offset().left;
		navTargetY = e.pageY - currentGallery.offset().top;
	});
	currentGallery.mouseleave(function(){
		//$('.imageNavigationHolder').stop(true).animate({opacity: 0}, 200);
		window.clearInterval(navigationFollowInterval);
	})
	$('.current-post .imageNavigation a').mouseenter(function(){
		if($(this).hasClass('nextImage')){
			$(this).stop(true).animate({
				backgroundPosition: '0'
			}, 400, 'easeOutQuint');
		} else {
			$(this).stop(true).animate({
				backgroundPosition: '-33'
			}, 400, 'easeOutQuint');
		}
		
	});
	$('.current-post .imageNavigation a').mouseleave(function(){
		if($(this).hasClass('nextImage')){
			$(this).stop(true).animate({
				backgroundPosition: '-33'
			}, 400, 'easeOutQuint');
		} else {
			$(this).stop(true).animate({
				backgroundPosition: '0'
			}, 400, 'easeOutQuint');
		}
	});
	$('.current-post .imageNavigation a').click(function(e){
		e.preventDefault();
		if(imageLoading != true){
			switch($(this).attr('class')){
				case "prevImage":
				prevImage();
				break;
				case "playPause":
				togglePlayPause($(this));
				break;
				case "nextImage":
				nextImage()
				break;
			}
		}
	})
}
function navigationFollowLoop(){
	navX += (navTargetX - navX) / 3;
	navY += (navTargetY - navY) / 3;
	console.log(navX);
	$('.imageNavigationHolder').css('left', navTargetX + 'px');
	$('.imageNavigationHolder').css('top', navTargetY + 'px');
}
function togglePlayPause(_button){
	if(rotationEnabled == true){
		rotationEnabled = false;
		stopRotationCountDown();
		_button.text('PLAY');
		_button.find('img').height(20);
	} else {
		$('.timer-bar').css('display', 'block');
		rotationEnabled = true;
		startRotationCountDown();
		_button.text('PAUSE');
		_button.find('img').height(20);
	}
}
function startRotationCountDown(){
	clearAllIntervals();
	if(rotationEnabled == true){
		countDown = countDownLength;
		rotationInterval = window.setInterval(rotationCountDown, 1);
		rotationIntervals.push(rotationInterval);
	}
}
function stopRotationCountDown(){
	$('.timer-bar').css('width', "0%");
	$('.timer-bar').css('display', 'none');
	clearAllIntervals();
}
function clearAllIntervals(){
	for(var i=0; i<rotationIntervals.length; i++){
		clearInterval(rotationIntervals[i]);
	}
	rotationIntervals.splice(0);
}
function rotationCountDown(){
	countDown --;
	$('.timer-bar').css('width', 100 - countDown / (countDownLength / 100) + "%");
	if(countDown < 0){
		nextImage();
	}
}
function stopImageRotation(){
	$('.timer-holder').remove();
	$('.imageNavigationHolder').remove();
	stopRotationCountDown();
}
function fit(){
	$('.post-holder').width($(window).width());
	$('#content').width($('.post-holder:last').position().left + $('.post-holder:last').width());
	var windowHeight = $(window).height();
	if(windowHeight < 600){
		windowHeight = 600;
	}
	var i = 0;
	$('.gallery').each(function(){
		var gallery = $(this);
		if(isHome == true){
			$(this).height(windowHeight - $(this).offset().top - 30);
		} else {
			$(this).height(windowHeight - $(this).offset().top - 60);
		}
		$(this).find('.bigImage').each(function(){
			setExactFit($(this), gallery);
		})
		i++;
	});
	$('.wpmaps').each(function(){
		$(this).height(windowHeight - $(this).offset().top - 30);
	});
	if(moving != true){
		$('#content-holder').scrollTo({top: 0, left:$('.current-post').position().left});
	}
	if(currentGallery != undefined && currentGallery.length > 0){
		$('.timer-holder').width(currentGallery.find('.bigImage:first').width());
		$('.timer-holder').css('top', currentGallery.position().top + currentGallery.find('.bigImage:first').height() - 10 + 'px');
	}
}
function setExactFit(image, container){
	var crop = false;
	containerRatio = container.width() / container.height();
	imageRatio = image.attr('width') / image.attr('height');
	
	var firstRatio;
	var secondRatio;
	
	if(isHome == true){
		crop = true;
	} else {
		crop = false;
	}
	if(crop == false){
		firstRatio = imageRatio;
		secondRatio = containerRatio;
	} else {
		firstRatio = containerRatio;
		secondRatio = imageRatio;
	}
	//
	if (firstRatio > secondRatio) {
		image.css('width', container.width());
		image.css('height', 'auto');
	} else {
		image.css('height', container.height());
		image.css('width', 'auto');
	}
	if(crop == true){
		image.css('left', (container.width() / 2 - image.width() / 2) + 'px');
		image.css('top', (container.height() / 2 - image.height() / 2) + 'px');
	}
	
}

///////////////////////////////////////////////////////////////////
//	jquery address
///////////////////////////////////////////////////////////////////
function initAddress(){
	addAddressLinks();
	reactToAddress($.address.path());
	$.address.change(function(event) {
		reactToAddress(event.value);
	});
	if($(".post-holder").length > 0 && $.address.value() == "/"){
		$.address.value($(".post-holder:first .post-anchor").attr('id'));
	}
}
function addAddressLinks(){
	$('a.prev-next').address(function(){
		return $(this).attr('href').split("#")[1];
	});
}
function reactToAddress(_path){
	// do something depending on the event.value property, e.g.
	if(_path.indexOf("/") == -1){
		_path = "/"+_path;
	}
	clearInterval(timeout);
	stopImageRotation();
	postSlug = _path.split("/")[1];
	if(_path != "/"){
		$(".post-holder").removeClass('current-post');
		moving = true;
		$("." + postSlug).addClass('current-post');
		$('.post-holder').css('height', 'auto');
		$.address.title(baseTitle + " | " + $('.current-post h2').text());
		$('#content-holder').scrollTo({top: 0, left:$('.current-post').position().left}, 400, {easing:'easeInOutQuint', onAfter:function(){
			moving = false;
			//fit();
		}});
		timeout = setTimeout(startImageRotation, 450);
	}
}
///////////////////////////////////////////////////////////////////
//	Keyboard Nav
///////////////////////////////////////////////////////////////////
function getAnchors(){
	anchors = new Array();
	$('.post-anchor').each(function(){
		anchors.push($(this).attr('id'));
		
	});
}
function addKeyboardNavigation(){
	getAnchors();
	$('body').keydown(function(e) {
		if(e.keyCode == "39"){
			nextPost();
		} else if(e.keyCode == "37"){
			if(addressChange != true){
				prevPost();
			}
		} else if(e.keyCode == "91"){
			addressChange = true;
		}
	});
	$('body').keyup(function(e){
		if(e.keyCode == "91"){
			addressChange = false;
		}
	})
}
function nextPost(){
	var path = $.address.value().replace("/", "");
	for(var i=0; i<anchors.length - 1; i++){
		if(anchors[i] == path){
			$.address.value(anchors[i+1]);
		}
	}
}
function prevPost(){
	var path = $.address.value().replace("/", "");
	for(var i=1; i<anchors.length; i++){
		if(anchors[i] == path){
			$.address.value(anchors[i-1]);
		}
	}
}
