function refreshMainForm() {
	showLoading();
	tapestry.form.refresh("uploadDocsForm");
}

function loadCustomerUploadJavaScript() {
	'use strict';
	
	//$("#errorSection .required").hide();

    var emailTest = new RegExp(/^[_A-Za-z0-9\-]+(\.[_A-Za-z0-9\-]+)*@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)*(\.[A-Za-z]{2,})$/), 
    	textTest = new RegExp(/^[-a-zA-ZäöüßÄÖÜéëïóÉËÏÓáíñúÁÍÑÚùûÿàâæçèêîôœÙÛŸÀÂÆÇÈÊÎÔŒ' ]+$/),
    	alphanumericTextTest = new RegExp(/^[-a-zA-ZäöüßÄÖÜéëïóÉËÏÓáíñúÁÍÑÚùûÿàâæçèêîôœÙÛŸÀÂÆÇÈÊÎÔŒ'0-9 ]+$/),
    	phoneTest = new RegExp(/^[\+]?[0-9 ]+$/),
    	hasFeedback,
    	generalFormField,
    	formField,
    	formFieldOnly,
    	body = $('body'),
    	thisWindow = $(window);
    
    //Individual field validations
    $('.has-feedback').each(function () {
        generalFormField = $(this).find('div').children();

        generalFormField.click(function () {
        	hasFeedback = $(this).closest('.has-feedback');
        	
            if (hasFeedback.hasClass('has-error')) {
            	$(this).find('.error-popover').first().show();
            }
        });
       
        generalFormField.focus(function () {
            hasFeedback = $(this).closest('.has-feedback');
        });
    });
    
    hasFeedback = $(this).closest('.has-feedback');
    
    $('#quoteReference').blur(function () {
    	if ($(this).val() === '') {
    		$('#quoteReference-error').hide();
    		$('#quoteReference-tick').hide();    
    	}
    	else if (!$(this).val().match(alphanumericTextTest)) {
    		hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#quoteReference-error').show();
            $('#quoteReference-tick').hide();              
        } 
    	else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#quoteReference-error').hide();
            $('#quoteReference-tick').show();              
        }
    });
    
	$('#policyHolderFirstName').blur(function () {
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#policyHolderFirstName-error-2').hide();
            $('#policyHolderFirstName-error-1').show();
            $('#policyHolderFirstName-tick').hide();
        } else if (!$(this).val().match(textTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#policyHolderFirstName-error-1').hide();
            $('#policyHolderFirstName-error-2').show();
            $('#policyHolderFirstName-tick').hide();            
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#policyHolderFirstName-error-1').hide();
            $('#policyHolderFirstName-error-2').hide();
            $('#policyHolderFirstName-tick').show();
              
        }
    });
	
	$('#policyHolderLastName').blur(function () {
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#policyHolderLastName-error-2').hide();
            $('#policyHolderLastName-error-1').show();
            $('#policyHolderLastName-tick').hide();
        } else if (!$(this).val().match(textTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#policyHolderLastName-error-1').hide();
            $('#policyHolderLastName-error-2').show();
            $('#policyHolderLastName-tick').hide();            
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#policyHolderLastName-error-1').hide();
            $('#policyHolderLastName-error-2').hide();
            $('#policyHolderLastName-tick').show();
              
        }
    });
	
	$('#emailAddress').blur(function () {
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#emailAddress-error-2').hide();
            $('#emailAddress-error-1').show();
            $('#emailAddress-tick').hide();
        } else if (!$(this).val().match(emailTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#emailAddress-error-1').hide();
            $('#emailAddress-error-2').show();
            $('#emailAddress-tick').hide();            
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#emailAddress-error-1').hide();
            $('#emailAddress-error-2').hide();
            $('#emailAddress-tick').show();
              
        }
    });
	
	$('#telephoneNumber').blur(function () {
		var trimmedTelephoneNumber = $('#telephoneNumber').val().replaceAll(" ", "").replaceAll("+", "");
	
		if ($(this).val() === '') {
			hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#telephoneNumber-error-2').hide();
            $('#telephoneNumber-error-1').show();
            $('#telephoneNumber-tick').hide();
        }
		else if (trimmedTelephoneNumber.length < 5 || !$(this).val().match(phoneTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#telephoneNumber-error-1').hide();
            $('#telephoneNumber-error-2').show();
            $('#telephoneNumber-tick').hide();
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#telephoneNumber-error-1').hide();
            $('#telephoneNumber-error-2').hide();
            $('#telephoneNumber-tick').show();
              
        }
    });
	
	var exists = {};
	$('#errorSection .required').each(function() {
		var content = $(this).text();
		//$('#dialog').dialog();
    	//$('#dialog').text($(this).attr('id'));
		
		if (exists[content]) {
			$(this).remove();
		} else {
			exists[content] = true;
		}
	});
	
	
	
	//Full form validation
    $('#uploadDocsForm').submit(function (e) {
		
    	
        $('.has-feedback').each(function () {
            formField = $(this).find('div').children().val();
            formFieldOnly = $(this).find('div').children();
                        
            if ($(this).hasClass('has-success') 
            		|| ((formField !== '' && formField !== null)
            				|| (formFieldOnly.attr('id') === 'uploadTextBox' && formField === '')
            				|| (formFieldOnly.attr('id') === 'uploadField' && formField === '')
            				|| (formFieldOnly.attr('id') === 'quoteReference' && formField === ''))) {
                // Default behaviour
            } else {
                $(this).addClass('has-error');
                $(this).children('span.glyphicon-ok').hide();
                
                    $(this).find('.error-popover').first().show();
                
                e.preventDefault();
            }
            });
    });
    
    //Set tooltip placement depending on current device width
    function wheretoplace() {
        if (thisWindow.width() < 753) {
            return 'bottom';
        }
        return 'right';
    }
    
    //Enable Boostrap popover
    body.popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'focus'
    });

    $('.whyDetails').popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'manual'
    });

    $('.whyDetails').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.whyDetails').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.whyDetails').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });

    body.click(function () {
        $('.whyDetails').popover('hide');
    });
	
}

