$(function() {
    var editorCreated = false,
        mkEditor = new baidu.editor.ui.Editor({
            minFrameHeight: $(window).height() - 50
        });
    mkEditor.addListener('afterpaste', function() {
        var iframes = $('.edui-editor-iframeholder').find('iframe')
        var doc = iframes[0].contentDocument;
        var obj = mknote.app.obj();
        var imgs = $('img', doc);
        imgs.each(function(i, img) {
            var word_img = $(img).attr('word_img');
            if (word_img) {
                var localUrl = obj.addLocalFile(window.location.href, word_img);
                $(img).attr('_src', localUrl);
                $(img).attr('src', localUrl);
                $(img).removeAttr('word_img');
            }
        })
    });
    mkEditor.addListener('ready', function() {
        var t = this;
        $(document).unbind('keydown.editorsave');
        $(window).unbind('resize');
        $(window).bind('resize', function() {
            t.setHeight($(window).height() - 50);
        });
        $(t.document).bind('click', function(e) {
            $(document.body).mouseup();
        });
    });
    mkEditor.addListener('contentchange', function() {
        if (editorCreated) {
            var obj = mknote.app.obj();
            obj.notifyContentChange(window.location.href);
        }
    });
    mkEditor.addListener('sourcemodechanged', function() {
        if (mkEditor.queryCommandState('source') == 1) {
            $(mkEditor.container).find('.CodeMirror').bind('keyup paste cut', function() {
                mkEditor.fireEvent('selectionchange');
            });
        }
    });
    mkEditor.render('notecontent');
    // mkEditor.fireEvent('selectionchange');


    setTimeout(function() {
        var iframes = $('.edui-editor-iframeholder').find('iframe'),
            iframe = null;
        if (iframes.length > 0) {
            iframe = iframes[0]
            var doc = iframe.contentDocument;
            $(iframe.contentDocument).delegate('.editor-note-checkbox', 'click', function() {
                var $this = $(this);
                if ($this.attr('data-checked') == 'false') {
                    $this.attr('src', 'themes/default/images/rte_todo_checked.gif')
                    $this.attr('data-checked', true);
                } else {
                    $this.attr('src', 'themes/default/images/rte_todo_unchecked.gif')
                    $this.attr('data-checked', false);
                }
                obj = mknote.app.obj();
                obj.notifyContentChange(window.location.href);
            });
        }
    }, 1000);

    editorCreated = true;

    //editor end


    function mkExecCommand(command, value) {
        mkEditor.execCommand(command, value);
    }

    //for window.external call functions

    window.getNoteContent = function() {
        var noteContent = mkEditor.getContent();
        noteContent = noteContent.replace(/<img\b[^<>]+?rte_todo_(un)?checked+?[^<>]+?>/g, function(word) {
            if (word.indexOf('data-checked="true"') >= 0) {
                return '<input class="editor-note-checkbox" type="checkbox" checked/>'
            } else {
                return '<input class="editor-note-checkbox" type="checkbox" />'
            }
        });
        return noteContent;
    }

    window.saveNote = function() {
        obj = mknote.app.obj();
        obj.notifyNoteContentSave(window.location.href, getNoteContent());
    }

    window.fetchNoteContent = function() {
        obj = mknote.app.obj();
        obj.notifyNoteContent(window.location.href, getNoteContent());
    }

    window.setNoteContent = function(value) {
        //移除图片拖拽div
        var eimagescale = document.getElementById("edui1_imagescale");
        if (eimagescale) {
            eimagescale.style.display="none";
        };
        
        var noteContent = value.replace(/<input.+?class=\"editor-note-checkbox\".+?type="checkbox".+?>/g, function(word) {
            if (word.indexOf('checked') >= 0) {
                return '<img src="themes/default/images/rte_todo_checked.gif" type="image" data-checked="true" style="cursor:pointer !important;cursor:hand;" class="editor-note-checkbox">'
            } else {
                return '<img src="themes/default/images/rte_todo_unchecked.gif" type="image" data-checked="false" style="cursor:pointer !important;cursor:hand;" class="editor-note-checkbox">'
            }
        });
        mkEditor.setContent(noteContent);
        obj = mknote.app.obj();
        obj.notifyNoteContentLoaded(window.location.href);
    }
    window.isWyswygMode = function() {
        return mkEditor.queryCommandState('source') == 0;
    }
    window.selectAllNoteContent = function() {
        mkExecCommand('SelectAll');
    }
    window.focusEditor = function() {
        mkEditor.focus();
    }
    window.insertHtml = function(value) {
        mkExecCommand('InsertHtml', value);
    }
    window.setFont = function(value) {
        $(mkEditor.document.body).css('font-family', value)
    }
    window.setFontSize = function(value) {
        $(mkEditor.document.body).css('font-size', value)
    }
    window.cut = function() {
        mkExecCommand('Cut');
    }

    window.undo = function() {
        mkExecCommand('Undo');
    }
    window.redo = function() {
        mkExecCommand('Redo');
    }
    window.canUndo = function() {
        return mkEditor.undoManger.hasUndo;
    }
    window.canRedo = function() {
        return mkEditor.undoManger.hasRedo;
    }
    window.removeFormat = function() {
        mkExecCommand('RemoveFormat');
    }

    window.getDataSrcHelper = function() {
        return 'data_ue_src';
    }
    window.isDialogShowing = function() {
        return false; // TODO: ÎÞÐ§·½·¨£¬µÈ×óÀÏ°åÀ´¸Ä
    }
    window.reset = function() {
        PCEditor.reset();
    }
    window.notifyContentChanged = function() {
        mkEditor.fireEvent('selectionchange');
    }
    window.notifyContentChange = function() {
        mkEditor.fireEvent('contentchange');
    }
    window.PCEditor = {
        insertImageFile: function(imgPara) {
            var imgObj;
            if (typeof imgPara == 'string') {
                imgObj = {};
                imgObj.src = imgPara;
                imgObj.data_ue_src = imgPara;
            } else {
                imgObj = imgPara;
            }
            mkEditor.execCommand('insertImage', imgObj);
        },
        addDialog: function(dialog) {
            this.dialog = dialog;
        },
        reset: function() {
            this.dialog && this.dialog.close();
            baidu.editor.ui.Popup.postHide();
            if (mkEditor.queryCommandState('source') == 1) {
                mkExecCommand('source')
            }
            mkEditor.reset();
        },
        showToolbar: function() {
            $('#edui1_toolbarbox').show();
        },
        hideToolbar: function() {
            $('#edui1_toolbarbox').hide();
        }
    }
    window.readOnly = function(value) {
        if (value) {
            mkEditor.setDisabled();
        } else {
            mkEditor.setEnabled();
        }
    }
    window.mkEditorExecCommand = function(command, value) {
        mkEditor.execCommand(command, value);
    };
    window.setBodyStyle = function(name, value) {
        $(mkEditor.document.body).css(name, value)
    }
    window.getWordCount = function() {
        var msg = mkEditor.queryCommandValue('wordcount');
        obj = mknote.app.obj();
        obj.notifyWordCount(window.location.href, msg.split(' ')[1]);
        //return msg.split(' ')[1];
    }
    window.convertTxtFormat = function() {
        // copy from editor_all.js getPlainTxt
        var dtd = UE.dom.dtd;
        var reg = new RegExp(UE.dom.domUtils.fillChar, 'g'),
            html = mkEditor.body.innerHTML.replace(/[\n\r]/g, ''); //ieÒªÏÈÈ¥ÁË\nÔÚ´¦Àí
        html = html.replace(/<(p|div|h1|h2|h3|h4|h5|li|ul|ol|a|span|img|em)[^>]*>/gi, '')
            .replace(/<br\w*\/?>/gi, function(a, b, c) {
                return '<br/>';
            })
            .replace(/<[^>/]+>/g, '')
            .replace(/(\n)?<\/([^>]+)>/g, function(a, b, c) {
                var c = c.toLowerCase();
                if (c == 'ol') {
                    return '';
                } else if (c == 'li') {
                    return '';
                } else if (c == 'tr') {
                    return '<br/>';
                } else if (c == 'h1' || c == 'h2' || c == 'h3' || c == 'h4' || c == 'h5') {
                    return '';
                } else if (c == 'br') {
                    return '<br/>';
                }
                return dtd.$block[c] ? '<br/>' : '';
            });
        //È¡³öÀ´µÄ¿Õ¸ñ»áÓÐc2a0»á±ä³ÉÂÒÂë£¬´¦ÀíÕâÖÖÇé¿ö\u00a0
        html = html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
        html = html.replace(/\s/g, '')
        mkEditor.setContent(html);
        obj = mknote.app.obj();
        obj.notifyContentChange(window.location.href);
    }
    window.replaceImageUrl = function(url1, url2) {
        $('img[src="' + url1 + '"]').attr('src', url2);
    }
    window.changeEditerBG = function(value) {
        try {
            var el = mkEditor.ui.getDom('iframeholder');
            var bgCss = '';
            switch (value) {
                default: bgCss = 'url(themes/default/images/edit_bg0.png)';
            }
            el.style.backgroundImage = bgCss;
        } catch (e) {
            alert(e)
        }
    }
    window.removeEditerBG = function() {
        try {
            var el = mkEditor.ui.getDom('iframeholder');
            el.style.backgroundImage = '';
        } catch (e) {

        }
    }
});