var busyimg = new Image();
busyimg.src = "/img/busy.gif";

function pokazUkryte(guzik) {
    var obj = guzik.nextSibling;
    if (obj.style.visibility == "visible")
        obj.style.visibility = "hidden";
    else
        obj.style.visibility = "visible";
}

var AddNote = Class.create({
    initialize: function(url, selector, upbox, xid, hintbox, withnull) {
        this.hoverOn = -1;
        this.url = url;
        this.selector = $(selector);
        this.seloutsrc = this.selector.src;
        this.upbox = $(upbox);
        this.xid = xid;
        this.withnull = withnull;
        if (hintbox)
            this.hintbox = $(hintbox);
        this.voted = this.cancelled = false;
        this.clickCallback = function(x,n) { 
            trackEvent('note', 'anonymous');
            return true; 
        };
        this.successCallback = function(x){};
        this.completeCallback = function(x){};
        this.failureCallback = function(x){};
        this.preload = new Array();
        for (var i = withnull ? 0 : 1; i <= 10; i++) {
            this.preload[i] = new Image();
            this.preload[i].src = (withnull ? "/limg/notev" : "/img/noteg") + i + ".png";
        }
        if (this.hintbox) {
            this.digbox = document.createElement("div");
            this.digbox.appendChild(document.createTextNode(""));
            this.hintbox.appendChild(this.digbox);
            this.hintbox.appendChild(document.createTextNode(""));
        }
        this.selector.observe("mouseover", this.mousemove.bind(this));
        this.selector.observe("mousemove", this.mousemove.bind(this));
        this.selector.observe("mouseout", this.mouseout.bind(this));
        this.selector.observe("click", this.click.bind(this));
    },
    mousemove: function(evnt) {
        if (this.voted) return;
        if (this.hoverOn == -1 && this.hintbox) {
            this.hintbox.style.display = "block";
        };
        var x = Event.pointerX(evnt) - this.selector.cumulativeOffset().left;
        var xs = this.selector.getWidth() / (this.withnull ? 12 : 10);
        var n = Math.floor(x/xs) + (this.withnull ? -1 : 1);
        if (n < 0) n = 0;
        if (!this.withnull && n < 1) n = 1;
        if (n > 10) n = 10;
        if (n != this.hoverOn) {
            if (this.hintbox) {
                this.digbox.nextSibling.nodeValue = notedescr[n];
                this.digbox.firstChild.nodeValue = n ? n : "-";
            }
            this.selector.src = this.preload[n].src;
        }
        this.hoverOn = n;
    },
    mouseout: function(evnt) {
        if (this.voted) return;
        this.hoverOn = -1;
        if (this.hintbox)
            this.hintbox.style.display = "none";
        this.selector.src = this.seloutsrc;
    },
    click: function(evnt) {
        if (evnt.button != 0 || this.hoverOn == -1 || this.voted) return;
        this.addnote(this.hoverOn, evnt);
    },
    addnote: function(note, evnt) {
        if (this.voted) return;
        var ccret = this.clickCallback(evnt, note);
        if (!ccret) return;
        this.voted = true;
        var data = { note: note, xid: this.xid };
        if (typeof(ccret) == 'object') 
            data = Object.extend(data, ccret);
        new Ajax.Updater(this.upbox, this.url, {
            postBody: Object.toJSON(data),
            evalScripts: true,
            onSuccess: this.successCallback,
            onComplete: this.completeCallback,
            onFailure: this.failureCallback
        });
        if (this.hintbox)
            this.hintbox.style.display = "none";
        this.selector.insert({after: busyimg});
        this.selector.remove();
        this.hoverOn = -1;
    },
    delnote: function() {
        if (this.cancelled) return;
        this.cancelled = true;
        this.upbox.insert(new Element("div").update(busyimg));
        new Ajax.Updater(this.upbox, this.url, {
            postBody: Object.toJSON({ note: null, xid: this.xid }),
            evalScripts: true
        });
    }
});

var AddNoteExt = Class.create(AddNote, {
    initialize: function($super, url, selector, upbox, xid, hintbox, withnull) {
        $super(url, selector, upbox, xid, hintbox, withnull);
        this.clickCallback = function(evnt, note) {
            trackEvent('note', 'review');
            var vstat = $(selector).parentNode.down('select[name="vstat"]');
            var fav = $(selector).parentNode.down('input[name="fav"]');
            vstat.disable();
            fav.disable();
            if ($(selector).next("div"))
                $(selector).next("div").remove();
            return {vstat: vstat.getValue(), fav: fav.getValue()};
        };
    },
    showform: function(edit) {
        edit.setStyle({visibility: "hidden"});
        if ($(this.selector).next("div"))
            $(this.selector).next("div").setStyle({display: "block"});
        $(this.selector).previous("div").setStyle({display: "block"});
        $(this.selector).previous("div").previous("div").setStyle({display: "none"});
    }
});

