jQuery(document).bind(
    'ready',
    function() {
        
        $.metadata.setType("attr", "validate");        
        
        var enableClientSideValidation = 1;
        
        if (enableClientSideValidation) {
            // Setup validation
            
            // don't validate when tabbing between fields
            // only on submit
            onfocusout: true;
            
            // writes debug output to firebug console
            // and stops form submitting
            debug: false 
            
            // customer form validation
            jQuery("form[id='customer']").validate({
                rules: {
                    title: "required",
                    forename: {
                        required: true,
                        string: true
                    },
                    surname: {
                        required: true,
                        string: true
                    },
                    day: {
                        required: true,
                        digits: true,
                        minlength: 1,
                        maxlength: 2
                    },
                    month: {
                        required: true,
                        string: true
                    },
                    year: {
                        required: true,
                        digits: true,
                        maxlength: 4
                    },
                    phone1_type: "required",
                    phone1_number: {
                        required: true,
                        phone: true
                        //minlength: 10,
                        //maxlength: 11
                    },
/*                    
                    phone2_number: {
                        phone: true,
                        minlength: 11,
                        maxlength: 11
                    },
*/
                    email: { 
                        required: true,
                        email: true
                    },
                    email2: {
                        required: true,
                        email: true,
                        equalTo: "#email"
                    },
                    national_insurance: {
                        required: false,
                        national_insurance: true
                    },
                    nationality: {
                        required: true,
                        string: true
                    },
                    address_1: {
                        required: true,
                        stringOrDigit: true
                    },
                    address_2: {
                        required: true,
                        stringOrDigit: true
                    },
                    address_3: {
                        required: true,
                        stringOrDigit: true
                    },
                    address_4: {
                        required: true,
                        stringOrDigit: true
                    },
                    postcode1: {
                        required: true,
                        outcode: true
                    },
                    postcode2: {
                        required: true,
                        incode: true
                    },
                    time_at_address_years: {
                        required: true,
                        digits: true
                    },
                    time_at_address_months: {
                        required: true,
                        digits: true,
                        range: [0, 11]
                    }
    /*                
                    current_address: {
                        required: true,
                        range: [0, 1]
                      
                    }
    */                  
                },            
                invalidHandler: function(form, validator) {
                      var errors = validator.numberOfInvalids();
                      if (errors) {
                        //var message = errors == 1
                        //? 'Incomplete submission. You missed 1 field. It has been highlighted'
                        //: 'Incomplete submission. You missed ' + errors + ' fields. They have been highlighted';
                        
                        // hide server side error code
                        $(".server").hide();
                        
                        var message = 'Incomplete or incorrect fields have been detected.  Please complete the form and click Next to continue.';
                        $("div.error span").html(message);
                        $("div.error").show();
                      } else {
                        $("div.error").hide();
                      }
                },
                
                // group inputs to single error message
                groups: {
                    dob: "day month year",
                    telephone1: "phone1_type phone1_number",
                    postcode: "postcode1 postcode2",
                    timeataddress: "time_at_address_years time_at_address_months"
                },
                errorPlacement: function(error, element) {
                    if (element.attr("name") == 'day' || element.attr("name") == 'month' || element.attr("name") == 'year')
                        error.insertAfter("#year");
                    else if (element.attr("name") == 'phone1_type' || element.attr("name") == 'phone1_number')
                        error.insertAfter("#phone1_number");
                    else if (element.attr("name") == 'postcode1' || element.attr("name") == 'postcode2')
                        error.insertAfter("#postcode2");
                    else if (element.attr("name") == 'time_at_address_years' || element.attr("name") == 'time_at_address_months')
                        error.insertAfter("#time_at_address_months");
                    else
                        error.insertAfter(element);
                },


/* 
                errorElement: "div",
            
                // display a bespoke message for each input
                messages: {
                    title: "please complete this mandatory field",
                    forename: "please complete this mandatory field",
                    surname: "please complete this mandatory field", 
                    day: "please complete this mandatory field",
                    month: "please complete this mandatory field", 
                    year: "please complete this mandatory field", 
                    phone1_type: "please complete this mandatory field", 
                    phone1_number: "please complete this mandatory field",
                    email: "please complete this mandatory field", 
                    email2: "please complete this mandatory field",
                    nationality: "please complete this mandatory field", 
                    address_1: "please complete this mandatory field", 
                    address_2: "please complete this mandatory field", 
                    address_3: "please complete this mandatory field", 
                    address_4: "please complete this mandatory field", 
                    postcode1: "please complete this mandatory field", 
                    postcode2: "please complete this mandatory field", 
                    time_at_address_years: "please complete this mandatory field", 
                    time_at_address_months: "please complete this mandatory field"
                }
*/
                
            });
            
            
            // address form validation
            jQuery("form[id='address']").validate({
                rules: {
                    address_1: {
                        required: true,
                        stringOrDigit: true
                    },
                    address_2: {
                        required: true,
                        stringOrDigit: true
                    },
                    address_3: {
                        required: true,
                        stringOrDigit: true
                    },
                    address_4: {
                        required: true,
                        stringOrDigit: true
                    },
                    postcode1: {
                        required: true,
                        outcode: true
                    },
                    postcode2: {
                        required: true,
                        incode: true
                    },
                    time_at_address_years: {
                        required: true,
                        digits: true
                    },
                    time_at_address_months: {
                        required: true,
                        digits: true,
                        range: [0, 11]
                    }
                },
                invalidHandler: function(form, validator) {
                      var errors = validator.numberOfInvalids();
                      if (errors) {
                        //var message = errors == 1
                        //  ? 'Incomplete submission. You missed 1 field. It has been highlighted'
                        //  : 'Incomplete submission. You missed ' + errors + ' fields. They have been highlighted';
                        var message = 'Incomplete or incorrect fields have been detected.  Please complete the form and click Next to continue.';
                        $("div.error span").html(message);
                        $("div.error").show();
                      } else {
                        $("div.error").hide();
                      }
                },
                
                // group inputs to single error message
                groups: {
                    postcode: "postcode1 postcode2",
                    timeataddress: "time_at_address_years time_at_address_months"
                },
                errorPlacement: function(error, element) {
                    if (element.attr("name") == 'postcode1' || element.attr("name") == 'postcode2')
                        error.insertAfter("#postcode2");
                    else if (element.attr("name") == 'time_at_address_years' || element.attr("name") == 'time_at_address_months')
                        error.insertAfter("#time_at_address_months");
                    else
                        error.insertAfter(element);
                },
                
/*                
                errorElement: "div",
                
                // display a bespoke message for each input
                messages: {
                    address_1: "please complete this mandatory field", 
                    address_2: "please complete this mandatory field", 
                    address_3: "please complete this mandatory field", 
                    address_4: "please complete this mandatory field", 
                    postcode1: "please complete this mandatory field", 
                    postcode2: "please complete this mandatory field", 
                    time_at_address_years: "please complete this mandatory field", 
                    time_at_address_months: "please complete this mandatory field"
                }
*/
                
            });
            
            
            // application form validation
            jQuery("form[id='application']").validate({
                rules: {
                    accommodation: "required",
                    residential_status: "required",
                    marital_status: "required",
                    dependants: {
                        required: true,
                        digits: true
                    },
                    loan_purpose: "required",
                    income_frequency: "required",
                    bank_account: "required",
                    have_credit_card: "required",
                    weekly_income: {
                        required: true,
                        digits: true
                    },
                    qualify_bankrupt: "required",
                    qualify_iva: "required",
                    qualify_dro: "required",
                    occupation: "required",
                    employment_status: "required",
                    employer_name: {
                        required: function(element) {
                            return ( $("#occupation").val() != 'Unemployed' && $("#occupation").val() != 'In Education' );
                        },
                        string: true
                    },
                    employment_length_years: {
                        required: function(element) { return ( $("#occupation").val() != 'Unemployed' && $("#occupation").val() != 'In Education' ); },
                        digits: true
                    },
                    employment_length_months: {
                        required: function(element) { return ( $("#occupation").val() != 'Unemployed' && $("#occupation").val() != 'In Education' ); },
                        digits: true,
                        range: [0, 11]
                    },
                    work_telephone: {
                        required: function(element) { return ( $("#occupation").val() != 'Unemployed' && $("#occupation").val() != 'In Education' ); },
                        landphone: true,
                    },
                    loan_amount: "required",
                    terms: "required",
					cca: "required"
                },
                invalidHandler: function(form, validator) {
                      var errors = validator.numberOfInvalids();
                      if (errors) {
                        //var message = errors == 1
                        //  ? 'Incomplete submission. You missed 1 field. It has been highlighted'
                        //  : 'Incomplete submission. You missed ' + errors + ' fields. They have been highlighted';
                        
                        // hide server side error code
                        $(".server").hide();
                        
                        var message = 'Incomplete or incorrect fields have been detected.  Please complete the form and click Next to continue.';                          
                        $("div.error span").html(message);
                        $("div.error").show();
                      } else {
                        $("div.error").hide();
                      }
                },
                
                // group inputs to single error message
                groups: {
                    employment_length: "employment_length_years employment_length_months"
                },
                errorPlacement: function(error, element) {
                    if (element.attr("name") == 'employment_length_years' || element.attr("name") == 'employment_length_months')
                        error.insertAfter("#employment_length_months");
                    else
                        error.insertAfter(element);
                },
                
/*                
                errorElement: "div",
                
                // display a bespoke message for each input
                messages: {
                    accommodation: "please complete this mandatory field", 
                    residential_status: "please complete this mandatory field", 
                    marital_status: "please complete this mandatory field", 
                    dependants: "please complete this mandatory field", 
                    loan_purpose: "please complete this mandatory field", 
                    income_frequency: "please complete this mandatory field", 
                    bank_account: "please complete this mandatory field",
                    have_credit_card: "please complete this mandatory field", 
                    weekly_income: "please complete this mandatory field", 
                    qualify_bankrupt: "please complete this mandatory field", 
                    qualify_iva: "please complete this mandatory field", 
                    qualify_dro: "please complete this mandatory field", 
                    occupation: "please complete this mandatory field", 
                    employment_status: "please complete this mandatory field", 
                    employer_name: "please complete this mandatory field", 
                    employment_length_years: "please complete this mandatory field", 
                    employment_lenght_months: "please complete this mandatory field", 
                    work_telephone: "please complete this mandatory field", 
                    loan_amount: "please complete this mandatory field", 
                    terms: "please complete this mandatory field"
                }
*/
            });
            
            
            /** Custome jQuery validation rules to match those in the Perl code
            Completely violates the DRY principle... **/
            jQuery.validator.addMethod("string", function(value, element) {
                return this.optional(element) || (value.match(/^[\w\s]*/));
            }, "Value must be a string");
            jQuery.validator.addMethod("stringOrDigit", function(value, element) {
                return this.optional(element) || (value.match(/^[\w\s\d]*/));
            }, "Value must be a string or digit");
            jQuery.validator.addMethod("outcode", function(value, element) {
                value = value.toUpperCase();
                if ( this.optional(element) ) {
                    return true;
                }
                else {
                    if (value.match(/^[A-PR-UWYZ][A-HK-Y0-9]$/)) {
                        return true;
                    }
                    else if (value.match(/^[A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]$/)) {
                        return true;
                    }
                    else if (value.match(/^[A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9][ABEHMNPRVWXY0-9]$/)) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }, "Invalid postcode");
            jQuery.validator.addMethod("incode", function(value, element) {
                value = value.toUpperCase();
                return this.optional(element) || (value.match(/^[0-9][ABD-HJLN-UW-Z]{2}$/));
            }, "Invalid postcode");
            jQuery.validator.addMethod("phone", function(value, element) {
                value = value.replace(/\s/,"");
                return this.optional(element) || ((value.match(/(\s*\(?0\d{4}\)?(\s*|-)\d{3}(\s*|-)\d{3}\s*)|(\s*\(?0\d{3}\)?(\s*|-)\d{3}(\s*|-)\d{4}\s*)|(\s*(7|8)(\d{7}|\d{3}(\-|\s{1})\d{4})\s*)/) && value.match(/^[\d|\s]*$/)) || (value.match(/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/) && value.match(/^[\d|\s]*$/)) );
            }, "Invalid phone number");
            jQuery.validator.addMethod("landphone", function(value, element) {
                value = value.replace(/\s/,"");
                return this.optional(element) || ( (value.match(/(\s*\(?0\d{4}\)?(\s*|-)\d{3}(\s*|-)\d{3}\s*)|(\s*\(?0\d{3}\)?(\s*|-)\d{3}(\s*|-)\d{4}\s*)|(\s*(7|8)(\d{7}|\d{3}(\-|\s{1})\d{4})\s*)/) && value.match(/^[\d|\s]*$/)) );
            }, "Invalid land phone number");
            jQuery.validator.addMethod("national_insurance", function(value, element) {
                value = value.toUpperCase();
                return this.optional(element) || (value.match(/^[A-Za-z]{2}\d{6}[A-Za-z]{1}$/));
            }, "Invalid national insurance");
            
            
/*            
            jQuery.validator.addMethod("phone", function(value, element) {
                value = value.replace(/\s/,"");
                return this.optional(element) || (value.match(/(\s*\(?0\d{4}\)?(\s*|-)\d{3}(\s*|-)\d{3}\s*)|(\s*\(?0\d{3}\)?(\s*|-)\d{3}(\s*|-)\d{4}\s*)|(\s*(7|8)(\d{7}|\d{3}(\-|\s{1})\d{4})\s*)/) || value.match(/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/));
            }, "Invalid phone number");
*/
            
            // end of new rules
        }    
            
        
        // application form only: submit to customer lead system
        jQuery('#submitToCLS').bind(
            'click',
            function() {
                
                if (enableClientSideValidation) {
                    //if ( $("form[id='customer']").valid() || $("form[id='address']").valid() || $("form[id='application']").valid() )
                    if ( $("form[id='application']").valid() ) {
                      "$.blockUI( { message: $('#domMessage'), css: { border: 'none', padding: '25px', backgroundColor: '#fff', color: '#006699', opacity: .75, fontWeight:'bold', fontSize:'1.1em' }, onBlock: function() { startCountDown(45, 1000, myFunction()); } } )";
                    }
                }
                else {
                    // block after 1.5 seconds, ToDo: this is a bit of a hack, but works fine for now.
                    // Once client side validation is added, then remove the 1.5 second pause.
                    // See the commented out code beneath to see how I expect it to work with partial client validation in play.

                    if ( $("#application").valid() ) {
                        setTimeout(
                          "$.blockUI( { message: $('#domMessage'), css: { border: 'none', padding: '25px', backgroundColor: '#fff', color: '#006699', opacity: .75, fontWeight:'bold', fontSize:'1.1em' }, onBlock: function() { startCountDown(45, 1000, myFunction()); } } )",
                        1500 );
                    }
                }
                
            }
        );
    }
);

function myFunction() {
    //alert("hi andrew");
}
       
        
function startCountDown(i, p, f) {
    // store parameters
    var pause = p;
    var fn = f;
    
    // i denotes countdown from in seconds
    
    var countDownObj = document.getElementById("countDown");
    var pleaseWaitObj = document.getElementById("pleaseWait");
    if (countDownObj == null) {
        alert("div not found, check your id");
    return;
    }
    
    countDownObj.count = function(i) {
        // write out count
        countDownObj.innerHTML = i;
        if (i == 0) {
            countDownObj.innerHTML = "\nUnfortunately, due to the high demand for our products and services, the system is running slower than usual.  Please bear with us, and you will received a response soon.";
            pleaseWaitObj.innerHTML = "";
            // execute function
            //fn();
            // stop
            return;
        }

        setTimeout(function() {
            // repeat
            countDownObj.count(i - 1);
        }, pause );
    }
    
    // set it going
    countDownObj.count(i);
}

