<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="MainEditor.aspx.vb" Inherits="WebFoundations.WFForms.UI.MainEditor" EnableEventValidation="false" %>

<%@ Register Src="~/WFAdmin/TagHeadAdmin.ascx" TagPrefix="wf" TagName="TagHeadAdmin" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Register Src="~/WFAdmin/WFForms/Editor/ConfigFrame.ascx" TagPrefix="wf" TagName="ConfigFrame" %>
<%@ Register Src="~/WFAdmin/WFForms/Editor/DataFrame.ascx" TagPrefix="wf" TagName="DataFrame" %>
<%@ Register Src="~/WFAdmin/WFForms/Editor/FormSettings.ascx" TagPrefix="fs" TagName="FormSettings" %>
<%@ Register TagPrefix="wff" Namespace="WebFoundations.ServerControls" Assembly="WebFoundations.ServerControls" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <title></title>
    <wf:TagHeadAdmin runat="server" ID="TagHeadAdmin" />
    <script type="text/javascript">
        (function ($) {
            $.fn.resizable = function () {
                this.each(function () {
                    if (this && this.addEventListener && this.getBoundingClientRect && !this.ninkiResize) {
                        this.ninkiResize = true;

                        var down = function (ev) {
                            var bounds = this.getBoundingClientRect();

                            var checkHit = function () {
                                var result = (
                                    ev.offsetX < 4 || //se clicou na borda esquerda
                                    (ev.offsetX >= (bounds.width - 16) && ev.offsetY >= (bounds.height - 16)) //se clicou no símbolo no canto inferior direito
                                );
                                console.log({
                                    name: "resizable checkHit",
                                    offsetX: ev.offsetX,
                                    offsetY: ev.offsetY,
                                    width: bounds.width,
                                    height: bounds.height,
                                    result: result
                                });
                                return result;
                            }

                            if (checkHit()) {
                                (function (e, obj, bounds) {
                                    var start = { x: ev.clientX, y: ev.clientY };

                                    var myup = function (ev) {
                                        obj.ownerDocument.removeEventListener("mouseup", myup, true);
                                        obj.ownerDocument.removeEventListener("mousemove", mymove, true);
                                        start = null;
                                        ev.stopImmediatePropagation();
                                    };

                                    var mymove = function (ev) {
                                        var d = { x: ev.clientX - start.x, y: ev.clientY - start.y };
                                        var s = {
                                            w: Math.max(bounds.width + d.x, 0),
                                            h: Math.max(bounds.height + d.y, 0)
                                        };
                                        $(obj).width(s.w).height(s.h);
                                        ev.stopImmediatePropagation();
                                    };

                                    obj.ownerDocument.addEventListener("mouseup", myup, true);
                                    obj.ownerDocument.addEventListener("mousemove", mymove, true);
                                })(ev, this, bounds);

                                ev.preventDefault();
                                ev.stopImmediatePropagation();
                                select(this.outerHTML);
                                return false;
                            }
                        }

                        this.addEventListener("mousedown", down, false);
                    }
                });
                return this;
            };

            var myEditor;
            var myPageId = %%PAGEID%%;
            var myFormId = %%FORMID%%;
            var contrHtml;
            var confFrame;

            function turnDivControlsResizable(editor) {
                $("div[moditemid]", editor.get_contentArea()).resizable();
            }

            window.OnClientLoad = function (editor) {
                myEditor = editor;
                turnDivControlsResizable(editor);
            };

            function select(contrHtml) {
                var hiddenTxt = document.getElementById('txtHidden');
                if (contrHtml != '') {
                    var idd, aId, fId, objName, mItemId, a, t;
                    idd = ''; aId = ''; fId = '';
                    objName = contrHtml.substring(contrHtml.indexOf(' id=') + 4);
                    objName = objName.substring(0, objName.indexOf(' '));
                    objName = objName.replace('"', '').replace('"', '');
                    mItemId = contrHtml.substring(contrHtml.indexOf(' moditemid="') + 12);
                    mItemId = mItemId.substring(0, mItemId.indexOf('"'));
                    if (mItemId == '') {
                        return false;
                    }
                    t = contrHtml.substring(contrHtml.indexOf(' tipo="') + 7);
                    t = t.substring(0, t.indexOf('"'));
                    var queries = window.location.search.split(/[\?&]+/);
                    if (queries != null && queries.length > 0) {
                        for (var i = 0; i < queries.length; i++) {
                            if (queries[i].substring(0, 2) == 'Id') { idd = queries[i].substring(3); }
                            if (queries[i].substring(0, 6) == 'AREAID') { aId = queries[i].substring(7); }
                            if (queries[i].substring(0, 6) == 'FormId') { fId = queries[i].substring(7); }
                        }
                    }
                    hiddenTxt.value = 'AREAID=' + aId + '&Id=' + idd + '&FormId=' + fId + '&ObjectName=' + objName + '&ModItemId=' + mItemId + '&Type=' + t;
                    __doPostBack('lnkConfigFrame', '');
                }
                else {
                    return false;
                }
            }
            window.OnClientSelectionChange = function (editor) {
                if (editor.getSelectionHtml() != '') {
                    select(editor.getSelectionHtml());
                } else {
                    //Este codigo serve para garantir que clicando ao fim de um div permite a onclusão de um texto
                    var existingHTML = editor.get_html(true);
                    if (existingHTML.endsWith('</div>')) {
                        editor.set_html(existingHTML + '&nbsp;');
                    }
                }
            };

            window.AddHTMLBlock = function (EditorControl, HTMLBlock) {
                EditorControl.pasteHtml(HTMLBlock);
                turnDivControlsResizable(EditorControl);
                __doPostBack('lnkConfigFrame', '');
            };

            window.GetNewControlId = function (ControlName) {
                var intControlId = 0;
                var myHTML = myEditor.get_html();
                if (myHTML != '') {
                    var strControls = new Array();
                    strControls = myHTML.split('id="' + ControlName);
                    for (var i = 1; i < strControls.length; i++) {
                        var strUltimoControleId = strControls[i].split(" ")[0].split("p")[1];
                        if (parseInt(intControlId) < parseInt(strUltimoControleId)) {
                            intControlId = strUltimoControleId;
                        }
                    }
                }
                intControlId = parseInt(intControlId) + 1;
                return ControlName + myPageId + 'p' + intControlId;
            };

            window.OnClicking = function (sender, eventArgs) {
                switch (eventArgs.Item.Value) {
                    case undefined:
                        return false;
                        break;
                    case 'insertdata':
                        return false;
                        break;
                    case 'test':
                        return false;
                        break;
                    default:
                        return true;
                }
            };

            window.UpdateDataPanel = function (formula) {
                if (formula) {
                    __doPostBack('btnRefreshFormulas', null);
                } else {
                    __doPostBack('btnRefreshDataSources', null);
                }
            };

            $(document).ready(function () {
                $("a.form-config").click(function () {
                    var isopen = $("div.form-config").is(":visible");
                    if (!isopen) {
                        $("div.form-config").css({ display: "inline-block" });
                        $("aside.sidebar").addClass("active");
                    } else {
                        $("div.form-config .form-save").click();
                    }
                    return false;
                });
            });

            window.onFormSaved = function () {
                if (window) {
                    var o = window.opener;
                    if (o && o.refreshGrid) {
                        try { o.refreshGrid(); } catch (error) { }
                    }
                    try {
                        $("aside.sidebar").removeClass("active");
                        $("div.form-config").hide();
                    } catch (error) { }
                }
            };

            window.onTitleChange = function (value) {
                $("h2#form-title").text(value || "");
            }

            //ao fechar a janela, faz o update da listagem
            $(window).unload(function () {
                if (window.opener && window.opener.refreshGrid) {
                    try {
                        window.opener.refreshGrid();
                    } catch (error) { }
                }
            });
        })(jQuery);
    </script>
    <style type="text/css">
        div[moditemid] {
            position: relative;
        }

        div[moditemid]:after {
            position: absolute;
            content: "\25e2"; /*http://www.w3schools.com/charsets/ref_utf_geometric.asp */
            right: 0;
            bottom: 2px;
            width: 1em;
            height: 1em;
            color: gray;
            text-align: right;
            cursor: nwse-resize;
            pointer-events: all;
            font-size: 16px;
        }
    </style>
