﻿

//*******************************************************


function openPDFVersion()

{
    
      var win =  window.open('Preview.aspx')
      detectPopupBlocker(win);
        
}
//Check Popup blocker

function detectPopupBlocker(wind)
{



 if(wind==null)
 {
    var message = 'The requested action cannot be completed. OAR has detected that a pop-up blocker is preventing a window from popping up. For information on how to turn the pop-up blocker off, please see the OAR FAQs.';
   if(window.location.href.indexOf('/Application.aspx')>-1)
     message+= '\n\nNote: If you turn any pop-up blockers off, your web browser will automatically refresh the OAR web page. This may clear the application data from your screen. If this happens, please return to the My Applications page and reopen your application (which OAR automatically saves). \nYou may now proceed with the action you were previously attempting.'         
     
     alert(message);

 }  

 
}
//To Get Confirm about Delete
function getConfirm()
{
	return confirm("Are you sure you want to delete?");
}
//*******************************************************

function autoTab(input,len, e) 
{
    var keyCode =  e.keyCode; 
    var filter = [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
    input.value = input.value.slice(0, len);
    input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) 
{
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
    else
    index++;
    return found;
}

function getIndex(input) 
{
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
}
return true;
}

function openWindow(pageURL, pageHeight, pageWidth) {

	    if (navigator.userAgent.indexOf("MSIE") != -1){
		    var a = new Array();
		    a[0] = window;
		    var dlgOptions = "dialogHeight: " + pageHeight + "px; dialogWidth: " + pageWidth + "px ; center: Yes; edge: Sunken; help: No; resizable: No; scroll: No; status: No;";
		    
		    var win = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
		    detectPopupBlocker(win);
		    if(win)
		    {
		        win.close();
		        window.showModalDialog(pageURL, a, dlgOptions);
		    }
		    
		    
	    }else
        {
		    var topPos = (screen.height - pageHeight.substring(0,pageHeight.length-2)) / 2;
		    var leftPos = (screen.width - pageWidth.substring(0,pageWidth.length-2)) / 2;
		    var windowOptions = "height=" + pageHeight + ",width=" + pageWidth + ",directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no,modal=yes,dependent=yes,top=" + topPos + ",left=" + leftPos;
		    var win=window.open(pageURL,"NewWindow",windowOptions);
		    detectPopupBlocker(win);
	    }
	
	return false;
}

function openNewWindow(pageURL, pageHeight, pageWidth) {

	
	
	{
	    var topPos = (screen.height - pageHeight.substring(0,pageHeight.length-2)) / 2;
	    var leftPos = (screen.width - pageWidth.substring(0,pageWidth.length-2)) / 2;
	    var windowOptions = "height=" + pageHeight + ",width=" + pageWidth + ",directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no,top=" + topPos + ",left=" + leftPos;
	    var win = window.open(pageURL,"NewWindow",windowOptions);
	    detectPopupBlocker(win);
	}
	
	return false;
}

function CustomClose(postBackButton)
{
	window.close();
} 


function OpenAttachmentWindow(clientid)
{

openWindow( 'ManageAttachments.aspx?Id=0','700px','850px');

    return Refresh('ManageAttachment1');
}
function EditAttachment(id)
{


openWindow( 'ManageAttachments.aspx?Id='+id,'700px','850px');

    return Refresh('ManageAttachment1');
}

function Refresh()
{
        Anthem_InvokePageMethod('Refresh');
        

}
function AnyInput_KeyDown ( e, target ) 
	{ 
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) 
		{ 
			document.getElementById(target).focus();
			return false; 
		} 
			return true; 
	} 

function ShowAttachment(id)
{
   
   
   var win=  window.open( 'ViewAttachments.aspx?id=' + id  ,'View','left=20,top=20,width=800,height=600,toolbar=1,resizable=1');
   detectPopupBlocker(win);
   return false;
}

function ChangeCheckBoxState(id, checkState)
        {
            var cb = document.getElementById(id);
            if (cb != null)
               cb.checked = checkState;
        }
        
        function ChangeAllCheckBoxStates(checkState)
        {
            // Toggles through all of the checkboxes defined in the CheckBoxIDs array
            // and updates their value to the checkState input parameter
            if (CheckBoxIDs != null)
            {
                for (var i = 0; i < CheckBoxIDs.length; i++)
                   ChangeCheckBoxState(CheckBoxIDs[i], checkState);
            }
        }
        
        function ChangeHeaderAsNeeded()
        {
            // Whenever a checkbox in the GridView is toggled, we need to
            // check the Header checkbox if ALL of the GridView checkboxes are
            // checked, and uncheck it otherwise
            if (CheckBoxIDs != null)
            {
                // check to see if all other checkboxes are checked
                for (var i = 1; i < CheckBoxIDs.length; i++)
                {
                    var cb = document.getElementById(CheckBoxIDs[i]);
                    if (!cb.checked)
                    {
                        // Whoops, there is an unchecked checkbox, make sure
                        // that the header checkbox is unchecked
                        ChangeCheckBoxState(CheckBoxIDs[0], false);
                        return;
                    }
                }
                
                // If we reach here, ALL GridView checkboxes are checked
                ChangeCheckBoxState(CheckBoxIDs[0], true);
            }
        }
        
        
