var BackgroundImageRotatorModel = function(backgroundImageDetailsList) {
    this.detailsList = backgroundImageDetailsList;
    this.index = 0;
}

Object.extend(BackgroundImageRotatorModel.prototype, {
    nextBackgroundImage: function() {
        this.incrementIndex();
        this.loadImage();
    },

    previousBackgroundImage: function() {
        this.decrementIndex();
        this.loadImage();
    },

    loadImage: function() {
        var imageDetails = this.getImageDetailsForCurrentIndex();

        var image = new Image();

//        image.onload = this.onLoadListener.bind(this, imageDetails, image);
        image.onload = this.onLoadListener.bind(this, imageDetails, image);
//        image.onload = this.onErrorListener.bind(this, imageDetails, image);

        image.src = imageDetails.url;
    },
	
	loadRandomImage: function() {
		var imageDetails = this.getImageDetailsForRandomIndex();

        var image = new Image();

//        image.onload = this.onLoadListener.bind(this, imageDetails, image);
        image.onload = this.onLoadListener.bind(this, imageDetails, image);
//        image.onload = this.onErrorListener.bind(this, imageDetails, image);

        image.src = imageDetails.url;
	},
    getImageDetailsForCurrentIndex: function() {
        return this.detailsList.get(this.getCurrentIndex());
    },

	getImageDetailsForRandomIndex: function()
	{
	    var ranNum= Math.floor(Math.random()*(this.detailsList.getLength()-1));
	    return this.detailsList.get(ranNum);
	},
	
    incrementIndex: function() {
        var newIndex = this.index + 1;

        if (newIndex >= this.detailsList.getLength())
            newIndex = 0;

        this.index = newIndex;
        return newIndex;
    },

    decrementIndex: function () {
        var newIndex = this.index - 1;

        if (newIndex < 0)
            newIndex = this.detailsList.getLength() - 1;

        this.index = newIndex;
        return newIndex;
    },

    getCurrentIndex: function() {
        return this.index;
    },

    setOnLoadListener: function(func) {
        this.onLoadListener = func;
    },

    onErrorListener: function(event, imageDetails, image) {
        alert("There was an error loading the image with URL " + imageDetails.url);
    }
});





