var EditableAreas = $H();
var EditableSections = $H();
var EditableEvents = {
    addEvent: function (B, A, C) {
        if (!Object.isArray(this.edEvents)) {
            throw "Manual initialization of event list required!"
        }
        this.edEvents.push({
            element: B,
            eventName: A,
            handler: C,
            wired: false
        })
    },
    connectEvents: function () {
        if (!Object.isArray(this.edEvents)) {
            throw "Couldn't find events list to act upon."
        }
        this.edEvents.each(function (A) {
            if (A.wired) {
                return
            }
            Event.observe(A.element, A.eventName, A.handler);
            A.wired = true
        })
    },
    disconnectEvents: function () {
        if (!Object.isArray(this.edEvents)) {
            throw "Couldn't find events list to act upon."
        }
        this.edEvents.each(function (A) {
            if (!A.wired) {
                return
            }
            Event.stopObserving(A.element, A.eventName, A.handler);
            A.wired = false
        })
    }
};
var EditableServer = {
    ServerFunctions: {
        GetHTML: 1,
        Save: 2,
        Delete: 3,
        Move: 4,
        Add: 5
    },
    ServerResponses: {
        Message: 0,
        Redirect: 1,
        HTML: 2,
        Delay: 3
    },
    MessageType: {
        Normal: 0,
        Info: 1,
        Warning: 2,
        Error: 3
    },
    serverQueue: function (A) {
        if (!Object.isArray(this.edQueue)) {
            throw "Manual initialization of command queue required!"
        }
        if (Object.isUndefined(A)) {
            throw "Argument fnId can't be undefined!"
        }
        this.edQueue.push($A(arguments))
    },
    serverRequest: function () {
        if (Object.isFunction(this.disconnectEvents)) {
            this.disconnectEvents()
        }
        if (Object.isElement(this.container)) {
            new Effect.Opacity(this.container, {
                duration: 0.3,
                from: 1,
                to: 0.25
            })
        }
        var A = this.edQueue.toJSON();
        this.edQueue.clear();
        new Ajax.Request(new String(document.location), {
            method: "post",
            parameters: {
                layer: "ajax",
                type: this.type,
                id: this.id,
                commands: A
            },
            onComplete: this.serverResponse.bind(this)
        })
    },
    serverResponse: function (B) {
        if (B.request.success()) {
            var A = $A(B.responseJSON);
            if (Object.isFunction(this.processResponse)) {
                A.each(this.processResponse.bind(this))
            }
        }
        if (Object.isElement(this.container)) {
            new Effect.Opacity(this.container, {
                duration: 0.3,
                from: 0.25,
                to: 1
            })
        }
        if (Object.isFunction(this.connectEvents)) {
            this.connectEvents()
        }
    }
};
var EditableCapabilities = {
    setCapabilities: function (A) {
        $H(A).each((function (B) {
            var C = "can" + B.key.capitalize();
            if (this[C] != undefined) {
                this[C] = B.value == true
            }
        }).bind(this))
    }
};
var EditableArea = Class.create(EditableServer, EditableEvents, EditableCapabilities, {
    initialize: function (D, B, A, C) {
        if (!Object.isUndefined(EditableAreas.get(D))) {
            throw 'Area with ID "' + D + '" alread registred!'
        }
        EditableAreas.set(D, this);
        this.edQueue = [];
        this.edEvents = [];
        this.container = null;
        this.id = D;
        this.type = B;
        this.acontainer = A;
        this.title = C;
        this.supported = $A();
        this.addTmpl = new Template('Lisa "#{name}"'.i18n());
        this.htmlMessage = null;
        this.htmlAdd = null;
        this.htmlAddMenu = null;
        this.canAdd = false;
        this.acontainer.observe("DOMNodeRemoved", (function (E) {
            if (E.target == this.acontainer) {
                EditableAreas.unset(this.id)
            }
        }).bindAsEventListener(this))
    },
    setSupportedSections: function () {
        this.supported = $A(arguments)
    },
    show: function () {
        if (!Object.isUndefined(this.htmlHeader)) {
            return
        }
        if (!this.canAdd) {
            return
        }
        this.htmlHeader = new Element("div", {
            "class": "editable_area_header"
        });
        var C = new Element("u", {
            "class": "title"
        }).update(this.title);
        this.htmlHeader.insert(C);
        var B = new Element("table");
        var D = new Element("tbody");
        var E = new Element("tr");
        var A = new Element("td");
        this.htmlMessage = new Element("div");
        A.insert(this.htmlMessage);
        E.insert(A);
        A = new Element("td");
        A.setStyle({
            textAlign: "right"
        });
        if (this.supported.length > 0) {
            this.htmlAdd = new Element("div", {
                "class": "editable_add"
            });
            if (this.supported.length > 1) {
                this.htmlAdd.update("Lisa ...".i18n());
                this.addEvent(this.htmlAdd, "click", this.openAddMenu.bind(this))
            } else {
                this.htmlAdd.update(this.addTmpl.evaluate({
                    name: this.supported[0][1]
                }));
                this.addEvent(this.htmlAdd, "click", this.addSection.bind(this, this.supported[0][0]))
            }
            A.insert(this.htmlAdd)
        }
        E.insert(A);
        D.insert(E);
        B.insert(D);
        this.htmlHeader.insert(B);
        this.acontainer.insert({
            top: this.htmlHeader
        });
        this.connectEvents();
        this.container = this.htmlHeader
    },
    openAddMenu: function () {
        if (this.htmlAddMenu === null) {
            this.htmlAddMenu = new Element("div").hide();
            var B = new Element("div");
            B.setStyle({
                position: "fixed",
                width: "100%",
                height: "100%",
                top: 0,
                left: 0,
                zIndex: 200
            });
            B.observe("mouseover", (function (F, E) {
                if (F.element() == E) {
                    this.htmlAddMenu.hide()
                }
            }).bindAsEventListener(this, B));
            this.htmlAddMenu.insert(B);
            var D = this.htmlAdd.cumulativeOffset();
            var A = new Element("div");
            A.setStyle({
                position: "absolute",
                zIndex: 201,
                top: (D.top - 25) + "px",
                left: (D.left - 25) + "px",
                padding: "25px"
            });
            this.htmlAddMenu.insert(A);
            var C = new Element("div", {
                "class": "editable_add_menu"
            });
            this.supported.each((function (E) {
                var F = new Element("a", {
                    href: "#"
                });
                F.update(this.addTmpl.evaluate({
                    name: E[1]
                }));
                F.observe("click", (function (H, G) {
                    H.stop();
                    this.addSection(G)
                }).bindAsEventListener(this, E[0]));
                C.insert(F)
            }).bind(this));
            A.insert(C);
            document.body.insert(this.htmlAddMenu)
        }
        this.htmlAddMenu.show()
    },
    addSection: function (A) {
        if (this.htmlAddMenu !== null) {
            this.htmlAddMenu.hide()
        }
        this.serverQueue(this.ServerFunctions.Add, A);
        this.serverRequest()
    },
    processResponse: function (B) {
        var E = B.first();
        if (E == this.ServerResponses.HTML) {
            var A = new Element("div");
            this.htmlHeader.insert({
                after: A
            });
            Element.replace(A, B[2])
        }
        if (E == this.ServerResponses.Message) {
            var D = B[1];
            var F = B[2];
            var C = "#000";
            if (D == this.MessageType.Error) {
                C = "#c00"
            }
            if (D == this.MessageType.Info) {
                C = "#00c"
            }
            if (D == this.MessageType.Warning) {
                C = "#cc0"
            }
            this.htmlMessage.setStyle({
                color: C
            });
            this.htmlMessage.update(F);
            if (!Object.isUndefined(this.htmlMessage._eff)) {
                this.htmlMessage._eff.cancel()
            }
            this.htmlMessage.setOpacity(1);
            this.htmlMessage.show();
            this.htmlMessage._eff = new Effect.Fade(this.htmlMessage, {
                delay: 5,
                duration: 5
            })
        }
    }
});
var EditableSection = Class.create(EditableEvents, EditableServer, EditableCapabilities, {
    Mode: {
        Display: 1,
        Edit: 2
    },
    initialize: function (D, B, A, C) {
        if (!Object.isUndefined(EditableSections.get(D))) {
            throw 'Section with ID "' + D + '" alread registred!'
        }
        EditableSections.set(D, this);
        this.id = D;
        this.type = B;
        this.container = A;
        this.title = C;
        this.canEdit = false;
        this.canDelete = false;
        this.canMove = false;
        this.timerShowControls = null;
        this.timerHideControls = null;
        this.htmlHeader = null;
        this.htmlFooter = null;
        this.htmlEditForm = null;
        this.statusControls = 0;
        this.status = this.Mode.Display;
        this.edEvents = new Array();
        this.edQueue = new Array();
        this.boundListeners = {
            showControlsDelayed: this.showControlsDelayed.bind(this),
            hideControlsDelayed: this.hideControlsDelayed.bind(this)
        };
        this.addEvent(this.container, "mouseover", this.boundListeners.showControlsDelayed);
        this.addEvent(this.container, "mouseout", this.boundListeners.hideControlsDelayed);
        this.connectEvents();
        this.container.observe("DOMNodeRemoved", (function (E) {
            if (E.target == this.container) {
                this.unregister()
            }
        }).bindAsEventListener(this))
    },
    unregister: function () {
        if (EditableSections.get(this.id) == this) {
            EditableSections.unset(this.id)
        }
    },
    showControls: function () {
        if (this.status != this.Mode.Display) {
            throw "Can't use this function while not in display mode."
        }
        if (this.timerHideControls !== null) {
            this.timerHideControls.stop();
            this.timerHideControls = null
        }
        if (this.statusControls == 2) {
            return
        }
        if (this.timerShowControls !== null) {
            this.timerShowControls.stop();
            this.timerShowControls = null
        }
        if (this.htmlHeader === null) {
            this.htmlHeader = new Element("div", {
                "class": "editable_header"
            });
            this.htmlHeader.update(this.title);
            this.container.insert({
                top: this.htmlHeader
            });
            if (this.canEdit) {
                var A = new Element("img", {
                    src: "/images/editables/edit.png",
                    title: "Muuda".i18n()
                });
                this.addEvent(A, "click", (function () {
                    this.serverQueue(this.ServerFunctions.GetHTML, this.Mode.Edit);
                    this.serverRequest()
                }).bind(this));
                this.htmlHeader.insert({
                    top: A
                })
            }
            if (this.canDelete) {
                var B = new Element("img", {
                    src: "/images/editables/remove.png",
                    title: "Kustuta".i18n()
                });
                this.addEvent(B, "click", (function () {
                    if (!confirm("Kas oled kindel, et soovid elemendi kustutada?".i18n())) {
                        return
                    }
                    this.serverQueue(this.ServerFunctions.Delete);
                    this.serverRequest()
                }).bind(this));
                this.htmlHeader.insert({
                    top: B
                })
            }
            this.connectEvents()
        }
        this.statusControls = 2;
        this.container.addClassName("editable_content");
        this.htmlHeader.show()
    },
    showControlsDelayed: function () {
        if (this.status != this.Mode.Display) {
            throw "Can't use this function while not in display mode."
        }
        if (this.timerHideControls !== null) {
            this.timerHideControls.stop();
            this.timerHideControls = null
        }
        if (this.statusControls >= 1) {
            return
        }
        if (this.timerShowControls !== null) {
            this.timerShowControls.stop();
            this.timerShowControls = null
        }
        this.statusControls = 1;
        this.container.addClassName("editable_content");
        this.timerShowControls = new PeriodicalExecuter(this.showControls.bind(this), 0)/* 1 */
    },
    hideControls: function () {
        if (this.status != this.Mode.Display) {
            throw "Can't use this function while not in display mode."
        }
        if (this.timerHideControls !== null) {
            this.timerHideControls.stop();
            this.timerHideControls = null
        }
        if (this.statusControls == 0) {
            return
        }
        if (this.timerShowControls !== null) {
            this.timerShowControls.stop();
            this.timerShowControls = null
        }
        this.statusControls = 0;
        this.container.removeClassName("editable_content");
        if (this.htmlHeader !== null) {
            this.htmlHeader.hide()
        }
    },
    hideControlsDelayed: function () {
        if (this.status != this.Mode.Display) {
            throw "Can't use this function while not in display mode."
        }
        if (this.timerHideControls !== null) {
            this.timerHideControls.stop();
            this.timerHideControls = null
        }
        this.timerHideControls = new PeriodicalExecuter(this.hideControls.bind(this), 0) /* 0.25 */
    },
    processResponse: function (C) {
        var F = C.first();
        if (F == this.ServerResponses.Redirect) {
            document.location = C[1]
        }
        if (F == this.ServerResponses.HTML && C[1] == this.Mode.Edit) {
            this.status == C[1];
            this.edEvents.clear();
            if (this.htmlHeader !== null) {
                this.htmlHeader.remove();
                this.htmlHeader = null
            }
            this.container.removeClassName("editable_content");
            this.htmlEditForm = new Element("form");
            this.htmlEditForm.observe("submit", (function (G) {
                G.stop()
            }).bindAsEventListener());
            this.htmlEditForm.update(C[2]);
            if (!Object.isUndefined(AutoUploader)) {
                this.htmlEditForm.select("input[type=file]").each(function (G) {
                    new AutoUploader(G, "editable/" + this.type + "/" + this.id + "/" + G.readAttribute("name"))
                }.bind(this))
            }
            this.container.update();
            this.container.insert({
                bottom: this.htmlEditForm
            });
            this.htmlHeader = new Element("div", {
                "class": "editable_header_edit"
            });
            this.htmlHeader.update(this.title);
            this.htmlEditForm.insert({
                top: this.htmlHeader
            });
            var D = new Element("div", {
                "class": "editable_footer_edit"
            });
            var B = new Element("input", {
                type: "button",
                value: "Salvesta".i18n()
            });
            B.observe("click", (function () {
                this.serverQueue(this.ServerFunctions.Save, Form.serializeElements(this.htmlEditForm.getElements(), true));
                this.serverQueue(this.ServerFunctions.GetHTML, this.Mode.Display);
                this.serverRequest()
            }).bind(this));
            D.insert({
                bottom: B
            });
            var E = new Element("input", {
                type: "button",
                value: "Tühista".i18n()
            });
            E.observe("click", (function () {
                this.serverQueue(this.ServerFunctions.GetHTML, this.Mode.Display);
                this.serverRequest()
            }).bind(this));
            D.insert({
                bottom: E
            });
            D.insert({
                bottom: new Element("div", {
                    style: "clear: both"
                })
            });
            this.htmlEditForm.insert({
                bottom: D
            });
            this.container.addClassName("editable_content_edit")
        }
        if (F == this.ServerResponses.HTML && C[1] == this.Mode.Display) {
            var A = new Element("div");
            this.container.insert({
                before: A
            });
            this.unregister();
            this.container.remove();
            Element.replace(A, C[2])
        }
    }
});
