var currentFace = -1;
var numberOfRandomFacesFromServer = 4;
var numberOfFaces = 6;

var currentColorIndex = 0;
var colorNames = ["#red", "#orange", "#yellow", "#green", "#blue", "#purple" ];
var colors = {
  "#red": { 
    normal: '#e88184', 
    highlighted: '#e60000' 
  }, 
  "#orange": { 
    normal: '#fec881', 
    highlighted: '#ff8d00' 
  }, 
  "#yellow": { 
    normal: '#fbf181', 
    highlighted: '#f5ec00' 
  }, 
  "#green": { 
    normal: '#92dc88', 
    highlighted: '#00c500' 
  }, 
  "#blue": { 
    normal: '#939fdc', 
    highlighted: '#390cc1' 
  }, 
  "#purple": { 
    normal: '#ba93dc', 
    highlighted: '#8800bf' 
  }
};

var interval = null;

var millisecondsBetweenFaces = 3000;
var millisecondsForTransition = 500;

function switchBackground(url) {
  var image = $("<img class='face' src='" + url + "' />");
  image.load(performSwitch(image));
  image.css('z-index', '10');
}

function highlightedColorValue(color) {
  return colors[color].highlighted;
}

function normalColorValue(color) {
  return colors[color].normal;
}

function changeBackgroundColor(color, newValue) {
  $('#rainbow ' + color).animate({ 'background-color': newValue }, millisecondsForTransition);
}

function fadeOutColor(color) {
  changeBackgroundColor(color, normalColorValue(color));
}

function fadeInColor(color) {
  changeBackgroundColor(color, highlightedColorValue(color));
}

function performSwitch(newImage) {
  newImage.unbind('load');
  
  var currentImage = $("#shadow > .face").first();
  newImage.insertAfter(currentImage);
  newImage = $("#shadow > .face").last();
  
  newImage.fadeOut(0);
  currentImage.fadeOut(millisecondsForTransition, function() {
    $(this).remove();
  })
  
  fadeOutColor(colorNames[currentColorIndex]);
  currentColorIndex++;
  if (currentColorIndex >= colorNames.length) {
    currentColorIndex = 0;
  }
  fadeInColor(colorNames[currentColorIndex]);
  
  newImage.fadeIn(millisecondsForTransition, function() {
    $(this).css('z-index', '11');
  });
}    

function showFace(faceNumber) {
  currentFace = faceNumber;
  var url = "/images/shadow-backgrounds/" + faceNumber + ".jpg"
  switchBackground(url);  
}

function nextFace() {
	if (currentFace == -1) {
		currentFace = initialRandomNumber();
	} else {	
		var newFace = randomFaceNumber();
		while (newFace == currentFace) {
			newFace = randomFaceNumber();
		}
		currentFace = newFace;
	}
  showFace(currentFace);
}

function initialRandomNumber() {
	return Math.floor(Math.random() * (numberOfFaces - numberOfRandomFacesFromServer)) + numberOfRandomFacesFromServer + 1;
}

function randomFaceNumber() {
	return Math.floor(Math.random() * numberOfFaces) + 1;
}

function startFaceAnimation() {
  interval = window.setInterval(nextFace, millisecondsBetweenFaces);
}

function stopFaceAnimation() {
  window.clearInterval(interval);
  $("#shadow > .face").dequeue();
  $("#shadow > .face").stop();
}

$(document).ready(function() {
  startFaceAnimation();  
});

