/* 
 * u-media.js - Common Function Definition.
 *
 * Copyright (c) 2008, U-Media Communications, Inc. All Rights Reserved.
 *
 */
 
var stopToWait = false;
var http_request = false;

function objectDisplay(IDName, value) {
	document.getElementById(IDName).style.display = value;
}

function removeAllOption(selectID) {
	var docTempName, loopCount;
	docTempName = document.getElementById(selectID);
	for (loopCount=docTempName.length; loopCount>=0; loopCount--)
		docTempName.remove(loopCount);
}

function addNewOption(selectID, optionID, optionName, optionValue, optionText) {
	var docTempName, newElement;
	docTempName = document.getElementById(selectID);
	newElement = document.createElement("option");
	newElement.id = optionID;
	newElement.name = optionName;
	newElement.value = optionValue;
	newElement.text = optionText;
	try {
		docTempName.add(newElement, null); //standards compliant
	}
	catch(ex) {
		docTempName.add(newElement); //IE only
	}
}


function stringToHex(tagName)
{
	var resultStr="";
	var docTemp;
	docTemp = document.getElementById("display_"+tagName).value;
	
	for (loopCount=0; loopCount<docTemp.length; loopCount++){
		if (docTemp.substr(loopCount, 1) == '\\'){
			if (docTemp.substr(loopCount+1, 1) == '"'){
				resultStr = resultStr + docTemp.substr(loopCount+1, 1);
				loopCount++;
			}
			else
				resultStr = resultStr + docTemp.substr(loopCount, 1);
		}
		else
			resultStr = resultStr + docTemp.substr(loopCount, 1);
	}
	document.getElementById("submit_"+tagName).value = resultStr;
}


function hexToString(string)
{
	var loopCount=0;
	var origSSID="";
	var tempChar;
	
	for (loopCount=0; loopCount<string.length; loopCount=loopCount+2) {
		tempChar = String.fromCharCode(parseInt(string.substr(loopCount, 2), 16));
		if (tempChar == '"')
			origSSID = origSSID + "\"";
		else
			origSSID = origSSID + tempChar;
	}
	return origSSID;
}

function translateSubmitToHex(tagName)
{
	var resultStr="";
	var docTemp;
	docTemp = document.getElementById("display_"+tagName).value;
	
	for (loopCount=0; loopCount<docTemp.length; loopCount++){
		if (docTemp.substr(loopCount, 1) == '\\'){
			if (docTemp.substr(loopCount+1, 1) == '"'){
				resultStr = resultStr + docTemp.substr(loopCount+1, 1);
				loopCount++;
			}
			else
				resultStr = resultStr + docTemp.substr(loopCount, 1);
		}
		else
			resultStr = resultStr + docTemp.substr(loopCount, 1);
	}
	document.getElementById("submit_"+tagName).value = resultStr;
	
	/*if (document.getElementById("submit_"+tagName).value.length < 1) {
		alert("The SSID length can't less than 1 character!");
		return false;
	}*/
	if ((tagName == "ESSID") && (document.getElementById("submit_"+tagName).value.length > 32)) {
		alert("The SSID length can't big than 32 character!");
		return false;
	}
	return true;
}

function transSSID(SSID)
{
	var loopCount=0;
	var origSSID="";
	var tempChar;
	
	for (loopCount=0; loopCount<SSID.length; loopCount=loopCount+2) {
		tempChar = String.fromCharCode(parseInt(SSID.substr(loopCount, 2), 16));
		if (tempChar == '"')
			origSSID = origSSID + "\"";
		else
			origSSID = origSSID + tempChar;
	}
	return origSSID;
}

function getHTMLContent(IDName) {
	if(window.ActiveXObject) { // IE
        return document.getElementById("ESSID_"+loopCount).innerText;
    } else if (window.XMLHttpRequest) { // Mozilla, Safari,...
        return document.getElementById("ESSID_"+loopCount).textContent;
    }
}

function checkWPAPSK(value) {
	if (value.length == 64) {
		for (loopCount=0; loopCount<64; loopCount++)
		{
			checkValue = value.substr(loopCount, 1);
			if (!(parseInt(checkValue, 16) >= 0) && !(parseInt(checkValue, 16) <= 15)) {
				alert("Please input 64 Hex character of pre-shared key!");
				return false;
			}
		}
		return true;
	}
	else if (value.length < 8 || value.length > 63) {
		alert("The passphrase key must between 8 and 63 ASCII characters!");
		return false;
	}
	
	if (!translateSubmitToHex("WPAPSK")){
		return false;
	}
	return true;
}

function selectWEPKeyLength(keyLength) {
	if (keyLength == 64) {
		for (loopCount=0; loopCount<4; loopCount++) {
			docTemp = document.getElementById("WEPKey"+loopCount);
			//docTemp.size = 11;
			docTemp.maxLength = 10;
			
			docTemp = document.getElementById("WEPKey"+loopCount).value;
			if (docTemp.length > 10)
				document.getElementById("WEPKey"+loopCount).value = docTemp.substr(0,10);
		}
	}
	else if (keyLength == 128) {
		for (loopCount=0; loopCount<4; loopCount++) {
			docTemp = document.getElementById("WEPKey"+loopCount);
			//docTemp.size = 27;
			docTemp.maxLength = 26;
		}
	}
	if (document.getElementById("wepPassphrase").value != "")
			Update_WEPKey(document.getElementById("wepPassphrase").value);
}

