﻿function fieldFocus(e){

    var myDiv = document.getElementById(e + "_div");
    myDiv.setAttribute('class','fieldFocus');   
    myDiv.setAttribute('className','fieldFocus'); 
    document.getElementById(e + "_msg").style.display = "block";
}

function fieldBlur(e){

    var myDiv = document.getElementById(e + "_div");
    myDiv.setAttribute('class','field');   
    myDiv.setAttribute('className','field'); 
    document.getElementById(e + "_msg").style.display = "none";
    document.getElementById(e + "_errMsg").style.display = "none";
}

function findPosY(obj)
{
    var curtop = 0;
    if(obj.offsetParent) {
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent) {
            break;
          }
          obj = obj.offsetParent;
        }
    } else if(obj.y) {
        curtop += obj.y;
    }
    
    return curtop;
}

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

/*
* This function is called on submission of the form, it checks if all the form went through the validation.
* @Parameters - 'whichForm': int of which form in the file should be validated, first form has 0 as value.
* @Return - Returns true if the form went through the validation, and false if it did not went through the validation.
*/

function submitForm(whichForm){
    try{
        if(document.ignoreValidation === true){
	    return true;
        }

        document.ValidationFieldErrors = "";
        document.ValidationFieldValues = "";
        
        //Assigning the form which should be validated to 'form'
        var form = document.getElementsByTagName("form")[whichForm];
        
        //Validation check of the form
        if(validateFormDatabanq(form, true)){
               //Form went through vaildation, return true.
               //alert("Process form... (temp alert)");
               return true;
        }else{
            //Form did not go through vaildation, return false, and show alert message.
            alert("Please, enter or correct the fields marked with a red background.");
            var divs = document.getElementsByTagName("div");
            var scrollTo = 0;
            var isFirstElemFound = false;
            
            for(var i = 0;i < divs.length;i++){
                
               if(!isFirstElemFound){                 
                    if(divs.item(i).getAttribute('class') == "fieldInvalid"){
                        scrollTo = findPosY(divs.item(i));
                        isFirstElemFound = true;
                    }
               }
            }
            window.scrollTo(0,scrollTo - 10);
           return false;
        }
	}catch(err){
	    LogError('SubmitForm - ' + err.description);
	} 
}

/****************************************************
* Rule set for validation and error messages.
* Rules for every different validation test. 
* Includes one label and one error message, if the 
* error messeges not going to be showed put "-".
* Currently the rules are called from the controls' 
* class. 
* 
* For example class="required zip", checks
* first if the field is rewuired and then if it's
* a valid zip code.
* 
* The fields are being validated on blur, currently
* by adding: onblur="javascript: validateFeild(this);"
* 
* TODO: Optically write a function that watches the
* form for on blurs. In that case the onblur tag does
* not have to be added on every field.
****************************************************/

