// ******************************************************************
// This file contains functions that are very useful for web design.
// Sadly, most of these functions were created by other people and 
// not by me.  Some have been modified to better suite my needs.
//
// The list of function in this file are as followed:
//		- ltrim (strText) 
//		- rtrim (strText)
//		- trim (strText)
//		- isdefined(variable)
//		- openPopUp(cellValue, url,target,attributes) 
//		- numbersonly(myfield, e,dec) //"0123456789.-/"
//		- digitssonly(myfield, e)  //"0123456789" 
//		- js_formatCurrency(strValue, strDlrSign)
//		- CurrToInt(cellValue)
//		- Valid_Email(str, a)
//		- isDate(dateStr)
//		- firstFocus()
//		- FormElementIsArray(obj)
//		- CheckForDate(vThis)
//		- DefaultDate(vThis,iOn)
//		- ShowHide(vthis, varToShow)
//		- Right(str, n)
//		- Left(str, n)
//		- blockSubmitButton(a,newButtonName,alertMsg)
//		- dateAdd(start, interval, number, blnFormat)
//		- highlightTextField(field)
//		- UnHighlightTextField(field)
//		- highlightSelectField(field)
//		- Format_Float(vThis,iDecPlaces)
//		- StrToDate(strDate)
//   	- EmployeeNumberOnly(myfield, e)
//		- ToggleHidden (fieldID)
//		- letternumber(e,blnAllowSpaces)
//		- randomString(e,intSize)
// ******************************************************************
//------------------------------------------------------------------------------------------
function ltrim(strText) { 
    // this will get rid of leading spaces 
    while (strText.charCodeAt(0) == 160 || strText.charCodeAt(0) == 32)
		strText = strText.substring(1, strText.length)
	return strText;
}
//------------------------------------------------------------------------------------------
function rtrim(strText){
    // this will get rid of trailing spaces 
    while (strText.charCodeAt(strText.length-1) == 160  || strText.charCodeAt(strText.length-1) == 32) 
        strText = strText.substring(0, strText.length-1);        
   return strText;
}
//------------------------------------------------------------------------------------------
function trim(strText) { 
    // this will get rid of leading/trailing spaces 
   return ltrim(rtrim(strText));
}
//------------------------------------------------------------------------------------------
// isdefined:  used to verify that a varible has been defined in case 
//             variables are created dynamically
function isdefined(a) { 
	return (typeof(window[a]) == "undefined")? false: true; 
	//return (typeof(variable) == "undefined")? false: true; 
} 
//----------------------------------------------------------------------------------------
function isObject(a) {
    return (a && typeof a == 'object')
}
//----------------------------------------------------------------------------------------
function isUndefined(a) {
    return typeof a == 'undefined';
}
//----------------------------------------------------------------------------------------
function openPopUp(url,target,attributes,popup_size) {
// THIS SCRIPT FROM BRAVENET
	var def_attributes = 'channelmode=no;directories=no;toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,';
	//var def_attributes = 'channelmode=no,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,';
	if (attributes == '') attributes = def_attributes;
	attributes += popup_size;
	popup = window.open(url,target,attributes);
	//popup.moveTo((window.screen.availWidth -  550) / 2, (window.screen.availHeight - 700) / 2);
	popup.moveTo(100,50);
	popup.focus();blur();
}
//----------------------------------------------------------------------------------------
// numbersonly: When you want to limit numeric values including .-/ only in any textbox. 
// How to Use: <input type="textbox" ... onKeyPress="return numbersonly(this, event)" >
// 7/27/06: Drew Theiss -- Removed /
function numbersonly(myfield, e,dec){
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers (add / to put them back in)
	else if ((("0123456789.-/").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == ".")){
	   myfield.form.elements[dec].focus();
	   return false;
	}
	else {
		alert('Only "0123456789.-" are accepted here.');
		return false;
	}
}
//----------------------------------------------------------------------------------------
// numbersonly: When you want to limit numeric values (0-9) only in any textbox. 
// How to Use: <input type="textbox" ... onKeyPress="return numbersonly(this, event)" >
function digitsonly(myfield, e){
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;	

	else {
		alert('Only "0123456789" are accepted here.');
		return false;
	}
}
//----------------------------------------------------------------------------------------
// js_formatCurrency: formats a string into currency format
function js_formatCurrency(strValue, strDlrSign){
	strValue = strValue.toString().replace(/\$[\s]|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue * 100 + 0.50000000001);
	intCents = dblValue % 100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if (intCents < 10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + strDlrSign + dblValue + '.' + strCents);
}
//----------------------------------------------------------------------------------------
//  CurrToInt: Formats any currency value to a numeric value (i.e. Strips currency and commas)
function CurrToInt(cellValue){
	return cellValue.replace(/\$[\s]|\,/g,'') * 1;
}
//----------------------------------------------------------------------------------------
function Valid_Email(strEmailList, a) {
	var at="@";
	var dot=".";
	var del=",";
	var strEmail="";
	var lat="";
	var lstr="";
	var ldot="";
	var msg="";
	
	strEmailList = strEmailList.replace(/;/g,',');
	var ldel=strEmailList.indexOf(del);
	var temp = new Array();
	temp = strEmailList.split(del);
	if (strEmailList.length == 0) return true;
	for (i=0;i<temp.length;i++){
		strEmail = trim(temp[i]);
		msg = 'Invalid E-mail (' + strEmail + ') address detected in the "' + a + '" field.\n\nPress ESC twice to clear the field.';
		lat=strEmail.indexOf(at);
		lstr=strEmail.length;
		ldot=strEmail.indexOf(dot);
		if (lat == -1){
		   alert(msg);
		   return false;
		}
	
		if (lat==-1 || lat==0 || lat==lstr){
		   alert(msg);
		   return false;
		}
	
		if (ldot==-1 || ldot==0 || ldot==lstr){
		    alert(msg);
		    return false;
		}
	
		 if (strEmail.indexOf(at,(lat+1))!=-1){
		    alert(msg);
		    return false;
		 }
	
		 if (strEmail.substring(lat-1,lat)==dot || strEmail.substring(lat+1,lat+2)==dot){
		    alert(msg);
		    return false;
		 }
	
		 if (strEmail.indexOf(dot,(lat+2))==-1){
		    alert(msg);
		    return false;
		 }
		
		 if (strEmail.indexOf(" ")!=-1){
		    alert(msg);
		    return false;
		 }
	}
	return true;
}
//------------------------------------------------------------------------------------------
function isDate(dateStr) {
// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        //alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        //alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        //alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        //alert("Month "+month+" doesn't have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            //alert("February " + year + " doesn't have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}
//------------------------------------------------------------------------------------------
// setData: this works with a checkbox and a textbox used for a date value.
//          when vThis is checked, it then sets dateField's value to today's date.
//	    note: backDate can be used to set the date back/ahead 'x' number of days
//		  by setting the '0' to a negative/positive number
function SetDate (vThis, dateField){
	var y = document.frmMain;
	var format = 'true';
	if (vThis.checked) {
		document.getElementById(dateField).disabled = false;
		var today=new Date();
		var backDate = dateAdd (today, 'd', '0', format);
		if (typeof (y.Inspection_dt) == 'undefined')
			today = new Date(backDate);
		else
			today = new Date(y.Inspection_dt.value);
		document.getElementById(dateField).value = (today.getMonth()+1)+"/"+(today.getDate())+"/"+today.getFullYear();
		document.getElementById(dateField).select();
		document.getElementById(dateField).focus();
	}
	else {
		document.getElementById(dateField).value = '';
		document.getElementById(dateField).disabled = true;
	}
}
//------------------------------------------------------------------------------------------
// Base Code from http://javascript.about.com/library/scripts/blfirstfocus.htm
// firstFocus: sets focus to the first available form element.
//	       frmMain is my default form name and takes precedence over the any other form
function firstFocus(){
	if (document.forms.length > 0){
		if (isdefined('frmMain')) {
	  		var TForm = document.frmMain;
		}
		else {
			var TForm = document.forms[0];
		}
		for (i=0;i<TForm.length;i++){
			if (document.getElementById(TForm.elements[i].id).disabled==false) {
				if ((TForm.elements[i].type=="text") || (TForm.elements[i].type=="textarea") || 
					(TForm.elements[i].type=="file") || (TForm.elements[i].type=="radio") || (TForm.elements[i].type=="checkbox") || 
					(TForm.elements[i].type=="button") || (TForm.elements[i].type.toString().charAt(0)=="s")) {
				document.getElementById(TForm.elements[i].id).focus();
				break;
				}
			}
      	}
   	}
}
//------------------------------------------------------------------------------------------
function FormElementIsArray(obj){
	var e = document.getElementsByName(obj);
	if (e.length > 1)			//Is an array
		return true;
	else if (e.length == 1)		//Is Not array
		return false;
	else {
		alert (obj + " is not a valid object!  Check your code.");
		return false;
	}
}
//------------------------------------------------------------------------------------------
function CheckForDate(vThis){
	if (!isDate(vThis) && vThis > '') {
		alert('Not a valid date or \nin an acceptable format [mm/dd/yyyy]!!!\n\nHit [esc] to return previous date.');
		return false;
	}
	else{
		return true;
	}
}
//------------------------------------------------------------------------------------------
// DefaultDate: Used to set default values to texboxes used for dates.
//	iOn is used to flag the function when to check for the value
//	iOn = 0: Checks the value when you leave the textbox (loose focus)
//	iOn = 1: Checks the value on Focus
function DefaultDate(vThis,iOn){
	if (iOn == '0') {			//onBlur
		if (vThis.value =='') vThis.value = '[mm/dd/yyyy]';
	}
	else if (iOn == '1') {		//onFocus
		if (vThis.value=='[mm/dd/yyyy]') vThis.value='';
	}
}
//----------------------------------------------------------------------------------------
// SHowHide: used to display/hide large blocks of HTML code.  I used it to display
//	additional code based on data input, mainily radio buttons Yes/No
// vthis needs to be passed 'this' in the call
// varToShow is the value of the ID attribute of the SPAN tag to show and hide
function ShowHide(vthis, varToShow){
	var y = document.getElementById(varToShow);
	if (vthis.value == 'Yes')
		y.innerHTML = eval(varToShow)
	else 
		y.innerHTML = '';
}
//----------------------------------------------------------------------------------------
function Left(str, n){
//    Scott Mitchell - mitchell@4guysfromrolla.com
//    http://www.4GuysFromRolla.com
/***
	IN: str - the string we are LEFTing
	    n - the number of characters we want to return
	
	RETVAL: n characters from the left side of the string
***/
	if (n <= 0)     // Invalid bound, return blank string
    	return "";
	else if (n > String(str).length)   // Invalid bound, return
		return str;                // entire string
	else // Valid bound, return appropriate substring
		return String(str).substring(0,n);
}
//----------------------------------------------------------------------------------------
function Right(str, n){
//    Scott Mitchell - mitchell@4guysfromrolla.com
//    http://www.4GuysFromRolla.com
/***
	IN: str - the string we are RIGHTing
	   n - the number of characters we want to return
	
	RETVAL: n characters from the right side of the string
***/
	if (n <= 0)     // Invalid bound, return blank string
	   return "";
	else if (n > String(str).length)   // Invalid bound, return
	   return str;                     // entire string
	else { // Valid bound, return appropriate substring
	   var iLen = String(str).length;
	   return String(str).substring(iLen, iLen - n);
	}
}
//----------------------------------------------------------------------------------------
function blockSubmitButton(a,newButtonName,alertMsg){
	if (a.value != newButtonName) {
		a.value = newButtonName;
		return true;
	} else
	{
		alert(alertMsg);
		return false;
	}
}
//----------------------------------------------------------------------------------------
// EXTRA CODE FROM A PREVIOUS PROJECT OF MINE
function fillBreakdown(){
	var sSel='';
	var ndx=0;
	// Deletes the dropdown contents
	for (i = document.frmMain_PO.selBreakDown.options.length - 1; i >= 0; i--) document.frmMain_PO.selBreakDown.options[i] = null;
	document.frmMain_PO.selBreakDown.selectedIndex = 0;
	
	// Populate the Select box
	if (document.frmMain_PO.chkAmtType.checked) {
		for (i=0; i < js_aryLabor[1].length; i++) {
			document.frmMain_PO.selBreakDown.options[i] = new Option(js_aryLabor[1][i],js_aryLabor[0][i]);
			if (sSel==js_aryLabor[0][i]) ndx = i;
		}
	}
	else {
		//alert(js_aryMaterial[1].length);
		for (j=0; j < js_aryMaterial[1].length; j++) {
			document.frmMain_PO.selBreakDown.options[j] = new Option(js_aryMaterial[1][j],js_aryMaterial[0][j]);
			if (sSel==js_aryMaterial[0][j]) ndx = j;
		}
	}
	document.frmMain_PO.selBreakDown.selectedIndex = ndx;
}
//----------------------------------------------------------------------------------------
// dateAdd: used in setDate function to add intervals to a valid date.
function dateAdd(start, interval, number, blnFormat) {
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var numberMsg = "Sorry the number parameter of the dateAdd function\n"
        numberMsg += "must be numeric.\n\n"
        numberMsg += "Please try again." ;
	if (trim(start.toString()).length == 0) {
		return '';
	}		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse( start ) ;
    // check that the start parameter is a valid Date. 
    if ( isNaN (buffer) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }

    // check that the number parameter is numeric. 
    if ( isNaN ( number ) )	{
        alert( numberMsg ) ;
        return null ;
    }

    // so far, so good...
    //
    // what kind of add to do? 
    switch (interval.charAt(0)) {
        case 'd': case 'D': 
            number *= 24 ; // days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60 ; // hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60 ; // minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000 ; // seconds to milliseconds
            break ;
        default:
        // If we get to here then the interval parameter didn't
        // meet the d,h,m,s criteria.  Handle the error. 		
	        alert(intervalMsg) ;
    	    return null;
    }
    var retDate = new Date(buffer + number) ;
	if (blnFormat == 'true') {retDate = (retDate.getMonth()+1) + "/" + (retDate.getDate()) + "/" + retDate.getFullYear()};
	return retDate;
}
//----------------------------------------------------------------------------------------
// This outlines an input field in red for required data
function highlightTextField(field) {
	if (field.type.toString().charAt(0)=="s") {
		field.style.background = '#ff0000';
		field.style.color = '#ffffff';
	}
	else {
		field.style.borderColor = '#ff0000';
		field.style.borderStyle = 'solid';
		field.style.borderWidth = '2px';
	}
}
//----------------------------------------------------------------------------------------
// This returns outlines of an input field to the default color for required data
function UnHighlightTextField(field,defColor) {
	if (field.type.toString().charAt(0)=="s") {
		field.style.background = '';
		field.style.color = '';
	}
	else {
		field.style.borderColor = defColor;
		field.style.borderStyle = 'solid';
		if (defColor > '') field.style.borderWidth = '1px';
		else field.style.borderWidth = '0px';
	}
}
//----------------------------------------------------------------------------------------
// This outlines a Dropdown field in red for required data
function highlightSelectField(field) {
	field.style.backgroundColor = 'red';
	field.style.color = 'white';
}
//----------------------------------------------------------------------------------------
// This formats a number to a float to iDecPlaces 
function Format_Float(vThis,iDecPlaces){
	var strThis = vThis.value.toString().replace(/\$[\s]|\,/g,'');
	var dblValue = parseFloat(strThis);
	var blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	var lngPower = Math.pow(10,iDecPlaces);
	var dblValue = Math.floor(dblValue * lngPower + 0.50000000001);
	var intCents = dblValue % lngPower;
	var strCents = intCents.toString();
	dblValue = Math.floor(dblValue/lngPower).toString();
	while (strCents.length < (String(lngPower).length-1)) {
	//if (intCents < 1000)
		strCents = "0" + strCents;
	}
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+dblValue.substring(dblValue.length-(4*i+3));
	//return ((blnSign)?'':'-') +  dblValue + '.' + strCents;
	vThis.value = ((blnSign)?'':'-') +  dblValue + '.' + strCents;
}
//----------------------------------------------------------------------------------------
// This formats a string to a Date for comparisons.
function StrToDate(strDate){
	if (strDate == '') 
		var d1 = new Date();
	else 
		d1 = new Date(strDate);
	return d1;
}
//----------------------------------------------------------------------------------------
// EmployeeNumberOnly: When you want to limit to only 5 digit numeric values or T values with 5 digits in any textbox. 
// How to Use: <input type="textbox" ... onKeyPress="return EmployeeNumberOnly(this, event)" >
function EmployeeNumberOnly(myfield, e){
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	else if ((myfield.value.length == 5) && (myfield.value.substr(0,1) != 'T'))
		return false;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
		 
	else if ((keychar == 'T') && (myfield.value == ''))
		 return true;
		 
	else
	   return false;
}
//----------------------------------------------------------------------------------------
// ToggleHidden: Flips elements to displayed or not.
// How to use: <a href="javascript:ToggleHidden('ElementID')">test</a> works rather well
function ToggleHidden(a) {
	if (document.getElementById(a).style.display == '') 
		document.getElementById(a).style.display = 'none';
	else
		document.getElementById(a).style.display = '';
}
//----------------------------------------------------------------------------------------
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function letternumber(e,blnAllowSpaces){
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) ||
		(blnAllowSpaces && key==32) )
	   return true;
	// alphas and numbers
	else if ((("abcdefghijklmnopqrstuvwxyz0123456789-").indexOf(keychar) > -1))
	   return true;
	else {
		alert('Letters and Numbers Only.');
	   return false;
	}
}
//----------------------------------------------------------------------------------------
// Copied from http://www.mediacollege.com/internet/javascript/number/random.html
// e = the field ID where to put the results.
// intSize = the number of characgers for the results
function randomString(e,intSize) {
	var chars = '123456789ABCDEFGHIJKLMNPQRSTUVWXTZ';
	intSize = parseInt(intSize);
	if (isNaN(intSize) || (intSize < 1) || (intSize > 99)) {intSize = 8;}
	var string_length = intSize;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	document.getElementById(e).value = randomstring;
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
	<!-- This script is based on the javascript code of Roman Feldblum (web.developer@programmer.net) -->
	<!-- Original script : http://javascript.internet.com/forms/format-phone-number.html -->
	<!-- Original script is revised by Eralper Yilmaz (http://www.eralper.com) -->
	<!-- Revised script : http://www.kodyaz.com -->
	<!-- Format : "(123) 456-7890" -->

var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 14;
var phonevalue1;
var phonevalue2;
var cursorposition;

function ParseForNumber1(object){
	  phonevalue1 = ParseChar(object.value, zChar);
	}
	
function ParseForNumber2(object){
	  phonevalue2 = ParseChar(object.value, zChar);
	}
	
	function backspacerUP(object,e) { 
	  if(e){ 
		e = e 
	  } else {
		e = window.event 
	  } 
	  if(e.which){ 
		var keycode = e.which 
	  } else {
		var keycode = e.keyCode 
	  }
	
	  ParseForNumber1(object)
	
	  if(keycode >= 48){
		ValidatePhone(object)
	  }
	}
	
	function backspacerDOWN(object,e) { 
	  if(e){ 
		e = e 
	  } else {
		e = window.event 
	  } 
	  if(e.which){ 
		var keycode = e.which 
	  } else {
		var keycode = e.keyCode 
	  }
	  ParseForNumber2(object)
	} 
	
function GetCursorPosition(){
	  var t1 = phonevalue1;
	  var t2 = phonevalue2;
	  var bool = false
	  for (i=0; i<t1.length; i++) 	  {
		if (t1.substring(i,1) != t2.substring(i,1)) {
		  if(!bool) {
			cursorposition=i
			window.status=cursorposition
			bool=true
		  }
		}
	  }
	}
	
function ValidatePhone(object){
	  var p = phonevalue1
	  p = p.replace(/[^\d]*/gi,"")
	  if (p.length < 3) {
		object.value=p
	  } else if(p.length==3){
		pp=p;
		d4=p.indexOf('(')
		d5=p.indexOf(')')
		if(d4==-1){
		  pp="("+pp;
		}
		if(d5==-1){
		  pp=pp+")";
		}
		object.value = pp;
	  } else if(p.length>3 && p.length < 7){
		p ="(" + p; 
		l30=p.length;
		p30=p.substring(0,4);
		p30=p30+") " 
	
		p31=p.substring(4,l30);
		pp=p30+p31;
	
		object.value = pp; 
	
	  } else if(p.length >= 7){
		p ="(" + p; 
		l30=p.length;
		p30=p.substring(0,4);
		p30=p30+") " 
	
		p31=p.substring(4,l30);
		pp=p30+p31;
	
		l40 = pp.length;
		p40 = pp.substring(0,9);
		p40 = p40 + "-"
	
		p41 = pp.substring(9,l40);
		ppp = p40 + p41;
	
		object.value = ppp.substring(0, maxphonelength);
	  }
	
	  GetCursorPosition()
	
	  if(cursorposition >= 0){
		if (cursorposition == 0) {
		  cursorposition = 2
		} else if (cursorposition <= 2) {
		  cursorposition = cursorposition + 1
		} else if (cursorposition <= 4) {
		  cursorposition = cursorposition + 3
		} else if (cursorposition == 5) {
		  cursorposition = cursorposition + 3
		} else if (cursorposition == 6) { 
		  cursorposition = cursorposition + 3 
		} else if (cursorposition == 7) { 
		  cursorposition = cursorposition + 4 
		} else if (cursorposition == 8) { 
		  cursorposition = cursorposition + 4
		  e1=object.value.indexOf(')')
		  e2=object.value.indexOf('-')
		  if (e1>-1 && e2>-1){
			if (e2-e1 == 4) {
			  cursorposition = cursorposition - 1
			}
		  }
		} else if (cursorposition == 9) {
		  cursorposition = cursorposition + 4
		} else if (cursorposition < 11) {
		  cursorposition = cursorposition + 3
		} else if (cursorposition == 11) {
		  cursorposition = cursorposition + 1
		} else if (cursorposition == 12) {
		  cursorposition = cursorposition + 1
		} else if (cursorposition >= 13) {
		  cursorposition = cursorposition
		}
	
		var txtRange = object.createTextRange();
		txtRange.moveStart( "character", cursorposition);
		txtRange.moveEnd( "character", cursorposition - object.value.length);
		txtRange.select();
	  }
	
	}
	
	function ParseChar(sStr, sChar)
	{
	
	  if (sChar.length == null) {
		zChar = new Array(sChar);
	  }
		else zChar = sChar;
	
	  for (i=0; i<zChar.length; i++) {
		sNewStr = "";
	
		var iStart = 0;
		var iEnd = sStr.indexOf(sChar[i]);
	
		while (iEnd != -1) {
		  sNewStr += sStr.substring(iStart, iEnd);
		  iStart = iEnd + 1;
		  iEnd = sStr.indexOf(sChar[i], iStart);
		}
		sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
		sStr = sNewStr;
	  }
	  return sNewStr;
	}


