function isHexaDigit(digit) {
   var hexVals = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                           "A", "B", "C", "D", "E", "F", "a", "b", "c", "d", "e", "f");
   var len = hexVals.length;
   var i = 0;
   var ret = false;

   for ( i = 0; i < len; i++ )
      if ( digit == hexVals[i] ) break;

   if ( i < len )
      ret = true;

   return ret;
}

function isValidKey(val, size) {
   var ret = false;
   var len = val.length;
   var dbSize = size * 2;

   if ( len == size )
      ret = true;
   else if ( len == dbSize ) {
      for ( i = 0; i < dbSize; i++ )
         if ( isHexaDigit(val.charAt(i)) == false )
            break;
      if ( i == dbSize )
         ret = true;
   } else
      ret = false;

   return ret;
}


function isValidHexKey(val, size) {
   var ret = false;
   if (val.length == size) {
      for ( i = 0; i < val.length; i++ ) {
         if ( isHexaDigit(val.charAt(i)) == false ) {
            break;
         }
      }
      if ( i == val.length ) {
         ret = true;
      }
   }

   return ret;
}


function isNameUnsafe(compareChar) {
// Jerry 20040628, @ . is allow
//   var unsafeString = "\"<>%\\^[]`\+\$\,='#&@.: \t";
   var unsafeString = "\"<>%\\^[]`\+\$\,='#&: \t";
	
   if ( unsafeString.indexOf(compareChar) == -1 && compareChar.charCodeAt(0) > 32
        && compareChar.charCodeAt(0) < 123 )
      return false; // found no unsafe chars, return false
   else
      return true;
}   

// Check if a name valid
function isValidName(name) {
   var i = 0;	
   
   for ( i = 0; i < name.length; i++ ) {
      if ( isNameUnsafe(name.charAt(i)) == true )
         return false;
   }

   return true;
}

// same as is isNameUnsafe but allow spaces
function isCharUnsafe(compareChar) {
   var unsafeString = "\"<>%\\^[]`\+\$\,='#&@.:\t";
	
   if ( unsafeString.indexOf(compareChar) == -1 && compareChar.charCodeAt(0) >= 32
        && compareChar.charCodeAt(0) < 123 )
      return false; // found no unsafe chars, return false
   else
      return true;
}   

function isValidNameWSpace(name) {
   var i = 0;	
   
   for ( i = 0; i < name.length; i++ ) {
      if ( isCharUnsafe(name.charAt(i)) == true )
         return false;
   }

   return true;
}

function isSameSubNet(lan1Ip, lan1Mask, lan2Ip, lan2Mask) {

   var count = 0;
   
   lan1a = lan1Ip.split('.');
   lan1m = lan1Mask.split('.');
   lan2a = lan2Ip.split('.');
   lan2m = lan2Mask.split('.');

   for (i = 0; i < 4; i++) {
      l1a_n = parseInt(lan1a[i], 10);
      l1m_n = parseInt(lan1m[i], 10);
      l2a_n = parseInt(lan2a[i], 10);
      l2m_n = parseInt(lan2m[i], 10);
      if ((l1a_n & l1m_n) == (l2a_n & l2m_n))
         count++;
   }
   if (count == 4)
      return true;
   else
      return false;
}


function isValidIpAddress(address) {
   var i = 0;
   var c = '';
   
   for (i = 0; i < address.length; i++) {
     c = address.charAt(i);
     if((c>='0'&&c<='9')||(c=='.'))
       continue;
     else
       return false;
   }
   if ( address == '0.0.0.0' ||
        address == '255.255.255.255' )
      return false;

   addrParts = address.split('.');

	//Frederick,060724	Make sure that everything is in decimal place
	for (i=0; i < addrParts.length; i++)
		addrParts[i] = parseInt(addrParts[i],10) + "";

   if ( addrParts.length != 4 ) return false;
   for (i = 0; i < 4; i++) {
      if (isNaN(addrParts[i]) || addrParts[i] =="")
         return false;
      num = parseInt(addrParts[i],10);
      if ( num < 0 || num > 255 )
         return false;
	  if (addrParts[i].length > 3)
		return false;
   }
   if (parseInt(addrParts[0],10)==0||parseInt(addrParts[3],10)==0)
   	return false;

   return true;
}

