/*******************************************************************
 * File Name:       common.js
 *
 * Date Created:    September 29, 2003
 *
 * Original Author: Gautam Sinha
 *
 *
 * Notes/To Do
 * ===========
 *
 * This is a collection of commonly used JavaScript functions in
 * BrightMail web applications.
 *
 *
 *
 * -----------------------------------------------------------------
 * Copyright 1998-2004 Symantec Corporation
 * 301 Howard Street, Suite 1800,
 * San Francisco, California, 94105, U.S.A.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Brightmail,Inc. Copying or reproduction without prior written
 * approval is prohibited.
 *
 *
 ******************************************************************/



/*
Sets the value of the action property on the
passed form to the passed action. If an action
has already been set on the form then the action
is replaced.
*/
function setAction(form, action)
{
  if(form.action != null)
  {
    var index = form.action.lastIndexOf("/");
    if(index > 0)
    {
      form.action = form.action.substring(0, index+1) + action;
    }
    else
    {
      form.action = action;
    }
  }
  else
  {
    form.action = action;
  }
}

/*
Same as 'setAction' but the form is then submitted
after setting the action on the form.
*/
function doAction(form, action)
{
    setAction(form, action);
    form.submit();
}

/*
Checks the slave checkboxes
when the master checkbox is clicked.
*/
function checkAll(master, slaves)
{
  var checkedCount = 0;
  if (slaves != null)
  {
    if (slaves.length == null)
    {
      // Special case for single check box
      if (master.checked)
      {
        slaves.checked = true;
        checkedCount++;
      }
      else
        slaves.checked = false;
    }
    else
    {
      for (i = 0; i < slaves.length; i++)
      {
        if (master.checked)
        {
          slaves[i].checked = true;
          checkedCount++;
        }
        else
          slaves[i].checked = false;
      }
    }
  }
  return checkedCount;
}

/*
Updates the master checkbox when a slave
checkbox is clicked.  This is to be used
when the master checkbox also serves as
a status indicator.  If the user checks
all the slave checkboxes, the master will
get checked to indicate that all items have been
selected.
*/
function trackCheckAllStatus(master, slaves)
{
  var slaveCount = slaves.length;
  var checkedCount = 0;

  if (slaves.length == null)
  {
    // Special case for single check box
    slaveCount = 1;
    if (slaves.checked)
      checkedCount++;
  }
  else
  {
    for (i = 0; i < slaveCount; i++)
    {
      if (slaves[i].checked)
        checkedCount++;
    }
  }

  if (checkedCount == slaveCount)
  {
    master.checked = true;
  }
  else
  {
    master.checked = false;
  }

  return checkedCount;
}

/*
 *  IE doesn't require the subcontext to be present on a URL if the containing
 *  form lists that subcontext in its action parameter--other browsers do.
 *
 *  This method expects the subcontext to be *complete*--that is, it is
 *  directly appended to the specified URL for non-IE browsers, so if a "/" is
 *  required in between, it must be provided as the last character of the
 *  subcontext parameter. The reason for this is that the subcontext may also
 *  specify a page, and URL might refer to a local anchor. Examples of the two
 *  follow:
 *
 *    browserSpecificUrl("some/sub/", "somethingTo.do")
 *    browserSpecificUrl("some/sub/somethingTo.do", "#local")
 */
function browserSpecificUrl(subcontext, URL)
{
  var bsUrl;

  if (browserCheck() == 0)
  {
    bsUrl = URL;
  }
  else
  {
    bsUrl = subcontext + URL;
  }

  return bsUrl;
}

/*
Prints the correct Frame in the Print View.
*/
function printReport() 
{
  window.parent.reportData.focus();
  window.parent.reportData.print();
}

/*
Image rollover functions generated by Dreamweaver
*/
function newImage(arg)
{
  if (document.images)
  {
    rslt = new Image();
    rslt.src = arg;
    return rslt;
  }
}

