/****************************************************************

  Traction Software, Inc. Confidential and Proprietary Information

  Copyright (c) 1996-2010 Traction Software, Inc.
  All rights reserved.

****************************************************************/

// PLEASE DO NOT DELETE THIS LINE -- make copyright depends on it.

// requires /images/modern/js/shared.js

var COMMENT_URL = "";
var COMMENT_WINDOW_NAME = "CommentWindow";
var COMMENT_WINDOW_FEATURES = "scrollbars=no,titlebar=no,resizable=yes,alwaysRaised=yes,menubar=no,location=no,status=no,toolbar=no,directories=no,width=570,height=300";

var hitSubmit = false;

function showComment() {
  return create_comment();
}

function create_comment() {
  var win = do_window_open(COMMENT_URL, 
			   COMMENT_WINDOW_NAME, 
			   COMMENT_WINDOW_FEATURES);
  return win;
}

function goLogin() {
  url = document.fm.login.value;
  rep = new RegExp("returnto=.*error=");
  orig = "returnto=" + escape(window.opener.location) + "&error=";
  url = url.replace(rep, orig);
  do_window_open(url, "");
  window.close();
}

function finishedLoading() {
  reloadOriginal();
  //setTimeout("reloadOriginal()", 2000);
}

function reloadOriginalWithAnchor( anchor ) {

  baseurl = document.fm.baseurl.value;
  origtype = document.fm.origtype.value;
  project = document.fm.project.value;
  url = "" + window.opener.location;
  wasContentSearch = document.fm.wasContentSearch.value;

//    alert("baseurl = " + baseurl );
//    alert("origtype = " + origtype );
//    alert("project = " + project );
//    alert("url = " + url );
//    alert("anchor = " + anchor );

  // remove exising anchor
  anchorpos = url.lastIndexOf('#');
  if ( anchorpos != -1 ) {
    url = url.substring( 0, anchorpos -1 );
  }

  // remove any existing cacheid parameter
  url = removeURLParameter( url, "cacheid" );
  
  // hack on cacheid for sketchy reloading
  date = new Date();
  id = "" + date.getTime();
  url += "&cacheid=" + id;

  // add new anchor
  url += anchor;

  // use the baseurl if we came from a permalink or /traction or
  // something...  [ajm 22.Sep.2003]
  // Actually, we can't always guarantee that we can deal with this
  // appropriately by simply using the baseurl.  In the case of
  // /traction, for example, we would really prefer to navigate to a
  // single entry view of the new comment, rather than reloading the
  // home view where the comment would not have even appeared.  So
  // instead, return false to indicate that the caller should deal
  // with this case.  For Server13908.  [shep 16.Feb.2005]
  if (url.indexOf('?') == -1) {
//     url = baseurl;
    return false;
  }

  // comments triggered from these types of views proceed to single
  // entry views

  // When we map very plain URLs, such as
  // http://server/servlet/tsi.Traction?type=home, to a single entry
  // view, we end up with incorrect garbage like
  // http://server/servlet/tsi.Traction?type=single#Projname123c.
  // Instead, if any of these conditions holds true, return false to
  // indicate that teh caller should deal with this case.  For
  // Server13908. [shep 16.Feb.2005]
  if (origtype == "" ||
      origtype == "np" || 
      origtype == "search" || 
      origtype == "home" || 
//       origtype == "single" || No need to map single to single, and it may cause problems.  See Server14423.03.  [shep 16.Feb.2005]
      wasContentSearch == "true" ) {
    return false;
//     url = replaceType(baseurl);	// go to single entry
//     url = replaceProject(url, project);
//     url += anchor;
  }

// Why ever replace the project? This is bizaar! I'm taking it out. [cjn 22.Jul.2004]
//    //   if (origtype == "home") {  // always replace the project!
//    url = replaceProject(url, project);
//    //   }
//    //  url = replaceVolume(url); [cjn 07.Oct.2003]

  if ( userAgentName == "iewin" ) {
    // needed for IE, illegal in other browsers [cjn 21.Jul.2004]
    window.opener.navigate( url );
  } else {
    window.opener.location = url;
  }

  setTimeout("window.close()", 1000);
  //window.close();

  return true;

}

function reloadOriginal() {
  reloadOriginalWithAnchor( "" );
}

function replaceProject(url, project) {
  rep = new RegExp("proj=[^&]*");
  str = "proj=" + encode_url_parameter(project);
  var newurl = url.replace(rep, str);

  //  alert("replaceProject:\n\n"+url+"\n\n->\n\n"+newurl);

  return newurl;
}

