window.addEvent('domready', init);
var IE = Browser.Engine.trident;
function init() {
    $$('a').each(function(item) {
        if (item.get('href') && (item.get('rel') == 'external' || item.get('title') == 'autolink')) item.set('target', '_blank');
    });
    $$('.disabled a, .disabled input').each(function(item) {
        item.addEvent('click', function(e) {
            e.preventDefault();
        });
    });
    //$('header').getElement('div').getElement('div').getElement('p').getLast('strong').set('text', $('footer').getLast('a').get('text'));
    $$('.delete').addEvent('click', function(e) {
        deleteMessage(e);
    });
    $$('form').each(function(form) {
        form.getElements('[class^=form-]').each(function(item) {
            item.addEvent('blur', function () {
                checkFormItem(item);
            });
        });
        form.addEvent('submit', function(e) {
            if (e.event.explicitOriginalTarget.name.indexOf('reset_') != 0) {
                result = true;
                form.getElements('[class^=form-]').each(function(item) {
                    if (!checkFormItem(item)) result = false;
                });
                if (!result) e.preventDefault();
            }
        });
    });
    $$('#content div.table > h2:first-child > span').each(function(item) {
        if (!item.get('id')) {
            var parent = item.getParent('div').getFirst('ol');
            parent.addClass('scroll');
            var step = parent.getSize().y;
            var limit = parent.getScrollSize().y - step;
            var scrollTo = 0;
            item.getFirst('b').addEvent('click', function() {
                scrollTo = (scrollTo + step).limit(0, limit)
                parent.scrollTo(0, scrollTo);
            });
            item.getLast('b').addEvent('click', function() {
                scrollTo = (scrollTo - step).limit(0, limit)
                parent.scrollTo(0, scrollTo);
            });
        }
    });
    //banners750x100();
    var tips = new Tips($$('#panel-last-threads a[title]', '#table td[class=name]', 'table.slim tr.type td[title]', 'table.chart th img[title]', 'table td:first-child span[title]', '#panel-last-seen img[title]'), {
        'text': function(el) {
            if (title = el.get('title'))
                return title.replace(/\|/gi, '<br />').replace(/([a-ząćęłńóśźż /]+:)/gi, '<strong>$1</strong> ');
            return null;
        },
        'title': '',
        'className': 'tooltip'
    });
    if ($('table')) {
        $('table').getElement('table').setStyle('float', 'none');
        new Table({'tips': tips});
    }

    $$('div.bbcodes').each(function(div) {
        //if ($('panel-shoutbox')) div.hide();
        var name = 'bbcode-';
        textarea = div.getParent('form').getElement('textarea[name=' + div.get('id').substr(name.length) + ']');
        //div.getElements('img').combine(div.getElements('input[type=image]')).each(function(item) {
        div.getChildren().each(function(item) {
            var bb = item.get('alt');
            if (!bb) bb = item.get('name');
            if (item.tagName == "SELECT") {
                item.addEvent('change', function() {
                    if (item.get('value')) {
                        switch (bb) {
                            case 'slims':
                                textarea.insertAtCursor('[kupon]' + item.get('value') + '[/kupon]', false);
                                break;
                            case 'size':
                            case 'color':
                                textarea.insertAroundCursor({before: '[' + bb + '=' + item.get('value') + ']', after: '[/' + bb + ']'}, false);
                                break;
                            default:
                                break;
                        }
                    }
                });
            } else if (bb) item.addEvent('click', function(e) {
                e.preventDefault();
                if (bb.charAt(0) == '\\') {
                    code = bb.substr(1);
                    textarea.insertAroundCursor({before: '[' + code + ']', after: '[/' + code + ']'}, false);
                } else {
                    textarea.insertAtCursor(bb, false);
                }
            });
        });
    });

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

    if ($('panel-an')) {
        var lis = $$($('panel-an').getElement('ol').getChildren());
        var tabs = $$($('panel-an').getElement('ol').getNext('ol').getChildren());
        tabs.each(function(item, index) {
            item.addEvent('click', function() {
                tabs.removeClass('active');
                this.addClass('active');
                lis.addClass('hidden');
                lis[index].removeClass('hidden');
            });
        })
        //console.log(lis, tabs);
    }

    if ($$('body.page-edit_profile').length) {
       if (document.location.hash) {
           input = $(document.location.hash.substr(1)).getNext();
           input.addClass('highlight');
           input.getParent().grab(new Element('div', {
               'text': input.get('title')
           }));
       }
    }


    if ($$('body.page-tv_schedule').length) {
        new Tabs($('side-center').getElement('div[class=ajax]'), '#side-center > ul.tabs li', {
            JSON: false
        });
    }
    if ($$('body.page-viewthread').length) {
        base = $('side-center').getElement('.t-main');
        if (base.getNext('a')) {
            base.getNext('a').addEvent('click', function(e) {
                e.preventDefault();
                $('side-center').getElement('form').getElements('input[type=checkbox]').set('checked', true);
            });
            base.getNext('a').getNext('a').addEvent('click', function(e) {
                e.preventDefault();
                $('side-center').getElement('form').getElements('input[type=checkbox]').set('checked', false);
            });
        }
    }
    if ($('table-analysises')) insertChart($('chart-holder'));
    if ($('table-profile')) {
        if ($('history-games')) insertChart($('table-profile').getElement('div[class=ajax]'));
        new Tabs($('table-profile').getElement('div[class=ajax]'), '#table-profile > ul.tabs li', {
            url: path + "includes/profile-modules.php",
            JSON: false,
            onSuccess: function(obj, response) {
                var div = new Element('div', {
                    'html': response
                });
                if (div.getElement('table') && div.getElement('table').get('id') == 'history-games') {
                    insertChart(div);
                }
                if (div.getElement('table.slim')) {
                    $(div).getElements('table.slim tr.type').each(function(item) {
                        chkType(item);
                    });
                    tips.attach(div.getElements('table.slim tr.type td[title]'));
                }
                obj.toInsert = div;
            },
            urlParams: function(obj) {
                var params = /([^,]+),([^,]+),([^,]+)\.html/.exec(obj.get('file'));
                return 'lookup=' + params[1] + '&module=' + params[3];
            }
        });
    }
    
    $$('table.slim tr.type').each(function(item) {
        if ($$('body.page-user_types').length == 0) chkType(item);
    });
    if (Browser.Engine.trident) {
        $$('td', 'th').each(function(item) {
            if (!item.innerHTML) item.innerHTML = '&nbsp;';
        });
    }
}

