var infra_security = [[true, "None", "0"], [true, "WEP", "1"], [true, "WPA-PSK", "2"]]; 
var adhoc_security = [[true, "None", "0"], [true, "WEP", "1"]]; 

function getKeyLength()
{
	var index = document.NetworkSetting.wireless_keylength.selectedIndex;
	
	if(index == 0)	return 5;
	if(index == 1)	return 13;
	if(index == 2)	return 29;
}

function checkKey(instr){
	var i;
  	var iKeyBytes = getKeyLength();
  	
  	if(document.NetworkSetting.wireless_keyformat.selectedIndex == 0)
  	{
		for(i=0; i<instr.value.length; i++)
		{
	    	var c = instr.value.charAt(i);
	    	if (!((c>='0'&& c<='9')||(c>='A' && c<='F')||(c>='a' && c<='f')))
	    	{
	    		alert("Invalid hex.");
		   		instr.focus();
		        instr.select();
	      		return -1;
	      	}
		}
		iKeyBytes = iKeyBytes * 2;
  	}
  	if(instr.value.length != iKeyBytes)
  	{
  		alert("Please enter exactly " + iKeyBytes + " characters.");
   		instr.focus();
        instr.select();  		
  		return -1;
  	}
}

function checkWPAKey()
{
	var wpak = document.NetworkSetting.wireless_presharedkey;
	if (wpak.value.length < 8)
	{
	    alert("Pre-shared key must be 8~63 characters or 64 hex-characters.");
		wpak.focus();
		wpak.select();
		return -1;
	}
	if (wpak.value.length == 64)
	{
		for (i=0; i<wpak.value.length; i++)
		{
	    	var c = wpak.value.charAt(i);
	    	if (!((c>='0'&& c<='9')||(c>='A' && c<='F')||(c>='a' && c<='f')))
	    	{
	    		alert("Invalid hex.");
		   		wpak.focus();
		        wpak.select();
	      		return -1;
	      	}
		}
	}
}

var newlocation;
var count, intervel;
var wait_time;
var have_submit = false;
var new_hostname;
var sure = 0;

function setDivShim()
{
    var DivRef = document.getElementById("notification");
    var IfrRef = document.getElementById("DivShim");
    IfrRef.style.width = DivRef.offsetWidth;
    IfrRef.style.height = DivRef.offsetHeight;
    IfrRef.style.display = "block";
}

function countdown()
{
	var board = document.getElementById("progress_bar");
	count --;
	if (count < 0)
	{
		top.window.location = newlocation;
		//alert("Redirect to " + newlocation);
	}
	else
	{
		board.value = board.value + "|";
		setTimeout("countdown()", intervel);
	}
}

function checkPortEven(thisObj, servName)
{
    if ((parseInt(thisObj.value)%2) != 0)
    {
        alert("Invalid port number! The " + servName + " port must be an even number!");
        return -1;    
    }
    return;       
}

