window.onload = function () {
    window.addEventListener('cookieBannerOpenFirstTime', function (event) {  // Event = Cookie Preferences Banner has been opened first time
        // Call GA function (Cookie Preferences Banner has been opened first time)
	ga('send', 'pageview','/Cookie banner modal');
        console.log('Cookie Preferences Center has been opened first time, call GA');
    });
    var cookieManager = new CookieManager();
    window.addEventListener('cookiePreferencesSubmitedFirstTime', function (event) {  // Event = Cookie Preferences were submited first time
        // Call GA function (Cookie Preferences Banner has been opened first time)
        ga('send', 'pageview','/Cookie banner modal- submit-preferences');
	console.log('Cookie Preferences were submited first time, call GA');
    });
}

/* Cookie Manager */
function CookieManager() {

    const INIT_PREFERENCES_CENTER = "initCookiePreferencesCenter"; // cookie's name for creating GA events
    const NUM_ADVERTISING = 3; // positive answer for advertising cookie = 3
    const NAME_TRUSTARC_COOKIE = "notice_preferences"; // cookie's name from TrustArc
    const VALUE_ALLOWING_ADVERT_COOKIE = "2:"; // value of advertising cookie from TrustArc
    const DOMAIN_NAME = "ascap.com"; // domain's name

    initFirstVisitEvent(); // init events for GA
    initConsentManager(); // initialisation of cookie preferences center

    /* isItFirstVisitPage
     * @return {Boolen} = 'false': It is not first visit of website
     *                    'true': It's first visit of website
     */
    function isItFirstVisitPage() {
        return isEmptyOrNull(readCookie(INIT_PREFERENCES_CENTER)); // Has website ever been opened by the client
    }
   /* isPreferncesCookieNotSubmited
    * @return {Boolen} = 'false': Preferences Cookie was submited
    *                    'true': Preferences Cookie was not submited
    */
    function isPreferncesCookieNotSubmited() {
        return readCookie(INIT_PREFERENCES_CENTER) == 'false'; // Cookie Preferences were not submited
    }
    /* initFirstVisitEvent - Init Event for GA
    */
    function initFirstVisitEvent() {
        if (isItFirstVisitPage()) {
            createCookie(INIT_PREFERENCES_CENTER, "false", 90); // Website has been opened first time -> create cookie 'initPreferencesCenter'
         // Create Event "Cookie Preferences Banner has been opened first time"
            var cookieBannerEvent = document.createEvent("Event");
            cookieBannerEvent.initEvent("cookieBannerOpenFirstTime", true, true);
            document.dispatchEvent(cookieBannerEvent);
        }
    }
    /* getConsentManagerCookie - Get Consent Manager Cookie
     * @return {String}
     */
    function getConsentManagerCookie() {
        return readCookie(NAME_TRUSTARC_COOKIE);
    }
    /* getAdvertisingCookiePreference - Get advertising cookie preference.
     * @return {Boolen} = 'false': Advertising is not allowed.
     *                    'true': Advertising is allowed.
     */
    function getAdvertisingCookiePreference() {
        return (getConsentManagerCookie() == VALUE_ALLOWING_ADVERT_COOKIE);
    }
    /* initConsentManager - Init Consent Manager
     * 
     */
    function initConsentManager() {
        var apiObject = {
            PrivacyManagerAPI:
            {
                action: "getConsent",
                timestamp: new Date().getTime(), self: DOMAIN_NAME
            }
        };
        var json = JSON.stringify(apiObject);
        window.top.postMessage(json, "*");
        window.addEventListener("message", ConsentManagerMessageHandler, false); // set event handler to retrieve notifications from Consent Manager 
    }
    /* ConsentManagerMessageHandler - 
     * Consent Manager Message Handler.
     */
    function ConsentManagerMessageHandler(e) {
        var answerConsentManager = getAdvertisingConsentDecision(DOMAIN_NAME);

        if (answerConsentManager !== null) { // if Consent Manager answers
            if ((isPreferncesCookieNotSubmited()) && (!isEmptyOrNull(getConsentManagerCookie()))) { // Cookie Preferences has been submited first time
                setCookie(INIT_PREFERENCES_CENTER, "true", 90);
                var cookieBannerEvent = document.createEvent("Event");
                cookieBannerEvent.initEvent("cookiePreferencesSubmitedFirstTime", true, true);
                document.dispatchEvent(cookieBannerEvent);
            }
        }
    }
    /* getAdvertisingConsentDecision - Get Advertising Consent Decision from TrustArc.
       @return {Boolen}:
         null - TrustArc doesn't answer
         true - Advertising Cookies are Allowed
         false - Advertising Cookies are not Allowed
     */
    function getAdvertisingConsentDecision(domain) {
        var advertisingConsentDecision = null; // TrustArc doesn't answer == null

        if (isConsentManagerReady()) {
            var answer = truste.cma.callApi("getGDPRConsentDecision", domain); // answer from TrustArc
            var str = answer.consentDecision.join();
            advertisingConsentDecision = (~str.indexOf(NUM_ADVERTISING)) ? true : false;
        }

        return advertisingConsentDecision;
    }
    /* isConsentManagerReady - Check of Consent Manager (ready or not).
       @return {Boolen}:
            true - ready
            false - not ready
     */
    function isConsentManagerReady() {
        return (!isEmptyOrNull(truste)) && ('cma' in truste) && ('callApi' in truste.cma);
    }
   /* readCookie - read a cookie
    * @argument {String} name - cookie name.
    * @returns {Object} - cookie.
    */
    function readCookie(name) {
        return (document.cookie.match('(^|;) *' + name + '=([^;]*)') || "")[2];
    }
    /* createCookie - create a new cookie
     * @argument {String} name - cookie name.
     * @argument {String} value - cookie's value.
     * @argument {number} expireTime - days to expire date.
     */
    function createCookie(name, value, expireTime) {
        var expires = getCookieExpireTime(expireTime);

        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }
    /* deleteCookie - delete a cookie
     * @argument {String} name - cookie name.
     */
    function deleteCookie(name) {
        createCookie(name, "", {
            expires: -1
        })
    }
    /* getCookieExpireTime
     * @argument {number} expireTime - days to expire date.
     */
    function getCookieExpireTime(expireTime) {
        var expires = "";
        if (expireTime) {
            var date = new Date();
            date.setTime(date.getTime() + (expireTime * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        return expires;
    }
    /* setCookie - set new cookie's value
     * @argument {String} name - cookie name.
     * @argument {String} value - cookie's value.
     * @argument {number} expireTime - days to expire date.
     */
    function setCookie(name, value, expireTime) {
        var expires = getCookieExpireTime(expireTime);

        document.cookie = name + "=" + escape(value) + expires + "; path=/";
    }
    /* isEmptyOrNull - check for empty object, variable. null, undefined, error all return true. Returns false if a value is found.
     * @argument {object} testString.
     */
    function isEmptyOrNull(testString) {

        try {
            if (typeof testString == 'string') {
                //is a string
                if (testString == null || testString == 'null') {
                    return true;
                } else if ($.trim(testString) == '') {
                    return true;
                } else if ($.trim(testString) == 'undefined') {
                    return true;
                } else {
                    return false;
                }
            } else if (typeof testString == 'undefined') {
                return true;

            } else if (typeof testString == 'object' && testString == null) {

                return true;
            } else {
                return false;
            }
        } catch (e) {
            return true;
        }

    }
}