function changeImages()
{
  if (document.images && (preloadFlag == true))
  {
    for (var i=0; i<changeImages.arguments.length; i+=2)
    {
      document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
    }
  }
}

function switchImages(oldImage, newImage)
{
  document.getElementById(oldImage).src = eval(newImage).src;
}

/*
Sets the value of the form's methodName variable
to the new action and submits the form.
*/
function submitFormWithMethod(form, newMethod)
{
    form.methodName.value = newMethod;
    form.submit();
}

<!-- This section is for the HISTORY TRAIL -------------------------------------------------------------------- --/>
var prefix="<span class\='bcTrail' style\='vertical-align:middle;'>...</span>";
var printbct;
var maxDepth="3";
var divider = " <span class\='bcTrail' style\='vertical-align:middle;'>:</span> ";
var bctName = new Array();//Array to hold page names for trail
var bctLink = new Array();//Array to hold page links for trail
var splitCookieData = new Array();//Array to hold paparsed cookie string
// If we do not use the application's tabs and links to navigate to a page, for example, if we jump
// to a page directly from the login page, the history trail becomes incorrect.
// Change 'historyTrailBypassed' below to 'true' before calling 'bctLength' on the page to override the default
// links and use the links provided by the page.  These should be defined on the page in a function
// called fixHistoryTrail(). PR # 8669 and 8744.
var historyTrailBypassed = false;
var bctCookieName = "brightmailBCTCookie";

function bctLength(bctDepth)
{
  var pageLink;
  if (bctDepth == 1 && pageName == 'Settings')
  {
    pageLink = "settings/showDefaultSettingsPage.do";
  }else if (bctDepth == 1 && pageName == 'Logs')
  {
    pageLink = "logs/showLogs.do";
  }else
  {
    pageLink = window.location;
  }
  
  //reads and parses the Name cookiE
  var CookieValue = readCookie(bctCookieName);
  var CookieData = unescape(CookieValue);
  var parsedNameCookieData = CookieData.substring(CookieData.indexOf("XXX")+3,CookieData.indexOf("YYY"));
  var bctName = parsedNameCookieData.split("~");
  
 //parses the Link cookie
  var parsedLinkCookieData = CookieData.substring(CookieData.indexOf("YYY")+3,CookieData.indexOf("ZZZ"));
  var bctLink = parsedLinkCookieData.split("~");

  //Adds current page info to BC Trail Arrays
  bctName.length = bctDepth;
  bctName[bctDepth-1] = pageName;
  bctLink[bctDepth-1] = pageLink;

  // If the history trail was bypassed by directly loading
  // a page instead of using the application's navigation, fix it
  if (historyTrailBypassed)
  {
      fixHistoryTrail(bctName, bctLink);
  }

  // Limits BC Trail to maxDepth
  if (bctDepth<=maxDepth)
  {
    //html formats all but the last item in BC trail
    for(i=0;i<bctDepth-1;i++)
    {
      printbct = printbct+divider+"<a href\='"+(bctLink[i])+"' id\='bctItem"+i+"' class\='bcTrailLink' valign\='top'>"+bctName[i]+"</a>";
    }
  
    //html formats the last item in BC trail
    printbct = printbct+divider+"<span class\='bcTrail' style\='vertical-align:middle;'>"+bctName[bctDepth-1]+"</span>";
    printbct = printbct.substring(printbct.indexOf(divider)+(divider.length-1));
  }
  else
  {
    //html formats all but the last item in BC trail
    for(i=bctDepth-maxDepth;i<bctDepth-1;i++)
    {
      printbct = printbct+divider+"<a href\='"+(bctLink[i])+"' id\='bctItem"+i+"' class\='bcTrailLink' valign\='top'>"+bctName[i]+"</a>";
    }
  
    //html formats the last item in BC trail
    printbct = printbct+divider+"<span class\='bcTrail' style\='vertical-align:middle;'>"+bctName[bctDepth-1]+"</span>";
    printbct = printbct.substring(printbct.indexOf(divider)+(divider.length-1));
    printbct = prefix+printbct;
  }

  //preps and writes Names and Links to cookie
  var stringNameCookieData = bctName.join("~");
  var stringLinkCookieData = bctLink.join("~");
  var allCookieData = "XXX"+stringNameCookieData+"YYY"+stringLinkCookieData+"ZZZ";
  var escapedCookieData = escape(allCookieData);
  writeCookie(bctCookieName, escapedCookieData, 24);
}
<!-- The end of the HISTORY TRAIL -------------------------------------------------------------------- --/>

