// copyright 2004 Google.com


/*
 * Comment()
 * 
 * For storing comments-related info in page scope.
 */
var Comment = new Object();
Comment.TOGGLE_ID = 'btnAll';
Comment.allVisible = true;

var OID_PROVIDER_COOKIE = "preferredOpenIDProvider";
var OID_PROVIDER_COOKIE_TTL = 60*60*24*1000;

/*
 * On body load, initialize all event handlers.
 */
window.onload = function() {
  initAllComments();
  // Don't change focus to form fields during load to prevent a harmless
  // error from appearing in Mozilla's JavaScript console.
  // Implemented with a global instead of an argument so that
  // show*Form methods stay as event handlers.

  Comment.preserveFocus = true;

  Comment.preserveFocus = false;

  if (SCROLL_TO_PREVIEW) {
    scrollToPreview();
  } else if (!IS_POPUP) {
    // setting focus scrolls to the bottom if done in popup, which we don't
    // want.
    var commentBody = d('comment-body');
    if (commentBody) commentBody.focus();
  }

  // Set the openIDProvider to whatever they chose last time.
  var oidProvider = GetCookie(OID_PROVIDER_COOKIE) || "google";
  var oidSelector = document.getElementById("oidProviderSelect");

  // only show if the user is not logged into google
  if (oidProvider && oidSelector) {
    oidSelector.value = oidProvider;

    // Don't set the radio button. It's set by default to the correct thing
    // which may not be "Sign-in using" if the user is previewing an anonymous
    // comment
    selectOpenIdProvider(oidProvider, false);
  }

  // initialize the default "empty" text box labels.
  if (d('uurl')) {
    d('uurl').emptyValue = d('uurl').value;
  }

  // BiG can have anon login but still not have openId
  if (d('rawOpenId')) {
    d('rawOpenId').emptyValue = d('rawOpenId').value;
  }

  // Initiates Blogger's page unload form check mechanism.
  try {
    cleanForm();
  } catch(e) {}
}

function clearUnusedAnonUrl() {
   if (d('iden-other') && !d('iden-other').checked) {
     d('uurl').value = "";
   }
}

/*
 * If you have selected an OpenID provider, this fuction transforms your
 * username into an openIdUrl appropriate for the selected provider and
 * sets the hidden form input value for "openIdIdentifier" to this url.
 */
function constructOpenIdIdentifier() {
  var oidProviderEl = d("openIdProvider");

  if (!oidProviderEl) return; // If the user has not enabled OpenID, skip it.

  var oidProvider = oidProviderEl.value;
  
  var rawIdEl = d("rawOpenId");
  var rawId = rawIdEl.value;

  var targetEl = d("openIdIdentifier");
  //If the user provides an empty string or a full OP url, leave as-is
 
  if (rawId.toLowerCase().indexOf("http://") != -1 || rawId.length == 0) {
    targetEl.value = rawId;
    return;
  }

  targetEl.value = openIdUrlFor(oidProvider, rawId);
}

/*
 * Generate an OpenID url string, either for preview or for submitting.  This
 * method is called on valuechange and key events for the openid text field,
 * as well as when the form is finally submitted.
 * @param oidProvider the short name of the selected provider
 * @rawId the id entered into the text field.
 * @preview boolean- this determines whether or not to <strong> the rawId
 */
function openIdUrlFor(oidProvider, rawId, preview) {

  if ("openid" == oidProvider) {
    return rawId;
  }

  var url = "";
  if (rawId != rawOpenIdEmptyValue && rawId != rawOpenIdEmptyUrlValue) {
    rawId = UrlEncode(rawId);
  }

  if (preview) {
    if (rawId == "") {
      if (oidProvider == "openid") {
        rawId = rawOpenIdEmptyUrlValue; 
      } else {
        rawId = rawOpenIdEmptyValue;
      }
    }
    rawId = "<strong>" + rawId + "</strong>";
  }
  
  if ("aol" == oidProvider) {
    url = "http://openid.aol.com/" + rawId;
  } else if ("lj" == oidProvider) {
    url = "http://" + rawId + ".livejournal.com";
  } else if ("typekey" == oidProvider) {
    url = "http://profile.typekey.com/" + rawId;
  } else if ("wp" == oidProvider) {
    url = "http://" + rawId + ".wordpress.com";
  }
  
  return url;
}

/*
 * Initializes all comments to be toggleable
 */