function loadBrokerUploadJavaScript() {
	'use strict';
	
	//$("#errorSection .required").hide();

    var emailTest = new RegExp(/^[_A-Za-z0-9\-]+(\.[_A-Za-z0-9\-]+)*@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)*(\.[A-Za-z]{2,})$/), 
    	textTest = new RegExp(/^[-a-zA-ZäöüßÄÖÜéëïóÉËÏÓáíñúÁÍÑÚùûÿàâæçèêîôœÙÛŸÀÂÆÇÈÊÎÔŒ' ]+$/),
    	alphanumericTextTest = new RegExp(/^[-a-zA-ZäöüßÄÖÜéëïóÉËÏÓáíñúÁÍÑÚùûÿàâæçèêîôœÙÛŸÀÂÆÇÈÊÎÔŒ'0-9 ]+$/),
    	phoneTest = new RegExp(/^[\+]?[0-9 ]+$/),
    	hasFeedback,
    	generalFormField,
    	formField,
    	formFieldOnly,
    	body = $('body'),
    	thisWindow = $(window);
    
    //Individual field validations
    $('.has-feedback').each(function () {
        generalFormField = $(this).find('div').children();

        generalFormField.click(function () {
        	hasFeedback = $(this).closest('.has-feedback');
        	
            if (hasFeedback.hasClass('has-error')) {
            	$(this).find('.error-popover').first().show();
            }
        });
       
        generalFormField.focus(function () {
            hasFeedback = $(this).closest('.has-feedback');
        });
    });
    
    hasFeedback = $(this).closest('.has-feedback');
    
    $('#quoteReference').blur(function () {
    	if ($(this).val() === '') {
    		$('#quoteReference-error').hide();
    		$('#quoteReference-tick').hide();    
    	}
    	else if (!$(this).val().match(alphanumericTextTest)) {
    		hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#quoteReference-error').show();
            $('#quoteReference-tick').hide();              
        } 
    	else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#quoteReference-error').hide();
            $('#quoteReference-tick').show();              
        }
    });

    $('#documentTypeDiv').click(function () {
                   $('#documentType-error').hide();
                   $('#documentType-tick').hide();
                   hasFeedback.removeClass('has-success');
                   hasFeedback.removeClass('has-error');

                   if (!validateDocumentTypeDiv("documentTypeDiv")){
                       $('#documentType-error').show();
                       hasFeedback.addClass('has-error');
                   } else {
                       $('#documentType-tick').show();
                       hasFeedback.addClass('has-success');
                   }
    });

	$('#brokerConsultantName').blur(function () {
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#brokerConsultantName-error-2').hide();
            $('#brokerConsultantName-error-1').show();
            $('#brokerConsultantName-tick').hide();
        } else if (!$(this).val().match(textTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#brokerConsultantName-error-1').hide();
            $('#brokerConsultantName-error-2').show();
            $('#brokerConsultantName-tick').hide();            
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#brokerConsultantName-error-1').hide();
            $('#brokerConsultantName-error-2').hide();
            $('#brokerConsultantName-tick').show();
              
        }
    });
	
	$('#brokerEmailAddress').blur(function () {
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#brokerEmailAddress-error-2').hide();
            $('#brokerEmailAddress-error-1').show();
            $('#brokerEmailAddress-tick').hide();
        } else if (!$(this).val().match(emailTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#brokerEmailAddress-error-1').hide();
            $('#brokerEmailAddress-error-2').show();
            $('#brokerEmailAddress-tick').hide();            
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#brokerEmailAddress-error-1').hide();
            $('#brokerEmailAddress-error-2').hide();
            $('#brokerEmailAddress-tick').show();
              
        }
    });
	
	$('#customerName').blur(function () {
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#customerName-error-2').hide();
            $('#customerName-error-1').show();
            $('#customerName-tick').hide();
        } else if (!$(this).val().match(textTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#customerName-error-1').hide();
            $('#customerName-error-2').show();
            $('#customerName-tick').hide();
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#customerName-error-1').hide();
            $('#customerName-error-2').hide();
            $('#customerName-tick').show();
              
        }
    });
	
	$('#brokerTelephoneNumber').blur(function () {
		var trimmedBrokerTelephoneNumber = $('#brokerTelephoneNumber').val().replaceAll(" ", "").replaceAll("+", "");
		
		if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
			$('#brokerTelephoneNumber-error').show();
            $('#brokerTelephoneNumber-tick').hide();
        }
		else if (trimmedBrokerTelephoneNumber.length < 5 || !$(this).val().match(phoneTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            $('#brokerTelephoneNumber-error').show();
            $('#brokerTelephoneNumber-tick').hide();
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            $('#brokerTelephoneNumber-error').hide();
            $('#brokerTelephoneNumber-tick').show();
              
        }
    });
	
	var exists = {};
	$('#errorSection .required').each(function() {
		var content = $(this).text();
		//$('#dialog').dialog();
    	//$('#dialog').text($(this).attr('id'));
		
		if (exists[content]) {
			$(this).remove();
		} else {
			exists[content] = true;
		}
	});
	
	
	
	//Full form validation
    $('#uploadDocsForm').submit(function (e) {
		
    	
        $('.has-feedback').each(function () {
            formField = $(this).find('div').children().val();
            formFieldOnly = $(this).find('div').children();
                        
            if ($(this).hasClass('has-success') 
            		|| ((formField !== '' && formField !== null)
            				|| (formFieldOnly.attr('id') === 'brokerTelephoneNumber' && formField === '')
            				|| (formFieldOnly.attr('id') === 'uploadTextBox' && formField === '')
            				|| (formFieldOnly.attr('id') === 'uploadField' && formField === '')
            				|| (formFieldOnly.attr('id') === 'quoteReference' && formField === ''))
            				|| (formFieldOnly.attr('id') === 'documentTypeDiv' && validateDocumentTypeDiv(formFieldOnly.attr('id')))){
                // Default behaviour
            } else {
                $(this).addClass('has-error');
                $(this).children('span.glyphicon-ok').hide();
                
                    $(this).find('.error-popover').first().show();
                
                e.preventDefault();
            }
            });
    });

    function validateDocumentTypeDiv(elementId){
    	const selectedDocumentTypes = document.getElementById(elementId).querySelectorAll('input[type="checkbox"]:checked');

        return selectedDocumentTypes.length > 0;
    }

    //Set tooltip placement depending on current device width
    function wheretoplace() {
        if (thisWindow.width() < 753) {
            return 'bottom';
        }
        return 'right';
    }
    
    //Enable Boostrap popover
    body.popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'focus'
    });

    $('.whyDetails').popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'manual'
    });

    $('.whyDetails').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.whyDetails').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.whyDetails').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });

    body.click(function () {
        $('.whyDetails').popover('hide');
    });
	
}

