window.ApexChat = window.ApexChat || {};
window.ApexChat.init = function () {
    try {
        // make sure this only runs once
        if (window.ApexChat && window.ApexChat.invitationv2run) {
            return;
        }
        window.ApexChat = window.ApexChat || {};
        window.ApexChat.invitationv2run = true;

        var fromQueryString = function (key) {
            var parts = window.location.search.substring(1).split('&');
            for (var i = 0; i < parts.length; i++) {
                var pair = parts[i].split('=');
                if (pair[0] == key) {
                    return pair[1];
                }
            }
            return '';
        };

        var readCookie = function (name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        };

        var createCookie = function (name, value, minutes) {
            if (minutes) {
                var date = new Date();
                date.setTime(date.getTime() + (minutes * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        };

        var head = document.getElementsByTagName('head')[0] || document.documentElement,
	        script = document.createElement('script'),
	        allScripts = document.getElementsByTagName('script'),
            companyId = '',
            query = '',
	        domain = document.location.protocol + 'http://www.apexchat.net/';

        for (var i = 0; i < allScripts.length; i++) {
            var s = allScripts[i];
            if (s.src.indexOf('invitation.ashx') > -1 || s.src.indexOf('apexchat.js') > -1) {
                var a = document.createElement('a');
                a.href = s.src;
                if (a.host) {
                    domain = document.location.protocol + '//' + a.host + '/';
                } else {
                    domain = '';
                }
                var parts = a.search.substring(1).split('&');
                for (var j = 0; j < parts.length; j++) {
                    var keyValues = parts[j].split('=');
                    if (keyValues[0].toLowerCase() == 'company') {
                        companyId = keyValues[1];
                    } else {
                        query += '&' + parts[j];
                    }
                }
                break;
            }
        }
        var VISITOR_ID_COOKIE = 'apexchat_visitor_id';
        var AGENT_ALIAS_ID_COOKIE = 'apexchat_agent_alias_id';
        var OPERATOR_ID_COOKIE = 'apexchat_operator_id';
        var PROFILE_ID_COOKIE = 'apexchat_profile_id';

        var visitorId = readCookie(VISITOR_ID_COOKIE) || 0;
        var agentAliasId = readCookie(AGENT_ALIAS_ID_COOKIE) || 0;
        var operatorId = readCookie(OPERATOR_ID_COOKIE) || 0;
        var profileId = readCookie(PROFILE_ID_COOKIE) || 0;

        // google ad - normally has a utm_source, but for the "automatic" ones may have the gclid
        // https://support.google.com/analytics/answer/1033981?hl=en
        var isGoogleAdSource = window.location.href.indexOf('gclid=') > -1 || window.location.href.indexOf('utm_source=') > -1
        // also, let's pull a few params
        var gSource = fromQueryString('utm_source'), gMedium = fromQueryString('utm_medium'), gCampaign = fromQueryString('utm_campaign'), gClid = fromQueryString('gclid');


        script.src = domain + 'scripts/invitation2.ashx?company=' + companyId +
            '&visitorId=' + visitorId +
            '&agentAliasId=' + agentAliasId +
            '&operatorId=' + operatorId +
            '&profileId=' + profileId +
            '&gclid=' + gClid +
            '&gs=' + gSource +
            '&gm=' + gMedium +
            '&gc=' + gCampaign +
            '&originalReferrer=' + encodeURIComponent(document.referrer).substring(0, 500) + 
            query;
        head.insertBefore(script, head.firstChild);

        // wait for the invitation to be ready to show
        var ready = function () {
            if (window.ApexChat && ApexChat.Invitation && ApexChat.Invitation.ready) {
                ApexChat.Invitation.ready();
            } else {
                window.setTimeout(ready, 50);
            }
        };
        ready();

    } catch (e) {
        window.ApexChat.invitationv2run = false;
        window.setTimeout(function () {
            window.ApexChat.init();
        }, 1000);

        if (window && window.console) {
            window.console.error(e);
        }
    }
};
window.ApexChat.init();