var HelpOptionsVar = "width=480,height=420,scrollbars,toolbar,resizable,dependent=yes";
var GlossOptionsVar = "width=420,height=180,scrollbars,toolbar,resizable,dependent=yes";
var bigsub   = "width=540,height=440,scrollbars,menubar,resizable,status,dependent=yes";
var smallsub = "width=440,height=320,scrollbars,resizable,dependent=yes";
var sersub   = "width=500,height=380,scrollbars,resizable,status,dependent=yes";
var memsub   = "width=630,height=320,scrollbars,menubar,resizable,status,dependent=yes";
var helpWinVar = null;
var glossWinVar = null;
var datSubWinVar = null;
var ValidStr = 'abcdefghijklmnopqrstuvwxyz-';
var ValidStr_ddns = 'abcdefghijklmnopqrstuvwxyz-1234567890';
var hex_str = "ABCDEFabcdef0123456789";

function check_goodwords(str, goodwords) {
 if (typeof (str) != "string" || typeof (goodwords) != "string") {
  return (false);
 }
 if( (str.length<=0) || (goodwords.length <= 0) )
     return false;
 for (i=0; i<str.length; i++) {
  this_str = str.charAt(i);
  for (j=0; j<goodwords.length; j++) {
   if (this_str == goodwords.charAt(j)) {
    break;
   }
   if(j==goodwords.length-1){
    return false;
   }
  }
 }
 return true;
}

// Returns "true" if the given string (str) contains atleast one character present in the given
// list of "badwords" and returns false otherwise.
function check_badwords(str, badwords) {
 if (typeof (str) != "string" || typeof (badwords) != "string") {
  return (true);
 }
 for (i=0; i<str.length; i++) {
  this_str = str.charAt(i);
  for (j=0; j<badwords.length; j++) {
   if (this_str == badwords.charAt(j)) {
    return true;
   }
  }
 }
 return false;
}

/* 
** Sorting algorithm for JS Arrays where IPv4 Address is stored at index 2
*/
function sortByIPv4(a, b)
{
	if (a[2] != b[2]) // sort by index 2 (IPv4 address)
	{ 
		// split and sort by each segment
		var a_split = a[2].split('.');
		var b_split = b[2].split('.');
		var length = Math.min(a_split.length, b_split.length);
		var i = 0;
		while(i < length) // minimum address length
		{
			// compare groups
            if(a_split[i] == b_split[i])
			{
				i++; // continue to next iteration
			}
			else
			{
				// sort empty group first - treat as zero
                if(a_split[i] == "")
                    return -1; // a should come first
                if(b_split[i] == "")
                    return 1; // b should come first
                return (a_split[i] - b_split[i]); // lowest value should come first
			}
		}
	}
	return 0; // strings are equal by default
}

/* 
** Sorting algorithm for JS Arrays where IPv6 Address is stored at index 4
*/
function sortByIPv6(a, b)
{
	if (a[4] != b[4]) // sort by index 4 (IPv6 address)
	{ 
		// split and sort by each segment
		var a_split = a[4].split(':');
		var b_split = b[4].split(':');
        
        // pad address with missing zeros if required
        var a_padded = padIPv6Address(a_split);
        var b_padded = padIPv6Address(b_split);
        
        // sort addresses
        var i = 0;
		while(i < 8) // fixed address length
		{
			// compare groups
            if(a_padded[i] == b_padded[i])
			{
				i++; // continue to next iteration
			}
			else
			{
                return (parseInt(a_padded[i],16) - parseInt(b_padded[i],16)); // lowest value should come first
			}
		}
	}
	return 0; // strings are equal by default
}

/* 
** IPv6 Addresses are padded with zeros and returned as an 8-group array
*/
function padIPv6Address(addr) 
{
    var length = 8;
    var padded_addr = new Array(length);    
    var group_index = 0;

    addr.forEach(function(group)
    {
        if(group == "")
        {
            // pad with zeros
            var num_empty_groups = (length - addr.length) + 1;
            for(var i = 0; i < num_empty_groups; i++)
            {
                padded_addr[group_index] = "0";
                group_index++;
            }
        }
        else 
        {
            padded_addr[group_index] = group;
            group_index++;
        }
    });
    
    return padded_addr;
}

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;

   if ( mask == '0.0.0.0' )
      return false;

   maskParts = mask.split('.');
   if ( maskParts.length != 4 ) return false;

   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;
   }

   return true;
}