function chkType(item) {
    var resultCell = item.getLast('td');
    var score = resultCell.getPrevious('td');
    var players = item.getElement('td.players');var type = null;var rate = null;var prediction = null;var edit = false;
    if (admin) {
        type = players.getNext('td');
        rate = type.getNext('td');
        prediction = rate.getNext('td');
        players.getPrevious('td').addClass('cursor').addEvent('click', function() {
            if (edit) return false;
            edit = true;
            var value = players.get('text').split(" - ");
            value[2] = type.get('text');
            value[3] = rate.get('text');
            value[4] = prediction.get('text').substr(0, prediction.get('text').indexOf('/'));
            var textbox = new Element('input', {'type': 'text'});
            players.empty();type.empty();rate.empty();prediction.empty();
            players.adopt(textbox.set('value', value[0]), textbox.clone().set('value', value[1]));
            type.grab(textbox.clone().set('value', value[2]));
            rate.grab(textbox.clone().set('value', value[3]));
            prediction.grab(textbox.clone().set('value', value[4])).appendText('/100');
            if (!score.getElement('input')) {
                var sc = score.get('text').split(":");
                score.empty();
                score.grab(textbox.clone().set('value', sc[0]))
                    .appendText(':')
                    .grab(textbox.clone().set('value', sc[1]));
            }
            resultCell.addClass('ok');
        });
    }
    resultCell.addEvent('click', function() {
        var input = score.getElement('input');
        if (!input) return false;
        toSend = {
            "type_id": item.get('id').substr(1),
            "val1": input.get('value'),
            "val2": input.getNext('input').get('value')
        };
        if (admin && players.getElement('input')) {
            toSend = $merge(toSend, {
                'player1': players.getElement('input').get('value'),
                'player2': players.getLast('input').get('value'),
                'type': type.getElement('input').get('value'),
                'rate': rate.getElement('input').get('value'),
                'prediction': prediction.getElement('input').get('value')
            })
        }
        new Request({
            url: path + 'infusions/types_panel/set_slimdata.php',
            onSuccess: function(response){
                if (response != "error") {
                    score.empty();
                    if (admin && players.getElement('input')) {
                        players.empty();type.empty();rate.empty();prediction.empty();
                        players.appendText(toSend.player1 + ' - ' + toSend.player2);
                        type.appendText(toSend.type);
                        rate.appendText(toSend.rate);
                        prediction.appendText(toSend.prediction + '/100');
                        resultCell.removeClass('ok');
                    }
                    score.appendText(toSend.val1 + ":" + toSend.val2);
                    if (response == "true") {
                        resultCell.addClass("win");
                    } else {
                        resultCell.addClass("lose");
                    }
                    edit = false;
                }
            }.bind(this)
        }).post(toSend);
    });
}
	/*function edit(type_id) {
		var cell = $("edit#" + type_id).up();
		cell = $(cell).next();
		if (cell.innerHTML.charAt(0) != '<") {
			var re = /<.*>/g;
			var value = cell.innerHTML.replace(re, "");
			var value = value.split(" - ");
			cell.innerHTML = '<input type="text" id="S' + type_id + '#player1" value="' + value[0] + '" class="edit-textbox" style="width: 140px;" />';
			cell.innerHTML += '-<input type="text" id="S' + type_id + '#player2" value="' + value[1] + '" class="edit-textbox" style="width: 140px;" />';
			cell = $(cell).next();
			cell.innerHTML = '<input type="text" id="S' + type_id + '#type" value="' + cell.innerHTML + '" class="edit-textbox" />';
			cell = $(cell).next();
			cell.innerHTML = '<input type="text" id="S' + type_id + '#rate" value="' + cell.innerHTML + '" class="edit-textbox" />';
			cell = $(cell).next();
			value = cell.innerHTML.split("/");
			cell.innerHTML = '<input type="text" id="S' + type_id + '#prediction" value="' + value[0] + '" class="edit-textbox" style="width: 20px;" />/100';
			cell = $(cell).next();
			if (cell.innerHTML.charAt(0) != '<") {
				value = cell.innerHTML.split(":");
				if (value[0] = "-") {
					value[0] = "';
					value[1] = "';
				}
				cell.innerHTML = '<input type="text" id="S' + type_id + '#1" value="' + value[0] + '" class="score-textbox" />';
				cell.innerHTML += ':<input type="text" id="S' + type_id + '#2" value="' + value[1] + '" class="score-textbox" />';
			}
			cell = $(cell).next();
			cell.innerHTML = '<img src="'.SITEURL.'infusions/types_panel/images/ok.gif" alt="ok" onclick="chk_type(' + type_id + ')" class="score-button" />';
		}
	}*/

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

