console.log('in begining');
var accessToken = 'd0bd571dc19c083d82f023c9666c5574';
var sPath = "https://sharpecf.salestech.cloud/form/";
var siteUrl = "https://sharpecf.salestech.cloud/";
// var accessToken = 'd0bd571dc19c083d82f023c9666c5574 ';
// var sPath = "http://localhost/custom/clifton/form/";
var currentUrl = window.location.href;
let loadjQuery = { "url": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js", "type": "text/javascript", "sync": true };
let loadjQueryValidation = { "url": "https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.20.0/jquery.validate.min.js", "type": "text/javascript", "sync": true };
let loadjQuerySelect2 = { "url": "https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js", "type": "text/javascript", "sync": true };
let loadjQueryUi = { "url": "https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js", "type": "text/javascript", "sync": true };
let loadjQueryMast = { "url": "https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js", "type": "text/javascript", "sync": true };
function loadingDependancies(target, callback) {
return new Promise((resolve, reject) => {
try {
let script = document.createElement("script");
script.type = target.type;
script.async = target.async;
script.src = target.url;
// Set onload callback to resolve the promise and execute the callback
script.onload = function () {
resolve();
if (callback) {
callback();
}
};
// Set onerror callback to reject the promise
script.onerror = function () {
reject(new Error('Script loading error: ' + target.url));
};
document.head.appendChild(script);
} catch (err) {
reject(err);
}
});
}
(function () {
var target = document.getElementById('embedForm'),
parent = target.parentElement,
containerDiv = document.createElement('div');
containerDiv.setAttribute('class', 'imclass');
containerDiv.setAttribute('id', 'imclass');
parent.insertBefore(containerDiv, target);
// Master div creation done
// add loader
var imclassDiv = document.getElementById('imclass');
imclassDiv.innerHTML = `
`;
// Load css
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId)) {
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
// link.href = sPath + 'stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
console.log('i am in on load');
getFormHTML();
}());
function getFormHTML(id) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("imclass").innerHTML = this.responseText;
loadingDependancies(loadjQuery)
.then(() => loadingDependancies(loadjQueryValidation))
.then(() => loadingDependancies(loadjQuerySelect2, initializeSelect2))
.then(() => loadingDependancies(loadjQueryUi))
.then(() => loadingDependancies(loadjQueryMast))
.then(() => {
// Call your custom function
customJs();
})
.catch(err => { console.log(err) });
}
};
// Extract parameters from current URL
var urlParams = new URLSearchParams(currentUrl.split('?')[1]);
var url = sPath + "form.php?accessToken=" + accessToken;
urlParams.forEach(function (value, key) {
url += "&" + key + "=" + value;
});
xhttp.open("POST", url, true);
xhttp.send();
}
// Function to initialize Select2
function initializeSelect2() {
$('.cliftion__form-select-item').select2({
minimumResultsForSearch: Infinity,
});
}
function customJs() {
var generate_json_object = jQuery.parseJSON(jQuery('.mandatoryFieldsJson').val());
var generate_error_msg_json_object = jQuery.parseJSON(jQuery('.mandatoryFieldsMessage').val());
var clph__element_form = $("form.clph__form");
$(document).ready(function () {
checkFieldLogic();
// $('.cliftion__form-select-item').select2({
// minimumResultsForSearch: Infinity,
// });
//Form Validation
clph__element_form.validate({
rules: generate_json_object,
messages: generate_error_msg_json_object,
errorPlacement: function (error, element) {
if (element.prop("type") === "radio") {
error.insertAfter(element.closest('.enquiry-flow__form-radio-wrap'));
} else if (element.prop("type") === "toggle") {
error.insertAfter(element.closest('.clifton__toggle_panel'));
} else if (element.prop("type") === "checkbox") {
error.insertAfter(element.closest('.enquiry-flow__form-check-wrap'));
} else if (element.hasClass('cliftion__currency_input')) {
error.insertAfter(element.closest('.input-group'));
} else if (element.hasClass('cliftion__form-select-item')) {
error.insertAfter(element.siblings('.select2'));
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
var formData = new FormData(form);
$.ajax({
type: 'POST',
url: clph__ajax_url,
data: formData,
dataType: 'JSON',
processData: false,
contentType: false,
success: function (response) {
console.log(response.redirect);
if (response.redirect != "") {
window.location.href = response.redirect;
}
update_next_step();
},
error: function (data) {
console.log('Error:', data);
}
});
}
});
//Company lookup
if (jQuery(".autocomplete__company_lookup").length) {
jQuery(".autocomplete__company_lookup").autocomplete({
source: sPath + "companies.php",
select: function (event, ui) {
jQuery(".autocomplete__company_lookup").val(ui.item.text);
jQuery("#hiddenCompanyNumber").val(ui.item.id);
jQuery("#hiddenBusinessName").val(ui.item.text);
jQuery("#hiddencompanyType").val(ui.item.company_type);
//For Company placehoder
// jQuery(".aef__js_lable_company_name").text(ui.item.text);
return false;
},
/*#15
"Embed company look up
As shown on here https://www.venturemotion.co.uk/sharpe-test/ the lookup search dropdown is not within the field and it didn't appear until I reloded the page
Nathan: Cleared cache and hard refreshed and this is still occuring https://prnt.sc/Jfl2jJS0Jy1-
Albert: Can you please share the URL where you are checking?
Nathan: This one https://sharpecf.co.uk/embed-test/ "
*/
open: function () {
var autocompleteMenu = jQuery(this).autocomplete("widget");
var parentWidth = jQuery('.enquiry-flow__form--wrapper').width();
autocompleteMenu.css("width", parentWidth + "px");
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var company_item = "";
company_item = `
` + item.text + `
` + item.address_snippet + `
`;
return $("
").append(company_item).appendTo(ul);
};
}
//Show Hidden Feild
$(".clifton__dependent-field").on('change', function () {
var checkedValue = $(this).val();
var action = $(this).data("action");
var value = $(this).data("value");
if (checkedValue == 'Yes') {
if (value && value === 'Yes') {
$(".field-" + action).show();
} else {
$(".field-" + action).hide();
}
} else {
$(".field-" + action).hide();
}
});
jQuery("input[name='clph__source_url']").val(currentUrl);
function handleFieldLogic(element, fieldLogic) {
console.log(element);
console.log(fieldLogic);
// Convert the fieldLogic object to a string
var fieldLogicString = JSON.stringify(fieldLogic);
// Replace single quotes with double quotes
var logicString = fieldLogicString.replace(/'/g, '"');
// Convert the string back to an object
var logicObj = JSON.parse(logicString);
// Extract logic conditions
var conditions = logicObj.condition;
// Evaluate each condition
var performAction = false;
var matchCount = 0;
for (var i = 0; i < conditions.length; i++) {
var condition = conditions[i];
var questionId = condition.questionId;
var field = $("[name^='inputs[" + questionId + "]']");
// console.log(field);
var field_val = field.val();
let checkedData = [];
// Check if the field is radio or checkbox
if (field.length && field.attr('type') === 'radio') {
//checked value
field_val = field.filter(':checked').val();
// console.log(field_val);
// Check if the field matches the condition
// if (field.length && field_val !== condition.value) {
// performAction = false;
// matchCount++;
// }
}
if (field.attr('type') === 'checkbox') {
//checked value
field_val = field.filter(':checked').val();
console.log(field.attr('id'));
$("[name^='inputs[" + questionId + "]']:checked").each(function () {
checkedData.push($(this).val());
});
console.log(checkedData);
}
// Check if the field matches the condition
if (field.attr('type') === 'checkbox') {
condition.value
console.log('field_val_array='); console.log(checkedData);
console.log('condition.value=' + condition.value);
if (field.length && checkedData.includes(condition.value)) {
performAction = true;
matchCount++;
}
}
else {
console.log('field_val=' + field_val);
console.log('condition.value=' + condition.value);
if (field.length && field_val == condition.value) {
performAction = true;
matchCount++;
}
}
}
console.log('matchCount=' + matchCount);
// Show or hide the element based on the logic
if ($(element).hasClass('iAmDefaultHide')) {
$(element).hide();
}
else {
$(element).show();
}
if (logicObj.relation == 'and') {
if (matchCount == conditions.length) {
if (logicObj.then === "show") {
$(element).show();
} else {
$(element).hide();
}
}
}
if (logicObj.relation == 'or') {
if (matchCount > 0) {
if (logicObj.then === "show") {
$(element).show();
} else {
$(element).hide();
}
}
}
}
function checkFieldLogic() {
// Loop through all elements with data-field-logic attribute
$('[data-field-logic]').each(function () {
var fieldLogic = $(this).data('field-logic');
if (fieldLogic) {
handleFieldLogic(this, fieldLogic);
}
});
}
// Event listener for change events on select inputs
$('.cliftion__form-select-item').change(function () {
checkFieldLogic();
});
// Event listener for change events on toggle inputs
$('.clifton__toggle_panel_button').change(function () {
checkFieldLogic();
});
// Event listener for change events on radio inputs
$('.clifton__radio_panel_button').change(function () {
checkFieldLogic();
});
//event listener for change events Multi choice
$('.clifton__checkbox_panel_button').change(function () {
checkFieldLogic();
});
$('.cliftion__currency_input').mask("000,000,000,000,000,000", {
reverse: true
});
$('.clph__date_inputmask').mask('99/99/9999', {
placeholder: "DD/MM/YYYY"
});
});
}