var defaultAreaCode='314'


function inValid(objFormelement){
	str = objFormelement.value
	if(str && str.charAt(0) != "'"){
	objFormelement.value = 	str + ' [Invalid]';
	objFormelement.style.color= "crimson";
	};
}

function rmInValid(objFormelement){
	str = objFormelement.value
	objFormelement.style.color= "black";
	p = str.indexOf("[Invalid]");
	if(p != -1){
		p2 = str.indexOf(" [Invalid]");
		if(p2 != -1)p =p2

		str = str.substring(0,p);
		objFormelement.value = str
		return str
	}
	return str
}

function cleanNum(checkString,unsigned,asint,comma_not_dot){

	if(checkString==undefined)return 0;
	checkString=String(checkString)

	if(checkString.indexOf('[object')!=-1)return 0;

	unsigned = (unsigned==undefined ? false : unsigned);
	asint= (asint==undefined ? false : (asint ? true : false))
	//comma_not_dot =
	if(comma_not_dot == undefined)comma_not_dot= false;

	var decsep = '.'
	//comma_not_dot = (comma_not_dot==undefined? false : comma_not_dot)
	if(comma_not_dot)decsep = ',';

	var newString = '';
	var dot = 0;

	for (i = 0; i < checkString.length; i++) {
			ch = checkString.charAt(i);
			if ( ch == decsep ){
				if(newString=="")
					newString += 0

				if(dot >0)
					continue;

				newString += '.';
				dot = newString.length;
			}
			else if ((!unsigned) && ch == "-" && newString==''){
					newString += ch;
			}
			else if (ch >= "0" && ch <= "9"){
				if(newString==""&& ch ==0)
					continue;
				else
					newString += ch;
			}
	 };

    if(asint && dot>0) return newString.substr(0,dot-1)

    return newString;
}
/*
function cleanNum(checkString,unsigned,asint){

	if(checkString==undefined)return 0;
	if(unsigned==undefined)unsigned= false
	if(asint==undefined)asint= false

	var newString = '';
	var dot = 0;

	for (i = 0; i < checkString.length; i++) {
			ch = checkString.charAt(i);
			if ( ch == "." ){
				if(newString=="")
					newString += 0

				if(dot >0)
					continue;

				newString += ch;
				dot = newString.length;
			}
			else if ((!unsigned) && ch == "-" && newString==''){
				newString += ch;
			}
			else if (ch >= "0" && ch <= "9"){
				if(newString==""&& ch ==0)
					continue;
				else
					newString += ch;
			}
	 };

        if(asint && dot>0)return newString.substr(0,dot-1)

	return newString;
}
*/

function cleanWordChr(iStr) {
	if(!iStr)
		return '';
	var myStr=''
	var oldChr=' ';
	for (i = 0; i < iStr.length; i++) {
		//iCOde = iStr.charCodeAt(i);
		iChr = isLocalChar(iStr.charAt(i))
		if(iChr){
			myStr += iChr
			oldChr=iChr
			continue;
		}
	/*
		if(
		||(iCOde > 47 && iCOde < 58)
		||( iCOde > 64 && iCOde < 91)
		||( iCOde > 96 && iCOde < 123)){
			myStr += iStr.charAt(i)
			oldCode=iCOde
			continue;
		};
	*/
		if(oldChr != ' ') myStr += ' '
		oldChr=' '
	/*
		if(oldCode != 32) myStr += ' '
		oldCode=32
	*/
	}
	if(myStr)
		return  myStr;
	else
		return  '';
}

function trim(iStr) {
	if(!iStr)
		return '';

	i = 0; 	k = 0; 	len = iStr.length;
	len -= 1;
	for (i = 0; i <= len; i++) {
		if(iStr.charCodeAt(i) <= 32)
			continue;
		else
			break;
	}
	for (k = len; k >= 0; k--) {
		if(iStr.charCodeAt(k) <= 32)
			continue;
		else
			break;
	}
	return  iStr.substring(i,k+1);
}




function toUrl (objFormelement) {
	str1 = objFormelement.value
	str1 = trim(str1);
	if(str1=='http://')str1='';
	if(!(str1.substring(0,6)=='ftp://'||str1.substring(0,7)=='http://'||str1.substring(0,8)=='https://')){
		if(str1)str1 = 'http://'+ str1;
		objFormelement.value =  str1;
		return true;
	}

}


