var fckw_ajax_object = new sack();
var fckw_page_element = null;
var fckw_draft_status_parent = null;

var fckw_get_page_element = function() {
    if (fckw_page_element == null) {
        fckw_page_element = fckw_get_draft_status_parent().parentNode.parentNode;//getElementsByClass('page',null,'div')[0];
    }
    return fckw_page_element;
}

var fckw_get_draft_status_parent = function () 
{
    if (!fckw_draft_status_parent) {
        fckw_draft_status_parent = document.getElementById('draft__status').parentNode;
    }
    return fckw_draft_status_parent;
}

var init_fckw = function() {
    var btn = document.createElement('input');
    btn.setAttribute('id', 'edbtn__wysiwyg');
    btn.setAttribute('class', 'button');
    btn.setAttribute('type', 'submit');
    btn.setAttribute('value', 'Wysiwyg');
    addEvent(btn, "click", get_xhtml);

    var edbtn__preview = document.getElementById('edbtn__preview');
    edbtn__preview.parentNode.appendChild(btn);
}

var write_back = function(name)
{
    var oEditor = FCKeditorAPI.GetInstance(name);
    $('wiki__text').value = renderer.render(oEditor.EditorDocument);
    document.getElementById('edit__summary').value = document.getElementById('edit__xsummary').value;

    // c.f. /lib/scripts/edit.js
    // we force the native drafts system ;)
    locktimer.lasttime.setTime(locktimer.lasttime.getTime() - 30*1000);
    locktimer.refresh();
    textChanged = true;
    oEditor.ResetIsDirty();
}

var edit_wikisyntax = function()
{
    write_back('wiki__xtext');

    xpage.style.display='none';
    fckw_get_page_element().style.display='';

    // move the draft__status box to its original place
    var draft_status_box = document.getElementById('draft__status');
    draft_status_box.parentNode.removeChild(draft_status_box);
    fckw_get_draft_status_parent().insertBefore(draft_status_box, fckw_get_draft_status_parent().firstChild);
}

var get_xhtml = function (e) {
    fckw_ajax_object.setVar('call', 'fckw_get_xhtml');
    // when moving to the updated version of SACK (v. 1.6.1 or newer),
    // you will need to remove the encodeURIComponent().
    fckw_ajax_object.setVar('text', encodeURIComponent($('wiki__text').value));
    fckw_ajax_object.requestFile = DOKU_BASE + 'lib/exe/ajax.php';
    fckw_ajax_object.method = 'POST';
    fckw_ajax_object.onCompletion = fckw_on_completion;
    fckw_ajax_object.runAJAX();

     if (!!(window.attachEvent && !window.opera)){
        // this is IE
        e.returnValue = false;
        e.cancelBubble = true;
    } else {
        e.preventDefault();
        e.stopPropagation();
    }
    e.stopped = true;
    
    // move the draft__status box into a visible place
    var draft_status_box = document.getElementById('draft__status');

    fckw_get_draft_status_parent().removeChild(draft_status_box);
    fckw_get_page_element().parentNode.insertBefore(draft_status_box, fckw_get_page_element());
}

var xpage = null;