function loadlBootstrap() {

    'use strict';

    var mainMemberEmailTest = new RegExp(/^[_A-Za-z0-9\-]+(\.[_A-Za-z0-9\-]+)*@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)*(\.[A-Za-z]{2,})$/),
        textTest = new RegExp(/^[a-zA-Z ]*$/),
        phoneTest = new RegExp(/^\d{5,}$/),
        hasFeedback,
        generalFormField,
        formField,
        formFieldWithoutValue,
        phoneCode,
        phoneNumber,
        body = $('body'),
        thisWindow = $(window),
        day,
        month,
        monthAsString,
        mainMemberCountry,
        mainMemberGen,
        depGen,
        year;

    //Set tooltip placement depending on current device width
    function wheretoplace() {
        if (thisWindow.width() < 753) {
            return 'bottom';
        }
        return 'right';
    }

    //Enable Boostrap popover
    body.popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'focus'
    });

    $('.whyDetails').popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'manual'
    });

    $('.whyDetails').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.whyDetails').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.whyDetails').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });

    body.click(function () {
        $('.whyDetails').popover('hide');
        $('.living').popover('hide');
        $('.nationality').popover('hide');
        $('.dependantLastName').popover('hide');
        $('.dependantLiving').popover('hide'); 
        $('.dependantNationality').popover('hide');
    });
    
    
    $('.living').popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'manual'
    });

    $('.living').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.living').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.living').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });
    
    
    $('.nationality').popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'manual'
    });

    $('.nationality').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.nationality').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.nationality').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });
    
     $('#phone-number').popover({
        selector: '[data-toggle="popover"]',
        placement: wheretoplace,
        trigger: 'focus'
    });

    //Individual field validations
    $('.has-feedback').each(function () {
        generalFormField = $(this).find('div').children();

        generalFormField.click(function () {
            hasFeedback = $(this).closest('.has-feedback');

            if ($(this).attr('id') === 'phone-code') {
                if (hasFeedback.hasClass('has-error')) {
                    $('#phone-number').popover('hide');
                } else {
                    $('#phone-number').popover('show');
                }
            }

        });

        generalFormField.focus(function () {
            hasFeedback = $(this).closest('.has-feedback');
        });
    });

           
    	hasFeedback = $(this).closest('.has-feedback');

    	$('#mainMemberFirstName').blur(function () {
            if ($(this).val() === '') {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#mainMemberFirstName-error').show();
                $('#mainMemberFirstName-tick').hide();
                $('#mainMemberFirstName-error').text('Please enter your first name.');
            } else if (!$(this).val().match(textTest)) {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#mainMemberFirstName-error').show();
                $('#mainMemberFirstName-tick').hide();
                $('#mainMemberFirstName-error').text('Please use alphabetical characters only for first name.');
            } else {
                hasFeedback.addClass('has-success');
                hasFeedback.removeClass('has-error');
                $('#mainMemberFirstName-error').hide();
                $('#mainMemberFirstName-tick').show();
                  
            }
        });


        $('#mainMemberFamilyName').blur(function () {
            if ($(this).val() === '') {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#mainMemberFamilyName-error').show();
                $('#mainMemberFamilyName-tick').hide();
                $('#mainMemberFamilyName-error').text('Please enter your last name.');
            } else if (!$(this).val().match(textTest)) {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#mainMemberFamilyName-error').show();
                $('#mainMemberFamilyName-tick').hide();
                $('#mainMemberFamilyName-error').text('Please use alphabetical characters only for last name.');
            } else {
                hasFeedback.addClass('has-success');
                hasFeedback.removeClass('has-error');
                $('#mainMemberFamilyName-error').hide();
                $('#mainMemberFamilyName-tick').show();
            }
        });

        $('#mainMemberEmail').blur(function () {
            if ($(this).val() === '') {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#mainMemberEmail-error').show();
                $('#mainMemberEmail-tick').hide();
                $('#mainMemberEmail-error').text('Please enter your email address.');
            } else if (!$(this).val().match(mainMemberEmailTest)) {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#mainMemberEmail-error').show();
                $('#mainMemberEmail-tick').hide();
                $('#mainMemberEmail-error').text('Your email address is incorrect - please double check.');
            } else {
                hasFeedback.addClass('has-success');
                hasFeedback.removeClass('has-error');
                $('#mainMemberEmail-error').hide();
                $('#mainMemberEmail-tick').show();
            }
        });

        $('#phone-number').blur(function () {
            if ($(this).val() === '' || $('#phone-code').val() === '') {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#phone-error').show();
                $('#phone-tick').hide();
                $('#phone-error').text('We need your telephone number so that we can contact you if we have any questions about your quote.');
            } else if (!$(this).val().match(phoneTest)) {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#phone-error').show();
                $('#phone-tick').hide();
                $('#phone-error').text('Please insert a valid home phone number (5 digits minimum).');
            } else {
                hasFeedback.addClass('has-success');
                hasFeedback.removeClass('has-error');
                $('#phone-error').hide();
                $('#phone-tick').show();
            }
        });
        
        $('#selectedDay').blur(function () {
            
        	if ($(this).val() != '' && $('#selectedMonth').val() != '' && $('#selectedYear').val() != '') {                
        		$('#mainMemberSelectedPicker').val($('#selectedDay').find('option:selected').text() + '/'+ $('#selectedMonth').find('option:selected').text() + '/'+ $('#selectedYear').find('option:selected').text());            
            }
        });

        $('#selectedMonth').blur(function () {
            
        	if ($('#selectedDay').val() != '' && $(this).val() != '' && $('#selectedYear').val() != '') {                
        		$('#mainMemberSelectedPicker').val($('#selectedDay').find('option:selected').text() + '/'+ $('#selectedMonth').find('option:selected').text() + '/'+ $('#selectedYear').find('option:selected').text());
            }
        	
        });       

        $('#selectedYear').blur(function () {
            if ($('#selectedDay').val() === '' || $('#selectedMonth').val() === '' || $(this).val() === '') {
                hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                $('#dob-error').show();
                $('#dob-tick').hide();
                $('#dob-error').text('Please enter date of birth as dd/mmm/yyyy.');
            } else {            	
            	
            	day = $('#selectedDay').find('option:selected').text();
            	monthAsString = $('#selectedMonth').find('option:selected').text();
            	month = $('#selectedMonth').val();
            	year = $('#selectedYear').find('option:selected').text();
            	    	
            	            	
            	var dateOfBirthAsString = day + " " + monthAsString + " " + year;  
            	           	           	
				var dob = new Date(dateOfBirthAsString);				
				
				var age = getAge(dob);					
										    
				if (!isValidDate(day, month, year)) {
					
					hasFeedback.addClass('has-error');
	                hasFeedback.removeClass('has-success');
	                $('#dob-error').show();
	                $('#dob-tick').hide();
	                $('#dob-error').text('Your date of birth is not a valid date.');
					
				}  else if (age > 100) {					
							
					hasFeedback.addClass('has-error');
	                hasFeedback.removeClass('has-success');
	                $('#dob-error').show();
	                $('#dob-tick').hide();
	                $('#dob-error').text('Main member’s date of birth must be on or after ' + getDateOfBirthToCheck(100));
					
				} else if (age < 18) {					
					
					hasFeedback.addClass('has-error');
	                hasFeedback.removeClass('has-success');
	                $('#dob-error').show();
	                $('#dob-tick').hide();
	                $('#dob-error').text('Main member’s date of birth must be on or before ' + getDateOfBirthToCheck(18));
					
				} else {
             	
	            	hasFeedback.addClass('has-success');
	                hasFeedback.removeClass('has-error');
	                $('#dob-error').hide();
	                $('#dob-tick').show();	                
	                $('#mainMemberSelectedPicker').val($('#selectedDay').find('option:selected').text() + '/'+ $('#selectedMonth').find('option:selected').text() + '/'+ $('#selectedYear').find('option:selected').text());
                
				}
            }
        });

        $('#mainMemberNationality').blur(function () {        	
        	
            if ($(this).val() === null || $(this).val() === '') {
                $('#mainMemberNationality-error').show();
                hasFeedback.addClass('has-error');                
                $('#mainMemberNationality-error').text('Please enter your nationality.');
            } else {              	
                hasFeedback.removeClass('has-error');
                $('#mainMemberNationality-error').hide();                
            }
        });

        $('#mainMemberCountry').blur(function () {
            if ($(this).val() === null || $(this).val() === '') {
                $('#mainMemberCountry-error').show();
                hasFeedback.addClass('has-error');                
                $('#mainMemberNationality-error').text('Please enter where you will be living.');
            } else {             	
                hasFeedback.removeClass('has-error');    
               
                var errorSpan = $(this).closest('span');                
                errorSpan.removeClass('errorTextbox');
                $('#mainMemberCountry-error').hide();
                hasFeedback.addClass('has-success');
            }
        });
        
        $('#mainMemberCurrentlyUS').blur(function () {
            if ($(this).val() === null || $(this).val() === '') {
                $('#mainMemberCurrentlyUS-error').show();
                hasFeedback.addClass('has-error');                
                $('#mainMemberCurrentlyUS-error').text('Please enter if you are currently in the United States.');
            } else {             	
                hasFeedback.removeClass('has-error');    
                $('#mainMemberCurrentlyUS-error').hide();
            }
        });
        
        $('#mainMemberSelectedState').blur(function () {
            if ($(this).val() === null || $(this).val() === '') {
                $('#mainMemberSelectedState-error').show();
                hasFeedback.addClass('has-error');                
                $('#mainMemberSelectedState-error').text('Please enter state.');
            } else {             	
                hasFeedback.removeClass('has-error');    
                $('#mainMemberSelectedState-error').hide();
            }
        });

