var g_bEditorFullscreen = false;
var g_sDefaultLocale = "de";
var g_sEditorIDPrefix = "editor_";
var g_nEditorFixedFooterOffset = 38;

// fixed names
var tinyfck_field;
var tinyfck;

// Function directly referenced from JavaCode!
function pdafExecCommandCallback(editor_id, elm, command, user_interface, value) {
  switch (command) {
  case "mceFullScreen":
    _pdaf_toggleEditorFullscreen();
    return true;
  case "mceSave":
    pdafEditorBgSave(editor_id);
    return true;
  }
  // Pass anyway to next handler in chain
  return false;
}

// Function directly referenced from JavaCode!
function pdafFileBrowserCallBack(field_name, url, type, win) {
  var connector = g_pdaf_context_path + "/stream/js/coreui/filemanager/browser.html"
      + "?Connector=" + g_pdaf_context_path + "/filebrowser/"
      + g_pdaf_configured_plugin;
  var cType;
  tinyfck_field = field_name;
  tinyfck = win;
  switch (type) {
  case "image":
    cType = "Image,UI";
    break;
  case "ui":
    cType = "UI";
    break;
  case "file":
    cType = "File";
    break;
  case "multimedia":
  case "media":
    cType = "Multimedia";
    break;
  }
  if (cType) {
    connector += "&Type=" + cType;
  }
  window.open(connector, "tinyfck",
      "dependent=yes,modal,width=800,height=600,resizable=yes,status=yes");
}

// Function directly referenced from JavaCode!
function pdafCustomCleanup(type, value) {
  // alert("pdafCustomCleanup(" + type + ")");
  switch (type) {
  case "get_from_editor":
    // _pdaf_cleanUpLists(value);
    break;
  case "insert_to_editor":
    // _pdaf_cleanUpLists(value);
    break;
  case "get_from_editor_dom":
    _pdaf_cleanUpLists(value);
    break;
  case "insert_to_editor_dom":
    _pdaf_cleanUpLists(value);
    break;
  }
  return value;
}

function _pdaf_toggleEditorFullscreen() {
  alert("toggling fullscreen");
  var oHeader = jphloc.ge('header');
  var oMenu = jphloc.ge('menu');
  var oToolbar = jphloc.ge('toolbar');

  alert('header:' + oHeader + '\nmenu:' + oMenu + '\ntoolbar:' + oToolbar);
  if (g_bEditorFullscreen) {
    g_bEditorFullscreen = false;
    jphloc.show(oHeader);
    jphloc.show(oMenu);
    jphloc.show(oToolbar);
  } else {
    g_bEditorFullscreen = true;
    jphloc.hide(oHeader);
    jphloc.hide(oMenu);
    jphloc.hide(oToolbar);
  }
  alert("done");
}

function _append_hiddenfield(sParentId, sName, sValue) {
  var oHidden = document.createElement('input');
  oHidden.setAttribute('type', 'hidden');
  oHidden.setAttribute('name', sName);
  oHidden.setAttribute('value', sValue);
  jphloc.ge(sParentId).appendChild(oHidden);
}

function _special_submit(sFormId, sValue, bSaveAs) {
  if (sValue != null)
    _append_hiddenfield(sFormId, 'submit_restricted', sValue);
  if (bSaveAs)
    _append_hiddenfield(sFormId, 'submit_saveas', 'true');
  jphloc.ge(sFormId).submit();
}

// Save and close the editor
function pdafEditorSave(sEditorID, sLocale) {
  _special_submit('mainform', sLocale, false);

  // now set editor to 'not dirty' so autosave will not interact
  _pdaf_reset_mce_dirty(sEditorID);
}

//Save and close the editor(s)
function pdafEditorSaveAll(aButton, sEditorIDs) {
  // now set all editors to 'not dirty' so autosave will not interact
  aEditorIDs = sEditorIDs.split(',');
  for (var i=0; i<aEditorIDs.length; i++)
    _pdaf_reset_mce_dirty(aEditorIDs[i]);
  pdaf_submit_form(aButton);
}

function pdafEditorSaveFile(sEditorID) {
  _special_submit('mainform', null, false);

  // now set editor to 'not dirty' so autosave will not interact
  _pdaf_reset_mce_dirty(sEditorID);
}

// Save page as and close the editor
function pdafEditorSaveAs(sEditorID, sLocale) {
  _special_submit('mainform', sLocale, true);

  // now set editor to 'not dirty' so autosave will not interact
  _pdaf_reset_mce_dirty(sEditorID);
}