// Browser Check - returns 0 for IE
function browserCheck()
{
  if (navigator.appName == "Microsoft Internet Explorer")
    return 0;
  if (navigator.appName != "Microsoft Internet Explorer")
    return 1;
}



/*
Cookie related functions inserted from DreamWeaver
*/

// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  {
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    {
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end));
    }
  }
  return cookieValue;
}

// Example:
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours)
{
  var expire = "";
  if(hours != null)
  {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire + "; path=/";
}

<!-- This section is for the DATE VALIDATION -------------------------------------------------------------------- --/>
//
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
  var i;
  for (i = 0; i < s.length; i++){
      // Check that current character is number.
      var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) return false;
  }
  // All characters are numbers.
  return true;
}

function stripCharsInBag(s, bag){
  var i;
  var returnString = "";
  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.
  for (i = 0; i < s.length; i++){
      var c = s.charAt(i);
      if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}

function daysInFebruary (year){
  // February has 29 days in any year evenly divisible by four,
  // EXCEPT for centurial years which are not also divisible by 400.
  return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
  for (var i = 1; i <= n; i++) {
    this[i] = 31
    if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
    if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
  var daysInMonth = DaysArray(12)
  var pos1=dtStr.indexOf(dtCh)
  var pos2=dtStr.indexOf(dtCh,pos1+1)
  var strMonth=dtStr.substring(0,pos1)
  var strDay=dtStr.substring(pos1+1,pos2)
  var strYear=dtStr.substring(pos2+1)
  strYr=strYear
  if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
  if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
  for (var i = 1; i <= 3; i++) {
    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
  }
  month=parseInt(strMonth)
  day=parseInt(strDay)
  year=parseInt(strYr)
  if (pos1==-1 || pos2==-1){
    alert("The date format should be : mm-dd-yyyy")
    return false
  }
  if (strMonth.length<1 || month<1 || month>12){
    alert("Please enter a valid month")
    return false
  }
  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    alert("Please enter a valid day")
    return false
  }
  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
    alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
    return false
  }
  if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
    alert("Please enter a valid date")
    return false
  }
  return true
}


function validateDate(inputName)
{
  var dt=inputName;
  if (isDate(dt.value)==false)
  {
    return false;
  }
  return true;
}

function validateNotEmpty(inputName)
{
  if( inputName.value != "" )
  {
    return true;
  }
  else
  {
    return false;
  }
}

<!-- This section is for the HELP SYSTEM -------------------------------------------------------------------- --/>


//Opens or closes Admin Help Nav based on it's current state
function toggleAdminSubNav(helpNav,helpNavAnchor){

//Enter the names of the MAIN headings in the Help navigation
var tabNames = new Array("Summary","Status","Reports","Logs","Quarantine","Settings","Glossary");
var numContentItems = tabNames.length;

  if(document.getElementById(helpNav).style.display == 'none'){
    /*for(i=0;i<numContentItems;i++){
    document.getElementById(tabNames[i]).style.display = 'none';
    }*/
    document.getElementById(helpNav).style.display = '';
  }else if(document.getElementById(helpNav).style.display == ''){
    /*for(i=0;i<numContentItems;i++){
      document.getElementById(tabNames[i]).style.display = 'none';
    }*/
    document.getElementById(helpNav).style.display = 'none';
  }

selectLink(helpNavAnchor);

}

