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 ]*$/),
    countryFieldTest = new RegExp(/^[a-zA-Z ()-\.']*$/),
    phoneTest = new RegExp(/^\d{5,}$/),
    mainMemberFirstName,
    mainMemberLastName,
    day,
    month,
    year,
    monthAsString,
    mainMemberNationality,
    email,
    phoneCode,
    phoneNumber,
    hasFeedback,
    generalFormField,
    formField,
    formFieldWithoutValue,
    body = $('body'),
    thisWindow = $(window),
    mainMemberGen,
    depGen,
    invalidForm = false,
    selectedCountry,
    currentlyThere,
    selectedNationality,
    scrollingAllowedToSpecificDependant = false,
    arr = {};

function initialLoad() {
	
	'use strict';
	
	
	setFieldsValidationOnBlur();
	
    $('#quoteForm').submit(function (e) {
    	invalidForm = false;

    	$('.form-control').each(function() {
    		setFieldsValidator($(this), 'submit');
    	});
    	
    	if(invalidForm){
    		console.log("Flagged as invalid form");
    		e.preventDefault();

    	}
    	
    	if(!invalidForm){
	    	console.log("BEFORE 'See My Price' btn data push==>" + selectedNationality);
	    	if(selectedNationality != null){
	    		selectedCountry = null;
	    		pushDataOnClickOfSeeMyPriceBtn('qnb_see_my_price');
	    	}
	
	    	console.log("BEFORE 'Get A Quote' btn data push==>" + selectedCountry);
	    	if(selectedCountry != null){
	    		pushDataOnClickOfGetAQuoteBtn('qnb_get_a_quote');
	    	}
    	}

    });
    
    $('#quoteForm').attr('novalidate', 'novalidate');
}

function validateInRegionRadioGroup(element) {
	if(currentlyThere == undefined) {
		invalidForm = true;
		toggleValidationErrorForInRegionFields(element, true);
	}
}

function toggleValidationErrorForInRegionFields(element, isErrorFlag) {
	toggleError(element,isErrorFlag,getInvalidFeedbackElement(element));
}

function countrySearchFieldEventHandler(countrySearchFieldId, countryDropdownFieldId) {
	
	setOnChangeEventForCountryDropdown(countrySearchFieldId, countryDropdownFieldId);

	populateCountriesList(countryDropdownFieldId);
	
	autocomplete(countrySearchFieldId, countryDropdownFieldId);
	
}

function dependantCountrySearchFieldEventHandler(defaultSelectFieldID, defaultSearchFieldID, currentDependantIndex, currentDependantSearchFieldValue) {
	var currentDependantSearchFieldID, currentDependantSelectFieldID;
	if(currentDependantIndex == 0) {
		currentDependantSelectFieldID = defaultSelectFieldID;
		currentDependantSearchFieldID = defaultSearchFieldID;
		($('#'+currentDependantSelectFieldID).prev('input')).attr('id',currentDependantSearchFieldID);
		setCountryFieldValueOnPageLoad(currentDependantSearchFieldID, currentDependantSearchFieldValue);
		countrySearchFieldEventHandler(currentDependantSearchFieldID, currentDependantSelectFieldID);
	} else {
		currentDependantSelectFieldID = defaultSelectFieldID + '_'+(currentDependantIndex-1);
		currentDependantSearchFieldID = defaultSearchFieldID + '_'+(currentDependantIndex-1);
		($('#'+currentDependantSelectFieldID).prev('input')).attr('id',currentDependantSearchFieldID);
		setCountryFieldValueOnPageLoad(currentDependantSearchFieldID, currentDependantSearchFieldValue);
		countrySearchFieldEventHandler(currentDependantSearchFieldID, currentDependantSelectFieldID);
	}
}

function setCountryFieldValueOnPageLoad(countrySearchFieldId, initialCountryValue) {
	if(!isEmptyValue(initialCountryValue)){
		$('#'+countrySearchFieldId).val(initialCountryValue);
		$('#'+countrySearchFieldId).attr('data-validcountryname','true');
	}
}

function setUserActionsToGlobalVariables(countryDropdownFieldId, countryName) {
	/* Below code for Google Analytics */
	selectedCountry = countryName;
	currentlyThere = undefined;
	if(countryDropdownFieldId == 'mainMemberNationality'){
		selectedNationality = countryName;
	}
}

function selectGivenCountry(countryDropdownFieldId, selectedOptionValue, countrySearchFieldId) {
	$("#"+countryDropdownFieldId+" option[value='"+selectedOptionValue+"']").prop('selected', true).change();
	console.log("After CHANGING: " + $("#"+countryDropdownFieldId+" option:selected").text());
	invalidForm = false;
	$('#'+countrySearchFieldId).attr('data-validcountryname','true')
}

function checkFieldMatchingCountriesList(element) {
	var countrySearchFieldFeedbackElement = getInvalidFeedbackElement(element);
	if((element.val() == undefined || isEmptyValue(element.val()))){
		invalidForm = true;
		countrySearchFieldFeedbackElement.text(element.attr('data-errormessage'));
		toggleError(element, true, countrySearchFieldFeedbackElement);
		//element.next('datalist').css( "display", "none" );
	} else if(element.attr('data-validcountryname') == 'false'){
		invalidForm = true;
		countrySearchFieldFeedbackElement.text('Please enter a valid country name.');
		toggleError(element, true, countrySearchFieldFeedbackElement);
		//element.next('datalist').css( "display", "none" );
	}
}

function setOnChangeEventForCountryDropdown(countrySearchFieldId, countryDropdownFieldId) {
    $('#'+countryDropdownFieldId).on('change', function(){
		invalidForm = false;
		toggleValidationClasses($("#"+countrySearchFieldId), false);

		$('#'+countrySearchFieldId).val($("#"+countryDropdownFieldId+" option:selected").text());

		console.log("**Service call made**");
    });
}

function populateCountriesList(countryDropdownFieldId) {
	$("#"+countryDropdownFieldId+" option").each(function(){
		if($(this).text() == "Please select..." || $(this).text().match(new RegExp(/^[=]*$/))){
			//$("."+datalistFieldClass).append("<option value='"+$(this).val()+"' disabled='disabled'>"+$(this).text()+"</option>");
		} else {
			arr[$(this).val()] = $(this).text();
			//$("."+datalistFieldClass).append("<option value='"+$(this).val()+"' onclick='selectedAnOption()'>"+$(this).text()+"</option>");
		}
	});
}

function validateCountryFieldsOnload(countrySearchFieldId) {
	if($("#"+countrySearchFieldId).val() == undefined || isEmptyValue($("#"+countrySearchFieldId).val()))
	{
		invalidForm = true;
	}
}

function updateDependantDetailsInTacticalDesign() {
	setFieldsValidationOnBlur();
	updateDependantDateDetailsInTacticalPage();
	
	scrollingAllowedToSpecificDependant = true;
	
    $('.removeDependant').click(function () {    
    	
    	var dependantsCountValue = parseInt($('#dependantsCount').val()) - 1;   	

    	toggleAddFamilyMemberButton(dependantsCountValue); 	
    	
    	$('#dependantsCount').val(dependantsCountValue);
    	
    });
}

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

		parentElement = $(this).closest('.jQuery_selection_dependantdob_wrapper');				
		
		dependantsValue = parentElement.find('input[name*="dependantSelectedPicker"]').val();
		
		if (dependantsValue === "") {

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

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

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

		}
	});
}

