var RE = {};/*定义函数对象*/

RE.currentSelection = {
    "startContainer": 0,
    "startOffset": 0,
    "endContainer": 0,
    "endOffset": 0};

RE.et_title = document.getElementById('et_title');/*标题*/
RE.et_hr = document.getElementById('et_hr');/*虚线*/

<!--屏蔽标题回车换行的方法-->
RE.et_title.onkeydown = function (e) {
    var code;
    if (!e) var  e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    if(code==13 && window.event){
        e.returnValue = false;
    }else if(code==13){
        e.preventDefault();
    }
}

/*隐藏标题和虚线*/
RE.setHidden = function () {
    RE.et_title.style.display="none";
    RE.et_hr.style.display="none";
}

RE.editor = document.getElementById('editor');/*内容编辑*/

document.addEventListener("selectionchange", function() { RE.backuprange(); });

/*内容输入的监听事件*/
RE.callback = function() {
   var ranges = [
         '\ud83c[\udf00-\udfff]',
         '\ud83d[\ude80-\udeff]'
     ];

    var oldlen=RE.editor.innerHTML;
    var newlen=RE.editor.innerHTML.replace(new RegExp(ranges.join('|'), 'g'), '');

    if(oldlen!=newlen){
        RE.backuprange();
        RE.editor.innerHTML =  RE.editor.innerHTML.replace(new RegExp(ranges.join('|'), 'g'), '');
        RE.restorerange();
    }
    //RE.editor.focus();
    window.location.href = "re-callback://" + encodeURI(RE.getHtml());
}

/*标题设置内容*/
RE.setHeadHtml = function (contents) {
    RE.et_title.innerHTML = decodeURIComponent(contents.replace(/\+/g, '%20'));
}

RE.setHtml = function(contents) {
    RE.editor.innerHTML = decodeURIComponent(contents.replace(/\+/g, '%20'));
}

/*标题得到内容*/
RE.getHeadHtml = function () {
    var ranges = [
        '\ud83c[\udf00-\udfff]',
        '\ud83d[\udc00-\ude4f]',
        '\ud83d[\ude80-\udeff]'
    ];
    return RE.et_title.innerHTML.replace(new RegExp(ranges.join('|'), 'g'), '');
}

RE.getHtml = function() {
    var ranges = [
        '\ud83c[\udf00-\udfff]',
        '\ud83d[\ude80-\udeff]'
    ];
    return RE.editor.innerHTML.replace(new RegExp(ranges.join('|'), 'g'), '');
}

RE.getText = function() {
    return RE.editor.innerText;
}

RE.setBaseTextColor = function(color) {
    RE.editor.style.color  = color;
}

RE.setBaseFontSize = function(size) {
    RE.editor.style.fontSize = size;
}

RE.setPadding = function(left, top, right, bottom) {
  RE.editor.style.paddingLeft = left;
  RE.editor.style.paddingTop = top;
  RE.editor.style.paddingRight = right;
  RE.editor.style.paddingBottom = bottom;
}

RE.setBackgroundColor = function(color) {
    document.body.style.backgroundColor = color;
}

RE.setBackgroundImage = function(image) {
    RE.editor.style.backgroundImage = image;
}

RE.setWidth = function(size) {
    RE.editor.style.minWidth = size;
}

RE.setHeight = function(size) {
    RE.editor.style.height = size;
}

RE.setTextAlign = function(align) {
    RE.editor.style.textAlign = align;
}

RE.setVerticalAlign = function(align) {
    RE.editor.style.verticalAlign = align;
}

/*设置标题为空时显示的文字*/
RE.setTitlePlaceholder = function(placeholder) {
    RE.et_title.setAttribute("placeholder", placeholder);
}

/*设置内容为空时显示的文字*/
RE.setPlaceholder = function(placeholder) {
    RE.editor.setAttribute("placeholder", placeholder);
}

RE.undo = function() {
    document.execCommand('undo', false, null);
}

RE.redo = function() {
    document.execCommand('redo', false, null);
}

RE.setBold = function() {
    document.execCommand('bold', false, null);
}

RE.setItalic = function() {
    document.execCommand('italic', false, null);
}

