/*
 * Pragma ident    "@(#)util.js    1.0    04/09/25    SMI"
 *
 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
 * Use is subject to license terms.
 */

function isEmpty(string){
	if(string == null){
		return true;
	}
	string.replace(/\s/g, ''); //trim space
	if(string.length == 0){
		return true;
	}
	return false;
}

// A vaild hostname is a RFC 952 "name", but permit underscore (_) in the name.
function isVaildHostname(hostname){
        // Have to seperate the regular express into sub expresses or it can not run on Netscape 4.79
	if(isEmpty(hostname)){
		return false;
	}
	if(/^[0-9]/.test(hostname)){ //start with digit, maybe an ip
		var ipRegexp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
		return ipRegexp.test(hostname);
	}
        var invaild = false;
        invaild |= /^[^a-zA-Z]/.test(hostname); //hostname must start with alpha character
        invaild |= /[^a-zA-Z0-9\-._]/.test(hostname); //hostname drawn from alphabet, digits, minus, period and underscore
        invaild |= /.{31,}/.test(hostname); //hostname up to 30 characters
        invaild |= /[^a-zA-Z0-9]$/.test(hostname); //hostname end with alpha and digit characters
        return !invaild;
}

var errorMessageInvaildHostname = 
	" is not a vaild host name or ip address.\n" +
	"A host name is a string of one to 30 characters. The first character\n" +
	"must be an alphabetic (A-Z or a-z) character. The remaining characters\n" +
	"can be alphabetic, numeric (0-9), hyphen (-), period (.), or underscore (_).\n" +
	"No distinction is made between upper case and lower case alphabetic\n" +
	"characters. The last character must be an alphabetic (A-Z,a-z) or numeric (0-9) character.\n" +
	"A host name cannot contain any whitespace characters.";

var errorMessageEmptyField = " can not be empty. Enter a value for this field.";

function checkHostname(hostname, msg){
	if(isEmpty(msg)){
		msg = "Hostname";
	}
	if(isEmpty(hostname)){
		alert (msg + errorMessageEmptyField);
		return false;
	}
	if(isVaildHostname(hostname)){
		return true;
	}
	alert ('"' + hostname + '"' + errorMessageInvaildHostname);
	return false;
}

function checkHostnames(hostnames){
	for(var i=0; hostnames!=null && i<hostnames.length; i++){
		var vaild = checkHostname(hostnames[i], "Hostnames and client names");
		if(!vaild){
			return false;
		}
	}
	return true;
}

function checkSerialClients(form){
	var isSerial = false;
	for(var i=0; i<form.option.length; i++){
		if(form.option[i].checked && form.option[i].value == "saip"){
			isSerial = true;
			break;
		}
	}
	if(!isSerial){
		return true;
	}
	var remotemachine = form.remotemachine.value;
	if(isEmpty(remotemachine)){
		alert ("Please enter ppp-client name.");
		return false;
	}
	var hostnames = remotemachine.split(/,/g);
	return checkHostnames(hostnames);
}
