
// ********************************************** //
// * Majestic - Content management for everyone * //
// * Copyright (c) 2008 Injader                 * //
// * More information at http://www.injader.com * //
// ********************************************** //

/* AJAX */

  function ajaxStart() {
    var http = createRequestObject();
  }

  function createRequestObject() {
    var ReqOb;
    var browser = navigator.appName;
    if (browser == "Microsoft Internet Explorer") {
      ReqOb = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
      ReqOb = new XMLHttpRequest();
    }
    return ReqOb;
  }
  
  function sndReq(action) {
    http.open('get', '_rpc.php?action='+action);
    http.onreadystatechange = handleResponse;
    http.send(null);
  }
  
  function handleResponse() {
    if (http.readyState == 4) {
      var response = http.responseText;
      var update = new Array();
      if (response.indexOf('|' != -1)) {
          update = response.split('|');
          document.getElementById(update[0]).innerHTML = update[1];
      }
    }
  }

/* POST AJAX EVENTS */

  function PostAjaxEvent(strAction) {
    if (strAction == "AddUserGroup") {
      AddUserGroupToTable();
    } else if ((strAction == "AddSiteTemplate") || (strAction == "CopySiteTemplate")) {
      AddSiteTemplateToTable();
    } else if ((strAction == "AddTemplateGroupCA") || (strAction == "CopyTemplateGroupCA")) {
      AddTemplateGroupToTable('CA');
    } else if ((strAction == "AddTemplateGroupFA") || (strAction == "CopyTemplateGroupFA")) {
      AddTemplateGroupToTable('FA');
    } else if ((strAction == "AddComment") ||
               (strAction == "DeleteComment") ||
               (strAction == "ArticleCommand") ||
               (strAction == "ApplySiteTemplate") ||
               (strAction == "DeleteArea") ||
               (strAction == "DeletePerProfile") ||
               (strAction == "DeleteAllExpiredSessions")) {
      reloadPage();
    }
  }

  function AddTemplateGroupToTable(strTypePrefix) {
    // Populate table
    strGroupName = document.getElementById('txtNewGroupName').value;
    intGroupID = document.getElementById('ajaxNewGroupID').innerHTML;
    if (strTypePrefix == "CA") {
      var elem1 = document.createTextNode(strTTYContentArea);
      var strAdminPageURL = strCAAdminPage;
    } else if (strTypePrefix == "FA") {
      var elem1 = document.createTextNode(strTTYFileArea);
      var strAdminPageURL = strFAAdminPage;
    }
    var elem2 = document.createTextNode(strGroupName);
    var elem3 = document.createElement('div');
    var elem3Edit = document.createElement('a');
    elem3Edit.setAttribute('href', strAdminPageURL + '?action=edit&id=' + intGroupID);
    elem3EditText = document.createTextNode("Edit");
    elem3Edit.appendChild(elem3EditText);
    var elem3Copy = document.createElement('a');
    elem3Copy.setAttribute('href', 'javascript:CopyTemplateGroup(\'' + intGroupID + '\', \'' + strTypePrefix + '\')');
    elem3CopyText = document.createTextNode("Copy");
    elem3Copy.appendChild(elem3CopyText);
    var elem3Export = document.createElement('a');
    elem3Export.setAttribute('href', strExportURL + '?action=exportgroup&id=' + intGroupID);
    elem3ExportText = document.createTextNode("Export");
    elem3Export.appendChild(elem3ExportText);
    var elem3Delete = document.createElement('a');
    elem3Delete.setAttribute('onclick', "DeleteTemplateGroup('" + intGroupID + "'," + "this.parentNode.parentNode.parentNode.getAttribute('id').replace(strTableRowPrefix,'')" + ")");
    elem3Delete.setAttribute('href', '#');
    elem3DeleteText = document.createTextNode("Delete");
    elem3Delete.appendChild(elem3DeleteText);
    txtSpacer = document.createTextNode(" : ");
    txtSpacer2 = document.createTextNode(" : ");
    txtSpacer3 = document.createTextNode(" : ");
    elem3.appendChild(elem3Edit);
    elem3.appendChild(txtSpacer);
    elem3.appendChild(elem3Copy);
    elem3.appendChild(txtSpacer2);
    elem3.appendChild(elem3Export);
    elem3.appendChild(txtSpacer3);
    elem3.appendChild(elem3Delete);
    var elem4 = document.createTextNode(' ');
    // Send to table row
    arrRowData = new Array(elem1, elem2, elem3, elem4);
    setTimeout("libAddTableRow('tblTemplateGroupsBody', arrRowData)", 1000);
    // Confirm
    libAjaxMsg('ajaxStatus', 'info', 'Added new group: ' + strGroupName);
  }

  function AddSiteTemplateToTable() {
    // Populate table
    strGroupName = document.getElementById('txtNewGroupName').value;
    intGroupID = document.getElementById('ajaxNewGroupID').innerHTML;
    var elem1 = document.createTextNode(strGroupName);
    var elem2 = document.createElement('a');
    elem2.setAttribute('onclick', "ApplySiteTemplate('" + intGroupID + "')");
    elem2.setAttribute('href', '#');
    elem2Text = document.createTextNode("Apply");
    elem2.appendChild(elem2Text);
    var elem3 = document.createElement('div');
    var elem3Edit = document.createElement('a');
    elem3Edit.setAttribute('href', strAdminPageURL + '?action=edit&id=' + intGroupID);
    elem3EditText = document.createTextNode("Edit");
    elem3Edit.appendChild(elem3EditText);
    var elem3Copy = document.createElement('a');
    elem3Copy.setAttribute('onclick', "CopySiteTemplate('" + intGroupID + "')");
    elem3Copy.setAttribute('href', '#');
    elem3CopyText = document.createTextNode("Copy");
    elem3Copy.appendChild(elem3CopyText);
    var elem3Export = document.createElement('a');
    elem3Export.setAttribute('href', strExportURL + '?action=exportgroup&id=' + intGroupID);
    elem3ExportText = document.createTextNode("Export");
    elem3Export.appendChild(elem3ExportText);
    var elem3Delete = document.createElement('a');
    elem3Delete.setAttribute('onclick', "DeleteSiteTemplate('" + intGroupID + "'," + "this.parentNode.parentNode.parentNode.getAttribute('id').replace(strTableRowPrefix,'')" + ")");
    elem3Delete.setAttribute('href', '#');
    elem3DeleteText = document.createTextNode("Delete");
    elem3Delete.appendChild(elem3DeleteText);
    txtSpacer  = document.createTextNode(" : ");
    txtSpacer2 = document.createTextNode(" : ");
    txtSpacer3 = document.createTextNode(" : ");
    elem3.appendChild(elem3Edit);
    elem3.appendChild(txtSpacer);
    elem3.appendChild(elem3Copy);
    elem3.appendChild(txtSpacer2);
    elem3.appendChild(elem3Export);
    elem3.appendChild(txtSpacer3);
    elem3.appendChild(elem3Delete);
    // Send to table row
    arrRowData = new Array(elem1, elem2, elem3);
    setTimeout("libAddTableRow('tblTemplateGroupsBody', arrRowData)", 1000);
    // Confirm
    libAjaxMsg('ajaxStatus', 'info', 'Added new group: ' + strGroupName);
  }

