RORTICUS.InlineEditor = function (element) {
    var me = this;

    var dynamicId = element.getAttribute("dynamicid");
    if(dynamicId)
    {
        this.dynamicId = dynamicId;
    }
    else
    {
        this.dynamicId = 0;
    }

    this.element = element;

    // set up a few event handlers
    this.mouseOverEventHandler = function () {
        element.style.backgroundImage = "url(" + RORTICUS.webRoot + RORTICUS.Resources.editableBackground + ")";
    };

    this.mouseOutEventHandler = function () {
        element.style.backgroundImage = "";
    };

    this.mouseClickHandler = function () {
        me.createEditor();
    };

    this.bodyClickHandler = function (event) {
        if(!event)
        {
            event = window.event;
        }

        // they click on US?
        var clickedUs = false;

        var node = ('srcElement' in event)?event.srcElement:event.target;
        var original = node;

        while(node)
        {
            if(node == me.element || node == me.toolbarFrame)
            {
                clickedUs = true;
                break;
            }

            node = node.parentNode;
        }

        if(!clickedUs)
        {
            if(me.element.innerHTML != me.originalHTML)
            {
                if(!confirm("You have unsaved changes, really cancel?"))
                {
                    event.cancelBubble = true;
                    if ('preventDefault' in event)
                    {
                        event.preventDefault();
                    }
                    else
                    {
                        event.returnValue = false;
                    }

                    me.element.focus();

                    return false;
                }
                else
                {
                    me.element.innerHTML = me.originalHTML;
                    me.stopEditing();
                }
            }
            else
            {
                me.stopEditing();
            }
        }

        return true;
    };

    RORTICUS.addEvent(this.element, "mouseover", this.mouseOverEventHandler);
    RORTICUS.addEvent(this.element, "mouseout", this.mouseOutEventHandler);
    RORTICUS.addEvent(this.element, "click", this.mouseClickHandler);
};

RORTICUS.createInlineEditors = function (root) {
    if(!root)
    {
        root = document.body;
    }

    for(var i = 0; i < root.childNodes.length; i++)
    {
        RORTICUS.createInlineEditors(root.childNodes[i]);
    }

    if('getAttribute' in root)
    {
        var isEditable = root.getAttribute("editable");
        if(isEditable)
        {
            var n = new RORTICUS.InlineEditor(root);
        }
    }
};

