
  // These may be used by various functions/scripts on any page
  var pagePath = document.URL;
  pagePath = pagePath.replace(/^http:\/\/\w+\.adf\.org/, '');
  var pageDir = '/';
  if (pagePath.match(/^(.+)\//)) { pageDir = pagePath.match(/^(.+)\//)[1]; }

  // Eval is, apparently, evil; we should clean this up someday (sigh)
  function popup(url) {
    var day = new Date();
    var id = day.getTime();
    eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=420,height=300');");
  }

  // This kind of ugliness looks like I got it from somewhere -ART
  function get_cookie(cname) {
    var allcookies = document.cookie;
    var pos = allcookies.indexOf(cname + '=');
    if (pos != -1) {
      var start = pos + (cname.length + 1);         // start of value
      var end = allcookies.indexOf(";", start);     // end of value
      if (end == -1) { end = allcookies.length; }
      var value = allcookies.substring(start, end); // extract value
      return unescape(value);
    } else {
      return '';
    }
  }

  // To disable form submit when pressing Enter in text fields by
  // accident - force someone to actually click Submit button; taken
  // from blog post at http://tinyurl.com/2u2r94a; To use, add
  // onKeyPress="return disableEnterKey(event)" to <form> tag
  function disableEnterKey(e) {
    var key;
    if (window.event) { key = window.event.keyCode; } // for IE
    else { key = e.which; }                           // for Firefox
    return (key != 13);     // return false if Enter, true otherwise
  }

  // Determine if someone has edit rights for this page/folder;
  // uses global variables pagePath and pageDir, defined above
  function can_edit_page() {
    edit_perms_cookie = get_cookie('adf-edit-perms');
    if (edit_perms_cookie != '') {
      // See if this user has edit permission on this directory;
      // go through all dirs they have edit perms on and check
      permtrees = edit_perms_cookie.split(/,\s*/);
      for (var i = 0; i < permtrees.length; i++) {
        if (pageDir.indexOf(permtrees[i]) != -1) { return true; }
      }
    }
    return false;
  }

  // Function to preload images such as the tag edit progress bar;
  // www.mattfarina.com/2007/02/01/preloading_images_with_jquery
  jQuery.preloadImages = function() {
    for(var i = 0; i<arguments.length; i++) {
      jQuery("<img>").attr("src", arguments[i]);
    }
  }

  // Given a list of keywords as comma-separated text, convert to HTML
  // and return the result; used by keyword-editing related functions
  function keywordsTextToHTML (keywordsText) {
    var keywordsHTML = '';
    var keywordsList = keywordsText.split(/,\s*/);
    keywords_num = keywordsList.length;
    for (var i = 0; i < keywords_num; i++) {
      keywordsHTML +=
        '<a href="/cgi-bin/adf/web-search?searchin=keywords&keywords=';
      keywordsHTML += (keywordsList[i]).replace(/\s+/g, '%20');
      keywordsHTML += '">';
      keywordsHTML += keywordsList[i];
      keywordsHTML += '</a>, ';
    }
    return keywordsHTML.substring(0,
      (keywordsHTML.length -3)); // remove last ", "
  }

  // Everything in this is executed/defined when page is done loading
  $(document).ready( function(){

    // Preload any images that need to be ready to go
    $.preloadImages('/images/loading.gif');

    // Make it so in-page links scroll smoothly
    $.localScroll();

    // Make it so in-page doc sections are highlighted; see /styles.css
    $(".section_links > li > a").click(function () {
      $(".named_section").removeClass('sectionhighlight'); // remove hl
      var str = $(this).attr('href');             // str = #foo
      str = "h2[id='" + str.substring(1) + "']"; // build up selector
      $(str).parent().addClass('sectionhighlight'); // add highlight
    });
    $(".section_links > a").click(function () {
      $(".named_section").removeClass('sectionhighlight'); // remove hl
      var str = $(this).attr('href');             // str = #foo
      str = "h2[id='" + str.substring(1) + "']"; // build up selector
      $(str).parent().addClass('sectionhighlight'); // add highlight
    });

    // Make it so that any PDF, DOC, XLS, etc. links open in a new
    // window AND have an icon next to them warning the user of this
    $("a").filter(function() {
      return this.href.match(/\.(pdf|doc|docx|odt|wps|rtf|xls|ods|ppt|odp|pub)$/i);
    }).addClass('newwin').attr('target', '_new');

    // See if someone should see the Edit Page and Edit Folder links
    if (can_edit_page()) {
      var edit_links = '<a id="editlink" ';
      edit_links += 'href="/cgi-bin/adf/editors/site-editor?action=edit&';
      edit_links += 'frompage=1&parm=';
      edit_links += pagePath;
      edit_links += '">Edit Page</a> / <a id="editlink" ';
      edit_links += 'href="/cgi-bin/adf/editors/site-editor?';
      edit_links += 'action=browsewebdir&parm=';
      edit_links += pageDir;
      edit_links += '">Edit Folder</a> / ';
      $('#edit_page_section_links').html(edit_links);
    }

    // Add click handler for the Edit Keywords link
    $('#edit_keyword_link').click(function() {
      $('#edit_keyword_link_section').hide();
      $('#tags_label').hide();
      $('#tags').hide();
      $('#new_keywords_label').show();
      $('#new_keywords').val($('#tags').text());
      $('#new_keywords').show();
      $('#keyword_save').show();
      $('#keyword_cancel').show();
      $('#feedback').show();
    });

    // Add click handler for button which cancels edit keywords
    $('#keyword_cancel').click(function() {
      $('#edit_keyword_link_section').show();
      $('#tags_label').show();
      $('#tags').show();
      $('#new_keywords_label').hide();
      $('#new_keywords').hide();
      $('#keyword_save').hide();
      $('#keyword_cancel').hide();
      $('#feedback').text('');
      $('#feedback').hide();
    });

    // Make it so that hitting Enter in new keywords field submits; see
    // http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter
    $('#new_keywords').keydown(function(e) {
      if (e.keyCode == 13) {
        $('#keyword_save').click();
        return false; // so that IE doesn't beep (cancels key press)
      }
    });

    // Handler for the Save button in editing keywords...
    $('#keyword_save').click(function() {

      // Show the loading icon to show that click worked
      // but the server hasn't finished the action yet
      $('#feedback').html('<img src="/images/loading.gif" width="128" height="15" alt="Processing your request..."/>');

      var oldkeywords = $('#tags').text();
      var keywords = $('#new_keywords').val();
      $.ajax({
        type: 'POST',
        url: '/cgi-bin/adf/editors/site-editor',
        data: { 'keywords':keywords, 'origkeywords':oldkeywords, 
          'parm':pagePath, 'action':'keyword_save' },

        // error handling for network/parsing errors
        error: function (xhr, statusText, errorThrown) {

          if (xhr.status == 0) {
            $('#feedback').html(
              '<b>Tags NOT saved</b> - you appear to be offline');

          } else if (xhr.status == 500) {
            $('#feedback').html(
              '<b>Tags NOT saved</b> - a server error has occurred');

          } else if (xhr.status == 403) {
            $('#feedback').html(
              '<b>Tags NOT saved</b> - you are not a logged-in member');

          } else if (statusText == 'timeout') {
            $('#feedback').html(
              '<b>Tags NOT saved</b> - request timed out');

          } else if (statusText == 'parsererror') {
            $('#feedback').html(
              '<b>Tags NOT saved</b> - error parsing server response');

          } else {
            // don't want to put xhr.responseText bc that's an error page!
            $('#feedback').html('<b>Tags NOT saved</b> - response ' +
              xhr.status);
          }
        },

        // Handling if there are no outright errors - but there could
        // still be business logic errors, such as if someone has the
        // page checked out for editing, so we can't save the keywords
        success: function (data) {

          // Get details from the XML response sent by the script
          var responseStatus = $('status', data).text(); // success or error
          var responseMessage = $('message', data).html();  // detailed msg

          if (responseStatus == 'success') {

            var successMsg = responseMessage ? responseMessage : 'thanks!';
            $('#feedback').html('<b>Tags saved successfully</b> - ' + 
              successMsg);
            $('#feedback').show();
            $('#feedback').fadeOut(3000);

            $('#edit_keyword_link_section').show();
            $('#tags_label').show();
            $('#tags').show();
            $('#new_keywords_label').hide();
            $('#new_keywords').hide();
            $('#keyword_save').hide();
            $('#keyword_cancel').hide();

            $('#tags').html(keywordsTextToHTML(keywords));

          // covers responseStatus == 'error' - any not success = error
          } else {
            var errorMsg = responseMessage ? responseMessage : 'unknown error';
            $('#feedback').html('<b>Tags NOT saved</b> - ' + errorMsg);
          }

        }
      }); // end $.ajax block
    });   // end $('#keyword_save').click(function() block

  }); // document.ready handler

