/*
CustomJS LIVE, Australian Ethical
Version 1.11

 - 

*/
if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, "includes", {
        enumerable: false,
        value: function (obj) {
            var newArr = this.filter(function (el) {
                return el == obj;
            });
            return newArr.length > 0;
        }
    });
}

if (!(IMI.CustomJS && IMI.CustomJS.customJSisLoaded)) {

    (function () {
        IMI.CustomJS = {
            customJSisLoaded: true,
            slideOutReverseOriginal: false,
            oldURL: window.location.href,
            incrementVisitCountCalled: false,
            visitCount: 0,

            locks: {},
            doMouseOut: undefined,
            afterInterceptsLoaded: function () {
                console.log('running CustomJS');
                //IMI.CustomJS.mods.lookForFeedbackIframe(211);
                var imm = IMI.CustomJS;

                if (!imm.slideOutReverseOriginal) {
                    console.log("Saving oiginal IMI.AnimationUtil.slideOutReverse");
                    imm.slideOutReverseOriginal = IMI.AnimationUtil.slideOutReverse;
                    IMI.AnimationUtil.slideOutReverse = imm.mods.slideOutReverse;
                }

                // Set start time in session storage.
                if (sessionStorage && (sessionStorage.getItem('startTime') == null)) {
                    sessionStorage.setItem('startTime', new Date().getTime())
                }

            },
            'mods': {
                getIntercept: function (id) {
                    for (var i = 0; i < IMI.Intercepts.length; i++) {
                        if (IMI.Intercepts[i].id == id) {
                            return IMI.Intercepts[i];
                        }
                    }
                },

                findEmailAddress: function () {
                    var targetClass = 'form-control-label';
                    var elements = document.getElementsByClassName(targetClass);
                    var emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/;
                    for (var i = 0; i < elements.length; i++) {
                        var elementContent = elements[i].textContent || elements[i].innerText;
                        var emailMatch = elementContent.match(emailRegex);
                        if (emailMatch) {
                            return emailMatch[0];
                        }
                    }
                },

                getSessionTime: function () {
                    var t = (new Date().getTime() - parseInt(sessionStorage.getItem('startTime'))) / 1000;
                    //console.log("getSessionTime: " + t);
                    return t;
                },

                urlList: function (domain, pageURL) {
                    domain = domain + '/';
                    //window.location.origin
                    var a = false;
                    var urls = [
                        domain + 'blog',
                        domain + 'insights',
                        domain + 'managed-funds/investment-commentary'
                    ];

                    if (domain != pageURL) {
                        //console.log( domain )
                        for (const type in urls) {
                            console.log(urls[type].includes(pageURL));
                            //if ( urls[type].includes(pageURL) ) {
                            if (pageURL.includes(urls[type])) {
                                a = true;
                            }
                        }

                        //console.log(a);

                        /* remove padding added by DI */
                        var css = 'body[style="padding-bottom: 80px;"]{'
                            + '	padding:unset !important;'
                            + '}',
                            head = document.head || document.getElementsByTagName('head')[0],
                            style = document.createElement('style');

                        if (head) {
                            head.appendChild(style);
                            style.type = 'text/css';
                            style.appendChild(document.createTextNode(css));
                        }
                    }


                    return a;
                },
				additionalUrlExclusionList: function () {
					
					var urlList = [
									'/insights/how-we-are-challenging-banks-on-their-lending/',
									'/blog/the-biggest-contributors-to-emissions-explained/',
									'/blog/fossil-fuels-remain-a-large-part-of-our-energy-system/',
									'/blog/how-to-take-action-with-your-energy-usage/',
									'/blog/how-to-take-action-with-your-finances/',
									'/insights/whos-financing-fossil-fuels/',
									'/blog/the-biggest-contributors-to-emissions-explained'
									];
					
					if (urlList.includes(window.location.pathname)){
						return false;
					}
					return true
				},
                productOutput: function () {
                    var pageURL = window.location.href;
                    var productList = ['super', 'pension', 'managed-funds', 'insights', 'unknown']
                    var productListSS = [1, 2, 3, 3, 4]


                    //var i;
                    //for (i = 0; i < productList.length; i++) {
                    //console.log(i)
                    //console.log( (window.location.href).indexOf( productList[i] ))
                    //console.log( pageURL.indexOf(productList[i] ))
                    if (pageURL.indexOf('super') >= 1) {
                        return 1;
                    } else if (pageURL.indexOf('pension') >= 1) {
                        return 2;
                    } else if (pageURL.indexOf('managed-funds') >= 1) {
                        return 3;
                    } else if (pageURL.indexOf('insights') >= 1) {
                        return 3;
                    } else {
                        return 4;
                    }


                    /*	
                      
                      console.log(Object.keys(productList)[i])
                      
                      if ( pageURL.indexOf( Object.keys(productList)[i] ) != -1 && Object.keys(productList)[i] != undefined ){
                        return productList[ Object.keys(productList)[i] ];
                        break;
                      }else {
                        return productList[ Object.keys(productList)[Object.keys(productList).length -1] ];
                      }
                      */
                    //}

                },
                customerTypeOutput: function () {
                    var pageURL = window.location.href;
                    var customerType = {
                        'super': 1,
                        'pension': 1,
                        'managed-funds': 2,
                        'MF': 2,
                        'A': 3,
                        'insights': 3,
                        'employer': 4,
                        'unknown': 5
                    }

                    var i;
                    for (i = 0; i < Object.keys(customerType).length; i++) {
                        if (pageURL.indexOf(Object.keys(customerType)[i]) != -1 && Object.keys(customerType)[i] != undefined) {
                            return customerType[Object.keys(customerType)[i]];
                        } else if (pageURL.indexOf('utm_campaign') != -1) {
                            return customerType[IMI.CustomJS.mods.getParameterByName('utm_campaign').split('-')[0]]
                        } else {
                            return customerType[Object.keys(customerType)[Object.keys(customerType).length - 1]];
                        }
                    }
                },
                getParameterByName: function (name, url) {
                    if (!url) url = window.location.href;
                    name = name.replace(/[\[\]]/g, "\\$&");
                    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                        results = regex.exec(url);
                    if (!results) return null;
                    if (!results[2]) return '';
                    return decodeURIComponent(results[2].replace(/\+/g, " "));
                },
                addCssToHead: function (idToAdd, css) {
                    var head = document.head || document.getElementsByTagName('head')[0];
                    var style = document.createElement('style');

                    if (head) {
                        head.appendChild(style);
                        style.type = 'text/css';
                        style.appendChild(document.createTextNode(css));
                    }

                },
                retirementCalculator: function (interceptId) {
                    var intercept = IMI.CustomJS.mods.getIntercept(interceptId);
                    var subVisualId = intercept.visual.subVisual.id;

                    var styleModal =
                        'section#_im_iframe_overlay__' + subVisualId + ' {'
                        + '	z-index: 9999999999; '
                        + '}';

                    IMI.CustomJS.mods.addCssToHead(subVisualId, styleModal);

                    return true;

                },
                retirementCalculatorIFRAME: function (interceptId) {
                    var intercept = IMI.CustomJS.mods.getIntercept(interceptId);
                    var visualId = intercept.visual.id;

                    var styleModal =
                        'section#_im_iframe_overlay__' + visualId + ' {'
                        + '	z-index: 9999999999; '
                        + '}'
                        + 'section#_im_iframe_overlay__' + visualId + ' {'
                        + '	max-width: 427px;'
                        + '	max-height: 800px;'
                        + '	height: 80% !important;'
                        + '    top: 100px;'
                        + '	right: 0px;'
                        + '	left: unset !important;'
                        + '    border: 2px solid rgba(0, 0, 0, 0.43);'
                        + '    animation-name: slidein;'
                        + '	animation-duration: 1s;'
                        + '}'
                        + '#intercept_close__' + visualId + ' {'
                        + '	right: 0px !important;'
                        + '}'
                        +

                        '@keyframes slidein {'
                        + '  from {'
                        + '	right: -427px;'
                        + '  }'
                        +

                        '  to {'
                        + '	right: 0px;'
                        + '  }'
                        + '}';

                    IMI.CustomJS.mods.addCssToHead(visualId, styleModal);

                    return true;

                },
                getURLParaValue: function (pageURL, searchVariable) {
                    var url = new URL(pageURL);
                    var c = url.searchParams.get(searchVariable);
                    return c;
                },
                getCohortValue: function (pageURL, searchVariable) {

                    var searchResult = (IMI.CustomJS.mods.getURLParaValue(pageURL, searchVariable) != null) ? (IMI.CustomJS.mods.getURLParaValue(pageURL, searchVariable)).toLowerCase() : null;

                    //if( pageURL.indexOf(variableToCheck) >= 1 )


                    var cohortArr = ['ae', 'cs', 'unknown'];
                    var cohortValArr = [1, 2, 4];

                    if (searchResult === null) {
                        return 4; // sending unknown
                    } else {
                        var i;
                        for (i = 0; i < cohortArr.length; i++) {
                            if (searchResult === cohortArr[i]) {
                                return cohortValArr[i]
                            }
                        }
                    }
                },

                balanceExistsInURL: function (pageURL, variableToCheck) {
                    if (pageURL.indexOf(variableToCheck) >= 1) {
                        return 4;
                    } else {
                        return 3;
                    }
                },

                getBalance: function (pageURL, variableToValue) {
                    if (pageURL.indexOf(variableToValue) >= 1) {
                        return IMI.CustomJS.mods.getURLParaValue(pageURL, variableToValue);
                    } else {
                        return 'Unknown';
                    }
                },
                getCurrentPage: function (pageURL) {

                    //example https://mol-aus-ethical.qa.tinasuper.com/dashboard?acc=6cf8070e-3989-4fab-a73a-1e1f1d11380e will display dashboard

                    var b = pageURL.split('/')

                    return b[b.length - 1].split('?')[0];

                },
                memberPortalListenPageChange: function (intercept) {
                    var intercept = IMI.CustomJS.mods.getIntercept(intercept);

                    if (intercept) {
                        if (!IMI.CustomJS.locks['memberPortalListenPageChangeListener']) {
                            IMI.CustomJS.locks['memberPortalListenPageChangeListener'] = true;
                            window.history.pushState = new Proxy(window.history.pushState, {
                                apply: (target, thisArg, argArray) => {
                                    let output = target.apply(thisArg, argArray);
                                    IMI.InterceptUtil.evaluateIntercepts([intercept]);
                                    return output;
                                },
                            });
                        }
                    }
                    return true;
                },

                memberPortal: function (intercept, fatigue, numberOfLogins) {
                    var intercept = IMI.CustomJS.mods.getIntercept(intercept);

                    if (intercept) {
                        if (window._interceptVars && window._interceptVars.login_count) {
                            console.log("window._interceptVars.login_count: ", window._interceptVars.login_count);
                            var loggedinAmount = window._interceptVars.login_count;
                            if (loggedinAmount > numberOfLogins) {
                                if (IMI.CustomJS.mods.checkLocalFatigue(intercept.id)) {
									var visualId = intercept.visual.id;
									var styleModal =
									  '#_im_banner__'+visualId+' {'+
									  '	  animation-name: example;'+
									  '	  animation-duration: 1s;'+
									  '	  height:85px !important;'+
									  '	}'+

									  '	@keyframes example {'+
									  '	  0% {bottom:-80px;}'+
									  '	  90%{bottom:0px;}'+
									  '	  100% {bottom:-10px;}'+
									  '}';
								  IMI.CustomJS.mods.addCssToHead(visualId, styleModal);
                                    IMI.InterceptUtil.appendAdditionalDataToURL(intercept);
                                    IMI.CustomJS.mods.setLocalFatigue(intercept.id, fatigue);
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                },

                productOutputJSObject: function (intercept) {
                    if (window._interceptVars && window._interceptVars.product_name) {
                        var productList = ['super', 'pension', 'managed-funds', 'insights', 'unknown'];
                        var productListSS = [1, 2, 3, 3, 4];
                        return productListSS[productList.indexOf(window._interceptVars.product_name.toLowerCase())]
                    }
                },
                setLocalFatigue: function (interceptId, fatigue) {
                    window.localStorage.setItem("IMI_InterceptFatigue_" + interceptId, new Date().setDate(new Date().getDate() + fatigue));
                },
                checkLocalFatigue: function (interceptId) {
                    var n = window.localStorage.getItem("IMI_InterceptFatigue_" + interceptId);
                    if (n && (new Date(parseInt(n)) > (new Date()))) {
                        return false;
                    }
                    return true;
                },
				joinFormCompletion: function (interceptId) {
				  var intercept = IMI.CustomJS.mods.getIntercept(interceptId);

				  if (!IMI.CustomJS.locks['startJoinFormCompletionPushStateListener']) {
					IMI.CustomJS.locks['startJoinFormCompletionPushStateListener'] = true;
					window.history.pushState = new Proxy(window.history.pushState, {
					  apply: (target, thisArg, argArray) => {

						let output = target.apply(thisArg, argArray);
						console.log('state change: reevaluateIntercepts');
						intercept.visual.type.unTriggerVisual(intercept.visual);
						intercept.visual.type.unTriggerVisual(intercept.visual.subVisual);
						if (intercept.visual.subVisual) {
						}
						IMI.InterceptUtil.evaluateIntercepts([intercept]);
						return output;
					  },
					});

				  }

				  var siteURL = window.location.href.split('?')[0];
				  var sitePath = window.location.href;

				  if (
					(
					  siteURL.match(/^https:\/\/cxplaza\.com/) ||
					  siteURL.match(/^https:\/\/ade1\.australianethical\.com\.au/) ||
					  siteURL.match(/^https:\/\/prep\.australianethical\.com\.au/)
					) &&
					sitePath.match(/cxplaza\.com\/#welcome/) ||
					sitePath.match(/ade1\.australianethical\.com\.au\/super\/new-join\/#welcome/) ||
					sitePath.match(/australianethical\.com\.au\/super\/join\/#welcome/) ||
					sitePath.match(/prep\.australianethical\.com\.au\/super\/new-join\/#welcome/)
				  ) {
					var visualId = intercept.visual.id;
					var subVisualId = intercept.visual.subVisual.id;

					var styleModal =
					  'section[id^="_im_feedbackTab__"] sidebar[id^="_im_feedbackTab_tab__"]{ ' +
					  'display:none !important;' +
					  '}' +
					  'section#_im_iframe_overlay__' + subVisualId + ' {' +
					  '	width: 300px !important;' +
					  '	height: 557px !important;' +
					  '	top: 25% !important;' +
					  '	left: unset !important;' +
					  '	right: 0 !important;' +
					  '	z-index: 9999999999 !important;' +
					  '	border: 1px solid #000;' +
					  '}' +
					  'section#_im_iframe_overlay__' + subVisualId + ' #intercept_section__' + subVisualId + ' {' +
					  '	top: 0 !important;' +
					  '	left: 0 !important;' +
					  '	height: 100% !important;' +
					  '	width: 100% !important;' +
					  '}' +

					  '.im_iframe_overlay .intercept-section .intercept-close {' +
					  '	right: 0px !important;' +
					  '}';

					IMI.CustomJS.mods.addCssToHead(visualId, styleModal);

					setTimeout(function() {
					  document.querySelector('#_im_feedbackTab__' + visualId).click();
					}, 10000);
				  }
				  return false;
				                },


                /**
                 * Detect mouse out intent. 
                 * 
                 * Add as last trigger:
                 * 
                 *  Trigger type: JS Expression
                 * 
                 *  Trigger Operator: Equals
                 * 
                 *  Js Expression: IMI.CustomJS.mods.detectMouseOutIntent(<interceptId>, <delay>);
                 * 
                 *  Return value to compare: true
                 *
                 * @param {integer} interceptId
                 *   Id of intercept to trigger
                 * @param {integer} delay
                 *   delay in seconds before listening for mouse out.
                 */
                detectMouseOutIntent: function (interceptId, delay, callback) {

                    if (IMI.CustomJS.locks['detectMouseOutIntent-' + interceptId]) {
                        return false;
                    } else {
                        IMI.CustomJS.locks['detectMouseOutIntent-' + interceptId] = true;
                        var armAfterMilliSeconds = delay * 1000 || 10000;
                        var intercept = IMI.CustomJS.mods.getIntercept(interceptId);
                        if (!intercept) {
                            return false;
                        }

                        function mouseout(callback, e) {
                            //console.log('mouseoutListener fired');
                            e = e ? e : window.event;
                            var from = e.relatedTarget || e.toElement;

                            if (!from || from.nodeName === 'HTML') {
                                var scrollPos = window.pageYOffset || window.scrollY || window.scrollTop || document.getElementsByTagName('html')[0].scrollTop;

                                if (e.pageY - scrollPos <= 1) {
                                    // the cursor has left the building
                                    document.removeEventListener("mouseout", IMI.CustomJS.doMouseOut);
                                    callback();
                                }
                            }
                        };

                        IMI.CustomJS.doMouseOut = function (event) {
                            var sitePath = window.location.pathname + window.location.hash;
                            
                            if (!(
                                sitePath.match(/super\/join\/#welcome/) ||
                                sitePath.match(/super\/join\/#supertransfermethodchoice/) ||
                                sitePath.match(/super\/join\/#supertransferchecklist/) ||
                                sitePath.match(/super\/join\/#supertransfertaxfilenumber/) ||
                                sitePath.match(/super\/join\/#supertransferverifyid/) ||
                                sitePath.match(/super\/join\/#supertransfermanualmatchfundnamesearch/) ||
                                sitePath.match(/super\/join\/#supertransfermanualmatchmemberdetails/) ||
                                sitePath.match(/super\/join\/#supertransfermanualmatchreview/) ||
                                sitePath.match(/super\/join\/#contributions/) ||
                                sitePath.match(/super\/join\/#contributionstemplatehelp/) ||
                                sitePath.match(/super\/join\/#SuperTransferSuperMatchSearch/) ||
                                sitePath.match(/super\/join\/#SuperTransferSuperMatchResults/) ||
                                sitePath.match(/super\/join\/#SuperTransferNotVerifiedError/) ||
                                sitePath.match(/super\/join\/#ContributionsInform/) ||
                                sitePath.match(/super\/join\/#ErrorUnableToGoBack`/)
                            )) {
                                mouseout(callback, event);
                            }
                        };

                        setTimeout(function () {
                            document.addEventListener("mouseout", IMI.CustomJS.doMouseOut);
                        }, armAfterMilliSeconds);

                        return false;
                    }
                },

                /**
                 * Trigger Intercept via JavaScript.
                 *
                 * @param {integer} interceptId
                 *   Id of intercept to trigger
                 */
                triggerIntercept: function (interceptId) {
                    var intercept = IMI.CustomJS.mods.getIntercept(interceptId);
                    if (intercept) {
                        IMI.InterceptUtil.appendAdditionalDataToURL(intercept);
                        IMI.InterceptUtil.triggerIntercept.call(
                            IMI.InterceptUtil.triggerIntercept,
                            intercept,
                            new Map()
                        );
                    }
                },
                updateStyling: function (interceptId) {
                    var intercept = IMI.CustomJS.mods.getIntercept(interceptId);
                    var visualId = intercept.visual.id;
                    //var subVisualId = intercept.visual.subVisual.id;

                    var styleModal =
                        `
                        section#intercept_section__${visualId} {
                            max-width:847px;
                            max-height:450px;
                            transform: translate(-50%, -50%);
                            left: 50% !important;
                            top: 50% !important;
                        }
                            `;

                    IMI.CustomJS.mods.addCssToHead(visualId, styleModal);
                },
                updateStylingMouseOut: function (interceptId) {
                    var intercept = IMI.CustomJS.mods.getIntercept(interceptId);
                    var visualId = intercept.visual.id;
                    //var subVisualId = intercept.visual.subVisual.id;

                    var styleModal =
                        `
                        section#intercept_section__${visualId} {
                            max-width:847px;
                            max-height: 660px !important;
                            transform: translate(-50%, -50%);
                            left: 50% !important;
                            top: 50% !important;
                        }
                            `;

                    IMI.CustomJS.mods.addCssToHead(visualId, styleModal);
                },
                joinMouseOut: function (interceptId) {
                    var intercept = IMI.CustomJS.mods.getIntercept(interceptId);

                    if (!IMI.CustomJS.locks['startJoinMouseOutPushStateListener']) {
                        IMI.CustomJS.locks['startJoinMouseOutPushStateListener'] = true;
                        window.history.pushState = new Proxy(window.history.pushState, {
                            apply: (target, thisArg, argArray) => {

                                let output = target.apply(thisArg, argArray);
                                console.log('state change: reevaluateIntercepts');
                                intercept.visual.type.unTriggerVisual(intercept.visual);
                                //intercept.visual.type.unTriggerVisual(intercept.visual.subVisual);
                                //if (intercept.visual.subVisual) {
                                //}
                                IMI.InterceptUtil.evaluateIntercepts([intercept]);
                                return output;
                            },
                        });

                    }
                    var siteURL = window.location.href.split('?')[0];
                    var sitePath = window.location.pathname + window.location.hash;

                    if (
                        siteURL.match(/^https:\/\/cxplaza\.com/) ||
                        siteURL.match(/^https:\/\/ade1\.australianethical\.com\.au/) ||
                        siteURL.match(/^https:\/\/prep\.australianethical\.com\.au/) ||
                        siteURL.match(/^https:\/\/www.\.australianethical\.com\.au/)
                    ) {

                        // if (
                        //     sitePath.match(/super\/join\/#welcome/) ||
                        //     sitePath.match(/super\/join\/#supertransfermethodchoice/) ||
                        //     sitePath.match(/super\/join\/#supertransferchecklist/) ||
                        //     sitePath.match(/super\/join\/#supertransfertaxfilenumber/) ||
                        //     sitePath.match(/super\/join\/#supertransferverifyid/) ||
                        //     sitePath.match(/super\/join\/#supertransfermanualmatchfundnamesearch/) ||
                        //     sitePath.match(/super\/join\/#supertransfermanualmatchmemberdetails/) ||
                        //     sitePath.match(/super\/join\/#supertransfermanualmatchreview/) ||
                        //     sitePath.match(/super\/join\/#contributions/) ||
                        //     sitePath.match(/super\/join\/#contributionstemplatehelp/) ||
                        //     sitePath.match(/super\/join\/#SuperTransferSuperMatchSearch/) ||
                        //     sitePath.match(/super\/join\/#SuperTransferSuperMatchResults/) ||
                        //     sitePath.match(/super\/join\/#SuperTransferNotVerifiedError/) ||
                        //     sitePath.match(/super\/join\/#ContributionsInform/) ||
                        //     sitePath.match(/super\/join\/#ErrorUnableToGoBack`/)
                        // ) {
                        //     document.removeEventListener("mouseout", IMI.CustomJS.doMouseOut);
                        //     return false
                        // }
                        if (
                            sitePath.match(/super\/join\/#start/)
                        ) {
                            return true
                        }

                    }

                }

            }


        }
    }

    )();
}