RE.setSubscript = function() {
    document.execCommand('subscript', false, null);
}

RE.setSuperscript = function() {
    document.execCommand('superscript', false, null);
}

RE.setStrikeThrough = function() {
    document.execCommand('strikeThrough', false, null);
}

RE.setUnderline = function() {
    document.execCommand('underline', false, null);
}

RE.setBullets = function() {
    document.execCommand('InsertUnorderedList', false, null);
}

RE.setNumbers = function() {
    document.execCommand('InsertOrderedList', false, null);
}

RE.setTextColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('foreColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setTextBackgroundColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('hiliteColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setFontSize = function(fontSize){
    document.execCommand("fontSize", false, fontSize);
}

RE.setHeading = function(heading,b) {
    if(b)
        document.execCommand('formatBlock', false, '<h'+heading+'>');
    else
        document.execCommand('formatBlock', false, '<p>');
}

RE.setIndent = function() {
    document.execCommand('indent', false, null);
}

RE.setOutdent = function() {
    document.execCommand('outdent', false, null);
}

RE.setJustifyLeft = function() {
    document.execCommand('justifyLeft', false, null);
}

RE.setJustifyCenter = function() {
    document.execCommand('justifyCenter', false, null);
}

RE.setJustifyRight = function() {
    document.execCommand('justifyRight', false, null);
}

RE.setBlockquote = function(b) {
    if(b)
        document.execCommand('formatBlock', false, '<blockquote>');
    else
        document.execCommand('formatBlock', false, '<p>');
}

//插入图片
RE.insertImage = function(url, alt,id) {

    //var html = '<img  src="' + url + '" alt="' + alt + '" id="'+id+'"/><p align=center style="color:#aaaaaa">来自陌筹君App的图片</p><hr align=center width=200 color=#aaaaaa size=1 /><br/><br/>';
    var html = '<img  src="' + url + '" alt="' + alt + '" id="'+id+'" style="max-width:100%"/><br/><br/>';
    RE.insertHTML(html);

    //图片的点击事件
    var image=document.getElementById(id);
    image.onclick = function(){
       // window.img.deleteImage(id);
    }
}

//通过图片id，替换src中的地址
RE.replaeUrl = function(id, url){
    document.getElementById(id).src = url;
    RE.callback();
}

//插入分割线
RE.insertHr = function() {
    var html = '<hr color=#e2e2e2 size=1 /><br/>';
    RE.insertHTML(html);
}

RE.insertHTML = function(html) {
    RE.restorerange();
    document.execCommand('insertHTML', false, html);
}


//插入链接
RE.insertLink = function(ur, title) {
    RE.restorerange();
    var url = ur ;
    if(ur.indexOf("http://")==-1){
        url = "http://"+ ur ;
    }
    var sel = document.getSelection();
    if (sel.toString().length == 0) {
        if(title.length == 0){
            document.execCommand("insertHTML",false,"<a href='"+url+"'>"+url+"</a>");
        }else{
            document.execCommand("insertHTML",false,"<a href='"+url+"'>"+title+"</a>");
        }

    } else if (sel.rangeCount) {
       var el = document.createElement("a");
       el.setAttribute("href", url);
       el.setAttribute("title", title);

       var range = sel.getRangeAt(0).cloneRange();
       range.surroundContents(el);
       sel.removeAllRanges();
       sel.addRange(range);
   }
    RE.callback();
}

RE.setTodo = function(text) {
    var html = '<input type="checkbox" name="'+ text +'" value="'+ text +'"/> &nbsp;';
    document.execCommand('insertHTML', false, html);
}

RE.prepareInsert = function() {
    RE.backuprange();
}

RE.backuprange = function(){
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
      var range = selection.getRangeAt(0);
      RE.currentSelection = {
          "startContainer": range.startContainer,
          "startOffset": range.startOffset,
          "endContainer": range.endContainer,
          "endOffset": range.endOffset};
    }
}

RE.restorerange = function(){
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
    range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
    selection.addRange(range);
}