function replaceType(url) {
  rep = new RegExp("type=[^&]*");

  if (url.match(rep)) {
    url = url.replace(rep, "type=single");
  } else {
    url += "&type=single";
  }

  //  alert("replaceType:\n\n"+url+"\n\n->\n\n"+newurl);

  return url;
}

function replaceVolume(url) {
  var rep;
  var newurl = url;
  if (url.indexOf("hvolume=brief") != -1) {
    rep = new RegExp("hvolume=brief");
    newurl = url.replace(rep, "hvolume=comments");  		
  }  
  if (url.indexOf("hvolume=full") != -1) {
    rep = new RegExp("hvolume=full");
    newurl = url.replace(rep, "hvolume=comments");  
  }
  if (url.indexOf("&brief=c") == -1) {
    newurl = url + "&brief=c";
  }

  //  alert("replaceVolume:\n\n"+url+"\n\n->\n\n"+newurl);

  return newurl;
}

function submit_comment() {
  if (hitSubmit == true) {
    alert( i18n("comment_already_submitted_be_patient", "The comment has been submitted. Please be patient.") );
    document.fm.fb_submit.value = "Multiple Submit";
    document.fm.submit();
  }
  else {
    if (document.fm.content.value == "") {
      if (confirm( i18n("comment_confirm_blank_comment", "Do you really wish to submit a blank comment?") )) {
        hitSubmit = true;
        document.fm.fb_submit.value="Submit Comment";
        document.fm.submit();
      }
    }
    else {
      hitSubmit = true;
      document.fm.fb_submit.value="Submit Comment";
      document.fm.submit();
   }
  }
}

function change_view() {
  document.fm.fb_submit.value="Change View";
  document.fm.submit();
}

function change_project() {
  document.fm.fb_submit.value="";
  document.fm.submit();
}

function comment_setup_resize() {
  register_resize("modern_comment_", document.fm.content, document.body, 1, 1, 100, 100);

  window.onresize = handle_resize;
  
  // make sure we're well sized
  handle_resize();
}

/**
 * Checks whether any content has been typed into the comment form.
 * @param targetid TractionId for item or entry whose comment form
 * should be checked.  The argument for this parameter MUST be URL
 * encoded (to accomodate Japanese project names).
 */
function checkCommentContent(targetid) {

  var textarea = document.getElementById(targetid.toLowerCase() + "ac");

  // This value has to be captured in this fashion to compare to the
  // <br /> string, because it doesn't work otherwise.  [shep 15.Mar.2005]
  if ( isRichText ) {
    var s = new String(textarea.value);
    if (s == "<br />\n<br />") {
      textarea.value = "";
      document.getElementById("mce_editor_" + mceIndices[targetid.toLowerCase() + "ac"]).contentWindow.document.body.innerHTML = "";
    }
  }

  if (trim(textarea.value) == "" || // no content / no plain text content
      (isRichText && isHTMLWhiteSpace(textarea.value))) { // no rich text content
    alert(i18n("editformparser_error_message_no_title_and_content_comment", "Please supply some content for this comment."));
    return false;
  } else {
    return true;
  }

}

/**
 * Checks whether a project has been selected.
 * @param targetid TractionId for item or entry whose comment form
 * should be checked.  The argument for this parameter MUST be URL
 * encoded (to accomodate Japanese project names).
 */
function checkCommentProject(targetid) {
  if (getHtmlCommentFormFromEncodedTractionId(targetid).edit_project.value != "") {
    return true;
  } else {
    alert(i18n("comment_alert_message_submit_choose_project", "Please select a project to which this comment should be posted."));
    return false;
  }
}

/**
 * Checks whether the content and project are valid for the comment on
 * the given target item or entry, submits the comment, and if
 * necessary inserts a new comment form.
 * @param targetid TractionId for item or entry.  The argument for this
 * parameter MUST be URL encoded (to accomodate Japanese project names).
 * @param displayNewForm A flag indicating whether a new comment form
 * should be inserted when the current comment is submitted.  Probably
 * used really only for entry level comment forms in single entry
 * views.
 */
function submitComment(targetid, inlinesubmit, displayNewForm) {
  Debug.println("submitComment(\"" + targetid + "\", " + (inlinesubmit ? "submit inline" : "submit normal") + ", " + (displayNewForm ? "display new form" : "don't display new form") + ")");
  if (inlinesubmit) {
    submitInlineComment(targetid, displayNewForm);
  } else {
    submitRegularComment(targetid);
  }
}