function toFloat (objFormelement) {
	str1 = rmInValid(objFormelement)

	p = str1.indexOf("e");

	if(p >0 ){
		alert(str1.substring(0,p) + ' '+str1.substring(p+1,str1.length))
		ibase=cleanNum(str1.substring(0,p),false,false);
		iexp=cleanNum(str1.substring(p+1,str1.length),false,true);
	 	if( parseInt(iexp) > 0){ iexp = '+' + iexp }
	 	str = ibase + 'e' + iexp
	} else {
		str = cleanNum(str1, false,false);
	}


	str2 = Number(str)
	if(isNaN(str2)){
		inValid(objFormelement);
		return false;
	}
	else if(!isFinite(str2)){
		str2= str + ' [Infinity]'
		objFormelement.style.color= "blue";
	}
	objFormelement.value =  str2;
	return true;
}

function toDec(objFormelement,prec,scale,unsigned)
{
	if(objFormelement==undefined)return false;
	checkString = rmInValid(objFormelement)

	newString = toDecimal(checkString,prec,scale,unsigned)

	if(newString==undefined)
	return false;

	objFormelement.value =  newString;
	return true;
}

function toDecimal(checkString,prec,scale,unsigned)
{
	if(checkString==undefined)return '';

	scale = parseInt(scale)
	scale =	(isNaN(scale) ? 2 : scale )
	if(scale>20)scale=20;
	else if(scale<0)scale=0;
//	prec = parseInt(prec)
//	prec =	(isNaN(prec) ? 10 : ( prec <= 0 ? 10 : prec ))

	unsigned = (unsigned==undefined ? false : ( (unsigned) ? true : false));

	//self.status = unsigned

	checkString =	Number(cleanNum(checkString,unsigned,false));

	if(scale<=0){
		newString = String( Math.round(checkString) )
		return newString;
	} else {

		newString = String(round(checkString,scale));

		dot = newString.indexOf(".");
		if(dot==0){
			newString = '0' + newString
			dot++
		};

		if(dot == -1){
			dot = newString.length
			newString += '.000000000000000000000000'
		}
		else {
			newString += '000000000000000000000000'
		}

		newString = newString.substr(0,dot+scale+1)
		return   newString;
	}
}


/*
function toDec(objFormelement,prec,scale,unsigned)
{
	checkString = rmInValid(objFormelement)
	if(!scale)scale=2
	if(!prec)prec=10
	if(!unsigned)unsigned=false

	newString = round(cleanNum(checkString,unsigned),scale) + '';
	if(newString.length > prec + 2){
		inValid(objFormelement)
		return true;
	}
	else {
	dot = newString.indexOf(".");
	if(dot == -1){
		dot = newString.length
		newString += '.000000000000'
	}
	else {
		newString += 000000000000
	}
	newString = newString.substr(0,dot+scale+1)

	if (checkString != newString) {
		objFormelement.value =  newString;
	}
	return true;
	}
}
*/


function round(number,scale) {
	scale = ((scale==undefined)||isNaN(Number(scale))  ? 0 : Number(scale));
	if(scale==0) return Math.round(number);
	number = ((number==undefined)||isNaN(Number(number))  ? 0 : Number(number));
	return Math.round(number*Math.pow(10,scale))/Math.pow(10,scale);
}


function toInt(objFormelement,isUnsigned, maxLength)
{
	checkString = rmInValid(objFormelement)
	if(!isUnsigned || isUnsigned==0){
	   isUnsigned=false;
	   if(!maxLength)maxLength= 10
	} else {
	   isUnsigned=true;
	   if(!maxLength)maxLength= 11
	}
	newString = cleanNum(checkString,isUnsigned,1);
	if(newString.length > maxLength) {
		inValid(objFormelement)
		return false;
	} else if (checkString != newString) {
		if(newString != 0)
			newString=parseInt(newString);

		objFormelement.value =  newString;
		return true;
	} else {
		return true;
	}
}



function toPosInt(objFormelement,max)
{
	return toInt(objFormelement,true,max)
}


// function toFloat(objFormelement)
// {
// 	checkString = objFormelement.value
// 	newString = cleanNum(checkString,false,false);
// 	if (checkString != newString) {
// 		objFormelement.value =  newString;
// 	}
// }

function toEmail(objFormelement)
{
    chkstr = rmInValid(objFormelement)
    if(!chkstr){
        inValid(objFormelement)
         return false
    }

    chkstr = parseEmail(chkstr)
    if( chkstr ){
	objFormelement.value = chkstr
	return true
    }
    else {
	inValid(objFormelement)
	return false
    }
}