var Scroller = Class.create({
    initialize: function(cnt, oname, total) {
        this.cur = 1;
        this.cnt = cnt;
        this.oname = oname;
        this.total = total;
    },
    shift: function(n) {
        var max = [this.cur + this.total-1, this.cnt].min();
        for (var i = this.cur; i <= max; i++) {
            $(this.oname+"img"+i).addClassName("invisible");
        }

        this.cur += n;
        if (this.cur < 1 || this.cur > this.cnt) this.cur -= n;

        max = [this.cur + this.total-1, this.cnt].min();
        for (var i = this.cur; i <= max; i++) {
            $(this.oname+"img"+i).removeClassName("invisible");
        }

        if (this.cur == 1) $("prev"+this.oname).style.visibility="hidden";
        else $("prev"+this.oname).style.visibility="visible";
        if (this.cnt == max) $("next"+this.oname).style.visibility="hidden";
        else $("next"+this.oname).style.visibility="visible";
    }
});

var ScreenChanger = Class.create(Scroller, {
    initialize: function($super, oname, total, screens) {
        $super(screens.length, oname, total);
        this.screens = screens;
        this.cache = new Array();
        this.preload();
    },
    shift: function($super, n) {
        $super(n);
        this.preload();
    },
    preload: function() {
        var max = [this.cur + this.total-1, this.cnt].min();
        for (var i = this.cur; i <= max; i++) {
            if (this.cache[i-1] != undefined) continue;
            this.cache[i-1] = new Image();
            this.cache[i-1].src = this.screens[i-1][0];
        }
    },
    sswitch: function(k) {
        $("img"+this.oname).src = this.screens[k-1][0];
        $("img"+this.oname).width = this.screens[k-1][1];
        $("img"+this.oname).height = this.screens[k-1][2];
    }
});

