// Functions for use with the GLS CMSLight system
// 2004/02/13

function findObject(name) {
  var obj = document[name];
  if (!obj && document.all) {
    obj=document.all[name];
  }
  for (var i=0; !obj && i<document.forms.length; i++) {
    obj=document.forms[i][name];
  }
  if (!obj && document.layers) {
    for(var i=0; !obj && i<document.layers.length;i++) {
      obj=document.layers[i].document[name];
    }
  }
  if (!obj && document.getElementById) {
    obj=document.getElementById(name);
  }
  return obj;
}

var formChanged;

function registerChange() {
  // register a change in a form input value
  formChanged = true;
}

function registerReset() {
  // reset change registrations
  formChanged = false;
}

function checkForUnsavedChanges() {
  // Check whether a form contains unsaved changes (inputs that have been 
  // changed), before f.i. following a link to another page
  if (formChanged) {
    if (typeof(langDiscardChangesWarning) == 'undefined') {
      langDiscardChangesWarning = 
        'Changes have not yet been commited. Discard changes?';
    }
    return confirm(langDiscardChangesWarning);
  } else {
    return true;
  }
}

function checkHtmlCheckboxes() {
  if (typeof(langHtmlCheckboxWarning) == 'undefined') {
    langHtmlCheckboxWarning = 'The HTML checkbox is used to indicate whether the corresponding input field CURRENTLY contains HTML-code. If the checkbox is unchecked, the contents will be HTML-encoded for display, so that viewers will see the exact textyou entered. If the checkbox is checked, the system will make no further effort to turn the contents into HTML for display, since it already is HTML: viewers will see your code as interpreted by their browser. Are you sure you want to check/uncheck this box?';
  }
  return confirm(langHtmlCheckboxWarning);
}

function confirmDeleteAndCheck() {
  // Check whether the current form contains unsaved instructions, AS WELL AS
  // whether the user really indended to activate a link to a delete action
  if (formChanged) {
    if (typeof(langDiscardChangesWarning) == 'undefined') {
      langDiscardChangesWarning = 
        'Changes have not yet been commited. Discard changes?';
    }
    if (! confirm(langDiscardChangesWarning)) {
      return false;
    }
  }

  if (typeof(langDeleteWarning) == 'undefined') {
    langDeleteWarning = 'Are you sure you wish to delete this item?';
  }
  return(confirm(langDeleteWarning));
}


var cacheActiveElement, cacheSelectedRange;
function hideToolbar() {
  // When leaving a contentEditable DIV, hide the toolbar
  // When leaving a contentEditable DIV to click on the toolbar,
  // don't hide it, but remember the previous selection/insertion point

  formChanged = true; // usually doesn't work in onChange handler
  var toElement = event.toElement;
  while (toElement 
        && ! (toElement.tagName == 'TABLE'
        || (toElement.contentEditable && toElement.contentEditable!='inherit')
        || (toElement.hasAttribute 
        && toElement.hasAttribute('contentEditable')
        && toElement.getAttribute('contentEditable')!='inherit' ))) {
    toElement = toElement.parentNode;
  }
  if (toElement && (toElement.id == 'buttonbar'
      || (toElement.contentEditable && toElement.contentEditable!='inherit')
      || (toElement.hasAttribute 
        && toElement.hasAttribute('contentEditable')
        && toElement.getAttribute('contentEditable')!='inherit' ))) {
    cacheActiveElement = document.activeElement;
    cacheSelectedRange = document.selection.createRange();
  } else {
    var buttonbar = findObject('buttonbar');
    buttonbar.style.visibility = 'hidden';
    cacheActiveElement = false;
    cacheSelectedRange = false;
  }
}
function restoreSelection() {
  if (cacheActiveElement) {
    if (document.activeElement != cacheActiveElement) {
      // return to last contentEditable DIV (probably left it to press button)
      cacheActiveElement.setActive();
      cacheSelectedRange.select();
    }
  }
}

function doCommand(cmd) {
  // Perform a button action, f.i. to make the current text selection Bold
  // inside a contentEditable DIV
  restoreSelection();
  document.execCommand(cmd);
}

