/*
 Utility functions for the knowbase toolbar.
*/

/*
Expand the tree to the node with the given repUri and apply some css highlight.
*/
function expandToNode(repUri)
{
   var topicNode;
   var expandTimer;
   tree = this.tree;

   if (tree == null || tree == "" || tree == "undefined") // tree not yet constructed
   {
      expandTimer = setTimeout("expandToNode('" + repUri + "')", 100);
   }
   else // we have the tree
   {
       clearTimeout(expandTimer);
       
      // check whether a directUrl has been inserted in the browser location bar
      if (repUri != null && repUri != "" && repUri != "undefined")
      {
         repUri += "?mt=text/html&amp;sty=Default";
         repUri = decodeURI(repUri);
         topicNode = tree.getNodeByProperty('href', repUri);
                 
         if (topicNode != null && topicNode != "undefined")
         {
            // expand tree
            expandTreePath(topicNode);
            // display topic in right frame
            window.parent.frames["contentwin"].location.href = topicNode.href;
         }
      }
      // no repUri, so just highlight the first node that represents a topicref
      else if (topicNode == null || topicNode == "" || topicNode == "undefined")
      {
         var found = false;
         var i = 1; // 0 is a hidden root
         while(!found) 
         {
           topicNode = tree.getNodeByIndex(i);
           var href = topicNode.href;
           if (href.indexOf("/Content") > -1)
             found = true;
           else
             i++;            
         }
         // expand tree 
         expandTreePath(topicNode);
         // display topic in the right frame
         window.parent.frames["contentwin"].location.href = topicNode.href;
      }
     
      // highlight the node
      highlightNode(topicNode);  //document.getElementById(topicNode.getElId()));     
      // position the vertical scrollbar
      var topicNodeId = topicNode.labelElId;
      var objDiv = document.getElementById(topicNodeId);
      objDiv.scrollTop = objDiv.scrollHeight;
      window.scroll(0, objDiv.scrollTop);
    
      // mark current node as the selected one
      selectedNode = topicNode;
   }
}

/*************************** FEEDBACK ************************************/

/*
Display feedback form in a popup window.
*/
function openFeedbackWin()
{
   var pathname = getContentHref("resourceToolbar");
    if(alertNoDocVisible())  // alert user that document must be visible in contentwin
    return;
  
   var pos = pathname.indexOf("knowbase");
    
   // extract the context only - it will always be the second token
   var tokens = parseHref(pathname);
   var context;
   if (tokens[0] == "" && pos > -1)  // knowbase context
      context = "/" + tokens[1];
   else                              // ROOT context
      context = tokens[0];
   
   var feedbackHref = context + "/feedback.jsp";
   window.open(feedbackHref, "", "toolbar=no,menu=yes,resizable=yes,width=750,height=625,screenX=1,screenY=1");
}

/*
Display pdf representation / printable view in a popup window.
*/
function openPrintableView()
{
  // detect Adobe Reader/Acrobat
  var pluginExists = detectAcrobat();
  
  if (!pluginExists)
  {
     var resp = confirm("The latest version of Adobe Reader is required to view this document. \n" +
                        "Click OK to be re-directed to the Adobe download site.");
    if (resp)
      window.open("http://get.adobe.com/reader/"); 
  }
  else
  {
    var href = getContentHref("contentwin");
      if(alertNoDocVisible())  // alert user that document must be visible in contentwin
      return;

    window.open(getPrintableHref(href), "", "resizable=yes,width=800,height=600,screenX=1,screenY=1");
   }
}

/*
Return the href of the document displayed in the "contentwin" frame.
*/
function getContentHref(frameName)
{
   var contentFrame = window.parent.frames[frameName];
   return contentFrame.document.location.pathname;         
}

/*
Return the url for a pdf representation. 
Query parameters:  mt  - mimetype
                   sty - style
           tbl  - toolbar (indicates where the request originated from)
*/
function getPrintableHref(currentUri)
{
   return currentUri += "?mt=application/pdf&sty=Default&tbl=true";                         
}

/*
Insert values into the pageUri date fields when the feedback
form is loaded.
*/
function insertValues()
{
   // insert document uri
   var contentFrame = opener.parent.frames["contentwin"];
   var currentUri = contentFrame.document.location.pathname;               
   
   var tokens = parseHref(currentUri);
   var resPathId = "";     
   
   // this won't exist when the confirmation message is returned
   if (document.feedback)
   {
     for (var i = 0; i < tokens.length; i++)
     {
         if (tokens[i] == "Content")
         {
             resPathId += "/" + tokens[i];
             resPathId += "/" + tokens[i+1];
             document.feedback.pageUri.value = resPathId;  // hidden value                   
             break;
         }
     }
     
     var docName = tokens[tokens.length-1];  // always the last one
     // make it presentable
     docName = docName.replace(/_/g, " ");
     docName = docName.replace(/\+/g, " ");
     document.feedback.docName.value = docName;
     
     // insert current date
     //var today = new Date();
     //document.feedback.date.value = getFormattedDate(today);
  }
}

function getFormattedDate(date)
{
   // see formatDate.js
   return date.formatDate('D M d Y G:i G\\MT O');
}