function showMsg()
{
	var msgVar=document.forms[0].message.value;
	if (msgVar.length > 1) 
		alert(msgVar);
}

function closeWin(win_var)
{
	if(document.layers)
		return;
	if ( ((win_var != null) && (win_var.close)) || ((win_var != null) && (win_var.closed==false)) )
		win_var.close();
}

function openHelpWin(file_name)
{
   helpWinVar = window.open(file_name,'help_win',HelpOptionsVar);
   if (helpWinVar.focus)
		setTimeout('helpWinVar.focus()',200);
}

function openGlossWin()
{
	glossWinVar = window.open('','gloss_win',GlossOptionsVar);
	if (glossWinVar.focus)
		setTimeout('glossWinVar.focus()',200);
}

var mutexVar = false;
function openDataSubWin(filename,win_type)
{
	if(false == mutexVar)
	{
		mutexVar = true;
		closeWin(datSubWinVar);
		datSubWinVar = window.open(filename,'datasub_win',win_type);
		if (datSubWinVar.focus)
			setTimeout('datSubWinVar.focus()',200); 
		mutexVar = false;
	}
}

function closeSubWins()
{
	closeWin(helpWinVar);
	closeWin(glossWinVar);
	closeWin(datSubWinVar);
}

function loadhelp(fname,anchname) {
if(top.frames.length > 0)
  {
	if ((loadhelp.arguments.length == 1 ) || (anchname == "" ))
		top.helpframe.location.href="h"+fname+".htm";
	else
		top.helpframe.location.href="h"+fname+".htm#" + anchname;
  }
}


function checkBlank(fieldObj, fname)
{
	var msg = "";	
	if (fieldObj.value.length < 1){	
		msg = addstr(msg_blank,fname);
        }
	return msg;
}

function checkNoBlanks(fObj, fname)
{
	var space = " ";
 	if (fObj.value.indexOf(space) >= 0 )
			return msg_space;
	else return "";
}

function checkValid(text_input_field, field_name, Valid_Str, max_size, mustFill)
{
	var error_msg= "";
	var size = text_input_field.value.length;
	var str = text_input_field.value;

	if ((mustFill) && (size != max_size) )
		error_msg = addstr(msg_blank_in,field_name);
 	for (var i=0; i < size; i++)
  	{
    	if (!(Valid_Str.indexOf(str.charAt(i)) >= 0))
    	{
			error_msg = addstr(msg_invalid,field_name,Valid_Str);
			break;
    	}
  	}
  	return error_msg;
}

function isValidStr(inputStr,validChars,len)  // returns true or false, no msg
{
	if (len <= 0) // no set length
		;
	else if (inputStr.length != len)
		return false;
    for(i=0; i < inputStr.length; i++) 
	{
        var c = inputStr.charAt(i);
		if (validChars.indexOf(c) == -1 )
			return false;
    }
    return true;
}
//bug 693 Fix: string length in input box on web page is not checked
function checkLength(text_input_field, field_name, min_value, max_value, required)
{
	var str = text_input_field.value;
	var error_msg= "";
	
	if( (str.length<min_value) ||(str.length>max_value))
	{
		if (required)
			error_msg = addstr(msg_outofrange,field_name,min_value,max_value);
	}
	
	return(error_msg);
}


function checkInt(text_input_field, field_name, min_value, max_value, required)
// NOTE: Doesn't allow negative numbers, required is true/false
{
	var str = text_input_field.value;
	var error_msg= "";
	
	if (text_input_field.value.length==0) // blank
	{
		if (required)
			error_msg = addstr(msg_blank,field_name);
	}
	else // not blank, check contents
	{
		for (var i=0; i < str.length; i++)
		{
			if ((str.charAt(i) < '0') || (str.charAt(i) > '9'))
				error_msg = addstr(msg_check_invalid,field_name);
		}
		if (error_msg.length < 2) // don't parse if invalid
		{
			var int_value = parseInt(str);
			if (int_value < min_value || int_value > max_value)
				error_msg = addstr(msg_outofrange,field_name,min_value,max_value);
		}
	}
	if (error_msg.length > 1)
		error_msg = error_msg + "\n";
	return(error_msg);
}


