﻿
function storeNum(sInput)
{	
	return storeChar(sInput, "0123456789");
}
function storeChar(sInput, sCharList)
{	var n;
	var sNextChar;
	var sOut="";
		
	for(n=0;n<sInput.length;++n)
	{	sNextChar = sInput.substring(n, n+1);
		if (sCharList.indexOf(sNextChar) >= 0)
			sOut += sNextChar;
	}
	return sOut;
}

function isValidEmail(val) 
{   
    var reg = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
    if ( reg.test(val) )
    {
        return true;
    }
    else
    { 
        return false;
    }
    
}

function commaAdd(objInput)
{	var n;
	var sNextChar;
	var objOut="";
		
	for(n=0;n<objInput.length;++n)
	{	
	    objOut += objInput.substring(n, n+1);
		if (n<objInput.length-1 && !((objInput.length-n-1)%3))
			objOut += ",";
	}
	return objOut;
}

function hyphenAdd(objInput)
{	var n;
	var objOut="";
			
	for(n=0;n<objInput.length;++n)
	{	objOut += objInput.substring(n, n+1);
		if (n<objInput.length && !((objInput.length-n)%3)){
		    objOut += "-";
		} else if (objInput.length>8){
		    objOut = objInput.substring(0,3) + "-" + objInput.substring(3,6) + "-" + objInput.substring(6,10);
		}
	}
	return objOut;
}

function phoneFormat(objInput)
{	var cAmt;
	cAmt = hyphenAdd(storeNum(objInput.value, "-() "));
//	if (cAmt.length)
//		cAmt = "$" + cAmt;
	objInput.value = cAmt;
}

function currencyFormat(objInput)
{	var cAmt;
	cAmt = commaAdd(storeNum(objInput.value, "$., "));
//	if (cAmt.length)
//		cAmt = "$" + cAmt;
	objInput.value = cAmt;
}

function isNumberKey(evt, isDecimal)
{
     var charCode = (evt.which) ? evt.which : event.keyCode;
     if (isDecimal && charCode == 46)
        return true;
     if (charCode > 31 && (charCode < 48 || charCode > 57))         
        return false;            

     return true;
}   
function RestrictOnlyNumericDigitsAndMinusSign()
{
    var key = window.event.keyCode; // Netscape Method
    //alert("Key is = " + key) //for testing purpose
    if ((key > 47 && key < 58 ) || (key == 45))
    //if (key > 47 && key < 58 )
        return;
    else
        window.event.returnValue = null;
}


function CheckLoanAmount(lfld)
{
    Num1 = document.getElementById(lfld).value;
    Num1 = Num1.replace('$',' ');

// remove commas
    Num1 = Num1.replace(',','');
    Num1 = Num1.replace(',','');
    Num1 = Num1.replace(',','');
	
	Num1 = parseFloat(Num1);
	
	/*
	if (Num1 < 10000)
	{
        alert( "Please confirm your Loan Amount...");	
	}
    */

    //	if ((Num1 < 10000) || (Num1 > 3000000))
    //	{
    //        alert( "Please confirm your Loan Amount...");	
    //        return false;
    //	}

    dollarAmount(lfld);    
}

//function FormatAmount(lfld)
//{
//    var key = window.event.keyCode; // Netscape Method
//   // alert("Key is = " + key) //for testing purpose

//    if (key <= 47 || key >= 58)
//        window.event.returnValue = null;
//    else
//    {
//        Num1 = document.getElementById(lfld).value;
//        Num1 = Num1.replace('$',' ');

//        // remove commas .replace(new RegExp(/,/g), '')
//        Num1 = Num1.replace(new RegExp(/,/g), '');
//        
//	    Num1 = parseFloat(Num1);


//        dollarAmount(lfld);   
//    } 

//}

function checkNum(data) 
{   // checks if all characters
    // are valid numbers or a ". 
    var valid = "0123456789.";    
    var ok = 1; var checktemp;
    for (var i=0; i<data.length; i++) 
    {
        checktemp = "" + data.substring(i, i+1);
        if (valid.indexOf(checktemp) == "-1") return 0; 
    }
    return 1;
}


function GetFloatValue(fld1)
{
    Num1 = document.getElementById(fld1).value;
    Num1 = Num1.replace('$',' ');

// remove commas
    Num1 = Num1.replace(',','');
    Num1 = Num1.replace(',','');
    Num1 = Num1.replace(',','');
	
	if (Num1 == '')
	  {  Num1 =0; }
    dollarAmount(fld1);    
    return 	Num1;
}

