﻿$(document).ready(function() {
    
    bindValidationEvents();
              
});

function bindValidationEvents()
{
    /* on textbox blur validate */
    $(".ValidateTextBox").blur(function() { 
        if($(this).val() != ""){
            msg = isValidTextBox(this,$(this).attr("class"));
            showError(this.id, msg, "TextBox");
        }else{
            $("#" + this.id + "_ValidationIcon").removeAttr("class");
            $("#" + this.id + "_ValidationIcon").attr("class","textBoxValidation");
        }     
    });
    
    $(".ValidateTextArea").blur(function() {
        if($(this).val() != ""){
            msg = isValidTextBox(this,$(this).attr("class"));
            showError(this.id, msg, "TextArea");
        }else{
            $("#" + this.id + "_ValidationIcon").removeAttr("class");
            $("#" + this.id + "_ValidationIcon").attr("class","textAreaValidation"); 
        }     
    });    
    
    /* Validate custom date */
    $(".ValidateCustomDate").blur(function() {
        validateCustomDate("#" + $(this).attr("id"), this);              
    });
    
    $(".ValidateCreditCardDate").blur(function(){
        validateCreditCardDate("#" + $(this).attr("id"), this);
    });
    
    /* on drop down change validate*/
    $(".ValidateDDL").change(function() {
        msg = isValidDropDown(this, $(this).attr("class"));
        showError(this.id, msg, "DropDown");
    });
    
    validatePreFilledItems();
}

function check_date(field){
    var checkstr = "0123456789";
    var DateField = field;
    var Datevalue = "";
    var DateTemp = "";
    var seperator = ".";
    var day;
    var month;
    var year;
    var leap = 0;
    var err = 0;
    var i;

    err = 0;
    DateValue = DateField

    /* Delete all chars except 0..9 */
    for (i = 0; i < DateValue.length; i++) {
      if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
         DateTemp = DateTemp + DateValue.substr(i,1);
      }
    }
    DateValue = DateTemp;
    /* Always change date to 8 digits - string*/
    /* if year is entered as 2-digit / always assume 20xx */
    if (DateValue.length == 6) {
      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
    if (DateValue.length != 8) {
      err = 19;}
    /* year is wrong if year = 0000 */
    year = DateValue.substr(4,4);
    if (year == 0) {
      err = 20;
    }
    /* Validation of month*/
    month = DateValue.substr(2,2);

    if ((month < 1) || (month > 12)) {
      err = 21;
    }
    /* Validation of day*/
    day = DateValue.substr(0,2);
    if (day < 1) {
     err = 22;
    }
    /* Validation leap-year / february / day */
    if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
    }
    if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
    }
    if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
    }
    /* Validation of other months */
    if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
    }
    if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
    }
    /* if 00 ist entered, no error, deleting the entry */
    if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
    }
    /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
    if (err == 0) {
      return true;
    }
    /* Error-message if err != 0 */
    else {
        return false;
    }
}

function validatePreFilledItems()
{
    //alert("validatePreFilledItems");

    $(".ValidateTextBox").each(function() {     
        if($(this).val() != "")
        {
            msg = isValidTextBox(this,$(this).attr("class"));
            showError(this.id, msg, "TextBox");         
        }     
    });
    
    /* loop all textareas that we want to validate */
    $(".ValidateTextArea").each(function(){   
        if($(this).val() != "")
        {
            msg = isValidTextBox(this,$(this).attr("class")); 
            showError(this.id, msg, "TextArea");        
        }
    });    
   
    /* loop all drop downs that we want to validate */
    $(".ValidateDDL").each(function() { 
        if($(this).val() != "" && $(this).val() != "0")
        {
            msg = isValidDropDown(this,$(this).attr("class"));
            showError(this.id, msg, "DropDown");
        }
    }); 
    
    $(".ValidateCustomDate").each(function() {
        if($(this).val())
        {
            validateCustomDate("#" + $(this).attr("id"), this);
        }        
    }); 
    
    $(".ValidateCreditCardDate").each(function() {
        if($(this).val())
        {
            validateCreditCardDate("#" + $(this).attr("id"), this);
        }        
    });            
    
}

