<!doctype html>
<?php
$dir = "data/";
$md = isset($_GET["md"]) ? $_GET["md"] : "new.md";
$title = "MD记事本";
?>
<script>
    var md = "<?php echo $md; ?>", title = "<?php echo $title; ?>";
</script>
<html>
  <head>
	<meta charset="utf-8">
	<title><?php echo $md . " - " . $title; ?></title>
  </head>

  <body>
	<link rel="stylesheet" href="css/editormd.min.css" />
	<div id="editormd">
	  <textarea style="display:none;"><?php echo file_get_contents($dir . $md); ?></textarea>
	</div>
	<script src="js/jquery.min.js"></script>
	<script src="js/editormd.js"></script>
	<script type="text/javascript">
    var MDEditor;
    $(function () {

      MDEditor = editormd("editormd", {
        width: "100%",
        height: 740,
        //fullscreen: true,
        //autoHeight: true,
        //path: 'lib/',
        //theme: "dark",
        //previewTheme: "dark",
        //editorTheme: "pastel-on-dark",
        //markdown: md,
        codeFold: true,
        //syncScrolling : false, //同步滚动条
        saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
        searchReplace: true,
        //watch : false,                // 关闭实时预览
        htmlDecode: "style,script,iframe|on*", // 开启 HTML 标签解析，为了安全性，默认不开启
        //toolbar  : false,             //关闭工具栏
        //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
        emoji: true,
        taskList: true,
        tocm: true, // Using [TOCM]
        tex: true, // 开启科学公式TeX语言支持，默认关闭
        flowChart: true, // 开启流程图支持，默认关闭
        sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
        //dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
        //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
        //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
        //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
        //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: "./php/upload.php",
        toolbarIcons: function () {
          // Or return editormd.toolbarModes[name]; // full, simple, mini
          // Using "||" set icons align right.
          return ["Open", "File", "Save", "|", "undo", "redo", "|",
            "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
            "h1", "h2", "h3", "h4", "h5", "h6", "|",
            "list-ul", "list-ol", "hr", "|",
            "link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
            "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
            "help", "info"]
        },
        toolbarIconsClass: {
          Open: "fa-folder-open-o",
          File: "fa-file-o",
          Save: "fa-save"
        },
        toolbarIconTexts: {
          Open: "打开文件",
          File: "新建文件",
          Save: "保存文件"  // 如果没有图标，则可以这样直接插入内容，可以是字符串或HTML标签
        },
        // 自定义工具栏按钮的事件处理
        toolbarHandlers: {
          /**
           * @param {Object}      cm         CodeMirror对象
           * @param {Object}      icon       图标按钮jQuery元素对象
           * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
           * @param {String}      selection  编辑器选中的文本
           */
          Save: function () {
            if (md == "new.md") {
              ispass();
              var FileName = prompt('请输入文件名');

              if (FileName) {
                var aj = $.ajax({
                  url: 'ok.php',
                  type: 'post',
                  cache: false,
                  dataType: 'json',
                  data: {'m': 'newfile', 'md': '<?php echo $dir; ?>' + FileName + '.md', 'data': MDEditor.getMarkdown(), 'pass': getCookie('pass')},
                  success: function (data) {
                    if (data.msg == "true") {
                      md = FileName + ".md";
                      $("title").html(md + " - " + title);
                      alert("保存成功！文件名:" + md);
                    } else {
                      alert(data.msg);
                    }
                  },
                  error: function () {
                    alert("出现异常！");
                  }
                });
              }
            } else {
              ispass();
              var aj = $.ajax({
                url: 'ok.php',
                type: 'post',
                cache: false,
                dataType: 'json',
                data: {'m': 'savefile', 'md': '<?php echo $dir; ?>' + md, 'data': MDEditor.getMarkdown(), 'pass': getCookie('pass')},
                //{ 'option':'delete','name':'11&adb'},
                success: function (data) {
                  if (data.msg == "true") {
                    $("title").html(md + " - " + title);
                    alert("保存成功！文件名:" + md);
                    //window.location.reload();
                  } else {
                    alert(data.msg);
                  }
                },
                error: function () {
                  alert("出现异常！");
                }
              });
            }
          },
          File: function () {
            ispass();
            var FileName = prompt('请输入文件名');
            if (FileName) {
              var aj = $.ajax({
                url: 'ok.php', // 跳转到 action
                type: 'post',
                cache: false,
                dataType: 'json',
                data: {'m': 'newfile', 'md': '<?php echo $dir; ?>' + FileName + '.md', 'data': MDEditor.getMarkdown(), 'pass': getCookie('pass')},
                success: function (data) {
                  if (data.msg == "true") {
                    MDEditor.setValue("");
                    md = FileName + ".md";
                    $("title").html(md + " - " + title);
                    alert("新建成功！文件名:" + md);
                  } else {
                    alert(data.msg);
                  }
                },
                error: function () {
                  alert("出现异常！");
                }
              });
            }
          },
          Open: function () {
            this.executePlugin("openDialog", "open-dialog/open-dialog");
          },
        },
        lang: {
          toolbar: {
            Open: "打开文件",
            Save: "保存文件",
            File: "新建文件"
          },
          dialog: {
            open: {
              title: "文件列表"
            }}
        },
        onload: function () {
          //console.log('onload', this);
          this.fullscreen();
          var keyMap = {
            "Ctrl-S": function (cm) {
              alert("Ctrl-S未启用");
            },
            "Ctrl-O": function (cm) {
              alert("Ctrl-O未启用");
            }
            ,
            "Alt-N": function (cm) {
              alert("Alt-N未启用");
            }
          };
          this.addKeyMap(keyMap);
          //this.unwatch();
          //this.watch().fullscreen();

          //this.setMarkdown("#PHP");
          //this.width("100%");
          //this.height(480);
          //this.resize("100%", 640);
        },
        onchange: function () {
          //$("title").html("(*)" + $('title').text());
          $("title").html("(*)" + md + " - " + title);
        }

      });
    });
    function getCookie(c_name)
    {
      if (document.cookie.length > 0)
      {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1)
        {
          c_start = c_start + c_name.length + 1
          c_end = document.cookie.indexOf(";", c_start)
          if (c_end == -1)
            c_end = document.cookie.length
          return unescape(document.cookie.substring(c_start, c_end))
        }
      }
      return ""
    }

    function setCookie(c_name, value, expiredays)
    {
      var exdate = new Date()
      exdate.setDate(exdate.getDate() + expiredays)
      document.cookie = c_name + "=" + escape(value) +
              ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
    }
    function ispass()
    {
      pass = getCookie('pass');
      if (pass == null || pass == "") {
        var pa = prompt('请输入密码');
        if (pa) {
          setCookie('pass', pa, 365);
        }
      }
    }
	</script>
  </body>
</html>
