﻿//keep these global
matchedSource = f_getSessionStorage('matchedSource');
matchedSourceId = f_getSessionStorage('matchedSourceId');
referralPhoneNum = f_getSessionStorage('referralPhoneNum');
trackingNumber = "";

function tryMatchingSourceFromReferrerUrl(document, sourcesList) {
    
    if(document == null || document == undefined)
    {
        throw new Error("tryMatchingSourceFromReferrerUrl: document must not be null");
    }
    if(sourcesList == null || sourcesList == undefined)
    {
        throw new Error("tryMatchingSourceFromReferrerUrl: sourcesList must not be null");
    }

    if (!matchedSource || !firstTouchEnabled) {
        var referrerUrl = f_getSessionStorage('referrerUrl');
        if (!referrerUrl && document.referrer && document.referrer.indexOf(document.domain) == -1) {
            referrerUrl = document.referrer;
            f_setSessionStorage('referrerUrl', referrerUrl);
        }

        if (referrerUrl) {
            hostname = (new URL(referrerUrl)).hostname;
            
            var referralFound = false;

            $(sourcesList).each(function () {
                if (hostname && hostname.match(/[^.]+.[^.]+(?=\.*$)/) && this.DisplayName.toLowerCase().indexOf(hostname.match(/[^.]+.[^.]+(?=\.*$)/).toString().toLowerCase()) > -1) {
                    matchedSource = encodeURIComponent(this.DisplayName);
                    matchedSourceId = this.PmSourceId;
                    f_setSessionStorage('matchedSource', matchedSource);
                    f_setSessionStorage('matchedSourceId', matchedSourceId);
                    referralFound = true;
                }
            });
            if (referralFound == false){
                $(sourcesList).each(function () {
                    //the regex will strip down to words so www.google.com -> google
                    if (hostname && this.DisplayName.toLowerCase().indexOf(hostname.match(/\w+(?=\.[^.]*$)/).toString().toLowerCase()) > -1) {
                        matchedSource = encodeURIComponent(this.DisplayName);
                        matchedSourceId = this.PmSourceId;
                        f_setSessionStorage('matchedSource', matchedSource);
                        f_setSessionStorage('matchedSourceId', matchedSourceId);
                    }
                });
            }
        }
    }
}

function commonDataOnReady(document, sourcesList) {
    var referrerUrl = f_getSessionStorage('referrerUrl');
    var domainUrl = document.location.host.match(/[^.]+.[^.]+(?=\.*$)/).toString();

    validateReferralUrl(document, referrerUrl, domainUrl);

    var ilm = checkForIlm(sourcesList);
    var utmKnock = false;
    var utm = false; 
    var cid = false;
    
    if (!ilm) {
        utmKnock = checkForUtmKnock(sourcesList);
    }

    if (!ilm && !utmKnock) {
        utm = checkForUtm(sourcesList, utmConfigInfo, utm);
    }

    if (!ilm && !utmKnock && !utm) {
        cid = checkForCid(sourcesList, cid);
    }

    if (!ilm && !utmKnock) {
        setDynamicPhoneNumber(document, referrerUrl, cid, utm);
    }
}

function validateReferralUrl(document, referrerUrl, domainUrl) {
    if (!referrerUrl && document.referrer) {
        f_setSessionStorage('referrerUrl', document.referrer);
        referrerUrl = document.referrer;
    } else if (referrerUrl && referrerUrl.indexOf(domainUrl) == -1 && document.referrer && document.referrer.indexOf(domainUrl) == -1 && referrerUrl != document.referrer) {
        f_setSessionStorage('referrerUrl', document.referrer);
        referrerUrl = document.referrer;
    }
}