function selectWPAMode(mode) {
	if (mode*1 == 1) //WPA
	{
		//document.getElementById("WPAPersonalMode").options[0].selected = true;
		removeAllOption("WPAPersonalEncryption");
		addNewOption("WPAPersonalEncryption", "", "", "0", "TKIP");
	}
	else if ((mode*1 == 2) || (mode*1 == 3)) //WPA2, WPA2 Mixed
	{
		//document.getElementById("WPAPersonalMode").options[1].selected = true;
		removeAllOption("WPAPersonalEncryption");
		addNewOption("WPAPersonalEncryption", "", "", "1", "AES");
		addNewOption("WPAPersonalEncryption", "", "", "2", "TKIP or AES");
		/*if (mode == 2)
			docTemp = document.getElementById("WPAPersonalEncryption").options[0];
		else if (mode == 3)
			docTemp = document.getElementById("WPAPersonalEncryption").options[1];
		docTemp.selected = true;*/
	}
}

function Update_WEPKey(passphrase)
{	
	var wepkey = new Array(4);
	var pp = passphrase;
	var key_len = document.getElementById("WEPKeyLength").value;
	
	if (pp=='') {
		//key.value='';
		/*key0.value='';
		key1.value='';
		key2.value='';
		key3.value='';*/
	} else {
		var l=pp.length;
		if(key_len == 128){
			var seed="";
			for (i=0;i<64;i++) seed+=pp.charAt(i%l);
			wepkey[0]=wepkey[1]=wepkey[2]=wepkey[3]=MD5(seed).slice(0,26);
		}else{
			var rand=0;
			for (i=0;i<l;i++) rand^=(pp.charCodeAt(i)<<((i%4)*8));
			
			for(i=0; i<4; i++){
				var s="";
				for (j=0;j<5;j++) {
					rand*=0x343fd;
					rand+=0x269ec3;
					rand&=0xffffffff;
					s+=ToHex(rand>>16);
				}
				wepkey[i]=s;
			}
		}
		document.getElementById("WEPKey0").value = wepkey[0];
		document.getElementById("WEPKey1").value = wepkey[1];
		document.getElementById("WEPKey2").value = wepkey[2];
		document.getElementById("WEPKey3").value = wepkey[3];	
	}
}
function atoi(str, num)
{
    i=1;
    if(num != 1 ){
        while (i != num && str.length != 0){
            if(str.charAt(0) == '.'){
                i++;
            }
            str = str.substring(1);
        }
        if(i != num )
            return -1;
    }

    for(i=0; i<str.length; i++){
        if(str.charAt(i) == '.'){
            str = str.substring(0, i);
            break;
        }
    }
    if(str.length == 0)
        return -1;
    return parseInt(str, 10);
}

function isAllNum(str)
{
	for (var i=0; i<str.length; i++){
	    if((str.charAt(i) >= '0' && str.charAt(i) <= '9') || (str.charAt(i) == '.' ))
			continue;
		return 0;
	}
	return 1;
}

function checkRange(str, num, min, max)
{
	d = atoi(str, num);
	if (d > max || d < min)
		return false;
	return true;
}

function checkIpAddr(field, ismask, msg)
{
	if (field.value == "") {
		alert("Error. " + msg + "is empty!");
		//field.value = field.defaultValue;
		//field.focus();
		return false;
	}

	if (isAllNum(field.value) == 0) {
		alert("The " + msg + "should be a [0-9] number.");
		//field.value = field.defaultValue;
		//field.focus();
		return false;
	}

	if (ismask) {
		if ((!checkRange(field.value, 1, 0, 256)) ||
				(!checkRange(field.value, 2, 0, 256)) ||
				(!checkRange(field.value, 3, 0, 256)) ||
				(!checkRange(field.value, 4, 0, 256)))
		{
			alert("The " + msg + " is illegal value!");
			//alert("The " + msg + "is illegal value!");
			//field.value = field.defaultValue;
			//field.focus();
			return false;
		}
	}
	else {
		if ((!checkRange(field.value, 1, 0, 255)) ||
				(!checkRange(field.value, 2, 0, 255)) ||
				(!checkRange(field.value, 3, 0, 255)) ||
				(!checkRange(field.value, 4, 1, 254)))
		{
			alert("The " + msg + " is illegal value!");
			//field.value = field.defaultValue;
			//field.focus();
			return false;
		}
	}
	return true;
}

function makeRequest(url, content, fieldID, disableFieldID) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert("Giving up :( Cannot create an XMLHTTP instance");
		return false;
	}
	http_request.onreadystatechange = function () {alertContents(fieldID, disableFieldID)};
	http_request.open('POST', url, true);
	//http_request.send(content);
}

function alertContents(fieldID, disableFieldID) {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			reWirteList(fieldID, disableFieldID, http_request.responseText);
		} else {
			//alert('There was a problem with the request.');
		}
	}
}

function reWirteList(fieldID, disableFieldID, str)
{
	stopToWait = true;
	
	if (disableFieldID != "" && str != "")
		objectDisplay(disableFieldID, "none")
	
	document.getElementById(fieldID).innerHTML = str;
}

function fwUpgraceStatus(status, IPandMask)
{
	docTemp = IPandMask;
	index = docTemp.indexOf(','); //IP
	currentIP = docTemp.substr(0, index);
	
	if (status*1 == 1)
		top.location.href = "http://" + currentIP + "/admin/upgrade.html";
}

function wpsStatus(status, mainPageName)
{
	/*docTemp = IPandMask;
	index = docTemp.indexOf(','); //IP
	currentIP = docTemp.substr(0, index);*/
	
	if (status*1 == 1)
	{
		if (mainPageName != "wps_status.html")
			top.location.href = "../station/wps_status.html";
	}
}