/* ** Comments ** */

  function AddComment(strType, intItemID, strContent, intUserID, strGuestData) {
    url = strHandlerURL + '?action=addcomment&sid=' + strSID + '&ip=' + strIP + '&parenttype=' + strType + '&itemid=' + intItemID + '&content=' + escape(strContent) + '&userid=' + intUserID + strGuestData;
    ajax_get(url, 'AddComment', 'ajaxStatus', strAJAXURL);
  }
  function DeleteComment(intCommentID) {
    if (window.confirm("Are you sure you wish to delete this comment?")) {
      url = strHandlerURL + '?action=deletecomment&sid=' + strSID + '&ip=' + strIP + '&id=' + intCommentID;
      ajax_get(url, 'DeleteComment', 'ajaxStatus', strAJAXURL);
    }
  }

/* ** Article/File Commands ** */

  function MarkArticle(intArticleID) {
    url = strHandlerURL + '?action=markarticle&sid=' + strSID + '&ip=' + strIP + '&id=' + intArticleID;
    ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
  }
  function MarkFile(intFileID) {
    url = strHandlerURL + '?action=markfile&sid=' + strSID + '&ip=' + strIP + '&id=' + intFileID;
    ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
  }
  function RestoreArticle(intArticleID) {
    url = strHandlerURL + '?action=restorearticle&sid=' + strSID + '&ip=' + strIP + '&id=' + intArticleID;
    ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
  }
  function RestoreArticleConf(intArticleID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to restore this article?")) {
      url = strHandlerURL + '?action=restorearticle&sid=' + strSID + '&ip=' + strIP + '&id=' + intArticleID;
      ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  function RestoreFile(intFileID) {
    url = strHandlerURL + '?action=restorefile&sid=' + strSID + '&ip=' + strIP + '&id=' + intFileID;
    ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
  }
  function RestoreFileConf(intFileID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to restore this file?")) {
      url = strHandlerURL + '?action=restorefile&sid=' + strSID + '&ip=' + strIP + '&id=' + intFileID;
      ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  function LockArticle(intArticleID) {
    url = strHandlerURL + '?action=lockarticle&sid=' + strSID + '&ip=' + strIP + '&id=' + intArticleID;
    ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
  }
  function UnlockArticle(intArticleID) {
    url = strHandlerURL + '?action=unlockarticle&sid=' + strSID + '&ip=' + strIP + '&id=' + intArticleID;
    ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
  }
  function DeleteArticle(intArticleID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this article?")) {
      url = strHandlerURL + '?action=deletearticle&sid=' + strSID + '&ip=' + strIP + '&id=' + intArticleID;
      ajax_get(url, 'DeleteArticle', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  function DeleteFile(intFileID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this file?")) {
      url = strHandlerURL + '?action=deletefile&sid=' + strSID + '&ip=' + strIP + '&id=' + intFileID;
      ajax_get(url, 'DeleteFile', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  function DeleteAllContent() {
    if (window.confirm("Are you sure you wish to delete all articles that are currently marked for deletion?")) {
      url = strHandlerURL + '?action=deleteallcontent&sid=' + strSID + '&ip=' + strIP;
      ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
    }
  }
  function RestoreAllContent() {
    if (window.confirm("Are you sure you wish to restore all articles that are currently marked for deletion?")) {
      url = strHandlerURL + '?action=restoreallcontent&sid=' + strSID + '&ip=' + strIP;
      ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
    }
  }
  function DeleteAllFiles() {
    if (window.confirm("Are you sure you wish to delete all files that are currently marked for deletion?")) {
      url = strHandlerURL + '?action=deleteallfiles&sid=' + strSID + '&ip=' + strIP;
      ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
    }
  }
  function RestoreAllFiles() {
    if (window.confirm("Are you sure you wish to restore all files that are currently marked for deletion?")) {
      url = strHandlerURL + '?action=restoreallfiles&sid=' + strSID + '&ip=' + strIP;
      ajax_get(url, 'ArticleCommand', 'ajaxStatus', strAJAXURL);
    }
  }
  
/* ** Admin ** */

  function DeleteArea(intAreaID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this area?")) {
      url = strHandlerURL + '?action=deletearea&sid=' + strSID + '&ip=' + strIP + '&id=' + intAreaID;
      ajax_get(url, 'DeleteArea', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }

  function DeleteUser(strUserID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this user?")) {
      url = strHandlerURL + '?action=deleteuser&sid=' + strSID + '&ip=' + strIP + '&id=' + strUserID;
      ajax_get(url, 'DeleteUser', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }

  function DeleteUserSession(strSessionID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this user session?")) {
      url = strHandlerURL + '?action=deletesession&sid=' + strSID + '&ip=' + strIP + '&id=' + strSessionID;
      ajax_get(url, 'DeleteUserSession', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  
  function DeleteAllExpiredSessions() {
    if (window.confirm("Are you sure you wish to delete all expired sessions?")) {
      url = strHandlerURL + '?action=deleteallexpiredsessions&sid=' + strSID + '&ip=' + strIP;
      ajax_get(url, 'DeleteAllExpiredSessions', 'ajaxStatus', strAJAXURL);
    }
  }

  function DeleteFormRecipient(strRecipientID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this form recipient?")) {
      url = strHandlerURL + '?action=deleteformrecipient&sid=' + strSID + '&ip=' + strIP + '&id=' + strRecipientID;
      ajax_get(url, 'DeleteFormRecipient', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  
  function DeleteCustomLink(intLinkID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this custom link?")) {
      url = strHandlerURL + '?action=deletecustomlink&sid=' + strSID + '&ip=' + strIP + '&id=' + intLinkID;
      ajax_get(url, 'DeleteCustomLink', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }
  
/* Site Templates */

  function AddSiteTemplate(strFieldName) {
    var strGroupName = document.getElementById(strFieldName).value;
    if (strGroupName == "") {
      libAjaxMsg('ajaxStatus', 'error', 'Please fill in a name!');
      return;
    }
    url = strHandlerURL + '?action=newsitetpl&sid=' + strSID + '&ip=' + strIP + '&name=' + escape(strGroupName);
    ajax_get(url, 'AddSiteTemplate', 'ajaxNewGroupID', strAJAXURL);
    setTimeout("ClearSiteTemplateFields()", 1000);
  }

  function CopySiteTemplate(intGroupToCopy) {
    strNewGroupName = window.prompt("Please enter a name for the new group.");
    if (strNewGroupName) {
      document.getElementById('txtNewGroupName').value = strNewGroupName;
      url = strHandlerURL + '?action=copysitetpl&sid=' + strSID + '&ip=' + strIP + '&name=' + escape(strNewGroupName) + '&groupid=' + intGroupToCopy;
      ajax_get(url, 'CopySiteTemplate', 'ajaxNewGroupID', strAJAXURL);
      setTimeout("ClearSiteTemplateFields()", 1000);
    }
  }

  function ApplySiteTemplate(intGroupID) {
    if (window.confirm("Are you sure you wish to apply this template to your site?")) {
      url = strHandlerURL + '?action=applysitetpl&sid=' + strSID + '&ip=' + strIP + '&id=' + intGroupID;
      ajax_get(url, 'ApplySiteTemplate', 'ajaxStatus', strAJAXURL);
    }
  }

  function DeleteSiteTemplate(intGroupID, intRowID) {
    if (window.confirm("Are you sure you wish to delete this site template?")) {
      url = strHandlerURL + '?action=delsitetpl&sid=' + strSID + '&ip=' + strIP + '&id=' + intGroupID + '&row=' + intRowID;
      ajax_get(url, 'DeleteSiteTemplate', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow('tblTemplateGroupsBody', intRowID);
      setTimeout("ClearSiteTemplateFields()", 1000);
    }
  }

  function ClearSiteTemplateFields() {
    document.getElementById('txtNewGroupName').value = "";
    document.getElementById('ajaxStatus').innerHTML = "";
    document.getElementById('ajaxNewGroupID').innerHTML = "";
  }
  
/* Page Templates */

  function DeletePageTemplate(intTemplateID, intRowID, strTableName) {
    if (window.confirm("Are you sure you wish to delete this template?")) {
      url = strHandlerURL + '?action=deletepagetemplate&sid=' + strSID + '&ip=' + strIP + '&id=' + intTemplateID;
      ajax_get(url, 'DeletePageTemplate', 'ajaxStatus', strAJAXURL);
      libDeleteTableRow(strTableName, intRowID);
    }
  }

  /* Check/uncheck */
  
  function ToggleCheckboxes(blnWhich) {
    var fields = document.getElementsByTagName('input');
    for (i=0; i<fields.length; i++) {
      if (fields[i].type == 'checkbox') {
        fields[i].checked = blnWhich;
      }
    }
  }

  function TogglePermissionCheckboxes(strName, blnWhich) {
    j = 0;
    var arrFields = new Array();
    var labels = document.getElementsByTagName('label');
    for (i=0; i<labels.length; i++) {
      if (labels[i].innerHTML == strName) {
        strFieldID = labels[i].id;
        arrFields[j] = strFieldID.replace('lbl', '');
        j++;
      }
    }
    var fields = document.getElementsByTagName('input');
    for (i=0; i<fields.length; i++) {
      if (fields[i].type == 'checkbox') {
        for (j=0; j<arrFields.length; j++) {
          if (arrFields[j] == fields[i].value) {
            fields[i].checked = blnWhich;
          }
        }
      }
    }
  }
  
/* Insert at current cursor position */

  function insertAtCursor(strFieldName, strValue) {
    elem = document.getElementById(strFieldName);
    if (document.selection) { // IE
      elem.focus();
      sel = document.selection.createRange();
      sel.text = strValue;
      elem.focus();
    } else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox/Mozilla/Netscape
      var startPos = elem.selectionStart;
      var endPos = elem.selectionEnd;
      elem.value = elem.value.substring(0, startPos)
      + strValue
      + elem.value.substring(endPos, elem.value.length);
      elem.focus();
      elem.selectionStart = startPos + strValue.length;
      elem.selectionEnd = startPos + strValue.length;
    } else {
      elem.value += strValue;
      elem.focus();
    }
  }

  function selectFieldData(elem) {
    elem.focus();
    elem.select();
  }

/* WYSIWYG */

  function getDocument() {
    var eframe = document.getElementById(strEditorID);
    if (!eframe) {
      return null;
    }
    if (eframe.contentDocument) {
      return eframe.contentDocument;
    } else {
      return eframe.contentWindow.document;
    }
  }
  function getSelectedText() {
    var objSel;
    if (objEditor.getSelection) { // all except IE
      strSelText = objEditor.getSelection();
    } else if (objEditor.document.selection) { // IE
      //objEditor.focus();
      objSel = objEditor.document.selection.createRange();
      strSelText = objSel.text;
    } else {
      strSelText = "";
    }
    return strSelText;
  }
  // ** importNode for IE ** //
  if (typeof document.importNode != "function") {
    document.importNode = function(importedNode, deep) {
    var newNode;
    if (importedNode.nodeType == 1) { // Node.ELEMENT_NODE
      newNode = document.createElement(importedNode.nodeName);
      for (var i = 0; i < importedNode.attributes.length; i++){
        var attr = importedNode.attributes[i];
        if (attr.nodeValue != null && attr.nodeValue != '') {
          newNode.setAttribute(attr.name, attr.nodeValue);
        }
      }
      if (typeof importedNode.style != "undefined")
        newNode.style.cssText = importedNode.style.cssText;
    } else if(importedNode.nodeType == 3) { // Node.TEXT_NODE
      newNode = document.createTextNode(importedNode.nodeValue);
    }
    if (deep && importedNode.hasChildNodes()){
      for(var i = 0; i < importedNode.childNodes.length; i++) {
        newNode.appendChild(
        document.importNode(importedNode.childNodes[i], true)
        );
      }
    }
    return newNode;
    }
  }
  // ** Standard insert HTML code ** //
  function InsertIntoEditor(strHTML) {
    if (document.all) {
      insertNodeAtSelection(document.frames('txtContent'), strHTML);
    } else {
document.getElementById("txtContent").contentWindow.document.execCommand('insertHTML', false, strHTML);
    }
  }
  // ** etc ** //
  function insertNodeAtSelection(win, insertNode) {
    if (win.getSelection) { // all except IE
      sel = win.getSelection();
      range = sel.getRangeAt(0);
      sel.removeAllRanges();
      range.deleteContents();
      var container = range.startContainer;
      var pos = range.startOffset;
      range = document.createRange();
      if (container.nodeType==3 && insertNode.nodeType==3) {
        // if we insert text in a textnode, do optimized insertion
        container.insertData(pos, insertNode.nodeValue);
        // put cursor after inserted text
        range.setEnd(container, pos+insertNode.length);
        range.setStart(container, pos+insertNode.length);
      } else {
        var afterNode;
        if (container.nodeType == 3) {
          // when inserting, create 2 new nodes and put insertNode in the middle
          var textNode = container;
          container = textNode.parentNode;
          var text = textNode.nodeValue;
          // text before the split
          var textBefore = text.substr(0,pos);
          // text after the split
          var textAfter = text.substr(pos);
          var beforeNode = document.createTextNode(textBefore);
          afterNode = document.createTextNode(textAfter);
          //win.execCommand("insertHTML", false, beforeNode + insertNode.innerHTML + afterNode);
          //var ed = getDocument();
////document.getElementById("txtContent").contentWindow.document.execCommand('insertHTML', false, "Hello");
          // insert the 3 new nodes before the old one
          /*
          container.insertBefore(afterNode, textNode);
          container.insertBefore(insertNode, afterNode);
          container.insertBefore(beforeNode, insertNode);
          // remove the old node
          container.removeChild(textNode);
          */
        } else {
          afterNode = container.childNodes[pos];
          container.insertBefore(insertNode, afterNode);
        }
        range.setEnd(afterNode, 0);
        range.setStart(afterNode, 0);
        sel.addRange(range);
      }
    } else if (win.document.selection) { // IE
      win.focus();
      sel = win.document.selection.createRange();
      sel.pasteHTML(insertNode); // insertHTML in other browsers
    }
  }
  
/* Template variables */

  function showVarDesc(strListName, intListCount) {
    elem = document.getElementById(strListName);
    if (elem.options.selectedIndex > -1) {
      intSel = elem.options.selectedIndex;
      strVar = elem.options[intSel].value;
      for (i=0; i<intListCount; i++) {
        document.getElementById(strListName + 'Desc' + i).style.display = 'none';
      }
      document.getElementById(strListName + 'Desc' + intSel).style.display = 'block';
    }
  }
  
  function addVariable(strListName, strFieldName) {
    elem = document.getElementById(strListName);
    if (elem.options.selectedIndex > -1) {
      strVar = elem.options[elem.options.selectedIndex].value;
      insertAtCursor(strFieldName, strVar);
      elem.focus(); // doesn't solve the scrolling problem...
    }
  }

/* Post buttons */

  function doSimpleCMSCode(control, desc, tag) {
    elem = document.getElementById(control);
    strText = window.prompt("Enter the " + desc + " text", desc + " text");
    strValue = "[" + tag + "]" + strText + "[/" + tag + "]";
    insertAtCursor(control, strValue);
  }

  function doLinkCMSCode(control) {
    elem = document.getElementById(control);
    strLinkAddress = window.prompt("Enter the address of the link (omit http:// if this is a relative link)", "http://");
    strLinkTextDefault = strLinkAddress.replace("http://", "");
    strLinkText = window.prompt("Enter the clickable text", strLinkTextDefault);
    strValue = "[link=" + strLinkAddress + "]" + strLinkText + "[/link]";
    insertAtCursor(control, strValue);
  }
  
  function doImageCMSCode(control) {
    elem = document.getElementById(control);
    strImageAddress = window.prompt("Enter the address of the image (omit http:// if this is a relative link)", "http://");
    strImageDescDefault = strImageAddress.replace("http://", "");
    strImageDesc = window.prompt("Enter a description of the image", strImageDescDefault);
    strValue = "[img src=" + strImageAddress + "]" + strImageDesc + "[/img]";
    insertAtCursor(control, strValue);
  }

/* Random images */

  function Mixer(intLimit) {
    var i = Math.round(intLimit*Math.random());
    if (i == 0) {
      i = Mixer(intLimit);
    }
    return i;
  }

  function MixField(varField, intLimit) {
    var el = document.getElementById(varField);
    var i = Mixer(intLimit);
    if (el.src == (arrImages[i-1].src)) {
      i = Mixer(intLimit);
      while (el.src == (arrImages[i-1].src)) {
        i = Mixer(intLimit);
      }
    }
    el.src = arrImages[i-1].src;
  }
  
  function preloadImages() {
    var arrImages = new Array();
    for (i=0; i<preloadImages.arguments.length; i++) {
      arrImages[i] = new Image();
      arrImages[i].src = preloadImages.arguments[i];
    }
    return arrImages;
  }

/* Cookies */

  function createCookie(name,value,days) {
  	if (days) {
  		var date = new Date();
  		date.setTime(date.getTime()+(days*24*60*60*1000));
  		var expires = "; expires="+date.toGMTString();
  	} else {
      var expires = "";
    }
    value = escape(value);
  	document.cookie = name+"="+value+expires+"; path=/";
  }

  function readCookie(name) {
  	var nameEQ = name + "=";
  	var ca = document.cookie.split(';');
  	for(var i=0;i < ca.length;i++) {
  		var c = ca[i];
  		while (c.charAt(0)==' ') c = c.substring(1,c.length);
  		if (c.indexOf(nameEQ) == 0) {
        value = c.substring(nameEQ.length,c.length);
        value = unescape(value);
        return value;
      }
  	}
  	return null;
  }

  function eraseCookie(name) {
  	createCookie(name,"",-1);
  }

/* Saving drafts */

  function SaveDraft(strType) {
    if (strType == "Article") {
      strTitle = document.getElementById("txtTitle").value;
      strBody  = document.getElementById("txtContent").value;
      if (strBody != "") {
        createCookie("ArticleTitle", strTitle, 1);
        createCookie("ArticleBody", strBody, 1);
        var date   = new Date();
        dteHours   = date.getHours();
        dteMinutes = date.getMinutes();
        dteSeconds = date.getSeconds();
        if (dteHours <= 9) {
          dteHours = "0" + dteHours;
        }
        if (dteMinutes <= 9) {
          dteMinutes = "0" + dteMinutes;
        }
        if (dteSeconds <= 9) {
          dteSeconds = "0" + dteSeconds;
        }
        strBodyCookie = readCookie("ArticleBody");
        if (strBody == strBodyCookie) {
          //document.getElementById("txtNewsContent").value = strBodyCookie;
          document.getElementById("strDraftSaved").innerHTML = 'Draft saved at ' + dteHours + ":" + dteMinutes + ":" + dteSeconds;
          document.getElementById("strDraftSaved").style.display = 'block';
        } else {
          document.getElementById("strDraftSaved").innerHTML = 'Error saving draft. Cookies may be disabled.';
          document.getElementById("strDraftSaved").style.display = 'block';
        }
      }
    }
  }
  
  function DeleteDraft(strType) {
    if (strType == "Article") {
      eraseCookie("ArticleTitle");
      eraseCookie("ArticleBody");
      eraseCookie("ArticleArea1");
      eraseCookie("ArticleArea2");
    }
  }

/* Miscellaneous */

  function reloadPage() {
    window.location.reload();
  }
  
  function EnlargeTextarea(strName) {
    elem = document.getElementById(strName);
    intRows = parseInt(elem.getAttribute('rows'));
    if (intRows >= 30) {
      window.alert("You cannot make this field any bigger.");
    } else {
      intRows = intRows + 3;
      elem.setAttribute('rows', intRows);
    }
  }

  function ShrinkTextarea(strName) {
    elem = document.getElementById(strName);
    intRows = parseInt(elem.getAttribute('rows'));
    if (intRows <= 6) {
      window.alert("You cannot make this field any smaller.");
    } else {
      intRows = intRows - 3;
      elem.setAttribute('rows', intRows);
    }
  }

  function EnlargeFrame(strName) {
    elem = document.getElementById(strName);
    strHeight = elem.style.height;
    strHeight.replace("px", "");
    intHeight = parseInt(strHeight);
    if (intHeight >= 500) {
      window.alert("You cannot make this field any bigger.");
    } else {
      intHeight = intHeight + 100;
      elem.style.height = intHeight + "px";
    }
  }

  function ShrinkFrame(strName) {
    elem = document.getElementById(strName);
    strHeight = elem.style.height;
    strHeight.replace("px", "");
    intHeight = parseInt(strHeight);
    if (intHeight <= 200) {
      window.alert("You cannot make this field any smaller.");
    } else {
      intHeight = intHeight - 100;
      elem.style.height = intHeight + "px";
    }
  }