function setFieldsValidationOnBlur() {
	$('.form-control').each(function() {
		$(this).blur(function () {
			setFieldsValidator($(this), 'blur');
		});
	});
}

function setFieldsValidator(element, action) {
	if(element.attr('id') === 'mainMemberFirstName'){
		fieldValidator(element, 'Please enter your first name.', textTest, 'Please use alphabetical characters only for first name.');
	} else if (element.attr('id') === 'mainMemberFamilyName') {
		fieldValidator(element, 'Please enter your last name.', textTest, 'Please use alphabetical characters only for last name.');
	} else if (element.attr('id') === 'mainMemberEmail') {
		fieldValidator(element, 'Please enter your email address.', mainMemberEmailTest, 'Your email address is incorrect - please double check.');
	} else if ((element.attr('id')).indexOf("dependantFirstName") >= 0) {
		fieldValidator(element, 'Please enter the first name for member.', textTest, 'Please use alphabetical characters only for first name.');
	} else if ((element.attr('id')).indexOf("dependantFamilyName") >= 0) {
		fieldValidator(element, 'Please enter the last name for member.', textTest, 'Please use alphabetical characters only for last name.');
	} else if (isDateField(element)) {
		dateFieldsValidator(element);
	} else if (isPhoneField(element)) {
		phoneCodeAndPhoneNumberFieldsValidator(element);
	} else if (((element.attr('id')).indexOf("primaryCountrySearchField") >= 0) || ((element.attr('id')).indexOf("secondaryCountrySearchField") >= 0) || ((element.attr('id')).indexOf("mainMemberNationalitySearchField") >= 0) || ((element.attr('id')).indexOf("dependantNationalitySearchField") >= 0) || ((element.attr('id')).indexOf("dependantLivingCountrySearchField") >= 0)) {
		if(action == 'submit'){
			checkFieldMatchingCountriesList(element);
		}
		/*Else: Do nothing, we have other functions in place to handle validation*/
	} else if (((element.attr('id')).indexOf("primaryInRegionRadioGroup") >= 0) || ((element.attr('id')).indexOf("secondaryInRegionRadioGroup") >= 0) || ((element.attr('id')).indexOf("inRegionRadioGroup") >= 0)) {
		validateInRegionRadioGroup(element);
	} else {
		fieldValidator(element, null, null, null);
	}
}