function dump_props(obj) {
  // debug routine: dump properties of object. Probably IE only
  var result = "";
  for (var i in obj) {
    if (String(obj[i]).length <= 30) {
      result += i + " = " + obj[i] + "\n";
    }
  }
  return result;
}



function storeEditableRegions() {
// This function transfers the contents of contentEditable DIV areas to
// hidden form fields. It is part of the HTML-Edit system which is used 
// when browsers which can handle contentEditable fields are detected
// (currently only MSIE5.5 or above).

  // Get form to be worked with
  var frm;
  if (arguments.length>0) {
    frm = arguments[0];
  } else {
    frm = document.forms["editform"];
  }

  // Search for contentEditable DIV's with nonempty names
  var els = frm.getElementsByTagName("DIV");
  for (i=0; i<els.length; i++) {
    var el = els[i];
    var name = el.name;
    if (!name) {
      name = el.id;
    }
    var contentEditable = el.contentEditable 
        || (el.hasAttribute && el.hasAttribute('contentEditable'));
    if (contentEditable && name) {
      // Fetch and adapt contents of el (removing anchor icons etc.)
      var text = el.innerHTML;
      text = text.replace(/<a name=[^>]*> *<\/a>/ig, '');
      text = text.replace(/<img[^>]*anchorImage[^>]*>/ig, '');
      text = text.replace(/(<br>$|<br \/>| |&nbsp;)+$/ig, '');
      // Transfer the content of el to a HIDDEN form input with the same name
      var el1;
      if (frm[name]) {
        el1 = frm[name];
      } else {
        for (var j=0; j<frm.elements.length; j++) {
          if (frm.elements[j].name==name) {
            el1=frm.elements[j];
            break;
          }
        }
      }
      if (el1) {
        // If such an element already exists (presumably as a result of a 
        // previous call to this routine), update its contents.
        el1.value = text;
      } else {
        // Otherwise, create it, and the corresponding xxxHtml element
        var el2 = document.createElement('input');
        el2.setAttribute('type', 'hidden');
        el2.setAttribute('name', name);
        el2.value = text;
        frm.appendChild(el2);
        el2 = document.createElement('input');
        el2.setAttribute('type', 'hidden');
        el2.setAttribute('name', name+'Html');
        el2.value = 'checked';
        frm.appendChild(el2);
      }
    }
  }
}

function isEmpty(inputObj) {
  // return true if field is empty
  switch(inputObj.type) {
    case "text":
    case "textarea":
    case "hidden":
      return (inputObj.value == "");
    case "select-one":
      if (inputObj.selectedIndex < 0) {
        return true;
      } else {
        return (inputObj.options[inputObj.selectedIndex].text == "");
      }
    case "select-multiple":
      return (inputObj.selectedIndex < 0);
    case "checkbox":
    case "radio":
      return (! inputObj.checked);
    default:
      if (inputObj.length) { // radiobutton group
        for(var i=0; i<inputObj.length; i++) {
          if (inputObj[i].checked) {
            return false;
          }
        }
        return true;
      }
      return false;
  }
}

function checkForm() {
  // This routine performs all actions necessary before submitting a form,
  // including tranferring all contentEditable DIV's to HIDDEN form inputs
  // and checking for required fields.
  // Syntax: checkForm(formvar, 'requiredField1', 'requiredField2', ...)
  // The form parameter usually gets value 'this', and can be omitted if
  // the form in question is named 'editform'.

  var frm;
  var i0=0;
  if (typeof(arguments[0]) != "object") {
    frm = document.forms["editform"];
  } else {
    frm = arguments[0];
    i0 = 1;
  }
  storeEditableRegions(frm);
  var missing = new Array;
  for(var i=i0; i<arguments.length; i++) {
    var inputName = arguments[i];
    var el;
    if (frm[inputName]) {
      el = frm[inputName];
    } else {
      for (var j=0; j<frm.elements.length; j++) {
        if (frm.elements[j].name==inputName) {
          el=frm.elements[j];
          break;
        }
      }
    }
    if (typeof(el)=="undefined") {
      var els = document.getElementsByName(inputName);
      el = els[0];
    }
    if (typeof(el)=="undefined") {
      window.alert("Checking for nonexisting field '" + inputName  + "'\n"
          + "(programming error?)");
    } else {
      if (isEmpty(el)) {
        missing[missing.length]=inputName; // push() doesn't work in Mac/IE
      }
    }
  }
  if (missing.length>0) {
    if (missing.length>1) {
      if (typeof(langNoValuesEnteredWarning)  == 'undefined') {
        langNoValuesEnteredWarning =
            'You didn\'t enter any values for the following fields';
      }
      window.alert(langNoValuesEnteredWarning + ': ' + missing.join(", "));
    } else {
      if (typeof(langNoValueEnteredWarning)  == 'undefined') {
        langNoValueEnteredWarning = 
            'You didn\'t enter a value for the field';
      }
      window.alert(langNoValueEnteredWarning + ': ' + missing[0]);
    }
    return false;
  }
  return true;
}