/*内容点击事件*/
RE.enabledEditingItems = function(e) {
    var items = [];

    if (document.queryCommandState('bold')) {
        items.push('bold');
    }
    if (document.queryCommandState('italic')) {
        items.push('italic');
    }
    if (document.queryCommandState('subscript')) {
        items.push('subscript');
    }
    if (document.queryCommandState('superscript')) {
        items.push('superscript');
    }
    if (document.queryCommandState('strikeThrough')) {
        items.push('strikeThrough');
    }
    if (document.queryCommandState('underline')) {
        items.push('underline');
    }
    if (document.queryCommandState('insertOrderedList')) {
        items.push('orderedList');
    }
    if (document.queryCommandState('insertUnorderedList')) {
        items.push('unorderedList');
    }
    if (document.queryCommandState('justifyCenter')) {
        items.push('justifyCenter');
    }
    if (document.queryCommandState('justifyFull')) {
        items.push('justifyFull');
    }
    if (document.queryCommandState('justifyLeft')) {
        items.push('justifyLeft');
    }
    if (document.queryCommandState('justifyRight')) {
        items.push('justifyRight');
    }
    if (document.queryCommandState('insertHorizontalRule')) {
        items.push('horizontalRule');
    }
    var formatBlock = document.queryCommandValue('formatBlock');
    if (formatBlock.length > 0) {
        items.push(formatBlock);
    }

    if(e.which==13){
        items.push("enter");
    }


    var ranges = [
        '\ud83c[\udf00-\udfff]',
        '\ud83d[\udc00-\ude4f]',
        '\ud83d[\ude80-\udeff]'
    ];

    window.location.href = "re-state://" + encodeURI(items.join(','))+"@_@"+encodeURI(RE.getHtml());
}

/*标题请求焦点*/
RE.headFocus = function() {
    var range = document.createRange();
    range.selectNodeContents(RE.et_title);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.et_title.focus();
}

/*内容请求焦点*/
RE.focus = function() {
    var range = document.createRange();
    range.selectNodeContents(RE.editor);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.editor.focus();
}

RE.headBlurFocus = function() {
    RE.et_title.blur();
}

RE.blurFocus = function() {
    RE.editor.blur();
}

RE.removeFormat = function() {
    execCommand('removeFormat', false, null);
}

// Event Listeners
RE.editor.addEventListener("input", RE.callback);
RE.editor.addEventListener("keyup", function(e) {
    //RE.enabledEditingItems(e);
   var KEY_LEFT = 37, KEY_RIGHT = 39;
   if (e.which == KEY_LEFT || e.which == KEY_RIGHT || e.which ==8 || e.which == 13) {
       RE.enabledEditingItems(e);
   }
});
RE.editor.addEventListener("click", RE.enabledEditingItems);

/*标题输入的监听事件*/
RE.et_title.addEventListener("input", function () {
    /*限制标题的字数*/
    var leng = RE.et_title.innerHTML.length;
     if(leng>200){
        RE.et_title.innerHTML = RE.et_title.innerHTML.substring(0,200);
         var range = document.createRange();
         range.selectNodeContents(RE.et_title);
         range.collapse(false);
         var selection = window.getSelection();
         selection.removeAllRanges();
         selection.addRange(range);
     }

    var ranges = [
        '\ud83c[\udf00-\udfff]',
        '\ud83d[\udc00-\ude4f]',
        '\ud83d[\ude80-\udeff]'
    ];

    var oldlen=RE.et_title.innerHTML;
    var newlen=RE.et_title.innerHTML.replace(new RegExp(ranges.join('|'), 'g'), '');

    if(oldlen!=newlen){
        RE.backuprange();
        RE.et_title.innerHTML =  RE.et_title.innerHTML.replace(new RegExp(ranges.join('|'), 'g'), '');
        RE.restorerange();
    }
    window.location.href = "tre-callback://" + encodeURI(RE.getHeadHtml());
})

/*标题获取焦点*/
RE.et_title.addEventListener("focus", function () {
    window.getFocus.hiddenLL();/*隐藏功能条*/
})

/*内容获取焦点*/
RE.editor.addEventListener("focus", function () {
    window.getFocus.showLL();/*显示功能条*/
})