function fieldValidator(element, errorMsg, regExp, regExpFailureErrorMsg) {
	var invalidFeedbackElement = getInvalidFeedbackElement(element);

	if (element.val() === '' || element.val() === null) {
		invalidForm = true;
		if(errorMsg !== '' && errorMsg !== null){
			invalidFeedbackElement.text(errorMsg);
		}
		toggleError(element, true, invalidFeedbackElement);
    } else if ((regExp !== '' && regExp !== null) && !element.val().match(regExp)) {
    	invalidForm = true;
    	if(regExpFailureErrorMsg !== '' && regExpFailureErrorMsg !== null){
    		invalidFeedbackElement.text(regExpFailureErrorMsg);
    	}
    	toggleError(element, true, invalidFeedbackElement);
    } else {
    	toggleError(element, false, invalidFeedbackElement);
    }
}

function getInvalidFeedbackElement(element) {
	if(typeof (element.nextAll('.invalid-feedback'))[0] === 'undefined' || (element.nextAll('.invalid-feedback'))[0] == undefined || (element.nextAll('.invalid-feedback'))[0] == null) {
		return $((element.parent().nextAll('.invalid-feedback'))[0]);
	} else {
		return $((element.nextAll('.invalid-feedback'))[0]);
	}
}

function phoneCodeAndPhoneNumberFieldsValidator(element) {
	var phoneCode = $('#phone-code');
	var phoneNumber = $('#phone-number');
	var phoneFeedbackElement = getInvalidFeedbackElement(element);
	var emptyFieldValidationErrorMessage = 'We need your telephone number so that we can contact you if we have any questions about your quote.';
	var phoneNumberValidationErrorMessage = 'Please insert a valid home phone number (5 digits minimum).';
	
	if(!isEmptyValue(phoneCode.val()) && (!isEmptyValue(phoneNumber.val()) && isValidPhoneNumber(phoneNumber.val()))){
		toggleError(phoneCode, false, phoneFeedbackElement);
		toggleError(phoneNumber, false, phoneFeedbackElement);
	} else {
		if(isEmptyValue(phoneCode.val()) || isEmptyValue(phoneNumber.val())) {
			invalidForm = true;
			phoneFeedbackElement.text(emptyFieldValidationErrorMessage);
			toggleError(phoneCode, true, phoneFeedbackElement);
			toggleError(phoneNumber, true, phoneFeedbackElement);
		}

		if(!isEmptyValue(phoneNumber.val()) && !isValidPhoneNumber(phoneNumber.val())){
			invalidForm = true;
			phoneFeedbackElement.text(phoneNumberValidationErrorMessage);
			toggleError(phoneNumber, true, phoneFeedbackElement);
		}
	}

}

function isValidPhoneNumber(num) {
	return num.match(phoneTest) ? true:false;
}