var CommentManager = Class.create({
    edited_message: "Czy na pewno chcesz zamknąć formularz edycji komentarza?",
    initialize: function(reqdata) {
        this.reqdata = reqdata;
        this.switching = false;
        this.count_edited = 0;
        this.count_posting = 0;
        this.cur_shift = -1;
        var bim = new Element("img", {src: busyimg.src});
        bim.setStyle({float: "right"});
        $("busyimgloc").hide();
        $("busyimgloc").appendChild(bim);
        this.currenthash = "";
        new PeriodicalExecuter((function(pe) {
            if (this.cur_shift < 0 || this.switching || this.currenthash == location.hash) return;
            this.currenthash = location.hash;
            this.locate_post_coid(this.currenthash.substr(1));
        }).bind(this), 1);
    },
    clean_added_posts: function(coid) {
        if (this.added_posts[coid]) {
            this.added_posts[coid].each(function(i){i.remove()});
            delete this.added_posts[coid];
        }
    },
    unfold_subtree_then: function(coid, then_do) {
        if (this.switching) return;
        if ($("unfolded"+coid).hasClassName("commentfold_u")) {
            then_do();
            return;
        }
        this.get_subtree_then(coid, then_do);
    },
    get_subtree: function(coid) {
        this.get_subtree_then(coid, function(){});
    },
    get_subtree_then: function(coid, then_do) {
        if (this.switching) return;
        var rpl = $("replies"+coid);
        if (rpl.unfolding) return;
        var unf = $("unfolded"+coid);
        if (!unf.hasClassName("commentfold_u")) {
            rpl.unfolding = true;
            var bim = new Element("img", {src: busyimg.src});
            bim.setStyle({marginLeft: "auto", marginRight: "auto", display: "block"});
            rpl.appendChild(bim);
            var onSuc = (function(x) {
                rpl.unfolding = false;
                this.clean_added_posts(coid);
                then_do();
            }).bind(this);
            new Ajax.Updater({success: rpl}, "/json_comments.php", {
                method: "get", 
                parameters: Object.extend({type: "subtree", coid: coid}, this.reqdata), 
                onFailure: this.reqFail, 
                onComplete: onSuc});
            unf.addClassName("commentfold_u");
        } else {
            if (this.forms_in_subtree[coid] &&
                this.forms_in_subtree[coid].any(function(p){
                    return p.value && $("openedform"+p.key).tanuki_edited;
                }) && !confirm(this.edited_message))
                return;
            delete this.forms_in_subtree[coid];
            rpl.childElements().each(function(i){i.remove()});
            unf.removeClassName("commentfold_u");
            this.clean_added_posts(coid);
        }
    },
    preloaded_comments: function(shift) {
        this.cur_shift = shift;
        if ($("openedform0")) $("openedform0").remove();
        this.added_posts = {};
        this.forms_in_subtree = {};
        this.count_edited = 0;
    },
    preloaded_go_to: function(coid, shift) {
        this.preloaded_comments(shift);
        var post = $("coid"+coid);
        if (post) post.scrollTo();
    },
    update_comments: function(shift) {
        this.update_comments_then(shift, function(){});
        trackPageview();
    },
    update_comments_then: function(shift, then_do) {
        if (this.switching || this.count_posting) return;
        if (this.count_edited && !confirm(this.edited_message)) return;
        if (this.cur_shift == shift) {
            then_do();
            return;
        }
        var old_shift = this.cur_shift;
        this.preloaded_comments(shift);
        this.switching = true;
        $("busyimgloc").show();
        var onSuc = (function(x) {
            $("busyimgloc").hide();
            this.switching = false;
            if (shift == 0) $("newposts").show();
            else $("newposts").hide();
            $("pagelinkA"+shift).addClassName("current");
            $("pagelinkB"+shift).addClassName("current");
            if (old_shift >= 0) {
                $("pagelinkA"+old_shift).removeClassName("current");
                $("pagelinkB"+old_shift).removeClassName("current");
            }
            then_do();
        }).bind(this);
        new Ajax.Updater({success: $("commentdata")}, "/json_comments.php", {
            method: "get", 
            parameters: Object.extend({type: "list", shift: shift}, this.reqdata), 
            onFailure: this.reqFail, 
            onComplete: onSuc});
    },
    addpost: function(coid, rootid) {
        if (this.switching) return;
        if ($("openedform"+coid)) {
            $("openedform"+coid).scrollTo();
            return;
        }
        if (!coid && this.cur_shift > 0) {
            this.update_comments_then(0, (function() {
                this.addpost(coid, rootid)
            }).bind(this));
            return;
        }
        var frame = new Element("div", {id: "openedform"+coid});
        if (rootid != coid) {
            if (!this.forms_in_subtree[rootid])
                this.forms_in_subtree[rootid] = new Hash();
            this.forms_in_subtree[rootid].set(coid, true);
        }
        var bim = new Element("img", {src: busyimg.src});
        bim.setStyle({marginLeft: "auto", marginRight: "auto", display: "block"});
        frame.appendChild(bim);
        frame.tanuki_posting = false;

        var ap = $("addpost"+coid);
        if (coid)
            ap.insert({before: frame});
        else
            ap.insert({after: frame});

        if (frame.offsetTop > window.scrollY + window.innerHeight ||
                frame.offsetTop + frame.offsetHeight < window.scrollY)
            frame.scrollTo();

        new Ajax.Updater({success: frame}, "/json_addcomment.php", {
            method: "get",
            parameters: Object.extend({parent: coid, rootid: rootid}, this.reqdata),
            evalScripts: true,
            onFailure: this.reqFail,
            onComplete: function(){
                var textarea = frame.down('textarea');
                textarea.writeAttribute('id', 'cedit'+coid);
                setupEditors(frame);
            }});
    },
    closeform: function(coid, rootid) {
        if (this.switching) return;
        if (!$("openedform"+coid) || $("openedform"+coid).tanuki_posting)
            return;
        if ($("openedform"+coid).tanuki_edited &&
                !confirm(this.edited_message)) return;
        $("openedform"+coid).remove();
        if (this.forms_in_subtree[rootid])
            this.forms_in_subtree[rootid].unset(coid);
    },
    submitpost: function(coid, rootid, sform) {
        if (this.switching) return;
        if (!$("openedform"+coid) || $("openedform"+coid).tanuki_posting)
            return;
        $(sform).disable();
        var bim = new Element("img", {src: busyimg.src});
        bim.setStyle({marginRight: "100px", verticalAlign: "middle"});
        sform["preview"].insert({before: bim});
        var pars = sform.getElements().inject({}, function(o,e) { o[e.name] = e.getValue(); return o; });
        delete pars.preview;
        pars.rootid = rootid; 
        pars = Object.extend(pars, this.reqdata);
        if (sform.flag) pars.flag = sform.flag.getValue();
        var callback_fun = (function(transport) {
            this.count_posting -= 1;
            $("openedform"+coid).tanuki_posting = false;
            var newcoid = transport.getHeader("X-Tanuki-NewCoid");
            trackEvent('comment', 'add');
            if (newcoid) {
                if (!this.added_posts[coid])
                    this.added_posts[coid] = new Array();
                this.added_posts[coid].push($("openedform"+coid));
                this.count_edited -= 1;
                if (this.forms_in_subtree[rootid])
                    this.forms_in_subtree[rootid].unset(coid);
                $("openedform"+coid).removeAttribute("id");
                if (rootid) {
                    $("unfolded"+rootid).setStyle({display: "block"});
                    $("responses"+rootid).firstChild.data =
                        parseInt($("responses"+rootid).firstChild.data) + 1;
                }
            }
        }).bind(this);
        if (this.action == "preview") pars.preview = "1";
        this.count_posting += 1;
        $("openedform"+coid).tanuki_posting = true;
        var frame = $("openedform"+coid);
        new Ajax.Updater({success: $("openedform"+coid)}, "/json_addcomment.php", {
            parameters: pars,
            evalScripts: true,
            onFailure: this.reqFail,
            onSuccess: callback_fun,
            onComplete: function(transport) {
                if (!transport.getHeader("X-Tanuki-NewCoid")) {
                    var textarea = frame.down('textarea');
                    textarea.writeAttribute('id', 'cedit'+coid);
                    setupEditors(frame);
                }
            }});
    },
    edited: function(coid) {
        if (!$("openedform"+coid) || $("openedform"+coid).tanuki_edited)
            return;
        $("openedform"+coid).tanuki_edited = true;
        this.count_edited += 1;
    },
    locate_post: function(coid, shift, ucoid) {
        var scrollTo = function() {
            var post = $("coid"+coid);
            if (post) post.scrollTo();
        };
        var doUnfold = (function() {
            this.unfold_subtree_then(ucoid, scrollTo);
        }).bind(this);
        if (!ucoid)
            this.update_comments_then(shift, scrollTo);
        else
            this.update_comments_then(shift, doUnfold);
    },
    locate_post_coid: function(coid) {
        if (this.switching) return;
        var post = $("coid"+coid);
        if (post) {
            post.scrollTo();
            return;
        }
        this.switching = true;
        $("busyimgloc").show();
        var onSuc = (function(transport) {
            this.switching = false;
            $("busyimgloc").hide();
            var loc = transport.headerJSON;
            this.locate_post(loc.coid, loc.shift, loc.unfold);
        }).bind(this);
        var onFail = (function(transport) {
            this.switching = false;
            $("busyimgloc").hide();
        }).bind(this);
        new Ajax.Request("/json_comments.php", {
            method: "get", 
            parameters: Object.extend({type: "locate", coid: coid}, this.reqdata), 
            onSuccess: onSuc, 
            onFailure: onFail});
    },
    moderate: function(coid) {
        if (this.switching) return;
        new Ajax.Updater({success: "postdata"+coid}, "/json_modcomment.php", {method: "get", parameters: {coid: coid, mode: this.reqdata.mode?this.reqdata.mode:""}});
    },
    hidepost: function(coid) {
        if (this.switching) return;
        new Ajax.Updater({success: "postdata"+coid}, "/json_comments.php", {method: "post", parameters: Object.extend({type: "hidepost", coid: coid}, this.reqdata)});
    },
    submitmoderate: function(coid, mform) {
        if (this.switching) return;
        $(mform).disable();
        var pars = mform.getElements().inject({}, function(o,e) { o[e.name] = e.getValue(); return o; });
        pars.coid = coid;
        pars = Object.extend(pars, this.reqdata);
        this.count_posting += 1;
        var callback_fun = (function(transport) {
            this.count_posting -= 1;
        }).bind(this);
        new Ajax.Updater({success: "postdata"+coid}, "/json_modcomment.php", {method: "post", parameters: pars, onComplete: callback_fun});
    },
    reloadonepost: function(coid) {
        if (this.switching) return;
        var pars = Object.extend(this.reqdata, {type: "onepost", coid: coid});
        new Ajax.Updater({success: "postdata"+coid}, "/json_comments.php", {method: "post", parameters: pars});
    },
    changeReqdata: function(mod) {
        if (this.switching) return;
        this.switching = true;
        new Ajax.Updater({success: "commentpage"}, "/json_comments.php", {
            method: "get",
            parameters: Object.extend(Object.extend({type: "modechange"}, this.reqdata), mod),
            evalScripts: true,
            onFailure: this.reqFail
        });
    },
    toggleParam: function(widget, param) {
        if (this.switching) return;
        widget.toggleClassName("chkbox_on");
        var r = {};
        if (widget.hasClassName("chkbox_on")) r[param] = 1;
        else r[param] = 0;
        this.changeReqdata(r);
    },
    reqFail: function(x) {
        alert("Błąd komunikacji z serwerem!");
    }
});