function validateCustomDate(controlID, control)
{
    day = $(controlID).parent().find(".CustomDateDays").val();
    month = $(controlID).parent().find(".CustomDateMonth").val();
    year = $(controlID).val();

    if(day == '' || month == '' || year == '')
    {
        $("#" + control.id + "_ValidationIcon").removeAttr("class");
        $("#" + control.id + "_ValidationIcon").attr("class","textBoxValidationNotOK");
        return false;
    }else{
    
        if(day.length == 1)
        {
            day = "0" + day;
        }
        
        if(month.length == 1)
        {
            month = "0" + month;
        }            
    
        if(check_date(day + "." + month + "." + year))
        {
            $("#" + control.id + "_ValidationIcon").removeAttr("class");
            $("#" + control.id + "_ValidationIcon").attr("class","textBoxValidationOK"); 
            return true;           
        }else{
            $("#" + control.id + "_ValidationIcon").removeAttr("class");
            $("#" + control.id + "_ValidationIcon").attr("class","textBoxValidationNotOK"); 
            return false;           
        }        
    }
}

function validateCreditCardDate(controlID, control)
{
    month = $(controlID).parent().find(".CustomDateMonth").val();
    year = $(controlID).val();

    if(month.length == 2 && year.length == 2 && IsNumeric(month) && IsNumeric(year) && month < 13)
    {
        $("#" + control.id + "_ValidationIcon").removeAttr("class");
        $("#" + control.id + "_ValidationIcon").attr("class","textBoxValidationOK"); 
        return false;      
    }else{
        $("#" + control.id + "_ValidationIcon").removeAttr("class");
        $("#" + control.id + "_ValidationIcon").attr("class","textBoxValidationNotOK"); 
        return false;  
    }
}

function showError(control, errorMessage, controlType){

    var validateOKIcon = "";
    var validateNotOKIcon = "";

    if(controlType == "TextArea")
    {
        validateOKIcon = "textAreaValidationOK"; 
        validateNotOKIcon = "textAreaValidationNotOK"; 
    }else{
        validateOKIcon = "textBoxValidationOK"; 
        validateNotOKIcon = "textBoxValidationNotOK";     
    }

    if(errorMessage != ""){  
        $("#" + control + "_ValidationIcon").removeAttr("class");
        $("#" + control + "_ValidationIcon").attr("class",validateNotOKIcon);     
        
        var myClasses = $('#' + control).attr("class");
        
        if(!myClasses.match(" DoNotShowMessage")){  
            $("#" + control + "_ErrorMessage").html(errorMessage);
            $("#" + control + "_Error").slideDown();             
        }                     
    }else{
        $("#" + control + "_Error").slideUp(function(){
            $("#" + control + "_ValidationIcon").removeAttr("class");
            $("#" + control + "_ValidationIcon").attr("class",validateOKIcon);
        });       
    }
};

/* Hide the error */
function hideError(control){   

    $("#" + control + "_Error").slideUp(function(){
        $("#" + control + "_ValidationIcon").removeAttr("class");
        $("#" + control + "_ValidationIcon").attr("class","textBoxValidation");
    });
};

/* Validate the form */
function validateForm(){

    var isValid = true;

    /* loop all textboxes that we want to validate */
    $(".ValidateTextBox").each(function(){
       if($(this).is(":visible")){      
            msg = isValidTextBox(this,$(this).attr("class"));
            if(msg != ''){  
                isValid = false;            
            }     
            showError(this.id, msg, "TextBox");
        }
    });
    
    /* loop all textareas that we want to validate */
    $(".ValidateTextArea").each(function(){
        if($(this).is(":visible")){ 
            msg = isValidTextBox(this,$(this).attr("class"));
            if(msg != ''){  
                isValid = false;            
            }      
            showError(this.id, msg, "TextArea");
        }
    });    
   
    /* loop all drop downs that we want to validate */
    $(".ValidateDDL").each(function() {
        if ($(this).is(":visible")) {
            msg = isValidDropDown(this, $(this).attr("class"));
            if (msg != '') {
                isValid = false;
            }
            showError(this.id, msg, "DropDown");
        }
    });
    
    $(".ValidateCustomDate").each(function() {
        if($(this).is(":visible")){
            if(!validateCustomDate("#" + $(this).attr("id"), this))
            {
                isValid = false;
            }
        }
    });
    return isValid;
};