//Save file as and close the editor
function pdafEditorSaveAsFile(sEditorID) {
  _special_submit('mainform', null, true);

  // now set editor to 'not dirty' so autosave will not interact
  _pdaf_reset_mce_dirty(sEditorID);
}

function pdafGetLocaleOfEditorID(sEditorID) {
  var sLocale = null;
  // getting locale out of editor id = pdaf_edit[de]
  var nStart = sEditorID.indexOf("[");
  if (nStart >= 0 && nStart < sEditorID.length) {
    sLocale = sEditorID.substring(nStart + 1);
    var nEnd = sLocale.indexOf("]");
    if (nEnd >= 0 && nEnd < sEditorID.length)
      sLocale = sLocale.substring(0, nEnd);
    else
      sLocale = null;
  }
  if (sLocale)
    return sLocale;
  return g_sDefaultLocale;
}

function pdafEditorBgSave(sEditorID) {
  pdafEditorBackgroundSave(sEditorID, pdafGetLocaleOfEditorID(sEditorID));
}

// Function directly referenced from JavaCode!
function pdafEditorBackgroundSave(sEditorID, sLocale) {
  // remove any possible existing success message of former calls...
  var oExistingMsg = jphloc.ge('pdaf_ajax_result_message');
  if (oExistingMsg)
    oExistingMsg.parentNode.removeChild(oExistingMsg);

  // find out the page ID,
  // if not given, we are creating a new page
  var sPlugin = document.getElementsByName("cfgplugin")[0].value;
  var sPageID = document.getElementsByName("cfgpage")[0].value;
  var sContent = tinyMCE.get(sEditorID).getContent();
  // alert ("plugin: " + sPlugin);
  // alert ("pageID: " + sPageID);
  // alert ("sLocale: " + sLocale);
  // alert ("sContent: " + sContent);
  // alert (tinyMCE);
  // alert (tinyMCE.get(sEditorID));
  // alert (tinyMCE.get(sEditorID).getContent ());
  sajax_do_call(null, "savePageBackground", _pdafCallbackSavePageBackground, [ g_pdaf_configured_plugin, sPageID, sLocale, sContent ]);

  // now set editor to 'not dirty' so autosave will not interact
  _pdaf_reset_mce_dirty(sEditorID);
}

//Function directly referenced from JavaCode!
function pdafEditorBackgroundSaveFile(sAJAXMethod, sEditorID, sFileName) {
  // remove any possible existing success message of former calls...
  var oExistingMsg = jphloc.ge('pdaf_ajax_result_message');
  if (oExistingMsg)
    oExistingMsg.parentNode.removeChild(oExistingMsg);

  sajax_do_call(null, sAJAXMethod, _pdafCallbackSaveFileBackground, [
      sFileName, tinyMCE.get(sEditorID).getContent() ]);

  // now set editor to 'not dirty' so autosave will not interact
  _pdaf_reset_mce_dirty(sEditorID);
}

function _pdaf_reset_mce_dirty(sEditorID) {
  // as the content has been saved, TinyMCE may not return true on isDirty() ...
  // this is the fix!
  //alert(sEditorID);
  //alert(tinyMCE.get(sEditorID));
  tinyMCE.get(sEditorID).isNotDirty = true;
}

  
function _getJSCode (oNode) {
  if (oNode && oNode.nodeType == 1 && oNode.nodeName.toLowerCase() == "script") {
    var sCode = oNode.innerHTML;
    var nStart = sCode.indexOf("<!--"); 
    var nEnd = sCode.indexOf("//-->");
    if (nEnd < 0)
      nEnd = sCode.indexOf("-->");
    if (nStart >= 0 && nEnd >= 0 && nEnd > nStart)
      return sCode.substring(nStart + 4, nEnd);
    return sCode;
  }
  return "";
}

function _evalJS (oAnyNode) {
  // important for IE, otherwise it does not evaluate/execute the DOMappended JS code!
  var z = jphloc.getChildrenByTagName (oAnyNode, "script", true);
  for (var key in z)
    jphloc.eval(_getJSCode(z[key]));    
}

function _pdafCallbackSaveBackground(sResultXHTMLSniplet) {
  sResultXHTMLSniplet = sajax_clean_result(sResultXHTMLSniplet);  
  // commented this since it removed the backslashed of paths within the message!
  //sResultXHTMLSniplet = sResultXHTMLSniplet.replace(/\\/g, "");

  // show returned message after main form
  var oForm = jphloc.ge("mainform");
  var oParent = oForm.parentNode;
  oMsg = document.createElement('span');
  oMsg.innerHTML = sResultXHTMLSniplet;
  oMsg.setAttribute ('id', 'pdaf_ajax_result_message');
  oParent.insertBefore(oMsg, oForm);
  
  pdaf_triggerWindowLayoutChange ();
  // important for IE, otherwise it does not evaluate/execute the DOM appended JS code!
  _evalJS(oMsg);
}

