//jump links
var JumpDemoLinks = [
    {
        name: "GView",
        children: [
            {name: "Node", url: "../../gview/node/index.html"},
            {name: "Link", url: "../../gview/link/index.html"},
            {name: "Group", url: "../../gview/group/index.html"},
            {name: "Subview", url: "../../gview/subview/index.html"},
            {name: "Text", url: "../../gview/text/index.html"},
            {name: "Topology", url: "../../gview/topology/index.html"},
            {name: "Rack", url: "../../gview/rack/index.html"},
            {name: "FlowChart", url: "../../gview/flowchart/index.html"},
            {name: "OrgChart", url: "../../gview/orgchart/index.html"},
            {name: "Animation", url: "../../gview/animation/index.html"},
            {name: "Layout", url: "../../gview/layout/index.html"},
            {name: "Editor", url: "../../gview/editor/index.html"},
            {name: "Map", url: "../../gview/map/index.html"}
        ]
    },
    {
        name: "Widgets",
        children: [
            {name: "Grid", url: "../../widgets/grid/index.html"},
            {name: "TreeGrid", url: "../../widgets/treegrid/index.html"},
            {name: "Tree", url: "../../widgets/tree/index.html"},
            {name: "ListView", url: "../../widgets/listview/index.html"},
            {name: "Tabs", url: "../../widgets/tabs/index.html"},
            {name: "Menu", url: "../../widgets/menu/index.html"},
            {name: "Tooltip", url: "../../widgets/tooltip/index.html"},
            {name: "Popover", url: "../../widgets/popover/index.html"},
            {name: "Notification", url: "../../widgets/notification/index.html"},
            {name: "Loader", url: "../../widgets/loader/index.html"},
            {name: "Modal", url: "../../widgets/modal/index.html"},
            {name: "MessageBox", url: "../../widgets/msgbox/index.html"},
            {name: "Collapse", url: "../../widgets/collapse/index.html"},
            {name: "Pagination", url: "../../widgets/pagination/index.html"}
        ]
    },
    {
        name: "Form",
        children: [
            {name: "Form", url: "../../form/form/index.html"},
            {name: "Validator", url: "../../form/validator/index.html"},
            {name: "I18n", url: "../../form/i18n/index.html"}
        ]
    }
];
var DemoIndex = {
    init: function () {
        if (!z.dom.query(".sidebar>.nav-tree") || this.tree) {
            return
        }
        this.in_server = window.location.protocol === "http:" || window.location.protocol === "https:";
        this.pageTitle = document.title;//.toLowerCase();
        this.pagePrefix = (document.title || "").replace(/ +/g, "_").toLowerCase();

        var location_href = window.location.href;
        if (location_href.indexOf("demo/widgets/") < 0 && z.dom.query(".demo_content>.theme")) {
            z.dom.remove(".demo_content>.theme")
        }

        if (z.dom.query("#editLink") && (this.in_server === false || window['FU_DEMO_CODE_EDITOR'] === false)) {//for website
            z.dom.remove("#editLink");
        }

        if (this.in_server) {
            var lang_index = Math.max(location_href.indexOf("/zh/"), location_href.indexOf("/en/"));
            if (lang_index > -1) {
                this.code_editor_url = location_href.substring(0, lang_index) + "/demo/_code_editor/code_editor.html?url="
            } else {
                this.code_editor_url = "../../_code_editor/code_editor.html?url="
            }
        }


        this.initJumpLinks();
        this.initMainView();
    },
    createLinkA: function (item, parent) {
        var a = z.dom.create("a");
        a.innerHTML = (item.icon || "") + item.name;
        z.dom.setAttribute(a, "href", item.url);
        var span = z.dom.create("span", "link-item");
        span.appendChild(a);
        if (parent) {
            parent.appendChild(span);
        }
        return span;
    },
    initJumpLinks: function () {
        var linksDiv = z.dom.query(".jump-links");
        if (!linksDiv) {
            return;
        }
        var items = (window.JumpDemoLinks || []);
        if (items.length === 0) {
            z.dom.remove(linksDiv);
            return;
        }

        var linkItemsDiv = z.dom.create("div", "links");
        items.forEach(function (item) {
            var children = item.children;
            if (children) {//group
                var group = z.dom.create("div", "group");
                var titleDiv = z.dom.create("div", "title");
                titleDiv.innerHTML = item.name;
                var groupItemsDiv = z.dom.create("div", "items");
                children.forEach(function (linkItem) {
                    DemoIndex.createLinkA(linkItem, groupItemsDiv);
                });
                group.appendChild(titleDiv);
                group.appendChild(groupItemsDiv);
                linkItemsDiv.appendChild(group);
            } else {
                DemoIndex.createLinkA(item, linkItemsDiv);
            }
        });
        var collapse = z.widget.Collapse();
        collapse.setData([{
            name: "Demos",
            content: linkItemsDiv
        }]);
        linksDiv.appendChild(collapse.getRoot());
    },

    initMainView: function () {
        this.initNavTree();
        this.initThemeSelect();

        var hash = z.bom.getLocationHash();
        if (hash === "*") {
            this.iterateDemos();
            return;
        }
        var introduction = z.dom.query(".introduction");
        if (introduction && introduction.textContent.trim() !== "") {
            return;
        }
        var lastData;
        if (hash) {//url hash
            hash = decodeURI(hash).toLowerCase();
            lastData = this.tree.findData(function (data) {
                return data.get("url") != null && data.get("name").toLowerCase() === hash;
            });
        }
        if (!lastData) {//storage
            var last = z.bom.getSessionStorage(this.pagePrefix + "_current");
            if (last) {
                lastData = this.tree.findData(function (data) {
                    return data.get("url") != null && (data.get("url") === last || data.get("name") === last);
                });
            }
        }
        if (!lastData) {
            lastData = this.tree.findData(function (data) {
                return data.get("url") != null;
            })
        }
        this.tree.setSelect(lastData);
    },
    initNavTree: function () {
        var _this = this;
        var treeMenus = window.DemoItems || [];
        DemoIndex.updateChangeStatus(treeMenus);
        this.tree = z.widget.Tree({
            appendTo: ".sidebar>.nav-tree",
            data: treeMenus,
            expand_on_click: true,
            onSelectBatchChange: function () {
                _this.setCurrent(this.getLastSelected());
            },
            isSelectable: function (data) {
                return data.get("url") != null && !data.get("link");
            },
            onDataClick: function (data) {
                var link = data.get("link");
                if (link) {
                    window.open(link);
                }
            },
            render: function (data, inWrapper) {
                var change = data.get("change");
                if (change) {
                    var changeSpan = z.dom.create("span", change);
                    changeSpan.innerHTML = change;
                    inWrapper.appendChild(changeSpan);
                }
                var version = data.get("version");
                if (version) {
                    z.dom.setAttribute(inWrapper, "title", version)
                }
            }
        });
        this.initNavTreeFilter();
    },
    updateChangeStatus: function (items) {
        items.forEach(function (item) {
            var changes = this.getItemChanges(item);
            if (changes.indexOf("new") > -1) {
                item.change = "new"
            } else if (changes.indexOf("update") > -1) {
                item.change = "update";
            }
            DemoIndex.updateChangeStatus(item.children || []);
        }, this);
    },
    getItemChanges: function (item, changeArr) {
        if (changeArr == null) {
            changeArr = [];
        }
        changeArr.push(item.change);
        (item.children || []).forEach(function (child) {
            this.getItemChanges(child, changeArr)
        }, this);
        return changeArr;
    },
    initNavTreeFilter: function () {
        if (!z.dom.query("#filterInput")) {
            return;
        }
        this.tree.addVisibleFilter(function (data) {
            var filterValue = z.dom.getValue("#filterInput").trim();
            if (filterValue) {
                filterValue = filterValue.toLowerCase();
                return data.get("name").toLowerCase().indexOf(filterValue) >= 0;
            }
            return true;
        });
        z.dom.event.on("#filterInput", "input", function () {
            this.tree.update();
        }, this);
        z.dom.event.on("#filterInput", "keydown.Escape", function (evt) {
            z.dom.setValue("#filterInput", "");
            this.tree.update();
        }, this);
    },
    initThemeSelect: function () {
        var themeSelect = z.dom.query("#themeSelect");
        if (!themeSelect) {
            return;
        }
        var themes = [
            {value: "bootstrap", label: "Bootstrap"}
        ];
        z.dom.initSelectOptions(themeSelect, themes);
        var currentTheme = z.bom.getLocalStorage("theme") || "bootstrap";
        z.dom.setValue(themeSelect, currentTheme);

        z.dom.event.onchange(themeSelect, function () {
            var theme = z.dom.getValue(themeSelect);
            z.bom.setLocalStorage("theme", theme);
            z.dom.query("#demoIF").contentWindow.location.reload();
        });
    },
    iterateDemos: function () {
        var tree = this.tree;
        var list = tree.filterData(function (data) {
            return data.get("url") != null;
        });
        var index = 0;
        z.util.callInterval(function () {
            var item = list[index++];
            if (!item) {
                return false;
            }
            tree.setSelect(item);
        }, 2000, null, true);
    },

    setCurrent: function (data) {
        var url = data.get("url");
        z.bom.setSessionStorage(this.pagePrefix + "_current", url);
        if (z.dom.query(".introduction")) {
            z.dom.remove(".introduction");
        }
        z.dom.query("#demoIF").setAttribute("src", url);
        this._updateUrlLink(data);
        z.dom.setValue("#demoTitle", this.pageTitle + " / " + data.get("name"));

        if (!this.in_server || data.get("source_visible") === false) {
            z.dom.setStyle(".source-code", "display", "none");
            return;
        }
        this.loadSource(url);
    },
    _updateUrlLink: function (data) {
        // z.util.callLater(function () {
        var url = data.get("url");
        var openLink = z.dom.query("#openLink");
        openLink.setAttribute("href", url)
        // z.dom.setAttribute("#openLink", "href", url);
        // console.log(z.dom.query("#openLink").href);
        var editLink = z.dom.query("#editLink");
        if (editLink) {
            z.dom.setAttribute(editLink, "href", this.code_editor_url + openLink.href);
        }
        // }, 100, this);
    },
    loadSource: function (url) {
        z.dom.query("#sourceCode").innerHTML = "";
        z.dom.setStyle(".source-code", "display", "block");
        var _this = this;
        this.loadPageSource(null, url, function (result, success) {
            var desc = "";
            if (success !== false) {//for widget theme
                result = result.replace('<!--<link rel="stylesheet" href="../../_lib/focus-ui/theme/bootstrap.min.css">-->',
                    '<link rel="stylesheet" href="../../_lib/focus-ui/theme/bootstrap.min.css">');
                result = result.replace('<!--<link rel="stylesheet" href="../_lib/focus-ui/theme/bootstrap.min.css">-->',
                    '<link rel="stylesheet" href="../_lib/focus-ui/theme/bootstrap.min.css">');
                var descIndex = result.indexOf("<demo-desc>");
                if (descIndex >= 0) {
                    desc = result.substring(
                        descIndex + 11, result.indexOf("</demo-desc>")
                    );
                }
                result = result.substring(0, result.indexOf("</html>") + 7);
                result = DemoIndex.encodeSource(result);
            }
            _this.updateSourceCode(result);
            _this.updateDescription(desc);
        });
    },
    updateSourceCode: function (sourceCode) {
        z.dom.query("#sourceCode").innerHTML = sourceCode;
        if (hljs) {
            hljs.highlightBlock(z.dom.query("#sourceCode"));
        }
    },
    updateDescription: function (desc) {
        if (desc) {
            z.dom.setStyle(".demo_content>.description", "display", "block");
            z.dom.query("#demoDescription").innerHTML = desc;
        } else {
            z.dom.setStyle(".demo_content>.description", "display", "none");
        }
    },
    encodeSource: function (result) {
        return result.replace(/</g, '&lt;').replace(/>/g, '&gt;')
    },
    loadPageSource: function (key, url, callBack, context) {
        if (key) {
            var cached = z.bom.getLocalStorage(key);
            if (cached) {
                callBack.apply(context, [cached]);
                return;
            }
        }
        z.ajax.get(url, {
            complete: function (status, result) {
                if (status === 200) {
                    if (key) {
                        z.bom.setLocalStorage(key, result, 12 * 60);
                    }
                } else {
                    if (status === 408) {
                        result = "load '" + url + "' timeout";
                    } else {
                        result = "load '" + url + "' fail";
                    }
                }
                callBack.apply(context, [result, status === 200])
            }
        });
    }
};
z.ready(function () {
    DemoIndex.init();
});