var ruler = require('../../components/jsRuler.js');
var pasteDataFormater = require('../../util/pasteDataFormatter.js');
import { BaseViewModel } from '../master/baseViewModel.js';
import { BaseSecondaryForm, BaseInnerModel } from '../master/baseModels.js';
import { ApiService } from "../../util/apiService.js";
import { MagazineDownloadFile } from './model.js';
var rangy = require("../../vendors/rangy.js");
export function RichTextEditor() {
    var self = this;
    self.magazine = ko.observable();
    self.wideRight = ko.observable(false);
    self.setting = ko.observable(new PageSetting(self));
    self.startPageNumber = ko.observable();
    self.textTemplates = ko.observableArray();
    self.activeObject = ko.observable();
    self.activeTextTemplate = ko.observable();
    self.showMenu = ko.observable(false);
    self.showMenuType = ko.observable(false);
    self.evenPage = ko.observable(false);
    self.oddPage = ko.observable(false);
    self.removeTextTemplate = ko.observable(false);
    self.onlyThisPageCaption = ko.observable(false);
    self.onlyThisPage = ko.observable(false);
    self.tagTemplates = ko.observableArray();
    self.fillTagTemplates = function () {
        var tagTemplates = [
            {
                category: "تیتر",
                templates: [
                    {
                        id: 1,
                        title: "تیتر 1",
                        value: "h1",
                        textBold: true,
                        textFontSize: "14px"
                    },
                    {
                        id: 2,
                        title: "تیتر 2",
                        value: "h2",
                        textBold: true,
                        textFontSize: "12px"
                    },
                    {
                        id: 3,
                        title: "تیتر 3",
                        value: "h3",
                        textBold: false,
                        textFontSize: "11px"
                    },
                    {
                        id: 4,
                        title: "تیتر 4",
                        value: "h4",
                        textBold: false,
                        textFontSize: "11px"
                    },
                    {
                        id: 5,
                        title: "تیتر 5",
                        value: "h5",
                        textBold: false,
                        textFontSize: "11px"
                    },
                    {
                        id: 6,
                        title: "تیتر 6",
                        value: "h6",
                        textBold: false,
                        textFontSize: "11px"
                    }
                ]
            },
            {
                category: "تیتیر شمارشی",
                templates: [
                    {
                        id: 7,
                        title: "H1 (1)",
                        className: "num-tag-h1",
                        textBold: true,
                        textFontSize: "14px"
                    },
                    {
                        id: 8,
                        title: "H2 (1-1)",
                        className: "num-tag-h2",
                        textBold: true,
                        textFontSize: "12px"
                    },
                    {
                        id: 9,
                        title: "H3 (1-1-1)",
                        className: "num-tag-h3",
                        textBold: false,
                        textFontSize: "11px"
                    },
                    {
                        id: 10,
                        title: "H4 (1-1-1-1)",
                        className: "num-tag-h4",
                        textBold: false,
                        textFontSize: "11px"
                    },
                    {
                        id: 11,
                        title: "H5 (1-1-1-1-1)",
                        className: "num-tag-h5",
                        textBold: false,
                        textFontSize: "11px"
                    }
                ]
            }
        ];
        self.tagTemplates.removeAll();
        for (var i = 0; i < tagTemplates.length; i++) {
            var target = tagTemplates[i];
            var record = new HtmlTemplateCategory(target);
            self.tagTemplates.push(record);
        }
    };
    self.addHtmlTemplate = function (model, item) {
        if (item.id <= 6) {
            self.toggleCommand(null, "fontSize", item.textFontSize);
            self.toggleCommand(null, "fontSize", item.textBold);
        }
        if (item.id > 6) {
            rangy.execSelectionCommand("addTemplate", undefined, item.className);
            self.refreshNumericalTags();
        }
        $(".col-select").removeClass("open");
    };
    self.refreshNumericalTags = function () {
        var lvl1 = 1, lvl2 = 1, lvl3 = 1,
            phrase,
            lvl4 = 1, lvl5 = 1, target;
        var tags = $(".num-tag");
        if (_h.any(tags))
            for (var i = 0; i < tags.length; i++) {
                target = $(tags[i]);
                var span = target.children(".num-tag-c");
                if (span.length === 0) {
                    target.prepend("<span class='num-tag-c'></span>");
                    span = target.children(".num-tag-c");
                }
                if ($(target).hasClass("num-tag-h1")) {
                    phrase = lvl1 + '.';
                    lvl1++;
                    lvl2 = 1;
                    lvl3 = 1;
                    lvl4 = 1;
                    lvl5 = 1;
                }
                if ($(target).hasClass("num-tag-h2")) {
                    phrase = lvl1 + '.' + lvl2;
                    lvl2++;
                    lvl3 = 1;
                    lvl4 = 1;
                    lvl5 = 1;
                }
                if ($(target).hasClass("num-tag-h3")) {
                    phrase = lvl1 + '.' + lvl2 + '.' + lvl3;
                    lvl3++;
                    lvl4 = 1;
                    lvl5 = 1;
                }
                if ($(target).hasClass("num-tag-h4")) {
                    phrase = lvl1 + '.' + lvl2 + '.' + lvl3 + '.' + lvl4;
                    lvl4++;
                    lvl5 = 1;
                }
                if ($(target).hasClass("num-tag-h5")) {
                    phrase = lvl1 + '.' + lvl2 + '.' + lvl3 + '.' + lvl4 + '.' + lvl5;
                    lvl5++;
                }
                $(target).attr("data-info", phrase);
                $(span).text(phrase);
            }
    };
    self.tableTemplateModel = ko.observable(new TableTemplateSelectViewModel(self));
    self.GetTableTemplateHtml = function (id, callback) {
        ApiService.request(
            {
                url: "/api/magazine/gettemplatepreview",
                data: {
                    magazineId: self.magazine().id(),
                    tableTemplateId: id
                },
                success: function (data) {
                    if (!_h.isNullOrEmpty(data.data)) {
                        callback(data);
                    }
                },
                error: function (data) {
                    callback(null);
                }
            });
    };
    self.getChartPicture = function (tableTemplateId, chartId, target) {
        ApiService.request(
            {
                url: "/api/magazine/getchartpreview",
                data: {
                    magazineId: self.magazine().id(),
                    tableTemplateId: tableTemplateId,
                    chartId: chartId
                },
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        if (target) {
                            $(target).attr("src", data.data);
                            $(target).attr("title", data.title);

                        } else {
                            var imgString = $('<img/>').attr("src", data.data)
                                .css({
                                    "max-height": "100%",
                                    "max-width": "100%"
                                })
                                .attr({
                                    title: data.title,
                                    'chart-id': chartId,
                                    'template-id': tableTemplateId
                                })
                                .addClass('mimage chart-image').prop('outerHTML');
                            var p = "<p style='text-align: center;'>" + imgString + "<p/>";
                            var hasSelectHtml = self.hasSelectHtml("mpart");
                            if (hasSelectHtml)
                                document.execCommand('insertHTML', false, p);
                            else
                                $(".active-ed").append(p);
                        }
                    }
                },
                error: function (data) {
                }
            });
    }
    self.toggleCommand = function (parent, command, value, e) {
        switch (command) {
            case "backColor":
            case "textColor":
            case "fontSize":
            case "fontName":
            case "lineHeight":
                rangy.execSelectionCommand(command, undefined, value);
                break;
            case "removeFormat":
                document.execCommand('styleWithCSS', false, false);
                document.execCommand("removeFormat", false, value);
                break;
            default:
                rangy.execSelectionCommand(command);
                break;
        }
        self.htmlContentCleaner();
        self.updateButtonPaneStatus();
    };
    self.toggleRegularTextCommand = function (parent, command, value) {
        var activePage = self.getActivePage();
        var header = activePage.find(".mheader");
        var footer = activePage.find(".mfooter");
        switch (command) {
            case "paragraphDelete":
                self.activeObject().remove();
                self.refreshPartsSize();
                self.activeObject(null);
                self.showMenu(false);
                break;
            case "defaultOddHeader":
                header.addClass("default-odd-header");
                self.setting().defaultOddHeader(header[0].outerHTML);
                self.setting().changePages("defaultOddHeader");
                break;
            case "defaultOddFooter":
                footer.addClass("default-odd-footer");
                self.setting().defaultOddFooter(footer[0].outerHTML);
                self.setting().changePages("defaultOddFooter");
                break;
            case "defaultHeader":
                header.addClass("default-header");
                self.setting().defaultHeader(header[0].outerHTML);
                self.setting().changePages("defaultHeader");
                break;
            case "defaultFooter":
                footer.addClass("default-footer");
                self.setting().defaultFooter(footer[0].outerHTML);
                self.setting().changePages("defaultFooter");
                break;
            case "defaultContent":
                var guid = _h.generateUuid();
                var array = self.getRangeHtml();
                var contentStr = "";
                if (array && array.length)
                    for (var i = 0; i < array.length; i++) {
                        var target = $(array[i]);
                        target.attr("data-id", guid);
                        contentStr += target[0].outerHTML;
                    }
                if (!_h.isEmpty(contentStr)) {
                    _h.kocnx()
                        .openForm(new TextTemplateForm(self, { id: guid, content: contentStr }));
                }
                break;
        }
    };
    self.saveTextTemplate = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var jsonModel = { id: item.id(), title: item.title(), content: item.content() };
        var model = new TextTemplate(jsonModel);
        self.textTemplates.push(model);
        self.addTextTemplate(jsonModel);
        _h.kocnx().closeForm();
    };
    self.getTextTemplate = function () {
        var data = localStorage.getItem("TextTemplates");
        if (!_h.isNullOrEmpty(data) && data !== "") {
            var list = [];
            try {
                list = JSON.parse(data);
                var title = list[0].title.toLowerCase();
            } catch (e) {
                localStorage.removeItem("TextTemplates");
                list = [];
            }
            if (_h.any(list))
                for (var i = 0; i < list.length; i++) {
                    var target = list[i];
                    self.textTemplates.push(new TextTemplate({
                        id: target.id, title: target.title, content: target.content
                    }));
                }
        }
    };
    self.addTextTemplate = function (item) {
        var list = [];
        var data = localStorage.getItem("TextTemplates");
        if (!_h.isNullOrEmpty(data) && data !== "") {
            list = JSON.parse(data);
            list.push(item);
        } else {
            list.push(item);
        }
        localStorage.setItem("TextTemplates", JSON.stringify(list));
    };
    self.clearTextTemplate = function (item) {
        var list = [];
        var data = localStorage.getItem("TextTemplates");
        if (!_h.isNullOrEmpty(data) && data !== "") {
            list = JSON.parse(data);
            list = list.filter(e => e.id !== item.id());
            self.textTemplates.remove(item);
        }
        localStorage.setItem("TextTemplates", JSON.stringify(list));
    };
    self.applyTextTemplate = function () {
        var html = self.activeTextTemplate().content();
        var pages = $(".page");
        for (var i = 0; i < pages.length; i++) {
            var target = $(pages[i]);
            var parent = target.parent();
            var pageId = Number(parent.attr("page-id"));
            var isEven = self.isEvenNumber(pageId);
            var template = $(html);
            template.addClass("text-template");
            var copyTarget = target.find(".mcontent");
            if (self.removeTextTemplate()) {
                var templateId = $(template[0]).attr("data-id");
                var templateTarget = copyTarget.find("[data-id='" + templateId + "']");
                if (templateTarget.length)
                    templateTarget.remove();
            } else {
                if ((self.evenPage() && isEven)
                    || (self.oddPage() && !isEven)
                    || (self.onlyThisPage() && target.hasClass("active-page"))) {
                    copyTarget.append(html);
                }
            }
        }
    }
    self.togglePictureCommand = function (parent, command, value) {
        switch (command) {
            case "rotateRight":
                var degreesRight = self.getRotateDegree("right");
                self.activeObject().css({
                    'transform': 'rotate(' + degreesRight + 'deg)',
                    '-ms-transform': 'rotate(' + degreesRight + 'deg)',
                    '-moz-transform': 'rotate(' + degreesRight + 'deg)',
                    '-webkit-transform': 'rotate(' + degreesRight + 'deg)',
                    '-o-transform': 'rotate(' + degreesRight + 'deg)'
                });
                break;
            case "rotateLeft":
                var degrees = self.getRotateDegree("left");
                self.activeObject().css({
                    'transform': 'rotate(' + degrees + 'deg)',
                    '-ms-transform': 'rotate(' + degrees + 'deg)',
                    '-moz-transform': 'rotate(' + degrees + 'deg)',
                    '-webkit-transform': 'rotate(' + degrees + 'deg)',
                    '-o-transform': 'rotate(' + degrees + 'deg)'
                });
                break;
            case "pictureDelete":
                $(self.activeObject().parent()[0]).remove();
                self.activeObject(null);
                self.showMenu(false);
                break;
            case "pictureRight":
                self.activeObject().css("float", "right");
                break;
            case "pictureCenter":
                self.activeObject().css("float", "none");
                break;
            case "pictureLeft":
                self.activeObject().css("float", "left");
                break;
        }
    };
    self.toggleTableTemplateCommand = function (parent, command, value) {
        var htmlTag;
        switch (command) {
            case "templateDelete":
                self.activeObject().remove();
                self.activeObject(null);
                self.showMenu(false);
                break;
            case "zoomIn":
                htmlTag = self.activeObject().find("iframe").contents().find("table");
                var zoom = parseFloat(htmlTag.css("zoom")) || 1;
                zoom = zoom + 0.1;
                htmlTag.css("zoom", zoom);
                self.activeObject().attr("data-zoom", zoom);
                self.resizeTableTemplateFrame(self.activeObject());
                break;
            case "zoomOut":
                htmlTag = self.activeObject().find("iframe").contents().find("table");
                var zoomOut = parseFloat(htmlTag.css("zoom")) || 1;
                zoomOut = zoomOut - 0.1;
                htmlTag.css("zoom", zoomOut);
                self.activeObject().attr("data-zoom", zoomOut);
                self.resizeTableTemplateFrame(self.activeObject());
                break;
            case "dragStartTable":
                $(".dragStopTable").removeClass("hide");
                $(".dragStartTable").addClass("hide");
                self.activeObject().draggable({
                    cursor: "move",
                    axis: "x",
                    grid: [2, 2]
                });
                parent = self.activeObject().closest(".mcontent");
                var groundParent = self.activeObject().closest(".page");
                parent.css("overflow", "visible");
                groundParent.css("overflow", "visible");
                self.activeObject().css("opacity", 0.3);
                break;
            case "dragStopTable":
                self.activeObject().closest(".mcontent").css("overflow", "hidden");
                self.activeObject().closest(".page").css("overflow", "hidden");
                self.activeObject().css("opacity", 1);
                self.activeObject().draggable("destroy");
                $(".dragStopTable").addClass("hide");
                $(".dragStartTable").removeClass("hide");
                break;
            case "templateRefresh":
                var page = self.activeObject().closest(".page");
                self.activeObject().empty();
                self.loadPageTableTemplates(page);
                self.showMenu(false);
                break;
        }
    };
    self.getRotateDegree = function (side) {
        try {
            parseInt(self.activeObject().attr('style').split('rotate(')[1].split('deg)')[0]);
        } catch (e) {
            if (side === "right") {
                return 90;
            } else {
                return -90;
            }
        }
        var deg = parseInt(self.activeObject().attr('style').split('rotate(')[1].split('deg)')[0]);
        if (side === "right") {
            if (deg === 360) {
                if (side === "right") {
                    deg = 90;
                } else {
                    deg = -90;
                }
            }
            else
                deg = deg + 90;
        } else {
            deg = deg - 90;
        }
        return deg;
    };
    self.updateButtonPaneStatus = function () {
        if (_h.isNullOrEmpty(self.getActiveEd()))
            return;
        var tags = self.getTagsRecursive(document.getSelection().anchorNode),
            activeClass = 'selected-tools';
        $(".rich-texteditor").find('.toolbar-btn').removeClass(activeClass);
        $(".rich-texteditor").find(".fontsizeVal").val("");
        $(".rich-texteditor").find(".fontfamilyVal").val("");
        $(".rich-texteditor").find(".linespaceVal").val("");
        $(".rich-texteditor").find(".textcolorVal").css("color", "");
        $(".rich-texteditor").find(".backcolorVal").css("background-color", "");
        var hasFontFamily = false;
        var hasLineHeight = false;
        var hasFontSize = false;
        $.each(tags, function (i, tag) {
            var btnName = self.tagToButton[tag.toLowerCase()],
                $btn = $('.' + btnName);
            if ($btn.length > 0) {
                $btn.addClass(activeClass);
            } else {
                var val, color;
                if (tag.startsWith("fontSize-")) {
                    val = tag.split("-")[1];
                    $(".rich-texteditor").find(".fnt-selector")
                        .fontSelector("setValue", {
                            textFontSize: val,
                        });
                    hasFontSize = true;
                }
                if (tag.startsWith("fontFamily-")) {
                    val = tag.split("-")[1];
                    $(".rich-texteditor").find(".fnt-selector")
                        .fontSelector("setValue", {
                            textFontFamily: val,
                        });
                    hasFontFamily = true;
                }
                if (tag.startsWith("lineHeight-")) {
                    val = Number(tag.split("-")[1]);
                    $(".linespaceVal").val(val);
                    hasLineHeight = true;
                }
                if (tag.startsWith("backgroundColor-")) {
                    val = tag.split("-")[1];
                    color = _h.toHex3(val);
                    $(".backcolorVal").css("background-color", color);
                }
                if (tag.startsWith("color-")) {
                    val = tag.split("-")[1];
                    color = _h.toHex3(val);
                    $(".textcolorVal").css("color", color);
                }
                if (tag.startsWith("fontWeight-")) {
                    val = tag.split("-")[1];
                    $(".boldVal").addClass(val === "bold" ? activeClass : "");
                }
                if (tag.startsWith("fontStyle-")) {
                    val = tag.split("-")[1];
                    $(".italicVal").addClass(val === "italic" ? activeClass : "");
                }
                if (tag.startsWith("textDecorationLine-")) {
                    val = tag.split("-")[1];
                    $(".underlineVal").addClass(val === "underline" ? activeClass : "");
                }

                if (tag.startsWith("direction-")) {
                    val = tag.split("-")[1];
                    if (val === "rtl")
                        $(".dirRtlVal").addClass(activeClass);
                    else
                        $(".dirLtrVal").addClass(activeClass);
                }

            }
        });
        //var defVal = self.getDefault();
        if (!hasFontSize) {
            $(".rich-texteditor").find(".fnt-selector").fontSelector("setValue", {
                textFontSize: "11px",
            });
        }
        if (!hasFontFamily) {

            $(".fontfamilyVal").val("Nazanin");
            $(".rich-texteditor").find(".fnt-selector").fontSelector("setValue", {
                textFontFamily: "Nazanin",
            });
        }
        if (!hasLineHeight) {
            $(".rich-texteditor").find(".linespaceVal").val("1");
        }

    };
    self.tagToButton = {
        "strong": "boldVal",
        "em": "italicVal",
        "u": "underlineVal",
        "del": "strikethroughVal",
        "right": "alignrightVal",
        "center": "aligncenterVal",
        "left": "alignleftVal",
        "justify": "alignFullVal",
        "ul": "listbulletsVal",
        "ol": "listnumbersVal"
    };
    self.getTagsRecursive = function (element, tags) {
        tags = tags || (element && element.tagName ? [element.tagName] : []);
        var temp;
        if (element && element.parentNode) {
            element = element.parentNode;
        } else {
            return tags;
        }

        var tag = element.tagName;
        if (tag === 'DIV') {
            return tags;
        }
        if (tag === 'P') {
            tags.push(element.style.textAlign);

            if (!_h.isNullOrEmpty(element.style.textAlign) && element.style.textAlign !== "")
                tags.push(element.style.textAlign);

            if (!_h.isNullOrEmpty(element.style.direction) && element.style.direction !== "")
                tags.push("direction-" + element.style.direction);

            if (!_h.isNullOrEmpty(element.style.lineHeight) && element.style.lineHeight !== "")
                tags.push("lineHeight-" + element.style.lineHeight);
        }
        if (tag === 'SPAN') {
            if (!_h.isNullOrEmpty(element.style.fontSize) && element.style.fontSize !== "") {
                temp = tags.filter(a => a.indexOf("fontSize-") !== -1);
                if (temp.length)
                    temp[0] = "fontSize-" + element.style.fontSize;
                else
                    tags.push("fontSize-" + element.style.fontSize);
            }
            if (!_h.isNullOrEmpty(element.style.fontFamily) && element.style.fontFamily !== "") {
                temp = tags.filter(a => a.indexOf("fontFamily-") !== -1);
                if (temp.length)
                    temp[0] = "fontFamily-" + element.style.fontFamily;
                else
                    tags.push("fontFamily-" + element.style.fontFamily);
            }
            if (!_h.isNullOrEmpty(element.style.backgroundColor) && element.style.backgroundColor !== "") {
                temp = tags.filter(a => a.indexOf("backgroundColor-") !== -1);
                if (temp.length)
                    temp[0] = "backgroundColor-" + element.style.backgroundColor;
                else
                    tags.push("backgroundColor-" + element.style.backgroundColor);
            }


            if (!_h.isNullOrEmpty(element.style.color) && element.style.color !== "") {
                temp = tags.filter(a => a.indexOf("color-") !== -1);
                if (temp.length)
                    temp[0] = "color-" + element.style.color;
                else
                    tags.push("color-" + element.style.color);
            }


            if (!_h.isNullOrEmpty(element.style.fontWeight) && element.style.fontWeight !== "")
                tags.push("fontWeight-" + element.style.fontWeight);

            if (!_h.isNullOrEmpty(element.style.fontStyle) && element.style.fontStyle !== "")
                tags.push("fontStyle-" + element.style.fontStyle);

            if (!_h.isNullOrEmpty(element.style.textDecorationLine) && element.style.textDecorationLine !== "")
                tags.push("textDecorationLine-" + element.style.textDecorationLine);

        }

        tags.push(tag);
        return self.getTagsRecursive(element, tags).filter(function (tag) {
            return tag != null && tag != "";
        });
    };
    self.defaultSemanticMap = [
        {
            name: "font", newName: "span"
        },
        {
            name: "b", newName: "span", style: "font-weight: bold;"
        },
        {
            name: "strong", newName: "span", style: "font-weight: bold;"
        },
        {
            name: "i", newName: "span", style: "font-style: italic;"
        },
        {
            name: "em", newName: "span", style: "font-style: italic;"
        },
        {
            name: "s", newName: "span"
        },
        {
            name: "del", newName: "span"
        },
        {
            name: "strike", newName: "span"
        },
        {
            name: "div", newName: "p", exceptionClasses: ["iframe-shadow", "table-templateId"]
        },
    ];
    self.hasClasses = function (tag, list) {
        if (!list || !list.length)
            return false;
        var res = false;
        for (var i = 0; i < list.length; i++) {
            if (tag.hasClass(list[i]))
                res = true;
        }
        return res;
    }
    self.pageNumbers = ko.observableArray();
    self.showPageNavigate = function () {
        self.pageNumbers.removeAll();
        var pages = $(".page");
        for (var i = 0; i < pages.length; i++) {
            var page = pages[i];
            var pageId = $(page).parent().attr("page-id");
            var isActive = $(page).hasClass("active-page");
            self.pageNumbers.push({ name: pageId, active: ko.observable(isActive) });
        }
    };
    self.navigateTo = function (item, e) {
        var pageBox = $(".tx-page-frame[page-id='" + item.name + "']")[0];
        var currentPage = $(pageBox).find(".page");
        if (!currentPage.hasClass("active-page")) {
            self.setGuidLines();
            $(".page").removeClass("active-page");
            currentPage.addClass("active-page");
            self.transferGuidLines();
            var templateList = $(".table-templateId:empty");
            var chartList = currentPage.find(".chart-image").filter(function (i, a) {
                if ($(a).attr("src") && $(a).attr("src").endsWith("f//Z"))
                    return true;
                return false;
            });
            if (_h.any(templateList) || _h.any(chartList))
                self.loadPageTableTemplates(currentPage);
        }
        self.activePageAnalyzer();
        self.updateButtonPaneStatus();
        for (var i = 0; i < self.pageNumbers().length; i++) {
            var page = self.pageNumbers()[i];
            if (item.name === page.name)
                page.active(true);
            else
                page.active(false);
        }
        currentPage.get(0).scrollIntoView();
    };
    self.configTools = function () {
        //var defVal = self.getDefault();
        var composition = false,
            debounceButtonPaneStatus,
            ctrl = false;
        $(document).on("click", ".evo-palette td", function (e) {
            var target = e.target;
            if (target) {
                var color = $(target).css("background-color");
                var trColor = _h.toHex3(color);
                var parent = $(target).closest(".dropdown-menu");
                if (parent) {
                    var prop = parent.attr("data-prop");
                    switch (prop) {
                        case "backcolor":
                            self.toggleCommand(null, "backColor", trColor);
                            break;
                        case "textcolor":
                            self.toggleCommand(null, "textColor", trColor);
                            break;
                    }
                    if (prop) {
                        var property = "." + prop + "Val";
                        $(property).css("background-color", trColor);
                    }
                }
            }
        });
        $(document).on("click", ".eraseColor", function (e) {
            var target = e.target;
            if (target) {
                var parent = $(target).closest(".dropdown-menu");
                if (parent) {
                    var prop = parent.attr("data-prop");
                    switch (prop) {
                        case "backcolor":
                            self.toggleCommand(null, "backColor", "#ffffff");
                            $(".backcolorVal").css("background-color", "#ffffff");
                            break;
                        case "textcolor":
                            self.toggleCommand(null, "textColor", "#000000");
                            $(".textcolorVal").css("background-color", "#000000");
                            break;
                    }
                }
            }
            return false;
        });
        $(document).on('click', ".rich-texteditor", function (e) {
            if (self.showMenu()
                && !$(e.target).hasClass("icon-image-xsmall")
                && !$(e.target).hasClass("toolbar-btn")) {
                self.showMenu(false);
                var activePage = self.getActivePage();
                if (!_h.isNullOrEmpty(self.activeObject())
                    && self.activeObject().hasClass("table-templateId")) {
                    self.activeObject().css("opacity", 1);
                    if (self.activeObject().hasClass("ui-draggable"))
                        self.activeObject().draggable("destroy");
                    activePage.closest(".mcontent ").css("overflow", "hidden");
                    activePage.closest(".page").css("overflow", "hidden");
                }
            }
        });
        $(document).on('dblclick', ".iframe-shadow", function (e) {
            e.preventDefault();
            var parent = $(e.currentTarget).parent();
            if (parent.hasClass("ui-draggable")) {
                parent.draggable("destroy");
                parent.css("opacity", 1);
                parent.closest(".mcontent").css("overflow", "hidden");
                parent.closest(".page").css("overflow", "hidden");
                $(".dragStopTable").addClass("hide");
                $(".dragStartTable").removeClass("hide");
            }
        });
        $(document).on('click', ".CopyTextTemplate", function (e) {
            e.preventDefault();
            var tag = $(e.target).closest("tr");
            var model = ko.contextFor(tag[0]);
            self.activeTextTemplate(model.$data);
            self.showMenu(true);
            self.showMenuType('text-template');
            var page = self.getActivePage();
            var parent = page.parent();
            var id = parent.attr("page-id");
            self.onlyThisPageCaption("فقط صفحه " + id);
            $(".image-menu").css({
                "top": e.clientY - $(".image-menu").height(),
                "left": e.clientX
            });
        });
        $(document).on("click", ".page-navigate-box", function (e) {
            self.showPageNavigate();
        });
        $(document).on('compositionstart compositionupdate', ".mheader, .mcontent, .mfooter", function (e) {
            composition = true;
        });
        $(document).on('keyup compositionend', ".mheader, .mcontent, .mfooter", function (e) {
            if (e.type === 'compositionend') {
                composition = false;
            } else if (composition) {
                return;
            }
            var keyCode = e.which;

            if (keyCode >= 37 && keyCode <= 40) {
                return;
            }
            if (keyCode === 8 || keyCode === 46) {
                self.refreshNumericalTags();
            }

            if ((e.ctrlKey || e.metaKey) && (keyCode === 89 || keyCode === 90)) {
                return false;
            } else if (!ctrl && keyCode !== 17) {
                self.htmlContentCleaner();
            } else if (typeof e.which === 'undefined') {
                self.htmlContentCleaner();
            }

            setTimeout(function () {
                ctrl = false;
            }, 50);
        });
        $(document).on('mouseup keydown keyup', ".mheader, .mcontent, .mfooter", function (e) {
            if ((!e.ctrlKey && !e.metaKey) || e.altKey) {
                setTimeout(function () { // "hold on" to the ctrl key for 50ms
                    ctrl = false;
                },
                    50);
            }


            clearTimeout(debounceButtonPaneStatus);
            debounceButtonPaneStatus = setTimeout(function () {
                self.updateButtonPaneStatus();
            },
                50);
        });
        $(document).on('keydown', ".mheader, .mcontent, .mfooter", function (e) {
            var sel = rangy.getSelection();
            var range = sel.rangeCount ? sel.getRangeAt(0) : null;
            var tag;
            if (e.keyCode === 46) {
                if (range.endContainer === range.startContainer) {
                    tag = range.startContainer;
                    if (tag.nodeType !== 3) {
                        if (tag.nodeName !== "P") {
                            tag = self.findUpTag(tag, "p");
                        }
                        if (!_h.isNullOrEmpty(tag) && $(tag).has("img").length === 0)
                            $(tag).remove();
                        return false;
                    }
                }
            }
        });

        setTimeout(function () {
            $(".rich-texteditor").find(".fnt-selector").fontSelector({
                textFontSize: "11px",
                textFontFamily: "Nazanin",
                magazine: true
            });
        }, 150);


        $(document).on('change', ".linespaceVal", function (e) {
            var optVal = $(e.currentTarget).val();
            self.toggleCommand(null, "lineHeight", optVal);
        });
        $(document).on('click', ".font-select", function (e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        });
        $(document).on('contextmenu', ".mheader, .mcontent, .mfooter", function (e) {
            e.preventDefault();
            var closestPart = $(e.currentTarget);
            if (!closestPart.hasClass("mpart"))
                closestPart = $(e.currentTarget).closest(".mpart");
            if (!closestPart.length)
                closestPart = $(e.target).closest(".mpart");
            var target = $(e.target);
            self.setActivePage(closestPart);
            self.showMenu(true);
            if (target.hasClass("mimage")) {
                self.showMenuType('image');
                self.activeObject($(e.target));
                self.pictureHeightsub.suspend();
                self.pictureWidthsub.suspend();
                var jObject = $(e.target).get(0);
                var height = jObject.style.height.replace("%", "");
                var width = jObject.style.width.replace("%", "");

                self.pictureHeight(height);
                self.pictureWidth(width);
                self.pictureHeightsub.unsuspend();
                self.pictureWidthsub.unsuspend();
                $(".image-menu").position({
                    my: 'right top',
                    at: 'right top',
                    of: $(e.target)
                });
            }
            else if (target.hasClass("iframe-shadow") || target.hasClass("table-templateId")) {
                self.showMenuType('table-template');
                self.activeObject($(e.target).parent());
            } else {
                self.showMenuType('text');
                self.activeObject(undefined);
            }
            if (closestPart.hasClass("mheader"))
                self.toggleToolbarVisibility("header");
            if (closestPart.hasClass("mcontent"))
                self.toggleToolbarVisibility("content");
            if (closestPart.hasClass("mfooter"))
                self.toggleToolbarVisibility("footer");

            if (self.showMenuType() !== 'image')
                $(".image-menu").position({
                    my: 'top top',
                    at: 'top top',
                    of: $(e.target)
                });

        });
        $(document).on('click', ".image-menu .form-control, .image-menu .btn, .image-menu .input-group-addon", function (e) {
            e.preventDefault();
            e.stopPropagation();
        });
    };
    self.toggleToolbarVisibility = function (loc) {
        var page = self.getActivePage();
        var parent = page.parent();
        var id = parent.attr("page-id");
        var isEven = self.isEvenNumber(id);
        $(".defaultOddHeader").css("display", (loc === "header" && !isEven) ? "" : "none");
        $(".defaultOddFooter").css("display", (loc === "footer" && !isEven) ? "" : "none");
        $(".defaultHeader").css("display", (loc === "header" && isEven) ? "" : "none");
        $(".defaultFooter").css("display", (loc === "footer" && isEven) ? "" : "none");
        $(".dragStartTable").css("display", (loc === "content" && self.showMenuType() === "table-template") ? "" : "none");

        //$(".pasteContent").css("display",  ? "" : "none");

    };
    self.getActivePage = function () {
        return $(".active-page");
    };
    self.setActivePage = function (currentTarget) {
        if (_h.isNullOrEmpty(currentTarget))
            return;
        var currentPage = currentTarget.closest(".page");
        if (!currentPage.hasClass("active-page")) {
            self.setGuidLines();
            $(".page").removeClass("active-page");
            currentPage.addClass("active-page");
            self.transferGuidLines();
            var templateList = $(".table-templateId:empty");
            var chartList = currentPage.find(".chart-image").filter(function (i, a) {
                if ($(a).attr("src") && $(a).attr("src").endsWith("f//Z"))
                    return true;
                return false;
            });
            if (_h.any(templateList) || _h.any(chartList))
                self.loadPageTableTemplates(currentPage);
        }
        self.activePageAnalyzer();
        self.updateButtonPaneStatus();
    };
    self.handleImageUploadBtn = function (element, e) {
        e.preventDefault();
        if (!$(".active-ed") || $(".active-ed").length === 0) {
            toast.custom("error", _h.getApiMessage("ErrorSelectPageSection"));
        } else {
            $("#upload:hidden").trigger('click');
        }
    };
    self.handleImageUpload = function (element) {
        var file = element.files[0];
        var ext = _h.getExtension(file.name);


        if (ext.toLowerCase() !== "jpg" && ext.toLowerCase() !== "jpeg" && ext.toLowerCase() !== "png") {
            toast.custom("error", " فرمت های صحیح تصویر" + " jpg, jpeg, png" + "می باشد");
            return false;
        }
        _h.toBase64(file, function (res) {
            var model = {
                controllerName: 7,
                fileName: file.name,
                file: res
            };
            ApiService.request(
                {
                    url: "/api/common/postimage",
                    data: model,
                    success: function (data) {
                        if (!_h.isEmpty(data)) {
                            if (_h.isEmpty(data.model)) {
                                _h.failToast("در هنگام بارگزاری تصویر خطایی رخ داده است");
                            } else {
                                var imgString = $('<img/>').attr("src", data.model)
                                    .css({
                                        "max-height": "100%",
                                        "max-width": "100%",
                                        "height": "100%",
                                        "width": "100%"
                                    }).addClass('mimage').prop('outerHTML');
                                var p = "<p style='text-align: center;'>" + imgString + "<p/>";
                                var hasSelectHtml = self.hasSelectHtml("mpart");
                                if (hasSelectHtml)
                                    document.execCommand('insertHTML', false, p);
                                else
                                    $(".active-ed").append(p);
                            }
                        }
                        $("#upload").val(null);
                    },
                    error: function (data) {
                        _h.failToast("در هنگام بارگزاری تصویر خطایی رخ داده است");
                    }
                });
        }.bind(this));
    };
    self.htmlContentCleaner = function () {
        var $ed = $(".active-ed");
        if (!$ed || $ed.length === 0)
            return;
        var newTag;
        for (var j = 0; j < self.defaultSemanticMap.length; j++) {
            var oldtag = self.defaultSemanticMap[j];
            newTag = oldtag.newName;
            $(oldtag.name, $ed).each(function () {
                var $oldTag = $(this);
                if ($oldTag) {
                    if (!oldtag.exceptionClasses || !self.hasClasses($oldTag, oldtag.exceptionClasses)) {
                        $oldTag.wrap('<' + newTag + '/>');
                        $oldTag.contents().unwrap();
                        if (oldtag.style)
                            $oldTag.attr("style", oldtag.style);

                        if (newTag === "p") {

                        }

                    }
                }
            });
        }
        if ($ed.children().length)
            for (var i = 0; i < $ed.children().length; i++) {
                if ($ed.children()[i].nodeName === "BR")
                    $($ed.children()[i]).remove();
            }

        var inlineElementsSelector =
            "a,abbr,acronym,b,caption,cite,code,col,dfn,dir,dt,dd,em,font,hr,i,kbd,ol,ul,li,q,span,strikeout,strong,sub,sup,u",
            blockElementsSelector = ':not(' + inlineElementsSelector + ')';

        $ed.contents().filter(function () {
            return this.nodeType === 3 && this.nodeValue.trim().length > 0;
        }).wrap('<span/>');
        var wrapInlinesInParagraphsFrom = function ($from) {
            if ($from.length !== 0) {
                var $finalParagraph = $from.nextUntil(blockElementsSelector)
                    .addBack().wrapAll('<p/>').parent(),
                    $nextElement = $finalParagraph.nextAll(inlineElementsSelector).first();
                $finalParagraph.next('br').remove();
                wrapInlinesInParagraphsFrom($nextElement);
            }
        };
        wrapInlinesInParagraphsFrom($ed.children(inlineElementsSelector).first());
        $.each($ed.find("p"), function () {
            var p = $(this);
            if (p.text() === "" && !p.has("br").length && !p.has("img").length) {
                p.remove();
            } else {
                if (p.has("p").length && (p.has("ol").length || p.has("ul").length)) {
                    p.find("p").remove();
                    var tar = $("<p><br></p>").insertAfter(p);
                    self.fixCursorLocation(tar);
                }
            }
        });
        $ed.find(".table-templateId br").remove();
        $.each($ed.find("ol li, ul li"),
            function () {
                var li = $(this);
                if (li.has("span")) {
                    var fontFamily, fontSize;
                    var spans = li.find("span");

                    $.each(spans,
                        function () {
                            var span = $(this);
                            var style = span.attr("style");
                            if (style && style.indexOf("font-size") !== -1)
                                fontSize = span.css("font-size");
                            if (style && style.indexOf("font-family") !== -1)
                                fontFamily = span.css("font-family");
                        });
                    if (fontSize)
                        li.css("font-size", fontSize);
                    if (fontFamily)
                        li.css("font-family", fontFamily);
                }
            });
    };
    self.fixCursorLocation = function (element, toEnd) {
        try {
            element = element.get(0);
        } catch (e) {
            //
        }
        var sel = rangy.getSelection();
        var range = sel.rangeCount ? sel.getRangeAt(0) : null;
        range.setStart(element, 0);
        range.setEnd(element);
        rangy.getSelection().setSingleRange(range);
    };
    self.fillModel = function (model) {
        var json;
        self.startPageNumber(self.magazine().startPageNumber());
        if (!_h.isNullOrEmpty(model.setting) && model.setting !== "") {
            json = JSON.parse(model.setting);
            self.setting().fillModel(json);
            if (json && !_h.isNullOrEmpty(json.guideLines) && json.guideLines !== "") {
                self.guideLines.portrait = json.guideLines.portrait;
                self.guideLines.landscape = json.guideLines.landscape;
            }
        }
        setTimeout(function () {
            if (!_h.isNullOrEmpty(model.pages)) {
                var list = $(model.pages);
                var counter = 0;
                var targetUpdate = undefined;
                $.each(list, function (i, p) {
                    var pageElement = $(p);
                    if (pageElement.hasClass("page")) {
                        var page = "<div class='col-lg-12 tx-page-frame' page-id=" +
                            (counter + 1) + ">";
                        var pageOrientation = pageElement.attr("orientation");
                        if (pageOrientation === "Landscape") {
                            pageElement.css({
                                "width": "",
                                "height": ""
                            });
                            pageElement.find(".main").css({
                                "transform": "",
                                "width": "",
                                "height": "",
                                "right": "",
                                "bottom": ""
                            });
                        }
                        pageElement.find(".main")
                            .append("<div class='header-area hide'></div><div class='footer-area hide'></div>");
                        pageElement.find(".mheader").attr("contenteditable", true);
                        pageElement.find(".mcontent").attr("contenteditable", true);
                        pageElement.find(".mfooter").attr("contenteditable", true);
                        if (!pageElement[0].hasAttribute("orientation"))
                            pageElement.attr("orientation", "Portrait");
                        if (counter === 0) {
                            if (!pageElement.hasClass("active-page"))
                                pageElement.addClass("active-page");
                            targetUpdate = counter + 1;
                        } else {
                            pageElement.removeClass("active-page");
                        }
                        page += pageElement[0].outerHTML;
                        page += "<div class='page-bottom-bar'>" +
                            "<span class='page-number-info'>" +
                            (i + 1) +
                            " از " +
                            model.pages.length +
                            " صفحه " +
                            "</span>" +
                            "</div>";
                        page += "</div>";
                        $(".editor-frame").append(page);
                        counter++;
                    }
                });
                if (targetUpdate > 0) {
                    targetUpdate = $('[page-id="' + targetUpdate + '"]');
                    self.loadPageTableTemplates(targetUpdate);
                    self.configDropFunctionality();
                    self.activePageAnalyzer();
                }
                self.handlePageNumbers();
            } else {
                var content = self.createNewPageContent({
                    paperSize: self.setting().pageSize(),
                    setActive: true,
                    orientation: "Portrait"
                }, 1);
                $(".editor-frame").append(content);
                self.tableTemplateModel().magazineId(self.magazine().id());
                self.tableTemplateModel().init();
                self.handlePageNumbers();
            }
        },
            200);
    };
    self.fillEmpty = function () {
        var content = self.createNewPageContent({
            paperSize: self.setting().pageSize(),
            setActive: true,
            orientation: "Portrait"
        }, 1);
        $(".editor-frame").append(content);
        self.activePageAnalyzer();
        self.handlePageNumbers();
    };
    self.saveChanges = function () {
        var pages = self.getMagazineOutputHtml();
        var setting = self.setting().toServer();
        setting.guideLines = self.guideLines;
        var model = {
            setting: JSON.stringify(setting),
            pages: pages,
            id: self.magazine().id()
        };
        ApiService.request(
            {
                url: "/api/magazine/postsavepages",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data))
                        if (_h.any(data.errors)) {
                            _h.errorListHandler(data.errors);
                        } else {
                            var text = _h.getApiMessage("PostPagesMagazineSuccess");
                            _h.successToast(text);
                        }
                },
                error: function (data) {
                    var text = _h.getApiMessage("PostPagesMagazineError");
                    _h.failToast(text);
                }
            });
    };
    self.getMagazineOutputHtml = function () {
        var pageList = $(".page");
        var outHhtml = "<!DOCTYPE html><html><head>";
        outHhtml += "<link href='" +
            location.protocol +
            "//" +
            location.host +
            "/App/src/styles/magazine-page.css' rel='stylesheet'/>";
        outHhtml += "</head><body>";
        for (var i = 0; i < pageList.length; i++) {
            var target = $(pageList[i])[0].outerHTML;
            var newTarget = $(target);
            var pageSize = newTarget.attr("size");
            var pageOrientation = newTarget.attr("orientation");
            if (pageOrientation === "Landscape") {
                switch (pageSize) {
                    case "A4":
                        newTarget.css({
                            "width": "210mm",
                            "height": "297mm"
                        });
                        newTarget.find(".main").css({
                            "transform": "rotate(90deg)",
                            "width": "297mm",
                            "height": "210mm",
                            "right": "-164px",
                            "bottom": "-164px"
                        });
                        break;
                    case "A3":

                        break;
                }
            }
            newTarget.find("img").css({
                "max-height": "",
                "max-width": "",
            });
            newTarget.find(".mheader").removeAttr("contenteditable");
            newTarget.find(".mcontent").removeAttr("contenteditable");
            newTarget.find(".mfooter").removeAttr("contenteditable");
            newTarget.find(".header-area").remove();
            newTarget.find(".footer-area").remove();
            outHhtml += newTarget[0].outerHTML.trim();
        }
        outHhtml += "</body></html>";
        return outHhtml;
    };
    self.guideLines = { landscape: [], portrait: [] };
    self.setGuidLines = function () {
        if (self.ruler) {
            var activePage = self.getActivePage();
            var direction = $(activePage).attr("orientation");
            if (activePage.parent().find(".rul_wrapper").length) {
                var list = self.ruler.api.getGuides();
                if (!list)
                    list = [];
                if (direction === "Portrait") {
                    self.guideLines.portrait = list;
                } else {
                    self.guideLines.landscape = list;
                }
            }
        }
    }
    self.transferGuidLines = function () {
        if (self.ruler) {
            var activePage = self.getActivePage();
            if (activePage.parent().find(".rul_wrapper").length) {
                var direction = $(activePage).attr("orientation");
                self.ruler.api.clearGuides();
                if (direction === "Portrait") {
                    self.ruler.api.setGuides(self.guideLines.portrait);
                } else {
                    self.ruler.api.setGuides(self.guideLines.landscape);
                }
            }
        }
    }
    self.toggleSuspendPageControls = function (sta) {
        if (sta) {
            self.pageNumbersub.suspend();
            self.marginRightsub.suspend();
            self.marginLeftsub.suspend();
            self.marginTopsub.suspend();
            self.marginBottomsub.suspend();
            self.disableHeadersub.suspend();
            self.disableFootersub.suspend();
            self.disableDefaultHeadersub.suspend();
            self.disableDefaultFootersub.suspend();
            self.disableInNumerationsub.suspend();
            self.disableMarginHeadersub.suspend();
            self.disableMarginFootersub.suspend();
            self.pageOrientationsub.suspend();
        } else {
            self.pageNumbersub.unsuspend();
            self.marginRightsub.unsuspend();
            self.marginLeftsub.unsuspend();
            self.marginTopsub.unsuspend();
            self.marginBottomsub.unsuspend();
            self.disableHeadersub.unsuspend();
            self.disableFootersub.unsuspend();
            self.disableDefaultHeadersub.unsuspend();
            self.disableDefaultFootersub.unsuspend();
            self.disableInNumerationsub.unsuspend();
            self.disableMarginHeadersub.unsuspend();
            self.disableMarginFootersub.unsuspend();
            self.pageOrientationsub.unsuspend();
        }
    };
    self.init = function () {
        rangy.init();
        self.configTools();
        self.tableTemplateModel().magazineId(self.magazine().id());
        self.tableTemplateModel().init();
        self.configDropFunctionality();
        self.getTextTemplate();
        self.fillTagTemplates();
        $(document).off("guideLineMove", ".rul_line");
    };
    self.ruler = undefined;
    self.toggleRuler = function () {
        var el;
        el = document.getElementsByClassName('active-page');
        if (!el)
            return;
        el = el[0];
        if (el.parentNode.getElementsByClassName("rul_wrapper").length > 0) {
            self.ruler.api.destroy();
            self.ruler = undefined;
            $(document).off("guideLineMove", ".rul_line");
        }
        else {
            if (self.ruler) {
                self.ruler.api.destroy();
                self.ruler = undefined;
                $(document).off("guideLineMove", ".rul_line");
            }
            el = document.getElementsByClassName('active-page');
            var pa = el[0].parentNode;
            if (pa) {
                self.ruler = new ruler({
                    container: pa,
                    orientation: self.pageOrientation(),
                    size: "A4",
                    enableMouseTracking: true,
                    enableToolTip: true
                });
                self.transferGuidLines();
                $(document).on("guideLineMove", ".rul_line", function () {
                    self.setGuidLines();
                });
            }
        }
    };
    self.createNewPageContent = function (model, priority) {
        var isEven = self.isEvenNumber(priority);
        var page = "<div class='col-lg-12 tx-page-frame' page-id=" +
            priority + ">" +
            "<div class='page tx-frame" +
            (model.setActive === true ? " active-page " : "") +
            "' orientation='" + model.orientation +
            "' size='" + model.paperSize + "'><div class='main'>";
        page += "<div class='mheader mpart' contenteditable='true'" +
            " style='padding-top:" + self.setting().marginTop() +
            "mm;padding-left:" + self.setting().marginLeft() +
            "mm;padding-right:" + self.setting().marginRight() + "mm;'>" +
            (isEven === true
                ? self.checkNullString(self.setting().defaultHeader())
                : self.checkNullString(self.setting().defaultOddHeader())) +
            "</div>";
        page += "<div class='mcontent mpart' contenteditable='true'" +
            " style='padding-left:" + self.setting().marginLeft() +
            "mm;padding-right:" + self.setting().marginRight() + "mm;'" +
            " ></div>";
        page += "<div class='mfooter mpart' contenteditable='true'" +
            " style='padding-bottom:" + self.setting().marginBottom() +
            "mm;padding-left:" + self.setting().marginLeft() +
            "mm;padding-right:" + self.setting().marginRight() + "mm;'>" +
            (isEven === true
                ? self.checkNullString(self.setting().defaultFooter())
                : self.checkNullString(self.setting().defaultOddFooter())) +
            "</div>";
        page += "<div class='page-number' type='" + self.setting().pageNumber() + "'></div>";
        page += "<div class='header-area hide'></div><div class='footer-area hide'>" +
            "</div></div></div>" +
            "<div class='page-bottom-bar'>" +
            "<span class='page-number-info'>" + priority + " از " + $(".page").length + " صفحه " + "</span>" +
            "</div>" +
            "</div>";
        return page;
    };
    self.addPage = function (setActive) {
        var activePage = self.getActivePage();
        var activePageId = Number(activePage.parent().attr("page-id"));

        var nextPage = activePage.parent().next(".tx-page-frame");
        var content;
        if (!nextPage.length) {
            var pageCount = $(".page").length;
            content = self.createNewPageContent({
                paperSize: self.setting().pageSize(),
                setActive: setActive,
                orientation: "Portrait"
            },
                pageCount + 1);
            $(".editor-frame").append(content);
        } else {
            content = self.createNewPageContent({
                paperSize: self.setting().pageSize(),
                setActive: setActive,
                orientation: "Portrait"
            },
                activePageId + 1);
            $(content).insertAfter(activePage.parent());
            var pages = $(".page");
            for (var i = 0; i < pages.length; i++) {
                var page = pages[i];
                $(page).parent().attr("page-id", i + 1);
            }
        }
        self.handlePageNumbers();
        self.configDragFunctionality();
        self.configDropFunctionality();
    };
    self.removePage = function () {
        if ($(".page").length > 1) {
            var nextItem;
            var page = self.getActivePage();
            var parent = page.parent();
            var pageId = Number(parent.attr("page-id"));
            if (pageId - 1 > 0)
                nextItem = pageId - 1;
            else
                nextItem = pageId + 1;


            var prev = $(".tx-page-frame[page-id='" + nextItem + "']");

            parent.remove();
            var pages = $(".page");
            for (var i = 0; i < pages.length; i++) {
                var target = pages[i];
                $(target).parent().attr("page-id", i + 1);
                $(target).removeClass("active-page");
            }
            self.setGuidLines();
            prev.find(".page").addClass("active-page");
            self.transferGuidLines();
            if (!_h.isNullOrEmpty(self.setting().defaultHeader()) && self.setting().defaultHeader() !== "")
                self.setting().changePages("defaultHeader");
            if (!_h.isNullOrEmpty(self.setting().defaultOddHeader()) && self.setting().defaultOddHeader() !== "")
                self.setting().changePages("defaultOddHeader");
            if (!_h.isNullOrEmpty(self.setting().defaultFooter()) && self.setting().defaultFooter() !== "")
                self.setting().changePages("defaultFooter");
            if (!_h.isNullOrEmpty(self.setting().defaultOddFooter()) && self.setting().defaultOddFooter() !== "")
                self.setting().changePages("defaultOddFooter");
            pages = $(".page");
            self.handlePageNumbers();
            for (var k = 0; k < pages.length; k++) {
                var target2 = pages[k];
                self.setting().refreshPartsSize(target2);
            }
        }
    };
    self.checkNullString = function (data) {
        return _h.isNullOrEmpty(data) ? "" : data;
    };
    self.isEvenNumber = function (number) {
        return number % 2 === 0;
    };
    self.disableInNumeration = ko.observable();
    self.pictureHeight = ko.observable();
    self.pictureWidth = ko.observable();
    self.pageNumber = ko.observable();
    self.pageOrientation = ko.observable("Portrait");
    self.disableHeader = ko.observable();
    self.disableFooter = ko.observable();
    self.disableDefaultHeader = ko.observable();
    self.disableDefaultFooter = ko.observable();
    self.disableMarginHeader = ko.observable();
    self.disableMarginFooter = ko.observable();
    self.marginRight = ko.observable();
    self.marginLeft = ko.observable();
    self.marginTop = ko.observable();
    self.marginBottom = ko.observable();
    self.activePageAnalyzer = function () {
        var page = self.getActivePage();
        var main = page.find(".main");
        self.toggleSuspendPageControls(true);
        var pageNumber = main.find(".page-number").attr("type");
        self.pageNumber(pageNumber);
        var disableInNumeration = main.attr("disable-innum") || false;
        self.disableInNumeration(disableInNumeration);
        var margins = self.getMargins(page);
        self.marginRight(margins.marginRight);
        self.marginLeft(margins.marginLeft);
        self.marginTop(margins.marginTop);
        self.marginBottom(margins.marginBottom);

        var disableMarginHeader = main.attr("disable-marginheader") === "true" ? true : false;
        var disableMarginFooter = main.attr("disable-marginfooter") === "true" ? true : false;

        self.disableMarginHeader(disableMarginHeader);
        self.disableMarginFooter(disableMarginFooter);
        var pageOrientation = page.attr("orientation") || "Portrait";
        self.pageOrientation(pageOrientation);
        var disableHeader = main.find(".mheader").length === 0;
        self.disableHeader(disableHeader);

        var disableFooter = main.find(".mfooter").length === 0;
        self.disableFooter(disableFooter);

        var disableDefaultHeader = main.attr("disable-defh") || false;
        self.disableDefaultHeader(disableDefaultHeader);

        var disableDefaultFooter = main.attr("disable-deff") || false;
        self.disableDefaultFooter(disableDefaultFooter);

        self.toggleSuspendPageControls(false);
    };
    self.getMargins = function (element) {
        var millimeters = {
            marginTop: 0,
            marginBottom: 0,
            marginRight: 0,
            marginLeft: 0
        };
        var header = element.find(".mheader");
        var footer = element.find(".mfooter");
        var content = element.find(".mcontent");
        var main = element.find(".main");
        var disableMarginHeader = main.attr("disable-marginheader") === "true" ? true : false;
        var disableMarginFooter = main.attr("disable-marginfooter") === "true" ? true : false;


        var paddingRight = self.getPaddingString(content.attr('style'), "padding-right");
        var paddingLeft = self.getPaddingString(content.attr('style'), "padding-left");
        var paddingTop;
        var paddingBottom;
        millimeters.marginRight = parseInt(paddingRight);
        millimeters.marginLeft = parseInt(paddingLeft);
        if (!disableMarginHeader) {
            if (header.length) {
                paddingTop = self.getPaddingString(header.attr('style'), "padding-top");
                millimeters.marginTop = parseInt(paddingTop);
            } else {
                paddingTop = self.getPaddingString(content.attr('style'), "padding-top");
                millimeters.marginTop = parseInt(paddingTop);
            }
        } else {
            paddingTop = self.getPaddingString(content.attr('style'), "padding-top");
            millimeters.marginTop = parseInt(paddingTop);
        }
        if (!disableMarginFooter) {
            if (footer.length) {
                paddingBottom = self.getPaddingString(footer.attr('style'), "padding-bottom");
                millimeters.marginBottom = parseInt(paddingBottom);
            } else {
                paddingBottom = self.getPaddingString(content.attr('style'), "padding-bottom");
                millimeters.marginBottom = parseInt(paddingBottom);
            }
        } else {
            paddingBottom = self.getPaddingString(content.attr('style'), "padding-bottom");
            millimeters.marginBottom = parseInt(paddingBottom);
        }
        return millimeters;
    };
    self.getPaddingString = function (style, item) {
        if (!_h.isNullOrEmpty(style) && style !== "" && style.indexOf("padding:") === -1) {
            var splits = style.split(";");
            var cleanStr;
            splits = _h.cleanArray(splits);
            if (_h.any(splits)) {
                for (var i = 0; i < splits.length; i++) {
                    var target = splits[i];
                    if (target.indexOf(item) !== -1) {
                        cleanStr = target.replace(item, "").replace(":", "").trim();
                    }
                }
                return cleanStr;
            }
            return "";
        }
        if (!_h.isNullOrEmpty(style) && style !== "" && style.indexOf("padding:") !== -1) {
            var padding = style.split('padding');
            for (var i = 0; i < padding.length; i++) {
                var targetpad = padding[i];
                if (!_h.isNullOrEmpty(targetpad) && targetpad !== "" && targetpad.startsWith(":")) {
                    var splits2 = targetpad.replace(":", "").split(";")[0];
                    splits2 = splits2.split(" ");
                    splits2 = _h.cleanArray(splits2);
                    switch (splits2.length) {
                        case 1:
                            return splits2[0];
                        case 2:
                            if (item === "padding-bottom" || item === "padding-top")
                                return splits2[0];

                            if (item === "padding-right" || item === "padding-left")
                                return splits2[1];
                        case 3:
                            if (item === "padding-top")
                                return splits2[0];

                            if (item === "padding-bottom")
                                return splits2[2];

                            if (item === "padding-right" || item === "padding-left")
                                return splits2[1];
                        case 4:
                            if (item === "padding-top")
                                return splits2[0];
                            if (item === "padding-right")
                                return splits2[1];

                            if (item === "padding-left")
                                return splits2[3];

                            if (item === "padding-bottom")
                                return splits2[2];
                    }
                }
            }
        }
        return "";
    };
    self.getLineHeight = function (element) {
        var val = undefined;
        var style = $(element).attr('style');
        if (style) {
            var padding = style.split('line-height');
            for (var i = 0; i < padding.length; i++) {
                var target = padding[i];
                if (!_h.isNullOrEmpty(target) && target !== "") {
                    var splits = target.replace(":", "").replace(";", "").replace("line-height", "");
                    val = parseFloat(splits.trim());
                }
            }
        }
        return val;
    };
    self.getFontSize = function (element) {
        var val = undefined;
        var style = $(element).attr('style');
        if (style) {
            var params = style.split('font-size');
            for (var i = 0; i < params.length; i++) {
                var target = params[i];
                if (!_h.isNullOrEmpty(target) && target !== "") {
                    var splits = target.replace(":", "").replace(";", "").replace("font-size", "");
                    val = parseFloat(splits.trim());
                }
            }
        }
        return val;
    };
    self.toggleCheckBox = function (name, e, parent) {
        self[name](!self[name]());
    };
    self.pictureHeightsub = self.pictureHeight.supsendableSubscribe(function (newValue) {
        if (newValue !== undefined && newValue !== null) {
            self.activeObject().css("height", newValue + "%");
        }
    });
    self.pictureWidthsub = self.pictureWidth.supsendableSubscribe(function (newValue) {
        if (newValue !== undefined && newValue !== null) {
            self.activeObject().css("width", newValue + "%");
        }
    });
    self.marginRightsub = self.marginRight.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue) && newValue >= 0) {
            var page = self.getActivePage();
            page.find(".mcontent").css('padding-right', newValue + "mm");
            if (!self.disableMarginHeader())
                page.find(".mheader").css('padding-right', newValue + "mm");
            else
                page.find(".mheader").css('padding-right', "");
            if (!self.disableMarginFooter())
                page.find(".mfooter").css('padding-right', newValue + "mm");
            else
                page.find(".mfooter").css('padding-right', "");
            self.refreshPartsSize();
        }
    });
    self.marginLeftsub = self.marginLeft.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue) && newValue >= 0) {
            var page = self.getActivePage();
            page.find(".mcontent").css('padding-left', newValue + "mm");
            if (!self.disableMarginHeader())
                page.find(".mheader").css('padding-left', newValue + "mm");
            else
                page.find(".mheader").css('padding-left', "");
            if (!self.disableMarginFooter())
                page.find(".mfooter").css('padding-left', newValue + "mm");
            else
                page.find(".mfooter").css('padding-left', "");
            self.refreshPartsSize();
        }
    });
    self.marginTopsub = self.marginTop.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue) && newValue >= 0) {
            var page = self.getActivePage();
            if (page.find(".mheader").length > 0) {
                if (!self.disableMarginHeader()) {
                    page.find(".mheader").css('padding-top', newValue + "mm");
                    page.find(".mcontent").css('padding-top', "");
                } else {
                    page.find(".mheader").css('padding-top', "");
                    page.find(".mcontent").css('padding-top', newValue + "mm");
                }

            } else {
                page.find(".mcontent").css('padding-top', newValue + "mm");
            }
            self.refreshPartsSize();
        }
    });
    self.marginBottomsub = self.marginBottom.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue) && newValue >= 0) {
            var page = self.getActivePage();
            if (page.find(".mfooter").length > 0) {
                if (!self.disableMarginFooter()) {
                    page.find(".mfooter").css('padding-bottom', newValue + "mm");
                    page.find(".mcontent").css('padding-bottom', "");
                } else {
                    page.find(".mfooter").css('padding-bottom', "");
                    page.find(".mcontent").css('padding-bottom', newValue + "mm");
                }

            } else {
                page.find(".mcontent").css('padding-bottom', newValue + "mm");
            }
            self.refreshPartsSize();
        }
    });
    self.disableMarginHeadersub = self.disableMarginHeader.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var page = self.getActivePage();
            if (newValue) {
                if (page.find(".mheader").length > 0) {
                    page.find(".mheader").css('padding-right', "");
                    page.find(".mheader").css('padding-left', "");
                    page.find(".mheader").css('padding-top', "");
                    page.find(".mcontent").css('padding-top', self.marginTop() + "mm");
                } else {
                    page.find(".mcontent").css('padding-top', "");
                }
                page.find(".main").attr("disable-marginheader", true);
            } else {
                if (page.find(".mheader").length > 0) {
                    page.find(".mheader").css('padding-right', self.marginRight() + "mm");
                    page.find(".mheader").css('padding-left', self.marginLeft() + "mm");
                    page.find(".mheader").css('padding-top', self.marginTop() + "mm");
                    page.find(".mcontent").css('padding-top', "");
                } else {
                    page.find(".mcontent").css('padding-top', self.marginTop() + "mm");
                }
                page.find(".main").removeAttr("disable-marginheader");
            }
        }
    });
    self.disableMarginFootersub = self.disableMarginFooter.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var page = self.getActivePage();
            if (newValue) {
                if (page.find(".mfooter").length > 0) {
                    page.find(".mfooter").css('padding-right', "");
                    page.find(".mfooter").css('padding-left', "");
                    page.find(".mfooter").css('padding-bottom', "");
                    page.find(".mcontent").css('padding-bottom', self.marginBottom() + "mm");
                } else {
                    page.find(".mcontent").css('padding-bottom', "");
                }
                page.find(".main").attr("disable-marginfooter", true);
            } else {
                if (page.find(".mfooter").length > 0) {
                    page.find(".mfooter").css('padding-right', self.marginRight() + "mm");
                    page.find(".mfooter").css('padding-left', self.marginLeft() + "mm");
                    page.find(".mfooter").css('padding-bottom', self.marginBottom() + "mm");
                    page.find(".mcontent").css('padding-bottom', "");
                } else {

                    page.find(".mcontent").css('padding-bottom', self.marginBottom() + "mm");
                }
                page.find(".main").removeAttr("disable-marginfooter");
            }
        }
    });
    self.disableHeadersub = self.disableHeader.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var page = self.getActivePage();
            var main = page.find(".main");
            if (newValue) {
                main.find(".mheader").remove();
                main.find(".header-area").remove();
                page.find(".mcontent").css('padding-top', self.marginTop() + "mm");
            }
            else {
                main.append("<div class='mheader' contenteditable='true'></div>");
                main.append("<div class='header-area hide'></div>");
                if (!self.disableMarginHeader()) {
                    page.find(".mheader").css('padding-right', self.marginRight() + "mm");
                    page.find(".mheader").css('padding-left', self.marginLeft() + "mm");
                    page.find(".mheader").css('padding-top', self.marginTop() + "mm");
                    page.find(".mcontent").css('padding-top', "");
                } else {
                    page.find(".mcontent").css('padding-top', self.marginTop() + "mm");

                }
            }
            self.refreshPartsSize();
        }
    });
    self.disableFootersub = self.disableFooter.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var page = self.getActivePage();
            var main = page.find(".main");
            if (newValue) {
                main.find(".mfooter").remove();
                main.find(".footer-area").remove();
                page.find(".mcontent").css('padding-bottom', self.marginBottom() + "mm");
            }
            else {
                main.append("<div class='mfooter' contenteditable='true'></div>");
                main.append("<div class='footer-area hide'></div>");
                if (!self.disableMarginFooter()) {
                    page.find(".mfooter").css('padding-right', self.marginRight() + "mm");
                    page.find(".mfooter").css('padding-left', self.marginLeft() + "mm");
                    page.find(".mfooter").css('padding-bottom', self.marginTop() + "mm");
                    page.find(".mcontent").css('padding-bottom', "");
                } else {
                    page.find(".mcontent").css('padding-bottom', self.marginTop() + "mm");
                }
            }
            self.refreshPartsSize();
        }
    });
    self.disableDefaultHeadersub = self.disableDefaultHeader.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var main = $(".active-page .main");
            if (newValue) {
                main.attr("disable-defh", true);
                main.find(".mheader").empty();
            }
            else {
                main.removeAttr("disable-defh");
            }
        }
    });
    self.disableDefaultFootersub = self.disableDefaultFooter.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var main = $(".active-page .main");
            if (newValue) {
                main.attr("disable-deff", true);
                main.find(".mfooter").empty();
            } else {
                main.removeAttr("disable-deff");
            }
        }
    });
    self.disableInNumerationsub = self.disableInNumeration.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var main = $(".active-page .main");
            if (newValue) {
                main.attr("disable-innum", true);
            } else {
                main.removeAttr("disable-innum");
            }
            self.handlePageNumbers();
        }
    });
    self.pageNumbersub = self.pageNumber.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var main = $(".active-page");
            main.find(".page-number").attr("type", newValue);
            self.handlePageNumbers();
        }
    });
    self.pageOrientationsub = self.pageOrientation.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var page = $(".active-page");
            page.attr("orientation", newValue);
            self.refreshPartsSize();
            self.handlePageNumbers();
            if (self.ruler) {
                self.ruler.api.destroy();
                self.ruler = undefined;
                el = document.getElementsByClassName('active-page');
                var pa = el[0].parentNode;
                if (pa) {
                    self.ruler = new ruler({
                        container: pa,
                        orientation: self.pageOrientation(),
                        size: "A4",
                        enableMouseTracking: true,
                        enableToolTip: true
                    });
                }
            }
        }
    });
    self.handlePageNumbers = function () {
        var pages = $(".page");
        var counter = self.magazine().startPageNumber();
        var realCounter = 1;
        for (var i = 0; i < pages.length; i++) {
            var target = $(pages[i]);
            var main = target.find(".main");
            var pageNumber = main.find(".page-number");
            var disableInNumeration = main.attr("disable-innum");
            if (_h.isNullOrEmpty(disableInNumeration)) {
                var type = Number(pageNumber.attr("type"));
                pageNumber.text(counter);
                var header = $(main).find(".mheader");
                var content = $(main).find(".mcontent");
                var restheight = _h.getHeight(header[0]) +
                    _h.getHeight(content[0]);
                switch (type) {
                    case 0:
                        pageNumber.css("display", "none");
                        break;
                    case 1:
                        pageNumber.css(
                            {
                                "display": "block",
                                "top": _h.pixelToMm(restheight - 30) + "mm",
                                "bottom": "initial",
                                "left": "7mm",
                                "right": "initial"
                            });
                        break;
                    case 2:
                        pageNumber.css(
                            {
                                "display": "block",
                                "top": _h.pixelToMm(restheight - 30) + "mm",
                                "bottom": "initial",
                                "right": "7mm",
                                "left": "initial"
                            });
                        break;
                    case 3:
                        pageNumber.css(
                            {
                                "display": "block",
                                "top": _h.pixelToMm(restheight - 30) + "mm",
                                "bottom": "initial",
                                "right": "48%",
                                "left": "initial"
                            });
                        break;
                    case 4:
                        pageNumber.css(
                            {
                                "display": "block",
                                "top": "initial",
                                "bottom": "5mm",
                                "left": "7mm",
                                "right": "initial"
                            });
                        break;
                    case 5:
                        pageNumber.css(
                            {
                                "display": "block",
                                "top": "initial",
                                "bottom": "5mm",
                                "left": "initial",
                                "right": "7mm"
                            });
                        break;
                    case 6:
                        pageNumber.css(
                            {
                                "display": "block",
                                "top": "initial",
                                "bottom": "5mm",
                                "left": "initial",
                                "right": "48%"
                            });
                        break;
                }
                counter++;
            } else {
                pageNumber.css("display", "none");
            }
            var pageNumberInfo = target.parent(".tx-page-frame").find(".page-number-info");
            pageNumberInfo.text(realCounter + " از " + pages.length + " صفحه ");
            realCounter++;
        }
    };
    self.refreshPartsSize = function () {
        var main = $(".active-page .main");
        main = main[0];
        var pageheight = main.getBoundingClientRect().height;
        var header = $(main).find(".mheader");
        var footer = $(main).find(".mfooter");
        var content = $(main).find(".mcontent");
        var restheight = _h.getHeight(header[0]) +
            _h.getHeight(footer[0]);
        var restTop = _h.getHeight(header[0]);
        content.css({
            'height': _h.pixelToMm(pageheight - restheight) + "mm",
            'top': _h.pixelToMm(restTop) + "mm"
        });
    };
    self.configDragFunctionality = function () {
        $(".template-item").draggable({
            cursor: "pointer",
            cursorAt: { top: 0, left: 60 },
            helper: function (event) {
                var nodeName = event.target.innerText.length > 15
                    ? event.target.innerText.substring(0, 12) + "..."
                    : event.target.innerText;
                var text =
                    "<div id=\"selected-label\" style=\"font-size: 13px;z-index: 100000;margin-left: 7px;\" class=\"label label-success pull-right\">" +
                    "<i class=\"fa fa-file-o\"></i>" +
                    "<span style=\"margin-right: 5px;\">" +
                    nodeName +
                    "</span></div>";
                return $(text);
            }
        });

        $(".chart-item").draggable({
            cursor: "pointer",
            cursorAt: { top: 0, left: 60 },
            helper: function (event) {
                var nodeName = event.target.title.length > 15
                    ? event.target.title.substring(0, 12) + "..."
                    : event.target.title;
                var text =
                    "<div id=\"selected-label\" style=\"font-size: 13px;z-index: 100000;margin-left: 7px;\" class=\"label label-success pull-right\">" +
                    "<i class=\"fa fa-bar-chart\"></i>" +
                    "<span style=\"margin-right: 5px;\">" +
                    nodeName +
                    "</span></div>";
                return $(text);
            }
        });
    };
    self.configDropFunctionality = function () {
        $(".page .mcontent").droppable({
            drop: function (event, ui) {
                if ($(ui.helper).hasClass("table-templateId") || $(ui.helper).hasClass("header-area") || $(ui.helper).hasClass("footer-area"))
                    return;
                var contentTag = $(event.target);
                var value = $(ui.draggable[0]).attr("data-value");
                var title = $(ui.draggable[0]).attr("data-original-title");
                var id = $(ui.draggable[0]).attr("data-id");
                var type = $(ui.draggable[0]).attr("data-type");
                switch (type) {
                    case "chart":
                        self.getChartPicture(id, value);
                        break;
                    case "template":
                        self.GetTableTemplateHtml(id, function (res) {
                            if (!_h.isNullOrEmpty(res.data)) {
                                var p = "<div class='table-templateId' data-id=" +
                                    id +
                                    " contenteditable='false'><div class='iframe-shadow' contenteditable='false'></div>";
                                p += "<iframe id='tabletemplate-box'>" +
                                    "</iframe>";
                                p += "</div><br>";
                                var hasSelectHtml = self.hasSelectHtml("mcontent");
                                if (hasSelectHtml)
                                    document.execCommand('insertHTML', false, p);
                                else
                                    contentTag.append(p);
                                var div = $("[data-id=" + id + "]");
                                div.attr("title", res.title);
                                var iframe = div.find("iframe").contents();
                                if (iframe) {
                                    iframe.find("head")
                                        .append("<link href='/App/src/styles/tabletemplate-meditor.css' rel='stylesheet'/>");
                                    iframe.find("body").append(res.data);
                                    self.resizeTableTemplateFrame(div);
                                }
                            }
                        });
                        break;
                }
            }
        });
    };
    self.hasSelectHtml = function (domain) {
        var selObj = document.getSelection();
        var base = $(selObj.baseNode).closest(".mpart");
        return base.hasClass(domain);
    };
    self.downloadModel = ko.observable();
    self.toPdfBtn = function () {
        var model = {};
        var data = clientStorage.getSetting("MagazinePdfPage");
        if (!_h.isEmpty(data)) {
            model = JSON.parse(data);
        }
        var model = new MagazineDownloadFile(self, model);
        self.downloadModel(model);
        _h.kocnx().openForm(model);
    };
    self.toPdfSaveSetting = function () {
        clientStorage.setSetting(
            [{
                key: "MagazinePdfPage", value: JSON.stringify({
                    displayType: self.downloadModel().displayType(),
                    amountType: self.downloadModel().amountType()
                })
            }]
        );
        var text = _h.getApiMessage("MagazinePdfPageSaveMessage");
        _h.successToast(text);
    }
    self.toPdf = function () {
        var page = self.getActivePage()[0].outerHTML;
        var outHtml = self.getPageOutputHtml(page);
        var model = {
            controllerName: 7,
            inputData: {
                id: self.magazine().id(),
                content: outHtml,
                displayType: self.downloadModel().displayType(),
                amountType: self.downloadModel().amountType()
            }
        };
       
        _h.kocnx().createPdf(model);
        _h.kocnx().closeForm();

    };
    self.getPageOutputHtml = function (html) {
        var outHhtml = "<!DOCTYPE html><html><head>";
        outHhtml += "<link href='" +
            location.protocol +
            "//" +
            location.host +
            "/App/src/styles/magazine-page.css' rel='stylesheet'/>";
        outHhtml += "</head><body>";
        var page = $(html);
        var pageSize = page.attr("size");
        var pageOrientation = page.attr("orientation");
        if (pageOrientation === "Landscape") {
            switch (pageSize) {
                case "A4":
                    page.css({
                        "width": "210mm",
                        "height": "297mm"
                    });
                    page.find(".main").css({
                        "transform": "rotate(90deg)",
                        "width": "297mm",
                        "height": "210mm",
                        "right": "-164px",
                        "bottom": "-164px"
                    });
                    break;
                case "A3":

                    break;
            }
        }
        page.find(".mheader").removeAttr("contenteditable");
        page.find(".mcontent").removeAttr("contenteditable");
        page.find(".mfooter").removeAttr("contenteditable");
        page.find("img").css({
            "max-height": "",
            "max-width": "",
        });
        page.find(".header-area").remove();
        page.find(".footer-area").remove();
        outHhtml += page[0].outerHTML.trim();
        outHhtml += "</body></html>";
        return outHhtml;
    };
    self.toggleRight = function () {
        self.wideRight(!self.wideRight());
    };
    self.loadPageTableTemplates = function (page) {
        var templates = page.find(".table-templateId");
        var target;
        if (_h.any(templates)) {
            for (var i = 0; i < templates.length; i++) {
                target = $(templates[i]);
                var id = Number(target.attr("data-id"));

                self.loadPageTableTemplate(target, page);
            }
        }
        var charts = page.find(".chart-image").filter(function (i, a) {
            if ($(a).attr("src") && $(a).attr("src").endsWith("f//Z"))
                return true;
            return false;
        });
        if (_h.any(charts)) {
            for (var j = 0; j < charts.length; j++) {
                target = $(charts[j]);
                var id = target.attr("template-id");
                var value = target.attr("chart-id");
                self.getChartPicture(id, value, target);
            }
        }
    };
    self.loadPageTableTemplate = function (target) {
        var id = target.attr("data-id");
        if (target.find(".iframe-shadow").length === 0) {
            ApiService.request(
                {
                    url: "/api/magazine/gettemplatepreview",
                    data: {
                        magazineId: self.magazine().id(),
                        tableTemplateId: id
                    },
                    success: function (res) {
                        if (!_h.isNullOrEmpty(res)) {
                            var p = "<div class='iframe-shadow' contenteditable='false'></div>";
                            p += "<iframe id='tabletemplate-box'>" +
                                "</iframe>";
                            var zoom;
                            var div = target;
                            div.empty();
                            try {
                                zoom = parseFloat(div.attr("data-zoom")) || 1;
                            } catch (e) {
                            }
                            div.append(p);
                            div.attr("contenteditable", false);
                            var iframe = $(div[0]).find("iframe").contents();
                            if (iframe.length) {
                                iframe.find("head")
                                    .append("<link href='/App/src/styles/tabletemplate-meditor.css' rel='stylesheet'/>");
                                var body = iframe.find("body")[0];
                                setTimeout(function () {
                                    $(body).append(res.data);
                                    var table = iframe.find("body table");
                                    var newWidth, newHeight;
                                    var width = table[0].scrollWidth;
                                    var height = table[0].scrollHeight;
                                    if (zoom !== 1) {
                                        newWidth = (width * (zoom * 100)) / 100;
                                        newHeight = (height * (zoom * 100)) / 100;
                                        table.css("zoom", zoom);
                                    } else {
                                        newWidth = width;
                                        newHeight = height;
                                    }
                                    div.css({
                                        'height': _h.pixelToMm(newHeight) + "mm",
                                        'width': _h.pixelToMm(newWidth) + "mm"
                                    });
                                    iframe.find("html").css({
                                        'height': _h.pixelToMm(newHeight) + "mm",
                                        'width': _h.pixelToMm(newWidth) + "mm"
                                    });
                                    div.attr("title", res.title);
                                    div.find(".iframe-shadow").css({
                                        'height': _h.pixelToMm(newHeight) + "mm",
                                        'width': _h.pixelToMm(newWidth) + "mm"
                                    });
                                    div.find("iframe").css({
                                        'height': _h.pixelToMm(newHeight) + "mm",
                                        'width': _h.pixelToMm(newWidth) + "mm"
                                    });
                                },
                                    200);
                            }
                        }
                    },
                    error: function (data) {
                    }
                });
        }
    };
    self.resizeTableTemplateFrame = function (div) {
        var iframe = div.find("iframe").contents();
        if (iframe) {
            var table = iframe.find("body table");
            var zoom = parseFloat(table.css("zoom")) || 1;
            if (table.length) {
                setTimeout(function () {
                    var newWidth, newHeight;
                    var width = table[0].scrollWidth;
                    var height = table[0].scrollHeight;
                    if (zoom !== 1) {
                        newWidth = (width * (zoom * 100)) / 100;
                        newHeight = (height * (zoom * 100)) / 100;

                    } else {
                        newWidth = width;
                        newHeight = height;
                    }
                    div.css({
                        'height': _h.pixelToMm(newHeight) + "mm",
                        'width': _h.pixelToMm(newWidth) + "mm"
                    });
                    iframe.find("html").css({
                        'height': _h.pixelToMm(newHeight) + "mm",
                        'width': _h.pixelToMm(newWidth) + "mm"
                    });
                    div.find(".iframe-shadow").css({
                        'height': _h.pixelToMm(newHeight) + "mm",
                        'width': _h.pixelToMm(newWidth) + "mm"
                    });
                    div.find("iframe").css({
                        'height': _h.pixelToMm(newHeight) + "mm",
                        'width': _h.pixelToMm(newWidth) + "mm"
                    });
                },
                    200);
            }
        }
    };
    self.getRangeHtml = function () {
        var outArray = [];
        var sel = rangy.getSelection();
        var range = sel.rangeCount ? sel.getRangeAt(0) : null;
        if (range) {
            range.splitBoundaries();
            var textNodes = range.getNodes([3]);
            if (textNodes.length) {
                var textNode;
                var lastPTag;
                var pTag, parent, addTag = false;
                for (var i = 0, len = textNodes.length; i < len; ++i) {
                    textNode = textNodes[i];
                    parent = textNode.parentNode;
                    pTag = self.findUpTag(parent, "p");
                    if (!lastPTag)
                        lastPTag = pTag;
                    var el;
                    if (pTag.outerHTML !== lastPTag.outerHTML || !outArray.length) {
                        el = document.createElement("p");
                        $(el).attr("style", $(pTag).attr("style"));
                        addTag = true;
                    } else {
                        el = outArray[outArray.length - 1];
                        addTag = false;
                    }
                    var html;
                    var liTag = self.findUpTag(parent, "li");
                    if (liTag)
                        parent = liTag;

                    switch (parent.nodeName.toLowerCase()) {
                        case "span":
                            html = $(parent.outerHTML);
                            $(html).text(textNode.textContent);
                            var finalSpan = html[0].outerHTML;
                            $(el).append(finalSpan);
                            break;
                        case "p":
                            el.innerHTML = parent.innerHTML;
                            break;
                        case "li":
                            var listTagName = "ul";
                            var listTag = self.findUpTag(parent, "ul");
                            if (listTag === null) {
                                listTag = self.findUpTag(parent, "ol");
                                listTagName = "ol";
                            }
                            var newListTag;
                            if (!$(el).find(listTagName + ":last").length) {
                                newListTag = document.createElement(listTagName);
                            } else {
                                newListTag = $(el).find(listTagName + ":last");
                            }
                            html = $(parent.outerHTML);
                            $(html).text(textNode.textContent);
                            var finalLi = html[0].outerHTML;
                            $(newListTag).append(finalLi);
                            $(el).append(newListTag);
                            break;
                    }
                    if (addTag)
                        outArray.push(el);
                }
            }
        }
        return outArray;
    };
    self.copyData = function () {
        var sel = rangy.getSelection();
        var range = sel.rangeCount ? sel.getRangeAt(0) : null;
        if (range) {
            range.splitBoundaries();
            var textNodes = range.getNodes([3]);
            if (textNodes.length) {
                var textNode;
                for (var i = 0, len = textNodes.length; i < len; ++i) {
                    textNode = textNodes[i];
                    var parent = textNode.parentNode;
                    var pTag = self.findUpTag(parent, "p");
                    var el = document.createElement("p");
                    //div.style.cssText = document.defaultView.getComputedStyle(p, "").cssText;
                }
            }
        }
    };
    self.findUpTag = function (el, tag) {
        if (el.tagName.toLowerCase() === tag)
            return el;
        try {
            while (el.parentNode) {
                el = el.parentNode;
                if (el.tagName.toLowerCase() === tag)
                    return el;
            }
            return null;
        } catch (e) {
            return null;
        }
    };
    self.getActiveEd = function () {
        if ($(".active-ed").length)
            return $(".active-ed");
    };
    self.fullScreen = ko.observable(false);
    self.toggleFullScreen = function () {
        self.fullScreen(!self.fullScreen());
        if (self.fullScreen()) {
            $("body").css("overflow", "hidden");
            $(".footer").css("display", "none");
        } else {
            $("body").css("overflow", "");
            $(".footer").css("display", "block");
        }
    };
    self.saveAsDefault = function () {
        var textColor = $(".rich-texteditor").find(".textcolorVal")[0].style.backgroundColor;
        var backColor = $(".rich-texteditor").find(".backcolorVal")[0].style.backgroundColor;
        var alignRight = $(".rich-texteditor").find(".alignrightVal.selected-tools").length > 0;
        var alignLeft = $(".rich-texteditor").find(".alignleftVal.selected-tools").length > 0;
        var alignCenter = $(".rich-texteditor").find(".aligncenterVal.selected-tools").length > 0;
        var linespace = $(".linespaceVal").val();
        var align;
        if (!alignRight && !alignLeft && !alignCenter) {
            align = undefined;
        } else {
            if (alignRight)
                align = "right";
            if (alignLeft)
                align = "left";
            if (alignCenter)
                align = "center";
        }
        var fontData = $(".rich-texteditor").find(".fnt-selector").fontSelector("getValues");
        clientStorage.setSetting(
            [{
                key: "DefaultMagazineStyle", value: JSON.stringify({
                    textColor: textColor,
                    backColor: backColor,
                    linespace: linespace,
                    textFontSize: fontData[1],
                    textFontFamily: fontData[0],
                    align: align
                })
            }]
        );
    }
    self.getDefault = function () {
        var model = {};
        var data = clientStorage.getSetting("DefaultMagazineStyle");
        if (!_h.isEmpty(data)) {
            model = JSON.parse(data);
        } else {
            return {
                textColor: "",
                backColor: "",
                linespace: "1",
                textFontSize: "12px",
                textFontFamily: "Nazanin",
                align: undefined
            };
        }
        return model;
    }
}