function sumvalue(F)
{    
	alert("Called sumvalue(), but should not.\nUse badMacField instead");

}
function MACAddressBlur(address)
{
	alert("Called MACAddressBlur(), but should not.\nUse badMacField instead");
}

// =============================   msg.js
//public message
var msg_blank = "%s can not be blank.\n";
var msg_space = "Blanks or spaces are not allowed in %s\n";
var msg_blank_in = "Blanks are not allowed in %s\n";
var msg_invalid = "\nInvalid character or characters in %s\nValid characters are: \n%s\n\n";
var msg_check_invalid = "%s contains an invalid number.";
var msg_greater = "%s must be greater than %s";
var msg_less = "%s must be less than %s";
var msg_outofrange = "%s is out of range [%s ~ %s]\n";

var msg_first = "First";
var msg_second = "Second";
var msg_third = "Third";
var msg_fourth = "Fourth";

function addstr(input_msg)
{
	var last_msg = "";
	var str_location;
	var temp_str_1 = "";
	var temp_str_2 = "";
	var str_num = 0;
	temp_str_1 = addstr.arguments[0];
	while(1)
	{
		str_location = temp_str_1.indexOf("%s");
		if(str_location >= 0)
		{
			str_num++;
			temp_str_2 = temp_str_1.substring(0,str_location);
			last_msg += temp_str_2 + addstr.arguments[str_num];
			temp_str_1 = temp_str_1.substring(str_location+2,temp_str_1.length);
			continue;
		}
		if(str_location < 0)
		{
			last_msg += temp_str_1;
			break;
		}
	}
	return last_msg;
}

// =============================   browser.js

function isIE(){
    var browser = new Object();
    browser.version = parseInt(navigator.appVersion);
    browser.isNs = false;
    browser.isIe = false;
    if(navigator.appName.indexOf("Netscape") != -1)
        browser.isNs = true;
    else if(navigator.appName.indexOf("Microsoft") != -1)
        browser.isIe = true;
    if(browser.isNs) return false;
    else if (browser.isIe) return true;
}

function add(out,in1,in2,in3,in4) {
    var Total;
    Total=in1.value+"."+in2.value+"."+in3.value+"."+in4.value;
    out.value=Total; 
}

function load4(Mydata,ip1,ip2,ip3,ip4) {
    var len; var ad; var temp;
    var Myall;
    Myall=Mydata.value;    //ip1 
    len=Myall.length;
    temp=Myall.indexOf(".");
    ad=Myall.substring(0,temp); 
    ip1.value=ad;
    //ip2 
    Myall=Myall.substring(temp+1,len);
    len=Myall.length;
    temp=Myall.indexOf(".");
    ad=Myall.substring(0,temp);
    ip2.value=ad;
    //ip3 
    Myall=Myall.substring(temp+1,len);
    len=Myall.length;
    temp=Myall.indexOf(".");
    ad=Myall.substring(0,temp);
    ip3.value=ad;
    //ip4 
    Myall=Myall.substring(temp+1,len);
    ad=Myall; ip4.value=ad;
} 

// =============================   utility.js
var msg_invalid_ip = "Invalid IP, please enter again!\n";
function isIPaddr(addr) {
    var i;
    var a;
    if(addr.split) {	
        a = addr.split(".");
    }else {	
        a = cdisplit(addr,".");
    }
    if(a.length != 4) {
        return false;
    }
    for(i = 0; i<a.length; i++) {
        var x = a[i];
        if( x == null || x == "" || !_isNumeric(x) || x<0 || x>255 ) {
            return false;
        }
    }
    return true;
}

function _isNumeric(str) {
    var i;
    for(i = 0; i<str.length; i++) {
        var c = str.substring(i, i+1);
        if("0" <= c && c <= "9") {
            continue;
        }
        return false;
    }
    return true;
}

function isHex(str) {
    var i;
    for(i = 0; i<str.length; i++) {
        var c = str.substring(i, i+1);
        if(("0" <= c && c <= "9") || ("a" <= c && c <= "f") || ("A" <= c && c <= "F")) {
            continue;
        }
        return false;
    }
    return true;
}

