var LTKSubPointToolbox = function () {
    var Revision = '1';
    var Version = '1.9.9.a';
    //var DebugMode = true;
    var DebugMode = _ltk_util.getQuerystringValue('ltkdebugmode') === '1' || _ltk_util.getQuerystringValue('ltksubpointdebug') === '1';
    var ForceSessionLog = false;
    var UseCookie = true;
    function ToolBox() { this.Version = "2.8.5" } ToolBox.prototype.inputExists = function (t) { return "undefined" != typeof t && null !== t }, ToolBox.prototype.getInputValueIfExists = function (t) { var e = document.getElementById(t); return this.inputExists(e) ? e.value : "" }, ToolBox.prototype.getSelectedOption = function (t) { var e = "string" == typeof t ? document.getElementById(t) : t; return this.inputExists(e) ? e.options[e.selectedIndex] : void 0 }, ToolBox.prototype.getCheckboxState = function (t) { var e = "string" == typeof t ? document.getElementById(t) : t; return this.inputExists(e) ? e.checked : !1 }, ToolBox.prototype.getHookValue = function (t) { var e = "string" == typeof t ? t : "ListrakDataHook"; return this.getInputValueIfExists(e) }, ToolBox.prototype.getHooks = function (t) { var e = "string" == typeof t ? t : "ListrakDataHook"; return document.getElementsByName(e) }, ToolBox.prototype.hasDataHook = function (t) { for (var e = document.querySelectorAll('[id="ListrakDataHook"]'), o = 0; o < e.length; o++) if (e[o].value == t) return !0; return !1 }, ToolBox.prototype.getDataAttribute = function (t) { var e = 0 == t.indexOf("data-") ? t : "data-" + t, o = document.querySelector("[" + e + "]"); return o ? o.getAttribute(e) : "" }, ToolBox.prototype.getURLPath = function () { return window.location.pathname }, ToolBox.prototype.isPagePath = function (t, e) { var o = window.location.pathname, n = "boolean" == typeof e ? e : !1; if (n) return o === t; if (o === t) return !0; var r = "/" == t.slice(-1) ? t.substring(0, t.length - 1) : t + "/"; return r === o ? !0 : !1 }, ToolBox.prototype.getQueryString = function (t, e) { null == e && (e = ""), t = t.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var o = new RegExp("[\\?&]" + t + "=([^&#]*)"), n = o.exec(window.location.href); return null == n ? e : n[1] }, ToolBox.prototype.findElementByAttribute = function (t, e, o, n) { for (var r = "number" == typeof n ? n : 0, i = document.getElementsByTagName(t), u = new Array, p = 0; p < i.length; p++) i[p].getAttribute(e) === o && u.push(i[p]); return u[r] }, ToolBox.prototype.findButtonByTitle = function (t) { return this.findElementByAttribute("button", "title", t) }, ToolBox.prototype.findInputByValue = function (t) { return this.findElementByAttribute("input", "value", t) }, ToolBox.prototype.setElementBlurIfExists = function (t, e) { var o = "string" == typeof t ? document.getElementById(t) : t; this.inputExists(o) && "function" == typeof e && (o.onblur = e) }, ToolBox.prototype.eventFire = function (t, e) { if (t.fireEvent) t.fireEvent("on" + e); else { var o = document.createEvent("Events"); o.initEvent(e, !0, !1), t.dispatchEvent(o) } }, ToolBox.prototype.appendClick = function (t, e) { var o = "string" == typeof t ? document.getElementById(t) : t; this.inputExists(o) && "function" == typeof e && (o.addEventListener ? o.addEventListener("click", e) : o.attachEvent("onclick", e)) }, ToolBox.prototype.appendEvent = function (t, e, o) { var n = "string" == typeof t ? document.getElementById(t) : t; this.inputExists(n) && "function" == typeof o && n.addEventListener && n.addEventListener(e, o) }, ToolBox.prototype.setTriggerPoints = function (t, e, o) { var n = "string" == typeof e ? document.getElementById(e) : e, r = "string" == typeof t ? document.getElementById(t) : t; this.inputExists(n) && this.inputExists(r) && "function" == typeof o && (this.appendClick(r, o), this.appendEvent(n, "keypress", function (t) { var e = t.keyCode ? t.keyCode : t.which; 13 == e && o() })) }, ToolBox.prototype.convertMonthNameToNumber = function (t) { return new Date(Date.parse(t + " 1, 2015")).getMonth() + 1 }, ToolBox.prototype.constructBirthday = function (t, e, o) { return "string" == typeof t && (t = this.convertMonthNameToNumber(t)), "number" == typeof t ? (e = "number" == typeof e ? e : 1, o = "number" == typeof o ? o : (new Date).getFullYear(), t + "/" + e + "/" + o) : void 0 }, ToolBox.prototype.elementHasParent = function (t, e) { var o = "string" == typeof t ? document.getElementById(t) : t, n = "string" == typeof e ? document.getElementById(e) : e; do { if (o === n) return !0; o = o.parentElement } while (this.inputExists(o)); return !1 }, ToolBox.prototype.createOptInElement = function (t, e) { var o = o = "string" == typeof e ? e : "is_subscribed", n = document.createElement("div"), r = document.createElement("input"); r.setAttribute("id", o), r.setAttribute("type", "checkbox"), r.style.marginRight = "10px", r.style.marginTop = "4px", r.style.cssFloat = "left"; var i = document.createElement("label"); return i.htmlFor = o, i.appendChild(document.createTextNode(t)), n.isChecked = function () { return this.firstChild.checked }, n.appendChild(r), n.appendChild(i), n }, ToolBox.prototype.isMobile = { Android: function () { return /Android/i.test(navigator.userAgent) }, BlackBerry: function () { return /BlackBerry/i.test(navigator.userAgent) }, iOS: function () { return /iPhone|iPad|iPod/i.test(navigator.userAgent) }, Opera: function () { return /Opera Mini/i.test(navigator.userAgent) }, Windows: function () { return /IEMobile/i.test(navigator.userAgent) }, any: function () { return this.Android() || this.BlackBerry() || this.iOS() || this.Opera() || this.Windows() } }, ToolBox.prototype.executeWhenExists = function (t, e, o) { var n = this, r = "number" == typeof o ? o : 10; r > 0 && setTimeout(function () { var o = document.getElementById(t); n.inputExists(o) ? e() : n.executeWhenExists(t, e, r - 1) }, 500) };
    function ListrakSubscriber() { this.trigger = "*", this.subscriptionPoint = null, this.email = null, this.profiles = Array() } function ListrakSubscriberHandler(e) { this.isDebug = "boolean" == typeof e ? e : !1, this.Version = Version, this.Revision = Revision, this.ForceSessionSaveLog = "boolean" == typeof ForceSessionLog ? ForceSessionLog : !1, this.UseCookie = "boolean" == typeof UseCookie ? UseCookie : !1, this.dataID = "ltkSubscriberObjs", this.subscriber = new ListrakSubscriber, this.toolbox = new ToolBox, this.supportsSessionStorage = "sessionStorage" in window && null !== window.sessionStorage; var i = function (e) { sessionStorage.setItem((new Date).getTime(), e) }; if (this.Log = function (e, r) { if (this.isDebug) switch (("undefined" == typeof console.log || this.ForceSessionSaveLog === !0) && i(e), r = "string" == typeof r ? r : "log") { case "warn": console.warn(e); break; case "info": console.info(e); break; case "debug": console.debug(e); break; case "error": console.error(e); break; default: console.log(e) } }, document.dispatchEvent) { var r = document.createEvent("Event"); r.initEvent("ListrakSubscriberHandlerLoaded", !1, !1), document.dispatchEvent(r) } this.Log("Loading LPS_LSH version " + Version + " (Toolbox v" + this.toolbox.Version + ") with debug mode - Revision: " + Revision, "debug") } ListrakSubscriberHandler.prototype.getDomain = function () { var e = window.location.host.indexOf("."), i = window.location.host; return 0 > e ? window.location.host : i.substr(e, i.length - e) }, ListrakSubscriberHandler.prototype.getCookie = function (e) { var i = "string" == typeof e ? e : this.dataID; return _ltk_util.getCookie(i) }, ListrakSubscriberHandler.prototype.setCookie = function (e, i, r) { var t = "string" == typeof e ? e : this.dataID; _ltk_util.setCookie(t, i, r, _ltk_util.getCookieDomain(), "/", null) }, ListrakSubscriberHandler.prototype.clearCookie = function (e) { var i = new Date(1970, 1, 1, 0, 0, 0); this.setCookie(e, "", i) }, ListrakSubscriberHandler.prototype.LoadSavedSubscriber = function () { var e = this.GetSubscriberData(); e[0].email && (this.subscriber.email = e[0].email), e[0].profiles && (this.subscriber.profiles = e[0].profiles), e[0].subscriptionPoint && (this.subscriber.subscriptionPoint = e[0].subscriptionPoint), e[0].trigger && (this.subscriber.trigger = e[0].trigger) }, ListrakSubscriberHandler.prototype.GetSubscriberData = function () { var e = this.UseCookie ? this.getCookie() : sessionStorage.getItem(this.dataID); if (e && "" !== e) { var i = this.ParseJSON(e); return "string" == typeof i && (i = this.ParseJSON(i)), i } }, ListrakSubscriberHandler.prototype.ParseJSON = function (e) { return JSON.parse ? JSON.parse(e) : JSON.decode(e) }, ListrakSubscriberHandler.prototype.SaveSubscriberData = function (e) { if (e) { var i, r = this.GetSubscriberData(); i = r ? r : new Array; for (var t = !1, o = 0; o < i.length; o++) i[o].trigger === e.trigger && (i[o] = e), t = !0; t || i.push(e); var s = JSON.stringify ? JSON.stringify(i) : JSON.encode(i); this.UseCookie ? (this.setCookie(this.dataID, s, 365), this.Log("saving data to cookie")) : sessionStorage.setItem(this.dataID, s) } }, ListrakSubscriberHandler.prototype.ClearSubscriberData = function () { this.UseCookie ? this.clearCookie(this.dataID) : sessionStorage.removeItem(this.dataID), this.subscriber = new ListrakSubscriber, this.Log("cleared local data", "info") }, ListrakSubscriberHandler.prototype.SetSubPoint = function (e) { this.subscriber.subscriptionPoint = e, this.Log("Setting subscription point to: " + e) }, ListrakSubscriberHandler.prototype.SetEmail = function (e) { this.subscriber.email = e, this.Log("Setting email address to: " + e) }, ListrakSubscriberHandler.prototype.SetTrigger = function (e) { this.subscriber.trigger = e, this.Log("Setting trigger option to: " + e) }, ListrakSubscriberHandler.prototype.AddProfile = function (e, i) { var r = this, t = !1; r.subscriber.profiles.forEach(function (o) { o.ProfileName == e && (r.Log("updating value for " + o.ProfileName + " to " + i), o.ProfileValue = i, t = !0) }), t || (r.subscriber.profiles.push(new Object({ ProfileName: e, ProfileValue: i })), r.Log("adding value for " + e + " : " + i)) }, ListrakSubscriberHandler.prototype.Save = function () { this.Log("Saving information for: " + this.subscriber.email, "info"), this.SaveSubscriberData(this.subscriber) }, ListrakSubscriberHandler.prototype.Subscribe = function () { var e = this, i = e.GetSubscriberData(); if (!i) return void e.Log("no subscriber data found in storage", "info"); var r = new Array; i.forEach(function (i) { e.Log("found subscriber data for " + i.email + " and trigger: " + i.trigger), i.trigger === e.toolbox.getHookValue() || i.trigger === e.toolbox.getURLPath() || "*" === i.trigger ? (_ltk.Subscriber.List = i.subscriptionPoint, _ltk.Subscriber.Email = i.email, i.profiles.forEach(function (e) { _ltk.Subscriber.Profile.Add(e.ProfileName, e.ProfileValue) }), "function" == typeof OnBeforeSubscriberSubmit && OnBeforeSubscriberSubmit(i), _ltk.Subscriber.Submit(), _ltk.Subscriber = new _LTKSubscriber, e.Log("Submitting " + i.email + " to listrak!"), "function" == typeof OnAfterSubscriberSubmit && OnAfterSubscriberSubmit(i)) : r.push(i) }), "function" == typeof OnBeforeSubscriberClearCall && OnBeforeSubscriberClearCall(i), e.ClearSubscriberData(), r.forEach(function (i) { e.SaveSubscriberData(i) }) };
    if (typeof _ltk.LPS_LSH === 'undefined' || typeof _ltk.LPS_LSH.Version === 'undefined' || (_ltk.LPS_LSH.Version < Version) || (_ltk.LPS_LSH.Revision < Revision)) { _ltk.LPS_LSH = new ListrakSubscriberHandler(DebugMode); } _ltk.LPS_LSH.Subscribe(); var handler = _ltk.LPS_LSH; var toolbox = _ltk.LPS_LSH.toolbox;

    /* Sub point collection-based framework */
    var collections = [{}];
    var capturedForms = [];

    this.addCollection = function (json) {
        var index = collections.length;
        if (isEmpty(collections[index - 1]))
            index -= 1;

        collections[index] = json;
        getForms();
    }

    function isEmpty(object) {
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
    }

    function getForms() {
        var form;
        collections.forEach(function (col) {
            form = parseInput(col.Container, document);
            bindToForm(form, col);
        });
    }

    function parseInput(val, parentForm) {
        var element;
        var isString = (typeof val == 'string');
        if (isString) {
            if (val.indexOf('[') > -1 && val.indexOf(']') > -1) {
                element = parentForm.querySelector(val);
            }
            else {
                element = parentForm.querySelector('[id="' + val + '"]');
                if (element == null) {
                    element = parentForm.querySelector('[name="' + val + '"]');
                }
            }
            return element;
        }
        else return val;
    }

    function bindToForm(form, col) {
        var parentForm = form;

        // Bind to and capture each form only once
        if (parentForm && !capturedForms.includes(form)) {
            handler.Log("Located container for: " + col.Subpoint);
            capturedForms.push(form);


            // Append click for buttons
            var submitButton;

            // Check if button is in a different container
            if (col.ButtonContainer) {
                var buttonContainer = parseInput(col.ButtonContainer, document);
                submitButton = parseInput(col.Button, buttonContainer);
            } else submitButton = parseInput(col.Button, parentForm);

            if (submitButton) {
                toolbox.appendClick(submitButton, function () {
                    handler.Log("Submit button clicked");
                    doSubmission(parentForm, col);
                });
            }

            // Set trigger-points for fields
            var submitField = parseInput(col.SubmissionField, parentForm);
            var email = parseInput(col.Email, parentForm);
            if (submitField) {
                toolbox.setTriggerPoints(submitField, email, function () {
                    handler.Log("Trigger-point fired");
                    doSubmission(parentForm, col);

                });
            }
        }
    }

    function doSubmission(form, col) {
        var optIn = parseInput(col.OptIn, form);
        if (optIn == undefined || (optIn && optIn.checked)) {
            addUserProfileData(form, col);
        } else { handler.Log("Not submitting to Listrak - customer has not opted in"); }
    }

    function addUserProfileData(container, col) {
        setTrigger(col);

        var subPoint = col.Subpoint;
        var email = parseInput(col.Email, container);
        if (email) handler.SetEmail(email.value);

        handler.AddProfile("ltkSource", "on");
        handler.SetSubPoint(col.Subpoint);
        addLtkProfiles(container);
        handler.Save();

        if (col.QuickSubmit != null) {
            handler.Log('--- Submitting immediately to Listrak ---');
            handler.Subscribe();
        }
        else handler.Log('--- Saving user data ---');

        // Scrape for new forms, any time an existing form is submitted
        handler.Log('Re-scraping for new forms...');
        repeatCallOnDelay(getForms, 2000);
    }

    function setTrigger(col) {
        if (col.Trigger != null)
            handler.SetTrigger(col.Trigger);
        else
            handler.SetTrigger('*');
    }

    function addLtkProfiles(container) {
        var elements = container.querySelectorAll('input, select');
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].type != "password" && elements[i].type != "submit") {
                var identifier = getIdentifier(elements[i]);
                if (elements[i].value)
                    handler.AddProfile(identifier.value, elements[i].value);
            }
        }
    }

    function getIdentifier(ele) {
        var pair = {};
        if (ele.id) pair = { "attr": "id", "value": ele.id };
        else if (ele.name) pair = { "attr": "name", "value": ele.name };
        else if (ele.title) pair = { "attr": "title", "value": ele.title };
        else if (ele.class) pair = { "attr": "class", "value": ele.class };

        //TODO: Try-catch to throw exception when no identifier found
        return pair;
    }

    function repeatCallOnDelay(func, timeout) {
        setTimeout(function () {
            func();
        }, timeout);
    }

    // Handle jQuery-based Single-page Applications
    if (jQuery)
        jQuery(document).ajaxComplete(function (e) { getForms() });
};

var LTKSubPoint = new LTKSubPointToolbox();