//Opens or closes Admin Help Nav based on it's current state
function autoToggleAdminSubNav(helpNav,helpNavAnchor){

  //Enter the names of the MAIN headings in the Help navigation
  var tabNames = new Array("Summary","Status","Reports","Logs","Quarantine","Settings","Glossary");
  var numContentItems = tabNames.length;

  if(document.getElementById(helpNav).style.display == 'none'){
    /*for(i=0;i<numContentItems;i++){
    document.getElementById(tabNames[i]).style.display = 'none';
    }*/
    document.getElementById(helpNav).style.display = '';
  }else if(document.getElementById(helpNav).style.display == ''){
    /*for(i=0;i<numContentItems;i++){
      document.getElementById(tabNames[i]).style.display = 'none';
    }*/
    document.getElementById(helpNav).style.display = '';
  }

  selectLink(helpNavAnchor);

}

//Opens or closes Quarantine User Help Nav based on it's current state
function toggleQuarantineSubNav(helpNav,helpNavAnchor)
{
  //Enter the names of the MAIN headings in the Help navigation
  var tabNames = new Array("Quarantine");
  var numContentItems = tabNames.length;


  if(document.getElementById(helpNav).style.display == 'none'){
    document.getElementById(helpNav).style.display = '';
  }else if(document.getElementById(helpNav).style.display == ''){
    document.getElementById(helpNav).style.display = 'none';
  }

  selectLink(helpNavAnchor);
}

//Opens or closes Quarantine User Help Nav based on it's current state
function autoToggleQuarantineSubNav(helpNav,helpNavAnchor)
{
  //Enter the names of the MAIN headings in the Help navigation
  var tabNames = new Array("Quarantine");
  var numContentItems = tabNames.length;

  if(document.getElementById(helpNav).style.display == 'none')
  {
    document.getElementById(helpNav).style.display = '';
  }
  else if(document.getElementById(helpNav).style.display == '')
  {
    document.getElementById(helpNav).style.display = '';
  }

  selectLink(helpNavAnchor);
}

/*
This tells the Help System whether to pull up a Help Page or the Glossary
*/
var isGlossary = false;
var glossaryHelpPage;
var glossaryHelpNav;
var glossaryHelpNavAnchor;

/*
Changes the state of a button to the state you pass in
*/

function changeButtonState(buttonId, newState)
{
  var buttonImage = document.getElementById(buttonId).src;
  var buttonName = buttonImage.substr(0, buttonImage.lastIndexOf(".gif"));

  if( buttonName.match("_Disabled$") == null )
  {
    var states = new Array("_Press");

    var isIdleState = true;
    for( i=0; i < states.length; i++ )
    {
      if( buttonName.match(states[i] + "$") != null )
      {
        isIdleState = false;
        switchButtonImages(buttonId, states[i], newState);
      }
    }

    if( isIdleState )
    {
      switchButtonImages(buttonId, "", newState);
    }
  }
}

function switchButtonImages(buttonId, oldState, newState)
{
  var oldSuffix = oldState + ".gif";
  var newSuffix = newState + ".gif";

  var buttonImage = document.getElementById(buttonId).src;
  var buttonName = buttonImage.substr(0, buttonImage.lastIndexOf(oldSuffix));
  var newButtonImage = buttonName + newSuffix;

  document.getElementById(buttonId).src = newButtonImage;
}

function highlightButton(buttonName)
{
  var buttonNameOver = buttonName + "Over";
  switchImages(buttonName, buttonNameOver);
  return true;
}

function removeHighlightFromButton(buttonName)
{
  var buttonNameIdle = buttonName + "Idle";
  switchImages(buttonName, buttonNameIdle);
  return true;
}