/*
Tokenizes the href and returns an array containing
each individual portion.
*/
function parseHref(href)
{
   return href.split('/');
}

/*
Validate the feedback form.
*/
function validateFeedback()
{
   var email = document.feedback.email.value;
   var firstName = document.feedback.firstName.value;
   var lastName = document.feedback.lastName.value;
   var comments  = document.feedback.comments.value;
   
   if (email == "undefined" || email == "")
   {
      valid = promptUser("Email address");
      document.feedback.email.focus();
      return false;
   }
   else if (firstName == "undefined" || firstName == "")
   {
      valid = promptUser("First Name");
      document.feedback.firstName.focus();
      return false;
   }
   else if (lastName == "undefined" || lastName == "")
   {
      valid = promptUser("Last Name");
      document.feedback.lastName.focus();
      return false;
   }
   else if (comments == "undefined" || comments == "")
   {
      valid = promptUser("Comments");
      document.feedback.comments.focus();
      return false;
   }
   
   //window.close();
   return true;
}

/*
Displays alert box with error message.
*/
function promptUser(value)
{
   alert("The " + value + " field must be completed.");
}

/*
Reset all values on feedback form.
*/
function resetValues()
{
   document.feedback.email.value = "";
   document.feedback.firstName.value = "";
   document.feedback.lastName.value = "";
   document.feedback.comments.value = "";
}

/*************************** DIRECT URL POPUP ***************************/

function openFrameLinkWin()
{
    if(alertNoDocVisible())  // alert user that document must be visible in contentwin
    return;
   
   // get the topicUri as a resVerId
   var contentFrame = window.parent.frames["contentwin"];
   var pathname = contentFrame.document.location.pathname;
   var topicUriAsVerId = parsePathForResVerId(pathname);

   window.open("directUrlWindow.jsp?topicUri=" + topicUriAsVerId, "", "toolbar=no,menu=yes,resizable=yes,width=650,height=150,screenX=1,screenY=1");
}

/*
Extract only the resVerId from the pathname.
*/
function parsePathForResVerId(pathname)
{
   var topicUriAsVerId = "";
   
   var pos = pathname.indexOf("Content");
   if (pos != -1)
      topicUriAsVerId = pathname.substring(pos-1); // keep the leading '/'
   /* 
   var pos = pathname.indexOf("knowbase");
   if (pos != -1)
      len = "knowbase".length +1;  // include the "/"
   pos = pathname.indexOf("xdrep");
   if (pos != -1)
      len += "xdrep".length +1;  // include the "/"
   if (len > -1)
      topicUriAsVerId = pathname.substring(len);
   else
      topicUriAsVerId = pathname;
   */
   return topicUriAsVerId;
}        

/*************************** EMAIL ************************************/

/*
Display a mail form in a popup window.
*/
function openEmailWin()
{
   var href = getContentHref("resourceToolbar");
    if(alertNoDocVisible())  // alert user that document must be visible in contentwin
    return;
   
  var pos = href.indexOf("knowbase");

   // extract the context only - it will always be the second token
   var tokens = parseHref(href);
   var context;
   if (tokens[0] == "" && pos > -1)  // "knowbase" context
      context = "/" + tokens[1]; 
   else                              // ROOT context
      context = tokens[0];
   
   var path = window.parent.frames["contentwin"].location.pathname;
   var topicUriAsVerId = parsePathForResVerId(path);    
  
   var mailtoHref = context + "/email?emailAction=displayEmailForm&topicUri=" + topicUriAsVerId;
   window.open(mailtoHref, "", "toolbar=no,menu=yes,resizable=yes,width=700,height=600,screenX=1,screenY=1");
}

/*
Returns the direct url for the currently displayed document.
*/
function getDirectUrl(contentFrame, servletContext)
{
   var path = contentFrame.document.location.pathname;          
   if (path == null || path == "undefined" || path == "")
      return "";
   
   path = parsePath(path, servletContext);
   var host = contentFrame.document.location.host;

   var url = "http://" + host + path;
   url = encodeURI(url);

   return url;
}

/*
Normalize the format of the uri to be attached as a parameter.
This is used for direct url insertions.
*/
function parsePath(pathname, servletContext)
{
   var path = "";
  var tokens = parseHref(pathname);
 
  var pos = pathname.indexOf("knowbase");
   var found;
   if (pos == -1)
      found = true;  // make this work with ROOT context
     
   for (var i = 0; i < tokens.length; i++)
   {
      var part = tokens[i];
      if (part == "" || part == "undefined")
         continue;
   
      path += "/";
      
      if (found)
      {
         if (servletContext != null && servletContext != "undefined" && servletContext != "")
            path += servletContext + "/";
         path += "?topicUri=";
         found = false;
         continue;
      }
      
      if (part == "knowbase") // the next token will be the mapping
         found = true;
   
      path += part;
   }
   return path;
}        

/*
Returns either '/' (for ROOT) or '/knowbase'.
*/
function getContextPath(href)
{
  var pos = href.indexOf("knowbase");
   if (pos == -1)
      return "/";  // make this work with ROOT context
   
   return "/knowbase/";
}

