document.tinymceConstructor = [];

function addTinyMCEEditor(element, options, loaderOptions, source) {
    if (!element) {
        return;
    }

    element = $(element);
    if (element.get('tag') != 'textarea') {
        element = element.getElements('textarea')[0];
    }

    var id = element.get('id');

    if (!source) {
        source = tinyMCESource;
    }
    
    if (!document.tinymcedata) {

            document.tinymcedata = {
                loaded: false,
                editors: new Hash(),
                waiting: null,
                settingup: false
            };
    }

    var defaultOptions = {
            mode : 'exact',
            theme : 'advanced',
            language : 'de',
            skin: 'o2k7',
            object_resizing : false,
            inline_styles : true,
            entity_encoding : 'raw',
            theme_advanced_blockformats : 'h2',
            convert_fonts_to_spans : true,
            force_p_newlines : false,
            document_base_url: domainDir,
            relative_urls : false,
            remove_script_host : true,
            pagebreak_separator: '&lt;!-- next page --&gt;',
            valid_elements : 'strong/b,embed[*],object[*],param[*],i,u,strike,p,br,ol,h2,hr,ul,li,sub,sup,span[class|align|style],+a[*],img[src|border|style|alt|class],font[color|style],div[class|align|style]',
            plugins : 'preview,safari,advlink,contextmenu,paste,media,pagebreak',
            //theme_advanced_toolbar_location : 'top',
            forced_root_block : false,
            theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,forecolor,|,justifyleft,justifyright,justifycenter,justifyfull,|,bullist,numlist,|,unlink,link,image,|,paste,pastetext,pasteword,removeformat',
            theme_advanced_buttons2 : 'formatselect,styleselect,hr,|,undo,redo,|,sub,sup,|,media,|,cleanup,code,preview',
            theme_advanced_buttons3 : '',
            theme_advanced_toolbar_align : 'left',
            theme_advanced_toolbar_location : 'external'
        };


    options = options||document.tinymcedata.editors[id]||null;
    if (!options) {
        for (var i=0; i<document.tinymceConstructor.length; i++) {
            options = document.tinymceConstructor[i].call(this, element);
            break;
        }
    }
    
    options = options || defaultOptions;

    if (options.extendsDefaultOptions) {
        var o = new Hash(options);
        options = defaultOptions;

        o.each((function(v, k){
            this.o[k] = v;
        }).bind({o: options}));
    }


    loaderOptions = loaderOptions||{
        plugins : options.plugins||'preview,advlink,safari,paste,media,pagebreak',
        themes : options.theme||'advanced',
        languages : options.language||'de',
        skin: options.skin||'o2k7',
        disk_cache : true,
        debug : false
    };

    document.tinymcedata.editors[id] = options;

    if (!document.tinymcedata.loaded) {
        if (!document.tinymcedata.waiting) {
            document.tinymcedata.waiting = [
                id
            ];


            new Asset.javascript(source, {
                'id': 'tinymcesource',
                'onload' : (function(){

                        document.tinymcedata.loaded = true;

                        tinyMCE_GZ.init(this.loaderOptions, (function(){
                            // loaded callback

                            document.tinymcedata.waiting.each((function(id){
                                addTinyMCEEditor(id, null, this.loaderOptions, this.source);
                            }).bind(this));

                        }).bind(this));

                }).bind({
                        options: options,
                        loaderOptions: loaderOptions,
                        source: source
                })
            });
            
        } else {
            document.tinymcedata.waiting.push(id);
        }

        return;
    }



    if (isdefined('tinyMCE') && !document.tinymcedata.settingup) {

        document.tinymcedata.settingup = true;

        tinyMCE.settings = options;
        tinyMCE.execCommand('mceAddControl', false, id);

        (function(){
            document.tinymcedata.settingup = false;
        }).delay(20);
        
        element.tinymceLoaded = true;

    } else {
        addTinyMCEEditor.delay(30, this, id, options, loaderOptions, source);
    }


}

function saveTinyMCEEditorData(id) {
    if (document.tinymcedata && document.tinymcedata.loaded) {
        var editor = tinyMCE.get(id);
        if (editor) {
            $(id).set('value', editor.getContent());
        }
    }
}

function removeAllTinyMCEEditors() {

    if (document.tinymcedata && document.tinymcedata.loaded) {

        document.tinymcedata.editors.each(function(options, id){
            if ($type(id) == 'element') {
                id = id.get('id');
            }

            saveTinyMCEEditorData(id);
            $(id).tinymceLoaded = false;

            tinyMCE.execCommand('mceRemoveControl', false, id);
        });

        document.tinymcedata.editors.empty();
        tinyMCE.idCounter = 0;
    }
}

function removeTinyMCEEditor(ids) {

    if ($type(ids)!='array') {
        ids = [ids];
    }

    if (document.tinymcedata && document.tinymcedata.loaded) {

        ids.each(function(id){
            if ($type(id) == 'element') {
                id = id.get('id');
            }

            saveTinyMCEEditorData(id);
            $(id).tinymceLoaded = false;

            tinyMCE.execCommand('mceRemoveControl', false, id);

            document.tinymcedata.editors.erase(id);
        });

        tinyMCE.idCounter = 0;
    }
}

function autoAddTinyMCEEditors() {
    $$('div.tinymce textarea').each(function(i){
        addTinyMCEEditor(i);
    });
}


window.addEvent('domready', function() {
	autoAddTinyMCEEditors();
});

window.addEvent('ajaxready', function() {
	autoAddTinyMCEEditors();
});