function getQueryVariable(variable) {
  var query = document.location.href.match(/\?.*$/g)[0].substring(1);
  var vars = query.split("&");
  for(var i = 0; i < vars.length; i++) { // >
    var pair = vars[i].split("=");
    if(pair[0] === variable) return pair[1]; 
  }
  return false;
}

(function(){
  var carousel = angular
    .module('carousel',[])
    .controller('CarouselController',CarouselController);
  
  CarouselController.$inject = ['$scope','$timeout'];
  function CarouselController($scope,$timeout){
    var wiki = getQueryVariable("wiki") || "scp-wiki";
    var page = getQueryVariable("page");

    var style = getQueryVariable("style");
    if (style !== "{$style}") {
      var styleElement = document.createElement("style");
      document.head.appendChild(styleElement);
      styleElement.appendChild(document.createTextNode(atob(style)));
    }

    var images = getQueryVariable("images").split(",");
    $scope.images = images.map(image => {
      if (!/^https?:/.test(image)) {
        // Make a full URL for the specified page
        return `https://${wiki}.wdfiles.com/local--files/${page}/${image}`;
      }
      return image;
    })

    var links = getQueryVariable("links");
    $scope.links = links !== "{$links}" ? links.split(",") : [];
    
    $scope.index = 0;
    $scope.increment = function(amount) {
      if(amount > 0 && $scope.index < $scope.images.length-1) { 
        $scope.index += amount;
      }
      if(amount < 0 && $scope.index > 0) { 
        $scope.index += amount;
      }
      $scope.state = "pause";
    }
    
    var interval = getQueryVariable("interval") || 0;
    if(interval === "{$interval}") interval = 0;
    $scope.state = "play";
    if(interval === 0) $scope.state = "pause";
    function oscillate() {
      $timeout(function() {
        if(!mouseover && $scope.state === "play") {
          if($scope.index < $scope.images.length-1) {
            $scope.index++;
          } else {
            $scope.index = 0;
          }
        }
        if($scope.state === "play") {
          oscillate();
        }
      }, interval*1000, true);
    }
    
    var mouseover = false;
    document.documentElement.onmouseover = function () {
      mouseover = true;
    }
    document.documentElement.onmouseout = function () {
      mouseover = false;
    }
    
    if($scope.state === "play") {
      oscillate();
    }
    document.getElementById('background').style.background = getQueryVariable("background");
    
    $scope.selectImage = function(index) {
      $scope.index = index;
      $scope.state = "pause";
    }
    
    $scope.control = function(direction) {
      switch(direction) {
        case "play":
          $scope.state = "play";
          oscillate();
          break;
        case "pause":
          $scope.state = "pause";
          break;
      }
    }
    
    $scope.options = getQueryVariable("options");
    if($scope.options === "{$options}") $scope.options = "yes";
  }
})();
