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){
     $scope.images = getQueryVariable("images").split(",");
     $scope.links = getQueryVariable("links").split(",");
     var wiki = getQueryVariable("wiki") || "scp-wiki";
     var page = getQueryVariable("page");
    
     for(var i = 0; i < $scope.images.length; i++) { // >
       if(!/^https?:\/\//.test($scope.images[i]))
         $scope.images[i] = `http://${wiki}.wdfiles.com/local--files/${page}/${$scope.images[i]}`;
     }
     // $scope.images is an array of image URLs
     if($scope.links[0] == "{$links}")
     $scope.links = []; // no parameter given
    
     $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";
    }
})();
