/* Cognoti default wysiwyg config */

var wysiwygs = new Array(0);
var xinha_editors   = new Array(0);
var xinha_init		= null;
var xinha_config = null;

var _editor_url = "/static/wysiwyg";
var _editor_lang = "en";
var _portal_name = "cognoti";
var extra_toolbar_info = null;
var xinha_plugins   = null;
var wysiwygLoaded = false;
var pageLoaded = false;
// This contains the names of textareas we will make into Xinha editors

xinha_init = xinha_init ? xinha_init : function()
{
    pageLoaded = true;
    if(wysiwygs.length == 0) { return; }
    
    if(loadWysiwygJS('xinha_init'))
    {
        return;    
    }
    
    
    xinha_plugins = ["TableOperations","CharacterMap","ContextMenu","NnInsertVideo", 
        "NnInsertImage", "NnInsertLink", "NnSpellCheck"];
    
    wysiwygs.each(function(e)
        {
            var p = e.get('plugins');
            if(p != null)
            {
                xinha_plugins.push(p);
            }
        });
    
    xinha_plugins = xinha_plugins.flatten().uniq();
    
    
    // THIS BIT OF JAVASCRIPT LOADS THE PLUGINS, NO TOUCHING	:)
    if(!Xinha.loadPlugins(xinha_plugins,xinha_init)) {
       return;
    }

    _custom_plugin_url = '/cognoti/xinhaplugin.nn';
    _resource_select_url = '/cognoti/helper/resource.nn';
    _link_select_url = '/cognoti/helper/link.nn';
    
    xinha_config = xinha_config ? xinha_config : new Xinha.Config();
    
    xinha_config.killWordOnPaste = true;
    xinha_config.statusBar = false;    
    xinha_config.showLoading = true;
	
    if(typeof config != 'undefined')
    {
        for(var item in config)
        {
            xinha_config[item] = config[item];    
        }
    }
    
    xinha_config.pageStyleSheets = ["/cognoti/css/wysiwyg.css"];
    
    xinha_editors = new Array(0);
    wysiwygs.each(function(e)
        {
            
            var ta = e.get('textarea');
            xinha_editors.push(ta);      
        });
    
    
    xinha_editors = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
    
    
    wysiwygs.each(function(e)
        {
            var toolbar = e.get('toolbar');
            var toolbar_extra = e.get('toolbar_extra');
            var st = e.get('stylesheets');
            var ta = xinha_editors[e.get('textarea')];
            ta.config.toolbar = configureToolbar(toolbar, toolbar_extra);
            
            if(Object.isArray(st))
            {
                st.each(function(s)
                    {
                        ta.config.pageStyleSheets.push(s);        
                    });
            }
            else if(st)
            {
                ta.config.pageStyleSheets.push(st);    
            }
            
            var pluginConfig = e.get('pluginconfig');
            
            Object.extend(ta.config, pluginConfig || {});
        });
    
    

    Xinha.startEditors(xinha_editors);    
    window.onload = null;
}

var configureToolbar = function(name, extra_toolbar_info)
{
    var tb = null;
    
    switch(name)
    {
        case 'minimal':
            tb =  [
                ["formatblock","bold","italic","underline","separator"],
                ["justifyleft","justifycenter","justifyright","justifyfull","separator"],
                ["insertorderedlist","insertunorderedlist","outdent","indent","separator"],
                ["forecolor","hilitecolor","textindicator", "killword", "removeformat","separator"],
                (extra_toolbar_info ? ["separator"] : ["createlink","insertimage", "separator","nnspellcheck", "separator", "htmlmode"]),
                (extra_toolbar_info ? extra_toolbar_info : [])                     
                
            ];
            break;
        case 'small':
            tb =  [
                ["formatblock","bold","italic","underline","separator"],
                ["justifyleft","justifycenter","justifyright","justifyfull","separator"],
                ["insertorderedlist","insertunorderedlist","outdent","indent","separator"],
                ["forecolor","hilitecolor","textindicator", "killword", "removeformat","separator"],
                (extra_toolbar_info ? ["separator"] : [/* "createlink","insertimage", */"nninsertimage","nninsertlink","nninsertvideo","separator","nnspellcheck", "separator", "htmlmode"]),
                (extra_toolbar_info ? extra_toolbar_info : [])                     
                
            ];
            break;
        case 'full':
        default:
            tb =  [
                ["fontname","fontsize","formatblock", "separator"],
                ["bold","italic","underline","separator"],
                ["strikethrough","subscript","superscript", "separator"],
                (HTMLArea.is_gecko ? [] : ["cut","copy","paste","overwrite","saveas","separator"]),
        
                ["undo","redo","selectall","separator"],
                ["justifyleft","justifycenter","justifyright","justifyfull","separator"],
                ["insertorderedlist","insertunorderedlist","outdent","indent","separator"],
                ["forecolor","hilitecolor","textindicator","insertcharacter", "killword", "removeformat", "separator"],
                ["inserthorizontalrule","inserttable", "separator"],
                (extra_toolbar_info ? [] : [/* "createlink","insertimage", */"nninsertimage","nninsertlink","nninsertvideo","separator","nnspellcheck", "separator","htmlmode"]),
                (extra_toolbar_info ? extra_toolbar_info : []),                     
                
            ];
    }        
        
    return tb;
}