var fckw_on_completion = function () {
    if (fckw_ajax_object.responseStatus[0] != 200) {
        return;
    }

    fckw_get_page_element().style.display='none';
    if (xpage != null) {
        area = document.getElementById('wiki__xtext');
        area.value = fckw_ajax_object.response;
        document.getElementById('edit__xsummary').value = document.getElementById('edit__summary').value;
        FCKeditorAPI.GetInstance('wiki__xtext').SetData(fckw_ajax_object.response, true);
        xpage.style.display='';
        return;
    }
    xpage = document.createElement('div');
    xpage.setAttribute('class', 'xpage');
    xpage.setAttribute('id', 'xpage');
    var area = document.createElement('textarea');
    area.setAttribute('id', 'wiki__xtext');
    area.value = fckw_ajax_object.response;
    xpage.appendChild(area);

    var editb = document.createElement('div');
    editb.setAttribute('id', 'wiki__xeditbar');
    xpage.appendChild(editb);
    var buttons = document.createElement('div');
    buttons.setAttribute('class', 'editButtons');
    buttons.setAttribute('style','float: left');
    buttons.style.padding='0pt 1em 0.7em 0pt';
    editb.appendChild(buttons);

    var cmds = ['save', 'cancel', 'wikisyntax'];
    for(var i in cmds) {
        var btn = document.createElement('input');
        btn.setAttribute('id', 'edbtn__x'+cmds[i]);
        btn.setAttribute('class', 'button');
        btn.setAttribute('type', 'submit');
        btn.setAttribute('value', fcwk_lang['btn_'+cmds[i]]);
        switch(cmds[i]) {
            case 'wikisyntax':
                addEvent(btn, "click", edit_wikisyntax);
                break;
            case 'save':
                addEvent(btn, 'click', fckw_save);
                break;
            case 'cancel':
                addEvent(btn, 'click', fckw_cancel);
                break;
        }
        buttons.appendChild(btn);
    }
    var summary = document.createElement('div');
    summary.setAttribute('class', 'summary');
    summary.style.float = 'left';
    editb.appendChild(summary);

    var label = document.createElement('label');
    label.setAttribute('class', 'nowrap');
    label.setAttribute('for', 'edit__xsummary');
    summary.appendChild(label);

    var span = document.createElement('span');
    span.appendChild(document.createTextNode(fcwk_lang['summary']+' '));
    label.appendChild(span);

    var inp = document.createElement('input');
    inp.setAttribute('id', 'edit__xsummary');
    inp.setAttribute('class', 'edit');
    inp.setAttribute('type', 'text');
    inp.setAttribute('size', '50');
    inp.setAttribute('name', 'summary');
    label.appendChild(inp);
    inp.value = $('edit__summary').value;

    fckw_get_page_element().parentNode.insertBefore(xpage, fckw_get_page_element().nextSibling);

    var fck = new FCKeditor("wiki__xtext", "100%", "600");
    // TODO: fix this, get the path from php (at the same time like the lang object;)
    fck.BasePath = DOKU_BASE + 'lib/plugins/fckw/js/fckeditor/';
    // fck.Config["CustomConfigurationsPath"] = DOKU_BASE + "' . $this->getConf('fckconfig') .'";
    //fck.Config["DokuWikiLinkProtocols"] = "'.$this->getConf('link_protocols').'";
    fck.Config['EditorAreaCSS'] = [fck.BasePath +'../../exe/css.php?s=all', fck.BasePath +'../../exe/css.php', fck.BasePath + 'editor/css/fck_editorarea.css'];
    fck.ReplaceTextarea();

}

var fckw_save =  function()
{
    write_back('wiki__xtext');
    var form = $('dw__editform');
    var input = document.createElement('input');
    input.setAttribute('name', 'do[save]');
    form.appendChild(input);
    form.submit();
}

var fckw_draft_timeout = 30*1000; // miliseconds used for drafts
var FCKeditor_OnComplete = function( editorInstance )
{
    // initChangeCheck("lalala");
    textChanged = true;
    summaryCheck();
    setTimeout('fckw_save_draft(\''+editorInstance.Name+'\');', fckw_draft_timeout);
}

var fckw_save_draft = function(name)
{
    var oEditor = FCKeditorAPI.GetInstance(name) ;
    if (oEditor.IsDirty()) {
        write_back('wiki__xtext');
    }

    setTimeout('fckw_save_draft(\''+name+'\');', fckw_draft_timeout);
}

var fckw_cancel = function()
{
    // TODO: check if you really need this ajax call from
    // the changeCheck function
    if (changeCheck("Unsaved changes will be lost. \nReally continue?")){
        var form = $('dw__editform');
        var input = document.createElement('input');
        input.setAttribute('name', 'do[draftdel]');
        form.appendChild(input);
        form.submit();
    }

}

addInitEvent(init_fckw);

