/*******************************************************************
 * File Name:       validation.js
 *
 * Date Created:    February 05, 2004
 *
 * Original Author: Navabharathi Gorantla
 *
 *
 * Notes/To Do
 * ===========
 *
 * This is a collection of JavaScript validation functions for
 * 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.
 *
 *
 ******************************************************************/

  // whitespace characters
  var whitespace = " \t\n\r";

  // alphabet characters
  var alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

  // number chars
  var numberChars = '0123456789';

  // wild chars
  var wildcards = '*?';

  // valid chars in domain name
  var domainChars = alphabets + numberChars + '-.';

  // valid chars in domain name with wild chars
  var wildCharDomainChars = domainChars + wildcards;

  // Checks whether a string is empty.
  function isEmpty(str)
  {
    return ((str == null) || (str.length == 0))
  }

  /* Checks if the string contains white spaces only.
   * Returns true if string s is empty or
   * whitespace characters only.
   */
  function isWhitespace (s)
  {
    var i;
    // Is s empty?
    if (isEmpty(s)) return true;
    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {
      // Check that current character isn't whitespace.
      var c = s.charAt(i);
      if (whitespace.indexOf(c) == -1)
      {
        return false;
      }
    }
    // All characters are whitespace.
    return true;
  }

  /* Checks for a period (.) character anywhere after the 3rd character
   * in the string, allowing for one letter domain names e.g. a@b.com;
   * and for @ characters anywhere after the first character
   * If both of these exist,
   * the function returns true, otherwise it returns false.
   */
  function isValidEmail(str)
  {
    return (str.lastIndexOf(".") > 2) && (str.indexOf("@") > 0);
  }

  // Checks for comma separated values
  // If a comma is found, returns true
  // otherwise returns false
  function commaSeparatedValuesFound(str)
  {
    return (str.indexOf(",") >= 0);
  }


  /* Returns true if the string passed in is a valid number
   * (no alpha characters), else it displays an error message
   */
   function ForceNumber(objField, FieldName)
   {
     var strField = new String(objField.value);
     if (isWhitespace(strField)) return true;
     var i = 0;
     for (i = 0; i < strField.length; i++)
     {
       if (strField.charAt(i) < '0' || strField.charAt(i) > '9')
       {
         alert(FieldName + " must be a valid numeric entry.  Please do not use commas or dollar signs or any non-numeric symbols.");
         objField.focus();
         return false;
       }
     }
     return true;
   }

  /* Validate the IP address */
  function isValidIP (IPvalue)
  {
    errorString = "";
    theName = '<fmt:message key="error.ipaddress" bundle="${bundle_message}"/>';

    var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    var ipArray = IPvalue.match(ipPattern);

    if (ipArray == null)
    {
      return false;
    }
    else
    {
      for (i = 0; i <= 4; i++)
      {
        thisSegment = ipArray[i];
        if (thisSegment > 255)
        {
          return false;
        }
        if ((i == 0) && (thisSegment > 255))
        {
          return false;
        }
      }
    }
    return true;
  }

  function isValidHostname(inputStr)
  {
    var hasPeriod = false;
    var hasChar = false;
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if ('.'.indexOf(oneChar) >= 0)
      {
        hasPeriod = true;
        // The '.' can't be the last character
        if (inputStr.lastIndexOf('.') == inputStr.length-1)
        {
          return false;
        }
      }
      if (!(domainChars.indexOf(oneChar) >= 0))
      {
         return false;
       }
      if (alphabets.indexOf(oneChar) >= 0)
      {
        hasChar = true;
      }
    }
    if (hasPeriod && hasChar)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  function isValidWildCharDomainname(inputStr)
  {
    var hasPeriod = false;
    var hasChar = false;
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if ('.'.indexOf(oneChar) >= 0)
      {
        hasPeriod = true;
        // The '.' can't be the last character
        if (inputStr.lastIndexOf('.') == inputStr.length-1)
        {
          return false;
        }
      }
      if (!(wildCharDomainChars.indexOf(oneChar) >= 0))
      {
         return false;
       }
      if (alphabets.indexOf(oneChar) >= 0)
      {
        hasChar = true;
      }
    }
    if (hasPeriod && hasChar)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  function containsWhiteSpace(inputStr)
  {
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if (whitespace.indexOf(oneChar) >= 0)
      {
        return true;
      }
    }
    return false;
  }

  function isValidIPAddressHostName(inputStr)
  {
    var status = true;
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if (oneChar =='/')
      {
        status = false;
        // substring till the '/' and
        // check for valid IPaddress on the first one and
        // valid subnet mask on the second one
        var ipaddress = inputStr.substring(0, i);
        var subnet = inputStr.substring(i+1, inputStr.length);
        if (isValidIP(ipaddress))
        {
          if (isValidIP(subnet))
          {
            return true;
          }
          else
          {
            return false;
          }
        }
        else
        {
          return false;
        }
        i = inputStr.length;
      }
    }
    if (status)
    {
      if (isValidIP(inputStr))
      {
        return true;
      }
      else
      {
        return isValidHostname(inputStr);
      }
    }
  }

  /* Check the number of check boxes checked and
   * disables/enables edit , moveup & movedown buttons accordingly
   */
  function updateButtonsStatus(checkBoxes, edit, moveUp, moveDown, frame)
  {
    var checkboxesLen = checkBoxes.length;
    /*
    if (isFrame != '')
    {
      checkboxes = frames[frame].document.checkBoxes;
      checkboxesLen = checkBoxes.length;
      alert("iframe Len : " + checkboxesLen);
    }
    */
    var checkedCount = 0;
    if (checkboxesLen > 0)
    {
      for (i=0; i<checkboxesLen; i++)
      {
        if (checkBoxes[i].checked)
        {
          checkedCount++;
        }
      }
    }
    if ((checkedCount >= 2) || (checkedCount == 0))
    {
      if (edit == 'edit')
      {
        // Disable the edit button if more than 1 selected
        document.getElementById('editButtonEnabled').style.display='none';
        document.getElementById('editButtonDisabled').style.display='';
      }
      if (moveUp == 'moveUp')
      {
        // Disable the moveUp button if more than 1 selected
        document.getElementById('moveUpButtonEnabled').style.display='none';
        document.getElementById('moveUpButtonDisabled').style.display='';
      }
      if (moveDown == 'moveDown')
      {
        // Disable the moveDown button if more than 1 selected
        document.getElementById('moveDownButtonEnabled').style.display='none';
        document.getElementById('moveDownButtonDisabled').style.display='';
      }
    }
    else
    {
      if (edit == 'edit')
      {
        // Enable the edit button if more than 1 selected
        document.getElementById('editButtonEnabled').style.display='';
        document.getElementById('editButtonDisabled').style.display='none';
      }
      if (moveUp == 'moveUp')
      {
        // Enable the moveUp button if more than 1 selected
        document.getElementById('moveUpButtonEnabled').style.display='';
        document.getElementById('moveUpButtonDisabled').style.display='none';
      }
      if (moveDown == 'moveDown')
      {
        // Enable the moveDown button if more than 1 selected
        document.getElementById('moveDownButtonEnabled').style.display='';
        document.getElementById('moveDownButtonDisabled').style.display='none';
      }
    }

    //Disable moveUp if first one is selected
    if (moveUp == 'moveUp')
    {
      if (checkboxesLen >= 1)
      {
        if (checkBoxes[0].checked)
        {
          // Disable the moveUp button if more than 1 selected
          document.getElementById('moveUpButtonEnabled').style.display='none';
          document.getElementById('moveUpButtonDisabled').style.display='';
        }
        else
        {
          // Enable the moveUp button if more than 1 selected
          document.getElementById('moveUpButtonEnabled').style.display='';
          document.getElementById('moveUpButtonDisabled').style.display='none';
        }
      }
    }

    //Disable moveDown if first one is selected
    if (moveDown == 'moveDown')
    {
      if (checkboxesLen >= 1)
      {
        if (checkBoxes[checkboxesLen-1].checked)
        {
          // Disable the moveDown button if more than 1 selected
          document.getElementById('moveDownButtonEnabled').style.display='none';
          document.getElementById('moveDownButtonDisabled').style.display='';
        }
        else
        {
          // Enable the moveDown button if more than 1 selected
          document.getElementById('moveDownButtonEnabled').style.display='';
          document.getElementById('moveDownButtonDisabled').style.display='none';
        }
      }
    }
  }

  /** Checks if the number is positive integer.
   * If yes returns true, else false.
   */
  function isPosInteger(inputVal)
  {
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if (oneChar < "0" || oneChar > "9")
      {
        return false;
      }
   }
   return true;
 }

 /** Checks if the number is positive integer and is greater than zero
   * If yes returns true, else false.
   */
  function isPosNonZeroInteger(inputVal)
  {
    if (isPosInteger(inputVal))
    {
      if (inputVal > 0)
      {
        return true;
      }
    }
    return false;
 }

 //This Javascript function checks to see if the supplied email address
 //is valid. It only check the syntax and does not do a verification
 //to see if the user exists in the domain.

 function checkEmail(emailAddr) {
   // this function checks for a well-formed e-mail address
   // in the format:
   // user@domain.com

   var i;

   // check for @
   i = emailAddr.indexOf("@");
   if (i == -1) {
     return false;
   }

   // separate the user name and domain
   var username = emailAddr.substring(0, i);
   var domain = emailAddr.substring(i + 1, emailAddr.length)

   // look for spaces at the beginning of the username
   i = 0;
   while ((username.substring(i, i + 1) == " ") && (i < username.length)) {
     i++;
   }
   // remove any found
   if (i > 0) {
     username = username.substring(i, username.length);
   }

   // look for spaces at the end of the domain
   i = domain.length - 1;
   while ((domain.substring(i, i + 1) == " ") && (i >= 0)) {
     i--;
   }
   // remove any found
   if (i < (domain.length - 1)) {
     domain = domain.substring(0, i + 1);
   }

   // make sure neither the username nor domain is blank
   if ((username == "") || (domain == "")) {
     return false;
   }

   // check for bad characters in the username
   var ch;
   for (i = 0; i < username.length; i++) {
     ch = (username.substring(i, i + 1)).toLowerCase();
     if (!(((ch >= "a") && (ch <= "z")) ||
       ((ch >= "0") && (ch <= "9")) ||
       (ch == "_") || (ch == "-") || (ch == "."))) {
         return false;
     }
   }

   // check for bad characters in the domain
   if (domain.substring(domain.length - 1) == ".")
   {
     return false;
   }

   for (i = 0; i < domain.length; i++) {
     ch = (domain.substring(i, i + 1)).toLowerCase();
     if (!(((ch >= "a") && (ch <= "z")) ||
       ((ch >= "0") && (ch <= "9")) ||
       (ch == "_") || (ch == "-") || (ch == "."))) {
         return false;
     }
   }

   if (domain.indexOf("..") > 0)
   {
     return false;
   }
   if (domain.indexOf(".") > 0)
   {
     return true;
   }

   // we would have exited if we'd found a good domain, so return false
   return false;
 }

  // Checks if the key pressed is enter and if so, transfers that as a click to 'SaveBtn'
  function checkEnter(e, elementID)
  {
    var characterCode; //literal character code will be stored in this variable

    if(e && e.which)
    { //if which property of event object is supported (NN4)
      characterCode = e.which; //character code is contained in NN4's which property
    }
    else
    {
      characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    //if character code is equal to ascii 13 (if enter key)
    if(characterCode == 13)
    {
      document.getElementById(elementID).click();
      return false;
    }
    else
    {
      return true;
    }
  }

  // Checks if the key pressed is enter and if so, returns false.
  function isEnterKey(e, elementID)
  {
    var characterCode; //literal character code will be stored in this variable

    if(e && e.which)
    { //if which property of event object is supported (NN4)
      e = e
      characterCode = e.which; //character code is contained in NN4's which property
    }
    else
    {
      e = event
      characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    //if character code is equal to ascii 13 (if enter key)
    if(characterCode == 13)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  // Check for wild chars '*' & '?'. If present return true, else false

  function haswildcards(inputStr)
  {
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if (wildcards.indexOf(oneChar) >= 0)
      {
         return true;
       }
    }
    return false;
  }

  // Returns the number of selected items
  function checkNumberSelected(selectedItems)
  {
    var checkedCount = 0;

    if (selectedItems == null)
    {
      // checkedCount = 0;
    }
    else if (selectedItems.length == null)
    {
      if (selectedItems.checked)
      {
        checkedCount = 1;
      }
    }
    else
    {
      for (i = 0; i < selectedItems.length; i++)
      {
        if (selectedItems[i].checked)
        {
          checkedCount++;
        }
      }
    }
    return checkedCount;
  }

  // Checks if multiple are selected.
  function isMultipleSelected(selectedItems)
  {
    var checkedCount = checkNumberSelected(selectedItems);
    if (checkedCount > 1)
    {
      return true;
    }
    return false;
  }

  // Checks if none are selected.
  function isNoneSelected(selectedItems)
  {
    var checkedCount = checkNumberSelected(selectedItems);
    if (checkedCount < 1)
    {
      return true;
    }
    return false;
  }

  // Checks if one or more are selected.
  function isOneOrMoreSelected(selectedItems)
  {
    if (isNoneSelected(selectedItems)) return false;
    else return true;
  }

  function hasValidDomainChars(inputStr)
  {
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if (!(domainChars.indexOf(oneChar) >= 0))
      {
         return false;
       }
    }
    return true;
  }

  /* Checks if the number is a valid port number between 0-65535 */
  function isValidPort(inputVal)
  {
    if (isPosInteger(inputVal))
    {
      num = parseInt(inputVal);
      if (num < 0 || num > 65535)
      {
        return false;
      }
      return true;
    }
    else
    {
      return false;
    }
 }

  function isValidCIDRNotation(inputStr)
  {
    var isValid = false;
    for (var i = 0; i < inputStr.length; i++)
    {
      var oneChar = inputStr.charAt(i)
      if (oneChar =='/')
      {
        // substring till the '/' and
        // check for valid IPaddress on the first one and
        // valid cidr on the second one
        var ipaddress = inputStr.substring(0, i);
        var cidr = inputStr.substring(i+1, inputStr.length);
        if (isValidIP(ipaddress))
        {
          if (isPosInteger(cidr))
          {
            var num = parseInt(cidr);
            if ((num >= 1) && (num <=32))
            {
              isValid = true;
            }
          }
          i = inputStr.length;
        }
      }
    }
    return isValid;
  }
 function isValidCIDRIPHostName(inputStr)
 {
   var isValid = isValidCIDRNotation(inputStr);
   if (!isValid)
   {
     isValid = isValidIPAddressHostName(inputStr);
   }
   return isValid;
 }
