;(function($){
  $(function(){
    if(!window.BoxmoeMdEditor||!BoxmoeMdEditor.enabled) return;
    var $ta = $('#content');
    if(!$ta.length) return;
    $('#content-tmce').hide();
    $('#content-html').hide();
    var $wrap = $('#wp-content-editor-container');
    var $bar = $('<div class="boxmoe-md-toolbar"></div>');
    var btn = function(text, cls){return $('<button type="button" class="md-btn '+(cls||'')+'">'+text+'</button>');};
    var $preview = $('<div class="boxmoe-md-preview"><div class="boxmoe-md-preview-inner"></div></div>');
    var $inner = $preview.find('.boxmoe-md-preview-inner');
    var insert = function(prefix, suffix, placeholder){
      var el = $ta.get(0);
      var start = el.selectionStart||0;
      var end = el.selectionEnd||start;
      var val = $ta.val();
      var sel = val.substring(start,end)|| (placeholder||'');
      var out = val.substring(0,start)+prefix+sel+suffix+val.substring(end);
      $ta.val(out);
      el.focus();
      el.selectionStart = start+prefix.length;
      el.selectionEnd = start+prefix.length+sel.length;
      
    };
    $bar.append(btn('B','md-bold').on('click',function(){insert('**','**','bold');}));
    $bar.append(btn('I','md-italic').on('click',function(){insert('*','*','italic');}));
    $bar.append(btn('H1').on('click',function(){insert('# ','','标题');}));
    $bar.append(btn('H2').on('click',function(){insert('## ','','副标题');}));
    $bar.append(btn('H3').on('click',function(){insert('### ','','小标题');}));
    $bar.append(btn('Link').on('click',function(){insert('[','](https://)','链接文字');}));
    $bar.append(btn('Image').on('click',function(){insert('![' ,'](https://)','alt');}));
    $bar.append(btn('Code').on('click',function(){insert('```\n','\n```','代码');}));
    $bar.append(btn('Quote').on('click',function(){insert('> ','','引用');}));
    $bar.append(btn('UL').on('click',function(){insert('- ','','列表项');}));
    $bar.append(btn('OL').on('click',function(){insert('1. ','','列表项');}));
    
    var $btnPreview = btn('预览','md-preview');
    $bar.append($btnPreview);
    function mountMdToolbar(){
      var $emoji = $('.quicktags-toolbar-emoji');
      if($emoji.length){
        $emoji.after($bar);
      }else{
        $wrap.prepend($bar);
      }
      $wrap.append($preview);
    }
    mountMdToolbar();
    function render(){
      $.post(BoxmoeMdEditor.ajaxUrl,{action:'boxmoe_md_preview',nonce:BoxmoeMdEditor.nonce,markdown:$ta.val()},function(resp){
        if(resp && resp.success){
          $inner.html(resp.data.html);
        }
      });
    }
    $btnPreview.on('click',function(){ render(); $preview.toggle(); });
  });
})(jQuery);