//--------------------------- Numeric Box----------------------------
       
       
       
function NumericBox_IE_AddNumericItem(e) {
	
	
	if(document.selection != null) {
		if(document.selection.createRange().text != '')
			document.selection.clear();
	}
	
	if(!e) var e = window.event;
	var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
	
	var control; 
	if(e.srcElement)
	    control=e.srcElement;
	else
	    control = e.target;
	
	
	var decPlaces = parseInt(control.decPlaces);
	if(control.decPlaces == null)
		decPlaces = parseInt(control.attributes[NumericBox_IE_FindAttributeIndex(control, "decplaces")].value);
	var decSign = control.decSign;
	if(decSign == null)
		decSign = control.attributes[NumericBox_IE_FindAttributeIndex(control, "decsign")].value;
	var isReal = control.isReal;
	if(isReal == null)
		isReal = control.attributes[NumericBox_IE_FindAttributeIndex(control, "isreal")].value;
	var isPos = control.isPos;
	if(isPos == null)
		isPos = control.attributes[NumericBox_IE_FindAttributeIndex(control, "ispos")].value;
	var placesBeforeDec = control.placesBeforeDec;
	if(placesBeforeDec == null)
		placesBeforeDec = parseInt(control.attributes[NumericBox_IE_FindAttributeIndex(control, "placesbeforedec")].value);
	if(keyCode == 9 ||keyCode == 39 || keyCode == 37 || keyCode == 27)
	    return true;
	
	if((keyCode >= 48 && keyCode <= 57) || keyCode == 13 || keyCode == 8) {
		if(decPlaces == -1 || isReal == 'false' || keyCode == 13 || keyCode == 8) {
			var tempVal = control.value;
			if(tempVal.indexOf('-', 0) == 0)
				tempVal = tempVal.replace('-', '');
			if(tempVal.indexOf('.', 0) == -1) {
				if(tempVal.length < placesBeforeDec || placesBeforeDec == -1)
					return true;
				else
					    return false;
			} else {
				return true;
			}
		} else {
			var tempVal = event.srcElement.value;
			if(tempVal.indexOf('-', 0) == 0)
				tempVal = tempVal.replace('-', '');
			if(tempVal.indexOf('.', 0) == -1) {
				if(tempVal.length < placesBeforeDec || placesBeforeDec == -1)
					return true;
				else
					    return false;
			} else {
				if(tempVal.indexOf(decSign, 0) == -1)
					return true;
				else {
					if((tempVal.length - tempVal.indexOf(decSign, 0)) <= decPlaces)
						return true;
					else
					    return false;
				}
			}
		}
	} else if(keyCode == 45 || keyCode == 46 || keyCode == 44) {
		if(keyCode == 45) {
			var tempVal = control.value + "-";
			if(tempVal.indexOf("-") == 0 && tempVal.indexOf("-", 1) == -1) {
				if(isPos == 'true')
					    return false;
				else
					return true;
			} else
				return false;
		} else if(keyCode == 46 && decSign == "."){
			var tempVal = event.srcElement.value;
			if(tempVal.indexOf(".", 0) == -1) {
				if(isReal == 'true')
					return true;
				else
					    return false;

			} else
					    return false;

		} else if(keyCode == 44 && decSign == ",") {
			var tempVal = control.value;
			if(tempVal.indexOf(",", 0) == -1) {
				if(isReal == 'true')
					return true;
				else
					return false;

			} else
				return false;
		} else
			return false;
	} else
		return false;
}

function NumericBox_IE_Paste(e) {
    
    return false;
}

function NumericBox_IE_ParseAdd(box, dollarSign, commaSign, decimalSign) {
	var currentValue = box.value;
	var parseValue = '';
	var newValue = '';
	var getDecimal = false;
	var addNegative = false;
	if(currentValue.indexOf('-') >= 0) {
		addNegative = true;
		currentValue = currentValue.replace('-', '');
	}
	if(currentValue != '' && currentValue.indexOf(decimalSign) > 0) {
		parseValue = currentValue.substr(0, currentValue.indexOf(decimalSign));
		getDecimal = true;
	} else {
		parseValue = currentValue;
		getDecimal = false;
	}
	var rotations = parseInt(parseValue.length / 3);
	if(parseValue.length % 3 == 0)
		rotations--;
	for(var i=0; i<rotations; i++)
		newValue = commaSign + parseValue.substr(parseValue.length - ((i + 1) * 3), 3) + newValue;
	newValue = parseValue.substr(0, parseValue.length - ((rotations) * 3)) + newValue;		
	if(getDecimal)
		newValue = newValue + currentValue.substr(currentValue.indexOf(decimalSign));
	if(newValue.length > 0) {
		if(addNegative)
			newValue = dollarSign + '-' + newValue;
		else
			newValue = dollarSign + newValue;
	}
	box.value = newValue;
}