//        $('#product').blur(function () { //currency drop down
//            if ($(this).val() === null || $(this).val() === '') {
//                hasFeedback.addClass('has-error');
//                hasFeedback.removeClass('has-success');
//                $('#currency-error').show();
//                $('#currency-tick').hide();
//            } else {
//                hasFeedback.addClass('has-success');
//                hasFeedback.removeClass('has-error');
//                $('#currency-error').hide();
//                $('#currency-tick').show();
//            }
//        });       
           

    //Full form validation
    $('#quoteForm').submit(function (e) {     	
    	
        $('.has-feedback').each(function () {
            formField = $(this).find('div').children().val();
            formFieldWithoutValue = $(this).find('div').children();
            phoneCode = $('#phone-code').val();
            phoneNumber = $('#phone-number').val();
            day = $('#selectedDay').val();
            month = $('#selectedMonth').val();
            year = $('#selectedYear').val();   
            mainMemberCountry = $('#mainMemberCountry').val(); 
            mainMemberGen = $('input[name ="mainMemberGender"]');
            depGen = $('input[name ="dependantGender"]');
                        
            if (formFieldWithoutValue.attr('class') === 'option') {
                if ($(this).hasClass('has-success') || (formField !== '' && formField !== null && phoneCode !== '' && phoneNumber !== '' && phoneNumber !== null && day !=='' && month !== '' && year !== '' && mainMemberCountry !== null && mainMemberCountry !== '')) {
                    //Default behaviour
                } else {
                    $(this).addClass('has-error');
                    $(this).children('span.glyphicon-ok').hide();
                    
                        $(this).find('.error-popover').show();
                    
                    e.preventDefault();
                }
            } else {
                if ($(this).hasClass('has-success') || (formField !== '' && formField !== null && phoneCode !== '' && phoneNumber !== '' && phoneNumber !== null && day !=='' && month !== '' && year !== '')) {
                    //Default behaviour
                } else if ($(this).hasClass('gen-radio') && mainMemberGen.length>0 && mainMemberGen.is(':checked')) {
                	var hasgenfeedback = $(this).closest('.has-feedback');
                	hasgenfeedback.removeClass('has-error');    
                    $('#mainMemberGender-error').hide();
                    hasgenfeedback.addClass('has-success');
                } else if ($(this).hasClass('depgen-radio') && depGen.length>0 && depGen.is(':checked')) {
                	var hasdepgenfeedback = $(this).closest('.has-feedback');
                	hasdepgenfeedback.removeClass('has-error');    
                    $('#dependantGender-error').hide();
                    hasdepgenfeedback.addClass('has-success');
                }
                  else{
                    $(this).addClass('has-error');
                    $(this).children('span.glyphicon-ok').hide();
                   
                        $(this).find('.error-popover').show();
                    
                    e.preventDefault();
                }
            }
        });
    });   
    
    
    if (location.protocol === 'https:') {    	
    	$('#nortonSecurity').show();	
    }
   
    
}