var DropDownSelector = Class.create({
    initialize: function(url, textfield, dropdownbox, datafield, callback, allownew, nonstrict) {
        this.seq = 0;
        this.url = url;
        this.textfield = $(textfield);
        this.dropdownbox = $(dropdownbox);
        this.datafield = datafield;
        this.current = $(textfield).value;
        this.mouseon = false;
        if (callback) this.callback = callback;
        else this.callback = function(a,b){};
        this.allownew = allownew;
        this.nonstrict = nonstrict;
        $(dropdownbox).style.width = ($(textfield).getWidth()-2) + "px";
        $(dropdownbox).observe("mouseover", 
            (function(){ this.mouseon = true; }).bind(this));
        $(dropdownbox).observe("mousemove", 
            (function(){ this.mouseon = true; }).bind(this));
        $(dropdownbox).observe("mouseout", 
            (function(){ this.mouseon = false; }).bind(this));
        $(textfield).setAttribute("autocomplete", "off");
        $(textfield).observe("focus", this.focushndlr.bind(this));
        $(textfield).observe("blur", this.blurhndlr.bind(this));
        $(textfield).observe("keydown", this.keydownhndlr.bind(this));
        $(textfield).observe("keypress", this.keypresshndlr.bind(this));
        new Form.Element.Observer(textfield, 0.5, this.onchange.bind(this));
    },
    onchange: function(el, value) {
        if (value == "" || value != this.current) {
            $(this.datafield).value = "";
            this.callback(null,null);
        }
        if (value != "" && value != this.current) {
            this.current = "";
            if ($(this.textfield).x_focused)
                $(this.dropdownbox).show();
            $(this.dropdownbox).update(new Element("div").update("Wyszukiwanie..."));
            var seq = ++this.seq;
            new Ajax.Request(this.url, {
                method: 'post',
                postBody: Object.toJSON({query: el.value}),
                onSuccess: (function(transport) {
                    if (seq < this.seq) return;
                    var result = transport.responseText.evalJSON();
                    if (result === null) {
                        $(this.dropdownbox).update(new Element("div").update("Zbyt dużo wyników."));
                    } else if (result.length == 0) {
                        if (this.allownew) {
                            var a = new Element("li").addClassName("hover").update("Dodaj: ");
                            var l = new Element("ul").insert(a);
                            a.appendChild(document.createTextNode(el.value));
                            a.observe("click", a.clickhandler = this.clickhndlr("", el.value));
                            $(this.dropdownbox).update(l);
                        } else {
                            $(this.dropdownbox).update(new Element("div").update("Brak wyników."));
                        }
                    } else {
                        var l = new Element("ul");
                        $(this.dropdownbox).update(l);
                        result.each((function(k){
                            var a = new Element("li").update(k[1]);
                            a.observe("click", a.clickhandler = this.clickhndlr(k[0],k[1]));
                            a.observe("mouseover", function() {
                                l.down("li.hover").removeClassName("hover");
                                a.addClassName("hover");
                            });
                            l.insert(a);
                        }).bind(this));
                        l.down("li").addClassName("hover");
                    }
                }).bind(this)
            });
        } else {
            $(this.dropdownbox).hide();
        }
    },
    clickhndlr: function(k,v) {
        return (function(ev) {
            this.mouseon = false;
            $(this.datafield).value = k;
            $(this.textfield).value = this.current = v;
            $(this.textfield).removeClassName("error");
            $(this.dropdownbox).update("").hide();
            this.callback(k,v);
        }).bind(this);
    },
    focushndlr: function(ev) {
        $(this.textfield).x_focused = true;
        $(this.textfield).removeClassName("error");
    },
    blurhndlr: function(ev) {
        if (this.mouseon) {
            Event.stop(ev);
            return false;
        }
        $(this.textfield).x_focused = false;
        (function() {
            if ($(this.textfield).x_focused) return;
            $(this.dropdownbox).hide();
            if (!this.nonstrict && $(this.textfield).value != this.current)
                $(this.textfield).addClassName("error");
        }).bind(this).defer();
    },
    keypresshndlr: function(ev) {
        if (ev.keyCode == Event.KEY_RETURN) {
            Event.stop(ev);
            return false;
        }
    },
    keydownhndlr: function(ev) {
        if (ev.keyCode == Event.KEY_RETURN) {
            var li1 = $(this.dropdownbox).firstChild.down("li.hover");
            if (li1) {
                li1.clickhandler(ev);
            }
            Event.stop(ev);
            return false;
        }
        if (ev.keyCode == Event.KEY_DOWN) {
            Event.stop(ev);
            var li1 = $(this.dropdownbox).firstChild.down("li.hover");
            var li2 = li1.next("li");
            if (li1 && li2) {
                li1.removeClassName("hover");
                li2.addClassName("hover");
                this.curhover++;
            }
            return false;
        }
        if (ev.keyCode == Event.KEY_UP) {
            Event.stop(ev);
            var li1 = $(this.dropdownbox).firstChild.down("li.hover");
            var li2 = li1.previous("li");
            if (li1 && li2) {
                li1.removeClassName("hover");
                li2.addClassName("hover");
                this.curhover--;
            }
            return false;
        }
    },
    forceSet: function(k,v) {
        $(this.datafield).value = k;
        $(this.textfield).value = this.current = v;
        $(this.textfield).removeClassName("error");
        var frame = $(this.textfield);
        if (frame.offsetTop > window.scrollY + window.innerHeight ||
                frame.offsetTop + frame.offsetHeight < window.scrollY)
            frame.scrollTo();
    }
});