function NumericBox_IE_ParseRemove(box, dollarSign, commaSign) {
	var currentValue = box.value;
	var newValue = currentValue;
	while(newValue.indexOf(dollarSign) > -1)
		newValue = newValue.replace(dollarSign, '');
	while(newValue.indexOf(commaSign) > -1)
		newValue = newValue.replace(commaSign, '');
	box.value = newValue;
	box.select();
}

function NumericBox_IE_FindAttributeIndex(element, attName) {
	var attIndex = -1;
	if(element != null) {
		for(var i=0; i<element.attributes.length; i++) {
			if(element.attributes[i].name.toLowerCase() == attName) {
				attIndex = i;
				i = element.attributes.length;
			}
		}
	}
	return attIndex;
}

   
//---------------------------End Numeric Box----------------------------

//------------------------Anthem CallBack

function Anthem_PreCallBack(  ) 
{
    var loading = document.createElement("div");
    loading.id = "loading";
     loading.className = "loadingdiv";
    loading.innerHTML = "Working on your request...";
    document.body.appendChild(loading);
}
function Anthem_PostCallBack() {
	var loading = document.getElementById("loading");
	document.body.removeChild(loading);
}
//----------------

//To Check Invalid Character 

    function CheckInvalidCharacter(e)
    {
        var index = 0;
        var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        var KeyCode = String.fromCharCode(keyCode)
        while(index < arr.length)
        if(arr[index] == KeyCode)
        {
          if(e.preventDefault) e.preventDefault();  
          return false;
         }
        else
          index++;

        return true;
    }

function openDeductiblePopup()
{
      alert('Deductible factor is subject to prior approval by the Minnesota Assigned Risk Plan.\nDocumentation approving the use of deductible must be attached to this application.');
}



/**************************************** Mask Inputs ****************************************************/
/*objField - Field name for the text field
  strMaskType - String value representing 
  one of the followin mask types
  1- "PHONE"
  2- "NUMBER"
  3- "ZIP"
  3- "CURRENCY"
  4- "DATE"
  5- "SSN"
  6- "FHA"
  7- "VA"
*/

//Get year from date string

function getYear(strDate)
{
		strYear = "";
	    i = 0;
	    
		if ( strDate.length > 0 )
		{
			for (i = strDate.length - 1 ; strDate.charAt(i) != '/' ; i-- )
				strYear = strYear + "" + strDate.charAt(i);		
		}
		
	strYear = reverse(strYear);
	
	return strYear;
}


function reverse(text)
	{
		var backwards="";
		
		var count;
		count = 0;
		
		for(count=text.length; count >= 0; count--)
			backwards+=text.substring(count,count-1);
		
		return backwards;
	}
	
	
 //changes the date for 2000
 //input control to show formatted date
function formatDate(txtDate)

		     {	
		        alert(txtDate.value);
				txtDate.value = Trim (txtDate.value);
				if ( txtDate.value != "" )
				 {				
				 if (isDate(txtDate.value)==true)
					 {
						year = getYear (txtDate.value);				
						var nDate = new Date(txtDate.value);				
						if ( year < 100  )
						{				
						if ( year < 50 ) 
							year  = "20" + year.toString() ;
						else
							year  = "19" + year.toString() ;				
						}	// year check
				 
						month = nDate.getMonth()+1;
						day = nDate.getDate();
						
						if ( day < 10 ) 
						 day = "0" + day.toString()
					
						if ( month < 10 ) 
						 month = "0" + month.toString()
					
						strDate = month.toString() + "/" + day.toString() + "/" + year.toString() ;
					
						nDate = new Date(strDate);
					
						txtDate.value = strDate;
					}
					else
					{	
					}
			  } // empty check
			}	
			
			 //changes the date for 2000
 
 //input control to show formatted date in the following format 
 // MM/YY
function formatDateMonth(txtDate)
{	
//alert(txtDate.value);
	txtDate.value = Trim (txtDate.value);
	if ( txtDate.value != "" )
	{				
		if (isDateMonth(txtDate.value)==true)
		{
			/*year = getYear (txtDate.value);				
			var nDate = new Date(txtDate.value);				
			if ( year < 100  )
			{				
				if ( year < 50 ) 
					year  = "20" + year.toString() ;
				else
					year  = "19" + year.toString() ;				
			}	// year check
		
			month = nDate.getMonth()+1;
			day = nDate.getDate();
			
			if ( day < 10 ) 
				day = "0" + day.toString()
		
			if ( month < 10 ) 
				month = "0" + month.toString()
		
			strDate = month.toString() + "/" + day.toString() + "/" + year.toString() ;
		
			nDate = new Date(strDate);
		
			txtDate.value = strDate;*/
		}
		else
		{	
		
		}
	} // empty check
}
// currency , replaces
function replaceCommas(v)
 {
		var re = new RegExp (',', 'gi') ;
		v = v.replace(re,'')
		return v
 }
				
function AttachDateMask(controlname)
{
    var control = document.getElementById(controlname);
    AttachMask(control,"DATE");
}
				