function submitInlineComment(targetid, displayNewForm) {
  var cform = getHtmlCommentFormFromEncodedTractionId(targetid);
  if (!validateCommentInput(targetid)) {
    return;
  }
  if (!comment_submit(targetid, displayNewForm)) {
    submitRegularComment(targetid);
  }
}

var singletargetid;

function submitRegularComment(targetid) {
  singletargetid = targetid;
  var cform = getHtmlCommentFormFromEncodedTractionId(targetid);
  if (cform == null) {
    return;
  }
  go("Custom Action", cform);
}

function validateCommentInput(targetid) {

  var cform = getHtmlCommentFormFromEncodedTractionId(targetid);

  if ( isRichText ) {
    richTextCleanup("mce_editor_" + mceIndices[targetid.toLowerCase() + "ac"]);
  } else {
    try {
      // Only set edit_simplify_on_submit to false and edit_format to
      // "text" if edit_simplify_on_submit is not already false.  This
      // allows us to correct the values to plain text versions if
      // rich text mode tried to initialize but was unable to do so.
      // [shep 15.Mar.2005]
      if (cform.edit_simplify_on_submit.value != "false") {
	cform.edit_simplify_on_submit.value = "false";
	cform.edit_format.value = "text";
      }
    } catch (xcp) { /* in case a field is null */ }
  }

  var valid = checkCommentContent(targetid) && checkCommentProject(targetid);
  if (!valid) {
    return false;
  }

  if (isRichText && cform.edit_attach_urls != null) {
    var imgurls = getExternalImageURLs(document.getElementById("mce_editor_" + mceIndices[targetid.toLowerCase() + "ac"]).contentWindow.document);
    if (imgurls == null) {
      return false;
    }
    cform.edit_attach_urls.value = imgurls;
  }

  return true;

}

function waitforload_onsubmit() {
  return validateCommentInput(singletargetid);
}

function closeInlineComment( targetid ) {

  var textarea = document.getElementById(targetid.toLowerCase() + "ac");

  if (textarea == null) {
    return; // what were they closing?
  }

  if (isRichText) {
    tinyMCE.triggerSave(true, true);
  }

  var OKtoclose;

  if (!(trim(textarea.value) == "" || // no content / no plain text content
	(isRichText && isHTMLWhiteSpace(textarea.value)))) { // no rich text content
    OKtoclose = confirm(i18n("comment_alert_message_confirm_close", "Are you sure you want to close this comment?"));
  } else {
    OKtoclose = true;
  }

  if (!OKtoclose) {
    return;
  }

  commentform_remove( targetid );
}

/**
 * This function returns true if the given element is not null and has
 * descendant elements that are textareas.
 */
function hasDescendantCommentForms(element) {
  if (element == null) {
    return false;
  }
  var textareas = element.getElementsByTagName("textarea");
  return ((textareas != null) && (textareas.length != 0));
}

function getHtmlCommentIdFromTractionId(id) {
  return getHtmlIdFromTractionId(id) + "c";
}

function pageContainsComment(id) {
  return (getCommentContainerFromTractionId(id) != null);
}

function getCommentContainerFromTractionId(id) {
  return document.getElementById(getHtmlCommentIdFromTractionId(id));
}

function getHtmlCommentFormIdFromTractionId(commentTargetId) {
  return getHtmlCommentFormIdFromEncodedTractionId(encode_url_parameter(commentTargetId));
}

function getHtmlCommentFormFromTractionId(commentTargetId) {
  return document.getElementById(getHtmlCommentFormIdFromTractionId(commentTargetId));
}

function getHtmlCommentFormIdFromEncodedTractionId(encodedCommentTargetId) {
  return encodedCommentTargetId.toLowerCase() + "cfm";
}

function getHtmlCommentFormFromEncodedTractionId(encodedCommentTargetId) {
  return document.getElementById(getHtmlCommentFormIdFromEncodedTractionId(encodedCommentTargetId));
}

function getHtmlCommentFormInsertionPointIdFromTractionId(commentTargetId) {
  return getHtmlCommentFormInsertionPointIdFromEncodedTractionId(encode_url_parameter(commentTargetId));
}

function getHtmlCommentFormInsertionPointIdFromEncodedTractionId(encodedCommentTargetId) {
  return encodedCommentTargetId.toLowerCase() + "cs";
}

function getHtmlCommentFormInsertionPointFromEncodedTractionId(encodedCommentTargetId) {
  return document.getElementById(getHtmlCommentFormInsertionPointIdFromEncodedTractionId(encodedCommentTargetId));
}

function getHtmlCommentFormInsertionPointFromTractionId(commentTargetId) {
  return document.getElementById(getHtmlCommentFormInsertionPointIdFromTractionId(commentTargetId));
}