function  toEmailAddr(objFormelement){
    chkstr = rmInValid(objFormelement)
    if(!chkstr || chkstr.indexOf('@')==-1){
        inValid(objFormelement)
         return false
    }
 	var outStr ='';
	ziStr = trim(chkstr)
	if(ziStr.indexOf(",")!= -1)
		ziStr = ziStr.substring(0,ziStr.indexOf(",")-1);

	if(ziStr){
	var iName=""
	var email="";
	if(ziStr.indexOf("(") != -1){
		 posIt = ziStr.indexOf('(')
		 iName = ziStr.substring(posIt)
		 ziStr = ziStr.substring(0,posIt -1)
	};

	if(ziStr.indexOf("<")!= -1){
		 wHere =ziStr.indexOf("<");
		 iName = ziStr.substring(0,wHere)
		 ziStr = ziStr.substring(wHere)
	};
	email = parseEmail(ziStr)
	}

        if(email){
	if(iName) iName = trim(cleanWordChr(iName))

	if(iName)
	   outStr = '"' + iName + '" <'+ email + '>';
	else
	   outStr =  email;
	}

    if(outStr){
	objFormelement.value = outStr
	return true
    }
    else {
	inValid(objFormelement)
	return false
    }
}


function parseEmail(str)
{
   if(!str)
   	return '';

    var chkstr = str.toLowerCase();
    var domainPart 	= "";
    var tldPart 	= "";
    var localPart 	= "";
    var sawAt 		= false;
    var lastDot = chkstr.lastIndexOf('.')

    if(lastDot != -1){
        for (var i = 0; i < chkstr.length; i++) {
        ch = chkstr.charAt(i)

        if (ch == '@'){
            sawAt=true;
            continue;
        };
        if( sawAt == true ){
       		  if( i < lastDot )
            domainPart += isDomainChar(ch)
          	  else if (ch >= 'a' && ch <= 'z')
            tldPart += ch

           continue;
        };
         localPart += isLocalChar(ch)
      };
    };

    if( localPart.length >0 && tldPart.length>1 && domainPart.length >1){
        return  localPart + '@' + domainPart + '.' + tldPart
    }
    else {
        return ''
    }
}

function isDomainChar(dchr){
    if (  (dchr >= "a" && dchr <= "z")
        || (dchr >= "0" && dchr <= "9" )
        || (dchr == ".")
        || (dchr == "-")){
    return dchr;
    };
    return '';
}
function isLocalChar(lchr){
    var ord = lchr.charCodeAt(0)
    if(ord < 33
        || ord ==34
        || ord ==40
        || ord ==41
        || ord ==44
        || (ord >= 58 && ord <= 60)
        || ord == 62
        || ord == 64
        || (ord >=91 && ord <= 93)
        || ord > 126 ) {
        return '';
    } else {
        return lchr
    }
}


function toZip(objFormelement,req)
{
	zip = rmInValid(objFormelement)

	var zipcode =cleanNum(zip,true,true);

	if (zipcode && zipcode.length == 9){
		zcode =   zipcode.substring(0,5)+ '-' + zipcode.substring(5,9)
		objFormelement.value = zcode;
		return true;
	}
	else if (zipcode && zipcode.length == 5){
		objFormelement.value = zipcode
		return true;
	}
	else {
		inValid(objFormelement)
		return false;
	}
}

function toTime (objFormelement) {
	timestr = rmInValid(objFormelement)
    	timestr = timestr.toLowerCase();

	var pm = 0
	if(timestr.indexOf("a")!=-1)
		pm = -1
	else if(timestr.indexOf("p")!=-1)
		pm = 1


	var newString=''
	for (i = 0; i < timestr.length; i++) {
		ch = timestr.charAt(i);
		if(ch =='.')ch=':'
		else if(ch =='-')ch=':'

		if(ch >= "0" && ch <= "9" || ch ==':'){
			newString += ch;
		}
	}
	if(newString ==''){objFormelement.value ='';  return true;};


	newString += ':0'

	times = newString.split(':');

	if(times && times.length > 1 && times.length < 5){

	if(times[1]>60)  times[1]= Math.round( times[1]* 0.01 * 60 - 0.5);
	if(times[1]>59) {
		times[1]=0;
		if(times[0]==12 && pm != 0)times[0]=1;
		else times[0]++
	}

	if(times[0]>23)
		times[0] -= 24

	if(times[1]<=59 && times[1]>-1 && times[0]>-1 && times[0]<24){
		if(!times[1])times[1]='00';
		else if(times[1] < 10)
			times[1] = '0' + parseInt(times[1]);

		times[0] = parseInt(times[0]);

		if(times[0] > 12){
		times[0] = parseInt(times[0])-12;
			pm = 1
		}
		else if(times[0] == 0){
		times[0] = 12;
			pm = -1
		}

	     	if(pm==0 && (times[0]< 8||times[0]==12))
	     		pm=1
		else if(pm==0)
			pm=-1


	     objFormelement.value = times[0] + ':' + times[1] + ((pm==1) ? ' PM' : ' AM')
	     return true;
	}
	}

	inValid(objFormelement)
	return false;
}