function AttachMask(objField, strMaskType)
	{
		if (strMaskType == "PHONE")
			{
				phoneMask = new Mask("(###)###-####");
				phoneMask.attach(objField);
			}
		else if (strMaskType == "NUMBER")
			{
				numberMask = new Mask("#######", "number");
				numberMask.attach(objField);
			}
		else if (strMaskType == "DOUBLE2")
			{
				currencyMask = new Mask("#,###.00", "double2","2");		
				currencyMask.attach(objField);
			}
		else if (strMaskType == "DOUBLE3")
			{
				//numberMask = new Mask("#######.000", "number");
				//numberMask.attach(objField);
			}
		else if (strMaskType == "DOUBLE4")
			{
				//numberMask = new Mask("#######.0000", "number");
				//numberMask.attach(objField);
			}
		else if (strMaskType == "DOUBLE5")
			{
				//numberMask = new Mask("#######.00000", "number");
				//numberMask.attach(objField);
			}
		else if (strMaskType == "ZIP")
			{
				zipMask = new Mask("######");
				zipMask.attach(objField);
			}
		else if (strMaskType == "CURRENCY")
			{
				currencyMask = new Mask("#,###.00", "number");		
				currencyMask.attach(objField);
			}
		else if (strMaskType == "DATE")
			{
				dateMask = new Mask("mm/dd/yyyy", "date");
				dateMask.attach(objField);	
			}	
		else if (strMaskType == "DATE_MONTH")
			{
				dateMask = new Mask("mm/yy", "date");
				dateMask.attach(objField);	
			}		
		else if (strMaskType == "SSN")
			{
				numberMask = new Mask("###-##-####");
				numberMask.attach(objField);	
			}	
		else if (strMaskType == "TIN")
			{
				numberMask = new Mask("##-#######");
				numberMask.attach(objField);	
			}				
		else if (strMaskType == "FHA")
			{
				numberMask = new Mask("###-######-#-###", "string");
				numberMask.attach(objField);	
			}
		else if (strMaskType == "VA")
			{
				numberMask = new Mask("##-##-#-#######");
				numberMask.attach(objField);	
			}	
	}

function formatCurrency(num) {
	
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	
	return (((sign)?'':'-') + num + '.' + cents);
}

function _MaskAPI(){
	this.version = "0.4a";
	this.instances = 0;
	this.objects = {};
}
MaskAPI = new _MaskAPI();

function Mask(m, t, d){
	this.mask = m;
	this.decimals = d;
	this.type = (typeof t == "string") ? t : "string";
	this.error = [];
	this.errorCodes = [];
	this.value = "";
	this.strippedValue = "";
	this.allowPartial = false;
	this.id = MaskAPI.instances++;
	this.ref = "MaskAPI.objects['" + this.id + "']";
	MaskAPI.objects[this.id] = this;
}

// define the attach(oElement) function
Mask.prototype.attach = function (o){
	$addEvent(o, "onkeydown", "return " + this.ref + ".isAllowKeyPress(event, this);", true);
	$addEvent(o, "onkeyup", "return " + this.ref + ".getKeyPress(event, this);", true);
	$addEvent(o, "onblur", "this.value = " + this.ref + ".format(this.value);", true);
   }

Mask.prototype.isAllowKeyPress = function (e, o){
//debugger;
	if( this.type != "string" && this.type != "double2") return true;
	var xe = new qEvent(e);

	if( ((xe.keyCode > 47) && (o.value.length >= this.mask.length)) && !xe.ctrlKey ) return false;
	return true;
}

Mask.prototype.getKeyPress = function (e, o, _u){
//debugger;
	this.allowPartial = true;
	var xe = new qEvent(e);

//	var k = String.fromCharCode(xe.keyCode);

	if( (xe.keyCode > 47) || (_u == true) || (xe.keyCode == 8 || xe.keyCode == 46) ){
	//debugger;
		var v = o.value, d;
		if( xe.keyCode == 8 || xe.keyCode == 46  || (this.type == "double2" && xe.keyCode == 110)) d = true;
		else d = false

		if( this.type == "number" ) this.value = this.setNumber(v, d);
		else if( this.type == "date" ) this.value = this.setDateKeyPress(v, d);
		else if( this.type == "double2" ) this.value = this.setDecimalCommaFormatted(v, d, o.maxLength);
		else this.value = this.setGeneric(v, d);

		o.value = this.value;
		valueChanged = 1;
	}
	/* */

	this.allowPartial = false;
	return true;
}

Mask.prototype.format = function (s){
//debugger;
	if( this.type == "number" ) this.value = this.setNumber(s);
	else if( this.type == "date" ) this.value = this.setDate(s);
	else if( this.type == "double2" ) this.value = this.setDecimal(s);
	else this.value = this.setGeneric(s);
	return this.value;
}

Mask.prototype.throwError = function (c, e, v){
	this.error[this.error.length] = e;
	this.errorCodes[this.errorCodes.length] = c;
	if( typeof v == "string" ) return v;
	return true;
}