var TurboVoter = Class.create({
    url: "/json_addnote.php?mode=userlist",
    initialize: function(name) {
        this.name = name;
        this.noteaddimg = new Image();
        this.noteaddimg.src = "/limg/noteva.png";
        this.curvalue = null;
        this.voting = false;
        this.editing = 0;
        this.ddsel = new DropDownSelector("/json_titlefind.php?q=search", name+"_title", 
                             name+"_dropdown", name+"_xid", this.onchange.bind(this));
    },
    onchange: function(key,value) {
        if (this.voting) return;
        $(this.name+"_wbox").update();
        if (key) {
            var x = new Element("img", {id: this.name+"_notesel"});
            x.src = this.noteaddimg.src;
            $(this.name+"_wbox").insert(x);
            var an = new AddNote(this.url, $(this.name+"_notesel"), $(this.name+"_notebox"), key, $(this.name+"_notehintbox"), true);
            an.clickCallback = (function(x,n) {
                if (this.editing) return false;
                trackEvent('note', 'listadd');
                $(this.name+"_title").disable();
                this.curnote = n;
                this.editing += 1;
                this.voting = true;
                return {fav: $(this.name+"_fav").getValue(),
                        vstat: $(this.name+"_vstat").getValue()};
            }).bind(this);
            an.completeCallback = (function() {
                this.editing -= 1;
                this.voting = false;
                this.curvalue = null;
                this.ddsel.current = "";
                $(this.name+"_title").enable().focus();
                $(this.name+"_title").value = "";
            }).bind(this);
            an.successCallback = this.addnoteSuccess.bind(this);
            an.failureCallback = this.addnoteFailure.bind(this);
        } 
        this.curvalue = key;
        this.curlabel = value;
    },
    addnoteSuccess: function(x) {
        if ($(this.name+"_row"+this.curvalue)) {
            var prow = $(this.name+"_row"+this.curvalue);
            prow.insert({after: x.headerJSON.row});
            var row = prow.next("tr");
            if (prow.hasClassName("even")) row.addClassName("even");
            else row.addClassName("odd");
            prow.remove();
        } else {
            var body = $(this.name+"_table").down("tbody").insert({top: x.headerJSON.row});
            var row = body.down("tr");
            var prow = row.next("tr");
            if (prow.hasClassName("even")) row.addClassName("odd");
            else row.addClassName("even");
        }
        $(this.name+"_wbox").update("");
    },
    addnoteFailure: function(x) {
        if (x.status == 403)
            alert("Ocena zablokowana");
        else
            alert("Błąd komunikacji");
    },
    changeExisting: function(k) {
        var row = $(this.name+"_row"+k);
        if (row.waiting) return;
        row.waiting = true;
        var target = new Element("div", {'class': "noteeditform"});
        var nrow = new Element("tr")
            .update(new Element("td", {colspan: 4}).update(target));
        row.classNames().each(function(n){nrow.addClassName(n);});
        nrow.removeClassName("deleted");
        row.insert({after: nrow});
        row.remove();
        var bi = $(new Image());
        bi.setStyle({marginLeft: "auto", marginRight: "auto", display: "block"});
        bi.src = busyimg.src;
        target.update(bi);
        new Ajax.Updater({success: target}, "/json_notehelp.php", {
            method: "get",
            parameters: {type: "turbovoter", xid: k},
            onSuccess: (function(transport) { (function() {
                var an = new AddNote(this.url, target.down("img"), $(this.name+"_notebox"), k, undefined, true);
                target.down("div.tvnotebox").down("div").observe("click", function(evt){an.addnote(transport.headerJSON.perm?transport.headerJSON.note:-1,evt);});
                an.clickCallback = (function(x,n) {
                    if (this.voting) return false;
                    trackEvent('note', 'listedit');
                    this.editing += 1;
                    var vstat = $(this.name+"_vstat"+k).getValue();
                    target.down("div.tvnotebox").down("div").remove();
                    return {fav: $(this.name+"_fav"+k).getValue(),
                            vstat: vstat};
                }).bind(this);
                an.completeCallback = (function() {
                    this.editing -= 1;
                }).bind(this);
                an.successCallback = (function(x) {
                    nrow.insert({after: x.headerJSON.row});
                    var row = nrow.next("tr");
                    if (nrow.hasClassName("even")) row.addClassName("even");
                    else row.addClassName("odd");
                    nrow.remove();
                }).bind(this);
                an.failureCallback = this.addnoteFailure.bind(this);
            }).bind(this).defer() }).bind(this)
        });
    },
    delNote: function(k) {
        if (this.voting) return;
        var row = $(this.name+"_row"+k);
        if (row.waiting) return;
        row.waiting = true;
        this.editing += 1;
        var bi = new Image();
        bi.src = busyimg.src;
        bi.setStyle({marginBottom: "-3px"});
        $(this.name+"_val"+k).update(bi);
        new Ajax.Updater($(this.name + "_notebox"), this.url, {
            postBody: Object.toJSON({ note: null, xid: k }),
            onSuccess: (function(x) {
                $(this.name+"_val"+k).update("-");
                row.addClassName("deleted");
                row.down("a.delnote").setStyle({visibility: "hidden"});
            }).bind(this),
            onComplete: (function(x) { 
                row.waiting = false;
                this.editing -= 1;
                bi.remove(); 
            }).bind(this),
            onFailure: this.addnoteFailure
        });
    }
});