function toUsPhone(objFormelement,defaultArea)
{
	//(314) 122-2222 x4323  => char(20)

	var checkString = rmInValid(objFormelement)

	var len = checkString.length;
	var intdialcode = checkString.indexOf("+1");
	if(intdialcode > -1 && intdialcode < 3)
		checkString = 	checkString.substring(intdialcode + 2,len)

	if(checkString.charAt(0) == "+")   return true;

	var extension = "";
	var newString = "";

	for (i = 0; i < len ; i++) {
		ch = checkString.substring(i, i+1);
		if (!extension && (ch == "x" || ch == "X"))  {
			extension = 'x'
			continue;
		};

		if (ch >= "0" && ch <= "9")  {
			if(extension)
			extension += ch;
			else
			newString += ch;
		};
	}

	if ( newString.length == 7 ){
	    if(defaultAreaCode && !defaultArea)
	    	defaultArea= defaultAreaCode;
	    if(defaultArea)
	    	newString = defaultArea + newString;
	}

	if ( newString.length == 10){
		newString = 	'(' + newString.substring(0,3)+ ') ' + newString.substring(3,6) + '-' + newString.substring(6,10);
		if(extension && extension.length >1 && extension.length < 6)
		newString +=	' '+ extension

		objFormelement.value = newString
		return true
	}
	else {
		inValid(objFormelement)
	}
}

function toZip(objFormelement)
{
	zip = rmInValid(objFormelement)

	var zipcode =cleanNum(zip,true,true);

	if (zipcode && zipcode.length == 9){
		zcode =   zipcode.substring(0,5)+ '-' + zipcode.substring(5,9)
		objFormelement.value = zcode;
		return true;
	}
	else if (zipcode && zipcode.length == 5){
		objFormelement.value = zipcode
		return true;
	}
	else {
		inValid(objFormelement)
		return false;
	}
}

function toNumFormat(objFormelement,scale,lead,sep)
{
	afloat = cleanNum(rmInValid(objFormelement))
	if(afloat == 0){
		objFormelement.value = ''
	} else {
		newstr = toNumFormatted(afloat,scale,lead,sep)
		if(newstr==undefined)
			return false;

		objFormelement.value = newstr
	}
	return true;
}

function toNumFormatted(afloat,scale,lead,sep)
{

	if (afloat==undefined )return ''

	scale = (scale==undefined ? 2 : parseInt(scale));
	if(isNaN(scale)) scale=0

	afloat = toDecimal(afloat,10,scale);


	if(lead==undefined)lead =  '';
	if(sep==undefined)sep =  ',';



	if(scale > 0){
	newString = String( round(afloat,scale));
	dot = newString.indexOf(".");
	var prefix=''

	if(dot == -1){
		suffix  = '000000000000000000000000'
		prefix=newString

	}
	else if (dot == 0){
		suffix  = newString.substring(1)+ '000000000000000000000000'
		prefix='0'
	}
	else {
		prefix = parseInt(newString.substring(0,dot))
		suffix  = newString.substring(dot+1) + '000000000000000000000000'
	}
		S = (lead=='$' ? '$ ' : '')+ formatNum(prefix,'',sep,0) + '.' + suffix.substr(0,scale) + (lead=='%' ? ' %' : '');
		return S;
	}
	else {
		return  formatNum(Math.round(afloat),lead,sep,1)
	}
}



function formatNum(value, lead, sep, space)
{
	if(space==undefined)space==false;
	var strValue = new String(value);
	var len = strValue.length;
	var n;
	var strRet = '';
	var ctChar = 3 - (len%3);
	if (ctChar == 3) ctChar =0;
	for (n=0; len > n; n++) {
		if (ctChar == 3) {
			strRet += sep;
			ctChar = 0;
		}
		ctChar++;
		strRet += strValue.substring(n,n+1)
	}
	if (lead == '%') {
		return strRet +(space ? ' ' : '')+ lead;
	}
	else if (lead) {
		return lead +(space ? ' ' : '')+ strRet;
	}
	else {
		return strRet;
	}
}