Mask.prototype.setGeneric = function (_v, _d){
	var v = _v, m = this.mask;
	var r = "x#*", rt = [], nv = "", t, x, a = [], j=0, rx = {"x": "A-Za-z", "#": "0-9", "*": "A-Za-z0-9" };

	// strip out invalid characters
	v = v.replace(new RegExp("[^" + rx["*"] + "]", "gi"), "");
	if( (_d == true) && (v.length == this.strippedValue.length) ) v = v.substring(0, v.length-1);
	this.strippedValue = v;
	var b=[];
	for( var i=0; i < m.length; i++ ){
		// grab the current character
		x = m.charAt(i);
		// check to see if current character is a mask, escape commands are not a mask character
		t = (r.indexOf(x) > -1);
		// if the current character is an escape command, then grab the next character
		if( x == "!" ) x = m.charAt(i++);
		// build a regex to test against
		if( (t && !this.allowPartial) || (t && this.allowPartial && (rt.length < v.length)) ) rt[rt.length] = "[" + rx[x] + "]";
		// build mask definition table
		a[a.length] = { "chr": x, "mask": t };
	}

	var hasOneValidChar = false;
	// if the regex fails, return an error
	if( !this.allowPartial && !(new RegExp(rt.join(""))).test(v) ) return this.throwError(1, "The value \"" + _v + "\" must be in the format " + this.mask + ".", _v);
	// loop through the mask definition, and build the formatted string
	else if( (this.allowPartial && (v.length > 0)) || !this.allowPartial ){
		for( i=0; i < a.length; i++ ){
			if( a[i].mask ){
				while( v.length > 0 && !(new RegExp(rt[j])).test(v.charAt(j)) ) v = (v.length == 1) ? "" : v.substring(1);
				if( v.length > 0 ){
					nv += v.charAt(j);
					hasOneValidChar = true;
				}
				j++;
			} else nv += a[i].chr;
			if( this.allowPartial && (j > v.length) ) break;
		}
	}
	
	if( this.allowPartial && !hasOneValidChar ) nv = "";
	if( this.allowPartial ){
		if( nv.length < a.length ) this.nextValidChar = rx[a[nv.length].chr];
		else this.nextValidChar = null;
	}

	return nv;
}

