/**********************************
jsPhoneObject 
Usage: Object Script to be included as a source file. Contains functions to format a phone number and check the format.
Created by Jeff Lee on 06/28/2001
Last Modified by Jeff Lee on 8/24/2001
Dependants: None
**********************************/


function jsPhoneObject() {
	var defaultFormat = "(###)###-####";
	var minimumFinalLength = "(###)###-####".length;
	
/**********************************
jsPhone.fixFormat(phone number to be formatted, optional format)
Usage: fixFormat formats a phone 
Example:
<input type="text" onkeyup="this.value=jsPhone.fixFormat(this.value);">
<input type="text" onblur="this.value=jsPhone.fixFormat(this.value,'###-###-####');">
**********************************/
	this.fixFormat = function (theValue,theFormat){ // this creates a method in the jsPhoneObject with a minimum of 1 argument
		if(event.keyCode==8) return theValue;
		argv = this.fixFormat.arguments;
		format = ((argv.length==2)?argv[1]:defaultFormat);
		theValue = theValue.replace(/[^0-9]/g,"");
		if(theValue=="") return theValue;
		tmp="";
		j=0;
		for (i=0;i<format.length;i++) {
			if(format.substr(i,1)=="#") {
				tmp+=theValue.substr(j,1);
				j++
				if(j==theValue.length) break;
			} else if(format.substr(i,1)=="%") {
				while (true) {
					tmp+=theValue.substr(j,1);
					j++
					if(j==theValue.length) break;
				}
				break;
			} else {
				tmp+=format.substr(i,1);
			}
		}
		return tmp;
	}
	
	this.checkFormat = function (theValue){
		if(this.checkFormat.arguments.length>1) {
			minimumLength = ((this.checkFormat.arguments.length>2)?this.checkFormat.arguments[2]:this.checkFormat.arguments[1].length);
			if(theValue.length < minimumLength) return false;
			if(theValue!=this.fixFormat(theValue,this.checkFormat.arguments[1])) return false;
		} else {
			if(theValue.length < minimumFinalLength) return false;
			if(theValue!=this.fixFormat(theValue)) return false;
		}
		return true;
	}
}

var jsPhone = new jsPhoneObject();