window.addEvent('domready', init);
var IE = Browser.Engine.trident;
function init() {
    $$('a').each(function(item) {
        if (item.get('href') && item.get('rel') == 'external') item.set('target', '_blank');
    });
    //banners750x100();
    if ($('table')) {
        $('table').getElement('table').setStyle('float', 'none');
        new Table();
    }

    if ($('panel-shoutbox')) {
        new Shoutbox();
    }
}

function correctPath(path) {
    return path.replace(/(src\s*=\s*['|"])(..\/)+/g, "$1" + basedir);
}

var Shoutbox = new Class({
    initialize: function() {
        var form = $('panel-shoutbox').getElement('form');
        this.textarea = form.getElement('textarea');
        this.textarea.set('name', 'shout_message');
        this.name = form.getElement('input[type=text]');
        if (!this.name) this.name = new Element('input', {'type': 'text'});
        this.sender = form.getElement('input[type=submit]');
        this.sender.set('name', 'post_shout');
        this.shoutsBox = $('panel-shoutbox').getElement('div');
        this.shouts = this.shoutsBox.getElement('ol');
        this.upBtn = $('shoutbox-controls').getFirst('a').getNext('a');
        this.downBtn = $('shoutbox-controls').getLast('a');
        this.refreshBtn = $('shoutbox-controls').getFirst('a');
        this.speed = 5;
        this.edit = 0;
        this.init();
        this.height = this.shouts.getSize().y - this.shoutsBox.getSize().y;
        this.fx = new Fx.Scroll(this.shoutsBox, {
            onComplete: function() {
                if (this.actualStep == this.scrollSteps.length - 3) {
                    this.load(this.shouts.getChildren('li').length - 1);
                }
            }.bind(this)
        });
        this.downBtn.addEvent('click', function(e) {
            e.preventDefault();
            this.scroll(1);
        }.bind(this));
        this.upBtn.addEvent('click', function(e) {
            e.preventDefault();
            this.scroll(-1);
        }.bind(this));
        this.refreshBtn.addEvent('click', function(e) {
            e.preventDefault();
            this.refresh();
        }.bind(this));
        this.sender.addEvent('click', function(e) {
            e.preventDefault();
            if (this.textarea.get('value') != "") {
                this.textarea.set('disabled', 'disabled');this.sender.set('disabled', 'disabled');
                this.spinner(true);
                new Request.JSON({url: 'infusions/shoutbox_panel/action.php', onSuccess: function(response) {
                    response.each(function(data, index) {
                        if (index == 0) {
                            this.spinner(false);
                            this.textarea.erase('disabled');this.sender.erase('disabled');
                            this.textarea.set('value', '');
                            this.fx.start(0, 0);
                            Growl.Smoke({text: data['message']});
                        } else {
                            this.addItem(data, 'top');
                        }
                    }.bind(this));
                }.bind(this)}).post({
                    'shout_message': this.textarea.get('value'),
                    'shout_name': this.name.get('value'),
                    'shout_id': this.edit,
                    's_action': this.edit ? 'edit' : ''
                });
            }
        }.bind(this));
        this.shouts.getElements('li').each(function(li) {
            this.activateButtons(li);
        }.bind(this));
    },

    init: function() {
        this.pos = 0;
        this.calculate();
        this.actualStep = 0;
    },

    refresh: function() {
       this.init();
       this.shouts.empty();
       this.spinner();
       this.fx.start(0, 0);
       this.load(0);
    },

    spinner: function(add) {
        if (!$defined(add) || add == true) this.shouts.grab(new Element('li', {'class': 'loading'}), 'top');
        else this.shouts.getFirst('li').dispose();
    },

    load: function(shout) {
       if (!$defined(shout)) shout = 0;
       new Request.JSON({url: 'infusions/shoutbox_panel/data.php', onSuccess: function(response) {
            this.spinner(false);
            response.each(function(data) {
                this.addItem(data);
            }.bind(this));
            this.calculate();
       }.bind(this)}).get({'shout': shout});
    },
    
    addItem: function(data, position) {
        var update = false, li, even = false;
        if (!$defined(position)) position = 'bottom';
        if (position == 'top')
            even = this.shouts.getFirst('li') && !this.shouts.getFirst('li').hasClass('even');
        else
            even = this.shouts.getLast('li') && !this.shouts.getLast('li').hasClass('even');
        if ($('shout-' + data['shout_id'])) update = true;
        if (update) {
            li = $('shout-' + data['shout_id']).empty();
            li.appendText(': ');
        } else {
            li = new Element('li', {
                id: 'shout-' + data['shout_id'],
                html: ': '
            });
            if (even) li.addClass('even');
        }
        li.grab(new Element('p', {'html': correctPath(data['shout_message'])}));
        var name;
        if (data['user_name'])
            name = new Element('a', {'href': data['user_link'], 'html': data['user_name']});
        else
            name = new Element('strong', {'html': data['shout_name']});
        var span = new Element('span');
        span.grab(name, 'top');
        if (data['can_edit']) span.grab(new Element('b'));
        if (data['can_del']) span.grab(new Element('b'));
        li.grab(span, 'top');
        span.appendText(data['shout_datestamp'] + ' ', 'top');
        if (!update) this.shouts.grab(li, position);
        this.activateButtons(li);
    },

    activateButtons: function(li) {
        li.set('tween', {
            onComplete: function() {
                new Request.JSON({url: 'infusions/shoutbox_panel/action.php', onSuccess: function(response) {;
                    Growl.Smoke({text: response[0]['message']});
                    li.dispose();
                    this.calculate();
                }.bind(this)}).post({
                    's_action': 'delete',
                    'shout_id': li.get('id').substr(6)
                });
            }.bind(this)
        });
        var button = li.getElement('b');
        if (button) {
            button.addEvent('click', function() {
                var text = li.getElement('p').get('html');
                text = text.replace(/<img(.*?)alt="([^"]+?)"(.*?)>/g, '$2');
                text = text.replace(/<span style="color: ([a-z]+);">(.*?)<\/span>/g, '[color=$1]$2[/color]');
                text = text.replace(/<((\/?)[b|i|s])>/g, '[$1]');
                this.textarea.set('text', text);
                this.edit = li.get('id').substr(6);
            }.bind(this));
            button = button.getNext('b');
            if (button) {
                button.addEvent('click', function() {
                    li.tween('height', 0);
                }.bind(this));
            }
        }
    },

    scroll: function(direction) {
        this.actualStep = (this.actualStep + direction).limit(0, this.scrollSteps.length - 1);
        this.fx.start(0, this.scrollSteps[this.actualStep]);
    },

    calculate: function() {
        this.scrollSteps = [0];
        var height = 0, tHeight = 0;
        var shouts = this.shouts.getChildren('li');
        var windowHeight = this.shoutsBox.getSize().y;
        for (var i = 0; i < shouts.length; i++) {
            if (i % 2 == 0) shouts[i].removeClass('even');
            else shouts[i].addClass('even');
            var elHeight = shouts[i].getComputedSize({
                styles: ['padding', 'border', 'margin'],
                mode: 'vertical'
            }).totalHeight;
            if (height + elHeight > windowHeight) {
                tHeight += height;
                this.scrollSteps.push(tHeight);
                height = 0;
            }
            height += elHeight;
        }
        if (this.scrollSteps[this.scrollSteps.length - 1] != tHeight) this.scrollSteps.push(tHeight);
    }

});

var Table = new Class({
    initialize: function() {
        this.days = Array();
        this.temp = null;
        this.days[1] = $('table').getElement('table').getFirst('tbody').clone();
        $$('#table ol > li > a').each(function(item, index) {
            item.addEvent('click', function(e) {
                $$('#table ol > li > a').removeClass('active');
                var loading = new Element('tr').grab(new Element('td', {
                    'class' : 'loading',
                    'colspan' : 12
                }));
                if (index != 7) e.preventDefault();
                if (index < 7) {
                    if (this.temp) {
                        $('table').getElement('table').dispose();
                        $('table').getElement('div.paddingEl').grab(this.temp);
                        this.temp = null;
                    }
                    $$('#table table > thead th').each(function(item) {
                        item.setStyle('width', item.getSize().x - item.getStyle('padding-left').toInt() - item.getStyle('padding-right').toInt() - item.getStyle('border-right-width').toInt() - item.getStyle('border-left-width').toInt());
                    });
                    item.set('class', 'active');
                    var tbody = $('table').getElement('table').getFirst('tbody');
                    tbody.empty();
                    if (this.days[index]) {
                        this.days[index].clone().replaces(tbody);
                        this.refreshScroll();
                    } else {
                        tbody.grab(loading);
                        new Request.JSON({url: 'infusions/types_panel/data.php', onSuccess: function(response) {
                            this.days[index] = this.fetchDay(response);
                            this.days[index].clone(true, true).replaces(tbody);
                            this.refreshScroll();
                        }.bind(this)}).get({'tab': index - 1});
                    }
                } else if (index == 8) {
                    this.getEff(index);
                }

            }.bind(this));
        }.bind(this));
        this.scroll = new MooScroll({
            selector: '#scrollbar',
            disabledOpacity: 1
        });
        this.scrollContent();
        //this.upBtnDown();
    },

    fetchDay: function(response) {
        var tbody = new Element('tbody');
        if (response == false) {
            var tr = new Element('tr').inject(tbody);
            new Element('td', {
                'text': "Brak typów na ten dzień",
                'colspan': 12
            }).inject(tr);
            return tbody;
        }
        var disc = response[0];
        var book = response[1];
        response.each(function(r, i) {
            if (i > 1) {
                d = disc[r['gd']];
                b = book[r['tb']];
                var tr = new Element('tr');
                if (i % 2 == 0) tr.set('class', 'odd');
                tr.inject(tbody);
                new Element('td', {'text': r['gt']}).inject(tr);
                new Element('td', {
                    'class': 'name'
                }).grab(new Element('span', {
                    'text': ' ' + r['p1'] + ' - ' + r['p2']
                }).grab(new Element('img', {
                    'src': 'infusions/types_panel/images/disciplines/' + d['dim'],
                    'alt': d['bn'],
                    'title': d['bn']
                }), 'top')).inject(tr);
                new Element('td').grab(new Element('img', {
                    'src': 'infusions/types_panel/images/nationalities/' + r['gc'] + '.gif',
                    'alt': r['gc'],
                    'title': r['gc']
                })).inject(tr);
                new Element('td', {'text': r['tt']}).inject(tr);
                new Element('td', {'text': r['tc']}).inject(tr);
                //new Element('td', {'text': r['tc2']}).inject(tr);
                //new Element('td', {'text': r['tc3']}).inject(tr);
                new Element('td', {'class': 'ans', 'text' : r['gp'] + '/10'}).inject(tr);
                var td = new Element('td');
                if (r['gs']) td.set({'class': r['s'] ? 'win' : 'lose', 'text': r['gs']});
                td.inject(tr);
                new Element('td').grab(new Element('a', {'href': b['bu'], 'rel': 'external'}).grab(
                new Element('img', {
                    'src': 'infusions/types_panel/images/bookmakers/' + b['bim'],
                    'alt': b['bn'],
                    'title': b['bn']
                }))).inject(tr);
            }
        });
        return tbody;
    },

    refreshScroll: function() {
        var height = $('table').getElement('table').getScrollSize().y;
        //console.log($('scrollbar').getStyle('max-height').toInt());
        if (height > $('scrollbar').getStyle('max-height').toInt()) height = $('scrollbar').getStyle('max-height').toInt();
        $('scrollbar').setStyle('height', height);
        $('scrollbar').getElement('.contentEl').setStyle('height', height);
        $('scrollbar').getElement('.scrollHandle').setStyle('top', 0);
        this.scroll.refresh();
    },

    scrollContent: function() {
        var now = new Date();var today = new Date().format('%x') + ' ';
        var height = 0;
        $('table').getElement('table').getFirst('tbody').getChildren('tr').each(function(item) {
            if (now - new Date(today + item.getFirst('td').get('text')) > 0) height += item.getComputedSize().totalHeight;
        });
        this.scroll.setSlider(height + $('table').getElement('tr').getComputedSize().totalHeight);
    },

    getEff: function(index, date) {
        new Request.HTML({url: 'infusions/types_panel/effectivity.php' + ($chk(date) ? date : ''), onSuccess: function(response) {
            this.days[index] = response[0];
            $('table').getElement('table').getFirst('tbody').empty();
            this.temp = $('table').getElement('table').clone(true, true);
            $('table').getElement('table').dispose();
            $('table').getElement('div.paddingEl').grab(this.days[index].clone(true, true));
            $('eff_month_changer').addEvent('change', function(e) {
                this.getEff(index, '?month=' + e.target.get('value') + '&year=' + $('eff_year_changer').get('value'));
            }.bind(this));
            new SortingTable($('table').getElement('table'), {
                zebra: true,                        // Stripe the table, also on initialize
                details: false,                     // Has details every other row
                dont_sort_class: 'nosort'          // Class name on th's that don't sort
            });
            this.refreshScroll();
        }.bind(this)}).get();
    }
});