function updateDependantDetails(){
	 
       
    var textTest = new RegExp(/^[a-zA-Z ]*$/),    
    hasFeedback,    
    day,
    month,
    year;       
 

    $('.dependantLastName').popover({
        selector: '[data-toggle="popover"]',
        placement: 'right',
        trigger: 'manual'
    });

    $('.dependantLastName').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.dependantLastName').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.dependantLastName').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });
    
    $('.dependantLiving').popover({
        selector: '[data-toggle="popover"]',
        placement: 'right',
        trigger: 'manual'
    });

    $('.dependantLiving').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.dependantLiving').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.dependantLiving').mouseout(function () {
        $(this).css('text-decoration', 'none');
    }); 
    
    $('.dependantNationality').popover({
        selector: '[data-toggle="popover"]',
        placement: 'right',
        trigger: 'manual'
    });

    $('.dependantNationality').click(function () {
        $(this).popover('toggle');
        return false;
    });

    $('.dependantNationality').mouseenter(function () {
        $(this).css('text-decoration', 'underline');
    });

    $('.dependantNationality').mouseout(function () {
        $(this).css('text-decoration', 'none');
    });
   
     
    $("input[name^='dependantFirstName']").blur(function () {    	
    	
    	 hasFeedback = $(this).closest('.has-feedback');
    	
        if ($(this).val() === '') {        	
        	           	
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            hasFeedback.find('.error-popover').show();
            hasFeedback.find('.glyphicon-ok').hide();
            hasFeedback.find('.error-popover').text('Please enter the first name for dependant.');             

        } else if (!$(this).val().match(textTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            hasFeedback.find('.error-popover').show();
            hasFeedback.find('.glyphicon-ok').hide();
            hasFeedback.find('.error-popover').text('Please use alphabetical characters only for dependant.');
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            hasFeedback.find('.error-popover').hide();
            hasFeedback.find('.glyphicon-ok').show();
        }
    });
    
    
    $("input[name^='dependantFamilyName']").blur(function () {
    	
    	 hasFeedback = $(this).closest('.has-feedback');
    	
        if ($(this).val() === '') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            hasFeedback.find('.error-popover').show();
            hasFeedback.find('.glyphicon-ok').hide();
            hasFeedback.find('.error-popover').text('Please enter the last name for dependant.');
        } else if (!$(this).val().match(textTest)) {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            hasFeedback.find('.error-popover').show();
            hasFeedback.find('.glyphicon-ok').hide();
            hasFeedback.find('.error-popover').text('Please use alphabetical characters only for dependant.');
        } else {
            hasFeedback.addClass('has-success');
            hasFeedback.removeClass('has-error');
            hasFeedback.find('.error-popover').hide();
            hasFeedback.find('.glyphicon-ok').show();
        }
    });
    
    
	    $('.dependantsSelectedDay').blur(function () {	   
	 	   
		       hasFeedback = $(this).closest('.has-feedback');
		     
		        day = $('option:selected', $(this)).text();
		    	month = hasFeedback.find('select[name*="selectedMonth"]').find(":selected").text();
		    	year = hasFeedback.find('select[name*="selectedYear"]').find(":selected").text();		    	
		    	
		   
		    	if (day != 'DD' && month != 'MMM' && year != 'YYYY') {
					
		    		hasFeedback.find('input[name*="dependantSelectedPicker"]')
							.val(day + '/' + month + '/' + year);	
					
				}    
	     
	  });

	  $('.dependantsSelectedMonth').blur(function() {

				hasFeedback = $(this).closest('.has-feedback');

				day = hasFeedback.find('select[name*="selectedDay"]').find(
						":selected").text();
				month = $('option:selected', $(this)).text();
				year = hasFeedback.find('select[name*="selectedYear"]').find(
						":selected").text();

				if (day != 'DD' && month != 'MMM' && year != 'YYYY') {
					
					hasFeedback.find('input[name*="dependantSelectedPicker"]')
							.val(day + '/' + month + '/' + year);				
				}
		});    
     
  

	   $('.dependantsSelectedYear').blur(function () {
    	
    	hasFeedback = $(this).closest('.has-feedback');    	
    	
    	day = hasFeedback.find('select[name*="selectedDay"]').find(":selected").text();
    	var monthAsString = hasFeedback.find('select[name*="selectedMonth"]').find(":selected").text();
    	month = hasFeedback.find('select[name*="selectedMonth"]').val();
    	year = $('option:selected', $(this)).text();
    	    	
    	hasFeedback = $(this).closest('.has-feedback');
    	
        if (day === 'DD' || month === 'MMM' || year === 'YYYY') {
            hasFeedback.addClass('has-error');
            hasFeedback.removeClass('has-success');
            hasFeedback.find('.glyphicon-ok').hide();
            hasFeedback.find('.error-popover').show();
            hasFeedback.find('.error-popover').text('Please enter the date of birth for dependant.');
        } else {        	
        
        	var dateAsString = day + " " + monthAsString + " " + year;  
        	           	           	
			var customerDate = new Date(dateAsString);
			
			var age = getAge(customerDate);					
									    
			if (!isValidDate(day, month, year)) {
				
				hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                hasFeedback.find('.glyphicon-ok').hide();
                hasFeedback.find('.error-popover').show();
                hasFeedback.find('.error-popover').text('Date of birth for dependant is not a valid date.');
				
			}  else if (age > 100) {				
				hasFeedback.addClass('has-error');
                hasFeedback.removeClass('has-success');
                hasFeedback.find('.glyphicon-ok').hide();
                hasFeedback.find('.error-popover').show();
                hasFeedback.find('.error-popover').text('Date of birth of dependant must be on or after ' + getDateOfBirthToCheck(100));
               				
			} else {    	
	        	
	            hasFeedback.addClass('has-success');
	            hasFeedback.removeClass('has-error');
	            hasFeedback.find('.error-popover').hide();
	            hasFeedback.find('.glyphicon-ok').show();     
	            
	            hasFeedback.find('input[name*="dependantSelectedPicker"]').val(day + '/'+ monthAsString+ '/'+ year);
	           
	            
		   }     
        }
    });

    $('select[name*="dependantNationality"]').blur(function () {
    	
    	hasFeedback = $(this).closest('.has-feedback');
    	
        if ($(this).val() === null || $(this).val() === '') {
        	hasFeedback.find('.error-popover').show();
            hasFeedback.addClass('has-error');            
            hasFeedback.find('.error-popover').text('Please enter the nationality of this dependant.');
        } else {         	
            hasFeedback.removeClass('has-error');
            hasFeedback.find('.error-popover').hide();                
        }
    });
    
    $('select[name*="dependantRelationship"]').blur(function () {
    	
    	hasFeedback = $(this).closest('.has-feedback');
    	
        if ($(this).val() === null || $(this).val() === '') {
        	hasFeedback.find('.error-popover').show();
            hasFeedback.addClass('has-error');            
            hasFeedback.find('.error-popover').text('Please enter the relationship to policy holder.');
        } else {         	
            hasFeedback.removeClass('has-error');
            hasFeedback.find('.error-popover').hide();                
        }
    });
    
 $("input[name^='dependantGender']").change(function () {
    	
    	hasFeedback = $(this).closest('.has-feedback');
    	       	
            hasFeedback.removeClass('has-error');
            hasFeedback.find('.error-popover').hide(); 
            hasFeedback.addClass('has-success');
    });

    $('.removeDependant').click(function () {    
    	
    	var dependantsCountValue = parseInt($('#dependantsCount').val()) - 1;   	

    	if (dependantsCountValue <= 8) {    		
    		$('#addPerson').show();		
    	} 	
    	
    	$('#dependantsCount').val(dependantsCountValue);
    	
    });
    
    updateDependantDateDetails();
   
}