function checkNormalStr(str)
{
    var i;
    for(i = 0; i<str.length; i++)
	{
        var c = str.substring(i, i+1);
        if(("0" <= c && c <= "9") || ("a" <= c && c <= "z") || ("A" <= c && c <= "Z") || (c == "-") || (c == "_") || (c == ",") || (c == "+")) 
		{
            continue;
        }
        return false;
    }
    return true;
}


function checkMacStr(macField) 
{
	var MacStrOrg = macField.value;
	var MacStrNoSep = MacStrOrg;
	var macArray; var c; var i;

	/*
	if(MacStrOrg.indexOf(":") > -1)
		c = ":";
	else if(MacStrOrg.indexOf("-") > -1)
		c = "-";
	else 
		return isValidStr(MacStrOrg,hex_str,12);
	*/
//bug 997: sky 1.6 wireless gui:Device Name and MAC Address need to be restricted
   MacStrOrg = MacStrOrg.toLowerCase();
   if ( MacStrOrg == 'ff:ff:ff:ff:ff:ff' ) return false;
   if ( MacStrOrg == '00:00:00:00:00:00' ) return false;
//end of bug 997
	
	if (MacStrOrg.indexOf(":")>-1)
		c = ":";
	else
		return false;
	
	macArray = MacStrOrg.split(c);
	if(macArray.length != 6)
		return false;
	for ( i = 0; i < macArray.length; i++)
	{
		if (macArray[i].length != 2 )
			return false;
	}
	MacStrNoSep =  MacStrNoSep.replace(/:/g,"");
	MacStrNoSep =  MacStrNoSep.replace(/-/g,"");
	return isValidStr(MacStrNoSep,hex_str,12);
}

/* Check IP Address Format*/
function checkIPMain(ip,max) {
    if( isNumeric(ip, max) ) {
        ip.focus();
        return true;
    }
}

function badLANIP(ip1, ip2, ip3, ip4,max) {
    if(checkIPMain(ip1,223)) return true; 
    if(checkIPMain(ip2,255)) return true;
    if(checkIPMain(ip3,255)) return true;
    if(checkIPMain(ip4,max)) return true;
    if((parseInt(ip1.value)==0)||(parseInt(ip1.value)==0)&&(parseInt(ip2.value)==0)&&(parseInt(ip3.value)==0)&&(parseInt(ip4.value)==0))
    	return true;
    return false;
}


function badIP(ip1, ip2, ip3, ip4,max) {
    if(checkIPMain(ip1,255)) return true; 
    if(checkIPMain(ip2,255)) return true;
    if(checkIPMain(ip3,255)) return true;
    if(checkIPMain(ip4,max)) return true;
    if((parseInt(ip1.value)==0)||(parseInt(ip1.value)==0)&&(parseInt(ip2.value)==0)&&(parseInt(ip3.value)==0)&&(parseInt(ip4.value)==0))
    	return true;
    return false;
}

/* Check Numeric*/
function isNumeric(str, max) {
    if(str.value.length == 0 || str.value == null || str.value == "") {
        str.focus();
        return true;
    }

    var i;
    i = str.value = parseInt(str.value,10);
    if(i>max) {
        str.focus();
        return true;
    }
    for(i=0; i<str.value.length; i++) {
        var c = str.value.substring(i, i+1);
        if("0" <= c && c <= "9") {
            continue;
        }
        str.focus();
        return true;
    }
    return false;
}

/* Check Blank*/
function isBlank(str) {
    if(str.value == "") {
        str.focus();
        return true;
    } else 
        return false;
}

/* Check Phone Number*/
function isPhonenum(str) {
    var i;
    if(str.value.length == 0) {
        str.focus();
        return true;
    }
    for (i = 0; i<str.value.length; i++) {
        var c = str.value.substring(i, i+1);
        if (c>= "0" && c <= "9")
            continue;
        if ( c == '-' && i !=0 && i != (str.value.length-1) )
            continue;
        if ( c == ',' ) continue;
        if (c == ' ') continue;
        if (c>= 'A' && c <= 'Z') continue;
        if (c>= 'a' && c <= 'z') continue;
        str.focus();
        return true;
    }
    return false;
}

/* 0:close 1:open*/
function openHelpWindow(filename) {
    helpWindow = window.open(filename,"thewindow","width=300,height=400,scrollbars=yes,resizable=yes,menubar=no");
}