function checkForIlm(sourcesList) {
    var ilmValue = f_getAnalyticsUserValueFromCookie('RP_LSWS_ILM');
    ilmValue = ilmValue ? ilmValue.replace(' ', '').toLowerCase() : "";
    let containsApartments = false;
    let apartmentsDisplayName = '';
    let apartmentsSourceId = '';

    if (ilmValue != "") {
        var ilmSourceSet = false;
        let sourceVal = '';
        $(sourcesList).each(function () {
            sourceVal = this && this.DisplayName ? this.DisplayName.replace(' ', '').toLowerCase() : '';

            //Keep track of Apartments.com if it's in the sources list'
            if (sourceVal.indexOf('apartments.com') > -1) {
                containsApartments = true;
                apartmentsDisplayName = this.DisplayName;
                apartmentsSourceId = this.PmSourceId;
            }

            if (sourceVal.indexOf(ilmValue) > -1) {
                matchedSource = encodeURIComponent(this.DisplayName);
                f_setSessionStorage('matchedSource', encodeURIComponent(this.DisplayName));
                matchedSourceId = this.PmSourceId;
                f_setSessionStorage('matchedSourceId', this.PmSourceId);
                ilmSourceSet = true;
                return;
            }
        });

        //If we didn't find a matched source for the ILM parameter and the ILM value is Costar, then set to Apartments.com if it is in the source list'
        if (!ilmSourceSet && ilmValue.indexOf('costar') > -1 && containsApartments) {
            matchedSource = encodeURIComponent(apartmentsDisplayName);
            f_setSessionStorage('matchedSource', encodeURIComponent(apartmentsDisplayName));
            matchedSourceId = apartmentsSourceId;
            f_setSessionStorage('matchedSourceId', apartmentsSourceId);
            ilmSourceSet = true;
        }

        if (ilmSourceSet) {
            iml = true;
            return true;
        }   else {
            return false;
        }
    } else {
        return false;
    }
}

