if (typeof gsi == "undefined") {
    gsi = {};
}

if (typeof gsi.gs == "undefined") {
    gsi.gs = {};
}

gsi.gs.PictureViewer = Class.create({
    pictureArray: null,
    currentPictureIndex: 0,

    imagePath: null,
    suffix: null,

    killAutoDisplay: true,

    autoStartLabel: null,
    autoStopLabel: null,            

    initialize: function(imagePath, suffix, autoStartLabel, autoStopLabel) {
        this.imagePath = imagePath;
        this.suffix = suffix;

        this.autoStartLabel = autoStartLabel;
        this.autoStopLabel = autoStopLabel;
    },

    nextPicture: function() {
        var newPictureIndex = this.currentPictureIndex > (this._getNumberOfPictures() - 2)
                ? 0
                : this.currentPictureIndex + 1;
        this.showPicture(newPictureIndex);
    },

    previousPicture: function() {
        var newPictureIndex = this.currentPictureIndex < 1
                ? this._getNumberOfPictures() - 1
                : this.currentPictureIndex - 1;
        this.showPicture(newPictureIndex);
    },

    showPicture: function(pictureIndex) {
        this.currentPictureIndex = pictureIndex;
        MM_swapImage('visBilde', '', this.imagePath + this.pictureArray[this.currentPictureIndex] + this.suffix, 1);
    },

    setupAutoDisplay: function() {
        if (this.killAutoDisplay) {
            $('autoDisplay').innerHTML = this.autoStopLabel;
            this.killAutoDisplay = false;
            this.autoDisplay();
        } else {
            $('autoDisplay').innerHTML = this.autoStartLabel;
            this.killAutoDisplay = true;
        }
    },

    autoDisplay: function() {
        if (this.killAutoDisplay) {
            return;
        }
        this.nextPicture();

        var self = this;
        setTimeout(function(){ self.autoDisplay(); }, 1500);
    },

    loadImages: function(lineId) {
        var that = this;
        that.killAutoDisplay = true;
        new Ajax.Request('/gsi/gs/companyDetailsJson.c', {
            method: 'get',
            requestHeaders: {Accept: 'application/json'},
            parameters: {
                lineId: lineId,
                jsonPictureIdArrayDisplay: true
            },
            onSuccess: function(transport) {
                that.currentPictureIndex = 0;
                that.pictureArray = transport.responseText.evalJSON(true);
            }
        });
    },

    _getNumberOfPictures: function() {
        return (this.pictureArray == null || this.pictureArray.length < 1
                ? 0
                : this.pictureArray.length);
    }

});