function updateDependantsCount() {	
	var dependantsCount = parseInt($('#dependantsCount').val()) + 1;
	
	if (dependantsCount > 8) {
		$('#addPerson').hide();
	} else {
		$('#addPerson').show();		
	}
	
	$('#dependantsCount').val(dependantsCount);
}


function isValidDate(dayValue, monthValue, yearValue) {
	var day = parseInt(dayValue);
	var month = parseInt(monthValue) + 1;
	var year = parseInt(yearValue);
	if (isNaN(day) || isNaN(month) || isNaN(year)) {
		return false;
	}
	if (day < 1 || year < 1)
		return false;
	if (month > 12 || month < 1)
		return false;
	if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8
			|| month == 10 || month == 12)
			&& day > 31)
		return false;
	if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30)
		return false;
	if (month == 2) {
		if (((year % 4) == 0 && (year % 100) != 0)
				|| ((year % 400) == 0 && (year % 100) == 0)) {
			if (day > 29)
				return false;
		} else {
			if (day > 28)
				return false;
		}
	}
	return true;

}


function getAge(dob) {
	var ageMS = Date.parse(Date()) - Date.parse(dob);
	var age = new Date();
	age.setTime(ageMS);
	var ageYear = age.getFullYear() - 1970;
	return ageYear;

};


