var RokMiN = {};
RokMiN.id = '#rokmicronews';
RokMiN.settings = {};
window.addEvent('load', function () {
    var rokmicronews = new RokMicroNews(RokMiN.id, {
        radius: 4,
        startHeight: 80,
        mousetype: 'click'
    })
});
var SortablesII = Sortables.extend({
    'move': function (event) {
        var now = event.page.y;
        this.previous = this.previous || now;
        var up = ((this.previous - now) > 0);
        var prev = this.active.getPrevious();
        var next = this.active.getNext();
        if (prev && prev.hasClass('micronews-drop')) prev = prev.getPrevious() || prev;
        if (next && next.hasClass('micronews-drop')) next = next.getNext() || next;
        if (prev && up && now < prev.getCoordinates().bottom) this.active.injectBefore(prev);
        if (next && !up && now > next.getCoordinates().top) this.active.injectAfter(next);
        this.tmp.injectAfter(this.active);
        this.previous = now
    },
    moveGhost: function (event) {
        var value = event.page.y - this.offset;
        value = value.limit(this.coordinates.top - 183, this.coordinates.bottom - this.ghost.offsetHeight - 183);
        this.ghost.setStyle('top', value);
        event.stop()
    },
    start: function (event, el) {
        this.active = el;
        this.coordinates = this.list.getCoordinates();
        if (this.options.ghost) {
            var position = el.getPosition();
            this.offset = event.page.y - position.y + 183;
            this.trash = new Element('div').inject(document.body);
            this.ghost = el.clone().inject(this.trash).setStyles({
                'position': 'absolute',
                'left': position.x,
                'top': event.page.y - this.offset
            });
            document.addListener('mousemove', this.bound.moveGhost);
            this.fireEvent('onDragStart', [el, this.ghost])
        }
        document.addListener('mousemove', this.bound.move);
        document.addListener('mouseup', this.bound.end);
        this.fireEvent('onStart', el);
        event.stop()
    }
});
var RokMicroNews = new Class({
    version: '0.1',
    options: {
        radius: 4,
        startHeight: 250,
        mousetype: 'click'
    },
    initialize: function (element, options) {
        this.container = $$(element)[0];
        if (!this.container) return false;
        this.setOptions(options);
        this.cookie = new Hash.Cookie('RokMicroNews', {
            duration: 30
        });
        this.selection = (window.ie) ? 'selectstart' : 'mousedown';
        var stopEvent = function (e) {
            new Event(e).stop()
        };
        var dummy = new Element('div', {
            'class': 'micronews-drop',
            'styles': {
                'position': 'absolute',
                'display': 'none'
            }
        }).inject(document.body),
        self = this;
        this.blocks = $$('.micronews');
        this.collapse = this.container.getElements('.collapse', '.expand');
        this.surrounds = this.container.getElements('.rokmicronews-surround');
        this.micro = {};
        this.status = {};
        this.sortables = this.doSortable(dummy);
        if (this.cookie.length) this.restore();
        this.blocks.each(function (block, i) {
            var index = i;
            this.micro[block.id] = {};
            var micro = this.micro[block.id],
            height = 0,
            listHeight;
            micro.headline = block.getElement('.micronews-headline');
            micro.wrapper = block.getElement('.micronews-article-wrapper');
            micro.articles = block.getElement('.micronews-articles').setStyle('height', this.options.startHeight);
            micro.entries = block.getElements('.micronews-articles .entry');
            micro.entriesFx = [];
            micro.mousetype = RokMiN.settings[block.id].mousetype;
            micro.inner = block.getElement('.micronews-inner').setStyle('overflow', 'hidden');
            micro.listWrapper = block.getElement('.micronews-list');
            micro.list = block.getElements('.micronews-list ul li');
            micro.fx = new Fx.Style(micro.inner, 'height', {
                wait: false,
                duration: 300
            });
            micro.open = (typeof this.status[block.id] == 'undefined') ? true : this.status[block.id];
            listHeight = micro.listWrapper.getSize().size.y;
            micro.entries.each(function (entry, i) {
                micro.entriesFx.push(new Fx.Style(entry, 'opacity', {
                    wait: false,
                    duration: 400
                }).set((!i) ? 1 : 0));
                
                var entryHeight = entry.getSize().size.y;
                if (entryHeight > height) height = entryHeight;
				entry.setStyles({
                    'position': 'absolute',
                    'top': micro.articles.getStyle('padding-top').toInt(),
                    'left': micro.articles.getStyle('padding-left').toInt()+10,
                    'right': micro.articles.getStyle('padding-right').toInt()+15,
					'bottom': micro.articles.getStyle('padding-bottom').toInt()+15
                });
            });
            micro.list.each(function (list, i) {
                if (!i) list.addClass('active');
                list.addEvent(micro.mousetype, function (e) {
                    new Event(e).stop();
                    micro.entriesFx.each(function (fx) {
                        fx.start(0)
                    });
                    micro.entriesFx[i].start(1);
                    micro.list.removeClass('active');
                    list.addClass('active')
                })
            },
            this);
            //alert("listHeight:"+listHeight + "height:" + height);
            micro.articles.setStyles({
                'position': 'relative',
                'height': Math.max(listHeight, height),
				'padding-bottom': 10
            });
            micro.height = micro.inner.getSize().size.y;
            if (this.collapse.length) {
                $(this.collapse[index]).addEvent('click', function (e) {
                    new Event(e).stop();
                    if (micro.open) {
                        self.show(0, block.id);
                        this.removeClass('collapse').addClass('expand')
                    } else {
                        self.show(micro.height, block.id);
                        this.removeClass('expand').addClass('collapse')
                    }
                    self.store()
                })
            };
            if (!micro.open) {
                this.show(0, block.id);
                this.collapse[i].removeClass('collapse').addClass('expand')
            }
        },
        this);
        if (!this.cookie.length) this.store()
    },
    show: function (amount, id) {
        switch (amount) {
        case 0:
            this.micro[id].open = false;
            this.micro[id].fx.start(0);
            break;
        default:
            this.micro[id].open = true;
            this.micro[id].fx.start(amount)
        }
        return this
    },
    doSortable: function (dummy) {
        var movers = this.container.getElements('.mover').setStyle('cursor', 'move'),
        self = this;
        if (movers.length == 1) {
            movers[0].remove();
            return false
        }
        return new SortablesII(this.container, {
            handles: movers,
            onComplete: this.store.bind(this),
            onDragStart: function (element, ghost) {
                var sizes = element.getCoordinates();
                var border = dummy.getStyle('border-width').toInt() || 0;
                ghost.inject(self.container);
                ghost.setStyles({
                    'opacity': 0.7,
                    'left': self.container.getParent().getStyle('padding-left').toInt(),
                    'width': sizes.width,
                    'height': sizes.height
                });
                this.tmp = new Element('div', {
                    'class': 'micronews-drop',
                    'styles': {
                        'width': sizes.width - (border * 2),
                        'height': sizes.height - (border * 2),
                        '-moz-border-radius': self.options.radius + 'px',
                        '-webkit-border-radius': self.options.radius + 'px'
                    }
                }).inject(element, 'before');
                element.setStyle('display', 'none')
            },
            onDragComplete: function (element, ghost) {
                element.setStyles({
                    'display': '',
                    'opacity': 1
                });
                ghost.remove();
                this.tmp.remove();
                this.trash.remove()
            }
        })
    },
    store: function () {
        var save = {};
        if (this.sortables) {
            var serialize = this.sortables.serialize(function (el) {
                return el.getElement('.micronews').id
            });
            serialize.each(function (block, i) {
                var micro = this.micro[block];
                save[i] = {
                    'open': micro.open,
                    'element': block
                }
            },
            this)
        } else {
            var hash = new Hash(this.micro);
            hash.each(function (value, key) {
                save[0] = {
                    'open': value.open,
                    'element': key
                }
            })
        };
        this.cookie.extend(save);
        return this
    },
    restore: function () {
        var hash = new Hash(this.cookie.obj),
        first = false;
        for (i = 0, l = hash.length; i < l; i++) {
            var el = $(hash.get(i).element);
            if (el) {
                el = el.getVeryParent('rokmicronews-surround');
                if (!i) {
                    first = el;
                    if (first) el.inject(this.container, 'top')
                } else {
                    var next = el.getPrevious();
                    if (next) {
                        next.inject(first ? first : el.getPrevious(), 'after');
                        first = el
                    }
                }
                this.status[hash.get(i).element] = hash.get(i).open
            }
        };
        return this
    }
});
RokMicroNews.implement(new Options);
Element.extend({
    getVeryParent: function (match) {
        var el = this;
        do {
            el = el.getParent()
        } while (!el.hasClass(match) || el.getTag() == 'body');
        return el
    }
});