export class PageSetting extends BaseSecondaryForm {
    constructor(parentForm) {
        super(parentForm, [
            { name: "pageSize", type: "ob", val: "A4" },
            { name: "pageNumber", type: "ob", val: 0 },
            { name: "marginLeft", type: "ob", val: 2 },
            { name: "marginTop", type: "ob", val: 2 },
            { name: "marginBottom", type: "ob", val: 2 },
            { name: "marginRight", type: "ob", val: 2 },
            { name: "defaultHeader", type: "ob", val: "" },
            { name: "defaultFooter", type: "ob", val: "" },
            { name: "defaultOddHeader", type: "ob", val: "" },
            { name: "defaultOddFooter", type: "ob", val: "" },
        ], "editCaption");
        this.disableUpdate = false;
        this.pageNumber.subscribe(function (newValue) {
            if (!_h.isNullOrEmpty(newValue) && !this.disableUpdate) {
                this.changePages("pageNumber");
            }
        }.bind(this));
        this.marginRight.subscribe(function (newValue) {
            if (!_h.isNullOrEmpty(newValue) && !this.disableUpdate) {
                this.changePages("marginRight");
            }
        }.bind(this));
        this.marginLeft.subscribe(function (newValue) {
            if (!_h.isNullOrEmpty(newValue) && !this.disableUpdate) {
                this.changePages("marginLeft");
            }
        }.bind(this));
        this.marginTop.subscribe(function (newValue) {
            if (!_h.isNullOrEmpty(newValue) && !this.disableUpdate) {
                this.changePages("marginTop");
            }
        }.bind(this));
        this.marginTop.subscribe(function (newValue) {
            if (!_h.isNullOrEmpty(newValue) && !this.disableUpdate) {
                this.changePages("marginTop");
            }
        }.bind(this));
    }
    fillModel(model) {
        this.disableUpdate = true;
        _autoMapper.fillModel(this, model)
        this.disableUpdate = false;
    };
    removeContent(parentModel, param, value) {
        var pages = $(".page");
        for (var i = 0; i < pages.length; i++) {
            var target = $(pages[i]);
            var main = target.find(".main");
            var parent = target.parent();
            var pageId = Number(parent.attr("page-id"));
            var isEven = this.parentVM.isEvenNumber(pageId);
            var disableHeader,
                disableDefaultHeader,
                header,
                disableFooter,
                disableDefaultFooter,
                footer;
            switch (param) {
                case "defaultHeader":
                    disableHeader = main.find(".mheader").length === 0;
                    disableDefaultHeader = main.attr("disable-defh") || false;
                    if (!disableHeader && !disableDefaultHeader) {
                        header = main.find(".mheader");
                        if (isEven) {
                            header.empty();
                            header.remove("default-header");
                        }
                    }
                    break;
                case "defaultOddHeader":
                    disableHeader = main.find(".mheader").length === 0;
                    disableDefaultHeader = main.attr("disable-defh") || false;
                    if (!disableHeader && !disableDefaultHeader) {
                        header = main.find(".mheader");
                        if (!isEven) {
                            header.empty();
                            header.remove("default-odd-header");
                        }
                    }
                    break;
                case "defaultFooter":
                    disableFooter = main.find(".mfooter").length === 0;
                    disableDefaultFooter = main.attr("disable-deff") || false;
                    if (!disableFooter && !disableDefaultFooter) {
                        footer = main.find(".mfooter");
                        if (isEven) {
                            footer.empty();
                            footer.remove("default-footer");
                        }
                    }
                    break;
                case "defaultOddFooter":
                    disableFooter = main.find(".mfooter").length === 0;
                    disableDefaultFooter = main.attr("disable-deff") || false;
                    if (!disableFooter && !disableDefaultFooter) {
                        footer = main.find(".mfooter");
                        if (!isEven) {
                            footer.empty();
                            footer.remove("default-odd-footer");
                        }
                    }
                    break;
            }
            this.refreshPartsSize(target);
        }
        this[param]("");
    };
    changePages(param) {
        var pages = $(".page");
        for (var i = 0; i < pages.length; i++) {
            var target = $(pages[i]);
            var main = target.find(".main");
            var parent = target.parent();
            var pageId = Number(parent.attr("page-id"));
            var isEven = this.parentVM.isEvenNumber(pageId);
            var disableHeader,
                disableDefaultHeader,
                header,
                disableFooter,
                disableDefaultFooter,
                footer,
                disableMarginHeader,
                disableMarginFooter;
            disableHeader = main.find(".mheader").length === 0;
            disableMarginHeader = main.attr("disable-marginheader") || false;
            disableMarginFooter = main.attr("disable-marginfooter") || false;
            switch (param) {
                case "defaultHeader":
                    disableHeader = main.find(".mheader").length === 0;
                    disableDefaultHeader = main.attr("disable-defh") || false;
                    if (!disableHeader && !disableDefaultHeader) {
                        header = main.find(".mheader");
                        if (isEven)
                            header.replaceWith(this.defaultHeader());
                    }
                    break;
                case "defaultOddHeader":
                    disableHeader = main.find(".mheader").length === 0;
                    disableDefaultHeader = main.attr("disable-defh") || false;
                    if (!disableHeader && !disableDefaultHeader) {
                        header = main.find(".mheader");
                        if (!isEven)
                            header.replaceWith(this.defaultOddHeader());
                    }
                    break;
                case "defaultFooter":
                    disableFooter = main.find(".mfooter").length === 0;
                    disableDefaultFooter = main.attr("disable-deff") || false;
                    if (!disableFooter && !disableDefaultFooter) {
                        footer = main.find(".mfooter");
                        if (isEven)
                            footer.replaceWith(this.defaultFooter());
                    }
                    break;
                case "defaultOddFooter":
                    disableFooter = main.find(".mfooter").length === 0;
                    disableDefaultFooter = main.attr("disable-deff") || false;
                    if (!disableFooter && !disableDefaultFooter) {
                        footer = main.find(".mfooter");
                        if (!isEven)
                            footer.replaceWith(this.defaultOddFooter());
                    }
                    break;
                case "pageNumber":
                    var pageNumber = main.find(".page-number");
                    var disableInNumeration = main.attr("disable-innum");
                    if (_h.isNullOrEmpty(disableInNumeration))
                        pageNumber.attr("type", this.pageNumber());
                    break;
                case "pageSize":
                    break;
                case "marginRight":
                    main.find(".mcontent").css('padding-right', this.marginRight() + "mm");
                    if (!disableMarginHeader) {
                        main.find(".mheader").css('padding-right', this.marginRight() + "mm");
                    } else
                        main.find(".mheader").css('padding-right', "");
                    if (!disableMarginFooter)
                        main.find(".mfooter").css('padding-right', this.marginRight() + "mm");
                    else
                        main.find(".mfooter").css('padding-right', "");
                    break;
                case "marginLeft":
                    main.find(".mcontent").css('padding-left', this.marginLeft() + "mm");
                    if (!disableMarginHeader)
                        main.find(".mheader").css('padding-left', this.marginLeft() + "mm");
                    else
                        main.find(".mheader").css('padding-left', "");
                    if (!disableMarginFooter)
                        main.find(".mfooter").css('padding-left', this.marginLeft() + "mm");
                    else
                        main.find(".mfooter").css('padding-left', "");
                    break;
                case "marginTop":
                    if (main.find(".mheader").length > 0) {
                        if (!disableMarginHeader) {
                            main.find(".mheader").css('padding-top', this.marginTop() + "mm");
                            main.find(".mcontent").css('padding-top', "");
                        } else {
                            main.find(".mheader").css('padding-top', "");
                            main.find(".mcontent").css('padding-top', this.marginTop() + "mm");
                        }
                    } else {
                        main.find(".mcontent").css('padding-top', this.marginTop() + "mm");
                    }
                    break;
                case "marginBottom":
                    if (main.find(".mfooter").length > 0) {
                        if (!disableMarginFooter) {
                            main.find(".mfooter").css('padding-bottom', this.marginBottom() + "mm");
                            main.find(".mcontent").css('padding-bottom', "");
                        } else {
                            main.find(".mfooter").css('padding-bottom', "");
                            main.find(".mcontent").css('padding-bottom', this.marginBottom() + "mm");
                        }
                    } else {
                        main.find(".mfooter").css('padding-bottom', "");
                        main.find(".mcontent").css('padding-bottom', this.marginBottom() + "mm");
                    }
                    break;
            }
        }
        if (param.startsWith("margin") || param === "pageNumber") {
            this.parentVM.handlePageNumbers();
        }
    };
    refreshPartsSize(target) {
        var main = $(target).find(".main");
        main = main[0];
        var pageheight = main.getBoundingClientRect().height;
        var pageWidth = main.getBoundingClientRect().width;
        var header = $(main).find(".mheader");
        var footer = $(main).find(".mfooter");
        var content = $(main).find(".mcontent");
        var restheight = _h.getHeight(header[0]) + _h.getHeight(footer[0]);
        var restTop = _h.getHeight(header[0]);
        content.css({
            'height': _h.pixelToMm(pageheight - restheight) + "mm",
            'top': _h.pixelToMm(restTop) + "mm",
            'width': _h.pixelToMm(pageWidth) + "mm"
        });
    };
    toServer() {
        return {
            pageSize: this.pageSize(),
            pageNumber: this.pageNumber(),
            marginRight: this.marginRight(),
            marginLeft: this.marginLeft(),
            marginTop: this.marginTop(),
            marginBottom: this.marginBottom(),
            defaultHeader: this.defaultHeader() || "",
            defaultFooter: this.defaultFooter() || "",
            defaultOddHeader: this.defaultOddHeader() || "",
            defaultOddFooter: this.defaultOddFooter() || ""
        };
    };
}
const selector = ".mheader, .mfooter, .mcontent";
$(document).on('click', selector, function (e) {
    if (!$(e.currentTarget).hasClass("active-ed")) {
        $(".mpart").removeClass("active-ed");
        $(e.currentTarget).addClass("active-ed");
    }
    var parent = $(e.target).parent();
    _h.kocnx().mgvm().designSelectedModel().setActivePage($(e.currentTarget));
    if (($(e.target).hasClass("mpart") === false && ($(e.target).has("img").length > 0 || e.target.nodeName === "IMG")) ||
        (parent.hasClass("table-templateId") && !parent.hasClass("ui-draggable"))) {
        var context = _h.kocnx().mgvm().designSelectedModel();
        var target = $(e.target);
        var tar, tagHeight, nextP, prevP;
        if (target.nodeName !== "P")
            target = context.findUpTag(target.get(0), "p");
        var templateTag = parent;
        var imgTag = $(target).has("img");
        var offset = e.offsetY;
        if (imgTag.length > 0) {
            tagHeight = imgTag.height();
            if (offset > tagHeight / 2) {
                nextP = $(target).next();
                if (nextP && nextP.length > 0 && nextP.get(0).nodeName === "P") {
                    if ((_h.isNullOrEmpty(nextP.text()) || nextP.text() === "") && !nextP.has("br").length > 0)
                        nextP.append("<br>");
                    context.fixCursorLocation(nextP);
                } else {
                    tar = $("<p><br></p>").insertAfter($(target));
                    context.fixCursorLocation(tar);
                }
            } else {
                prevP = imgTag.prev();
                if (prevP && prevP.length > 0 && prevP.get(0).nodeName === "P") {
                    context.fixCursorLocation(prevP);
                } else {
                    tar = $("<p><br></p>").insertBefore($(target));
                    context.fixCursorLocation(tar);
                }
            }
        } else if (templateTag.length > 0) {
            tagHeight = templateTag.height();
            if (offset > tagHeight / 2) {
                nextP = templateTag.next();
                if (nextP && nextP.length > 0 && nextP.get(0).nodeName === "P") {
                    if ((_h.isNullOrEmpty(nextP.text()) || nextP.text() === "") && !nextP.has("br").length > 0)
                        nextP.append("<br>");
                    context.fixCursorLocation(nextP);
                } else {
                    tar = $("<p><br></p>").insertAfter(parent);
                    context.fixCursorLocation(tar);
                }
            } else {
                prevP = templateTag.prev();
                if (prevP && prevP.length > 0 && prevP.get(0).nodeName === "P") {
                    context.fixCursorLocation(prevP);
                } else {
                    tar = $("<p><br></p>").insertBefore(parent);
                    context.fixCursorLocation(tar);
                }
            }
        }
    }

});
$(document).on('cut', selector, function (e) {
    e.preventDefault();
    var array = _h.kocnx().mgvm().designSelectedModel().getRangeHtml();
    var html = "";
    if (array.length)
        for (var i = 0; i < array.length; i++) {
            var target = $(array[i]);
            html += target[0].outerHTML;
        }

    if (html) {
        e.originalEvent.clipboardData.clearData('application/json');
        e.originalEvent.clipboardData.setData('application/json', JSON.stringify({ content: html }));
        var sel = rangy.getSelection();
        var range = sel.rangeCount ? sel.getRangeAt(0) : null;
        range.deleteContents();
        setTimeout(function () {
            _h.kocnx().mgvm().designSelectedModel().htmlContentCleaner();
        }, 0);
    }
});
$(document).on('copy', selector, function (e) {
    e.preventDefault();
    var array = _h.kocnx().mgvm().designSelectedModel().getRangeHtml();
    var html = "";
    if (array.length)
        for (var i = 0; i < array.length; i++) {
            var target = $(array[i]);
            html += target[0].outerHTML;
        }
    if (html) {
        e.originalEvent.clipboardData.clearData('application/json');
        e.originalEvent.clipboardData.setData('text/html', html);
        e.originalEvent.clipboardData.setData('text/plain', html);
        e.originalEvent.clipboardData.setData('application/json', JSON.stringify({ content: html }));
    }
});
$(document).on('paste', selector, function (e) {
    e.preventDefault();
    if (window.getSelection && window.getSelection().deleteFromDocument) {
        window.getSelection().deleteFromDocument();
    }
    var data;
    var types = (e.originalEvent || e).clipboardData.types;
    if (types.indexOf("text/rtf") !== -1) {
        data = (e.originalEvent || e).clipboardData.getData('text/html');
        data = pasteDataFormater.getMicrosoftWordData(data);
        if (data)
            document.execCommand("insertHTML", false, data);
    }
    else if (types.indexOf("application/json") !== -1) {
        try {
            data = (e.originalEvent || e).clipboardData.getData('application/json');
            data = JSON.parse(data);
        } catch (e) {
            data = "";
        }
        if (!_h.isNullOrEmpty(data) && data !== "")
            document.execCommand("insertHTML", false, data.content);
    } else if (types.indexOf("text/html") !== -1) {
        data = (e.originalEvent || e).clipboardData.getData('text/html');
        data = pasteDataFormater.getHtmlData(data);
        if (data)
            document.execCommand("insertHTML", false, data);
    } else if (types.indexOf("image/png") !== -1 ||
        types.indexOf("image/jpeg") !== -1 ||
        types.indexOf("image/jpg") !== -1) {
        var items = (e.originalEvent || e).clipboardData.items,
            reader;
        if (items && items.length)
            for (var i = items.length - 1; i >= 0; i -= 1) {
                if (items[i].type.match(/^image\//)) {
                    reader = new FileReader();
                    reader.onloadend = function (event) {
                        var imgString = $('<img/>').attr("src", event.target.result)
                            .css({
                                "max-width": "100%",
                                "max-height": "100%"
                            }).addClass('mimage').prop('outerHTML');
                        var p = "<p style='text-align: center;'>" + imgString + "<p/>";
                        document.execCommand('insertHTML', false, p);
                    };
                    reader.readAsDataURL(items[i].getAsFile());
                }
            }
    } else {
        data = (e.originalEvent || e).clipboardData.getData('text/plain');
        if (data)
            document.execCommand("insertText", false, data);
    }
    setTimeout(function () {
        _h.kocnx().mgvm().designSelectedModel().htmlContentCleaner();
    }, 0);
    return false;
});
$(document).on('dblclick', ".tx-page-frame", function (e) {
    var currentTarget = $(this).find(".page");
    var header = currentTarget.find(".mheader");
    var footer = currentTarget.find(".mfooter");
    var headerArea = currentTarget.find(".header-area");
    var footerArea = currentTarget.find(".footer-area");
    var hasRuller = $(this).find(".rul_wrapper").length > 0;
    if (($(e.target).hasClass("tx-page-frame") && !hasRuller) || hasRuller) {
        if (headerArea.hasClass("hide")) {
            if (_h.isNullOrEmpty(header[0])) {
                $(headerArea[0]).addClass("hide");
                return;
            }
            $(headerArea[0]).css('top', _h.pixelToMm(header[0].getBoundingClientRect().height) + "mm");
            $(headerArea[0]).removeClass("hide");
            $(headerArea[0]).draggable({
                axis: "y",
                stop: function (event, ui) {
                    $(event.target).css("left", 0);
                    var newHeight = $(headerArea[0]).css("top").replace("px", "");
                    $(header[0]).css("height", _h.pixelToMm(Number(newHeight)) + "mm");
                    _h.kocnx().mgvm().designSelectedModel().refreshPartsSize();
                }
            });
        }
        else {
            $(headerArea[0]).addClass("hide");
        }
        if (footerArea.hasClass("hide")) {
            if (_h.isNullOrEmpty(footer[0])) {
                $(footerArea[0]).addClass("hide");
                return;

            }
            var main = $(".active-page .main");
            main = main[0];
            var pageheight = main.getBoundingClientRect().height;
            $(footerArea[0]).removeClass("hide");
            var footerHeight = footer[0].getBoundingClientRect().height;
            $(footerArea[0]).css('top', _h.pixelToMm(pageheight - footerHeight) + "mm");

            $(footerArea[0]).draggable({
                axis: "y",
                stop: function (event, ui) {
                    var main = $(".active-page .main");
                    main = main[0];
                    var pageheight = main.getBoundingClientRect().height;
                    $(event.target).css("left", 0);
                    var newHeight = $(footerArea[0]).css("top").replace("px", "");
                    $(footer[0]).css("height", _h.pixelToMm(Number(pageheight - newHeight)) + "mm");
                    _h.kocnx().mgvm().designSelectedModel().refreshPartsSize();
                }
            });
        }
        else {
            $(footerArea[0]).addClass("hide");
        }
    }
});

export class TextTemplate extends BaseInnerModel {
    constructor(model) {
        super(model);
    }
}
export class TextTemplateForm extends BaseSecondaryForm {
    constructor(viewModel, model) {
        super(viewModel, [
            { name: "id", type: "ob", val: model.id },
            { name: "title", type: "ob" },
            { name: "content", type: "ob", val: model.content },

        ], "textTemplateFormCation");
        this.setValidationObject();
        this.createForm();
    }
    setValidationObject() {
        var self = this;
        self.validationObject = ko.validatedObservable({
            title: self.title.extend({
                required: true,
                minLength: 3,
                maxLength: 32
            })
        });
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'txb', val: this.title }, null, true),
            this.createLine({ t: 'tm', templateName: 'texttemplate-form-t' }, undefined, true, 30, 0),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: "custom", resText: 'editFormBtn', vis: true, click: this.parentVM.saveTextTemplate },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export class TableTemplateSelect extends BaseInnerModel {
    constructor(model) {
        super(model);
    }
}
export function TableTemplateSelectViewModel(parentForm) {
    var self = this;
    self.parentForm = ko.observable(parentForm);
    self.magazineId = ko.observable();
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.iconSize("icon-image-small");
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "TableTemplateSelect",
        apiService: {
            actionList: ["filterby"]
        },
        buttons: [
            { name: 'refresh', access: false, cMenu: false }
        ],
        sortDirection: "Ascending",
        sortProperty: "priority",
        context: self,
        cols: tabletemplateselectModelRes,
        getList: false,
        selectRow: false,
        saveState: false,
        tableStyle: "table-layout: fixed;font-size:11px;",
        isMultiSelectRows: false,
        contextMenu: false
    }));
    self.getRecords = function () {
        var filterModel = {
            pageNumber: self.pageNumber(),
            pageSize: self.pageSize(),
            searchKey: self.searchKey(),
            sortProperty: "priority",
            sortDirection: self.sortDirection(),
            magazineId: self.magazineId()
        };
        self.apiService.request(
            {
                name: "/api/tabletemplate/gettemplatesformagazine",
                data: filterModel,
                success: function (data) {
                    self.records.removeAll();
                    if (!_h.isNullOrEmpty(data)) {
                        if (_h.any(data.list))
                            for (var j = 0; j < data.list.length; j++) {
                                var target = data.list[j];
                                var record = new TableTemplateSelect(target);
                                self.records.push(record);
                            }
                        self.total(data.total);
                        self.parentForm().configDragFunctionality();
                        self.parentForm().configDropFunctionality();
                        self.refreshTemplateTitle();
                    }
                },
                error: function (data) {
                    toast.error(self.entityName, 'getList');
                }
            });
    };
    self.refreshTemplateTitle = function () {
        var templates = $(".table-templateId");
        var target;
        if (_h.any(templates)) {
            for (var i = 0; i < templates.length; i++) {
                target = $(templates[i]);
                var id = Number(target.attr("data-id"));
                if (_h.any(self.records())) {
                    for (var j = 0; j < self.records().length; j++) {
                        if (id === self.records()[j].id()) {
                            $(templates[i]).attr("title", self.records()[j].title());
                        }
                    }
                }
            }
        }
    };
}
export class HtmlTemplateCategory extends BaseInnerModel {
    constructor(model) {
        super(model);
        this.templates = ko.observableArray(model.templates);
    }
}