function checkPassword(Pass1, Pass2)
{
    var vPass1 = Pass1.value;
    var vPass2 = Pass2.value;

    for (i = 0; i < vPass1.length; i++){
        c = vPass1.charAt(i);
        if (!( (c>='@' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9') || c=="!" ||
               c=="$" || c=="%" || c=="'" || c=="-" || c=="." || c=="^" || c=="_" || c=="~"))
        {
          alert("You have used invalid characters.\n\nThese characters are valid:\nA-Z, a-z, 0-9 and !$%'-.@^_~ ");
          Pass1.focus();
          Pass1.select();
          return -1;
        }
    }

    if (vPass1 != vPass2){
        alert("The confirm password differs from the password. \nPlease try again.")
        Pass1.focus();
        Pass1.select();
        return -1;
    }
    return 0;
}

function NetConfirm()
{
    var msg = "\nAny incorrect setting may cause system failure.\nConfirm all settings and the system will restart.";
    var netForm = document.NetworkSetting;
	
	/* Only send this form once */
	if (have_submit)	return -1;
	if(checkPortEven(netForm.network_audioport, "RTP audio") == -1)
	    return -1;
	if(checkPortEven(netForm.network_videoport, "RTP video") == -1)
	    return -1;
	
	if (netForm.network_httpport.value == netForm.network_rtspport.value)
	{
	    alert("HTTP port can not be the same as RTSP port.\nPlease change one of them and apply again!");
	    return -1;        
	}
	else if ((netForm.network_httpport.value == netForm.network_audioport.value) || (netForm.network_httpport.value == netForm.network_rtcpaudioport.value) ||
	         (netForm.network_httpport.value == netForm.network_videoport.value) || (netForm.network_httpport.value == netForm.network_rtcpvideoport.value))
	{
	    alert("HTTP port can not be the same as RTP/RTCP audio/video port.\nPlease change one of them and apply again!");
	    return -1;        
	}
	else if ((netForm.network_rtspport.value == netForm.network_audioport.value) || (netForm.network_rtspport.value == netForm.network_rtcpaudioport.value) ||
	         (netForm.network_rtspport.value == netForm.network_videoport.value) || (netForm.network_rtspport.value == netForm.network_rtcpvideoport.value))
	{
	    alert("RTSP port can not be the same as RTP/RTCP audio/video port.\nPlease change one of them and apply again!");
	    return -1;        
	}


	if (netForm.network_videoport.value == netForm.network_audioport.value)
	{
	    alert("RTP video port can not be the same as RTP audio port.\nPlease change one of them and apply again!");
	    return -1;        
	}

	if (checkPort(netForm.network_httpport, 80, "HTTP"))
		return;
	if (checkPort(netForm.network_rtspport, 554, "RTSP"))
		return;
	if (checkPort(netForm.network_audioport, 5556, "RTP audio"))
		return;
    if (checkPort(netForm.network_videoport, 5558, "RTP video"))
		return;
	if (checkPort(netForm.network_rtcpaudioport, 5557, "RTCP audio"))
		return;
    if (checkPort(netForm.network_rtcpvideoport, 5559, "RTCP video"))
	    return;
	if (!checkInAccessNameString(netForm.network_accessname))
		return;
	if (checkPassword(netForm.network_pppoepass, netForm.network_pppoeconfirmpass) == -1)
        	return -1;	
	if (netForm.network_type[0].checked && netForm.network_resetip[1].checked)
	{
        if (checkIPaddr(netForm.network_ipaddress))
	        return;
        if (checkIPaddr(netForm.network_subnet))
	        return;
        if (checkIPaddr(netForm.network_router))
	        return;
        if ((netForm.network_dns1.value.length != 0) && (checkIPaddr(netForm.network_dns1)))
	        return;
        if ((netForm.network_dns2.value.length != 0) && (checkIPaddr(netForm.network_dns2)))
	        return;
	    new_hostname = netForm.network_ipaddress.value;
	}
	else
	    new_hostname = location.hostname;
    
	if (!checkInString(netForm.wireless_ssid))
		return;
		
	if(checkKey(netForm.wireless_key1) < 0 ||
	   checkKey(netForm.wireless_key2) < 0 ||
	   checkKey(netForm.wireless_key3) < 0 ||
	   checkKey(netForm.wireless_key4) < 0)
	{
		return -1;
	}
	if (checkWPAKey() < 0)
		return -1;
  	if (confirm(msg))
  	{
	    have_submit = true;
		newlocation = "http://" + new_hostname + ":" + netForm.network_httpport.value + "/";
		document.getElementById("notification").style.display = "block";
		setDivShim();
		document.getElementById("notify_location").innerHTML = newlocation;
		wait_time = 55;
		count = 100;
		intervel = wait_time * 1000 / count;
		netForm.submit();
		countdown();
  	}
}

function ChangeKeyLengthFormat()
{
	var i;
	var szAddKey;
	var iKeyBytes;
	var tmp, iIndex;
	var sNetwork = document.NetworkSetting;
	var sNetworkH = document.NetworkHidden;
	iKeyBytes = getKeyLength();
	
	iIndex = (sNetwork.wireless_keylength.selectedIndex+1)*64;
 
	  if(sNetworkH.wireless_orgkeylength.value == iIndex)
	{ 
		if(sNetwork.wireless_keyformat.selectedIndex == 0)
		{
			sNetwork.wireless_key1.value = sNetworkH.wireless_orgkey1.value;
			sNetwork.wireless_key2.value = sNetworkH.wireless_orgkey2.value;
			sNetwork.wireless_key3.value = sNetworkH.wireless_orgkey3.value;
			sNetwork.wireless_key4.value = sNetworkH.wireless_orgkey4.value;
		}
		else
		{
			tmp = Hex2Ascii(sNetworkH.wireless_orgkey1.value);
			sNetwork.wireless_key1.value = tmp;
			tmp = Hex2Ascii(sNetworkH.wireless_orgkey2.value);
			sNetwork.wireless_key2.value = tmp;
			tmp = Hex2Ascii(sNetworkH.wireless_orgkey3.value);
			sNetwork.wireless_key3.value = tmp;
			tmp = Hex2Ascii(sNetworkH.wireless_orgkey4.value);
			sNetwork.wireless_key4.value = tmp;
		}
	}
	else
	{
		if(sNetwork.wireless_keyformat.selectedIndex == 0)
		{
				sNetwork.wireless_key1.value = "";
				sNetwork.wireless_key2.value = "";
				sNetwork.wireless_key3.value = "";
				sNetwork.wireless_key4.value = "";
			for(i=0;i<iKeyBytes*2;i++)
			{
				sNetwork.wireless_key1.value += "0";
				sNetwork.wireless_key2.value += "0";
				sNetwork.wireless_key3.value += "0";
				sNetwork.wireless_key4.value += "0";
			}
		}
		else
		{
			sNetwork.wireless_key1.value = "";
			sNetwork.wireless_key2.value = "";
			sNetwork.wireless_key3.value = "";
			sNetwork.wireless_key4.value = "";
			for(i=0;i<iKeyBytes;i++)
			{
				sNetwork.wireless_key1.value += "0";
				sNetwork.wireless_key2.value += "0";
				sNetwork.wireless_key3.value += "0";
				sNetwork.wireless_key4.value += "0";
			}
		}
	}
}

function Ascii2Hex(in_str)
{
    var atr="";
	for (i = 0; i < in_str.length; i ++)
	{
	    tmp = in_str.charCodeAt(i).toString(16);
		if (tmp.length == 1)	tmp = "0" + tmp;
		atr = atr + tmp;
	}
	return atr;
}

function Hex2Ascii(in_str)
{
	var astr = "";
	var asub = "";
	var i;	
	var tmp = in_str.toUpperCase();
	
	if((tmp.length & 1) > 0)	tmp = tmp + "0";
		
	for (i=0; i<tmp.length; i+=2) 
	{
		var c = tmp.charAt(i);
		if (!((c>='0'&& c<='9')||(c>='A' && c<='F')))
			return -2;
		asub = tmp.substring(i, i+2);
		var code = parseInt(asub, 16);
		if (code == 34 || code == 60 || code == 62 || code < 32 || code >= 127)
			astr = astr + " ";
		else if (code > 255) 
			return -2;
		else
			astr = astr + String.fromCharCode(code);
	}
	return astr;
}


function changeSecutityMode()
{
	var e = document.NetworkSetting.wireless_encrypt;
	document.getElementById("wpatable").style.display = "none";
	document.getElementById("weptable1").style.display = "none";
	document.getElementById("weptable2").style.display = "none";
	resetWPA();
	resetWEP();
	if (e.options[e.selectedIndex].value == "1")
	{
		document.getElementById("weptable1").style.display = "block";
		document.getElementById("weptable2").style.display = "block";
	}
	else if (e.options[e.selectedIndex].value == "2")
		document.getElementById("wpatable").style.display = "block";
		
}

function changeWLANMode()
{
    var netForm = document.NetworkSetting;
	var m = netForm.wireless_wlmode;
	// infrastructure
	if (m.options[m.selectedIndex].value == 0)
	{
		netForm.wireless_channel.disabled = 1;
		updateDynSelOpt (netForm.wireless_encrypt, infra_security);
	}
	// ad-hoc
	else
	{
		netForm.wireless_channel.disabled = 0;
		updateDynSelOpt (netForm.wireless_encrypt, adhoc_security);
	}
	changeSecutityMode();
}

function resetWPA()
{
	var netForm = document.NetworkSetting;
	selectTheDropdownEnt(netForm.wireless_algorithm, wireless_algorithm);
	netForm.wireless_presharedkey.value = wireless_presharedkey;
}

function resetWEP()
{
	var netForm = document.NetworkSetting;
	selectTheDropdownEnt(netForm.wireless_authmode, wireless_authmode);
	selectTheDropdownEnt(netForm.wireless_keylength, wireless_keylength);
	selectTheDropdownEnt(netForm.wireless_keyformat, wireless_keyformat);
	selectTheRadioButton(netForm.wireless_keyselect, 4, wireless_keyselect);
	netForm.wireless_key1.value = wireless_key1;
	netForm.wireless_key2.value = wireless_key2;
	netForm.wireless_key3.value = wireless_key3;
	netForm.wireless_key4.value = wireless_key4;
}

function updateWlanChOpts(x)
{
	x.length = wlan_endchannel - wlan_beginchannel + 1;
	j = wlan_beginchannel;
	for (i = 0; i < x.length; i ++) {
	    x.options[i].text = j;
		x.options[i].value = j;
		j ++;
	}
	return x.length;
}