function checkSave() {
    answer = confirm("Did you save this page?");
    if (answer !=0) {
        return true;
    } else return false;
}

function alertPassword(formObj) {
    alert("Re-Confirm the password!");
    formObj.focus();
}
function isEqual(cp1,cp2)
{
	if(parseInt(cp1.value) == parseInt(cp2.value))
	{
		cp2.focus();
		return true;
	}	
	else return false;
}
function setDisabled(OnOffFlag,formFields)
{
	for (var i = 1; i < setDisabled.arguments.length; i++)
		setDisabled.arguments[i].disabled = OnOffFlag;
}

function cp_ip(from1,from2,from3,from4,to1,to2,to3,to4)
//true invalid from and to ip;  false valid from and to ip;
{
    var total1 = 0;
    var total2 = 0;
    
    total1 += parseInt(from4.value,10);
    total1 += parseInt(from3.value,10)*256;
    total1 += parseInt(from2.value,10)*256*256;
    total1 += parseInt(from1.value,10)*256*256*256;
    
    total2 += parseInt(to4.value,10);
    total2 += parseInt(to3.value,10)*256;
    total2 += parseInt(to2.value,10)*256*256;
    total2 += parseInt(to1.value,10)*256*256*256;
    if(total1 > total2)
        return true;
    return false;
}


function cp_ip_mask(ip1,ip2,ip3,dhcpstart1,dhcpstart2,dhcpstart3, dhcpend1, dhcpend2, dhcpend3)
{
    var ip = 0;
    var dhcpstart = 0;
    var dhcpend = 0;
    
    ip += parseInt(ip3.value,10);
    ip += parseInt(ip2.value,10)*256;
    ip += parseInt(ip1.value,10)*256*256;
    
    dhcpstart += parseInt(dhcpstart3.value,10);
    dhcpstart += parseInt(dhcpstart2.value,10)*256;
    dhcpstart += parseInt(dhcpstart1.value,10)*256*256;

    
    dhcpend += parseInt(dhcpend3.value,10);
    dhcpend += parseInt(dhcpend2.value,10)*256;
    dhcpend += parseInt(dhcpend1.value,10)*256*256;

    if((ip >= dhcpstart) && (ip <= dhcpend))
        return true;
    else
	return false;
}


function pi(val)
{
    return parseInt(val,10);
}    
function alertR(str)    
{
    alert(str);
    return false;
}    



function blankIP(f1,f2,f3,f4) // true if 0 or blank
{
	if( containStr(f1,"") && containStr(f2,"") && containStr(f3,"") && containStr(f4,"") )
		return true;
	if( containStr(f1,"0") && containStr(f2,"0") && containStr(f3,"0") && containStr(f4,"0") )
		return true;
	return false;
}


function containStr(fn,str) 
{
	return  (fn.value == str);
}

function goToIndexPage()
{
	window.location.href="sky_index.html";
}

//
//returns false if enter key is pressed on text fields.
//
//If any HTML file wants to disable the EnterKey,
//It needs to assign the onkeypress event with this API.
//
//Example: document.onkeypress = disableEnterKey
//
function disableEnterKey(evt)
{ 
    var evt = (evt) ? evt : ((event) ? event : null); 
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
    if ((evt.keyCode == 13) && (node.type=="text"))
    {
        return false;
    } 
} 

function skyCheckIPV6Address(address)
{
    if ((address != "") && (address != "::") && (address.indexOf(':') !== -1))
    {
        return isValidIPV6(address);
    }
    else
    {
        return false;
    }
}