var errMsg = {
	
	//Test that a field has a value.
	required:{
		msg: "This field is required",
		test: function(obj,load) {
		    try{
                return obj.value.trim().length > 0;
            }catch(err){
                LogError('RequiredValidation - ' + obj.id + ' - ' + load + ' - ' + err.description);
                return true;
            }	   		   
		}
	},
	
	//Test that a field is a valid zip.
	zip: {
		msg: "Enter a valid zip.",
		test: function(obj){
			var numericExpression = /^[0-9]+$/;
			
			if(obj.value.length == 0){
			    return true;
			}else if(obj.value.length !== 5){
				return false;
			}else if(!numericExpression.test(obj.value)){
				return false;
			}else{
				return true;
			}
		}
	},
	
	//Test that a field is valid phone number, and converts the phone number to the form of (123)-456-4567. Only for phone numbers in single textboxes. 
	phone: {
        msg: "Enter a valid phone number.",
        test: function(obj) {
            var m = /([2-9][0-9][0-9]).*([2-9][0-9][0-9]).*(\d{4})/.exec( obj.value );
			
            if ( m ) { obj.value = "(" + m[1] + ") " + m[2] + "-" + m[3]; }
				
            return !obj.value || m;
        }
    },
    
    //Date validation
	date: {
        msg: "Enter a valid date.",
        test: function(obj) {
            
            try{
        
                var dtStr = obj.value;
            	var daysInMonth = DaysArray(12);
	            var pos1=dtStr.indexOf(dtCh);
	            var pos2=dtStr.indexOf(dtCh,pos1+1);
	            var strMonth=dtStr.substring(0,pos1);
	            var strDay=dtStr.substring(pos1+1,pos2);
	            var strYear=dtStr.substring(pos2+1);
	            strYr=strYear;
	            if (strDay.charAt(0)=="0" && strDay.length>1) { strDay=strDay.substring(1); }
	            if (strMonth.charAt(0)=="0" && strMonth.length>1) { strMonth=strMonth.substring(1); }
	            for (var i = 1; i <= 3; i++) {
		            if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	            }
	            month=parseInt(strMonth);
	            day=parseInt(strDay);
	            year=parseInt(strYr);
	            
	         if (dtStr !== ""){
	            if (pos1==-1 || pos2==-1){
	                
		            alert("The date format should be : mm/dd/yyyy");
		            return false;
		        
	            }
	            if (strMonth.length<1 || month<1 || month>12){
		            alert("Please enter a valid month");
		            return false;
	            }
	            if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		            alert("Please enter a valid day");
		            return false;
	            }
	            if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		            alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		            return false;
	            }
	            if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		            alert("Please enter a valid date");
		            return false;
	            }else if (!isFutureDate(dtStr)){
	                alert("Please enter a future date");
	                return false;
	            }else if (!isWithinMonth(dtStr)){
	                alert("Date must be within the next 31 days");
	                return false;
	            }
	         }
            return true
            
            }catch(err){
	            LogError('DateValid - ' + err.description);
            }
            
        }
    },
    
    //Test that a field is valid phone number, and converts the phone number to the form of (123)-456-4567. Only for phone numbers in single textboxes. 
	ssn: {
        msg: "Invalid Social Sequrity Number",
        test: function(obj) {
            if(obj.value.length > 0){
                var matchArr = obj.value.match(/^(\d{3})-?\d{2}-?\d{4}$/);
                var numDashes = obj.value.split('-').length - 1;
                if (matchArr == null || numDashes == 1) {
                    return false; 
                }else{
                    return true;
                }  
            }else{
                return true;
            }     
        }
    },
	
	//Test if field if is a valid bank routing number.
	bankRouting: {
		msg: "Enter a valid bank routing number.",
		test: function(obj){
		    
		    try{
		        //Test value: 123123123
    		
		        //Code from http://www.brainjar.com/js/validation/default.asp
		        var s = obj.value;
			    var i, n, t;

                // First, remove any non-numeric characters.

                t = "";
                if(obj.value.length == 0){
                    return true;
                }else{
                    for (i = 0; i < s.length; i++) {
                    c = parseInt(s.charAt(i), 10);
                    if (c >= 0 && c <= 9)
                        t = t + c;
                    }

                    // Check the length, it should be nine digits.

                    if (t.length != 9)
                        return false;

                    // Now run through each digit and calculate the total.
                    n = 0;
                    for (i = 0; i < t.length; i += 3) {
                        n += parseInt(t.charAt(i),     10) * 3
                        +  parseInt(t.charAt(i + 1), 10) * 7
                        +  parseInt(t.charAt(i + 2), 10);
                    }

                    // If the resulting sum is an even multiple of ten (but not zero),
                    // the aba routing number is good.

                    if (n != 0 && n % 10 == 0){
                        return true;
                    }else{
                        return false;
    	            }
    	        }
    	     
    	    }catch(err){
                LogError('RoutingNumber - ' + err.description);
            }
         }
	},
	
	//Test that a field has a correct e-mail address.		
	email: {
		msg: "Enter a valid email address.",
		test: function(obj){
			var emailExpression = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			    
			    if(obj.value == ''){
				    return true;
			    }else if(!emailExpression.test(obj.value)){
				    return false;
			    }else{
				    return true;
				}
		}
	}
};

/*******************************
* END RULE SET
*******************************/

/*
* Loop through each and every control in the form, and call validateField function to check validation
* @Return: true or false, if there are errors or no.
*/
function validateFormDatabanq(form, load){
    
    //Boolean variable set to false if there are any errors.
    var valid = true;
	
	//Go through every controll in the form.
	for(var i = 0; i < form.elements.length; i++){
	    
	    //If the control did not pass the validation, set 'valid' to false.
	    if(!validateField(form.elements[i], load)){
	        valid = false;
	    }
	}
  
  	if(valid){
	    return true;
	} else {

	    //Try to log the errors
	    try {
	        document.getElementById('imgError').src = '/common/form_error.aspx?error=Invalid&field=' + escape(document.ValidationFieldErrors) + '&fieldValues=' + escape(document.ValidationFieldValues);
	    } catch (err) {}
	
	    return false;
	}
}