function checkForUtmKnock(sourcesList) {
    var knockValue = f_getAnalyticsUserValueFromCookie('RP_LSWS_UTM_KNOCK');
    knockValue = knockValue ? knockValue : "";
    if (knockValue != "") {
        var knockSourceSet = false;
        $(sourcesList).each(function () {
            if (this && this.PmSourceId == knockValue) {
                matchedSource = encodeURIComponent(this.DisplayName);
                f_setSessionStorage('matchedSource', encodeURIComponent(this.DisplayName));
                matchedSourceId = this.PmSourceId;
                f_setSessionStorage('matchedSourceId', this.PmSourceId);
                knockSourceSet = true;
                return;
            }
        });
        if (knockSourceSet) {
            utmKnock = true;
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function checkForUtm(sourcesList, utmConfigInfo, utm) {
    var utmValue = f_getAnalyticsUserValueFromCookie('RP_LSWS_UTM');
    
    utmValue = utmValue ? utmValue : "";
    if (utmValue != "") {
        utm = true;
        var utmValueArray = utmValue.split("&");
        var utmSource;
        var utmMedium;
        var utmCampaign;
        utmValueArray.forEach(function(value) {
            if (value.indexOf("Source=") > -1) {
                utmSource = value.substring(value.indexOf("Source=") + 7, value.length);
            }
            else if (value.indexOf("Medium=") > -1) {
                utmMedium = value.substring(value.indexOf("Medium=") + 7, value.length);
            }
            else if (value.indexOf("Campaign=") > -1) {
                utmCampaign = value.substring(value.indexOf("Campaign=") + 9, value.length);
            }
        }); 
    }

    if (utm) {
        var utmSourceSet = false;
        $(sourcesList).each(function () {
            if (this && this.DisplayName && this.DisplayName.replace(' ', '').toLowerCase().indexOf(utmSource.replace(' ', '').toLowerCase()) > -1) {
                matchedSource = encodeURIComponent(this.DisplayName);
                f_setSessionStorage('matchedSource', encodeURIComponent(this.DisplayName));
                matchedSourceId = this.PmSourceId;
                f_setSessionStorage('matchedSourceId', this.PmSourceId);
                return;
            } 
        });
        try {
            if (utmConfigInfo.indexOf("Error") == 0) {
                console.error('Error getting UTM config from API: ', utmConfigInfo);
            }
            else {
                if (utmConfigInfo != "") {
                    var utmConfigurations = JSON.parse(utmConfigInfo);
                    $(utmConfigurations.response.utmConfigurations).each(function () {
                        if (this.utmSource.toLowerCase() == utmSource.toLowerCase() &&
                            this.utmMedium.toLowerCase() == utmMedium.toLowerCase() &&
                            this.utmCampaign.toLowerCase() == utmCampaign.toLowerCase()) {
                            trackingNumber = this.inboundLeadConfig.trackingNumber;
                            setUtmPhoneNumber(trackingNumber);
                            utmSourceSet = true;
                            return;
                        }
                    });
                }
            }
        } 
        catch(e){
            console.error("Error parsing the UTM config object. ", e.Message);
        }
        if (utmSourceSet) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function setUtmPhoneNumber(trackingNumber) {
    if (trackingNumber != "") {
        if (trackingNumber.length == 10) {
            trackingNumber = trackingNumber.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
        }
        if (trackingNumber.length == 11) {
            trackingNumber = trackingNumber.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
        }
        setSEONumber(trackingNumber);
    }
}

function checkForCid(sourcesList, cid) {
    var cidValue = f_getAnalyticsUserValueFromCookie('RP_LSWS_SEM');
        cidValue = cidValue ? cidValue : "";
    if (cidValue != "")
        cid = true;
    
    var cidSourceSet = false;
    if (cid) {
        $(sourcesList).each(function () {
            if (this && this.DisplayName && this.DisplayName.replace(' ', '').toLowerCase().indexOf(cidValue.replace(' ', '').toLowerCase()) > -1) {
                matchedSource = encodeURIComponent(this.DisplayName);
                f_setSessionStorage('matchedSource', encodeURIComponent(this.DisplayName));
                matchedSourceId = this.PmSourceId;
                f_setSessionStorage('matchedSourceId', this.PmSourceId);
                cidSourceSet = true;
                return;
            }
        });

        if (!cidSourceSet) {
            $(sourcesList).each(function () {
                if (this && this.DisplayName && this.DisplayName.replace(' ', '').toLowerCase().indexOf('propertywebsite') > -1) {
                    matchedSource = encodeURIComponent(this.DisplayName);
                    f_setSessionStorage('matchedSource', encodeURIComponent(this.DisplayName));
                    matchedSourceId = this.PmSourceId;
                    f_setSessionStorage('matchedSourceId', this.PmSourceId);
                    cidSourceSet = true;
                    return;
                }
            });
        }
    }
    if (cidSourceSet) {
        return true;
    } else {
        return false;
    }
}

function setDynamicPhoneNumber(document, referrerUrl, cid, utm, jsrxEnabled) {
    var changePhoneNum = false;
    if (!cid && !googleCallTrackingEnabled && !jsrxEnabled) {
        changePhoneNum = true;
        console.log('set changePhoneNum to ' + changePhoneNum)
    }
    if (!utm || trackingNumber == "") {
        if (changePhoneNum && ((referrerUrl && referrerUrl.indexOf('http') > -1) || referralPhoneNum)) {
            var a = document.createElement('a');
            a.setAttribute('href', referrerUrl);
            var referrerHostname = a.hostname.match(/[^.]+.[^.]+(?=\.*$)/).toString();
            var phoneNumberList = [];
            if (referralPhoneNum)
                phoneNumberList.push(referralPhoneNum);
            else if (leadObj) {
                $(leadList).each(function(i, v) {
                    if (v.Domain.toLowerCase().indexOf(referrerHostname.toLowerCase()) > -1) {
                        $(leadObj).each(function() {
                            if (this.LeadChannelName && this.LeadChannelName.toLowerCase().indexOf(v.hcLeadChannelName.toLowerCase()) > -1) {
                                phoneNumberList.push(this.PhoneNumber);
                                f_setSessionStorage('referralPhoneNum', this.PhoneNumber);
                            }
                        });
                    }
                });
            }

            if (phoneNumberList.length == 1) {
                setSEONumber(phoneNumberList[0]);
            } else if (phoneNumberList.length == 0) {
                if (referrerHostname.indexOf('.') > -1)
                    referrerHostname = referrerHostname.substring(0, referrerHostname.indexOf('.'));

                $(leadObj).each(function (i, v) {
                    if (v.LeadChannelName && v.LeadChannelName.toLowerCase().indexOf(referrerHostname.toLowerCase()) > -1 && v.PhoneNumber != null) {
                            phoneNumberList.push(this.PhoneNumber);
                            f_setSessionStorage('referralPhoneNum', this.PhoneNumber);
                        }
                    });

                if (phoneNumberList.length == 1) {
                    setSEONumber(phoneNumberList[0]);
                }
            }
        }
    }
}



try{
    module.exports.tryMatchingSourceFromReferrerUrl = tryMatchingSourceFromReferrerUrl;
    module.exports.commonDataOnReady = commonDataOnReady;
    module.exports.validateReferralUrl = validateReferralUrl;
    module.exports.checkForUtm = checkForUtm;
    module.exports.setUtmPhoneNumber = setUtmPhoneNumber;
    module.exports.checkForCid = checkForCid;
    module.exports.setDynamicPhoneNumber = setDynamicPhoneNumber;
    module.exports.checkForIlm = checkForIlm;
    module.exports.checkForUtmKnock = checkForUtmKnock;
}catch(e){/*shhh ignore errors*/}
