  var sfgate_user        = sfgate_un();
  try {
    var sfgate_articleKey  = new ArticleKey(sfgate_file);
    var sfgate_userKey     = new UserKey(sfgate_user);
  } catch(err) {}

  var sfgate_rowsPerPage = 10;
  var cpp_value          = 10;
  sfgate_presetCSOandCPPValues();

  function sfgate_setCommentsPerPageCookie(withValue) {
    if(withValue == '10' || withValue == '20') {
      var nextyear = new Date();
        nextyear.setDate(nextyear.getDate() + 365);
        document.cookie = 'comments_per_pg=' + escape( withValue ) +
                  '; expires=' + nextyear.toUTCString() +
                  '; path=/' +
                  '; domain=.sfgate.com';
      document.getElementById('sfgate_comments_per_page').value = withValue;
    }
  }

  function sfgate_setSortOrderCookie(withValue) {
    if(withValue == 'TimeStampDescending' || withValue == 'TimeStampAscending') {
      var nextyear = new Date();
        nextyear.setDate(nextyear.getDate() + 365);
        document.cookie = 'comments_sort_order=' + escape( withValue ) +
                  '; expires=' + nextyear.toUTCString() +
                  '; path=/' +
                  '; domain=.sfgate.com';
//      sfgate_comment_sort_o.value = withValue;
    }
  }

  function sfgate_presetCSOandCPPValues() {
    var ccpp_cookie_text = document.cookie.indexOf('comments_per_pg');
    var defaultCPPValue  = 10;
    if (ccpp_cookie_text == -1) {
      cpp_value = defaultCPPValue;
    } else {
      cpp_value = document.cookie.substr(ccpp_cookie_text + 16);
      ccpp_terminatingCharIndex = cpp_value.indexOf(';');
      if(ccpp_terminatingCharIndex >= 0) {
        cpp_value = cpp_value.split(';')[0];
      }
    }

    var cso_cookie_text = document.cookie.indexOf('comments_sort_order');
    var defaultCSOValue = 'TimeStampAscending';
    if (cso_cookie_text == -1) {
      sort_value = defaultCSOValue;
    } else {
      sort_value = document.cookie.substr(cso_cookie_text + 20);
      cso_terminatingCharIndex = sort_value.indexOf(';');
      if(cso_terminatingCharIndex >= 0) {
        sort_value = sort_value.split(';')[0];
      }
    }

    sort_value = document.cookie.substr(cso_cookie_text + 20);
    var cso_cookie_text = document.cookie.indexOf('comments_sort_order')
    if (cso_cookie_text == -1) {
      sfgate_setSortOrderCookie('TimeStampAscending');
    }
    sort_value = document.cookie.substr(cso_cookie_text + 20);
    cso_terminatingCharIndex = sort_value.indexOf(';');
    if(cso_terminatingCharIndex >= 0) {
      sort_value = sort_value.split(';')[0];
    }
  }
  
  function sfgate_ArticleComments() {
    // if Pluck didn't return requesttypes.js (i.e. in maintenance mode), we can't display comments
    if(!sfgate_articleKey)
      return;

//  historyManager(sfgate_title);
    var requestBatch = new RequestBatch();
    requestBatch.AddToRequest(new UpdateArticleAction(sfgate_articleKey, 'http://sfgate.com/cgi-bin/article/article?f='+sfgate_file, sfgate_title, new Section(sfgate_section), sfgate_categories));
    requestBatch.AddToRequest(sfgate_articleKey);
    requestBatch.BeginRequest(sfgate_serverUrl, sfgate_ShowArticleComments);
  }

  function sfgate_ShowArticleComments(responseBatch) {
    var sfgate_article = null;
    if(responseBatch.Responses.length && responseBatch.Responses[0].Article != null) {
      sfgate_article = responseBatch.Responses[0].Article;
    }
    var sfgate_comment_question = '';
    var sfgate_commentCnt = 0;
    if (sfgate_article != null) {
      var sfgate_commentCnt = sfgate_article.Comments.NumberOfComments
    }
    if (sfgate_commentCnt > 0) {
      sfgate_topCnt.innerHTML    = '('+sfgate_commentCnt+')';
      sfgate_bottomCnt.innerHTML = '('+sfgate_commentCnt+')';
      if (sfgate_custom_label) {
        sfgate_comment_question = sfgate_custom_label;
      } else {
        sfgate_comment_question = sfgate_comment_label2;
      }
      if (!sfgate_isActive) {
        sfgate_comment_question += sfgate_comment_append2;
      }
    } else {
      sfgate_topCnt.innerHTML    = '(0)';
      sfgate_bottomCnt.innerHTML = '(0)';
      if (sfgate_custom_label) { 
        sfgate_comment_question = sfgate_custom_label;
        if (sfgate_isActive) {
          sfgate_comment_question += sfgate_comment_append1;
        } else {
          sfgate_comment_question += sfgate_comment_append2;
        }
      } else {
        if (sfgate_isActive) {
          sfgate_comment_question = sfgate_comment_label1;
        } else {
          sfgate_comment_question = 'Comments are closed.';
        }
      }
    }
    sfgate_question.innerHTML = sfgate_comment_question;
    if (sfgate_isActive) { sfgate_addlink_elm.innerHTML  = sfgate_addlink; }
    sfgate_viewlink_elm.innerHTML = sfgate_viewlink;
  }

  function historyManager(t) {
//alert("alert from the historyManager");
    frames["hFrame"].location.href='/cgi-bin/article/comments/ajaxhistory?f='+f+'&t='+t;
  }

  function historyFunc(f) {
    document.getElementByID('hFrame').innerHTML = "f";
  }

  function sfgate_clean_html(s) {
    var re = /<[^>]*>/g;
    if ( re.test(s) ) {
        s = s.replace(re,'');
        s = '[html markup was removed from this comment] '+s;
    }
    return s;
  }

  function sfgate_SubmitComments(form) {
    if (!sfgate_un()) {sfgate_reports_elm.innerHTML = 'Your session has expired! Please login.'; sfgate_disableForm(); return false; }
    if (sfgate_user != sfgate_un()) { if (sfgate_RenewUserKey()) {} else {return false;} }
    var requestBatch = new RequestBatch();
    requestBatch.AddToRequest(sfgate_userKey);
    requestBatch.AddToRequest(new CommentAction(sfgate_articleKey, '/cgi-bin/article.cgi?f='+sfgate_file, sfgate_page_title, sfgate_clean_html(form.comment.value)));
    requestBatch.AddToRequest(new CommentPage(sfgate_articleKey, 1, sfgate_rowsPerPage, "TimeStampAscending"));
    requestBatch.BeginRequest(sfgate_serverUrl, sfgate_HandleSubmitComments);
    return false;
  }

  function sfgate_SubmitRecomendation(key) {
    if (sfgate_un() && sfgate_user != sfgate_un()) { if (sfgate_RenewUserKey()) {} else {return false;} }
    var requestBatch = new RequestBatch();
    requestBatch.AddToRequest(sfgate_userKey);
    requestBatch.AddToRequest(new RecommendAction(new CommentKey(key)));
    requestBatch.AddToRequest(new CommentPage(sfgate_articleKey, sfgate_rowsPerPage, sfgate_page, "TimeStampAscending"));
    requestBatch.BeginRequest(sfgate_serverUrl, sfgate_HandleComments);
  }

  function sfgate_HandleSubmitComments(responseBatch) {
try { console.log(responseBatch); } catch(err) {}
    var re = /^.*\(for example: (.+)\).*$/;
    for(var i = 0; i < responseBatch.Messages.length; i++) {
      if (responseBatch.Messages[i].Message.match(re)) {
        var bwords = RegExp.$1;
        if((bwords) && bwords != '') {
          var form_header_bad_words = 'Your submission included words not permitted by our language filter (for example: '+bwords+'). Please avoid use of inappropriate language on our site in the future. Thanks.';
         sfgate_form_verbiage.innerHTML = '<h4>Add Your Comment</h4><h4 class="error">Comment Not Posted</h4><p class="error">'+form_header_bad_words+'</p>';
          return false;
        }
      }
    }

    // if we reach this point, there is no "bad word" error in the response message array.

    // the following line is assumed to work, depending on message/response permutations received from Pluck
    if(responseBatch.Messages[0].Message != 'okay' && responseBatch.Messages[0].Message != 'ok') {
      var appendedMessages      = '<span style="font-style: italic; background-color: #D0D0D0;">';

      for(var i = 0; i < responseBatch.Messages.length; i++) {
        appendedMessages += '<font style="font-weight: bold;">[' + i + ']</font> ' + responseBatch.Messages[i].Message + '<br />';
      }
      appendedMessages += '</span>';

      var form_header_error_verbiage = 'Apologies for the inconvenience but we are unable to submit this comment due to a technical system glitch. We are actively working to correct this issue. Thanks for your patience.';
// 'Your submission was not processed due to an error. <br />' + appendedMessages + ...
      sfgate_form_verbiage.innerHTML = '<h4>Add Your Comment</h4><h4 class="error">Comment Not Posted</h4><p class="error">'+form_header_error_verbiage+'</p>';
      return false;
    }

    var gotopage = 1;
/*
    if (responseBatch.Responses[1] &&
        responseBatch.Responses[1].CommentPage &&
        responseBatch.Responses[1].CommentPage.NumberOfComments > sfgate_rowsPerPage) {
      gotopage = Math.ceil(responseBatch.Responses[1].CommentPage.NumberOfComments / cpp_value);
    }
*/
    window.location = '/cgi-bin/article/comments/view?f='+sfgate_file+'&o='+gotopage;
    return false;
  }

  function sfgate_RenewUserKey() {
    if (confirm('You are logged in as '+sfgate_un()+' not '+sfgate_user+'. Is this OK?')) {
      sfgate_user    = sfgate_un();
      sfgate_userKey = new UserKey(sfgate_user);
      return true;
    }
    return false;
  }

  function sfgate_HandleResponseMessages(responseBatch) {
    for (var i=0; i < responseBatch.Messages.length; i++) {
      sfgate_appendError('MessageTime:' + responseBatch.Messages[i].MessageTime);
      sfgate_appendError('Message ' + i + ':' + responseBatch.Messages[i].Message);
    }
    sfgate_printErrors();
  }
  
  function sfgate_DrawCommentsHeader(commentpage) {
    var sfgate_commentCnt = 0;
    if (commentpage != null) {
      var sfgate_commentCnt = commentpage.NumberOfComments;
    }
    if (sfgate_commentCnt > 0) {
      sfgate_topCnt.innerHTML = '('+sfgate_commentCnt+')';
    } else {
      sfgate_topCnt.innerHTML = '(0)';
    }
  }

  var sfgate_ResponseErrors = new Array(); // array used to collect respons errors/messages

  function sfgate_appendError(errorMessage) {
    if(!sfgate_useErrors) {return;}
    sfgate_ResponseErrors.push(errorMessage);
  }

  function sfgate_printErrors() {
    if(!sfgate_useErrors) {return;}
    var sfgate_collectedErrors = 'RESPONSE ERRORS/MESSAGES:';
    for (var i=0; i < sfgate_ResponseErrors.length; i++) {
      sfgate_collectedErrors += '<br />'+sfgate_ResponseErrors[i];
    }
    sfgate_errors_elm.innerHTML = sfgate_collectedErrors;
    sfgate_ResponseErrors = new Array();
  }

  function sfgate_enableForm() {
    sfgate_comment_input.disabled = false;
    sfgate_submit_button.disabled = false;
    sfgate_form_verbiage.innerHTML = form_header;
    sfgate_counter_input.style.visibility = 'visible';
  }

  function sfgate_disableForm() {
    sfgate_comment_input.disabled = true;
    sfgate_submit_button.disabled = true;
    sfgate_form_verbiage.innerHTML = loginorreg;
    sfgate_counter_input.style.visibility = 'hidden';
  }

  function sfgate_setFormState() {
    if(sfgate_un()) {sfgate_enableForm()} else {sfgate_disableForm()}
  }