/* Converts a human readable IP address to a packed binary string  */
function inet_pton(a) {
    var r, m, x, i, j, f = String.fromCharCode;
   // IPv4
  m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/);
  if (m) {
    m = m[0].split('.');
    m = f(m[0]) + f(m[1]) + f(m[2]) + f(m[3]);
    // Return if 4 bytes, otherwise false.
    return m.length === 4 ? m : false;
  }

  // IPv6
  r = /^((?:[\da-f]{1,4}(?::|)){0,8})(::)?((?:[\da-f]{1,4}(?::|)){0,8})$/;
  m = a.match(r);
  if (m) 
  {
    // Translate each hexadecimal value.
    for (j = 1; j < 4; j++) 
    {
      // Indice 2 is :: and if no length, continue.
      if (j === 2 || m[j].length === 0) 
      {
        continue;
      }
      m[j] = m[j].split(':');
      for (i = 0; i < m[j].length; i++) 
      {
        m[j][i] = parseInt(m[j][i], 16);
        // Would be NaN if it was blank, return false.
        if (isNaN(m[j][i])) 
        {
          // Invalid IP.
          return false;
        }
        m[j][i] = f(m[j][i] >> 8) + f(m[j][i] & 0xFF);
      }
      m[j] = m[j].join('');
    }
    x = m[1].length + m[3].length;
    if (x === 16) 
    {
      return m[1] + m[3];
    } 
    else if (x < 16 && m[2].length > 0) 
    {
      return m[1] + (new Array(16 - x + 1))
        .join('\x00') + m[3];
    }
  }
  // Invalid IP.
  return false;
}

// The filter is ported from Hub3 source and further extended to handle threats mentioned in
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#XSS_using_HTML_quote_encapsulation
function xSSpatternExists(key)
{
    var xSSpattern = /<script>(.*?)<\/script>|<script(.*?)>|<\/script>|<IFRAME(.*?)<\/IFRAME>|<FRAMESET(.*?)<\/FRAMESET>|<TABLE(.*?)>|<DIV STYLE(.*?)|<A HREF(.*?)<\/A>|<img onload(.*?)>|<IMG STYLE(.*?)>|<BR SIZE(.*?)>|<BODY ONLOAD(.*?)>|<IMG(.*?)>|<svg\/onload(.*?)>|javascript:|vbscript:/gi;
    return (xSSpattern.test(key));
}

function skyCheckValidPrefixAndLength(address)
{
        var splitArray = address.split("/");
        var prefix = $.trim(splitArray[1]);
        var ULA = $.trim(splitArray[0]);
        var charValue = ULA.substr(0,2);

        if(prefix != "64" )
        {
            return false;
        }

        if( (charValue.toLowerCase() != "fc") && (charValue.toLowerCase() != "fd") ) /* ULA will be of FC00::/7 range */
        {
                return false;
        }
        return isValidIPV6(ULA+"1");/*prefix will be of format fd17:e418:dda4:0000:: */
}

function isValidIPV6(ipv6address)
{
	var spacer=/\s/; //check for space leading,trailing/in between etc.
        if(spacer.test(ipv6address) == true)
        {
                return false; //Any space in string return false, since space will not be considered as valid IPV6 address in back end
        }

        var r = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
        return r.test(ipv6address);
}

function checkWpaPskOrSsidChangeAllowed(newKey,newSsid,otherWlSsid,otherWlPsk,currentSsid,currentPsk){
    var errorStr="";
	if (!(otherWlSsid.localeCompare(newSsid)))
	{
	  if((otherWlPsk.localeCompare(newKey))){
	  	/*PSK change or SSID change not allowed*/
	  	if(currentSsid.localeCompare(newSsid)) /*user changing the SSID*/
			errorStr = "You have unchecked \'Synchronise 2.4GHz and 5GHz Settings\'. Please make sure that SSIDs are not identical as you have configured different Network Keys";
		else if(currentPsk.localeCompare(newKey)) /*user changing the Network Key*/
			errorStr = "You have unchecked \'Synchronise 2.4GHz and 5GHz Settings\'. Please make sure that Network keys are identical as you have configured identical SSIDs";
		else{
			/*oops this shoud not hit here*/
		}
			
	  }
	}			

	return errorStr;

}


function checkWpaPskKey(key) {
    var validWpaPskKeyStr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
    var errorStr="";

    if(key.length>63 || key.length<8) {
        errorStr = "Network Key must be between 8 and 63 ASCII characters";
        return errorStr;
    }
    var space=" ";
    if( (key.indexOf(space)==0) || (key.lastIndexOf(space)==key.length-1) ) {
        errorStr = "Network key cannot have space character at beginning or end";
        return errorStr;
    }
    if( check_goodwords(key,validWpaPskKeyStr) == false ) {
        errorStr = "Network key contains characters which are not allowed. Valid special characters are SPACE!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
    }
    if( xSSpatternExists(decodeHtml(key)) ){
        errorStr = "Invalid network key";
    }

	
    return errorStr;
}

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

// =====  end  utility.js