function _pdafCallbackSavePageBackground(sResultXHTMLSniplet) {
  _pdafCallbackSaveBackground(sResultXHTMLSniplet);
}

function _pdafCallbackSaveFileBackground(sResultXHTMLSniplet) {
  _pdafCallbackSaveBackground(sResultXHTMLSniplet);
}

/* TINY MCE addon code */

function _pdaf_cleanUpLists(d) {
  var nl, x, a = [ 'ol', 'ul' ], i, j, n, c;

  // check for all ol and ul
  for (x = 0; x < a.length; x++) {
    nl = d.getElementsByTagName(a[x]);

    for (i = 0; i < nl.length; i++) {
      n = nl[i];
      // iterate all list children
      if (n.hasChildNodes()) {
        for (j = 0; j < n.childNodes.length; j++) {
          c = n.childNodes[j];
          // if child != li
          if (c.nodeName != "LI") {
            // get last li of this list
            lli = _pdaf_prevNode(c, 'LI');
            np = d.ownerDocument.createElement('li');
            np.innerHTML = '&nbsp;';
            np.appendChild(c);

            // first element in list
            if (!lli)
              n.insertBefore(np, n.firstChild);
            else
              _pdaf_inserAfter(np, lli);
          }
        }
      }
    }
  }
}

function _pdaf_inserAfter(n, r) {
  if (r.nextSibling)
    r.parentNode.insertBefore(n, r.nextSibling);
  else
    r.parentNode.appendChild(n);
}

function _pdaf_prevNode(e, n) {
  var a = n.split(','), i;
  while ((e = e.previousSibling) != null) {
    for (i = 0; i < a.length; i++)
      if (e.nodeName == a[i])
        return e;
  }
  return null;
}

function pdafFullPageSetupContent(editor_id, body, doc)
{
  var aEditor = tinymce.EditorManager.getInstanceById(editor_id);
  var sContentCSS = aEditor.getParam("content_css", "");
  if (sContentCSS != "")
  {
    var sCSSLinks = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
    var lContentCSS = sContentCSS.split(',');
    var oHead = aEditor.plugins.fullpage.head;
    for (var i=0; i<lContentCSS.length; i++)
    {
      var sRefLink = 'href="' + lContentCSS[i] + '"';
      var sCurSheet = '<link ' + sRefLink + ' type="text/css" rel="stylesheet"></link>';
      if (oHead.indexOf(sRefLink) < 0)
        sCSSLinks += sCurSheet + '\n'
    }
    var sTmp = oHead.replace('</head>', sCSSLinks + '</head>');
    aEditor.plugins.fullpage.head = sTmp;
  }
}

// This function receives the editor Object to operate on
// This parameter is required to work as Editor callback!
function pdafTinyMCEAutoResize (ed) {
  var editorID = ed.id;
  var frame = document.getElementById(editorID+"_ifr");
  if (frame == null)
    alert ("Failed to resolve editor IFrame with ID '" + editorID + "_ifr'");
    
  var nAvailable;
  if (window.innerHeight)
    nAvailable = window.innerHeight;
  else 
    if (document.documentElement && document.documentElement.clientHeight)
      nAvailable = document.documentElement.clientHeight;
  
  //get the document object
  var doc;
  if (frame.contentDocument) 
    doc = frame.contentDocument; 
  else 
    if (frame.contentWindow)
      doc = frame.contentWindow.document; 
    else
      if (frame.document)
        doc = frame.document; 
  
  if (doc == null) {
    alert ("Failed to resolve Editor document!");
    return;
  }
  
  //Fixes the issue of the table leaving empty space below iframe
  var tble = frame.parentNode.parentNode.parentNode.parentNode;
  tble.style.height = 'auto';
  
  //MAKE BIGGER
  frame.style.height = (nAvailable - jphloc.getOffsetTopRecursive(frame) - g_nEditorFixedFooterOffset) + "px";
}

// Called via the "setup" TinyMCE callback:
function pdafTinyMCESetup (ed)
{
  // Add "onInit" event to do the resizing!
  ed.onInit.add(pdafTinyMCEAutoResize);  
}

pdaf_registerWindowLayoutChangeListener (function (){
  // EDITOR RESIZE
  if (typeof(tinyMCE) != "undefined" && tinyMCE.activeEditor)
    pdafTinyMCEAutoResize(tinyMCE.activeEditor);  
});