</head>
<body class="wf-designer forms-designer">
    <form runat="server">
        <asp:ScriptManager runat="server" />
        <header>
            <h1>
                <asp:Literal ID="ltTitle" runat="server" /></h1>
            <h2 id="form-title">
                <asp:Literal ID="ltName" runat="server" /></h2>
            <menu type="toolbar" id="toolbar">
                <li class="formulas">
                    <input type="radio" name="toolgroup" id="toolgroup-formula" checked="checked" />
                    <label for="toolgroup-formula">
                        <asp:Literal ID="ltFormulas" runat="server" Text="Fórmulas" /></label>
                    <div class="content">
                        <asp:HyperLink ID="lnkInsertFormula" CssClass="add" runat="server" Text="Adicionar" />
                        <asp:UpdatePanel ID="updDataFormulas" class="data-sources" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <wf:DataFrame ID="formulasFrame" runat="server" Formulas="true" />
                                <asp:Button ID="btnRefreshFormulas" runat="server" Style="display: none;" />
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </div>
                </li>
                <li class="data">
                    <input type="radio" name="toolgroup" id="toolgroup-data" />
                    <label for="toolgroup-data">
                        <asp:Literal ID="ltData" runat="server" Text="Dados" /></label>
                    <div class="content">
                        <asp:HyperLink ID="lnkInsertData" CssClass="add" runat="server" Text="Adicionar" />
                        <asp:UpdatePanel ID="updDataPanel" class="data-sources" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <wf:DataFrame ID="dataSourcesFrame" runat="server" />
                                <asp:Button ID="btnRefreshDataSources" runat="server" Style="display: none;" />
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </div>
                </li>
            </menu>
        </header>
        <main>
            <telerik:RadTabStrip ID="tabPages" runat="server" AutoPostBack="true" />
            <telerik:RadEditor runat="server" CssClass="maineditor" ID="HTMLContent" Width="100%" Height="100%"
                OnClientSelectionChange="OnClientSelectionChange" HasPermission="True" EnableDocking="false"
                AllowThumbGeneration="false" showsubmitcancelbuttons="false" AllowScripts="true" CacheLocalization="true"
                LocalizationPath="~/wfresources/formsweb/Editor/Localization"
                ToolsFile="~/wfresources/formsweb/Editor/WFFormsToolbar.xml" SpellAllowAddCustom="False" CausesValidation="False"
                OnClientLoad="OnClientLoad" ToolbarMode="RibbonBar" />
            <asp:PlaceHolder ID="phEditorScripts" runat="server" />
        </main>
        <aside class="sidepanel props">
            <asp:UpdatePanel ID="updConfigs" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <wf:ConfigFrame ClientIDMode="Static" name="cFrame" runat="server" ID="ConfigFrame" />
                    <asp:LinkButton ID="lnkConfigFrame" runat="server" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </aside>
        <aside class="sidebar form-info">
            <menu>
                <li class="activate">
                    <asp:LinkButton ID="lnkGenerate" runat="server" />
                </li>
                <li class="test">
                    <asp:HyperLink ID="lnkTest" runat="server" />
                </li>
                <li id="liInsertPage" runat="server">
                    <asp:LinkButton ID="lnkInsertPage" CssClass="inserir-pag" runat="server" />
                </li>
                <li class="config">
                    <asp:LinkButton ID="lnkSettings" CssClass="form-config" runat="server" />
                </li>
            </menu>
            <asp:UpdatePanel runat="server" class="fields form-config" ID="uppFormInfo">
                <ContentTemplate>
                    <fs:FormSettings runat="server" ID="FormSettings" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </aside>
        <wff:WindowManager ID="EditWindow" runat="server">
            <Windows>
                <telerik:RadWindow ID="EditDialog" runat="server" Behaviors="Close,Move,Reload,Resize" Height="600px" VisibleStatusbar="false" Width="800px" ReloadOnShow="true" Modal="true" />
            </Windows>
        </wff:WindowManager>
    </form>
</body>
</html>