function dateFieldsValidator(element) {
	var dateFeedbackElement = getInvalidFeedbackElement(element);

	element.parents('.dobFieldsContainer').each(function() {
		var dayElement;
		var monthElement;
		var yearElement;
		$(this).find('select').each(function() {
			if(($(this).attr('id')).toLowerCase().indexOf('day') >= 0) {
				dayElement = $(this);
			}
			if(($(this).attr('id')).toLowerCase().indexOf('month') >= 0) {
				monthElement = $(this);
			}
			if(($(this).attr('id')).toLowerCase().indexOf('year') >= 0) {
				yearElement = $(this);
			}
		});
		
		if(!isEmptyValue(dayElement.val()) && !isEmptyValue(monthElement.val()) && !isEmptyValue(yearElement.val())){
			toggleError(dayElement, false, dateFeedbackElement);
			toggleError(monthElement, false, dateFeedbackElement);
			toggleError(yearElement, false, dateFeedbackElement);
			if($(this).find('input[type=text]').attr('id') == 'mainMemberSelectedPicker'){
				validateGivenDate(dayElement, monthElement, yearElement, dateFeedbackElement, 'mainMemberSelectedPicker');
			} else if(($(this).find('input[type=text]').attr('id')).indexOf('dependantSelectedPicker') >= 0){
				$(this).find('input[type=text]').val(dayElement.find('option:selected').text() + '/'+ monthElement.find('option:selected').text() + '/'+ yearElement.find('option:selected').text());
			}
		} else {
			invalidForm=true;
			
			if((element.attr('id')).toLowerCase().indexOf('year') >= 0) {
				toggleError(dayElement, true, dateFeedbackElement);
				toggleError(monthElement, true, dateFeedbackElement);
				toggleError(yearElement, true, dateFeedbackElement);
			}
		}
	});
	
}

function validateGivenDate(dayElement, monthElement, yearElement, dateFeedbackElement, selectedPickerID) {
	var day = dayElement.find('option:selected').text();
	var monthAsString = monthElement.find('option:selected').text();
	var month = monthElement.val();
	var year = yearElement.find('option:selected').text();
	
	var dateOfBirthAsString = day + " " + monthAsString + " " + year;  
	var dob = new Date(dateOfBirthAsString);				
	var age = getAge(dob);

	if (!isValidDate(day, month, year)) {
		dateFeedbackElement.text("Your date of birth is not a valid date.");
		toggleError(dayElement, true, dateFeedbackElement);
		toggleError(monthElement, true, dateFeedbackElement);
		toggleError(yearElement, true, dateFeedbackElement);
	} else if (age > 100) {
		dateFeedbackElement.text('Main member’s date of birth must be on or after ' + getDateOfBirthToCheck(100));
		toggleError(dayElement, true, dateFeedbackElement);
		toggleError(monthElement, true, dateFeedbackElement);
		toggleError(yearElement, true, dateFeedbackElement);		
	} else if (age < 18) {
		dateFeedbackElement.text('Main member’s date of birth must be before ' + getDateOfBirthToCheck(18));
		toggleError(dayElement, true, dateFeedbackElement);
		toggleError(monthElement, true, dateFeedbackElement);
		toggleError(yearElement, true, dateFeedbackElement);		
	} else {
		toggleError(dayElement, false, dateFeedbackElement);
		toggleError(monthElement, false, dateFeedbackElement);
		toggleError(yearElement, false, dateFeedbackElement);
		$('#'+selectedPickerID).val(dayElement.find('option:selected').text() + '/'+ monthElement.find('option:selected').text() + '/'+ yearElement.find('option:selected').text());
	}
}

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 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 toggleError(element, isError, invalidFeedbackElement) {
	if(isError) {
		element.removeClass('is-valid').addClass('is-invalid');
		invalidFeedbackElement.show();
	} else {
		element.removeClass('is-invalid').addClass('is-valid');
    	invalidFeedbackElement.hide();
	}
}

function toggleValidationClasses(element, isInvalid) {
	if(isInvalid) {
		element.removeClass('is-valid').addClass('is-invalid');
	} else {
		element.removeClass('is-invalid').addClass('is-valid');
	}
}

function isDateField(element) {
	return ((element.attr('id')).toLowerCase().indexOf("day") >= 0 || (element.attr('id')).toLowerCase().indexOf("month") >= 0 || (element.attr('id')).toLowerCase().indexOf("year") >= 0)? true:false;
}

function isPhoneField(element) {
	return ((element.attr('id')).toLowerCase().indexOf("phone") >= 0)? true:false;
}

function isEmptyValue(value) {
	return (value === '' || value === null) ? true:false;
}

$(document).on('click', '.inRegionResponseLabel', function(){
	currentlyThere = $(this).text();
	toggleValidationErrorForInRegionFields($(this).parent().closest('span'),false);
});

