function getVendorCompanyId(application) {
let vendorItem = application
&& application.relatedContent.details.vendor.items
&& application.relatedContent.details.vendor.items.length > 0
? application.relatedContent.details.vendor.items[0].href
: null;
if(vendorItem === null) {
return vendorItem;
}
let regex = /[?&]([^=#]+)=([^&#]*)/g;
let match;
let params = {};
while ((match = regex.exec(vendorItem))) {
params[match[1]] = match[2];
}
let vendorCompanyId = params['vendor'];
return vendorCompanyId;
}

function callCompanyAssociationAPI(application) {
let companyAssociationUrl = '/api/custom/adp/appReseller/v1/companyAssociations';
fetch( companyAssociationUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'AD-Tenant': 'ADP'
},
body:JSON.stringify({
customerCompanyId: window.UserInfo && window.UserInfo.company_id ? window.UserInfo.company_id: null,
resellerCompanyId: getVendorCompanyId(application)
})
}).then(response => {
if (!response.ok) {
let error = response.status;
return Promise.reject(error);
}
return response.json()
}).then(function(data){
console.log("Association creation successful for id "+ data.id);
}).catch((error) => {
console.log(error)
// Error not to be notified to end user
});
}

function registerProxyFetchCall(application) {
window.isEditionLeadGenClicked = false;
window.addEventListener('message', event => {
if (event.data.message === 'openContactUs') {
if(window.isEditionLeadGenClicked) {
callCompanyAssociationAPI(application);
window.isEditionLeadGenClicked = false;
}
}
});
}

function registerEventClick() {
window.isEditionLeadGenClicked = false;
document.addEventListener('click', function (event) {
if(event.target && (event.target.classList && event.target.classList.contains('js-edition-request-quote-button')
|| (event.target.parentElement && event.target.parentElement.classList
&& event.target.parentElement.classList.contains('js-edition-request-quote-button')))) {
window.isEditionLeadGenClicked = true;
}
}, true);
}

registerEventClick();