/*
 *  Takes a string with a series of items delimited by comma, semi-colon, or
 *  whitespace and returns a String[] containing the items. Null or empty items
 *  are removed from the array before it is returned.
 *
 *  Since experience with regular expressions varies widely, here is a detailed
 *  description of the regex used to split lists into tokens.
 *
 *  [,;\s]+   -   treat a series of one or more commas, semi-colons, or
 *                whitespace characters as a single delimiter
 */
function splitList(list)
{
  var items = list.split( /[,;\s]+/ );

  var nonEmptyItems = new Array();
  var j = 0;
  for( var i=0; i < items.length; i++ )
  {
    if( items[i] != null && items[i] != "" )
    {
      nonEmptyItems[j] = items[i];
      j++;
    }
  }

  return nonEmptyItems;
}

/*
 *  This function compensates for a Netscape bug that causes input fields to
 *  frequently load with their sizes too small (both width and height are
 *  lessened by 5 pixels). This function takes the element ID of the input and
 *  the desired width and height (in pixels) of that input and sets the
 *  specified values on that input.
 *
 *  If the browser being used to view the page is IE, the specified width and
 *  height values will be 5 pixels too big, so this function subtracts 5 from
 *  both.
 *
 *  Because of the nature of the Netscape bug for which this function provides
 *  a workaround, it is not guaranteed to work. The best it can do is inform
 *  the caller whether it worked or not and let the caller decide how best to
 *  handle the situation. As such, this function returns true if the workaround
 *  was applied successfully, and false if it was not. (Usually, if it works
 *  for one input on a particular page load, then it works for every input on
 *  that page load, so it's probably unnecessary to check more than one.)
 *
 *  IMPORTANT: The return value of this function can only be trusted if the
 *  specified input is visible! Calling this function with
 *  input.style.display=="none" will always result in a return value of true,
 *  whether it actually worked or not.
 */
function adjustInputSize(inputId, width, height)
{
  if( browserCheck() != 0 )
  {
    var input = document.getElementById( inputId );

    // set the size of the specified input
    input.style.width = width + "px";
    input.style.height = height + "px";

    if( input.style.display != "none"  &&  input.style.width != (input.offsetWidth + "px") )
    {   // it didn't take :(
      return false;
    }
    else
    {   // it worked!
      return true;
    }
  }
}

/*
 *  This function replaces all occurrences of the replacement token "{0}"
 *  in the message String with the first element of the args Array,
 *  args[0], "{1}" with args[1], and so on. Examples:
 *
 *    formatMessage("My name...is {0}!", new Array("Neo")) returns
 *      "My name...is Neo!"
 *
 *    formatMessage("{1} and {0} rock the house", new Array("KG", "JB")) returns
 *      "JB and KG rock the house"
 *
 *    formatMessage("{0}? {0}? ...{0}?", new Array("Bueller")) returns
 *      "Bueller? Bueller? ...Bueller?"
 *
 *  If the replacement token refers to an index that is not present in
 *  the args Array, it will simply be left alone:
 *
 *    formatMessage("{0} {1} {2} {3}", new Array("only", "three", "args") returns
 *      "only three args {3}"
 *
 *  Callers should not specify an args Array that contains replacement
 *  tokens itself...unexpected behavior may result:
 *
 *    formatMessage("{1} {0} {1}", new Array("{1}", "{0}")    // DON'T DO THIS!
 */
function formatMessage( message, args )
{
  for( var i=0; i < args.length; i++ )
  {
    message = message.replace( new RegExp("\\{" + i + "\\}", "g"), args[i] );
  }

  return message;
}

// Gets the key code for a pressed key
function getKeyCode(e)
{
  var keyPressed = null;
  if (e && e.which)
  {
    keyPressed = e.which;
  }
  else
  {
    keyPressed = event.keyCode;
  }
  return keyPressed;
}

function shiftKeyPressed(e) 
{
  var shiftPressed = false;
  if (navigator.appName=="Netscape") 
  {
    shiftPressed = (e.which == 16);
  }
  else 
  {
    shiftPressed = event.shiftKey;
  }
  return shiftPressed;
}