var AddDescr = Class.create({
    initialize: function(url, name, xid) {
        this.url = url;
        this.name = name;
        this.xid = xid;
    },
    submit: function(form) {
        var bim = new Element("img", {src: busyimg.src});
        bim.setStyle({marginLeft: "auto", marginRight: "auto", display: "block"});
        $(this.name).down("form").appendChild(bim);
        form["do"].remove();
        new Ajax.Updater($(this.name), this.url, {
            parameters: {xid: this.xid, descr: form.descr.value}
        });
    },
    load: function() {
        $(this.name).update(busyimg);
        new Ajax.Updater($(this.name), this.url, {
            parameters: {xid: this.xid}
        });
    }
});

function updateLengthCounter(obj, target, maxlen) {
	var obj = $(obj);
	if (obj.value.length <= maxlen){
		$(target).update(maxlen-obj.value.length);
	} else {
		$(target).update("<b>o " + (obj.value.length-maxlen) + " za dużo</b>");
	}
	return true;
}

function displayHelp(title, data) {
    var db = new Element("div", {'class': "dialogblocker"});
    var body = new Element("div", {'class': "dialogbody"}).update(busyimg);
    var hbox = new Element("div", {'class': "dialogheader"}).insert(new Element("a", {'class': "dialogclose", title: "Zamknij"}).update(new Element("span").update("Zamknij")).observe('click', function() {hbox.remove();body.remove();db.remove();})).insert("Pomoc – "+title);
    $("all").insert(db);
    $("all").insert(hbox);
    $("all").insert(body);

    new Ajax.Updater(body, "/statyczna.php", {method: "get", parameters: {name: "help_"+data}});
}

