﻿var imageToggler = new Class({
    Implements: [Options],
    options: {
        imageWidth: 695
    },
    initialize: function (options) {
        this.setOptions(options);
        site.addEvent('toggleImage', function (containerId) { this._toggle($(containerId)); } .bind(this));       
        site.addEvent('imageloading', function (containerElt) { containerElt.store("curIndex", -1); this._toggle(containerElt); } .bind(this));
    },
    _toggle: function (container) {
        var curIndex = container.retrieve("curIndex", -1);

        var imgArr = container.getElements("div.produitBackground img");
        curIndex = (curIndex + 1) % imgArr.length;
        container.store("curIndex", curIndex);
        this._loading(container, imgArr[curIndex], function(cont, img) {this._fadein(cont, img);}.bind(this));
        var nextIndex = (curIndex + 1) % imgArr.length;
        if(container.getElement("div.produit_right a.thumb"))
            container.getElement("div.produit_right a.thumb").setStyle("background-image", "url(" + imgArr[nextIndex].get('data-js') + "?width=80&height=50&crop=auto)");
    },
    _fadein: function (container, image) {
        var fx = image.retrieve("fx", new Fx.Tween(image, { 'property': 'opacity' }));
        fx.cancel().set(0);
        var curZindex = container.retrieve('zindex', 0);
        curZindex += 1;
        image.setStyle('z-index', curZindex);
        container.store('zindex', curZindex);
        fx.start(1);
    },
    _loading: function (container, image, completeHandler, options) {
        if(!image.retrieve('loaded')){
            new Asset.image(image.get("data-js") + "?maxwidth=" + this.options.imageWidth + "&maxheight=445", {'onLoad' : function(e) { e.set('data-js', image.get("data-js")).replaces(image); image.store('loaded', true); completeHandler.pass([container, e], this)();}.bind(this) });   
        }
        else {
            completeHandler.pass([container, image], this)();
        }
    }
    
});