function isValidNetworkAddress(address) {
   var i = 0;
   var c = '';
   
   for (i = 0; i < address.length; i++) {
     c = address.charAt(i);
     if((c>='0'&&c<='9')||(c=='.'))
       continue;
     else
       return false;
   }
   if ( address == '0.0.0.0' ||
        address == '255.255.255.255' )
      return false;

   addrParts = address.split('.');
   if ( addrParts.length != 4 ) return false;

   for (i = 0; i < 4; i++) {
      num = parseInt(addrParts[i])
      if ( isNaN(num) )
         return false;
      if ( num < 0 || num > 255 )
         return false;
   }
   if (parseInt(addrParts[0])==0)
   	return false;

   return true;
}

function getLeftMostZeroBitPos(num) {
   var i = 0;
   var numArr = [128, 64, 32, 16, 8, 4, 2, 1];

   for ( i = 0; i < numArr.length; i++ )
      if ( (num & numArr[i]) == 0 )
         return i;

   return numArr.length;
}

function getRightMostOneBitPos(num) {
   var i = 0;
   var numArr = [1, 2, 4, 8, 16, 32, 64, 128];

   for ( i = 0; i < numArr.length; i++ )
      if ( ((num & numArr[i]) >> i) == 1 )
         return (numArr.length - i - 1);

   return -1;
}

function isValidSubnetMask(mask) {
   var i = 0, num = 0;
   var zeroBitPos = 0, oneBitPos = 0;
   var zeroBitExisted = false;
   var c = '';
   
   for (i = 0; i < mask.length; i++) {
     c = mask.charAt(i);
     if((c>='0'&&c<='9')||(c=='.'))
       continue;
     else
       return false;
   }
   if ( mask == '0.0.0.0' )
      return false;

   maskParts = mask.split('.');
   if ( maskParts.length != 4 ) return false; //Frederick 060503, this part is buggy, an entry of 255.255.255. will not be detected

	//Frederick, 060503	check that every single digit is not blank{
	for (i=0; i<maskParts.length; i++)
		if (maskParts[i].length < 1)
			return false;
	//Frederick, 060503	check that every single digit is not blank}

   for (i = 0; i < 4; i++) {
      if ( isNaN(maskParts[i]) == true )
         return false;
      num = parseInt(maskParts[i]);
      if ( num < 0 || num > 255 )
         return false;
      if ( zeroBitExisted == true && num != 0 )
         return false;
      zeroBitPos = getLeftMostZeroBitPos(num);
      oneBitPos = getRightMostOneBitPos(num);
      if ( zeroBitPos < oneBitPos )
         return false;
      if ( zeroBitPos < 8 )
         zeroBitExisted = true;
   }
   if (parseInt(maskParts[0])==0)
   	return false;

   if (parseInt(maskParts[3])>=255)
   	return false;

   return true;
}

function isValidPort(port) {
   var fromport = 0;
   var toport = 100;

   portrange = port.split(':');
   if ( portrange.length < 1 || portrange.length > 2 ) {
       return false;
   }
   if ( isNaN(portrange[0]) )
       return false;
   //fromport = parseInt(portrange[0]);
   fromport = (portrange[0] * 1);
   if ( portrange.length > 1 ) {
       if ( isNaN(portrange[1]) )
          return false;
       //toport = parseInt(portrange[1]);
		toport = (portrange[1] * 1);
       if ( toport <= fromport )
           return false;      
   }
   
   if ( fromport < 1 || fromport > 65535 || toport < 1 || toport > 65535 )
       return false;
   
   return true;
}

function isValidNatPort(port) {
   var fromport = 0;
   var toport = 100;

   portrange = port.split('-');
   if ( portrange.length < 1 || portrange.length > 2 ) {
       return false;
   }
   if ( isNaN(portrange[0]) )
       return false;
   //fromport = parseInt(portrange[0]);
	fromport = (portrange[0] * 1);
   if ( portrange.length > 1 ) {
       if ( isNaN(portrange[1]) )
          return false;
       //toport = parseInt(portrange[1]);
		toport = (portrange[1] * 1);
       if ( toport <= fromport )
           return false;
   }

   if ( fromport < 1 || fromport > 65535 || toport < 1 || toport > 65535 )
       return false;

   return true;
}