function updateDependantDateDetails() {
	
	var hasFeedback;	
	var dependantsValue;
	var parts;
	var daySelect;
	var monthSelect;
	var yearSelect;
	
		$("input[name^='dependantSelectedPicker']").each(
			function() {

				hasFeedback = $(this).closest('.has-feedback');				
				
				dependantsValue = hasFeedback.find('input[name*="dependantSelectedPicker"]').val();
				
				if (dependantsValue === "") {

					hasFeedback.find('select[name*="selectedDay"]').val("");
					hasFeedback.find('select[name*="selectedMonth"]').val("");
					hasFeedback.find('select[name*="selectedYear"]').val("");
				
				} else {

					parts = dependantsValue.split('/');
					daySelect = parseInt(parts[0]) - 1;
					monthSelect = parts[1];
					yearSelect = parseInt(parts[2]);					

					hasFeedback.find('select[name*="selectedDay"]').val(daySelect);
					
					
					hasFeedback.find('select[name*="selectedMonth"] option').each(function(){						
			             if ($(this).text() ==  monthSelect) {
			                  option = this;
			                  option.selected = true;
			                  return false;    
			              }
			        }); 					
									
					
					hasFeedback.find('select[name*="selectedYear"] option').each(function(){						
			             if ($(this).text() ==  yearSelect) {
			                  option = this;
			                  option.selected = true;
			                  return false;    
			              }
			        });  

				}		
		
		
	});
	

}