function MaskCommaFormatted(amount)
{
	var delimiter = ",";
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d == null || d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

function RComma(S) { S = String(S)
  var RgX = /^(.*\s)?([-+\u00A3\u20AC]?\d+)(\d{3}\b)/
  return S == (S=S.replace(RgX, "$1$2,$3")) ? S : RComma(S) }
 
 Mask.prototype.setNumber = function(_v, _d){
	var v = String(_v).replace(/[^\d.-]*/gi, "");
	return RComma(v);
 }
 
 Mask.prototype.setDecimalCommaFormatted = function(_v, _d, _l){
	var v = String(_v).replace(/[^\d.-]*/gi, "");
	//return RComma(v);
	return MaskCommaFormatted ( v, _l);
 }
 
 function MaskCommaFormatted(amount, maxlength)
{
	var delimiter = ",";
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	/*if(! d ) 
		{ amount = n; }
	else 
		{ amount = n + '.' + d; }
		*/
	if(amount.indexOf('.') > -1 ) 
		{
			if (!d ) 
				amount = n + '.'
			else
				{
					amount = n + '.' + d;
					
					if (d.length > 2)
						amount = amount.substring(0,( amount.length - 1));
				}
		}
	else 
		amount = n;
				
	amount = minus + amount;
	
	if (amount.indexOf('..') > -1)
		amount = amount.substring(0,amount.indexOf('.'));
	
	else if (amount.indexOf('.') < -1 && amount.length > (maxlength - 3))
		amount = amount.substring(0,(maxlength - 2));
	
	else if (amount.length > maxlength)
		amount = amount.substring(0,maxlength - 1);
				
	return amount;
}

 
 Mask.prototype.setDecimal = function(_v, _d){
	var v = String(_v).replace(/[^\d.-]*/gi, "");
	//return RComma(v);
	return RoundDecimalCommaFormatted ( v, this.decimals );
 }
 
Mask.prototype.setNumber1 = function(_v, _d){
	var v = String(_v).replace(/[^\d.-]*/gi, ""), m = this.mask;
	// make sure there's only one decimal point
	v = v.replace(/\./, "d").replace(/\./g, "").replace(/d/, ".");

	// check to see if an invalid mask operation has been entered
	if( !/^[\$]?((\$?[\+-]?([0#]{1,3},)?[0#]*(\.[0#]*)?)|([\+-]?\([\+-]?([0#]{1,3},)?[0#]*(\.[0#]*)?\)))$/.test(m) )
		return this.throwError(1, "An invalid mask was specified for the \nMask constructor.", _v);

	if( (_d == true) && (v.length == this.strippedValue.length) ) v = v.substring(0, v.length-1);

	if( this.allowPartial && (v.replace(/[^0-9]/, "").length == 0) ) return v;
	this.strippedValue = v;

	if( v.length == 0 ) v = NaN;
	var vn = Number(v);
	if( isNaN(vn) ) return this.throwError(2, "The value entered was not a number.", _v);

	// if no mask, stop processing
	if( m.length == 0 ) return v;

	// get the value before the decimal point
	var vi = String(Math.abs((v.indexOf(".") > -1 ) ? v.split(".")[0] : v));
	// get the value after the decimal point
	var vd = (v.indexOf(".") > -1) ? v.split(".")[1] : "";
	var _vd = vd;

	var isNegative = (vn != 0 && Math.abs(vn)*-1 == vn);

	// check for masking operations
	var show = {
		"$" : /^[\$]/.test(m),
		"(": (isNegative && (m.indexOf("(") > -1)),
		"+" : ( (m.indexOf("+") != -1) && !isNegative )
	}
	show["-"] = (isNegative && (!show["("] || (m.indexOf("-") != -1)));


	// replace all non-place holders from the mask
	m = m.replace(/[^#0.,]*/gi, "");

	/*
		make sure there are the correct number of decimal places
	*/
	// get number of digits after decimal point in mask
	var dm = (m.indexOf(".") > -1 ) ? m.split(".")[1] : "";
	if( dm.length == 0 ){
		vi = String(Math.round(Number(vi)));
		vd = "";
	} else {
		// find the last zero, which indicates the minimum number
		// of decimal places to show
		var md = dm.lastIndexOf("0")+1;
		// if the number of decimal places is greater than the mask, then round off
		if( vd.length > dm.length ) vd = String(Math.round(Number(vd.substring(0, dm.length + 1))/10));
		// otherwise, pad the string w/the required zeros
		else while( vd.length < md ) vd += "0";
	}

	/*
		pad the int with any necessary zeros
	*/
	// get number of digits before decimal point in mask
	var im = (m.indexOf(".") > -1 ) ? m.split(".")[0] : m;
	im = im.replace(/[^0#]+/gi, "");
	// find the first zero, which indicates the minimum length
	// that the value must be padded w/zeros
	var mv = im.indexOf("0")+1;
	// if there is a zero found, make sure it's padded
	if( mv > 0 ){
		mv = im.length - mv + 1;
		while( vi.length < mv ) vi = "0" + vi;
	}


	/*
		check to see if we need commas in the thousands place holder
	*/
	if( /[#0]+,[#0]{3}/.test(m) ){
		// add the commas as the place holder
		var x = [], i=0, n=Number(vi);
		while( n > 999 ){
			x[i] = "00" + String(n%1000);
			x[i] = x[i].substring(x[i].length - 3);
			n = Math.floor(n/1000);
			i++;
		}
		x[i] = String(n%1000);
		vi = x.reverse().join(",");
	}


	/*
		combine the new value together
	*/
	if( (vd.length > 0 && !this.allowPartial) || ((dm.length > 0) && this.allowPartial && (v.indexOf(".") > -1) && (_vd.length >= vd.length)) ){
		v = vi + "." + vd;
	} else if( (dm.length > 0) && this.allowPartial && (v.indexOf(".") > -1) && (_vd.length < vd.length) ){
		v = vi + "." + _vd;
	} else {
		v = vi;
	}

	if( show["$"] ) v = this.mask.replace(/(^[\$])(.+)/gi, "$") + v;
	if( show["+"] ) v = "+" + v;
	if( show["-"] ) v = "-" + v;
	if( show["("] ) v = "(" + v + ")";
	return v;
}

Mask.prototype.setDate = function (_v){
	var v = _v, m = this.mask;
	var a, e, mm, dd, yy, x, s;

	// split mask into array, to see position of each day, month & year
	a = m.split(/[^mdy]+/);
	// split mask into array, to get delimiters
	s = m.split(/[mdy]+/);
	// convert the string into an array in which digits are together
	e = v.split(/[^0-9]/);
	
	if( s[0].length == 0 ) s.splice(0, 1);

	for( var i=0; i < a.length; i++ ){
		x = a[i].charAt(0).toLowerCase();
		if( x == "m" ) mm = parseInt(e[i], 10)-1;
		else if( x == "d" ) dd = parseInt(e[i], 10);
		else if( x == "y" ) yy = parseInt(e[i], 10);
	}

	// if year is abbreviated, guess at the year
	if (isNaN(yy))
	    yy=(new Date()).getFullYear();
	    
	if( String(yy).length < 3 ){
		yy = 2000 + yy;
		if( (new Date()).getFullYear()+20 < yy ) yy = yy - 100;
	}

	// create date object
	var d = new Date(yy, mm, dd);

	if( d.getDate() != dd ) return this.throwError(1, "An invalid day was entered.", _v);
	else if( d.getMonth() != mm ) return this.throwError(2, "An invalid month was entered.", _v);

	var nv = "";

	for( i=0; i < a.length; i++ ){
		x = a[i].charAt(0).toLowerCase();
		if( x == "m" ){
			mm++;
			if( a[i].length == 2 ){
				mm = "0" + mm;
				mm = mm.substring(mm.length-2);
			}
			nv += mm;
		} else if( x == "d" ){
			if( a[i].length == 2 ){
				dd = "0" + dd;
				dd = dd.substring(dd.length-2);
			}
			nv += dd;
		} else if( x == "y" ){
			if( a[i].length == 2 ) nv += d.getYear();
			else nv += d.getFullYear();
		}

		if( i < a.length-1 ) nv += s[i];
	}

	return nv;
}

Mask.prototype.setDateKeyPress = function (_v, _d){
	var v = _v, m = this.mask, k = v.charAt(v.length-1);
	var a, e, c, ml, vl, mm = "", dd = "", yy = "", x, p, z;

	if( _d == true ){
		while( (/[^0-9]/gi).test(v.charAt(v.length-1)) ) v = v.substring(0, v.length-1);
		if( (/[^0-9]/gi).test(this.strippedValue.charAt(this.strippedValue.length-1)) ) v = v.substring(0, v.length-1);
		if( v.length == 0 ) return "";
	}

	// split mask into array, to see position of each day, month & year
	a = m.split(/[^mdy]/);
	// split mask into array, to get delimiters
	s = m.split(/[mdy]+/);
	// mozilla wants to add an empty array element which needs removed
	if( s[0].length == 0 ) s.splice(0,1);
	// convert the string into an array in which digits are together
	e = v.split(/[^0-9]/);
	// position in mask
	p = (e.length > 0) ? e.length-1 : 0;
	// determine what mask value the user is currently entering
	c = a[p].charAt(0);
	// determine the length of the current mask value
	ml = a[p].length;

	for( var i=0; i < e.length; i++ ){
		x = a[i].charAt(0).toLowerCase();
		if( x == "m" ) mm = parseInt(e[i], 10)-1;
		else if( x == "d" ) dd = parseInt(e[i], 10);
		else if( x == "y" ) yy = parseInt(e[i], 10);
	}
	
	
	var nv = "";
	var j=0;

	for( i=0; i < e.length; i++ ){
		x = a[i].charAt(0).toLowerCase();
	
		if( x == "m" ){
			z = ((/[^0-9]/).test(k) && c == "m");
			mm++;
			if( (e[i].length == 2 && mm < 10) || (a[i].length == 2 && c != "m") || (mm > 1 && c == "m") || (z && a[i].length == 2) ){
				mm = "0" + mm;
				mm = mm.substring(mm.length-2);
			}
			vl = String(mm).length;
			ml = 2;
			nv += mm;
		} else if( x == "d" ){
			z = ((/[^0-9]/).test(k) && c == "d");
			if( (e[i].length == 2 && dd < 10) || (a[i].length == 2 && c != "d") || (dd > 3 && c == "d") || (z && a[i].length == 2) ){
				dd = "0" + dd;
				dd = dd.substring(dd.length-2);
			}
			vl = String(dd).length;
			ml = 2;
			nv += dd;
		} else if( x == "y" ){
			z = ((/[^0-9]/).test(k) && c == "y");
			if( c == "y" ) yy = String(yy);
			else {
				if( a[i].length == 2 ) yy = d.getYear();
				else yy = d.getFullYear();
			}
			if( (e[i].length == 2 && yy < 10) || (a[i].length == 2 && c != "y") || (z && a[i].length == 2) ){
				yy = "0" + yy;
				yy = yy.substring(yy.length-2);
			}
			ml = a[i].length;
			vl = String(yy).length;
			nv += yy;
		}

		if( ((ml == vl || z) && (x == c) && (i < s.length)) || (i < s.length && x != c ) ) nv += s[i];
	}

	if( nv.length > m.length ) nv = nv.substring(0, m.length);

	this.strippedValue = (nv == "NaN") ? "" : nv;

	return this.strippedValue;
}

function qEvent(e){
	// routine for NS, Opera, etc DOM browsers
	if( window.Event ){
		var isKeyPress = (e.type.substring(0,3) == "key");

		this.keyCode = (isKeyPress) ? parseInt(e.which, 10) : 0;
		this.button = (!isKeyPress) ? parseInt(e.which, 10) : 0;
		this.srcElement = e.target;
		this.type = e.type;
		this.x = e.pageX;
		this.y = e.pageY;
		this.screenX = e.screenX;
		this.screenY = e.screenY;
		if( document.layers ){
			this.altKey = ((e.modifiers & Event.ALT_MASK) > 0);
			this.ctrlKey = ((e.modifiers & Event.CONTROL_MASK) > 0);
			this.shiftKey = ((e.modifiers & Event.SHIFT_MASK) > 0);
			this.keyCode = this.translateKeyCode(this.keyCode);
		} else {
			this.altKey = e.altKey;
			this.ctrlKey = e.ctrlKey;
			this.shiftKey = e.shiftKey;
		}
	// routine for Internet Explorer DOM browsers
	} else {
		e = window.event;
		this.keyCode = parseInt(e.keyCode, 10);
		this.button = e.button;
		this.srcElement = e.srcElement;
		this.type = e.type;
		if( document.all ){
			this.x = e.clientX + document.body.scrollLeft;
			this.y = e.clientY + document.body.scrollTop;
		} else {
			this.x = e.clientX;
			this.y = e.clientY;
		}
		this.screenX = e.screenX;
		this.screenY = e.screenY;
		this.altKey = e.altKey;
		this.ctrlKey = e.ctrlKey;
		this.shiftKey = e.shiftKey;
	}
	if( this.button == 0 ){
		this.setKeyPressed(this.keyCode);
		this.keyChar = String.fromCharCode(this.keyCode);
	}
}

// this method will try to remap the keycodes so the keycode value
// returned will be consistent. this doesn't work for all cases,
// since some browsers don't always return a unique value for a
// key press.
qEvent.prototype.translateKeyCode = function (i){
	var l = {};
	// remap NS4 keycodes to IE/W3C keycodes
	if( !!document.layers ){
		if( this.keyCode > 96 && this.keyCode < 123 ) return this.keyCode - 32;
		l = {
			96:192,126:192,33:49,64:50,35:51,36:52,37:53,94:54,38:55,42:56,40:57,41:48,92:220,124:220,125:221,
			93:221,91:219,123:219,39:222,34:222,47:191,63:191,46:190,62:190,44:188,60:188,45:189,95:189,43:187,
			61:187,59:186,58:186,
			"null": null
		}
	}
	return (!!l[i]) ? l[i] : i;
}

// try to determine the actual value of the key pressed
qEvent.prototype.setKP = function (i, s){
	this.keyPressedCode = i;
	this.keyNonChar = (typeof s == "string");
	this.keyPressed = (this.keyNonChar) ? s : String.fromCharCode(i);
	this.isNumeric = (parseInt(this.keyPressed, 10) == this.keyPressed);
	this.isAlpha = ((this.keyCode > 64 && this.keyCode < 91) && !this.altKey && !this.ctrlKey);
	return true;
}

// try to determine the actual value of the key pressed
qEvent.prototype.setKeyPressed = function (i){
	var b = this.shiftKey;
	if( !b && (i > 64 && i < 91) ) return this.setKP(i + 32);
	if( i > 95 && i < 106 ) return this.setKP(i - 48);
	
	switch( i ){
		case 49: case 51: case 52: case 53: if( b ) i = i - 16; break;
		case 50: if( b ) i = 64; break;
		case 54: if( b ) i = 94; break;
		case 55: if( b ) i = 38; break;
		case 56: if( b ) i = 42; break;
		case 57: if( b ) i = 40; break;
		case 48: if( b ) i = 41; break;
		case 192: if( b ) i = 126; else i = 96; break;
		case 189: if( b ) i = 95; else i = 45; break;
		case 187: if( b ) i = 43; else i = 61; break;
		case 220: if( b ) i = 124; else i = 92; break;
		case 221: if( b ) i = 125; else i = 93; break;
		case 219: if( b ) i = 123; else i = 91; break;
		case 222: if( b ) i = 34; else i = 39; break;
		case 186: if( b ) i = 58; else i = 59; break;
		case 191: if( b ) i = 63; else i = 47; break;
		case 190: if( b ) i = 62; else i = 46; break;
		case 188: if( b ) i = 60; else i = 44; break;

		case 106: case 57379: i = 42; break;
		case 107: case 57380: i = 43; break;
		case 109: case 57381: i = 45; break;
		case 110: i = 46; break;
		case 111: case 57378: i = 47; break;

		case 8: return this.setKP(i, "[backspace]");
		case 9: return this.setKP(i, "[tab]");
		case 13: return this.setKP(i, "[enter]");
		case 16: case 57389: return this.setKP(i, "[shift]");
		case 17: case 57390: return this.setKP(i, "[ctrl]");
		case 18: case 57388: return this.setKP(i, "[alt]");
		case 19: case 57402: return this.setKP(i, "[break]");
		case 20: return this.setKP(i, "[capslock]");
		case 32: return this.setKP(i, "[space]");
		case 91: return this.setKP(i, "[windows]");
		case 93: return this.setKP(i, "[properties]");

		case 33: case 57371: return this.setKP(i*-1, "[pgup]");
		case 34: case 57372: return this.setKP(i*-1, "[pgdown]");
		case 35: case 57370: return this.setKP(i*-1, "[end]");
		case 36: case 57369: return this.setKP(i*-1, "[home]");
		case 37: case 57375: return this.setKP(i*-1, "[left]");
		case 38: case 57373: return this.setKP(i*-1, "[up]");
		case 39: case 57376: return this.setKP(i*-1, "[right]");
		case 40: case 57374: return this.setKP(i*-1, "[down]");
		case 45: case 57382: return this.setKP(i*-1, "[insert]");
		case 46: case 57383: return this.setKP(i*-1, "[delete]");
		case 144: case 57400: return this.setKP(i*-1, "[numlock]");
	}
	
	if( i > 111 && i < 124 ) return this.setKP(i*-1, "[f" + (i-111) + "]");

	return this.setKP(i);
}

// define the addEvent(oElement, sEvent, sCmd, bAppend) function
function $addEvent(o, _e, c, _b){
	var e = _e.toLowerCase(), b = (typeof _b == "boolean") ? _b : true, x = (o[e]) ? o[e].toString() : "";
	// strip out the body of the function
	x = x.substring(x.indexOf("{")+1, x.lastIndexOf("}"));
	x = ((b) ? (x + c) : (c + x)) + "\n";
	return o[e] = (!!window.Event) ? new Function("event", x) : new Function(x);
}

/**************************************** Mask Inputs ****************************************************/