var TextElement;


if ($type(window['ModuleElement']) == 'class') {
    TextElement = new Class({
        Extends: ModuleElement,
        options:{
        }
    });
    $extend(TextElement, {
        attach:function() {

        },
        load:function(textarea, options) {
            textarea.toRichTextarea($merge(TextElement.tinyMCEConfig, options));
            (function() {
                if (tinyMCE.activeEditor) tinyMCE.activeEditor.execCommand('mceCleanup');
            }).delay(1000);
        },
        unload:function(textarea) {
            var id = textarea.get('id');
            tinyMCE.execCommand('mceRemoveControl', false, id);
        },

        askToSaveIfDirty : function(textarea) {
            return tinyMCE.getInstanceById($(textarea).get('id')).isDirty() ? confirm('You have unsaved changes. Are you sure you want to continue?') : true;
        },

        saveText : function (textarea) {
            var editor = tinyMCE.get(textarea.get('id'));
            if (editor) {
                editor.save();
                //editor.setProgressState(1);
            }
        },

        unlockText : function(textarea) {
            var editor = tinyMCE.get(textarea.get('id'));
            if (editor)
                editor.setProgressState(0);
        }

        ,clearDirty: function(textarea) {
            var editor = tinyMCE.get(textarea.get('id')).isNotDirty = 1;
        }
    });
    if (tinymce.majorVersion == '3' && tinymce.minorVersion == '2.5') {
        TextElement.tinyMCEConfig = {
            plugins : "safari,paste,searchreplace,inlinepopups,filemanager,imagemanager,media,spellchecker,table",
            theme_advanced_buttons1 : "undo,redo,|,pasteword,|,search,replace,|,justifyleft,justifycenter,justifyright,justifyfull,|,insertfile,insertimage,|,table,row_before,row_after,delete_row,row_props,col_before,col_after,delete_col,cell_props",
            moduleinstid : null,
            extended_valid_elements : 'iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder]'
        };
    } else {
        TextElement.tinyMCEConfig = {
            //   	mode : "exact",
            // elements : "test_textarea1,test_textarea2",
            theme : "advanced",
            skin : "default",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            add_unload_trigger : false,
            apply_source_formatting : 0,
            height: Math.max(225,window.getSize().y-200),
            autosave_interval: '5s', // for client autosave
            autosave_retention: '60m', // for client autosave
            // theme_advanced_statusbar_location : "bottom",
            // theme_advanced_resizing : true,
            // // theme_advanced_resizing_max_height : 240,
            // theme_advanced_resizing_max_width : 533,
            // theme_advanced_resizing_min_height : 250,
            // theme_advanced_resizing_min_width : 533,

            //plugins : "paste,searchreplace,inlinepopups,imagemanager,media,spellchecker,table",
            // plugins : "paste,searchreplace,media,spellchecker,table,inlinepopups,filemanager,imagemanager",
            plugins : "paste,searchreplace,spellchecker,table,inlinepopups,filemanager,imagemanager,media,autosave",
            theme_advanced_buttons1 : "undo,redo,restoredraft,|,pasteword,|,search,replace,|,justifyleft,justifycenter,justifyright,justifyfull,|,insertfile,insertimage,mceMedia|,table,row_before,row_after,delete_row,row_props,col_before,col_after,delete_col,cell_props",

            theme_advanced_buttons2 : "forecolor,fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,|,bullist,numlist,outdent,indent,|,link,unlink,|,spellchecker",
            theme_advanced_buttons3 : "",


            onchange_callback: function(inst) {
                //console.log(inst, inst.getBody(), inst.getBody().innerHTML);
            },
            // valid_elements: '*[*]',
            extended_valid_elements : 'iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder]',
            media_strict: false,
            valid_elements : "@[id|class|style|title|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|"
                + "onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|"
                + "onkeydown|onkeyup],a[rel|rev|charset|hreflang|tabindex|accesskey|type|"
                + "name|href|target|title|class|onfocus|onblur],strong/b,em/i,strike,u,"
                + "#p,-ol[type|compact],-ul[type|compact],-li,br,img[longdesc|usemap|"
                + "src|border|alt=|title|hspace|vspace|width|height|align],-sub,-sup,"
                + "-blockquote,-table[border=0|cellspacing|cellpadding|width|frame|rules|"
                + "height|align|summary|bgcolor|background|bordercolor],-tr[rowspan|width|"
                + "height|align|valign|bgcolor|background|bordercolor],tbody,thead,tfoot,"
                + "#td[colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor"
                + "|scope],#th[colspan|rowspan|width|height|align|valign|scope],caption,-div,"
                + "-span,-code,-pre,address,-h1,-h2,-h3,-h4,-h5,-h6,hr[size|noshade],-font[face"
                + "|size|color],dd,dl,dt,cite,abbr,acronym,del[datetime|cite],ins[datetime|cite],"
                + "object[classid|width|height|codebase|*],param[name|value|_value],embed[type|width"
                + "|height|src|*],script[src|type],map[name],area[shape|coords|href|alt|target],bdo,"
                + "button,col[align|char|charoff|span|valign|width],colgroup[align|char|charoff|span|"
                + "valign|width],dfn,fieldset,form[action|accept|accept-charset|enctype|method],"
                + "input[accept|alt|checked|disabled|maxlength|name|readonly|size|src|type|value],"
                + "kbd,label[for],legend,noscript,optgroup[label|disabled],option[disabled|label|selected|value],"
                + "q[cite],samp,select[disabled|multiple|name|size],small,"
                + "textarea[cols|rows|disabled|name|readonly],tt,var,big",
            tinyautosave_oninit: "configAutoSave"




// extended_valid_elements : 'iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder],object[style|bgcolor|scale|loop|autostart],embed[height|width]',


        };
    }

    TextElement.tinyMCEConfig.init_instance_callback = function(ed) {
        // drag & drop image from system issue of FF
        if (window.navigator.appCodeName == 'Mozilla') {
            ed.getBody().addEventListener('DOMNodeInserted', function(e){
                if (e.target.nodeName == 'IMG' && 0 == e.target.src.indexOf('data:image/')) {
                    e.target.parentNode.removeChild(e.target);
                    (function(){
                        alert("Text editor doen't support drag & drop images from your system");
                    }).delay(1);
                }
            }, false);
        }


        /*
         // comment out because tinymce toolbar behavior can't working
         ed.onNodeChange.addToTop(function() {
         return false;
         });
         */
    };

    TextElement.tinyMCEConfig.setup = function(ed) {
        ed.onActivate.add(function(editr) {
            $(editr.id + "_ifr").setStyle('height', Math.max(225, window.getSize().y - 200));
        });

        var tId;
        function save(ed, e) {
            clearTimeout(tId);
            tId = setTimeout(function() {
                ed.formElement.module.submit();
                clearTimeout(tId);
            }, 1000);
        }

        ed.onInit.add(function() {
            //see tiny_mce_src.js:12758 near case 'reset':
            var form = ed.getElement().form || tinymce.DOM.getParent(ed.id, 'form');
            if (!form.autosaveToggle) {
                return;
            }

            ed.formElement.autosaveToggle.addEvent('change', function() {
                if (this.checked) {
                    ed.onKeyUp.add(save);
                    ed.onChange.add(save);
                } else {
                    ed.onKeyUp.remove(save);
                    ed.onChange.remove(save);
                }
            });

            if (ed.formElement.autosaveToggle.checked) {
                ed.onKeyUp.add(save);
                ed.onChange.add(save);
            }
        });
    };
}
// Make sure we're using the new text editor, and then add support for resizing of text areas
if(typeof(tinymce)!='undefined' && tinymce && tinymce.majorVersion == '3' && tinymce.minorVersion >= '4.3.2') {

    window.addEvent('resize', function() {
        if (tinymce && tinymce.activeEditor && $("textelementvalue" + tinymce.activeEditor.settings.moduleinstid + "_ifr")) {
        // Need to change both iframe and parent,parent,parent table to target chrome... grr.
            $("textelementvalue" + tinymce.activeEditor.settings.moduleinstid + "_tbl").setStyle('height', 1);  // Fix: not sure if this is the best way
            $("textelementvalue" + tinymce.activeEditor.settings.moduleinstid + "_ifr").setStyle('height', Math.max(225, window.getSize().y - 200));
        }
    });
}
;

