/**
* AnimatedPanel
*
* Dependencies: MooTools 1.2
*
* @version			0.0.1
*
* @license			MIT-style license
* @author			Alexander Seel
* @copyright		Author
* @docmentation	
*/

var AnimatedPanel = new Class({

    Implements: [Events, Options],

    options: {
        onStart: $empty,
        onClickView: $empty,
        onAutoStop: $empty,
        onResized: $empty,
        onEmptyinit: $empty,
        bgColor: '#ffffff',
        childrenPerRow: 4,
        useMouseWheel: true,
        useKeyInput: true
    },

    initialize: function(element, options) {
        this.AnimatedPanel = element;
        this.setOptions(options);
        this.isFull = false;
        this.isLoading = false;
        this.inMotion = false;
        this.initElementWidth = Math.max(1, parseInt(this.AnimatedPanel.getSize().x / this.options.childrenPerRow));

        this.AnimatedPanel.addClass('ap').setStyles({
            'background-color': this.options.bgColor,
            'position': 'relative',
            'opacity': 0
        });

        if (this.options.useWindowResize) window.addEvent('resize', this.update.bind(this, 'init'));
        if (this.options.useMouseWheel || this.options.useSlider) this.AnimatedPanel.addEvent('mousewheel', this.wheelTo.bind(this));
        if (this.options.useKeyInput) document.addEvent('keydown', this.keyTo.bind(this));

        this.getElements(this.AnimatedPanel);
    },

    clearInit: function() {
        this.fireEvent('emptyinit');
    },

    getElements: function(el) {
        this.master = { 'images': [] };
        var els = el.getChildren();
        if (!els.length) { this.clearInit(); return; }
        $$(els).each(function(el) {
            var hash = $H(el.getElement('img').getProperties('src', 'title', 'alt', 'longdesc'));
            if (el.get('tag') == 'a') hash.combine(el.getProperties('href', 'rel', 'target', 'id'));
            this.master['images'].push(hash.getClean());
            el.dispose();
        }, this);
        this.clearMain();
    },

    clearMain: function() {

        this.AnimatedPanel.empty();
        this.addLoader();

    },

    getAnimatedPanelElements: function(key) {
        var els = [];
        this.master.images.each(function(el) {
            els.push(el[key]);
        });
        return els;
    },

    addLoader: function() {
        this.AnimatedPanel.store('height', this.AnimatedPanel.getSize().y);
        this.loader = new Element('div', { 'class': 'loader' }).inject(this.AnimatedPanel);
        new Fx.Tween(this.AnimatedPanel, {
            'duration': 800,
            'onComplete': this.preloadImg.bind(this)
        }).start('opacity', 1);
    },

    preloadImg: function() {
        this.loadedImages = new Asset.images(this.getAnimatedPanelElements('src'), {
            'onComplete': this.loaded.bind(this),
            'onProgress': this.createAnimatedPanelElement.bind(this)
        });
    },

    createAnimatedPanelElement: function(counter, i) {
        var obj = this.getCurrent(i);
        var img = this.loadedImages[i];
        obj['width'] = this.initElementWidth;
        obj['height'] = img.height / img.width * this.initElementWidth;
        img.removeProperties('width', 'height');
        var divleft = parseInt(i % parseInt(this.options.childrenPerRow)) * this.initElementWidth;
        var divtop = parseInt(i / parseInt(this.options.childrenPerRow)) * this.initElementWidth;
        obj['div'] = new Element('div').setStyles({
            'position': 'absolute',
            'height': obj['height'],
            'width': obj['width'],
            'top': divtop,
            'display': 'none',
            'left': divleft,
        }).inject(this.AnimatedPanel);
        if (obj['id'] != '') {
            obj['div'].setProperty('id', obj['id']);
        }       

        img.setStyles({ 'vertical-align': 'middle', 'text-align': 'center', 'width': '90%', 'height': '90%', 'cursor': 'pointer' });
        img.addEvents({ 'click': this.viewCallBack.bind(this, i), 'dblclick': this.viewCallBack.bind(this, i) });
        img.inject(obj['div']);
//      cvi_glossy.add(img, { shadow: 75, shade: 20 });
        this.loader.set('text', (counter + 1) + ' / ' + this.loadedImages.length);
    },

    loaded: function() {
        this.index = this.options.startIndex;
        this.iL = this.master.images.length - 1;
        new Fx.Tween(this.loader, {
            'duration': 800,
            'onComplete': this.createUI.bind(this)
        }).start('opacity', 0);
        this.process(0);
    },

    createUI: function() {
        this.loader.dispose();
        this.showUI();
    },

    showUI: function() {
        this.fireEvent('start');
        this.update();
    },

    getCurrent: function(index) {
        return this.master.images[$chk(index) ? index : this.index];
    },

    update: function(e) {
        this.isLoading = false;
    },
    viewCallBack: function(index) {
        if (this.index != index || this.inMotion) return;
        var el = $H(this.getCurrent());
        var returnObj = {};
        returnObj['coords'] = el.div.getElement('img').getCoordinates();
        el.each(function(v, k) {
            if ($type(v) == 'number' || $type(v) == 'string') returnObj[k] = v;
        }, this);
        this.fireEvent('clickView', returnObj);
    },

    wheelTo: function(e) {
        if (e.wheel > 0) this.shrinkSize();
        if (e.wheel < 0) this.growSize();
        e.stop().preventDefault();
    },
    keyTo: function(e) {
        switch (e.code) {
            case 37: e.stop(); this.shrinkSize(); break;
            case 39: e.stop(); this.growSize();
        }
    },
    growSize: function() {
        this.process(1);
    },
    shrinkSize: function() {
        this.process(-1);
    },
    process: function(x) {
        if (this.options.childrenPerRow + x > 0) {
            this.options.childrenPerRow += x;
        }
        this.initElementWidth = Math.max(1, parseInt(this.AnimatedPanel.getSize().x / this.options.childrenPerRow));
        var countPerRow = 0;
        var maxPerRow = this.options.childrenPerRow;
        var newElementWidth = this.initElementWidth;
        var images = this.loadedImages;
        this.master.images.each(function(el) {
            elw = el.width;
            elh = el.height;
            var divwidth = newElementWidth;
            var divheight = elh / elw * newElementWidth;
            var divleft = parseInt(countPerRow % parseInt(maxPerRow)) * newElementWidth;
            var divtop = parseInt(countPerRow / parseInt(maxPerRow)) * newElementWidth;
            el.div.setStyle('display', 'block');            
            countPerRow++;
            if (el.div) {
                if (el.div.fx) {
                    el.div.fx.cancel();
                }
                else {
                    el.div.fx = new Fx.Morph(el.div, { duration:  600 + countPerRow * 10, transition: Fx.Transitions.Expo.easeInOut });
					el.div.setStyle('z-Index',countPerRow+10);
                }
                el.div.fx.start({ 'width': divwidth, 'height': divheight, 'top': divtop, 'left': divleft });

            }
        });

    }
});

window.addEvent('domready', function() {
    $$('.AnimatedPanelieze').each(function(AnimatedPanel) {
        new AnimatedPanel(AnimatedPanel);
    });
});