function callDialog(dialog) {
  restoreSelection();
  var resultValue = showModalDialog(wwwroot+"/editor/"+dialog+".html",
      document,
      "dialogWidth:24em; dialogHeight:18; help: no; status: no" );
  if ( resultValue != null ) {
    var selectionRange = document.selection.createRange();
    if (selectionRange.pasteHTML) { 
      selectionRange.pasteHTML(resultValue);
    } else if (selectionRange.length==1 && selectionRange.item(0).tagName=="IMG") {
      selectionRange.item(0).outerHTML=resultValue;
    }
  }
}

function showToolbar() {
    var buttonbar = findObject('buttonbar');
    buttonbar.style.visibility = 'visible';
}

function initContentEditableDivs() {
  // Get form to be worked with
  // Search for contentEditable DIV's with nonempty names
  var els = document.getElementsByTagName("DIV");
  var i,j;
  for (i=0; i<els.length; i++) {
    var el = els[i];
    var name = el.name;
    if (!name) {
      name = el.id;
    }
    var contentEditable = el.contentEditable 
        || (el.hasAttribute && el.hasAttribute('contentEditable'));
    if (contentEditable && name) {
      if (el.innerHTML=='') {
        el.innerHTML = '<br />';
      }
      el.onbeforedeactivate = hideToolbar;
      el.onfocus = showToolbar;
      if (el==document.activeElement) {
        showToolbar();
      }
      var els2 = el.getElementsByTagName("A");
      for (j=0; j<els2.length; j++) {
        var el2 = els2[j];
        if (el2.name && ! el2.innerHtml) {
          el2.innerHTML = '<img id="anchorImage" src="'+wwwroot+'/images/anchor.gif">';
        }
      }
    }
  }
}

function showPreview() {
  // This routine performs all actions necessary to generate a preview
  // Basically, it fakes a form submission, suitably adjusted

  var frm, actionValue;
  var i0=0;
  if (typeof(arguments[0]) != "object") {
    frm = document.forms["editform"];
  } else {
    frm = arguments[0];
    i0++;
  }
  if (typeof(arguments[i0]) != 'string') {
    actionValue = frm.elements["action"].value.replace(/^submit/, "preview");
  } else {
    actionValue = arguments[i0];
    i0++;
  }
  storeEditableRegions(frm);

  var oldAction = frm.attributes 
      ? frm.attributes.getNamedItem("action").nodeValue 
      : frm.getAttribute("action");
  var oldActionValue = frm.elements["action"].value;
  var oldMethod = frm.getAttribute("method");
  var oldTarget = frm.getAttribute("target");
  var oldEnctype = frm.getAttribute("enctype");

  if (frm.attributes) {
    frm.attributes.getNamedItem("action").nodeValue = wwwroot+"/index.php";
  } else {
    frm.setAttribute("action", wwwroot + "/index.php");
  }
  frm.elements["action"].value = actionValue;
  frm.setAttribute("method", "get");
  frm.setAttribute("target", "_blank");
  frm.setAttribute("enctype", "");

  frm.submit();

  if (frm.attributes) {
    frm.attributes.getNamedItem("action").nodeValue = oldAction;
  } else {
    frm.setAttribute("action", oldAction);
  }
  frm.elements["action"].value = oldActionValue;
  frm.setAttribute("method", oldMethod);
  frm.setAttribute("target", oldTarget);
  frm.setAttribute("enctype", oldEnctype);

  return false;
}

function prepCommand() {
// left over from prevous versions.
}