/*
Insert the url into the "body" field for an email message.
Note: called from onload event handler.
*/
function insertUrl()
{
   // insert document url
   var contentFrame = opener.parent.frames["contentwin"];
   var url = getDirectUrl(contentFrame, null);
   document.email.body.value = url;
}

/*
Do some validation before processing the email.
*/
function validateEmail()
{
   var mailto = document.email.mailto.value;
   var mailfrom = document.email.mailfrom.value;
   var copyto = document.email.copyto.value;
   var subject = document.email.subject.value;
   var body  = document.email.body.value;
   
   if (mailto == "undefined" || mailto == "")
   {
     valid = promptUser("To");
     document.email.mailto.focus();
     return false;
   }
   else if (mailfrom == "undefined" || mailfrom == "")
   {
     valid = promptUser("From");
     document.email.mailfrom.focus();
     return false;
   }
   else if (subject == "undefined" || subject == "")
   {
     valid = promptUser("Subject");
     document.email.subject.focus();
     return false;
   }
   else if (body == "undefined" || body == "")
   {
     valid = promptUser("Body");
     document.email.body.focus();
     return false;
   }
   
   // validate the email address
   if (!validateAddress(mailto, "recipient"))
   {
     return false;
   }
   else if (!validateAddress(mailfrom, "sender"))
   {
     return false;
   }
   // validate CC address, only if inserted
   else if (copyto != "undefined")
   {
     if (copyto.length > 0)
     {
        if (!validateAddress(copyto, "copy to addresses"))
           return false;
        return true;
     }
   }
     
   window.close();
   return true;
}

function validateAddress(address, addressType) 
{
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   //var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) 
   {
      var errorMsg = 'Email address is invalid for ' + addressType + ". "
      if (address.indexOf(";") > -1)
         errorMsg += "Only one email address is allowed.";
        
      alert(errorMsg);
      return false;
   }
   return true;
}

/*
Reset all values on the email form.
*/
function resetEmailValues()
{
   document.email.mailto.value = "";
   document.email.copyto.value = "";
   document.email.mailfrom.value = "";
   document.email.subject.value = "";
   document.email.body.value = "";
}

/*
Show a search result in its containing folder.
*/
function showInToc()
{
  // get the document URL
   var url = getContentHref("contentwin");
    if(alertNoDocVisible())  // alert user that document must be visible in contentwin
    return;

  url += "?mt=text/html&amp;sty=Default";
  url = decodeURI(url);

  // get the tree node for the url
   var yTextNode = getTreeNode(url);
   
   // let the user know that this node is not in the ditamap
   if (yTextNode == null || yTextNode == "undefined")
   {
    alert("This search result is not located in the table of contents.");
  }
   
   // start expanding, if the tree node is found
   if (yTextNode != null && yTextNode != "undefined")
   {
      // build a treepath to the root node and expand
      expandTreePath(yTextNode);
      
      // load the content frame
      loadFrame(url, "contentwin");

      highlightNode(yTextNode); // remove existing css styles from the previously selected node
      // mark the currently selected node
      selectedHref = url;

      // Programmatically switch from the "Search" to "Folder" tab
      // This will also update the content in the right frame and
      // highlight the selected node.  see tabcontent.js
      selectedDomElem = yTextNode.getLabelEl();
      // expand the tab from the tree frame since the toolbar frame knows nothing about the tabs
      window.parent.frames["toc"].expandtab("maintab", 0);
   }
}


/*
Build a treepath from the yTextNode to the root node
and expand.
@param yTextNode  a node in the Yahoo tree
*/
function expandTreePath(yTextNode)
{
   // open root node to first level
   tree.root.expand();
   var firstChild = tree.root.children[0];  // this is actually the "/" node
   if(!firstChild.expanded)  
         firstChild.expand();

   // build a treepath to the root node and expand
  var nodesToExpand = new Array();
   if (!yTextNode.expanded)
   {
    var i = 0;
    var parentNode = yTextNode.parent;
    while(parentNode != firstChild && parentNode != null) // firstChild is actually "/" node
    {
      nodesToExpand[i] = parentNode;
      parentNode = parentNode.parent;
      i++;
      }
      
      // now expand the nodes in reverse order
      for (var j = nodesToExpand.length-1; j >= 0; j--)
      {
        var node = nodesToExpand[j];
        if (!node.expanded)
            node.expand();
    }
   }
}


/*
 Return the tree node associated with the given url.
*/
function getTreeNode(url)
{
   tree = this.tree;
   return tree.getNodeByProperty('href', url);
}


/*
 Prompt to ensure that a document is always visible in the content frame.
 This is required for each of the items on this toolbar.
*/
function alertNoDocVisible()
{
  var href = window.parent.frames["contentwin"].location.href;

  if (href == null || href == "undefined" || href == "" || href == "about:blank")
  {
    alert("This feature requires a document to be visible in the content area.");
    return true;
   }
   return false;
}


// behaves as if JavaScript functions
String.prototype.startsWith = 
function(str)
{
  return (this.match("^"+str)==str);
}

String.prototype.endsWith = 
function(str)
{
  return (this.match(str+"$")==str)
}