function initAllComments() {
  var dtNodes = document.getElementsByTagName("DT");
  var ddNodes = document.getElementsByTagName("DD");

  for (var i = 0; i < dtNodes.length; i++) {
    initComment(dtNodes[i], ddNodes[i]);
  }
}

/* 
 * Setup a comment to be able to toggle itself when it's header is clicked
 */
function initComment(dt, dd) {
  dt.dd = dd;

  if (dt.id != "preview-header") {
    dt.onclick = dtClickHandler;
  }
}

/* 
 * Handle the click of a comment header. Toggle the comment body and scroll
 * if in a popup window.
 */
function dtClickHandler() {
  toggleComment(this);
  
  // Popup windows are tiny.  Scroll a bit up and down to help with each click.
  if (IS_POPUP) {
    var scrollAmt = this.className == "collapsed" ? 22 : -22;
    window.scroll(0, getScrollOffset() + scrollAmt);
  }
}

/**
 * You can specify whether or not to have this change the "Sign-in using" radio
 * for you so deciding to switch from Nickname to Sign-in using AOL doesn't take
 * two clicks. You can prevent this behavior if (for example) you're
 * repopulating the form after preview/error and you want to keep the old
 * selection checked. (This method is called in onload)
 */
function selectOpenIdProvider(idp, changeSignInTypeRadio, changeDropDown) {
  var idEl = d('openIdProvider');
  if (!idEl) {
    return;
  }

  if (changeSignInTypeRadio) {
    showOpenId();  
  }

  idEl.value = idp;

  if (changeDropDown) {
    d('openIdDropDown').value = idp;
  }
  
  d("lj-icon").className = null;
  d("aol-icon").className = null;
  d("wp-icon").className = null;
  d("openid-icon").className = null;
  d("typekey-icon").className = null;

  //set the client-side cookie to save this choice
  SetCookie(OID_PROVIDER_COOKIE, idp, OID_PROVIDER_COOKIE_TTL, "/");
  if (idp == "openid") {
    d("openIdUrlPreviewWrapper").style.display = "none";
  } else {
    d("openIdUrlPreviewWrapper").style.display = "block";
  }

  if (d("rawOpenId").value == rawOpenIdEmptyValue || 
      d("rawOpenId").value == rawOpenIdEmptyUrlValue) {
    if (idp == "openid") {
      d("rawOpenId").value = rawOpenIdEmptyUrlValue;
    } else {
      d("rawOpenId").value = rawOpenIdEmptyValue;
    }
  }
  updateOpenIdUrlPreview();
}

function updateOpenIdUrlPreview() {
  var url = openIdUrlFor(d("openIdProvider").value, d("rawOpenId").value, true);
  d("openIdUrlPreview").innerHTML = url;
}

/*
 * Handles the click of the anchor which says "collapse comments" and "show all 
 * comments" The text toggles back and forth each time the anchor is clicked,
 * as does the display of all comments.
 */
function toggleAllComments() {
  var toggler = d(Comment.TOGGLE_ID);
  var dtNodes = document.getElementsByTagName("DT");
  var show = !Comment.allVisible;

  // In the case of hide, we don't toggle the last set, it always stays on :)
  var max = show ? dtNodes.length : dtNodes.length - 1;

  for (var i = 0; i < max; i++) {
    toggleComment(dtNodes[i], show);
  }

  if (show) {
    toggler.innerHTML = COLLAPSE_MSG;
  } else {
    toggler.innerHTML = SHOW_ALL_MSG;
  }

  Comment.allVisible = show;
}

/* 
 * Show or hide a comment. If show is not specified, toggles the current value.
 */
function toggleComment(dt, show) {
  if (typeof(show) == "undefined") {
    show = dt.className == "collapsed";
  }

  var className = show ? "" : "collapsed";

  dt.className = className;
  dt.dd.className = className;
}

/*
 * Brings the comment preview into view
 */
function scrollToPreview() {
  var prev = getPreview();
  var pos = getXY(prev[0]);
  window.scroll(0, pos.y - 200);
}

/*
 * Hides the preview container and moves the scrollbar back to the top of the 
 * page.
 */
function hidePreview() {
  var previewArr = getPreview();
  hideElement(previewArr[0]);
  hideElement(previewArr[1]);
  window.scroll(0, 0);

  // Need to focus on the window after a scroll in Firefox. Otherwise giving
  // the comment body focus doesn't do anything.
  window.focus();
  d('comment-body').focus();
} 