function getDateOfBirthToCheck(yearsToDeduct) {

	var policyStartDate = new Date();
	policyStartDate.setDate(policyStartDate.getDate() + 1);

	var minYear = parseInt(policyStartDate.getFullYear()) - yearsToDeduct;

	var dd = policyStartDate.getDate();
	var mm = policyStartDate.getMonth() + 1; //January is 0!

	if (dd < 10) {
		dd = '0' + dd;
	}

	if (mm < 10) {
		mm = '0' + mm;
	}	

	var dateOfBirth = dd + "/" + mm + "/" + minYear;

	return dateOfBirth;

}

function clearDateOfBirthSelection() {	
	updateMainMemberDateDetails();
	if ($('input[name*="mainMemberSelectedPicker"]').val() == "") {
		
		$('#selectedDay').val("");
		$('#selectedMonth').val("");
		$('#selectedYear').val("");
		
	}

function updateMainMemberDateDetails() {
		
		var hasFeedback;	
		var mainMemberValue;
		var parts;
		var daySelect;
		var monthSelect;
		var yearSelect;
		
			$("input[name^='mainMemberSelectedPicker']").each(
				function() {

					hasFeedback = $(this).closest('.has-feedback');				
					
					mainMemberValue = hasFeedback.find('input[name*="mainMemberSelectedPicker"]').val();
					
					if (mainMemberValue === "") {

						hasFeedback.find('select[name*="selectedDay"]').val("");
						hasFeedback.find('select[name*="selectedMonth"]').val("");
						hasFeedback.find('select[name*="selectedYear"]').val("");
					
					} else {

						parts = mainMemberValue.split('/');
						daySelect = parseInt(parts[0]) - 1;
						monthSelect = parts[1];
						yearSelect = parseInt(parts[2]);					

						hasFeedback.find('select[name*="selectedDay"]').val(daySelect);
						
						
						hasFeedback.find('select[name*="selectedMonth"] option').each(function(){						
				             if ($(this).text() ==  monthSelect) {
				                  option = this;
				                  option.selected = true;
				                  return false;    
				              }
				        }); 					
										
						
						hasFeedback.find('select[name*="selectedYear"] option').each(function(){						
				             if ($(this).text() ==  yearSelect) {
				                  option = this;
				                  option.selected = true;
				                  return false;    
				              }
				        });  

					}		
			
			
		});
		

	}
}



  
	
