var goBackground = function (game, options, api) {
    var self = {};
    self.name = "";
    var layerGroups = [];
    var groundBlocks = { name: "", layers: [] };

    self.getObject = function () {
        //TODO: Fixme
        return layerGroups;
    }

    self.moveObject = function (relX, worldX) {
        for (var x = 0; x < groundBlocks.layers.length; x++) {
            var speed = groundBlocks.layers[x][1];
            var removeFirst = false;
            var addNew = false;
            layerGroups[x].forEach(function (member) {
                member.x -= speed;
                if (member.x < -member.width) {
                    removeFirst = true;
                }
            }, this);
            var lastObj = layerGroups[x].getAt(layerGroups[x].countLiving() - 1);
            if (lastObj.x + lastObj.width <= game.width) {
                addNew = true;
            }
            if (removeFirst) {
                layerGroups[x].removeChildAt(0);
            }
            if (addNew) {
                var bgBlock = game.add.sprite(game.width, 0, self.name + x);
                bgBlock.height = game.height;
                layerGroups[x].add(bgBlock);
            }
            
        }
    }

    self.preload = function () {
        for (var i = 0; i < groundBlocks.layers.length; i++) {
            game.load.image(self.name + i, groundBlocks.layers[i][0]);
        }
    }

    self.SetConfig = function (groundObject) {
        groundBlocks = groundObject;
        self.name = groundObject.name;
    }

    self.create = function () {
        for (var x = 0; x < groundBlocks.layers.length; x++) {
            var backgroundLayer = game.add.group();
            
            // Add the ground blocks, enable physics on each, make them immovable
            var cWidth = 0;

            while (cWidth < game.width) {
                var rbgBlock = game.add.sprite(cWidth, 0, self.name + x);
                rbgBlock.height = game.height;
                cWidth += rbgBlock.width - 10;
                backgroundLayer.add(rbgBlock);
            }
            layerGroups.push(backgroundLayer);
            game.world.sendToBack(backgroundLayer);
        }
    }

    return self;
}