var Tabs = new Class({
    Implements: [Events, Options],
    options: {
        url: '',
        cache: true,
        JSON: true,
        activeClass: 'active',
        loadingClass: 'loading',
        onSuccess: function(obj, response) {
            obj.toInsert = response;
        },
        urlParams: function(obj) {
            return obj.get('query');
        }
    },

    initialize: function(container, tabs, options) {
        this.container = $(container);
        this.tabs = $$(tabs);
        this.response = null;
        this.setOptions(options);
        this.build();
    },

    build: function() {
        this.tabs.each(function(item) {
            item = item.getElement('a');
            item.addEvent('click', function(e) {
                e.preventDefault();
                if (this.selected != item) {
                    this.selected = item;
                    this.container.empty();
                    this.getData(item);
                }
            }.bind(this));
        }.bind(this));
    },

    getData: function(item) {
        if (toInsert = item.retrieve('toInsert')) {
            this.insert(toInsert, item);
        } else {
            var href = item.get('href');
            var linkURI = new URI(href);
            this.container.addClass(this.options.loadingClass);
            if (this.options.JSON) var req = Request.JSON;
            else var req = Request;
            new req({
                url: this.options.url ? this.options.url : href,
                method: 'get',
                onSuccess: function(response){
                    var toInsert = this.fireEvent('onSuccess', [this, response]).toInsert;
                    this.insert(toInsert, item);
                    this.container.removeClass(this.options.loadingClass);
                    item.store('toInsert', $type(toInsert) == 'element' ? toInsert.clone() : toInsert);
                }.bind(this)
            }).send(this.options.url ? this.options.urlParams(linkURI) : null);
        }
    },

    insert: function(toInsert, item) {
        this.tabs.removeClass(this.options.activeClass);
        item.getParent('li').addClass(this.options.activeClass);
        if ($type(toInsert) == 'element') this.container.adopt(toInsert);
        else this.container.innerHTML = toInsert;
        $$('.delete').addEvent('click', function(e) {
            deleteMessage(e);
        });
    }
});

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('b').getNext('b');
        this.downBtn = $('shoutbox-controls').getFirst('b');
        this.refreshBtn = $('panel-shoutbox').getElement('form').getElement('b');
        this.smileysBtn = this.refreshBtn.getNext('b');
        this.sticky = $('panel-shoutbox').getElement('form').getElement('label');
        if (this.sticky) this.sticky = this.sticky.getElement('input');
        else this.sticky = null;
        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.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));
        if (this.smileysBtn) this.smileysBtn.addEvent('click', function(e) {
            $('panel-shoutbox').getElement('div.bbcodes').toggle();
            if (this.sticky) this.sticky.getParent().toggle();
        }.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' : '',
                    'sticky': this.sticky ? this.sticky.get('checked') : ''
                });
            }
        }.bind(this));
        this.shouts.getElements('li').each(function(li) {
            this.activateButtons(li);
        }.bind(this));
        //$('bbcode-shout_message').grab(new Element('div', {'class': 'smiley'}).adopt($('bbcode-shout_message').getElements('img')));
        //$('bbcode-shout_message').grab(new Element('div', {'class': 'bbcode'}).adopt($('bbcode-shout_message').getElements('input')));
    },

    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';
        var first;
        if (position == 'top') {
            this.shouts.getElements('li').each(function(item) {
                if (first == null && item.hasClass('sticky') == false) first = item;
            });
            even = first && !first.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');
        }
        if (data['shout_sticky'] != 0) li.addClass('sticky');
        else li.removeClass('sticky');
        data['classes'].each(function(item) {
            li.addClass(item);
        });
        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) {
            if (position == 'bottom') this.shouts.grab(li, position);
            else li.inject(first, 'before');
        }
        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(/<a(.*?) title="(.*?)">www<\/a>/g, '$2');
                text = text.replace(/<a(.*?)>(.*?)<\/a>/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('value', text);
                this.edit = li.get('id').substr(6);
                if (this.sticky) this.sticky.set('checked', li.hasClass('sticky'));
            }.bind(this));
            button = button.getNext('b');
            if (button) {
                button.addEvent('click', function() {
                    if (window.confirm('Potwierdzenie spowoduje usunięcie. Kontynuować?')) {
                        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({
    Implements: Options,
    options: {
        tips: null
    },
    initialize: function(options) {
        this.days = Array();
        this.temp = null;
        this.setOptions(options);
        this.days[1] = this.replace($('table').getElement('table').getFirst('tbody'));
        this.options.tips.attach(this.days[1].getElements('tr > td:first-child + td'));
        $$('#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.replace(this.days[index]).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.options.tips.attach(this.days[index].getElements('tr > td:first-child + td'));
                            this.replace(this.days[index]).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.refreshScroll();
        this.scrollContent();
        //this.upBtnDown();
    },
    
    refreshScroll: function() {
        var height = $('table').getElement('table').getScrollSize().y;
        var max = $('scrollbar').getStyle('max-height').toInt();
        if (height > max) height = max;
        $('scrollbar').setStyle('height', height);
        $('scrollbar').getElement('.contentEl').setStyle('height', height);
        this.scroll.refresh();
        this.scroll.setSlider(0);
        $('scrollbar').getElement('.scrollHandleTop').setStyle('float', 'left');
        $('scrollbar').getElement('.scrollHandleTop').setStyle('float', 'none');
    },

    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);
    },

    replace: function(tbody) {
        replace = new Element('tbody');
        tbody.getElements('tr').each(function(item) {
            toGrab = item.clone();
            from = item.getElement('td:first-child + td');
            if (from)
                toGrab.getElement('td:first-child + td').cloneEvents(from).store('tip:text', from.retrieve('tip:text'))
            replace.grab(toGrab);
        });
        return replace;
    },

    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',
                    title: r['tip']
                }).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', {'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);
                var td = new Element('td');
                if (r['gtr']) td.grab(new Element('a', {'href': r['gtr'], 'rel': 'external', 'class': 'trans'}));
                if (r['gl']) td.grab(new Element('a', {'href': r['gl'], 'rel': 'external', 'class': 'live'}));
                td.inject(tr);
                var td = new Element('td', {'class': 'ans'}).inject(tr);
                if (r['a']) {
                    td.grab(new Element('a', {'href': 'infusions/analysises_panel/analysis.php?id=' + r['a']}));
                } else {
                    td.set('title', 'Brak analizy');
                }
            }
        });
        return tbody;
    },

    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));
            
            //console.log(obj);
            this.refreshScroll();
        }.bind(this)}).get();
    }
});