/* 
 * Google Analytics section
 * 
 */
function setSelectedCountryAndCurrentlyThere(selectedCountryInitially, currentlyThereInitially) {
	selectedCountry = selectedCountryInitially;
	switch(currentlyThereInitially){
		case 'true':
			currentlyThere = 'Yes';
			break;
		case 'false':
			currentlyThere = 'No';
			break;
		default:
			currentlyThere = undefined;
			break;
	}
	console.log("Intial values: " + selectedCountry + " + " + currentlyThere);
}

function pushDataOnClickOfSeeMyPriceBtn(eventValue) {
	console.log("Push on click of 'See My Price' btn==>" + eventValue + " + " + selectedNationality + " + " + $('#dependantsCount').val());
	if(selectedNationality != undefined){
		dataLayer.push({
		    event: eventValue,
		    nationality: selectedNationality,
		    dependants: $('#dependantsCount').val()
		});
	} else {
		console.log("selectedNationality is undefined");
	}
}

function pushDataOnClickOfGetAQuoteBtn(eventValue) {
	if(currentlyThere != undefined){
		currentlyThere = isEmptyValue(currentlyThere) ? 'No':currentlyThere;
		console.log("Push on click of 'Get A Quote' btn==>" + eventValue + " + " + selectedCountry + " + " + currentlyThere);
		dataLayer.push({
		    event: eventValue,
		    destination: selectedCountry,
		    currently_there: currentlyThere
		});
	} else {
		console.log("Push on click of 'Get A Quote' btn==>" + eventValue + " + " + selectedCountry);
		dataLayer.push({
		    event: eventValue,
		    destination: selectedCountry,
		});
	}
}

function pushCountrySelectorPageInfo(pageName) {
	if(window.datalayer == undefined){
    	window.dataLayer = window.dataLayer || [];
    }
	
	console.log("Push on 'Country Selector' page load==>" + pageName);
	window.dataLayer.push({
        event: 'page_info',
        user_agent: window.navigator.userAgent,
        funnel_step: pageName
    });
}

function pushAboutYouPageInfo(pageName) {
    if(window.datalayer == undefined){
    	window.dataLayer = window.dataLayer || [];
    }
    
    if(selectedCountry != undefined){
    	if(currentlyThere != undefined){
			currentlyThere = isEmptyValue(currentlyThere) ? 'No':currentlyThere;
	    
			console.log("Push on 'About you' page load==>" + pageName + " + " + selectedCountry + " + " + currentlyThere);
			
		    window.dataLayer.push({
		        event: 'page_info',
		        user_agent: window.navigator.userAgent,
		        funnel_step: pageName,
		        destination: selectedCountry,
		        currently_there: currentlyThere
		    });
    	} else {
    		console.log("Push on 'About you' page load==>" + pageName + " + " + selectedCountry);
    		window.dataLayer.push({
    	        event: 'page_info',
    	        user_agent: window.navigator.userAgent,
    	        funnel_step: pageName,
    	        destination: selectedCountry
    	    });
    	}
    } else {
    	console.log("Push on 'About you' page load==>" + pageName);
    	window.dataLayer.push({
	        event: 'page_info',
	        user_agent: window.navigator.userAgent,
	        funnel_step: pageName
	    });
    }
}

function scrollToLatestDependant(totalDependantCount, currentDependantIndex) {
	if(scrollingAllowedToSpecificDependant && (totalDependantCount == currentDependantIndex)) {
		$('html, body').animate({
            scrollTop: $('#For_' + (currentDependantIndex-1)).offset().top
        }, 1000);
	}
}

