$(document).ready(initImages);
$(document).ready(initMoverAndButtons);
$(window).resize(initMoverAndButtons);
$(window).scroll(initMoverAndButtons);

// Opacity value of side images
var opacityValue = 0.3;
// Scroll speed
var speed = 1000;
// Total image in the slider
var totalImages = null;
// Relative index offset of the sliderMover (0=centered mover, +/- value=mover dislocated)
var currentOffset = 0;
// Current showed image index (from 0 to N-1 where N is the total number of projects)  
var currentImageIndex = 0;
// Activate debug in javascript console
var isDebug = false;

// Bind buttons press to scroll images
$(document).bind('keydown', function(event) {
	if (event.which == '37') // Arrow left key
		scrollImages(-1);
	else if (event.which == '39') // Arrow Right key 
		scrollImages(+1)
});

function initImages() {
	
	$('#projectSliderImage'+prevIndex(currentImageIndex)).css('left', -(projectImageWidth + projectImageGap));
	$('#projectSliderImage'+prevIndex(currentImageIndex)).animate({opacity:opacityValue}, 0);
	$('#projectSliderImage'+prevIndex(currentImageIndex)).show();

	$('#projectSliderImage'+currentImageIndex).css('left', 0);
	$('#projectSliderImage'+currentImageIndex).animate({opacity:1.0}, 0);
	$('#projectSliderImage'+currentImageIndex).show();

	$('#projectSliderImage'+nextIndex(currentImageIndex)).css('left', (projectImageWidth + projectImageGap));
	$('#projectSliderImage'+nextIndex(currentImageIndex)).animate({opacity:opacityValue}, 0);
	$('#projectSliderImage'+nextIndex(currentImageIndex)).show();
	
	// Init title
	$('#projectTitle' + currentImageIndex).show();
	
	// Load current images (other only when requested)
    loadImage('#projectSliderImage' + currentImageIndex);
    loadImage('#projectSliderImage' + nextIndex(currentImageIndex));
    loadImage('#projectSliderImage' + prevIndex(currentImageIndex));
		
	// Set click on current image
	enableImagesFunction();
	
}

function initMoverAndButtons() {
	var projectsSliderMoverLeft = getContainerOffset() - currentOffset * (projectImageWidth + projectImageGap);
	$('#projectsSliderMover').css('left', projectsSliderMoverLeft);
	//if (isDebug) console.log('initMoverAndButtons > currentImageIndex:' + currentImageIndex + ' currentOffset:' + currentOffset + ' projectsSliderMoverLeft:' + projectsSliderMoverLeft + 'px');

	// Position arrows
	$('.scrollLeftButton').css('left', getContainerOffset() - projectImageGap - 42);
	$('.scrollLeftButton').show();
	$('.scrollRightButton').css('left', getContainerOffset() + projectImageWidth + projectImageGap + 10);
	$('.scrollRightButton').show();
}

function getContainerOffset() {
	return $('#t_container').offset().left;
}

function prevIndex(index) {
	return getIndex(index, -1);
}

function nextIndex(index) {
	return getIndex(index, 1);
}

function getIndex(index, delta) {

	var newIndex = index + delta; 
	if (newIndex < 0)
		return getTotalImages() + newIndex;
	else if (newIndex > getTotalImages()-1)
		return newIndex - getTotalImages();
	else
		return newIndex;
}

function getTotalImages() {
	if (totalImages == null) {
		totalImages = $('.projectsSliderImage').length;
	}
	return totalImages;
}

function scrollImages(delta) {
	
	var imageIndex = getIndex(currentImageIndex, delta);
	scrollImagesToIndex(imageIndex);
}

function scrollImagesToIndex(imageIndex, playVideo) {

	if (imageIndex == currentImageIndex) {
		if (playVideo) 
			playCurrentVideoProject();
		return;
	}
	
	imageIndex = parseInt(imageIndex);
	
	// Calculate the correct delta (max = 3)
	var delta = imageIndex - currentImageIndex;
	if (Math.abs(getTotalImages() - imageIndex + currentImageIndex) < Math.abs(delta)) // any lower negative delta? 
		delta = -(getTotalImages() - imageIndex + currentImageIndex);
	if (Math.abs(getTotalImages() - currentImageIndex + imageIndex) < Math.abs(delta)) // any upper positive delta?
		delta = getTotalImages() - currentImageIndex + imageIndex;
	if (delta > 3)
		delta = 3;
	if (delta < -3)
		delta = -3;
	if (isDebug) console.log('delta:' + delta);
	
	// Stop video
	stopProject();

	if ($('#projectsSliderMover').queue()!=0)
		return;
	
	disableImagesFunction();

	// Update offset and current image
	currentOffset = currentOffset + delta;
	
	if (isDebug) console.log('scrollImages > imageIndex:' + imageIndex + ' delta:' + delta + ' currentOffset:' + currentOffset + ' currentImageIndex:' + currentImageIndex);

	// De-highlight central image
	//$('#projectSliderImage'+currentImageIndex).animate({opacity: opacityValue}, speed);

	// Prepare Central image
	if (Math.abs(delta) > 1) {
	    loadImage('#projectSliderImage'+imageIndex);
		$('#projectSliderImage'+imageIndex).show();
		$('#projectSliderImage'+imageIndex).css('left', (currentOffset) * (projectImageWidth + projectImageGap));
	}
	$('#projectSliderImage'+imageIndex).animate({opacity: 1.0}, speed);

	// Prepare previous image
	$('#projectSliderImage'+prevIndex(imageIndex)).animate({opacity: opacityValue}, speed);
	if (prevIndex(imageIndex) != currentImageIndex) {
	    loadImage('#projectSliderImage'+prevIndex(imageIndex));
		$('#projectSliderImage'+prevIndex(imageIndex)).show();
		$('#projectSliderImage'+prevIndex(imageIndex)).css('left', (currentOffset - 1) * (projectImageWidth + projectImageGap));
	}
	// Prepare Next image
	$('#projectSliderImage'+nextIndex(imageIndex)).animate({opacity: opacityValue}, speed);
	if (nextIndex(imageIndex) != currentImageIndex) {
	    loadImage('#projectSliderImage'+nextIndex(imageIndex));
		$('#projectSliderImage'+nextIndex(imageIndex)).show();
		$('#projectSliderImage'+nextIndex(imageIndex)).css('left', (currentOffset + 1) * (projectImageWidth + projectImageGap));
	}	

	// Move images
	var distance = delta * (projectImageWidth + projectImageGap);
	$('#projectsSliderMover').animate({
		left: '-='+distance
	}, speed, function() {
		// Animation complete, Hide unseen images
		$(".projectsSliderImage").each(function(index) {
			if ($(this).attr('id') != 'projectSliderImage'+prevIndex(imageIndex) &&
				$(this).attr('id') != ('projectSliderImage'+imageIndex) &&
				$(this).attr('id') != 'projectSliderImage'+nextIndex(imageIndex)) {
				//if (isDebug) console.log('Hide id:' + $(this).attr('id'));
				$(this).hide();
			}
		});
		if (playVideo)
			playCurrentVideoProject();
	});

	currentImageIndex = imageIndex;
	updateProjectTitle();
	enableImagesFunction();

}