function dollarAmount(field) 
{ 
    Num = document.getElementById(field).value;
	if (Num == '')
	  {  Num ='0'; }

    Num = Num.replace('$',' ');

// remove commas
    Num = Num.replace(',','');
    Num = Num.replace(',','');


    dec = Num.indexOf(".");
    end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ".00");

    Num = "" + parseInt(Num);

    var temp1 = "";
    var temp2 = "";
    if (checkNum(Num) != 0) 
    {    
        if (end.length == 2) end += "0";
        if (end.length == 1) end += "00";
        if (end == "") end += ".00";
        var count = 0;
        for (var k = Num.length-1; k >= 0; k--) 
        {
            var oneChar = Num.charAt(k);
            if (count == 3)  {
                temp1 += ",";
                temp1 += oneChar;
                count = 1;
                continue;
            }
            else {
                temp1 += oneChar;
                count ++;
            }
        }
        for (var k = temp1.length-1; k >= 0; k--) {
            var oneChar = temp1.charAt(k);
            temp2 += oneChar;
        }
        temp2 = "$" + temp2;  //+ end;
        temp2 = temp2 + end; //For the time being since the Range validator does not wolrk with $ sign!
        document.getElementById(field).value = temp2;
    }
}



function DisplayForgotPassword()
{
   document.getElementById('divForgotPassword').style.display = '';   
}

function HideForgotPassword()
{
   document.getElementById('divForgotPassword').style.display = 'none';   
}

//Function added by Tadesse on 07/15/07 to disable <Enter Key> in the Steps so as to 
//solve Issues such as #8 and #27
function KeyPress() 
{
    //alert(window.event.keyCode)
    //Disable the <Enter Key>
    if (window.event.keyCode == 13)
        window.event.keyCode =0;
} 

//Function to prevent copying using Mouse and pasting contents from a 
//text box such as in Re-typing an Email Id
//Added by Tadesse on 07/20/07 to address Issue #28
function noCopyMouse(e) 
{
    var isRight = (e.button) ? (e.button == 2) : (e.which == 3);
    
    if (isRight) {
        alert ('Please type the e-mail address for validation purposes, Copy/Paste function not allowed.');
        return false;
    }
    return true;
} 

//Function to prevent copying and pasting contents using shortcuts from a text box such 
//as in Re-typing an Email Id
//Added by Tadesse on 07/20/07 to address Issue #28
function noCopyKey(e) 
{
    var forbiddenKeys = new Array('c','x','v');
    var keyCode = (e.keyCode) ? e.keyCode : e.which;
    var isCtrl;

    if(window.event)
        isCtrl = e.ctrlKey
    else
        isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;

    if(isCtrl) {
        for(i = 0; i < forbiddenKeys.length; i++) {
            if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                alert('Please type the e-mail address for validation purposes, Copy/Paste function not allowed.');
                return false;
            }
        }
    }
    return true;
}



/*------------------------------------------------------------------------
Purpose: Restricts the text field to Alpha numeric
Inputs : Text field object, event object
Returns: Bool
Enter the filter condition and on code behind page load, add the keypress event 
to the element by: TextBox1.Attributes.Add("OnKeyPress","return RestrictOnlyNumericDigits()";
Author: Tadesse 
Date:   08/30/2007
-------------------------------------------------------------------------*/
function RestrictOnlyNumericDigits()
{
    var key = window.event.keyCode; // Netscape Method
    //alert("Key is = " + key) //for testing purpose
    //if ((key > 47 && key < 58 ) || (key == 46))
    if (key > 47 && key < 58 )
        return;
    else
        window.event.returnValue = null;
   
}

function RestrictOnlyAlphabets(){
    var key = window.event.keyCode; // Netscape Method
   // alert("Key is = " + key) //for testing purpose
    //if ((key > 47 && key < 58 ) || (key == 46))
    if ((key > 64 && key < 91 ) || (key > 96 && key < 123) || key == 32) //Space is included
        return;
    else
        window.event.returnValue = null;
}


function CommaSeparatedNos()
{
    var key = window.event.keyCode; // Netscape Method
   // alert("Key is = " + key) //for testing purpose
    if ((key > 47 && key < 58 ) || (key == 44))
    //if (key > 47 && key < 58 )
        return;
    else
        window.event.returnValue = null;
}


//function ValidateAges(obj) {
//    val = obj.value;
//    val = val.split(',');
//    for(var c=0; c < val.length; c++) {
//        if (val[c] > 120)
//        {
//            alert (val[c] + " Age should be less than 120 years. Please re-enter.");
//            return false;
//        }
//    }
//}