function autocomplete(countrySearchFieldId, countryDropdownFieldId) {
  var inp = document.getElementById('' + countrySearchFieldId)
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus;
  
  inp.addEventListener("focus", function(e) {
      var a, b, noOptionsAdded = 0, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      /*if (!val) {
    	  val = 'A';
	  }*/
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items" + " " + $(this).attr('data-design'));
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.insertBefore(a, document.getElementById('' + countryDropdownFieldId));
      /*for each item in the array...*/
      for (var i in arr) {
        /*check if the item starts with the same letters as the text field value:*/
    	// if ((val == '') || ((arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) && (i>5))) { /*Use this 'if' when you want to add condition while listing dropdown values*/
    	  noOptionsAdded++;
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          b.setAttribute("class", "cs-option");
          /*make the matching letters bold:*/
          b.innerHTML = "" + arr[i].substr(0, val.length) + "";
          b.innerHTML += arr[i].substr(val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' data-code='"+i+"' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
          b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              
              /* Code added to select value in the select element */
              selectGivenCountry(countryDropdownFieldId, $(this.getElementsByTagName("input")[0]).attr('data-code'), countrySearchFieldId);
              setUserActionsToGlobalVariables(countryDropdownFieldId, this.getElementsByTagName("input")[0].value);
              
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);
        // }
      }

      if(!(noOptionsAdded > 0)){
    	  closeAllLists();
      }
  });
  
  /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) {
      var a, b, noOptionsAdded = 0, val = this.value;
      
      $('#'+countrySearchFieldId).attr('data-validcountryname','false');
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) {
    	  if((countrySearchFieldId.indexOf('primaryCountrySearchField') >= 0) || (countrySearchFieldId.indexOf('secondaryCountrySearchField') >= 0)){
    		$('#primaryCountrySearchField').val('');
			$('#secondaryCountrySearchField').val('');
    	  }
    	  // return false;
	  }
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items" + " " + $(this).attr('data-design'));
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.insertBefore(a, document.getElementById('' + countryDropdownFieldId));
      /*for each item in the array...*/
      for (var i in arr) {
        /*check if the item starts with the same letters as the text field value:*/
        if ((val == '') || ((arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) && (i>5))) {
          noOptionsAdded++;
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          b.setAttribute("class", "cs-option");
          /*make the matching letters bold:*/
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' data-code='"+i+"' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
          b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              
              /* Code added to select value in the select element */
              selectGivenCountry(countryDropdownFieldId, $(this.getElementsByTagName("input")[0]).attr('data-code'), countrySearchFieldId);
              setUserActionsToGlobalVariables(countryDropdownFieldId, this.getElementsByTagName("input")[0].value);
              
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);
        }
        
        if(arr[i].toUpperCase() == val.toUpperCase()){
        	selectGivenCountry(countryDropdownFieldId, i, countrySearchFieldId);
  			setUserActionsToGlobalVariables(countryDropdownFieldId, arr[i]);
        }
      }

      if(!(noOptionsAdded > 0)){
    	  closeAllLists();
      }
  });
  /*execute a function presses a key on the keyboard:*/
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*If the arrow DOWN key is pressed,
        increase the currentFocus variable:*/
        currentFocus++;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /*If the arrow UP key is pressed,
        decrease the currentFocus variable:*/
        currentFocus--;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 13) {
        /*If the ENTER key is pressed, prevent the form from being submitted,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*and simulate a click on the "active" item:*/
          if (x) x[currentFocus].click();
        }
      }
  });
  
  inp.onblur = function(e) {
	checkFieldMatchingCountriesList($(this));
  }

  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("active");
  }
  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("active");
    }
  }
  
  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
	      x[i].parentNode.removeChild(x[i]);
	  }
	}
  }
  
  function closeAllListsOnDocumentClick(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
	      if (elmnt != x[i] && !elmnt.classList.contains("autoCompleteSearchField")) {
		      x[i].parentNode.removeChild(x[i]);
		  }
	}
  }
  
  /*execute a function when someone clicks in the document:*/
  document.addEventListener("click", function (e) {
	closeAllListsOnDocumentClick(e.target);
  });

}

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

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

		parentElement = $(this).closest('.jQuery_selection_mainmemberdob_wrapper');				
		
		mainMemberValue = parentElement.find('input[name*="mainMemberSelectedPicker"]').val();
		
		if (mainMemberValue === "") {

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

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

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

		}		
	});
}

function updateDependantsCount() {	
	var dependantsCount = parseInt($('#dependantsCount').val()) + 1;
	
	toggleAddFamilyMemberButton(dependantsCount);
	
	$('#dependantsCount').val(dependantsCount);
}

function setInitalValueofDependantsCount(initialValue) {
	if(!isEmptyValue(initialValue)) {
		$('#dependantsCount').val(initialValue);
		toggleAddFamilyMemberButton(initialValue);
	}
}

function toggleAddFamilyMemberButton(currentCount) {
	if (currentCount > 8) {
		$('#addPerson').hide();
	} else {
		$('#addPerson').show();		
	}
}

function addRequiredPropToSpecificSelectElements() {
	$('.addRequired').each(function() {
		$(this).prop('required', true);
	});
}