function jumpforum(forum_id) {
    document.location.href = 'forum,' + forum_id;
}
function checkFormItem(item) {
    ok = true;
    value = item.get('value');
    re = /^[0-9,.]*$/;
    if (item.hasClass('form-req')) {
        if ((item.type != "select-one" && value == "") || (item.type == "select-one" && item.options[item.selectedIndex].text == "- Wybierz -"))
            ok = false;
        else
            ok = true;
    }
    if (item.hasClass('form-num')) {
        if (value) {
            if (!re.test(value)) {
                item.set('value', '');
                ok = false;
            } else {
                ok = true;
            }
        }
    }
    if (ok) {
        item.setStyle('border-color', 'green');
        return true;
    } else {
        item.setStyle('border-color', 'red');
        item.focus();
        return false;
    }
}
function insertChart(div) {
    var temp = new Element('div', {
        'id': 'eff-chart'
    });
    div.grab(temp, 'top');
    flash = newChart(1);
    var select = new Element('select', {id: 'month-changer'}).addEvent('change', function() {
        flash = newChart(this.get('value')).replaces(flash);
    });
    select.adopt(
        new Element('option', {value: '1', text: 'Miesiąc'}),
        new Element('option', {value: '3', text: 'Kwartał'}),
        new Element('option', {value: '6', text: 'Pół roku'}),
        new Element('option', {value: '12', text: 'Rok'}),
        new Element('option', {value: '120', text: 'Wszystkie'})
    );
    temp.grab(select, 'top');
    temp.grab(flash, 'top');
}
function newChart(time) {
    var params, text;
    if ($('table-profile')) text = location.pathname;
    else if ($('table-analysises')) text = $('analysis-author').get('href');
    params = /profil,([0-9]+),([^,.]+)/.exec(text);
    return new Swiff(path + 'includes/OFC/open-flash-chart.swf', {
        width: 738,
        height: 200,
        params: {
            'wmode': 'transparent',
            'bgcolor': 'ffffff',
            'quality': 'high',
            'flashvars': 'data-file=' + escape(path + 'includes/profile-results.php?id=' + params[1] + '&name=' + params[2] + '&time=' + time)
        }
    });
}
function deleteMessage(e) {
    if (!window.confirm('Potwierdzenie spowoduje usunięcie. Kontynuować?')) {
        e.preventDefault();
    }
}