/*
* Validating a specific field
*/
function validateField(elem, load){
	
	try{
	
	    //List of all the errors.
	    var errors = [];
	    //List of errors that should be shown.
	    var errorList = [];
    	
	    //Go through every rule in errMsg.	
	    for(var name in errMsg){
    	    
    	    try{
    	    
	            //Create a regular expression for every rule name.
	            var re = new RegExp("(^|\\s)" + name + "(\\s|$)");
        					    	            
	                //Check if the class name belongs to the rule set and if it passes the validation    
	                if(re.test(elem.className) && !errMsg[name].test(elem, load)){
	        	        //Add error to errorlist
	                    errors.push(errMsg[name].msg);            
	       	        //Else if the feild passes the validation, hide all errors around the control      	   
		            }else if(re.test(elem.className) && errMsg[name].test(elem, load)){
			            hideErrors(elem);
		            }
		        
		    }catch(err){
		        LogError('ValidateSingleField - ' + name + ' - ' + elem.id + ' - ' + load + ' - ' + err.description);
		    }
	    }
    	
	    //Check if there are any errors
	    if(errors.length){
	        //Show error messages
		    showErrors(elem, errors, errorList);
	    }
    	
	    //Check if there are any errors
	    if (errors.length == 0){
	        //alert("Control: " + elem + " True: " + elem.value);
	        return true;
	    }else{
	        //alert("Control: " + elem + " False: " + elem.value);
	        return false;
	    }
	    
	}catch(err){
	   LogError('ValidateField - ' + err.description);
	}
}

/*
* Hides error messages
*/
function hideErrors(elem){
    
    try{
        var divWrap = elem.parentNode;
        divWrap.setAttribute('class','fieldPassed');
        divWrap.setAttribute('className','fieldPassed');
        elem.nextSibling.nextSibling.style.display = "none";
        
        try{
        elem.nextSibling.nextSibling.nextSibling.style.display = "none";
        elem.nextSibling.nextSibling.nextSibling.nextSibling.style.display = "none";
        }catch(err){
            //Do Nothing
        }
        
	}catch(err){
	    LogError('HideErrors - ' + err.description);
	}
}

/*
* Shows error messages
*/
function showErrors(elem, errors, errorList){
    try{
        var divWrap = elem.parentNode;
        divWrap.setAttribute('class','fieldInvalid');
        divWrap.setAttribute('className','fieldInvalid');
        elem.nextSibling.nextSibling.style.display = "block";
        elem.nextSibling.nextSibling.innerHTML = errors;
        
        try{
        elem.nextSibling.nextSibling.nextSibling.nextSibling.style.display = "none";
        }catch(err){
            //Do Nothing
        }
        
    }catch(err){
	    LogError('ShowErrors - ' + err.description);
	}
}

var d = new Date();
var curr_year = d.getFullYear();

var dtCh= "/";
var minYear=curr_year;
var maxYear=curr_year + 1;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30};
		if (i==2) {this[i] = 29};
   } 
   return this
}

function isWithinMonth(dtStr) {

try{

    var d = new Date();
    var curr_date = new Date().setDate(d.getDate() + 33);
    var entered_date = Date.parse(dtStr);

    if (curr_date < entered_date) {
        return false;
    } else {
        return true;
    }

}catch(err){
	   LogError('isWithinMonth - ' + err.description);
}

}

function isFutureDate(dtStr){

try{

    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    curr_month = curr_month + 1;
    var curr_year = d.getFullYear();

    var selectedYear = dtStr.substr(6);

    var selectedDay = dtStr.charAt(3) + dtStr.charAt(4);
    if (selectedDay.charAt(0) == 0){
        selectedDay = selectedDay.charAt(1);
    }

    var selectedMonth = dtStr.charAt(0) + dtStr.charAt(1);
    if (selectedMonth.charAt(0) == 0){
        selectedMonth = selectedMonth.charAt(1);
    }

    if (selectedYear < curr_year){
        return false;
    }else if (selectedYear == curr_year && selectedMonth < curr_month){
        return false;
    }else if (selectedYear == curr_year && selectedMonth == curr_month && selectedDay < curr_date){
        return false;
    }else{
        return true;
    }
    
}catch(err){
	   LogError('isFutureDate - ' + err.description);
}

}

function LogError(err){
    try {
	    document.getElementById('imgError').src = '/form_error.aspx?error=Fatal&ErrorString=' + escape(err);
	} catch (err) {}
}