function isValidMacAddress(address) {
   var c = '';
   var i = 0, j = 0;

   if ( address.toLowerCase() == 'ff:ff:ff:ff:ff:ff' ) return false;
   if ( address.toLowerCase() == '00:00:00:00:00:00' ) return false;

   addrParts = address.split(':');
   if ( addrParts.length != 6 ) return false;

   for (i = 0; i < 6; i++) {
      if ( addrParts[i] == '' )
         return false;
	  //Frederick, 060523	one byte can consist of only 2 characters{
	  if (addrParts[i].length != 2)
		 return false;
	  //Frederick, 060523}
      for ( j = 0; j < addrParts[i].length; j++ ) {
         c = addrParts[i].toLowerCase().charAt(j);
         if ( (c >= '0' && c <= '9') ||
              (c >= 'a' && c <= 'f') )
            continue;
         else
            return false;
      }
   }

   return true;
}

function isValidMacFltAddress(address) {
   var c = '';
   var i = 0, j = 0;

   addrParts = address.split(':');
   if ( addrParts.length != 6 ) return false;

   for (i = 0; i < 6; i++) {
      if ( addrParts[i] == '' )
         return false;
	  //Frederick, 060523	one byte can consist of only 2 characters{
	  if (addrParts[i].length != 2)
		 return false;
	  //Frederick, 060523}
      for ( j = 0; j < addrParts[i].length; j++ ) {
         c = addrParts[i].toLowerCase().charAt(j);
         if ( (c >= '0' && c <= '9') ||
              (c >= 'a' && c <= 'f') )
            continue;
         else
            return false;
      }
   }

   return true;
}

var hexVals = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
              "A", "B", "C", "D", "E", "F");
var unsafeString = "\"<>%\\^[]`\+\$\,'#&";
// deleted these chars from the include list ";", "/", "?", ":", "@", "=", "&" and #
// so that we could analyze actual URLs

function isUnsafe(compareChar)
// this function checks to see if a char is URL unsafe.
// Returns bool result. True = unsafe, False = safe
{
   if ( unsafeString.indexOf(compareChar) == -1 && compareChar.charCodeAt(0) > 32
        && compareChar.charCodeAt(0) < 123 )
      return false; // found no unsafe chars, return false
   else
      return true;
}

function decToHex(num, radix)
// part of the hex-ifying functionality
{
   var hexString = "";
   while ( num >= radix ) {
      temp = num % radix;
      num = Math.floor(num / radix);
      hexString += hexVals[temp];
   }
   hexString += hexVals[num];
   return reversal(hexString);
}

function reversal(s)
// part of the hex-ifying functionality
{
   var len = s.length;
   var trans = "";
   for (i = 0; i < len; i++)
      trans = trans + s.substring(len-i-1, len-i);
   s = trans;
   return s;
}


//Frederick, 060414	Add converting of special characters for URL encoding {
function convertSpclChar (compareChar) {

	var i_ctr = 0;
	var toConvertString = "\"<>%\\^[]`\+\$\,='#&: \t";
	var returnString = "";	

	while (i_ctr < compareChar.length){

		if (toConvertString.indexOf(compareChar.charAt(i_ctr)) == -1)
			returnString = returnString + compareChar.charAt(i_ctr);			
		else
			returnString = returnString + convert(compareChar.charAt(i_ctr));			

		i_ctr++;
	}

	return returnString
}
//Frederick, 060414 Add converting of special characters for URL encoding }


//Frederick, 060503	Check if there's a ":" available or else don't allow post, issue of WinXP SP2{
function checkFile(txtBox)
{
//aids, 060719 fix for F/W upgrade linux.
var OS = GetBrowserOS();

	if (txtBox.length == 0)
	{
		alert("Please enter a valid filename");
		return false;
	}

if (OS.indexOf("win")!=-1){

	if (txtBox.indexOf("\\\\")!=-1)
		return true;

	//check if a : is existing
	temp = txtBox.search(":");
	if (temp != 1)
	{
		alert("Please enter a valid filename");
		return false;
	}
}

	return true;
}