/* Checks whether dropdown is valid */
function isValidDropDown(myDropDown, myClasses) {
    if (myClasses.match(" Selected")) {
        var value = $(myDropDown).val();
        if (value == "" || value == "0") {
            return "** Please select an item from the list **";
        }                
    }
    else if (myClasses.match(" YesNoSelected")) {
        var value = $(myDropDown).val();                    
        if (value == "" || value == "0") {
            return "** Select **";
        }
    }        
    return "";    
}

/* Check whether textbox is valid */
function isValidTextBox(myTextBox, myClasses) {

    if(myClasses.match(" Required")){
        if ($(myTextBox).val() == "") {
            return "** This is a required field **";
        }                
    }          
    
    if(myClasses.match(" IsNumeric")){    
        if(!IsNumeric(myTextBox.value)){
            return "** Invalid Number **";
        }                
    }   
    
    if(myClasses.match(" IsDecimal")){    
        if(!IsDecimal(myTextBox.value)){
            return "** Invalid Amount **";
        }                
    }     
    
    if(myClasses.match(" IsValidEmail")){ 
        if(myTextBox.value != "")
        {
            if(!isValidEmail(myTextBox.value)){
                return "** Invalid Email **";
            }        
        }    
    }
    
    if(myClasses.match(" IsValidDepositAmount")){ 
        if(myTextBox.value != "")
        {
            if(!isValidDepositAmount(myTextBox.value)){
                return "** Please enter a valid deposit amount **";
            }        
        }    
    }
    
    if(myClasses.match(" IsValidPassword")){
        if(myTextBox.value != "")
        {
            if(!isValidPassword(myTextBox.value)){
                return "** Please enter a valid password **";
            }        
        }    
    }
    
    if(myClasses.match(" MinLength_")){
        MinLength = myClasses.substring(myClasses.indexOf("MinLength_"));
        MinLength = MinLength.substring(10);    
        if(MinLength.indexOf(" ") > 0){
            MinLength = MinLength.substring(0,MinLength.indexOf(" "));
        }  

        if(myTextBox.value.length < MinLength){
            return "** Must be at least **" + MinLength + " characters **";
        }               
    } 

    if(myClasses.match(" Child_")){     
        childID = myClasses.substring(myClasses.indexOf("Child_"));
        childID = childID.substring(6);    
        if(childID.indexOf(" ") > 0){
            childID = childID.substring(0,childID.indexOf(" "));
        }  

        if($("#" + childID).val() != ""){
            if($("#" + childID).val() != myTextBox.value){
                showError(childID, "** Data Does Not Match **", "TextBox");
            }else{
                showError(childID, "", "TextBox");
            }
        }
    }
    
    if(myClasses.match(" Parent_")){    
        parentID = myClasses.substring(myClasses.indexOf("Parent_"));                        
        parentID = parentID.substring(7);            

        if(parentID.indexOf(" ") > 0){
            parentID = parentID.substring(0,parentID.indexOf(" "));   
        }
        parentID = "#" + parentID;

        if(myTextBox.value != $(parentID).val()){
            return "** Data Does Not Match **";            
        }             
    }    
            
    return "";   
};

function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;   
};

function IsDecimal(sText)
{
    var filter = /^\d+(\.\d+)?$/;
    if (!(filter.test(sText))){
        return false;
    }else{
        return true;
    }        
};

function isValidEmail(Email){
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!(filter.test(Email))){
        return false;
    }else{
        return true;
    }
};

function isValidDepositAmount(depositAmount){
    var re = new RegExp(/^\£?(\d{1,3},?(\d{3},?)*\d{3}(\.\d{1,3})?|\d{1,3}(\.\d{2})?)$/);
    if (depositAmount.match(re)) {
        return true;
    } 
    else {
        return false;
    }   
}

function isValidPassword(password){    
    
    var re = new RegExp(/^.*(?=.{8,16})(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z]).*$/);
    if (password.match(re)) {
        return true;
    } 
    else {
        return false;
    }        
}