RORTICUS.InlineEditor.prototype.createEditor = function () {
    // create the toolbar at the top of the element
    var elementCoords = RORTICUS.elementFrame(this.element);
    var self = this;

    this.originalHTML = this.element.innerHTML;

    this.toolbarFrame = RORTICUS.initElement("DIV", "height: 16px; position: absolute; background-color: #FFFFFF; border: 1px solid #DDDDDD;", function () {
        this.style.left = elementCoords.left + "px";
        this.style.top = elementCoords.top - 16 + "px";

        document.body.appendChild(this, true);
    });

    var buttons = [
        { icon: "textAlignLeft", click: function () { document.execCommand("justifyLeft", null, null); } },
        { icon: "textAlignCenter", click: function () { document.execCommand("justifyCenter", null, null); } },
        { icon: "textAlignRight", click: function () { document.execCommand("justifyRight", null, null); } },
        '-',
        { icon: "textBold", click: function () { document.execCommand("bold", null, null); } },
        { icon: "textItalic", click: function () { document.execCommand("italic", null, null); } },
        { icon: "textUnderline", click: function () { document.execCommand("underline", null, null); } },
        '-',
        { icon: "textIndentRemove", click: function () { document.execCommand("outdent", null, null); } },
        { icon: "textIndent", click: function () { document.execCommand("indent", null, null); } },
        { icon: "textListBullets", click: function () { document.execCommand("insertUnorderedList", null, null); } },
        { icon: "textListNumbers", click: function () { document.execCommand("insertOrderedList", null, null); } },
        '-',
        { icon: "textAllcaps", click: function () { document.execCommand("removeFormat", null, null); } },
        { icon: "textHeading1", click: function () { document.execCommand("formatBlock", null, "<h1>"); } },
        { icon: "textHeading2", click: function () { document.execCommand("formatBlock", null, "<h2>"); } },
        { icon: "textHeading3", click: function () { document.execCommand("formatBlock", null, "<h3>"); } },
        { icon: "textHeading4", click: function () { document.execCommand("formatBlock", null, "<h4>"); } },
        { icon: "textHeading5", click: function () { document.execCommand("formatBlock", null, "<h5>"); } },
        { icon: "textHeading6", click: function () { document.execCommand("formatBlock", null, "<h6>"); } },
        '-',
        { icon: "imageAdd", click: function () {
            uploadContainer = { selectedFile: "" };

            var w = window.open(RORTICUS.linkRoot + "/uploader", "_blank", "width=500,height=300");

            setTimeout(function () {
                if(w.closed)
                {
                    if(uploadContainer.selectedFile != "")
                    {
                        // insert this image!
                        document.execCommand("insertImage", null, RORTICUS.webRoot + "uploads" + uploadContainer.selectedFile);
                    }
                }
                else
                {
                    setTimeout(arguments.callee, 100);
                }
            }, 100);
        } },
        { icon: "pageWhiteAdd", click: function () {
            uploadContainer = { selectedFile: "" };

            var w = window.open(RORTICUS.linkRoot + "/uploader", "_blank", "width=500,height=300");

            setTimeout(function () {
                if(w.closed)
                {
                    if(uploadContainer.selectedFile != "")
                    {
                        // insert this image!
                        document.execCommand("createLink", null, RORTICUS.webRoot + "uploads" + uploadContainer.selectedFile);
                    }
                }
                else
                {
                    setTimeout(arguments.callee, 100);
                }
            }, 100);
        } },
        { icon: "anchor", click: function () {
            var linkUrl = prompt("Enter link URL");
            if(linkUrl)
            {
                document.execCommand("createLink", null, linkUrl);
            }
        } },
        '-',
        { icon: "tag", click: function () {
            var position = RORTICUS.elementFrame(this.element);

            RORTICUS.removeEvent(document, "click", this.bodyClickHandler);

            this.toolbarFrame.style.display = "none";

            var textArea = RORTICUS.initElement("textarea", "position:absolute; font-family: monospace;", function () {
                this.style.left = position.left + "px";
                this.style.top = position.top + "px";
                this.style.width = (position.right - position.left) + "px";
                this.style.height = (position.bottom - position.top) + "px";

                this.value = self.element.innerHTML;

                document.body.appendChild(this, true);

                this.focus();
                this.onblur = function () {
                    self.element.innerHTML = textArea.value;

                    document.body.removeChild(textArea);
                    setTimeout(function () {
                        self.element.focus();
                        self.toolbarFrame.style.display = "";
                        RORTICUS.addEvent(document, "click", self.bodyClickHandler);
                    }, 100);
                };
            });
        } },
        '-',
        { icon: "disk", click: function () {
            RORTICUS.ajax({
                url: RORTICUS.linkRoot + "/ajax/savecontent",
                method: "POST",
                params: {
                    id: this.dynamicId,
                    html: this.element.innerHTML
                },
                success: function (response) {
                    self.stopEditing();
                }
            });
        } },
        { icon: "cross", click: function () {
            if(this.element.innerHTML != this.originalHTML)
            {
                if(confirm("You have unsaved changes, really cancel editing?"))
                {
                    this.element.innerHTML = this.originalHTML;
                    this.stopEditing();
                }
            }
            else
            {
                this.stopEditing();
            }
        } }
    ];

    for(var i = 0; i < buttons.length; i++)
    {
        if(buttons[i] == '-')
        {
            RORTICUS.initElement("IMG", "", function () {
                this.src = RORTICUS.webRoot + RORTICUS.Resources.menuSeparator;
                self.toolbarFrame.appendChild(this, true);
            });
        }
        else
        {
            RORTICUS.initElement("IMG", "cursor:pointer;", function () {
                this.src = RORTICUS.webRoot + RORTICUS.Resources[buttons[i].icon];
                this.onclick = function (i) {
                    return function() { try { buttons[i].click.apply(self); } catch(e) {} };
                }(i);

                self.toolbarFrame.appendChild(this, true);
            });
        }
    }

    this.setupForEditing();

    this.element.focus();
};

RORTICUS.InlineEditor.prototype.setupForEditing = function () {
    this.element.contentEditable = true;
    this.element.designMode = true;

    RORTICUS.removeEvent(this.element, "mouseover", this.mouseOverEventHandler);
    RORTICUS.removeEvent(this.element, "mouseout", this.mouseOutEventHandler);
    RORTICUS.removeEvent(this.element, "click", this.mouseClickHandler);

    RORTICUS.addEvent(document, "click", this.bodyClickHandler);
};

RORTICUS.InlineEditor.prototype.stopEditing = function () {
    this.element.contentEditable = false;
    this.element.designMode = false;

    this.element.style.backgroundImage = "";

    RORTICUS.removeEvent(document, "click", this.bodyClickHandler);

    RORTICUS.addEvent(this.element, "mouseover", this.mouseOverEventHandler);
    RORTICUS.addEvent(this.element, "mouseout", this.mouseOutEventHandler);
    RORTICUS.addEvent(this.element, "click", this.mouseClickHandler);

    this.element.style.border = "";
    document.body.removeChild(this.toolbarFrame);

    this.toolbarFrame = null;
};

RORTICUS.addEvent(window, 'load', function () { RORTICUS.createInlineEditors(); });