function updateWithNewEntry(result) {

  var updated = false;

  // if there are inline comment forms present in the page as DOM
  // descendents of an update target, we won't want to reload.
  var reloadOK = true;

  if (result.fm.edit_comment_id != null) {
    if (result.fm != null && result.fm.edit_comment_id) {
      updated = comment_popupinsert(encode_url_parameter(result.id).toLowerCase(),
				    encode_url_parameter(result.fm.edit_comment_id.value),
				    null);
      inlinecomment_.unregisterFormID(getHtmlCommentFormIdFromTractionId(result.fm.edit_comment_id.value));
    }
  } else if (result.isupdate && pageContainsComment(result.id)) {

    reloadOK = !hasDescendantCommentForms(document.getElementById(getHtmlCommentIdFromTractionId(result.id)));
    if (reloadOK) {
      updated = comment_refresh(getHtmlIdFromTractionId(result.id), null, true);
    }
  }

  // If an inline update was not requested, or if the inline update
  // could not be performed, updated will still be false.  Also, if
  // reloadOK is false, it means a comment is being edited that still
  // has open comment forms that the user has not yet submitted, in
  // which case we did not do an inline update but we don't want to
  // reload the page, either.  [shep 14.Mar.2005]

  // Also, if we are meant to be refreshing the opener window, we want
  // to do that and none of this other clever stuff.
  if (reloadOK && !updated && !result.refreshOpener) {

    if (result.fm.edit_comment_id != null && result.fm != null && result.fm.baseurl != null) {

      updated = reloadWithAnchor(result.fm, "#" + result.id + "c");

      // If reloadOriginalWithAnchor was not successful, and we have a
      // non-null parentEntryUrl, navigate to the parent URL appending the
      // anchor.  This isn't perfect, because the parent entry might
      // not be the original main entry from the view, but it's better
      // than using the a URL for the comment root, in which case the
      // new comment isn't even guaranteed to appear.  [shep 16.Feb.2005]
      if (!updated && result.parentEntryUrl != null && result.parentEntryUrl != "") {
	result.newEntryUrl = result.parentEntryUrl + "#" + result.id + "c";
      }

    } else if (result.isupdate && result.fm != null && result.fm.baseurl != null) {

      // Navigate to the SampleProj123c anchor for the updated entry
      // in the original view, if such a named anchor exists.  The
      // anchors also have id attributes that allow them to be
      // identified.  [shep 16.Feb.2005]
      if (pageContainsComment(result.id)) {
	updated = reloadWithAnchor(result.fm, "#" + result.id + "c");
      }

      // This could be done to snap to the edited entry when it's a
      // main entry rather than a comment, but we don't think we want
      // to do this.  In the future, we may want to offer a preference
      // referring to this behavior.  [shep 16.Feb.2005]

//       else if (document.getElementById(result.id.toLowerCase() + "m") != null) {
// 	// Navigate to original view, at main entry anchor.
// 	reloadWithAnchor(result.fm, "#" + result.id + "m");
// 	navigated = true;
//       }

    }

  }

  // If we have not yet navigated or updated in some more clever
  // fashion:
  if (!updated) {
    // If it is ok to reload the parent window, then simply a) refresh
    // it [shep 03.Oct.2005]; or b) navigate it to the new URL [shep 16.Feb.2005].
    if (reloadOK) {
      if (result.refreshOpener) {
	if (result.fm && result.fm.baseurl && (window.location.href == result.fm.baseurl.value)) {
	  window.location.reload(true);
	} else if (result.fm && result.fm.baseurl) {
	  window.location.href = result.fm.baseurl.value;
	} else {
	  window.location.href = result.newEntryUrl;
	}
      } else {
	window.location.href = result.newEntryUrl;
      }
    }
    // Or, if it is not OK to reload the parent window, open a new
    // window with either a) the same URL as the parent window's
    // original base URL (or its current URL, if the base URL is
    // unavailable) [shep 03.Oct.2005]; or b) a single entry view of
    // the entry just created or edited [shep 14.Mar.2005]
    else {
      if (result.refreshOpener) {
	var baseurl = "";
	if (result.fm == null || result.fm.baseurl == null || trim(result.fm.baseurl.value) == "") {
	  baseurl = window.location.href;
	} else {
	  baseurl = result.fm.baseurl.value;
	}
	window.open(baseurl);
      } else {
	window.open(FORM_ACTION_READ_ONLY + "?type=single&rec=" + result.id);
      }
    }
  }

}