function switchImg(id, src, width, height, alt) {
    $(id).src = src;
    $(id).width = width;
    $(id).height = height;
    $(id).alt = alt;
}

function switchTab(node, name) {
    for (var i in node.parentNode.childNodes) {
        var name2 = node.parentNode.childNodes[i].id;
        if (!name2 || name2.substr(name2.length-4) != '_tab') continue;
        name2 = name2.substr(0, name2.length-4);
        $(name2).style.display = 'none';
        $(name2+'_tab').addClassName('inactive');
    }
    $(name).style.display = 'block';
    $(name+'_tab').removeClassName('inactive');
}

function refreshRandom(what, params) {
    if (typeof(params) == 'undefined') params = {};
    params.random = what;
    var rl = $("random"+what);
    var e = document.createElement('div');
    e.appendChild(busyimg);
    e.style.marginTop = "8px";
    e.style.textAlign = "center";
    rl.appendChild(e);
    new Ajax.Updater(rl, "/json_random.php", {method: "get", parameters: params});
    trackEvent('random', what);
}

var toplist = 0;

function refreshToplist(arr) {
    toplist += 1;
    if (toplist >= arr.length) toplist = 0;
    refreshRandom('toplist', {geid: arr[toplist]});
}

function trackPageview(url) {
    if (typeof pageTracker == 'undefined') {
        return;
    }
    if (!url) {
        url = document.URL.substr(document.URL.indexOf(document.domain)+document.domain.length);
    }
    pageTracker._trackPageview(url);
}