//Frederick, 060503	Check if there's a ":" available or else don't allow post, issue of WinXP SP2}


//Frederick, 060503	Add function for checking if value entered is pure number (decimal) not hex or octal{
function cus_isNaN (entry)
{
	var tempString;
//frank,060728, check blank
		if(entry == "") return true;
	  //check if this is a hex value since it is ignored by isNaN
		tempString = entry.toUpperCase();
		tempString = tempString.search("X");
	
		if (tempString == 1)
		{
			return true;
		}
		
	  if (isNaN(entry) == true ) {
         return true;
      }
	return false;
}
//Frederick, 060503	Add function for checking if value entered is pure number (decimal) not hex or octal}

function convert(val)
// this converts a given char to url hex form
{
   return  "%" + decToHex(val.charCodeAt(0), 16);
}


function encodeUrl(val)
{
   var len     = val.length;
   var i       = 0;
   var newStr  = "";
   var original = val;

   for ( i = 0; i < len; i++ ) {
      if ( val.substring(i,i+1).charCodeAt(0) < 255 ) {
         // hack to eliminate the rest of unicode from this
         if (isUnsafe(val.substring(i,i+1)) == false)
            newStr = newStr + val.substring(i,i+1);
         else
            newStr = newStr + convert(val.substring(i,i+1));
      } else {
         // woopsie! restore.
         alert ("Found a non-ISO-8859-1 character at position: " + (i+1) + ",\nPlease eliminate before continuing.");
         newStr = original;
         // short-circuit the loop and exit
         i = len;
      }
   }

   return newStr;
}

var markStrChars = "\"'";

// Checks to see if a char is used to mark begining and ending of string.
// Returns bool result. True = special, False = not special
function isMarkStrChar(compareChar)
{
   if ( markStrChars.indexOf(compareChar) == -1 )
      return false; // found no marked string chars, return false
   else
      return true;
}

// use backslash in front one of the escape codes to process
// marked string characters.
// Returns new process string
function processMarkStrChars(str) {
   var i = 0;
   var retStr = '';

   for ( i = 0; i < str.length; i++ ) {
      if ( isMarkStrChar(str.charAt(i)) == true )
         retStr += '\\';
      retStr += str.charAt(i);
   }

   return retStr;
}

// Web page manipulation functions

function showhide(element, sh)
{
    var status;
    if (sh == 1) {
        status = "block";
    }
    else {
        status = "none"
    }
    
	if (document.getElementById)
	{
		// standard
		document.getElementById(element).style.display = status;
	}
	else if (document.all)
	{
		// old IE
		document.all[element].style.display = status;
	}
	else if (document.layers)
	{
		// Netscape 4
		document.layers[element].display = status;
	}
}

// Load / submit functions

function getSelect(item)
{
	var idx;
	if (item.options.length > 0) {
	    idx = item.selectedIndex;
	    return item.options[idx].value;
	}
	else {
		return '';
    }
}

function setSelect(item, value)
{
	for (i=0; i<item.options.length; i++) {
        if (item.options[i].value == value) {
        	item.selectedIndex = i;
        	break;
        }
    }
}

function setCheck(item, value)
{
    if ( value == '1' ) {
         item.checked = true;
    } else {
         item.checked = false;
    }
}

function setDisable(item, value)
{
    if ( value == 1 || value == '1' ) {
         item.disabled = true;
    } else {
         item.disabled = false;
    }     
}

function submitText(item)
{
	return '&' + item.name + '=' + item.value;
}

function submitSelect(item)
{
	return '&' + item.name + '=' + getSelect(item);
}


function submitCheck(item)
{
	var val;
	if (item.checked == true) {
		val = 1;
	} 
	else {
		val = 0;
	}
	return '&' + item.name + '=' + val;
}

