/*
input type="text" onKeyPress="return xFilter(event.keyCode, this, "(###) ###-####");"
*/

var xFilterStep

function xFilterStrip( xFilterTemp, xFilterMask )
{
    xFilterMask = replace( xFilterMask, '#', '' );
    
    for( xFilterStep = 0; xFilterStep < xFilterMask.length++; xFilterStep++ )
		xFilterTemp = replace( xFilterTemp, xFilterMask.substring( xFilterStep, xFilterStep + 1 ), '' );

	return xFilterTemp;
}

function xFilterMax( xFilterMask )
{
 	xFilterTemp = xFilterMask;
    for( xFilterStep = 0; xFilterStep < ( xFilterMask.length + 1 ); xFilterStep++ )
	{
		if( xFilterMask.charAt( xFilterStep ) != '#' )
			xFilterTemp = replace( xFilterTemp, xFilterMask.charAt( xFilterStep ), '' );
	}
	return xFilterTemp.length;
}

function xFilter( key, textbox, xFilterMask )
{       
    var selLength;
    if ( textbox.setSelectionRange ) {        
        selLength=textbox.selectionEnd - textbox.selectionStart;//textbox.value.substring(0,textbox.selectionStart) + textbox.value.substring(textbox.sectionStart,textbox.selectionEnd).length 
    } else {
        selLength=document.selection.createRange().text.length;
    }   

	if( selLength > 0 )
		{
			if (isNaN(String.fromCharCode(key)))
				{
					return false;
				}
			else	
				{
					return true;
				}
		}
	
	if (isNaN(String.fromCharCode(key)))
	{
		return false;
	}
	
	xFilterNum = xFilterStrip( textbox.value, xFilterMask );
		
	if( key == 9 || key == 8 )
		return true;
		
	//else if( key == 8 && xFilterNum.length != 0 )
	//	xFilterNum = xFilterNum.substring(0,xFilterNum.length-1);
		
 	else if( (( key > 47 && key < 58 ) || ( key > 95 && key < 106 )) && xFilterNum.length < xFilterMax( xFilterMask ) )
	    xFilterNum = xFilterNum + String.fromCharCode(key);

	var xFilterFinal = '';
    for( xFilterStep = 0; xFilterStep < xFilterMask.length; xFilterStep++ )
	{
		if( xFilterMask.charAt( xFilterStep ) == '#' )
		{
			if( xFilterNum.length != 0 )
			{
				xFilterFinal = xFilterFinal + xFilterNum.charAt(0);
				xFilterNum = xFilterNum.substring( 1, xFilterNum.length );
			}
			else
				xFilterFinal = xFilterFinal + "";
		}
		else if( xFilterMask.charAt( xFilterStep ) != '#' )
			xFilterFinal = xFilterFinal + xFilterMask.charAt(xFilterStep); 			
	}

	textbox.value = xFilterFinal;
    return false;
}

function replace( fullString, text, by ) 
{
	// Replaces text with by in string
    var strLength = fullString.length, txtLength = text.length;
    if( (strLength == 0) || (txtLength == 0) ) 
		return fullString;

    var i = fullString.indexOf(text);
    if( (!i) && ( text != fullString.substring(0,txtLength) ) ) 
		return fullString;
		
    if(i == -1) 
		return fullString;

    var newstr = fullString.substring(0, i) + by;

    if( i + txtLength < strLength )
        newstr += replace( fullString.substring( i + txtLength, strLength ), text, by );

    return newstr;
}