function updateProjectTitle() {
	$('#projectTitleContainer > div').hide();
	$('#projectTitle' + currentImageIndex).show();
}

function disableImagesFunction() {
	// Remove click from leaving images
	//$('#projectSliderImage'+currentImageIndex).css('cursor', 'default');
	$('#projectSliderImage'+currentImageIndex).unbind('click');
	$('#projectSliderImage'+currentImageIndex).children(1).css('display', 'none'); // Disable video
	$('#projectSliderImage'+currentImageIndex).children(0).show();
	// Remove click from next and prev
	$('#projectSliderImage'+prevIndex(currentImageIndex)).unbind('click');
	$('#projectSliderImage'+nextIndex(currentImageIndex)).unbind('click');
}

function enableImagesFunction() {
	// Set click on current image
	//$('#projectSliderImage'+currentImageIndex).css('cursor', 'pointer');
	$('#projectSliderImage'+currentImageIndex).click(function() {
		//$(this).children(0).fadeOut('slow');
		// Go to project page
		var linkToVideo = 'projects/view/' + $(this).children(0).attr('id').replace('videoImage_projectId', '');
		location.href = linkToVideo;
	});
	$('#projectSliderImage'+currentImageIndex).children(1).css('display', 'block'); // Enable video

	// Add click to next and prev image
	$('#projectSliderImage'+nextIndex(currentImageIndex)).click(function() {
		scrollImages(+1);
	});
	$('#projectSliderImage'+prevIndex(currentImageIndex)).click(function() {
		scrollImages(-1);
	});
}

// Pagination
function goToPage(pageNumber) {
	
	$("#projectsListContainer").children().hide();
	$("#loadingBox").show();
	$.ajax({//data: 'imageModelName=' + imageModelName,
		dataType: "html",
		success: function (data, textStatus) {$("#projectsListContainer").html(data);},
		url: rootPathAction  + "projects/index/page:" + pageNumber}
	);
}

// Image loading utility function
function loadImage(imageContainer) {
	
	var tempAnchor = $(imageContainer).children('a:first');
	var tempAnchorId = tempAnchor.attr('id');
	var imagePath =	tempAnchor.attr('rel');
	if (imagePath == null) {
		$(imageContainer).children('img:first').hide().fadeIn('slow');
		return;
	}
	tempAnchor.remove();

	// new image object
	var img = new Image();
	$(img).attr('id', tempAnchorId);
	// load current image
	$(img).load(function () {
		// remove loading class
		$(imageContainer).removeClass('projectsSliderImageLoading').append(this);
		// fade it in
		$(this).hide().fadeIn('slow');
		if (isDebug) console.log('Image loaded: ' + $(img).attr('id'));

	}).error(function () {
		// if loading error remove container
		$(imageContainer).remove();
	}).attr('src', imagePath);
}

function playCurrentVideoProject() {
	
	if (isDebug) console.log('Play video:' + currentImageIndex);
	// Load video page
	$.ajax({dataType: "html",
		success: function (data, textStatus) {$("#videoPlayerContainer").html(data);},
		complete: function (jqXHR, textStatus) {$f("videoPlayer").addEvent("ready", videoPlayerReady);},
		url: rootPathAction  + "projects/video/" + currentImageIndex}
	);
	$('#videoPlayerContainer').show();
}

function videoPlayerReady(player_id) {
	
	if (isDebug) console.log(player_id + " is ready.");
	var froogaloopVideoPlayer = $f(player_id);
	froogaloopVideoPlayer.api('play');
	froogaloopVideoPlayer.removeEvent('ready');
	$('#videoPlayerContainer').css('visibility', 'visible');
}

function stopProject() {
	
	if (isDebug) console.log('Stop video');
	$('#videoPlayerContainer').hide().empty();
}