//add by alex, 08/31/05'
/* checked is integer */
function isInteger(val)
{
	var i;
	if (val.length < 1)
		return false;
	for (i=0; i<val.length; i++ )
	{
		ch = val.charAt(i);
		if( (ch==' ')||(ch=='\n')||(ch=='\t') )
			return false;
		if (isNaN(ch))
			return false;
	}
	//if(isNaN(val))
		//return false;
	
	//if(parseInt(val) != val)
		//return false;
		
	return true;
}

/* checked invalid range */
function isInValidRange(s,low,high) {
	if(!isInteger(s))
		return false;
 	if(s<low||s>high)
    	return false;
	else
		return true;
}

//add by koukai,2005/06/03
/* checked blank */
function isBlank(s) {
	var c;
	for(i=0;i<s.length;i++) {
		c = s.charAt(i);
		if( (c!=' ')&&(c!='\n')&&(c!='\t') )
	            return false;
	}
	return true;
}

/* All input field should accepted [a-z],[A-Z],[0-9],[~!@#$%^&*()[]{}<>_+\|?/;:] otherwise we should filter. */
/* checked name(domain name, host name) */
function isValidName_Voice(raw)
{
	var i;
	var ch;
	
	if(raw == "")
	{
		return true;
	}
	else if(raw.length != 0)
	{
		for(i = 0; i<raw.length; i++)
		{
			ch = raw.charAt(i);
			if(ch.search(/[0-9]|[a-z]|[A-Z]|-/) == -1)  //modify by alex,08/30/2005
			{
				return false;
			}
		}
	}
	
	return true;
	
}

/* checked password field */
function isValidPassword(val)
{
    var ch;
    for(j = 0; j < val.length; j++)
    {
        ch = val.charAt(j);
        if (ch.search(/[0-9]|[a-z]|[A-Z]/) == -1)
            return false;           
    }
    return true;    
}  



/* Get form element StringIP, ex. 0.0.0.0 */
function isFormElements_UsedByAddress(name)
{
    var isExists = false;
    for(i=0; i<document.forms[0].elements.length;i++)
    {
        if(document.forms[0].elements[i].name == name)
        {
            isExists = true;
            break;
        }
    }
    if(document.forms[0].elements[i].value == "")
	{
		document.forms[0].elements[i].value = '0.0.0.0';
		return ('0.0.0.0');
	}
	else
    	return (document.forms[0].elements[i].value);
}
/* Get form elements checked */
function isFormElements_Checked(name)
{
    var isExists = false;
    for(i=0; i<document.forms[0].elements.length;i++)
    {
        if(document.forms[0].elements[i].name == name)
        {
            isExists = true;
            break;
        }
    }
    if(document.forms[0].elements[i].checked == true)
		return true;
	else
    	return false;
}
/* Get form element */
function isFormElements(name)
{
    var isExists = false;
    for(i=0; i<document.forms[0].elements.length;i++)
    {
        if(document.forms[0].elements[i].name == name)
        {
            isExists = true;
            break;
        }
    }
    if(document.forms[0].elements[i].value == "")
	{
		document.forms[0].elements[i].value = 0;
		return (0);
	}
	else
    	return (document.forms[0].elements[i].value);
}

/* Set form elements focus */
function SetFormElementsFocus(name)
{
    var isExists = false;
    for(i=0; i<document.forms[0].elements.length;i++)
    {
        if(document.forms[0].elements[i].name == name)
        {
            isExists = true;
            document.forms[0].elements[i].focus();
            break;
        }
    }
    
    return (isExists);
}

/* check Domain name or IP */
function isValidIPOrDomainName(str)
{
	var i;
	var str_array = str.split(".");

	for (i=0; i<str_array.length; i++ )
	{
		if (str_array[i] == "")
			return false;
	}
	for (i=0; i<str_array.length; i++ )
	{
		if (!isInteger(str_array[i]))
			break;
	}

	if (i == str_array.length)
	{
		if (str_array.length == 4)
		{
			if (!isValidIpAddress(str))
				return false;
		}
		else
			return false;
	}
	return true;
}


/*Frederick, 060505	Add browser detection functionality{*/