/*
 * Returns an array containing the last items in the comment collection. The 
 * last items are presumed to be the preview items.
 */
function getPreview() {
  var dt = d('preview-header');
  var dd = d('preview-main');
  return [dt, dd];
}


/*
 * Toggles the display of the original post.
 */
function togglePostBody() {
  var bod = d('cpost-body');
  var dest = d('cpost-display');
  var cmtToggle = d(Comment.TOGGLE_ID);
  var btnPost = d('btnPost');
  var container = d('cpost-container');

  if (container.style.display == 'none') {
    dest.innerHTML = bod.innerHTML;
    try {cmtToggle.style.display = 'none';} catch(e) {}
    btnPost.innerHTML = HIDE_ORIG_MSG;
    showElement(container);
  } else {
    dest.innerHTML = '';
    try {cmtToggle.style.display = 'block';} catch(e) {}
    btnPost.innerHTML = SHOW_ORIG_MSG;
    hideElement(container);
  }
}

/*
 * Returns the number of pixels the document is currently scrolled by.
 */
function getScrollOffset() {
  if (document.all) {
    return document.body.scrollTop;
  } else {
    return window.pageYOffset;
  }
}


function switchForm(el) {
  showForm(el.value);
}

function showForm(formName) {
  var form = d('commentForm');
  form.className = 'show-' + formName + '-form';
}

/**
 * Handler for radio button labels to simulate clicking on their associated
 * radio button.
 */
function pressRadio(el) {
  var button = d(el.getAttribute('for'));
  if (button) {
    button.checked = true;
    switchForm(button);
    return false;
  }

  return true;
}

/*
 * Your typical everyday popupper, with a twist; close the window if already
 * open so that the new window is guaranteed to come out on top.
 */
function popUp(URL) {
  if (window.popup) { 
    try {
      window.popup.close();
    } catch(e) {}
  }

  window.popup = window.open(URL, 'bloggerPopup', 
		'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,' + 
    'width=770,height=550');
}

/*
 * Write out the anchor used to toggle the original post. Javascript so that
 * it isn't written when javascript is not present.
 */
function WritePostCollapsor() {
  document.open();
  // SHOW_ORIG_POST value is outputted to the page by server-side code
  document.write('<a ' +
          'onclick="togglePostBody();try{this.blur();}catch(e){};' +
          'return false" id="btnPost" href="javascript:void(0);">' +
          SHOW_ORIG_MSG + '</a>');
  document.close();
}

/*
 * Write out the anchor used to toggle all comments. Javascript so that
 * it isn't written when javascript is not present.
 */
function WriteCommentsCollapsor() {
  document.open();
  document.write('<span id="' + Comment.TOGGLE_ID + '" class="hide" ' + 
                 'style="display:block;" ' +
                 'onmousedown="toggleAllComments(); ' + 
		 'try{this.blur();}catch(e){}">' + COLLAPSE_MSG + '</span>');
  document.close();
}

function WriteCommentFormsCSS() {
  document.write('<style type="text/css">' + 
                 '#bloggeruser, #nonbloggeruser { display:none; }' +
                 '</style>');
}

// hide/unhide the form fields associated with the various login options.

function hide(id) {
  if (d(id)) {
    d(id).style.display='none';
  }
}

function unHide(id) {
  if (d(id)) {
    d(id).style.display='';
  }
}

function showGoogle() {
  unHide('google');
  hide('openid');
  hide('nickname');
}

function showOpenId() {
  hide('google');
  unHide('openid');
  hide('nickname');
  d('iden-openid').checked = true;
  if (!d('openIdProvider').value) {
    selectOpenIdProvider("openid", false, true);
  } else {
    selectOpenIdProvider(d('openIdProvider').value, false, false); 
  }
}

function showNickname() {
  hide('google');
  hide('openid');
  unHide('nickname');
}

function showAnonymous() {
  hide('google');
  hide('openid');
  hide('nickname');
}

function onOpenIdFocus(el) {
  if (el.value == rawOpenIdEmptyValue ||
      el.value == rawOpenIdEmptyUrlValue) {
    el.style.color = '#000000';
    el.value = '';
  }
}

function onOpenIdBlur(el) {
  if (el.value == '') {
    el.style.color='#999999';
    if (d('openIdDropDown').value != 'openid') {
      el.value = rawOpenIdEmptyValue;
    } else {
      el.value=rawOpenIdEmptyUrlValue;
    }
    updateOpenIdUrlPreview();
  }
}

