const FORM_CONST = {
environmentUrl: 'https://api.ringlead.com/',
hubspot_regex: 'company-[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}',
inputTags: {
rl_allTextFields: ['input', 'text'],
rl_allInputButtonFields: ['input', 'submit'],
rl_allForms: ['form', ''],
rl_allButtons: ['button', 'submit'],
rl_allEmailFields: ['input', 'email'],
rl_allTextAreaFields: ['textarea', ''],
rl_allHiddenFields: ['input', 'hidden'],
rl_allInputNumberFields: ['input', 'number'],
rl_allSelectFields: ['select', ''],
rl_allButtons2: ['button', null]
},
inputTagName: {
rl_allTextFields: 'textField',
rl_allInputButtonFields: 'inputButton',
rl_allForms: 'form',
rl_allButtons: 'button',
rl_allEmailFields: 'emailField',
rl_allTextAreaFields: 'textAreaField',
rl_allHiddenFields: 'hiddenField',
rl_allSelectFields: 'selectField',
rl_allInputNumberFields: 'numberField'
},
formSettings: {
rl_Street: 'rl_address_element',
rl_City: 'rl_city_element',
rl_State: 'rl_state_element',
rl_Country: 'rl_country_element',
rl_Zip: 'rl_zip_element',
rl_Form: 'rl_form_element',
rl_Company: 'rl_company_element',
rl_Email: 'rl_email_element'
},
outputFields: ['Company', 'Address', 'City', 'State', 'Zip', 'Country'],
logo: ` INTELLIGENT FORMS BY RINGLEAD`
};
class IntelligentForm {
constructor(uuid) {
this.rl_uuid = uuid;
this.hsPopUpForm = null;
this.rl_company_element = null;
this.rl_address_element = null;
this.rl_city_element = null;
this.rl_zip_element = null;
this.rl_country_element = null;
this.rl_form_element = null;
this.rl_email_element = null;
this.hubspot_iframe = null;
this.rl_company_suggestions = null;
this.rl_company_suggestions_list = null;
this.rl_company_response = [];
this.rl_company_suggetions_style = null;
this.rl_form_abandon = true;
this.rl_form_stats_submitted = this.rl_suggested_count = this.rl_confirmed_count = this.rl_not_found_count = 0;
this.leadLocationDetails = null;
this.companyIpDetails = this.rl_form_button_object = {};
this.isPopUpHubspot = false;
this.initialCompanyChange = 1;
this.rl_tracking_api_name = this.rl_form_type = this.rl_form_page_fields = this.status = null;
}
createXHR = () => {
try {
return new XMLHttpRequest();
}
catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
return new ActiveXObject("Msxml2.XMLHTTP");
}
}
}
handleApiResponse = (type, response) => {
switch (type) {
case 'TASK_STATUS':
switch (response.status) {
case 'CREA':
console.log('Field mapping is still missing. Please map and toggle task status.');
this.rl_form_type = response.form_type;
this.processNewTask();
break;
case 'Active':
console.log('Existing task processed successfully.');
this.setFields(response);
this.addRingleadEventListeners();
break;
case 'Inactive':
console.log('Task is inactive. Can not perform intelligent activities');
break;
default:
console.log(`Something is wrong with task status: ${response.status}`);
}
break;
case 'NEW_TASK':
console.log('New task setup request sent to DMS.');
case 'SEARCH':
this.rl_company_response = response.result;
localStorage['token'] = response.token || '';
if (this.rl_company_response) {
this.rl_company_response.length === 0 ? this.rl_not_found_count++ : this.rl_suggested_count++;
this.displayRenderResults(this.rl_company_response);
}
break;
case 'STATS':
console.log(response);
this.rl_form_stats_submitted = 1;
this.rl_suggested_count = this.rl_confirmed_count = this.rl_not_found_count = 0;
break;
default:
console.log('Implementation in progress...');
}
}
callAPI = (payload, url, type, async = false) => {
let http = this.createXHR();
http.onreadystatechange = () => {
if (http.readyState === XMLHttpRequest.DONE) {
let response = JSON.parse(http.responseText);
this.handleApiResponse(type, response);
}
}
http.open("POST", url, async);
http.setRequestHeader("Content-type", "application/json");
http.send(JSON.stringify(payload));
}
formSubmitAction = () => this.rl_form_abandon = false;
hideResultDiv = () => this.rl_company_suggestions.style.display = "none";
strip = (str) => str.replace(/^\s+|\s+$/g, '');
tabOut = (event) => event.keyCode === 9 ? this.rl_company_suggestions.style.display = "none" : null;
focusOutCompany = () => {
let resultDiv = document.getElementById("results_div");
resultDiv.style.display = "none";
}
clearFieldValues = () => {
let fs = FORM_CONST.formSettings;
try {
for (let field in fs) {
if (field !== 'rl_Form' && field !== 'rl_Company' && this[fs[field]] && field !== 'rl_Email')
this[fs[field]].value = '';
}
} catch (e) { console.log(e) }
}
displayRenderResults = (rl_results) => {
let resultDisplayCount = 0;
if (rl_results.length !== 0) {
for (let i in rl_results) {
if (resultDisplayCount === 4)
break;
if (rl_results[i]['Company'] !== undefined) {
let option = document.createElement('li'),
optionString = "";
FORM_CONST.outputFields.forEach((field) => {
if (rl_results[i][field])
optionString += `${field === 'Company' ? `` : ''}${rl_results[i][field]}${field === 'Company' ? '
' : ''}${field !== 'Company' ? ', ' : ''}`
})
optionString = optionString.slice(0, -1);
option.innerHTML = optionString;
option.setAttribute('responseid', i);
option.addEventListener('click', this.selectOption);
this.rl_company_suggestions_list.appendChild(option);
resultDisplayCount += 1;
optionString = "";
}
}
}
let companyval = this.rl_company_element.value,
option = document.createElement('li');
option.style.cursor = 'pointer';
option.innerHTML = 'None of the above ( "' + companyval + '" )';
option.setAttribute('responseid', (99).toString());
option.addEventListener('click', this.hideResultDiv);
this.rl_company_suggestions_list.appendChild(option);
this.rl_company_suggestions.style.display = "block";
}
addCssStyleHeader = (cssSettings) => {
let allCssSettings = null;
if (cssSettings) {
allCssSettings = `${cssSettings.resultDivCssClass}${cssSettings.companySuggestionsListCss}${cssSettings.listElementCss}${cssSettings.listElementHoverCss}${cssSettings.rl_company_footer}`
if (cssSettings.customCss)
allCssSettings = allCssSettings + cssSettings.customCss;
}
return allCssSettings;
}
setFields = (data) => {
this.status = data.status ? data.status : this.status;
this.rl_form_type = data.form_type ? data.form_type : this.rl_form_type;
this.rl_form_settings = data.form_settings ? data.form_settings : this.rl_form_settings;
this.rl_css_settings = data.form_settings ? data.form_settings.css_template : this.rl_css_settings;
this.leadLocationDetails = data.locationDetails ? data.locationDetails : this.leadLocationDetails;
this.rl_tracking_api_name = data.marketo_configuration ? data.marketo_configuration : this.rl_tracking_api_name;
this.companyIpDetails = data.companyDetails ? data.companyDetails : this.companyIpDetails;
this.rl_form_button_object = data.form_page_fields ? data.form_page_fields.rl_form_button : this.rl_form_button_object;
this.rl_form_page_fields = data.form_page_fields ? data.form_page_fields : this.rl_form_page_fields;
this.rl_company_suggetions_style = this.rl_css_settings && this.addCssStyleHeader(this.rl_css_settings);
localStorage['token'] = data.token ? data.token : '';
}
addRingleadEventListeners = (hsFormDetected = false) => {
let htmlId = this.rl_form_settings['rl_Company']['html_id'];
htmlId = this.getHubspotFormId(htmlId);
let pardotComapnyId = this.getpardotFormElementId('company');
htmlId = this.rl_form_type === 'Pardot' && pardotComapnyId ? pardotComapnyId : htmlId;
this.resolveRingleadFormSettings(hsFormDetected);
this.addRingleadHtmlElements(htmlId);
}
getHubspotFormId = (htmlId) => {
let hsForm = null
try {
hsForm = htmlId.match(FORM_CONST.hubspot_regex);
} catch (e) {
console.log('Not a hubspot form!');
}
if (hsForm) {
this.is_hubspot_form = true;
return hsForm[0];
}
return htmlId;
}
getpardotFormElementId = (element) => {
if (!this.rl_form_element)
this.rl_form_element = document.getElementById('pardot-form');
if (!this.rl_form_element) return;
let p_child_nodes = this.rl_form_element.getElementsByClassName(element);
if (p_child_nodes.length > 0) {
let p_company_child_nodes = [];
p_company_child_nodes = p_child_nodes[0].getElementsByTagName('input');
if (p_company_child_nodes.length === 0) {
p_company_child_nodes = p_child_nodes[0].getElementsByTagName('select');
}
for (let i = 0; i < p_company_child_nodes.length; i++) {
let node = p_company_child_nodes[0];
return node.getAttribute('id');
}
}
return null;
}
getPageFields = (tagName, tagType) => {
let querySelectorText = null;
switch (true) {
case (tagName === 'input' && tagType === 'text'):
querySelectorText = 'input[type=text]';
break;
case (tagName === 'input' && tagType === 'submit'):
querySelectorText = 'input[type=submit]';
break;
case (tagName === 'button' && tagType === 'submit'):
querySelectorText = 'button[type=submit]';
break;
case (tagName === 'form'):
querySelectorText = 'form';
break;
case (tagName === 'textarea'):
querySelectorText = 'textarea';
break;
case (tagName === 'input' && tagType === 'email'):
querySelectorText = 'input[type=email]';
break;
case (tagName === 'input' && tagType === 'hidden'):
querySelectorText = 'input[type=hidden]';
break;
case (tagName === 'input' && tagType === 'number'):
querySelectorText = 'input[type=number]';
break;
case (tagName === 'select'):
querySelectorText = 'select';
break;
case (tagName == 'button' && tagType === null):
querySelectorText = 'button';
break;
}
if (this.rl_form_type === 'Hubspot') {
if (this.isPopUpHubspot) {
return querySelectorText && this.hsPopUpForm.querySelectorAll(querySelectorText);
}
let hsIFrame = document.querySelector('iframe[id*="hs-form-iframe"]');
if (hsIFrame && hsIFrame.length !== 0) {
this.hubspot_iframe = hsIFrame;
let hsFormContent = hsIFrame.contentDocument;
let iframeHead = hsFormContent.getElementsByTagName('head');
let hs_trigger_event = document.createElement('script');
hs_trigger_event.type = 'text/javascript';
hs_trigger_event.innerHTML = 'function triggerChangeEvent(e){' +
'let iframe_data = JSON.parse(e.data);' +
'console.log(iframe_data);' +
'let disp_ele = document.getElementById(iframe_data.id);' +
'disp_ele.value = iframe_data.value;' +
'console.log(disp_ele);' +
'disp_ele.dispatchEvent(new Event("change"));}' +
'window.addEventListener("message", triggerChangeEvent);';
iframeHead[0].appendChild(hs_trigger_event);
return querySelectorText && hsFormContent.querySelectorAll(querySelectorText);
}
else {
return querySelectorText && document.querySelectorAll(querySelectorText);
}
}
else
return querySelectorText && document.querySelectorAll(querySelectorText);
}
findFormSubmitButtonPairs = (buttonTag) => {
let rl_form_submit_object = {};
for (let i = 0; i < buttonTag.length; i++) {
let rl_tagName = buttonTag[i],
rl_parentNode = rl_tagName.parentNode;;
while (true) {
if (rl_parentNode.nodeName === 'FORM') {
let rl_formParentId = rl_parentNode.getAttribute('id'),
rl_formParentName = rl_parentNode.getAttribute('name'),
rl_tagNameId = rl_tagName.getAttribute('id');
if (rl_formParentId) {
if (rl_tagNameId)
rl_form_submit_object[rl_formParentId] = rl_tagNameId;
} else {
if (rl_tagNameId)
rl_form_submit_object[rl_formParentName] = rl_tagNameId;
}
break;
}
if (rl_parentNode.nodeName === 'BODY') {
break;
}
rl_parentNode = rl_parentNode.parentNode;
}
}
return rl_form_submit_object;
}
fillSelectField = (fieldStateValue, selectElement) => {
if (selectElement.nodeName === "INPUT") {
selectElement.value = fieldStateValue;
if (this.hubspot_iframe) {
let iframe_data = {
id: selectElement.getAttribute('id'),
value: fieldStateValue
};
this.hubspot_iframe.contentWindow.postMessage(JSON.stringify(iframe_data), "*")
}
return true;
}
if (selectElement.nodeName === "SELECT") {
let fieldDetailsOptions = selectElement.options;
for (let opt = 0; opt < fieldDetailsOptions.length; opt++) {
if (fieldDetailsOptions[opt].innerHTML === this.strip(fieldStateValue)) {
selectElement.selectedIndex = opt;
if (this.hubspot_iframe) {
let iframe_data = {
id: selectElement.getAttribute('id'),
value: fieldStateValue
};
this.hubspot_iframe.contentWindow.postMessage(JSON.stringify(iframe_data), "*")
}
else {
selectElement.dispatchEvent(new Event('change'));
}
return true;
}
}
}
return false;
}
updateStats = () => {
if (this.initialCompanyChange === 0) {
this.rl_confirmed_count -= 1;
this.initialCompanyChange = 1;
}
let payload = {
uuid: this.rl_uuid,
form_stats: {
company_confirmed: this.rl_confirmed_count,
company_not_found: this.rl_not_found_count,
company_suggested: this.rl_suggested_count
}
},
url = `${FORM_CONST.environmentUrl}api/v1/intelligent-forms/update_stats/`;
this.callAPI(payload, url, 'STATS');
}
updateSubmissionStats = () => {
let data = {};
if (this.rl_form_abandon) {
data = {
'uuid': this.rl_uuid,
form_stats: {
form_abandoned: 1
}
}
}
else {
data = {
'uuid': this.rl_uuid,
form_stats: {
form_submitted: 1
}
}
}
var regionDetails = {
regionName: this.leadLocationDetails['region'] || '',
regionCountry: this.leadLocationDetails['countryCode'] || '',
type: (this.rl_form_abandon ? 'form_abandoned' : 'form_submitted')
}
data['form_stats']['leads_by_location'] = regionDetails;
let url = `${FORM_CONST.environmentUrl}api/v1/intelligent-forms/update_stats/`;
this.callAPI(data, url, 'STATS');
}
selectOption = (option) => {
this.rl_confirmed_count++;
let selectedValueId = option.target.getAttribute('responseid'),
selectedCompany = this.rl_company_response[selectedValueId];
if (selectedValueId !== '99') {
//Set Company value
this.rl_company_element.value = selectedCompany['Company'];
if (this.hubspot_iframe) {
let iframe_data = {
id: this.rl_company_element.getAttribute('id'),
value: selectedCompany['Company']
}
this.hubspot_iframe.contentWindow.postMessage(JSON.stringify(iframe_data), "*")
}
else {
this.rl_company_element.dispatchEvent(new Event('change'));
}
//Set hidden fields
// 1. Street
if (this.rl_address_element) {
this.rl_address_element.value = selectedCompany['Address'];
if (this.hubspot_iframe) {
let iframe_data = {
id: this.rl_address_element.getAttribute('id'),
value: selectedCompany['Address']
};
this.hubspot_iframe.contentWindow.postMessage(JSON.stringify(iframe_data), "*")
}
else {
this.rl_address_element.dispatchEvent(new Event('change'));
}
}
// 2. City
if (this.rl_city_element) {
this.rl_city_element.value = selectedCompany['City'];
if (this.hubspot_iframe) {
let iframe_data = {
id: this.rl_city_element.getAttribute('id'),
value: selectedCompany['City']
};
this.hubspot_iframe.contentWindow.postMessage(JSON.stringify(iframe_data), "*")
}
else {
this.rl_city_element.dispatchEvent(new Event('change'));
}
}
// 3. State
if (this.rl_state_element) {
let is_selected = this.fillSelectField(selectedCompany['State'], this.rl_state_element);
if (!is_selected)
is_selected = this.fillSelectField(selectedCompany['StateCode'], this.rl_state_element);
this.rl_state_element.dispatchEvent(new Event('change'));
}
// 4. Zip
if (this.rl_zip_element) {
this.rl_zip_element.value = selectedCompany['Zip'];
if (this.hubspot_iframe) {
let iframe_data = {
id: this.rl_zip_element.getAttribute('id'),
value: selectedCompany['Zip']
};
this.hubspot_iframe.contentWindow.postMessage(JSON.stringify(iframe_data), "*")
}
else{
this.rl_zip_element.dispatchEvent(new Event('change'));
}
}
// 5. Country
if (this.rl_country_element) {
// let is_set = this.fillSelectField(selectedCompany['Country'], this.rl_country_element);
let is_selected = this.fillSelectField(selectedCompany['Country'], this.rl_country_element);
if (!is_selected)
is_selected = this.fillSelectField(selectedCompany['CountryCode'], this.rl_country_element);
this.rl_country_element.dispatchEvent(new Event('change'));
if (!this.rl_state_element) {
if (this.rl_form_settings.hasOwnProperty('rl_State')) {
this.rl_state_element = document.getElementById(this.rl_form_settings['rl_State']['html_id']);
if (this.rl_state_element) {
let is_selected = this.fillSelectField(selectedCompany['State'], this.rl_state_element);
if (!is_selected)
this.fillSelectField(selectedCompany['StateCode'], this.rl_state_element);
}
this.rl_state_element.dispatchEvent(new Event('change'));
}
}
}
}
this.rl_company_suggestions.style.display = "none";
this.updateStats();
}
createJsonObject = (element, elementType) => {
let rl_fieldsObject = {}, noName = 0, rl_fieldName = '', rl_fieldId = '';
for (let i = 0; i < element.length; i++) {
switch (this.rl_form_type) {
case 'Hubspot':
if (elementType === 'form' && !this.isPopUpHubspot) {
rl_fieldName = element[i].getAttribute('name')
rl_fieldId = element[i].getAttribute('data-form-id')
}
else {
rl_fieldName = element[i].getAttribute('name');
rl_fieldId = element[i].getAttribute('id');
}
break;
case 'Marketo':
case 'Salesforce':
rl_fieldName = element[i].getAttribute('name');
rl_fieldId = element[i].getAttribute('id');
break;
case 'Instapage':
if (elementType === 'form') {
// rl_fieldName = element[i].getAttribute('name')
rl_fieldId = element[i].getAttribute('data-id')
rl_fieldName = `Form-${rl_fieldId}`
}
else {
let form_name = element[i].form.getAttribute('data-id');
rl_fieldName = `form-${form_name} : ${element[i].getAttribute('name')}`;
rl_fieldId = element[i].getAttribute('name');
}
break;
case 'Pardot':
if (elementType === 'form')
rl_fieldId = rl_fieldName = 'pardot-form';
else if (elementType === 'hiddenField') {
let KNOWN_CLASS = ['form-field', 'pd-text', 'required', 'pd-hidden', 'pd-select',
'form-field-master', 'form-field-slave', 'dependentFieldSlave'];
if (element[i].parentNode.classList.contains('pd-hidden')) {
rl_fieldId = element[i].parentNode.classList.value.trim();
KNOWN_CLASS.forEach(kc => {
rl_fieldId = rl_fieldId.replace(kc, '').trim();
});
rl_fieldName = rl_fieldId;
}
else
break;
}
else if (elementType === 'button' || elementType === 'inputButton') {
rl_fieldName = element[i].getAttribute('value');
rl_fieldId = element[i].getAttribute('id');
}
else {
let KNOWN_CLASS = ['form-field', 'pd-text', 'required', 'pd-hidden', 'pd-select',
'form-field-master', 'form-field-slave', 'dependentFieldSlave'];
rl_fieldId = element[i].parentNode.classList.value.trim();
KNOWN_CLASS.forEach(kc => {
rl_fieldId = rl_fieldId.replace(kc, '').trim();
});
rl_fieldName = element[i].labels[0].innerText;
}
// if (elementType === 'textAreaField' || elementType === 'textField') {
// }
if (rl_fieldName && !rl_fieldId) rl_fieldId = rl_fieldName;
break;
}
if (rl_fieldName) {
if (rl_fieldId) {
rl_fieldsObject[rl_fieldName] = rl_fieldId;
}
else {
rl_fieldsObject[rl_fieldName] = rl_fieldName;
}
} else {
if (rl_fieldId) {
noName += 1;
rl_fieldsObject[`${elementType} ${noName}`] = rl_fieldId;
}
}
}
return rl_fieldsObject;
}
detectHubspotPopUp = (newForm = true) => {
const target = document.body;
const options = {
childList: true,
subtree: true,
};
const observer = new MutationObserver(callback);
let self = this;
function callback(mutations) {
mutations.forEach(({ attributeName, oldValue, target }) => {
let hsForm = target.querySelector('form[id*="hsPopUpForm"]');
if (hsForm) {
console.log("Got the form... stop looking!");
observer.disconnect();
self.hsPopUpForm = hsForm;
self.isPopUpHubspot = true;
newForm ? self.processNewTask(true) : self.addRingleadEventListeners(true);
}
});
};
observer.observe(target, options);
};
findHubspotForm = (newForm) => {
let found = true;
if (newForm) {
let hsForm = document.querySelector('iframe[id*="hs-form-iframe"]');
if(!hsForm || hsForm.length === 0){
hsForm = document.querySelectorAll('form[action*="forms.hsforms.com"');
}
if (!hsForm || hsForm.length === 0){
this.detectHubspotPopUp(newForm);
found = false;
}
}
else{
found = false;
let hsForm = document.querySelector('iframe[id*="hs-form-iframe"]');
if(hsForm && hsForm.length !== 0) {
hsForm = hsForm.contentDocument;
let hsFormId = hsForm.querySelector(`form[data-form-id="${this.rl_form_settings.rl_Form['html_id']}"]`);
if (hsFormId) {
found = true;
}
}
if(!found) {
hsForm = document.querySelectorAll('form[action*="forms.hsforms.com"');
if (hsForm.length !== 0) {
try{
for (let idx in hsForm) {
let dataFormId = hsForm[idx].getAttribute('data-form-id');
if (dataFormId === this.rl_form_settings.rl_Form['html_id']){
found = true;
return found;
}
}
}
catch (e) {
console.log(e)
}
}
}
if (!found)
this.detectHubspotPopUp(newForm);
}
return found;
}
processNewTask = (hsFormDetected = false) => {
if (this.rl_form_type === 'Hubspot' && !hsFormDetected) {
let found = this.findHubspotForm(true);
if (!found) return;
}
let pageFields = {}, rl_formSubmitObject = {}, fieldsObject = {},
payload = { 'uuid': this.rl_uuid };
for (const [k, v] of Object.entries(FORM_CONST.inputTags)) {
pageFields[k] = this.getPageFields(v[0], v[1]);
}
[pageFields.rl_allInputButtonFields, pageFields.rl_allButtons, pageFields.rl_allButtons2].forEach((buttonTag) =>
rl_formSubmitObject = Object.assign({}, rl_formSubmitObject, this.findFormSubmitButtonPairs(buttonTag)));
for (const [k, v] of Object.entries(FORM_CONST.inputTagName)) {
fieldsObject = Object.assign({}, fieldsObject, this.createJsonObject(pageFields[k], v));
}
// handle form object separately
let formsObject = this.isPopUpHubspot ?
this.createJsonObject([this.hsPopUpForm], 'form') :
this.createJsonObject(pageFields.rl_allForms, 'form');
for (var key in formsObject) fieldsObject['form_id'] = formsObject[key];
fieldsObject['all_forms'] = formsObject;
fieldsObject['rl_form_button'] = rl_formSubmitObject;
payload['form_page_fields'] = fieldsObject;
payload['website'] = window.location.href;
payload['form_details'] = formsObject;
let url = `${FORM_CONST.environmentUrl}api/v1/intelligent-forms/create_new/`;
this.callAPI(payload, url, 'NEW_TASK', true);
}
resolveRingleadFormSettings = (hsFormDetected) => {
if (this.rl_form_settings.hasOwnProperty("rl_Form")) {
let formId = this.rl_form_settings['rl_Form']['html_id'];
if (formId)
this.rl_form_element = document.getElementById(formId);
}
switch (this.rl_form_type) {
case 'Eloqua':
case 'Salesforce':
this.sfFormSettings();
break;
case 'Pardot':
this.pardotFormSettings();
break;
case 'Hubspot':
this.hubspotFormSettings(hsFormDetected);
break;
case 'Marketo':
this.mktoFormSettings();
break;
case 'Instapage':
this.rl_form_element = this.rl_form_element.getElementsByTagName('form')[0];
this.instapageFormSettings();
break;
default:
console.log(`No support for form type: ${this.form_type}`);
}
}
sfFormSettings = () => {
const formSettings = FORM_CONST.formSettings;
for (let element in formSettings) {
if (this.rl_form_settings.hasOwnProperty(element) && element !== 'rl_Form') {
let elementHtmlId = this.rl_form_settings[element]['html_id'];
if (this.rl_form_element)
this[formSettings[element]] = this.rl_form_element.elements[elementHtmlId];
else
this[formSettings[element]] = document.getElementById(elementHtmlId);
}
}
}
hubspotFormSettings = (hsFormDetected) => {
const formSettings = FORM_CONST.formSettings;
if (!hsFormDetected) {
let found = this.findHubspotForm(false);
if (!found) return;
}
let hsFormContent = document;
if (this.isPopUpHubspot) {
hsFormContent = this.hsPopUpForm;
}
else {
let hsIFrame = document.querySelector('iframe[id*="hs-form-iframe"]');
if (hsIFrame && hsIFrame.length !== 0)
hsFormContent = hsIFrame.contentDocument;
}
if (this.rl_form_settings.hasOwnProperty('rl_Form'))
this.rl_form_element = this.isPopUpHubspot ? this.hsPopUpForm :
hsFormContent.querySelector(`[data-form-id="${this.rl_form_settings['rl_Form']['html_id']}"]`);
for (let element in formSettings) {
if (this.rl_form_settings.hasOwnProperty(element) && element !== 'rl_Form') {
let elementHtmlId = this.rl_form_settings[element]['form_field_name'];
if (this.rl_form_element) {
console.log(this.rl_form_element.querySelector(`[name="${elementHtmlId}"]`));
this[formSettings[element]] = this.rl_form_element.querySelector(`[name="${elementHtmlId}"]`);
}
else
this[formSettings[element]] = hsFormContent.querySelector(`[name="${elementHtmlId}"]`);
}
}
}
pardotFormSettings = () => {
const formSettings = FORM_CONST.formSettings;
for (let element in formSettings) {
if (this.rl_form_settings.hasOwnProperty(element) && element !== 'rl_Form') {
let elementHtmlId = this.rl_form_settings[element]['html_id'], elementPTag = null;
if (this.rl_form_element)
elementPTag = this.rl_form_element.querySelector(`p[class*="${elementHtmlId}"]`);
else
elementPTag = document.querySelector(`#pardot-form p[class*="${elementHtmlId}"]`);
if (elementPTag) {
let ele = elementPTag.getElementsByTagName('input')[0];
if (!ele)
ele = elementPTag.getElementsByTagName('select')[0];
if (!ele)
ele = elementPTag.getElementsByTagName('textarea')[0];
this[formSettings[element]] = ele;
}
}
}
}
mktoFormSettings = () => {
this.sfFormSettings()
};
instapageFormSettings = () => {
const formSettings = FORM_CONST.formSettings;
for (let element in formSettings) {
if (this.rl_form_settings.hasOwnProperty(element) && element !== 'rl_Form') {
let elementHtmlId = this.rl_form_settings[element]['html_id'];
if (this.rl_form_element) {
this[formSettings[element]] = this.rl_form_element.elements[elementHtmlId];
}
else
this[formSettings[element]] = document.getElementById(elementHtmlId);
}
}
};
addRingleadHtmlElements = (htmlId) => {
let next_sibling;
if(!this.rl_company_element){
this.rl_company_element = document.getElementById(htmlId);
}
try {
next_sibling = this.rl_company_element.nextSibling;
}
catch (e) {
console.log('Something went wrong. Setting up fields failed. Please try again later');
return;
}
//create div element for results
this.rl_company_suggestions = document.createElement("div");
this.rl_company_suggestions.setAttribute("class", "rl_results_div");
if (next_sibling) {
this.rl_company_element.parentNode.insertBefore(this.rl_company_suggestions, next_sibling);
} else {
this.rl_company_element.parentNode.appendChild(this.rl_company_suggestions);
}
//Create Unordered List to display results
this.rl_company_suggestions_list = document.createElement("ul");
this.rl_company_suggestions_list.setAttribute("class", "rl_suggestions");
this.rl_company_suggestions.appendChild(this.rl_company_suggestions_list);
//Add events to company fields
this.rl_company_element.setAttribute("list", "rl_suggestions");
this.rl_company_element.addEventListener('keyup', this.Lookup);
if(this.rl_email_element) this.rl_email_element.addEventListener('blur', this.validateDomain);
this.rl_company_element.addEventListener('blur', this.updateStats);
//Add Footer for suggestions
let rl_company_footer = document.createElement('div');
rl_company_footer.setAttribute("class", "rl_company_footer");
rl_company_footer.style.textAlign = "center";
rl_company_footer.style.fontWeight = "bold";
let rl_company_logo = document.createElement('span');
rl_company_logo.innerHTML = FORM_CONST.logo;
rl_company_footer.appendChild(rl_company_logo);
this.rl_company_suggestions.appendChild(rl_company_footer);
//Add Div Hide if he clicks on document
document.addEventListener('click', this.hideResultDiv);
//before unload to track form abandon
window.addEventListener("beforeunload", this.updateSubmissionStats);
window.addEventListener("keydown", this.tabOut);
let { rl_allInputButtonFields, rl_allButtons } = FORM_CONST.inputTags;
[rl_allInputButtonFields, rl_allButtons].forEach((buttonTag) => {
let rl_btn = this.getPageFields(buttonTag[0], buttonTag[1]);
if (rl_btn) {
for (let i = 0; i < rl_btn.length; i++) {
let button = rl_btn[i];
button.addEventListener('click', this.formSubmitAction);
}
}
});
//Hide Div initially
this.rl_company_suggestions.style.display = "none";
//Create styles dynamically
let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = this.rl_company_suggetions_style;
document.getElementsByTagName('head')[0].appendChild(style);
if (this.rl_form_type === 'Hubspot' && !this.isPopUpHubspot) {
let hsIFrame = document.querySelector('iframe[id*="hs-form-iframe"]');
if (hsIFrame && hsIFrame.length !== 0) {
let hsFormContent = hsIFrame.contentDocument;
hsFormContent.getElementsByTagName('head')[0].appendChild(style);
}
}
//Add KickFire Details
let companyDetails = null;
if (this.companyIpDetails) {
companyDetails = this.companyIpDetails[0];
}
if (companyDetails && companyDetails.hasOwnProperty('isISP')) {
if (!companyDetails["isISP"]) {
this.rl_suggested_count += 1;
this.rl_confirmed_count += 1;
this.initialCompanyChange = 0;
this.rl_company_element.value = companyDetails.name;
if (this.rl_address_element)
this.rl_address_element.value = companyDetails.street;
if (this.rl_city_element)
this.rl_city_element.value = companyDetails.city;
if (this.rl_state_element) {
try {
this.fillSelectField(companyDetails.region, this.rl_state_element);
} catch (e) {
console.log('Invalid value for state field');
}
}
if (this.rl_zip_element)
this.rl_zip_element.value = companyDetails.postal;
if (this.rl_country_element) {
try {
this.fillSelectField(companyDetails.country, this.rl_country_element);
} catch (e) {
console.log('Invalid value for state field');
}
}
}
}
}
doLookup = () => {
let display_property = this.rl_company_suggestions.style.display;
if (display_property != "none") {
this.rl_company_suggestions.style.display = "none";
}
var rlCompanyValue = this.rl_company_element.value;
if (rlCompanyValue.length < 3) {
if (display_property != "none") {
this.rl_company_suggestions.style.display = "none";
}
return;
}
//Clear Previous Company Suggestions
this.rl_company_suggestions_list.innerHTML = "";
//Call Ringlead Intelligent Forms API
let url = `${FORM_CONST.environmentUrl}api/v1/intelligent-forms/search/`;
var companyRequest = {
"rl_company_id": 1000,
"companyName": rlCompanyValue,
"state": this.leadLocationDetails ? this.leadLocationDetails.region : '',
"stateName": this.leadLocationDetails ? this.leadLocationDetails.regionName : '',
"country": this.leadLocationDetails ? this.leadLocationDetails.country : '',
"countryName": this.leadLocationDetails ? this.leadLocationDetails.countryCode : '',
"uuid": this.rl_uuid,
"token": localStorage['token'] || ''
};
this.callAPI(companyRequest, url, 'SEARCH');
}
Lookup = (event) => {
let charCode = event["keyCode"];
let rlCompanyValue = this.rl_company_element.value;
if (rlCompanyValue.length < 3) {
let display_property = this.rl_company_suggestions.style.display;
this.rl_company_response = [];
if (display_property != "none") {
this.rl_company_suggestions.style.display = "none";
}
return;
}
if (charCode != 9)
this.clearFieldValues();
setTimeout(this.doLookup, 500);
}
validateDomain = (event) => {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
setTimeout(() => {
let rlEmailValue = this.rl_email_element.value;
if (!re.test(String(rlEmailValue).toLowerCase())) alert("Please enter valid email.")
if (this.rl_form_settings.email_domains_to_block){
this.rl_form_settings.email_domains_to_block.forEach(dm => {
if (rlEmailValue.endsWith(dm)) alert("Please enter work/corporate email.")
})
}
}, 500)
}
start = () => {
console.log('Checking intelligent form task status...');
let payload = {
"uuid": this.rl_uuid
},
url = `${FORM_CONST.environmentUrl}api/v1/intelligent-forms/check_status/`;
this.callAPI(payload, url, 'TASK_STATUS', true);
}
}
let RingLeadIntelligentForm = {
init: (uuid) => {
window.onload = () => {
setTimeout(function () {
let intForm = new IntelligentForm(uuid);
intForm.start();
}, 2000);
}
}
}