function createXinhaEditor(textarea, toolbarname, toolbarextra, plugins, stylesheets, pluginConfig)
{
    if(plugins && !Xinha.loadPlugins(plugins,function() { createXinhaEditor(textarea, toolbarname, toolbarextra, plugins, stylesheets, pluginConfig); })) {
       return;
    }
    
    var taElem = $(textarea);
    
    var h = new Hash();
    h.set('textarea', textarea);
    h.set('toolbar', toolbarname);
    h.set('toolbar_extra', toolbarextra);
    h.set('plugins', plugins);
    h.set('pluginconfig', pluginConfig);
    h.set('stylesheets', stylesheets);
    h.set('parent', textarea.parentNode);
    h.set('sibling', taElem.previous());
    
    taElem.wysiwygInfo = h;
    
    var newEditor = Xinha.makeEditors([textarea], xinha_config, xinha_plugins);
    newEditor[textarea].config.toolbar = configureToolbar(toolbarname, toolbarextra);
    Xinha.startEditors(newEditor);
    xinha_editors[textarea] = newEditor[textarea];
}

function reconfigureWysiwyg(textarea)
{
    /* This was supposed to fix Wysiwygs that were part of a cloneNode or node moving problem... the end result
    is that for some awful reason neither the data a person enters or the state of the wysiwyg is persisted. So for now,
    since it technically doesn't lose data, but only functionality, this function will be ignored */
    
    textarea = $(textarea);
    
    var info = textarea.wysiwygInfo;
    
    if(info)
    {
        var dataMissingWarning = new Element('div', {'class': 'info_msg' });
        dataMissingWarning.insert(new Element('div').update('Wondering where your text just went?  Some browsers dislike moving text areas around, and this is the end result.  But rest assured, your text was not lost.  If you want to modify this text, you will need to click "Save" first so that the page reloads working correctly.  Thanks.'));
        
        $(textarea).insert({before: dataMissingWarning});
        
        
    }
}

function getWysiwygContent(textarea)
{
    var wysiwyg = xinha_editors[textarea];
    if(wysiwyg)
    {
        return wysiwyg.getEditorContent();    
    }
    else
    {
        return $(textarea).getValue();    
    }
}

function closeTextArea(textarea)
{
    var wysiwyg = xinha_editors[textarea];

    if(wysiwyg)
    {
        delete wysiwyg;    
        delete xinha_editors[textarea];
    }
}

function isWysiwyg(textarea)
{
    
    return !Object.isUndefined(xinha_editors[$(textarea).identify()]);   
}

function registerTextArea(textarea, toolbarname, toolbarextra, plugins, stylesheets, pluginConfig)
{
    if(!wysiwygLoaded)
    {
        
        var h = new Hash();
        h.set('textarea', textarea);
        h.set('toolbar', toolbarname);
        h.set('toolbar_extra', toolbarextra);
        h.set('plugins', plugins);
        h.set('pluginconfig', pluginConfig);
        h.set('stylesheets', stylesheets);
        
        
        
        var taElem = $(textarea);
        h.set('sibling', taElem.previous());
        taElem.wysiwygInfo = h;
        wysiwygs.push(h);
        
        if(pageLoaded)
        {
            loadWysiwygJS('xinha_init');        
        }
    }
    else
    {
        createXinhaEditor(textarea, toolbarname, toolbarextra, plugins, stylesheets); 
    }
}

function loadWysiwygJS(callback)
{
    if(!wysiwygLoaded)
    {
        wysiwygLoaded = true;
        
        var wysiwygFile = _editor_url+"/XinhaCore.js";
        var script = new Element('script', { type: 'text/javascript', src: wysiwygFile});
        $(document.body).insert({bottom: script});
        
        
        var script = new Element('script', { type: 'text/javascript'}).update('setTimeout('+callback+', 500);');
        $(document.body).insert({bottom: script});
        
        return true;
    }
    
    return false;
}

Event.observe(window, 'load', xinha_init);