function GetBrowserOS()
{

	var detect = navigator.userAgent.toLowerCase();
	var OS,browser,version,total,thestring, browseVer;

	if (do_checkstr('konqueror'))
	{
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (do_checkstr('safari')) browser = "safa";
	else if (do_checkstr('omniweb')) browser = "omni";
	else if (do_checkstr('opera')) browser = "oper";
	else if (do_checkstr('webtv')) browser = "webt";
	else if (do_checkstr('icab')) browser = "icab";
	else if (do_checkstr('msie')) browser = "msie";
	//Frederick,060721	Add firefox detection
	else if(navigator.userAgent.indexOf("Firefox")!=-1){
		var versionindex=navigator.userAgent.indexOf("Firefox")+8
		if (parseInt(navigator.userAgent.charAt(versionindex))>=1)
		browser = "fire";
	}
	else if (!do_checkstr('compatible'))
	{
		browser = "nets"
	}
		else browser = "unknown";

	if (browser != "unknown")
		if (!OS)
		{
			if (do_checkstr('linux')) OS = "lin";
			else if (do_checkstr('x11')) OS = "uni";
			else if (do_checkstr('mac')) OS = "mac"
			else if (do_checkstr('win')) OS = "win"
			else OS = "unknown";
		}

	browseVer = browser + OS;

	return browseVer;
}


function do_checkstr(string)
{
	var detect = navigator.userAgent.toLowerCase();
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*end add browser detection functionality}*/

/*Frederick,060724	Add re-encode IP address to make sure that it is in consistent decimal form*/
/*e.g. 0192.0168.1.1 -> 192.168.1.1*/
function reencodeIP (IP)
{
	var newIP = '';
	addrParts = IP.split('.');

	//Frederick,060724	Make sure that everything is in decimal place
	for (i=0; i < addrParts.length; i++)
		if (i == 3)
			newIP = newIP + parseInt(addrParts[i],10);
		else
			newIP = newIP + parseInt(addrParts[i],10) + '.';
		
	return newIP;
}
/*}060724*/

//aids, 060810 for checking broadcast ip
function getBroadcastIP(HostIp, Mask)
{
  var Hostadd = HostIp.match("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$");
  var Maskadd = Mask.match("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$");
  var digits1, digits3;
  var result;
  var count = 0;

    var oct1a = 0;
    var oct2a = 0;
    var oct3a = 0;
    var oct4a = 0;

    var snm1a = 255;
    var snm2a = 255;
    var snm3a = 255;
    var snm4a = 255;

    var nw1a = 0;
    var nw2a = 0;
    var nw3a = 0;
    var nw4a = 0;

    var broad1a = 255;
    var broad2a = 255;
    var broad3a = 255;
    var broad4a = 255;

    digits1 = Hostadd[0].split(".");
    digits3 = Maskadd[0].split(".");
	
    oct1a = digits1[0];
    oct2a = digits1[1];
    oct3a = digits1[2];
    oct4a = digits1[3];

    snm1a = digits3[0];
    snm2a = digits3[1];
    snm3a = digits3[2];
    snm4a = digits3[3];

  	nw1a = eval(snm1a & oct1a);
	nw2a = eval(snm2a & oct2a);
	nw3a = eval(snm3a & oct3a);
	nw4a = eval(snm4a & oct4a);
	broad1a = ((nw1a) ^ (~ snm1a) & 255);
	broad2a = ((nw2a) ^ (~ snm2a) & 255);
	broad3a = ((nw3a) ^ (~ snm3a) & 255);
	broad4a = ((nw4a) ^ (~ snm4a) & 255);

	result = broad1a + "." + broad2a + "." + broad3a + "." + broad4a

  return result;
}

function valIsBroadcastIP(HostIp, Mask)
{
	var broadIP = getBroadcastIP(HostIp, Mask);
	var hostIPSplit = HostIp.split(".");
	var broadIPSlip = broadIP.split(".");

	var result = true;
	for (i = 0; i < 4; i++) {
		if (hostIPSplit[i] != broadIPSlip[i])
			result = false;
	}

	return result;

}