function ValidateAges(source, args) {
    val = args.Value;
    val = val.split(',');
    for(var c=0; c < val.length; c++) {
        if (val[c] > 120)
        {
           // alert ("Age should be less than 120 years. Please re-enter.");
            args.IsValid = false;
            break;
        }
    }
     //args.IsValid =  true;
}

function capitalizeMe(obj) {
    val = obj.value;
    newVal = '';
    val = val.split(' ');
    for(var c=0; c < val.length; c++) {
        newVal += val[c].substring(0,1).toUpperCase() +
        val[c].substring(1,val[c].length) + ' ';
    }
    obj.value = newVal;
}


////The following two functions are added to solve entry problrms of Numeric fields. Currently, we are not using them.
////In the future, please  add a call to EnableNumericValidation on the ValidatorOnLoad function. 
////You can insert the call at the end of the function. 
////This function is called every time we enter a page with validation controls.
//function NumericDataOnly()
//{
//   var key = window.event.keyCode;
//// alert("Got It data=");
//   if ( key > 47 && key < 58 )
//      return;
//   else
//      window.event.returnValue = null;
//}

//function EnableNumericValidation()
//{
//    var i;
//    for (i = 0; i < Page_Validators.length; i++) {
//        if (Page_Validators[i].type == "Integer") { //how does it work? It checks the validator in the page
//            document.getElementById(Page_Validators[i].controltovalidate).onkeypress = NumericDataOnly;
//        }
//    }
//}


/*------------------------------------------------------------------------
Purpose: Restricts entry of repeating chars such as 111-111-1111 for Phone number
Inputs : source, args
Returns: String
Where to Use: This function can be used for SSN, Phone#, or any text values whose values
            does not permit entering repeating single char value. Example: 1111111111
How:  in the CustomValidator
       Example:
             <asp:CustomValidator ID="CustValSSN" runat="server" 
                    ControlToValidate="txtSSN" ClientValidationFunction="CheckRepeatingString" Display="None"
                    ErrorMessage="Invalid Borrower's SSN. Please enter valid SSN."></asp:CustomValidator>
Author: Tadesse 
Date:   09/04/2007
-------------------------------------------------------------------------*/
function CheckRepeatingString(source, args) 
{
     var str = args.Value;
     for (var i=0; i < str.length; i++)
     {
        var oneChar = str.charAt(i);
        
        if (replaceSubstring(str, oneChar, "") == "") 
        {
            //alert("Please enter valid string ...");	
            args.IsValid = false;
            break;
        }
     }      
//     
//     args.IsValid = true; 
            
}

//
//The following function is written on 09/04/07 by Tadesse to be called by CheckRepeatingString() function.
//  Examples: 1. replaceSubstring("1111111111", "1", "") = ""
//           2. replaceSubstring("Getting rid of unwanted words", "unwanted", "unneeded") = "Getting rid of unneeded words"
//
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

//The following function is written on 09/06/07 by Tadesse to resolve Issue #404 (Age of a borrower/co-borrower 
//should be greater or equal to 18 years.
function ageCalc(source, args){ 

    if (!isValidDate(args.Value, "MDY")) {args.IsValid = false;}

    var d = args.Value.split('/'); 
    var bday=new Date(d[2],d[0],d[1]); //YYYY/MM/DD format
   
    var BirthDay= bday.getDate();
    var BirthMonth= bday.getMonth();
    var BirthYear= bday.getFullYear();

    var now = new Date();
    var CurrDay=now.getDate();
    var CurrMonth=now.getMonth()+1;
    var CurrYear=now.getFullYear();
    
    var age = CurrYear-BirthYear-1;
    if ((BirthMonth < CurrMonth) || ((BirthMonth == CurrMonth) && (BirthDay <= CurrDay)))
      age++;
    
    if (age < 18) args.IsValid = false; 
    
  //  alert('You are ' + age + ' years old and You are BD'+ BirthDay + ' month ' + BirthMonth + ' year ' + BirthYear) //for debugging
} 

//The following function is used by the above function!, ageCalc.
function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ((format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1)) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ((reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was

   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") {var mm = parts[0];} else if (format.substring(1, 2) == "M") {var mm = parts[1];} else {var mm = parts[2];}
   if (format.substring(0, 1) == "D") {var dd = parts[0];} else if (format.substring(1, 2) == "D") {var dd = parts[1];} else {var dd = parts[2];}
   if (format.substring(0, 1) == "Y") {var yy = parts[0];} else if (format.substring(1, 2) == "Y") {var yy = parts[1];} else {var yy = parts[2];}
            
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