function trackEvent(category, action, opt_label, opt_value) {
    if (typeof pageTracker == 'undefined') {
        return;
    }
    pageTracker._trackEvent(category, action, opt_label, opt_value);
}

function evLoginFocus()
{
	if (this.value == '' || this.value == this._text) {
		this.value = '';
	}
	this.removeClassName('defaultValue');
}

function evLoginBlur()
{
	if (this.value == '' || this.value == this._text) {
		this.value = this._text;
		this.addClassName('defaultValue');
	}
}

function setupLoginField(field, text)
{
	field._text = text;
	evLoginBlur.bind(field)();
	field.observe('focus', evLoginFocus);
	field.observe('blur', evLoginBlur);
}

function load_more(url, where)
{
    new Ajax.Updater($(where.parentNode).update(busyimg), url, {method: "get"});
}

function compactselector_update(what)
{
    var cs = $(what).up("div.compactselector");
    var d = new Array();
    for (var k = 0;; k++) {
        var i = cs.down("input", k);
        if (!i) break;
        if (i.checked) d.push(cs.down("label[for=\""+i.id+"\"]").lastChild.nodeValue);
    }
    cs.down("div.compactselectortext").update((d.length == 0) ? "Wybierz" : d.join(", "));
}

function load_facebook(appid)
{
    window.fbAsyncInit = function() {
        FB.init({appId: appid, status: true, cookie: true, xfbml: true});
    };
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
        '//connect.facebook.net/pl_PL/all.js';
    var fbdiv = document.createElement('div');
    fbdiv.id = 'fb-root';
    fbdiv.insert(e);
    $(document.body).insert({top: fbdiv});
}

document.observe('dom:loaded', function() {
	var usrpanel = $('usrpanel');
	var form = usrpanel.down('form');
	if (form) {
		var login = form.down('input');
		var password = login.next('input');
		setupLoginField(login, 'Login');
		setupLoginField(password, '.....');
		form.observe('submit', function(e) {
			evLoginFocus.bind(login)();
			evLoginFocus.bind(password)();
		});
		form.addClassName('inactive');
		form.observe('mouseover', function(){this.removeClassName('inactive');});
		form.observe('mouseout', function(){this.addClassName('inactive');});
	}

	$$('.reltitles.more').each(function(el) {
		el = $(el);
		el.hide();
		var count = el.childElements().length;
		var linkShow = (new Element('a', {href:'#'})).update('<small><b>pokaż pozostałe ' + count+'</b></small>');
		var linkHide = (new Element('a', {href:'#'})).update('<small><b>zwiń listę</b></small>');
		linkShow.setStyle({'margin': '3px 0', 'display': 'inline-block'});
		linkHide.setStyle({'margin': '3px 0', 'display': 'inline-block'});
		linkShow.observe('click', function(e) {
			e.stop();
			$(this).remove();
			el.show();
			el.insert({after: linkHide});
		});
		linkHide.observe('click', function(e) {
			e.stop();
			$(this).remove();
			el.hide();
			el.insert({after: linkShow});
		});
		el.insert({after: linkShow});
	});

	var fb_root = $('fb-root');
	if (fb_root) {
		var fb_status = fb_root.hasClassName('fb-status');
		var fb_cookie = fb_root.hasClassName('fb-cookie');
		var app_id = fb_root.className.match(/fb-app-(\d+)/);
		window.fbAsyncInit = function() {
			FB.init({appId: app_id[1], status: fb_status, cookie: fb_cookie, xfbml: true});
		};
		(function() {
			var e = document.createElement('script');
			e.type = 'text/javascript';
			e.src = document.location.protocol + '//connect.facebook.net/pl_PL/all.js';
			e.async = true;
			document.getElementById('fb-root').appendChild(e);
		}());
	}
});

