From cd22a514c553585c408f8bdae31fae2655fefe25 Mon Sep 17 00:00:00 2001 From: Jude Pereira Date: Sat, 23 May 2020 17:24:56 +0200 Subject: [PATCH 01/31] Add 'core/lc/' from commit 'afc2c461cc12d3a3e2c06ac69bcaac212a35a247' git-subtree-dir: core/lc git-subtree-mainline: 59d727d12334c52c685bf777180d2bf7bd142603 git-subtree-split: afc2c461cc12d3a3e2c06ac69bcaac212a35a247 --- a.js | 3722 ++++++++++++++++++++++++++++++++++++++++++++ clevertap_sw.js | 1 + ct_logo.svg | 1 + dialog.js | 189 +++ gtm_segment.html | 47 + localforage.min.js | 5 + p.js | 501 ++++++ q.js | 315 ++++ sw_webpush.js | 161 ++ wzrk-shopify.js | 207 +++ 10 files changed, 5149 insertions(+) create mode 100644 a.js create mode 100644 clevertap_sw.js create mode 100644 ct_logo.svg create mode 100644 dialog.js create mode 100644 gtm_segment.html create mode 100644 localforage.min.js create mode 100644 p.js create mode 100644 q.js create mode 100644 sw_webpush.js create mode 100644 wzrk-shopify.js diff --git a/a.js b/a.js new file mode 100644 index 00000000..4f577751 --- /dev/null +++ b/a.js @@ -0,0 +1,3722 @@ +function __wizrocket() { + + + var targetDomain = 'wzrkt.com'; + // var targetDomain = 'localhost:3838'; //ALWAYS comment this line before deploying + + var wz_pr = "https:"; + + var dataPostURL, recorderURL, emailURL; + var wiz = this; + // var serviceWorkerPath = '/clevertap_sw.js'; // the service worker is placed in the doc root + var doc = document; + var domain = window.location.hostname; + var broadDomain; + var wc = window.console; + var requestTime = 0, seqNo = 0; + var wzrk_error = {}; //to trap input errors + var wiz_counter = 0; // to keep track of number of times we load the body + var globalCache = {}; + // to be used for checking whether the script loaded fine and the wiz.init function was called + var onloadcalled = 0; // 1 = fired + var processingBackup = false; + + var gcookie, scookieObj; + var accountId, region; + var campaignDivMap = {}; + var blockRequeust = false, clearCookie = false; + var SCOOKIE_NAME, globalChargedId; + var globalEventsMap, globalProfileMap, currentSessionId; + var storageDelim = "|$|"; + var staleEvtMaxTime = 20 * 60; //20 mins + var COOKIE_EXPIRY = 86400 * 365 * 10; //10 years in seconds. Seconds in an days * days in an year * number of years + var LRU_CACHE, LRU_CACHE_SIZE = 100; + var chromeAgent; + var firefoxAgent; + + // for VAPID web push + function urlBase64ToUint8Array(base64String) { + var padding = '='.repeat((4 - base64String.length % 4) % 4); + var base64 = (base64String + padding) + .replace(/\-/g, '+') + .replace(/_/g, '/') + ; + var rawData = window.atob(base64); + var processedData = [] + for (var i=0; i maxLen ? referrer_domain.substring(0, maxLen) : referrer_domain; + data['referrer'] = referrer_domain; + } + + + var utm_source = url_params['utm_source'] || url_params['wzrk_source']; + if (typeof utm_source != STRING_CONSTANTS.UNDEFINED) { + utm_source = utm_source.length > maxLen ? utm_source.substring(0, maxLen) : utm_source; + data['us'] = utm_source; //utm_source + } + + var utm_medium = url_params['utm_medium'] || url_params['wzrk_medium']; + if (typeof utm_medium != STRING_CONSTANTS.UNDEFINED) { + utm_medium = utm_medium.length > maxLen ? utm_medium.substring(0, maxLen) : utm_medium; + data['um'] = utm_medium; //utm_medium + } + + + var utm_campaign = url_params['utm_campaign'] || url_params['wzrk_campaign']; + if (typeof utm_campaign != STRING_CONSTANTS.UNDEFINED) { + utm_campaign = utm_campaign.length > maxLen ? utm_campaign.substring(0, maxLen) : utm_campaign; + data['uc'] = utm_campaign; //utm_campaign + } + + // also independently send wzrk_medium to the backend + if (typeof url_params['wzrk_medium'] != STRING_CONSTANTS.UNDEFINED) { + var wm = url_params['wzrk_medium']; + if (wm.match(/^email$|^social$|^search$/)) { + data['wm'] = wm; //wzrk_medium + } + + } + + } + + data = wiz.addSystemDataToObject(data, undefined); + data['cpg'] = currLocation; + + data[STRING_CONSTANTS.CAMP_COOKIE_NAME] = wiz.getCampaignObjForLc(); + var pageLoadUrl = dataPostURL; + wiz.addFlags(data); + //send dsync flag when page = 1 + if (data['pg'] != STRING_CONSTANTS.UNDEFINED && data['pg'] == 1) { + wiz.overrideDSyncFlag(data); + } + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "page"); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(JSON.stringify(data))); + wiz.saveAndFireRequest(pageLoadUrl, false); + + + // -- ping request logic + + var pingRequest = function () { + var pageLoadUrl = dataPostURL; + var data = {}; + data = wiz.addSystemDataToObject(data, undefined); + + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PING); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(JSON.stringify(data))); + wiz.saveAndFireRequest(pageLoadUrl, false); + }; + + setTimeout(function () { + if (pgCount <= 3) { // send ping for up to 3 pages + pingRequest(); + } + + if (wiz.isPingContinuous()) { + setInterval(function () { + pingRequest(); + }, CONTINUOUS_PING_FREQ_IN_MILLIS); + } + }, FIRST_PING_FREQ_IN_MILLIS); + + // -- ping request logic + + + if (typeof wizrocket['session'] == STRING_CONSTANTS.UNDEFINED) { + + wizrocket['event']['getDetails'] = function (evtName) { + if (!wzrk_util.isPersonalizationActive()) { + return; + } + if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { + globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE); + } + if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { + return; + } + var evtObj = globalEventsMap[evtName]; + var respObj = {}; + + if (typeof evtObj != STRING_CONSTANTS.UNDEFINED) { + respObj['firstTime'] = new Date(evtObj[1] * 1000); + respObj['lastTime'] = new Date(evtObj[2] * 1000); + respObj['count'] = evtObj[0]; + return respObj; + } + + + }; + + wizrocket['profile']['getAttribute'] = function (propName) { + if (!wzrk_util.isPersonalizationActive()) { + return; + } + if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { + globalProfileMap = wiz.readFromLSorCookie(STRING_CONSTANTS.PR_COOKIE); + } + if (typeof globalProfileMap != STRING_CONSTANTS.UNDEFINED) { + return globalProfileMap[propName]; + } + }; + wizrocket['session'] = {}; + wizrocket['session']['getTimeElapsed'] = function () { + if (!wzrk_util.isPersonalizationActive()) { + return; + } + if (typeof scookieObj != STRING_CONSTANTS.UNDEFINED) { + scookieObj = wiz.getSessionCookieObject(); + } + var sessionStart = scookieObj['s']; + if (typeof sessionStart != STRING_CONSTANTS.UNDEFINED) { + var ts = wzrk_util.getNow(); + return Math.floor(ts - sessionStart); + } + }; + + wizrocket['user'] = {}; + wizrocket['user']['getTotalVisits'] = function () { + if (!wzrk_util.isPersonalizationActive()) { + return; + } + var visitCount = wiz.getMetaProp('sc'); + if (typeof visitCount == STRING_CONSTANTS.UNDEFINED) { + visitCount = 1; + } + return visitCount; + }; + + wizrocket['session']['getPageCount'] = function () { + if (!wzrk_util.isPersonalizationActive()) { + return; + } + + if (typeof scookieObj != STRING_CONSTANTS.UNDEFINED) { + scookieObj = wiz.getSessionCookieObject(); + } + return scookieObj['p']; + }; + + wizrocket['user']['getLastVisit'] = function () { + if (!wzrk_util.isPersonalizationActive()) { + return; + } + var prevSession = wiz.getMetaProp('ps'); + if (typeof prevSession != STRING_CONSTANTS.UNDEFINED) { + return new Date(prevSession * 1000); + } + }; + } + onloadcalled = 1; //always the last line in this function + + + }; + + + wiz.readFromLSorCookie = function (property) { + var data; + if (globalCache.hasOwnProperty(property)) { + return globalCache[property]; + } + if (wzrk_util.isLocalStorageSupported()) { + data = localStorage[property]; + } else { + data = wiz.readCookie(property); + } + if (typeof data != STRING_CONSTANTS.UNDEFINED && data !== null && data.trim() != '') { + var value = JSON.parse(decodeURIComponent(data)); + globalCache[property] = value; + return value; + } + }; + + wiz.saveToLSorCookie = function (property, val) { + if (typeof val == STRING_CONSTANTS.UNDEFINED || val == null) { + return; + } + try { + if (wzrk_util.isLocalStorageSupported()) { + localStorage[property] = encodeURIComponent(JSON.stringify(val)); + } else { + if (property === STRING_CONSTANTS.GCOOKIE_NAME) { + wiz.createCookie(property, encodeURIComponent(val), 0, domain); + } else { + wiz.createCookie(property, encodeURIComponent(JSON.stringify(val)), 0, domain); + } + } + globalCache[property] = val; + } catch (e) { + } + }; + + var processEvent = function (data) { + + wiz.addToLocalEventMap(data['evtName']); + data = wiz.addSystemDataToObject(data, undefined); + wiz.addFlags(data); + data[STRING_CONSTANTS.CAMP_COOKIE_NAME] = wiz.getCampaignObjForLc(); + var compressedData = wiz.compressData(JSON.stringify(data)); + + var pageLoadUrl = dataPostURL; + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); + + + wiz.saveAndFireRequest(pageLoadUrl, false); + }; + + wiz.processEventArray = function (eventArr) { + + if (wzrk_util.isArray(eventArr)) { + + /** looping since the events could be fired in quick succession, and we could end up + with multiple pushes without getting a chance to process + */ + while (eventArr.length > 0) { + + var eventName = eventArr.shift(); // take out name of the event + + if (!wzrk_util.isString(eventName)) { + wc.e(wzrk_msg['event-error']); + return; + } + + if (eventName.length > 1024) { + eventName = eventName.substring(0, 1024); + wiz.reportError(510, eventName + "... length exceeded 1024 chars. Trimmed."); + } + + if (eventName == "Stayed" || eventName == "UTM Visited" || eventName == "App Launched" || + eventName == "Notification Sent" || eventName == "Notification Viewed" || eventName == "Notification Clicked") { + wiz.reportError(513, eventName + " is a restricted system event. It cannot be used as an event name."); + continue; + } + var data = {}; + data['type'] = "event"; + data['evtName'] = wzrk_util.sanitize(eventName, unsupportedKeyCharRegex); + + if (eventArr.length != 0) { + var eventObj = eventArr.shift(); + + if (!wzrk_util.isObject(eventObj)) { + eventArr.unshift(eventObj); // put it back if it is not an object + } else { + //check Charged Event vs. other events. + if (eventName == "Charged") { + if (!wiz.isChargedEventStructureValid(eventObj)) { + wiz.reportError(511, "Charged event structure invalid. Not sent."); + continue; + } + } else { + if (!wiz.isEventStructureFlat(eventObj)) { + wiz.reportError(512, eventName + " event structure invalid. Not sent."); + continue; + } + + } + + data['evtData'] = eventObj; + } + } + processEvent(data); + + } + + } + }; + + wiz.addToLocalEventMap = function (evtName) { + if (wzrk_util.isLocalStorageSupported()) { + if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { + globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE); + if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { + globalEventsMap = {}; + } + } + var nowTs = wzrk_util.getNow(); + var evtDetail = globalEventsMap[evtName]; + if (typeof evtDetail != STRING_CONSTANTS.UNDEFINED) { + evtDetail[2] = nowTs; + evtDetail[0]++; + } else { + evtDetail = []; + evtDetail.push(1); + evtDetail.push(nowTs); + evtDetail.push(nowTs); + } + globalEventsMap[evtName] = evtDetail; + wiz.saveToLSorCookie(STRING_CONSTANTS.EV_COOKIE, globalEventsMap); + } + }; + + wiz.addToLocalProfileMap = function (profileObj, override) { + if (wzrk_util.isLocalStorageSupported()) { + if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { + globalProfileMap = wiz.readFromLSorCookie(STRING_CONSTANTS.PR_COOKIE); + if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { + globalProfileMap = {}; + } + } + + //Move props from custom bucket to outside. + if (typeof profileObj['_custom'] != STRING_CONSTANTS.UNDEFINED) { + var keys = profileObj['_custom']; + for (var key in keys) { + if (keys.hasOwnProperty(key)) { + profileObj[key] = keys[key]; + } + } + delete profileObj['_custom']; + } + + for (var prop in profileObj) { + if (profileObj.hasOwnProperty(prop)) { + if (globalProfileMap.hasOwnProperty(prop) && !override) { + continue; + } + globalProfileMap[prop] = profileObj[prop]; + } + } + if (typeof globalProfileMap['_custom'] != STRING_CONSTANTS.UNDEFINED) { + delete globalProfileMap['_custom']; + } + wiz.saveToLSorCookie(STRING_CONSTANTS.PR_COOKIE, globalProfileMap); + } + }; + + wiz.overrideDSyncFlag = function (data) { + if (wzrk_util.isPersonalizationActive()) { + data['dsync'] = true; + } + }; + + wiz.addARPToRequest = function (url, skipResARP) { + if(typeof skipResARP !== STRING_CONSTANTS.UNDEFINED && skipResARP === true) { + var _arp = {}; + _arp["skipResARP"] = true; + return wiz.addToURL(url, 'arp', wiz.compressData(JSON.stringify(_arp))); + } + if (wzrk_util.isLocalStorageSupported() && typeof localStorage[STRING_CONSTANTS.ARP_COOKIE] != STRING_CONSTANTS.UNDEFINED) { + return wiz.addToURL(url, 'arp', wiz.compressData(JSON.stringify(wiz.readFromLSorCookie(STRING_CONSTANTS.ARP_COOKIE)))); + } + return url; + }; + + wiz.addFlags = function (data) { + + //check if cookie should be cleared. + clearCookie = wiz.getAndClearMetaProp(STRING_CONSTANTS.CLEAR); + if (clearCookie !== undefined && clearCookie) { + data['rc'] = true; + wc.d("reset cookie sent in request and cleared from meta for future requests."); + } + if (wzrk_util.isPersonalizationActive()) { + var lastSyncTime = wiz.getMetaProp('lsTime'); + var expirySeconds = wiz.getMetaProp('exTs'); + + //dsync not found in local storage - get data from server + if (typeof lastSyncTime == STRING_CONSTANTS.UNDEFINED || typeof expirySeconds == STRING_CONSTANTS.UNDEFINED) { + data['dsync'] = true; + return; + } + var now = wzrk_util.getNow(); + //last sync time has expired - get fresh data from server + if (lastSyncTime + expirySeconds < now) { + data['dsync'] = true; + } + } + + + }; + + var unregisterTokenForGuid = function (givenGUID) { + var data = {}; + data["type"] = "data"; + if (wiz.isValueValid(givenGUID)) { + data["g"] = givenGUID; + } + data["action"] = "unregister"; + data["id"] = accountId; + + var obj = wiz.getSessionCookieObject(); + + data["s"] = obj["s"]; //Session cookie + var compressedData = wiz.compressData(JSON.stringify(data)); + + var pageLoadUrl = dataPostURL; + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "data"); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); + + wiz.fireRequest(pageLoadUrl, true); + }; + + var LRU_cache = function (max) { + this.max = max; + var keyOrder; + var LRU_CACHE = wiz.readFromLSorCookie(STRING_CONSTANTS.LRU_CACHE); + if (LRU_CACHE) { + var lru_cache = {}; + keyOrder = []; + LRU_CACHE = LRU_CACHE.cache; + for (var entry in LRU_CACHE) { + if(LRU_CACHE.hasOwnProperty(entry)) { + lru_cache[LRU_CACHE[entry][0]] = LRU_CACHE[entry][1]; + keyOrder.push(LRU_CACHE[entry][0]); + } + + } + this.cache = lru_cache; + } else { + this.cache = {}; + keyOrder = []; + } + + this.get = function (key) { + var item = this.cache[key]; + if (item) { + var temp_val = item; + this.cache = deleteFromObject(key, this.cache); + this.cache[key] = item; + keyOrder.push(key); + } + this.saveCacheToLS(this.cache); + return item; + }; + + this.set = function (key, value) { + var item = this.cache[key]; + var all_keys = keyOrder; + if (item != null) { + this.cache = deleteFromObject(key, this.cache); + } else if (all_keys.length === this.max) { + this.cache = deleteFromObject( + all_keys[0], + this.cache + ); + } + this.cache[key] = value; + if (keyOrder[keyOrder.length - 1] !== key) { + keyOrder.push(key); + } + this.saveCacheToLS(this.cache); + }; + + this.saveCacheToLS = function (cache) { + var obj_to_array = []; + var all_keys = keyOrder; + for (var index in all_keys) { + if(all_keys.hasOwnProperty(index)) { + var temp = []; + temp.push(all_keys[index]); + temp.push(cache[all_keys[index]]); + obj_to_array.push(temp); + } + } + wiz.saveToLSorCookie(STRING_CONSTANTS.LRU_CACHE, { + cache: obj_to_array + }); + }; + + this.getKEY = function (givenVal) { + if (givenVal == null) return null; + var all_keys = keyOrder; + for (var index in all_keys) { + if(all_keys.hasOwnProperty(index)) { + if ( + this.cache[all_keys[index]] != null && + this.cache[all_keys[index]] === givenVal + ) { + return all_keys[index]; + } + } + } + return null; + }; + + this.getSecondLastKEY = function () { + var keysArr = keyOrder; + if (keysArr != null && keysArr.length > 1) { + return keysArr[keysArr.length - 2]; + } else { + return -1; + } + }; + + this.getLastKey = function () { + if (keyOrder.length) { + return keyOrder[keyOrder.length - 1]; + } + }; + + + var deleteFromObject = function (key, obj) { + var all_keys = JSON.parse(JSON.stringify(keyOrder)); + var new_cache = {}; + var indexToDelete; + for (var index in all_keys) { + if(all_keys.hasOwnProperty(index)) { + if (all_keys[index] !== key) { + new_cache[all_keys[index]] = obj[all_keys[index]]; + } else { + indexToDelete = index; + } + } + } + all_keys.splice(indexToDelete, 1); + keyOrder = JSON.parse(JSON.stringify(all_keys)); + return new_cache; + }; + }; + + wiz.getCampaignObjForLc = function () { + var campObj = {}; + if (wzrk_util.isLocalStorageSupported()) { + campObj = wzrk_util.getCampaignObject(); + + var resultObj = []; + var globalObj = campObj['global']; + var today = wzrk_util.getToday(); + var dailyObj = campObj[today]; + + if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) { + var campaignIdArray = Object.keys(globalObj); + for (var index in campaignIdArray) { + if (campaignIdArray.hasOwnProperty(index)) { + var dailyC = 0; + var totalC = 0; + var campaignId = campaignIdArray[index]; + if (campaignId == 'tc') { + continue; + } + if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED && typeof dailyObj[campaignId] != STRING_CONSTANTS.UNDEFINED) { + dailyC = dailyObj[campaignId]; + } + if (typeof globalObj != STRING_CONSTANTS.UNDEFINED && typeof globalObj[campaignId] != STRING_CONSTANTS.UNDEFINED) { + totalC = globalObj[campaignId]; + } + var element = [campaignId, dailyC, totalC]; + resultObj.push(element); + } + } + } + var todayC = 0; + if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED && typeof dailyObj['tc'] != STRING_CONSTANTS.UNDEFINED) { + todayC = dailyObj['tc']; + } + resultObj = {"wmp": todayC, 'tlc': resultObj}; + return resultObj; + } + }; + + var handleCookieFromCache = function () { + blockRequeust = false; + wc.d("Block request is false"); + if (wzrk_util.isLocalStorageSupported()) { + delete localStorage[STRING_CONSTANTS.PR_COOKIE]; + delete localStorage[STRING_CONSTANTS.EV_COOKIE]; + delete localStorage[STRING_CONSTANTS.META_COOKIE]; + delete localStorage[STRING_CONSTANTS.ARP_COOKIE]; + delete localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; + delete localStorage[STRING_CONSTANTS.CHARGEDID_COOKIE_NAME]; + } + wiz.deleteCookie(STRING_CONSTANTS.CAMP_COOKIE_NAME, domain); + wiz.deleteCookie(SCOOKIE_NAME, broadDomain); + wiz.deleteCookie(STRING_CONSTANTS.ARP_COOKIE, broadDomain); + scookieObj = ''; + }; + + var deleteUser = function () { + blockRequeust = true; + wc.d("Block request is true"); + globalCache = {}; + if (wzrk_util.isLocalStorageSupported()) { + delete localStorage[STRING_CONSTANTS.GCOOKIE_NAME]; + delete localStorage[STRING_CONSTANTS.KCOOKIE_NAME]; + delete localStorage[STRING_CONSTANTS.PR_COOKIE]; + delete localStorage[STRING_CONSTANTS.EV_COOKIE]; + delete localStorage[STRING_CONSTANTS.META_COOKIE]; + delete localStorage[STRING_CONSTANTS.ARP_COOKIE]; + delete localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; + delete localStorage[STRING_CONSTANTS.CHARGEDID_COOKIE_NAME]; + } + wiz.deleteCookie(STRING_CONSTANTS.GCOOKIE_NAME, broadDomain); + wiz.deleteCookie(STRING_CONSTANTS.CAMP_COOKIE_NAME, domain); + wiz.deleteCookie(STRING_CONSTANTS.KCOOKIE_NAME, domain); + wiz.deleteCookie(SCOOKIE_NAME, broadDomain); + wiz.deleteCookie(STRING_CONSTANTS.ARP_COOKIE, broadDomain); + gcookie = null; + scookieObj = ''; + + }; + + var setInstantDeleteFlagInK = function () { + var k = wiz.readFromLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME); + if (typeof k == STRING_CONSTANTS.UNDEFINED) { + k = {}; + } + k['flag'] = true; + wiz.saveToLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME, k); + }; + + wiz.logout = function () { + wc.d("logout called"); + setInstantDeleteFlagInK(); + }; + + + wiz.clear = function () { + wc.d("clear called. Reset flag has been set."); + deleteUser(); + wiz.setMetaProp(STRING_CONSTANTS.CLEAR, true); + }; + + + /* + We dont set the arp in cache for deregister requests. + For deregister requests we check for 'skipResARP' flag payload. If present we skip it. + + Whenever we get 'isOUL' flag true in payload we delete the existing ARP instead of updating it. + */ + wiz.arp = function (jsonMap) { + // For unregister calls dont set arp in LS + if(typeof jsonMap["skipResARP"] !== STRING_CONSTANTS.UNDEFINED && jsonMap["skipResARP"]) { + wc.d("Update ARP Request rejected", jsonMap); + return null; + } + + var isOULARP = (typeof jsonMap[STRING_CONSTANTS.IS_OUL] !== STRING_CONSTANTS.UNDEFINED + && jsonMap[STRING_CONSTANTS.IS_OUL] === true) ? true : false; + + if (wzrk_util.isLocalStorageSupported()) { + try { + var arpFromStorage = wiz.readFromLSorCookie(STRING_CONSTANTS.ARP_COOKIE); + if (typeof arpFromStorage == STRING_CONSTANTS.UNDEFINED || isOULARP) { + arpFromStorage = {}; + } + + for (var key in jsonMap) { + if (jsonMap.hasOwnProperty(key)) { + if (jsonMap[key] == -1) { + delete arpFromStorage[key]; + } else { + arpFromStorage[key] = jsonMap[key]; + } + } + } + wiz.saveToLSorCookie(STRING_CONSTANTS.ARP_COOKIE, arpFromStorage); + + + } catch (e) { + wc.e("Unable to parse ARP JSON: " + e); + } + + } + }; + + wiz.processProfileArray = function (profileArr) { + if (wzrk_util.isArray(profileArr) && profileArr.length > 0) { + + for (var index in profileArr) { + if(profileArr.hasOwnProperty(index)) { + var outerObj = profileArr[index]; + var data = {}; + var profileObj; + if (typeof outerObj['Site'] != STRING_CONSTANTS.UNDEFINED) { //organic data from the site + profileObj = outerObj['Site']; + if (wzrk_util.isObjectEmpty(profileObj) || !wiz.isProfileValid(profileObj)) { + return; + } + + } else if (typeof outerObj['Facebook'] != STRING_CONSTANTS.UNDEFINED) { //fb connect data + var FbProfileObj = outerObj['Facebook']; + //make sure that the object contains any data at all + + if (!wzrk_util.isObjectEmpty(FbProfileObj) && (!FbProfileObj['error'])) { + profileObj = wiz.processFBUserObj(FbProfileObj); + } + + } else if (typeof outerObj['Google Plus'] != STRING_CONSTANTS.UNDEFINED) { + var GPlusProfileObj = outerObj['Google Plus']; + if (!wzrk_util.isObjectEmpty(GPlusProfileObj) && (!GPlusProfileObj['error'])) { + profileObj = wiz.processGPlusUserObj(GPlusProfileObj); + } + } + if (typeof profileObj != STRING_CONSTANTS.UNDEFINED && (!wzrk_util.isObjectEmpty(profileObj))) { // profile got set from above + data['type'] = "profile"; + if (typeof profileObj['tz'] === STRING_CONSTANTS.UNDEFINED) { + //try to auto capture user timezone if not present + profileObj['tz'] = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; + } + + data['profile'] = profileObj; + wiz.addToLocalProfileMap(profileObj, true); + data = wiz.addSystemDataToObject(data, undefined); + + wiz.addFlags(data); + var compressedData = wiz.compressData(JSON.stringify(data)); + + var pageLoadUrl = dataPostURL; + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); + + wiz.saveAndFireRequest(pageLoadUrl, blockRequeust); + + } + } + } + } + }; + + /* + anonymousUser => Only GUID present. + foundInCache => Identity used in On User Login is present in LRU_CACHE. So use the guid associated with it. + + Clear the cache in case on On User Login and Block all the request till we get resume requests flag in the response. + When user is found in Cache or the user is anonymous then dont block any requests. Just clear cache (handleCookieFromCache) + + + On every On User Login we deregister the token for older User. + If new user is found in Cache then we call deregister function now + Else we call it once we get guid for new user in 'wiz.s' function. + */ + wiz.processOUL = function (profileArr) { + var sendOULFlag = true; + var addToK = function (ids) { + var k = wiz.readFromLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME); + var g = wiz.readFromLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME); + var kId, flag; + var nowDate = new Date(); + if (typeof k == STRING_CONSTANTS.UNDEFINED) { + k = {}; + kId = ids; + } else {/*check if already exists*/ + kId = k['id']; + var anonymousUser = false; + var foundInCache = false; + if (kId == null) { + kId = ids[0]; + anonymousUser = true; + } + + if (LRU_CACHE == null && wzrk_util.isLocalStorageSupported()) { + LRU_CACHE = new LRU_cache(LRU_CACHE_SIZE); + } + + if (anonymousUser) { + if (wiz.isValueValid(g)) { + LRU_CACHE.set(kId, g); + blockRequeust = false; + } + } else { + for (var idx in ids) { + if(ids.hasOwnProperty(idx)) { + var id = ids[idx]; + if (LRU_CACHE.cache[id]) { + kId = id; + foundInCache = true; + break; + } + } + } + } + + if (foundInCache) { + if (kId !== LRU_CACHE.getLastKey()) { + // Same User + handleCookieFromCache(); + } else { + sendOULFlag = false; + } + var g_from_cache = LRU_CACHE.get(kId); + LRU_CACHE.set(kId, g_from_cache); + wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, g_from_cache); + gcookie = g_from_cache; + + var lastK = LRU_CACHE.getSecondLastKEY(); + if(lastK !== -1) { + var lastGUID = LRU_CACHE.cache[lastK]; + unregisterTokenForGuid(lastGUID); + } + } else { + if (!anonymousUser) { + wiz.clear(); + } else { + if (wiz.isValueValid(g)) { + gcookie = g; + wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, g); + sendOULFlag = false; + } + } + kId = ids[0]; + } + } + k['id'] = kId; + wiz.saveToLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME, k); + }; + + if (wzrk_util.isArray(profileArr) && profileArr.length > 0) { + + for (var index in profileArr) { + if(profileArr.hasOwnProperty(index)) { + var outerObj = profileArr[index]; + var data = {}; + var profileObj; + if (typeof outerObj['Site'] != STRING_CONSTANTS.UNDEFINED) { //organic data from the site + profileObj = outerObj['Site']; + if (wzrk_util.isObjectEmpty(profileObj) || !wiz.isProfileValid(profileObj)) { + return; + } + + } else if (typeof outerObj['Facebook'] != STRING_CONSTANTS.UNDEFINED) { //fb connect data + var FbProfileObj = outerObj['Facebook']; + //make sure that the object contains any data at all + + if (!wzrk_util.isObjectEmpty(FbProfileObj) && (!FbProfileObj['error'])) { + profileObj = wiz.processFBUserObj(FbProfileObj); + } + + } else if (typeof outerObj['Google Plus'] != STRING_CONSTANTS.UNDEFINED) { + var GPlusProfileObj = outerObj['Google Plus']; + if (!wzrk_util.isObjectEmpty(GPlusProfileObj) && (!GPlusProfileObj['error'])) { + profileObj = wiz.processGPlusUserObj(GPlusProfileObj); + } + } + if (typeof profileObj != STRING_CONSTANTS.UNDEFINED && (!wzrk_util.isObjectEmpty(profileObj))) { // profile got set from above + data['type'] = "profile"; + if (typeof profileObj['tz'] === STRING_CONSTANTS.UNDEFINED) { + //try to auto capture user timezone if not present + profileObj['tz'] = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; + } + + data['profile'] = profileObj; + var ids = []; + if (wzrk_util.isLocalStorageSupported()) { + if (typeof profileObj['Identity'] != STRING_CONSTANTS.UNDEFINED) { + ids.push(profileObj['Identity']); + } + if (typeof profileObj['Email'] != STRING_CONSTANTS.UNDEFINED) { + ids.push(profileObj['Email']); + } + if (typeof profileObj['GPID'] != STRING_CONSTANTS.UNDEFINED) { + ids.push("GP:" + profileObj['GPID']); + } + if (typeof profileObj['FBID'] != STRING_CONSTANTS.UNDEFINED) { + ids.push("FB:" + profileObj['FBID']); + } + if (ids.length > 0) { + addToK(ids); + } + } + wiz.addToLocalProfileMap(profileObj, true); + data = wiz.addSystemDataToObject(data, undefined); + + wiz.addFlags(data); + // Adding 'isOUL' flag in true for OUL cases which. + // This flag tells LC to create a new arp object. + // Also we will receive the same flag in response arp which tells to delete existing arp object. + if(sendOULFlag) { + data[STRING_CONSTANTS.IS_OUL] = true; + } + + var compressedData = wiz.compressData(JSON.stringify(data)); + + var pageLoadUrl = dataPostURL; + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); + + // Whenever sendOULFlag is true then dont send arp and gcookie (guid in memory in the request) + // Also when this flag is set we will get another flag from LC in arp which tells us to delete arp + // stored in the cache and replace it with the response arp. + wiz.saveAndFireRequest(pageLoadUrl, blockRequeust, sendOULFlag); + + } + } + } + } + }; + + wiz.processLoginArray = function (loginArr) { + if (wzrk_util.isArray(loginArr) && loginArr.length > 0) { + var profileObj = loginArr.pop(); + var processProfile = typeof profileObj != STRING_CONSTANTS.UNDEFINED && wzrk_util.isObject(profileObj) && + ((typeof profileObj['Site'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Site"]).length > 0) || + (typeof profileObj['Facebook'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Facebook"]).length > 0) || + (typeof profileObj['Google Plus'] != "undefined" && Object.keys(profileObj["Google Plus"]).length > 0)); + if (processProfile) { + setInstantDeleteFlagInK(); + wiz.processOUL([profileObj]); + } else { + //console.error + wc.e("Profile object is in incorrect format"); + } + } + }; + + wiz.overloadArrayPush = function () { + + if (typeof wizrocket['onUserLogin'] === "undefined") { + wizrocket['onUserLogin'] = []; + } + + wizrocket['onUserLogin'].push = function () { + //since arguments is not an array, convert it into an array + wiz.processLoginArray(Array.prototype.slice.call(arguments)); + return 0; + }; + + if (typeof wizrocket['privacy'] === "undefined") { + wizrocket['privacy'] = []; + } + + wizrocket['privacy'].push = function () { + //since arguments is not an array, convert it into an array + wiz.processPrivacyArray(Array.prototype.slice.call(arguments)); + return 0; + }; + + wizrocket['event'].push = function () { + //since arguments is not an array, convert it into an array + wiz.processEventArray(Array.prototype.slice.call(arguments)); + return 0; + }; + + if (typeof wizrocket['notifications'] === STRING_CONSTANTS.UNDEFINED) + wizrocket['notifications'] = []; + + wizrocket['notifications'].push = function () { + wiz.setUpWebPush(Array.prototype.slice.call(arguments)); + return 0; + }; + + + wizrocket['profile'].push = function () { + //since arguments is not an array, convert it into an array + wiz.processProfileArray(Array.prototype.slice.call(arguments)); + return 0; + }; + wizrocket['logout'] = wiz.logout; + wizrocket['clear'] = wiz.clear; + wiz.processLoginArray(wizrocket['onUserLogin']); // process old stuff from the login array before we overloaded the push method + wiz.processPrivacyArray(wizrocket['privacy']); // process old stuff from the privacy array before we overloaded the push method + wiz.processEventArray(wizrocket['event']); // process old stuff from the event array before we overloaded the push method + wiz.processProfileArray(wizrocket['profile']); // process old stuff from the profile array before we overloaded the push method + wiz.setUpWebPush(wizrocket['notifications']); // process old stuff from notifications array before overload + + // clean up the notifications array + while (wizrocket['notifications'].length > 0) + wizrocket['notifications'].pop(); + }; + + var isOptInRequest = false; + + var dropRequestDueToOptOut = function () { + if (isOptInRequest || !wiz.isValueValid(gcookie) || !wzrk_util.isString(gcookie)) { + isOptInRequest = false; + return false; + } + return gcookie.slice(-3) === STRING_CONSTANTS.OPTOUT_COOKIE_ENDSWITH; + }; + + var addUseIPToRequest = function (pageLoadUrl) { + var useIP = wiz.getMetaProp(STRING_CONSTANTS.USEIP_KEY); + if (typeof useIP !== 'boolean') { + useIP = false; + } + return wiz.addToURL(pageLoadUrl, STRING_CONSTANTS.USEIP_KEY, useIP ? 'true' : 'false'); + }; + + wiz.processPrivacyArray = function (privacyArr) { + if (wzrk_util.isArray(privacyArr) && privacyArr.length > 0) { + var privacyObj = privacyArr[0]; + var data = {}; + var profileObj = {}; + if (privacyObj.hasOwnProperty(STRING_CONSTANTS.OPTOUT_KEY)) { + var optOut = privacyObj[STRING_CONSTANTS.OPTOUT_KEY]; + if (typeof optOut === 'boolean') { + profileObj[STRING_CONSTANTS.CT_OPTOUT_KEY] = optOut; + //should be true when user wants to opt in + isOptInRequest = !optOut; + } + } + if (privacyObj.hasOwnProperty(STRING_CONSTANTS.USEIP_KEY)) { + var useIP = privacyObj[STRING_CONSTANTS.USEIP_KEY]; + if (typeof useIP === 'boolean') { + wiz.setMetaProp(STRING_CONSTANTS.USEIP_KEY, useIP); + } + } + if (!wzrk_util.isObjectEmpty(profileObj)) { + data['type'] = "profile"; + data['profile'] = profileObj; + data = wiz.addSystemDataToObject(data, undefined); + var compressedData = wiz.compressData(JSON.stringify(data)); + var pageLoadUrl = dataPostURL; + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); + pageLoadUrl = wiz.addToURL(pageLoadUrl, STRING_CONSTANTS.OPTOUT_KEY, optOut ? 'true' : 'false'); + wiz.saveAndFireRequest(pageLoadUrl, blockRequeust); + } + } + }; + + wiz.saveAndFireRequest = function (url, override, sendOULFlag) { + + var now = wzrk_util.getNow(); + url = wiz.addToURL(url, "rn", ++REQ_N); + var data = url + '&i=' + now + "&sn=" + seqNo; + wiz.backUpEvent(data, REQ_N); + + + if (!blockRequeust || override || (clearCookie !== undefined && clearCookie)) { + if (now == requestTime) { + seqNo++; + } else { + requestTime = now; + seqNo = 0; + } + + wiz.fireRequest(data, false, sendOULFlag); + + } else { + wc.d("Not fired due to block request - " + blockRequeust + " or clearCookie - " + clearCookie); + } + + }; + + +// profile like https://developers.google.com/+/api/latest/people + wiz.processGPlusUserObj = function (user) { + + var profileData = {}; + if (typeof user['displayName'] != STRING_CONSTANTS.UNDEFINED) { + profileData['Name'] = user['displayName']; + } + if (typeof user['id'] != STRING_CONSTANTS.UNDEFINED) { + profileData['GPID'] = user['id'] + ""; + } + + if (typeof user['gender'] != STRING_CONSTANTS.UNDEFINED) { + if (user['gender'] == "male") { + profileData['Gender'] = "M"; + } else if (user['gender'] == "female") { + profileData['Gender'] = "F"; + } else if (user['gender'] == "other") { + profileData['Gender'] = "O"; + } + } + + if (typeof user['image'] != STRING_CONSTANTS.UNDEFINED) { + if (user['image']['isDefault'] == false) { + profileData['Photo'] = user['image'].url.split('?sz')[0]; + } + } + + if (typeof user['emails'] != "undefined") { + for (var emailIdx = 0; emailIdx < user['emails'].length; emailIdx++) { + var emailObj = user['emails'][emailIdx]; + if (emailObj.type == 'account') { + profileData['Email'] = emailObj.value; + } + } + } + + + if (typeof user['organizations'] != "undefined") { + profileData['Employed'] = 'N'; + for (var i = 0; i < user['organizations'].length; i++) { + var orgObj = user['organizations'][i]; + if (orgObj.type == 'work') { + profileData['Employed'] = 'Y'; + } + } + } + + + if (typeof user['birthday'] != STRING_CONSTANTS.UNDEFINED) { + var yyyymmdd = user['birthday'].split('-'); //comes in as "1976-07-27" + profileData['DOB'] = $WZRK_WR.setDate(yyyymmdd[0] + yyyymmdd[1] + yyyymmdd[2]); + } + + + if (typeof user['relationshipStatus'] != STRING_CONSTANTS.UNDEFINED) { + profileData['Married'] = 'N'; + if (user['relationshipStatus'] == 'married') { + profileData['Married'] = 'Y'; + } + } + wc.d("gplus usr profile " + JSON.stringify(profileData)); + + return profileData; + }; + + wiz.processFBUserObj = function (user) { + var profileData = {}; + profileData['Name'] = user['name']; + if (typeof user['id'] != STRING_CONSTANTS.UNDEFINED) { + profileData['FBID'] = user['id'] + ""; + } + // Feb 2014 - FB announced over 58 gender options, hence we specifically look for male or female. Rest we don't care. + if (user['gender'] == "male") { + profileData['Gender'] = "M"; + } else if (user['gender'] == "female") { + profileData['Gender'] = "F"; + } else { + profileData['Gender'] = "O"; + } + + var getHighestEducation = function (eduArr) { + if (typeof eduArr != "undefined") { + var college = ""; + var highschool = ""; + + for (var i = 0; i < eduArr.length; i++) { + var edu = eduArr[i]; + if (typeof edu.type != "undefined") { + var type = edu.type; + if (type == "Graduate School") { + return "Graduate"; + } else if (type == "College") { + college = "1"; + } else if (type == "High School") { + highschool = "1"; + } + } + } + + if (college == "1") { + return "College"; + } else if (highschool == "1") { + return "School"; + } + } + + }; + + if (user['relationship_status'] != STRING_CONSTANTS.UNDEFINED) { + profileData['Married'] = 'N'; + if (user['relationship_status'] == 'Married') { + profileData['Married'] = 'Y'; + } + } + + var edu = getHighestEducation(user['education']); + if (typeof edu !== "undefined") { + profileData['Education'] = edu; + } + + var work = (typeof user['work'] !== STRING_CONSTANTS.UNDEFINED) ? user['work'].length : 0; + if (work > 0) { + profileData['Employed'] = 'Y'; + } else { + profileData['Employed'] = 'N'; + } + + if (typeof user['email'] !== "undefined") { + profileData['Email'] = user['email']; + } + + if (typeof user['birthday'] !== "undefined") { + var mmddyy = user['birthday'].split('/'); //comes in as "08/15/1947" + profileData['DOB'] = $WZRK_WR.setDate(mmddyy[2] + mmddyy[0] + mmddyy[1]); + } + return profileData; + }; + + + wiz.getEmail = function () { + wiz.handleEmailSubscription('-1'); + }; + + + wiz.unSubEmail = function () { + wiz.handleEmailSubscription("0") + }; + + wiz.subEmail = function () { + wiz.handleEmailSubscription("1") + }; + + wiz.handleEmailSubscription = function (subscription) { + + var url_params_as_is = wzrk_util.getURLParams(location.href); // can't use url_params as it is in lowercase above + var encodedEmailId = url_params_as_is['e']; + var encodedProfileProps = url_params_as_is['p']; + + if (typeof encodedEmailId !== STRING_CONSTANTS.UNDEFINED) { + var data = {}; + data['id'] = accountId; //accountId + + var url = emailURL; + url = wiz.addToURL(url, "e", encodedEmailId); + url = wiz.addToURL(url, "d", wiz.compressData(JSON.stringify(data))); + if(encodedProfileProps){ + url = wiz.addToURL(url, "p", encodedProfileProps); + } + + if (subscription != '-1') { + url = wiz.addToURL(url, "sub", subscription); + } + + wiz.fireRequest(url); + } + }; + + + wiz.reportError = function (code, desc) { + wzrk_error['c'] = code; + wzrk_error['d'] = desc; + wc.e(wzrk_error_txt + code + ": " + desc); + }; + + + //to debug put this in the JS console -> sessionStorage['WZRK_D']=""; + wiz.isDebug = function () { + return ((typeof sessionStorage != STRING_CONSTANTS.UNDEFINED) && sessionStorage['WZRK_D'] == ''); + }; + + wiz.isPingContinuous = function () { + return ((typeof wzrk_d != STRING_CONSTANTS.UNDEFINED) && (wzrk_d['ping'] == 'continuous')); + }; + + + wiz.compressData = function (dataObject) { + wc.d('dobj:' + dataObject); + return LZS.compressToBase64(dataObject); + }; + + + wiz.addSystemDataToObject = function (dataObject, ignoreTrim) { + // ignore trim for chrome notifications; undefined everywhere else + if (typeof ignoreTrim === STRING_CONSTANTS.UNDEFINED) { + dataObject = wzrk_util.removeUnsupportedChars(dataObject); + } + if (!wzrk_util.isObjectEmpty(wzrk_error)) { + dataObject['wzrk_error'] = wzrk_error; + wzrk_error = {}; + } + + dataObject['id'] = accountId; + + //Global cookie + if (wiz.isValueValid(gcookie)) { + dataObject['g'] = gcookie; + } + + var obj = wiz.getSessionCookieObject(); + + dataObject['s'] = obj['s']; //Session cookie + dataObject['pg'] = (typeof obj['p'] == STRING_CONSTANTS.UNDEFINED) ? 1 : obj['p']; //Page count + + return dataObject; + }; + + + wiz.getSessionCookieObject = function () { + var scookieStr = wiz.readCookie(SCOOKIE_NAME); + var obj = {}; + + if (scookieStr != null) { + // converting back single quotes to double for JSON parsing - http://www.iandevlin.com/blog/2012/04/html5/cookies-json-localstorage-and-opera + scookieStr = scookieStr.replace(singleQuoteRegex, "\""); + + obj = JSON.parse(scookieStr); + if (!wzrk_util.isObject(obj)) { + obj = {}; + } else { + if (typeof obj['t'] != STRING_CONSTANTS.UNDEFINED) { // check time elapsed since last request + var lasttime = obj['t']; + var now = wzrk_util.getNow(); + if ((now - lasttime) > (SCOOKIE_EXP_TIME_IN_SECS + 60)) // adding 60 seconds to compensate for in-journey requests + + //ideally the cookie should've died after SCOOKIE_EXP_TIME_IN_SECS but it's still around as we can read + //hence we shouldn't use it. + + obj = {}; + + } + } + } + scookieObj = obj; + return obj; + }; + + + wiz.setSessionCookieObject = function (obj) { + + var objStr = JSON.stringify(obj); + + wiz.createBroadCookie(SCOOKIE_NAME, objStr, SCOOKIE_EXP_TIME_IN_SECS, domain); + + }; + + wiz.isValueValid = function (value) { + if (value == null || value == STRING_CONSTANTS.UNDEFINED) { + return false; + } + return true; + }; + + wiz.getGuid = function () { + var guid = null; + if (wiz.isValueValid(gcookie)) { + return gcookie; + } + if (wzrk_util.isLocalStorageSupported()) { + var value = localStorage[STRING_CONSTANTS.GCOOKIE_NAME]; + if (wiz.isValueValid(value)) { + try { + guid = JSON.parse(decodeURIComponent(value)); + } catch (e) { + wc.d("Cannot parse Gcookie from localstorage - must be encoded " + value); + //assumming guids are of size 32. supporting both formats. + // guid can have encodedURIComponent or be without it. + // 1.56e4078ed15749928c042479ec2b4d47 - breaks on JSON.parse(decodeURIComponent()) + // 2.%2256e4078ed15749928c042479ec2b4d47%22 + if (value.length == 32) { + guid = value; + wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, value); + } else { + wc.e("Illegal guid " + value); + } + } + + // Persist to cookie storage if not present there. + if (wiz.isValueValid(guid)) { + wiz.createBroadCookie(STRING_CONSTANTS.GCOOKIE_NAME, guid, COOKIE_EXPIRY, domain); + } + } + } + if (!wiz.isValueValid(guid)) { + guid = wiz.readCookie(STRING_CONSTANTS.GCOOKIE_NAME); + if (wiz.isValueValid(guid) && (guid.indexOf('%') === 0 || + guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) { + guid = null; + } + if (wiz.isValueValid(guid)) { + wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, guid); + } + } + + return guid; + + }; + + wiz.g = function () { + + gcookie = wiz.getGuid(); + + + if (wzrk_util.isLocalStorageSupported()) { + currentSessionId = wiz.getMetaProp('cs'); + } + }; + + wiz.setMetaProp = function (key, value) { + if (wzrk_util.isLocalStorageSupported()) { + var wzrkMetaObj = wiz.readFromLSorCookie(STRING_CONSTANTS.META_COOKIE); + if (typeof wzrkMetaObj == STRING_CONSTANTS.UNDEFINED) { + wzrkMetaObj = {}; + } + if (value === undefined) { + delete wzrkMetaObj[key]; + } else { + wzrkMetaObj[key] = value; + } + wiz.saveToLSorCookie(STRING_CONSTANTS.META_COOKIE, wzrkMetaObj); + } + }; + + + wiz.getMetaProp = function (key) { + if (wzrk_util.isLocalStorageSupported()) { + var wzrkMetaObj = wiz.readFromLSorCookie(STRING_CONSTANTS.META_COOKIE); + if (typeof wzrkMetaObj != STRING_CONSTANTS.UNDEFINED) { + return wzrkMetaObj[key]; + } + } + }; + wiz.getAndClearMetaProp = function (key) { + var value = wiz.getMetaProp(key); + wiz.setMetaProp(key, undefined); + return value; + }; + + wiz.manageSession = function (session) { + //first time. check if current session id in localstorage is same + //if not same then prev = current and current = this new session + if (typeof currentSessionId === STRING_CONSTANTS.UNDEFINED || currentSessionId !== session) { + var currentSessionInLS = wiz.getMetaProp('cs'); + //if sessionId in meta is undefined - set current to both + if (typeof currentSessionInLS === STRING_CONSTANTS.UNDEFINED) { + wiz.setMetaProp('ps', session); + wiz.setMetaProp('cs', session); + wiz.setMetaProp('sc', 1); + } + //not same as session in local storage. new session + else if (currentSessionInLS !== session) { + wiz.setMetaProp('ps', currentSessionInLS); + wiz.setMetaProp('cs', session); + var sessionCount = wiz.getMetaProp('sc'); + if (typeof sessionCount === STRING_CONSTANTS.UNDEFINED) { + sessionCount = 0; + } + wiz.setMetaProp('sc', sessionCount + 1); + } + currentSessionId = session; + } + }; + + + // call back function used to store global and session ids for the user + //resume - this is used to signal that we can resume sending events to server + // was waiting for the server to reset the cookie. everything was getting written to cookie + wiz.s = function (global, session, resume, respNumber, optOutResponse) { + + if (typeof respNumber === "undefined") { + respNumber = 0; + } + + wiz.removeBackup(respNumber); + + if (respNumber > REQ_N) { + //request for some other user so ignore + return; + } + + if (!wiz.isValueValid(gcookie) || resume || typeof optOutResponse === 'boolean') { + if (!wiz.isValueValid(gcookie)) { + //clear useIP meta prop + wiz.getAndClearMetaProp(STRING_CONSTANTS.USEIP_KEY); + } + wc.d("Cookie was " + gcookie + " set to " + global); + gcookie = global; + // global cookie + + if (global) { + if (wzrk_util.isLocalStorageSupported()) { + if (LRU_CACHE == null) { + LRU_CACHE = new LRU_cache(LRU_CACHE_SIZE); + } + + var kId_from_LS = wiz.readFromLSorCookie( + STRING_CONSTANTS.KCOOKIE_NAME + ); + if (kId_from_LS != null && kId_from_LS["id"] && resume) { + var guidFromLRUCache = LRU_CACHE.cache[kId_from_LS["id"]]; + if (!guidFromLRUCache) { + LRU_CACHE.set(kId_from_LS["id"], global); + } + } + wiz.saveToLSorCookie( + STRING_CONSTANTS.GCOOKIE_NAME, + global + ); + + var lastK = LRU_CACHE.getSecondLastKEY(); + if(lastK !== -1) { + var lastGUID = LRU_CACHE.cache[lastK]; + unregisterTokenForGuid(lastGUID); + } + } + } + + wiz.createBroadCookie(STRING_CONSTANTS.GCOOKIE_NAME, global, COOKIE_EXPIRY, domain); + wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, global); + } + + if (resume) { + blockRequeust = false; + wc.d("Resumed requests"); + } + if (wzrk_util.isLocalStorageSupported()) { + wiz.manageSession(session); + } + + // session cookie + var obj = wiz.getSessionCookieObject(); + + // for the race-condition where two responses come back with different session ids. don't write the older session id. + if (typeof obj["s"] == "undefined" || obj["s"] <= session) { + obj["s"] = session; + obj["t"] = wzrk_util.getNow(); // time of last response from server + wiz.setSessionCookieObject(obj); + } + + + if (resume && !processingBackup) { + wiz.processBackupEvents(); + } + + RESP_N = respNumber; + + }; + + wiz.processBackupEvents = function () { + + var backupMap = wiz.readFromLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME); + if (typeof backupMap == 'undefined' || backupMap == null) { + return; + } + processingBackup = true; + for (var idx in backupMap) { + if (backupMap.hasOwnProperty(idx)) { + var backupEvent = backupMap[idx]; + if (typeof backupEvent['fired'] == 'undefined') { + wc.d("Processing backup event : " + backupEvent['q']); + if (typeof backupEvent['q'] != 'undefined') { + wiz.fireRequest(backupEvent['q']); + } + backupEvent['fired'] = true; + } + } + } + wiz.saveToLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME, backupMap); + processingBackup = false; + + }; + + wiz.removeBackup = function (respNo) { + var backupMap = wiz.readFromLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME); + if (typeof backupMap != 'undefined' && backupMap != null && typeof backupMap[respNo] != 'undefined') { + wc.d("del event: " + respNo + " data->" + backupMap[respNo]['q']); + delete backupMap[respNo]; + wiz.saveToLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME, backupMap); + } + }; + + wiz.backUpEvent = function (data, reqNo) { + var backupArr = wiz.readFromLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME); + if (typeof backupArr == 'undefined') { + backupArr = {}; + } + backupArr[reqNo] = {'q': data}; + wiz.saveToLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME, backupArr); + wc.d("stored in " + STRING_CONSTANTS.LCOOKIE_NAME + " reqNo : " + reqNo + "-> " + data); + + }; + + // sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com" + wiz.createBroadCookie = function (name, value, seconds, domain) { + + + //To update an existing "broad domain" cookie, we need to know what domain it was actually set on. + //since a retrieved cookie never tells which domain it was set on, we need to set another test cookie + //to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain + //for updating the actual cookie. + + + if (domain) { + if (typeof broadDomain == STRING_CONSTANTS.UNDEFINED) { // if we don't know the broadDomain yet, then find out + var domainParts = domain.split("."); + var testBroadDomain = ""; + for (var idx = domainParts.length - 1; idx >= 0; idx--) { + testBroadDomain = "." + domainParts[idx] + testBroadDomain; + + // only needed if the cookie already exists and needs to be updated. See note above. + if (wiz.readCookie(name)) { + + // no guarantee that browser will delete cookie, hence create short lived cookies + var testCookieName = "test_" + name + idx; + wiz.createCookie(testCookieName, value, 10, testBroadDomain); // self-destruct after 10 seconds + if (!wiz.readCookie(testCookieName)) { // if test cookie not set, then the actual cookie wouldn't have been set on this domain either. + continue; + } else { // else if cookie set, then delete the test and the original cookie + wiz.deleteCookie(testCookieName, testBroadDomain); + } + } + + wiz.createCookie(name, value, seconds, testBroadDomain); + var tempCookie = wiz.readCookie(name); + if (tempCookie == value) { + broadDomain = testBroadDomain; + //wc.d("Was able to retrieve cookie on: " + testBroadDomain + "->" + name + "=" + tempCookie); + break; + } + } + } else { + wiz.createCookie(name, value, seconds, broadDomain); + } + } else { + wiz.createCookie(name, value, seconds, domain); + } + }; + + //read - cookie get-set: http://www.quirksmode.org/js/cookies.html + + wiz.createCookie = function (name, value, seconds, domain) { + var expires = ""; + var domainStr = ""; + if (seconds) { + var date = new Date(); + date.setTime(date.getTime() + (seconds * 1000)); + + expires = "; expires=" + date.toGMTString(); + } + + if (domain) { + domainStr = "; domain=" + domain; + } + + value = encodeURIComponent(value); + + document.cookie = name + "=" + value + expires + domainStr + "; path=/"; + }; + + wiz.readCookie = function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for (var idx = 0; idx < ca.length; idx++) { + var c = ca[idx]; + while (c.charAt(0) == ' ') { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) == 0) { + return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } + } + return null; + }; + + wiz.deleteCookie = function (name, domain) { + var cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + + if (domain) { + cookieStr = cookieStr + " domain=" + domain + "; path=/"; + } + + document.cookie = cookieStr; + }; + + + wiz.addToURL = function (url, k, v) { + return url + "&" + k + "=" + encodeURIComponent(v); + }; + + var MAX_TRIES = 50; + + var fireRequest = function (url, tries, skipARP, sendOULFlag) { + if (dropRequestDueToOptOut()) { + wc.d("req dropped due to optout cookie: " + gcookie); + return; + } + if ( + !wiz.isValueValid(gcookie) && + RESP_N < REQ_N - 1 && + tries < MAX_TRIES + ) { + setTimeout(function () { + fireRequest(url, tries + 1, skipARP, sendOULFlag); + }, 50); + return; + } + + if(!sendOULFlag) { + if (wiz.isValueValid(gcookie)) { + //add cookie to url + url = wiz.addToURL(url, "gc", gcookie); + } + url = wiz.addARPToRequest(url, skipARP); + } + // url = addUseIPToRequest(url); + url = wiz.addToURL(url, "r", new Date().getTime()); // add epoch to beat caching of the URL + if (wizrocket.hasOwnProperty("plugin")) { + //used to add plugin name in request parameter + var plugin = wizrocket["plugin"]; + url = wiz.addToURL(url, "ct_pl", plugin); + } + if (url.indexOf("chrome-extension:") != -1) { + url = url.replace("chrome-extension:", "https:"); + } + var s = doc.createElement("script"); + s.setAttribute("type", "text/javascript"); + s.setAttribute("src", url); + s.setAttribute("rel", "nofollow"); + s.async = true; + + doc.getElementsByTagName("head")[0].appendChild(s); + wc.d("req snt -> url: " + url); + }; + + wiz.fireRequest = function (url, skipARP, sendOULFlag) { + fireRequest(url, 1, skipARP, sendOULFlag); + }; + + wiz.closeIframe = function (campaignId, divIdIgnored) { + if (typeof campaignId != STRING_CONSTANTS.UNDEFINED && campaignId != '-1') { + if (wzrk_util.isLocalStorageSupported()) { + var campaignObj = wzrk_util.getCampaignObject(); + + var sessionCampaignObj = campaignObj[currentSessionId]; + if (typeof sessionCampaignObj == STRING_CONSTANTS.UNDEFINED) { + sessionCampaignObj = {}; + campaignObj[currentSessionId] = sessionCampaignObj; + } + sessionCampaignObj[campaignId] = 'dnd'; + wzrk_util.saveCampaignObject(campaignObj); + } + } + if (typeof campaignDivMap != STRING_CONSTANTS.UNDEFINED) { + var divId = campaignDivMap[campaignId]; + if (typeof divId != STRING_CONSTANTS.UNDEFINED) { + document.getElementById(divId).style.display = "none"; + if (divId == 'intentPreview') { + if (document.getElementById('intentOpacityDiv') != null) { + document.getElementById('intentOpacityDiv').style.display = "none"; + } + } + } + } + + + }; + + // helper variable to handle race condition and check when notifications were called + var notifApi = {}; + notifApi.notifEnabledFromApi = false; + + /** + * Function is exposed to customer; called as needed after specific events to set up push notifications + * @param displayArgs array: [titleText, bodyText, okButtonText, rejectButtonText] + */ + wiz.setUpWebPush = function (displayArgs) { + if (webPushEnabled && displayArgs.length > 0) { + wiz.handleNotificationRegistration(displayArgs); + } else if (typeof webPushEnabled === STRING_CONSTANTS.UNDEFINED && displayArgs.length > 0) { + notifApi.notifEnabledFromApi = true; + notifApi.displayArgs = displayArgs.slice(); + } else if (webPushEnabled === false && displayArgs.length > 0) { + wc.e('Make sure push notifications are fully enabled and integrated'); + } + + }; + + wiz.setApplicationServerKey = function(applicationServerKey) { + fcmPublicKey = applicationServerKey; + } + + wiz.handleNotificationRegistration = function (displayArgs) { + + // make sure everything is specified + var titleText; + var bodyText; + var okButtonText; + var rejectButtonText; + var okButtonColor; + var skipDialog; + var askAgainTimeInSeconds; + var okCallback; + var rejectCallback; + var subscriptionCallback; + var hidePoweredByCT; + var serviceWorkerPath; + var httpsPopupPath; + var httpsIframePath; + + if (displayArgs.length === 1) { + if (wzrk_util.isObject(displayArgs[0])) { + var notifObj = displayArgs[0]; + titleText = notifObj["titleText"]; + bodyText = notifObj["bodyText"]; + okButtonText = notifObj["okButtonText"]; + rejectButtonText = notifObj["rejectButtonText"]; + okButtonColor = notifObj["okButtonColor"]; + skipDialog = notifObj["skipDialog"]; + askAgainTimeInSeconds = notifObj["askAgainTimeInSeconds"]; + okCallback = notifObj["okCallback"]; + rejectCallback = notifObj["rejectCallback"]; + subscriptionCallback = notifObj["subscriptionCallback"]; + hidePoweredByCT = notifObj["hidePoweredByCT"]; + serviceWorkerPath = notifObj["serviceWorkerPath"]; + httpsPopupPath = notifObj["httpsPopupPath"]; + httpsIframePath = notifObj["httpsIframePath"]; + } + } else { + titleText = displayArgs[0]; + bodyText = displayArgs[1]; + okButtonText = displayArgs[2]; + rejectButtonText = displayArgs[3]; + okButtonColor = displayArgs[4]; + skipDialog = displayArgs[5]; + askAgainTimeInSeconds = displayArgs[6] + } + + if (typeof skipDialog === "undefined") { + skipDialog = false; + } + + if (typeof hidePoweredByCT === "undefined") { + hidePoweredByCT = false; + } + + if (typeof serviceWorkerPath === "undefined") { + serviceWorkerPath = '/clevertap_sw.js'; + } + + // ensure that the browser supports notifications + if (typeof navigator["serviceWorker"] === "undefined") { + return; + } + + // var isHTTP = location.protocol === 'http:' && typeof httpsPopupPath !== "undefined" && + // typeof httpsIframePath !== "undefined"; + + var isHTTP = typeof httpsPopupPath !== "undefined" && typeof httpsIframePath !== "undefined"; + + // make sure the site is on https for chrome notifications + if (location.protocol !== 'https:' && document.location.hostname !== 'localhost' && !isHTTP) { + wc.e("Make sure you are https or localhost to register for notifications"); + return; + } + + // right now, we only support Chrome V50 & higher & Firefox + if (navigator.userAgent.indexOf('Chrome') !== -1) { + chromeAgent = navigator.userAgent.match(/Chrome\/(\d+)/); + if (typeof chromeAgent === STRING_CONSTANTS.UNDEFINED || parseInt(chromeAgent[1], 10) < 50) + return; + }else if(navigator.userAgent.indexOf('Firefox') !== -1){ + firefoxAgent = navigator.userAgent.match(/Firefox\/(\d+)/); + if(typeof firefoxAgent === STRING_CONSTANTS.UNDEFINED || parseInt(firefoxAgent[1], 10) < 50) + return; + } else { + return; + } + + // we check for the cookie in setUpChromeNotifications(); the tokens may have changed + + if (!isHTTP) { + if (typeof Notification === STRING_CONSTANTS.UNDEFINED) { + return; + } + // handle migrations from other services -> chrome notifications may have already been asked for before + if (Notification.permission === 'granted') { + // skip the dialog and register + wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath); + return; + } else if (Notification.permission === 'denied') { + // we've lost this profile :'( + return; + } + + if (skipDialog) { + wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath); + return; + } + } + + // make sure the right parameters are passed + if (!titleText || !bodyText || !okButtonText || !rejectButtonText) { + wc.e('Missing input parameters; please specify title, body, ok button and cancel button text'); + return; + } + + // make sure okButtonColor is formatted properly + if (typeof okButtonColor === STRING_CONSTANTS.UNDEFINED || !okButtonColor.match(/^#[a-f\d]{6}$/i)) { + okButtonColor = "#f28046"; // default color for positive button + } + + // make sure the user isn't asked for notifications more than askAgainTimeInSeconds + var now = new Date().getTime() / 1000; + if (typeof (wiz.getMetaProp('notif_last_time')) === STRING_CONSTANTS.UNDEFINED) { + wiz.setMetaProp('notif_last_time', now); + } else { + if (typeof askAgainTimeInSeconds === "undefined") { + // 7 days by default + askAgainTimeInSeconds = 7 * 24 * 60 * 60; + } + + if (now - wiz.getMetaProp('notif_last_time') < askAgainTimeInSeconds) { + return; + } else { + // continue asking + wiz.setMetaProp('notif_last_time', now); + } + } + + if (isHTTP) { + //add the https iframe + var httpsIframe = document.createElement('iframe'); + httpsIframe.setAttribute('style', 'display:none;'); + httpsIframe.setAttribute('src', httpsIframePath); + document.body.appendChild(httpsIframe); + window.addEventListener("message", function (event) { + if (typeof event['data'] !== "undefined") { + try { + var obj = JSON.parse(event['data']); + } catch (e) { + //not a call from our iframe + return; + } + if (typeof obj['state'] !== "undefined") { + if (obj['from'] === "ct" && obj['state'] === "not") { + wiz.addWizAlertJS().onload = function () { + // create our wizrocket popup + wzrkPermissionPopup['wizAlert']({ + 'title': titleText, + 'body': bodyText, + 'confirmButtonText': okButtonText, + 'confirmButtonColor': okButtonColor, + 'rejectButtonText': rejectButtonText, + 'hidePoweredByCT': hidePoweredByCT + }, function (enabled) { // callback function + if (enabled) { + // the user accepted on the dialog box + if (typeof okCallback !== "undefined" && typeof okCallback === "function") { + okCallback(); + } + //redirect to popup.html + window.open(httpsPopupPath); + } else { + if (typeof rejectCallback !== "undefined" && typeof rejectCallback === "function") { + rejectCallback(); + } + } + wiz.removeWizAlertJS(); + }); + } + } + } + } + // console.log(event.origin); + }, false); + } else { + wiz.addWizAlertJS().onload = function () { + // create our wizrocket popup + wzrkPermissionPopup['wizAlert']({ + 'title': titleText, + 'body': bodyText, + 'confirmButtonText': okButtonText, + 'confirmButtonColor': okButtonColor, + 'rejectButtonText': rejectButtonText, + 'hidePoweredByCT': hidePoweredByCT + }, function (enabled) { // callback function + if (enabled) { + // the user accepted on the dialog box + if (typeof okCallback !== "undefined" && typeof okCallback === "function") { + okCallback(); + } + wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath); + } else { + if (typeof rejectCallback !== "undefined" && typeof rejectCallback === "function") { + rejectCallback(); + } + } + wiz.removeWizAlertJS(); + }); + } + } + }; + + wiz.tr = function (msg) { + + var doCampHouseKeeping = function (targetingMsgJson) { + + var campaignId = targetingMsgJson['wzrk_id'].split('_')[0]; + var today = wzrk_util.getToday(); + + if (wzrk_util.isLocalStorageSupported()) { + delete sessionStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; + var campObj = wzrk_util.getCampaignObject(); + + //global session limit. default is 1 + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] == STRING_CONSTANTS.UNDEFINED) { + targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] = 1; + } + var excludeFromFreqCaps = -1, campaignSessionLimit = -1, campaignDailyLimit = -1, + campaignTotalLimit = -1, + totalDailyLimit = -1, totalSessionLimit = -1; + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['efc'] != STRING_CONSTANTS.UNDEFINED) { + excludeFromFreqCaps = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['efc'], 10); + } + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['mdc'] != STRING_CONSTANTS.UNDEFINED) { + campaignSessionLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['mdc'], 10); + } + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tdc'] != STRING_CONSTANTS.UNDEFINED) { + campaignDailyLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tdc'], 10); + } + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tlc'] != STRING_CONSTANTS.UNDEFINED) { + campaignTotalLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tlc'], 10); + } + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmp'] != STRING_CONSTANTS.UNDEFINED) { + totalDailyLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmp'], 10); + } + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] != STRING_CONSTANTS.UNDEFINED) { + totalSessionLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'], 10); + } + + + function incrCount(obj, campaignId, excludeFromFreqCaps) { + var currentCount = 0, totalCount = 0; + if (typeof obj[campaignId] != STRING_CONSTANTS.UNDEFINED) { + currentCount = obj[campaignId]; + } + currentCount++; + if (typeof obj['tc'] != STRING_CONSTANTS.UNDEFINED) { + totalCount = obj['tc']; + } + //if exclude from caps then dont add to total counts + if (excludeFromFreqCaps < 0) { + totalCount++; + } + + obj['tc'] = totalCount; + obj[campaignId] = currentCount; + } + + + //session level capping + var sessionObj = campObj[currentSessionId]; + if (typeof sessionObj != STRING_CONSTANTS.UNDEFINED) { + var campaignSessionCount = sessionObj[campaignId]; + var totalSessionCount = sessionObj['tc']; + //dnd + if (campaignSessionCount == 'dnd') { + return false; + } + + //session + if (totalSessionLimit > 0 && totalSessionCount >= totalSessionLimit && excludeFromFreqCaps < 0) { + return false; + } + //campaign session + if (campaignSessionLimit > 0 && campaignSessionCount >= campaignSessionLimit) { + return false; + } + } else { + sessionObj = {}; + campObj[currentSessionId] = sessionObj; + } + + //daily level capping + var dailyObj = campObj[today]; + if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED) { + var campaignDailyCount = dailyObj[campaignId]; + var totalDailyCount = dailyObj['tc']; + //daily + if (totalDailyLimit > 0 && totalDailyCount >= totalDailyLimit && excludeFromFreqCaps < 0) { + return false; + } + //campaign daily + if (campaignDailyLimit > 0 && campaignDailyCount >= campaignDailyLimit) { + return false; + } + } else { + dailyObj = {}; + campObj[today] = dailyObj; + } + + var globalObj = campObj[STRING_CONSTANTS.GLOBAL]; + if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) { + var campaignTotalCount = globalObj[campaignId]; + //campaign total + if (campaignTotalLimit > 0 && campaignTotalCount >= campaignTotalLimit) { + return false; + } + } else { + globalObj = {}; + campObj[STRING_CONSTANTS.GLOBAL] = globalObj; + } + + + } + //delay + if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay'] > 0) { + var delay = targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay']; + targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay'] = 0; + setTimeout(wiz.tr, delay * 1000, msg); + return false; + } + + incrCount(sessionObj, campaignId, excludeFromFreqCaps); + incrCount(dailyObj, campaignId, excludeFromFreqCaps); + incrCount(globalObj, campaignId, excludeFromFreqCaps); + + //get ride of stale sessions and day entries + var newCampObj = {}; + newCampObj[currentSessionId] = sessionObj; + newCampObj[today] = dailyObj; + newCampObj[STRING_CONSTANTS.GLOBAL] = globalObj; + wzrk_util.saveCampaignObject(newCampObj); + + + }; + + var getCookieParams = function () { + if (!wiz.isValueValid(gcookie)) { + gcookie = wiz.getGuid(); + } + if (scookieObj == null) { + scookieObj = wiz.getSessionCookieObject(); + } + return '&t=wc&d=' + encodeURIComponent(LZS.compressToBase64(gcookie + '|' + scookieObj['p'] + '|' + scookieObj['s'])); + }; + + var setupClickEvent = function (onClick, targetingMsgJson, contentDiv, divId, isLegacy) { + if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { + var ctaElement; + if (isLegacy) { + ctaElement = contentDiv; + } else { + var jsCTAElements = contentDiv.getElementsByClassName('jsCT_CTA'); + if (typeof jsCTAElements != STRING_CONSTANTS.UNDEFINED && jsCTAElements.length == 1) { + ctaElement = jsCTAElements[0]; + } + } + var jsFunc = targetingMsgJson['display']['jsFunc']; + var isPreview = targetingMsgJson['display']['preview']; + if (typeof isPreview == STRING_CONSTANTS.UNDEFINED) { + onClick += getCookieParams(); + } + + if (typeof ctaElement != STRING_CONSTANTS.UNDEFINED) { + ctaElement.onclick = + function () { + //invoke js function call + if (typeof jsFunc != STRING_CONSTANTS.UNDEFINED) { + //track notification clicked event + if (typeof isPreview == STRING_CONSTANTS.UNDEFINED) { + wiz.fireRequest(onClick); + } + invokeExternalJs(jsFunc, targetingMsgJson); + //close iframe. using -1 for no campaignId + wiz.closeIframe('-1', divId); + return; + } + //pass on the gcookie|page|scookieId for capturing the click event + if (targetingMsgJson['display']['window'] == '1') { + window.open(onClick, '_blank'); + } else { + window.location = onClick; + } + } + } + } + }; + + var invokeExternalJs = function (jsFunc, targetingMsgJson) { + var func = window.parent[jsFunc]; + if (typeof func == "function") { + if (typeof targetingMsgJson['display']['kv'] !== STRING_CONSTANTS.UNDEFINED) { + func(targetingMsgJson['display']['kv']); + } else { + func(); + } + } + }; + + var setupClickUrl = function (onClick, targetingMsgJson, contentDiv, divId, isLegacy) { + incrementImpression(targetingMsgJson); + setupClickEvent(onClick, targetingMsgJson, contentDiv, divId, isLegacy); + }; + + var incrementImpression = function (targetingMsgJson) { + var data = {}; + data['type'] = "event"; + data['evtName'] = "Notification Viewed"; + data['evtData'] = {"wzrk_id": targetingMsgJson['wzrk_id']}; + processEvent(data); + }; + + var renderFooterNotification = function (targetingMsgJson) { + var campaignId = targetingMsgJson['wzrk_id'].split('_')[0]; + var displayObj = targetingMsgJson['display']; + + if (displayObj['layout'] == 1) { + return showExitIntent(undefined, targetingMsgJson); + } + if (doCampHouseKeeping(targetingMsgJson) == false) { + return; + } + + var divId = 'wizParDiv' + displayObj['layout']; + + if (document.getElementById(divId) != null) { + return; + } + campaignDivMap[campaignId] = divId; + var isBanner = displayObj['layout'] == 2; + var msgDiv = document.createElement('div'); + msgDiv.id = divId; + var viewHeight = window.innerHeight; + var viewWidth = window.innerWidth; + var legacy = false; + + + if (!isBanner) { + var marginBottom = viewHeight * 5 / 100; + var contentHeight = 10; + var right = viewWidth * 5 / 100; + var bottomPosition = contentHeight + marginBottom; + var width = viewWidth * 30 / 100 + 20; + var widthPerct = 'width:30%;'; + //for small devices - mobile phones + if ((/mobile/i.test(navigator.userAgent) || (/mini/i.test(navigator.userAgent))) && /iPad/i.test(navigator.userAgent) == false) { + width = viewWidth * 85 / 100 + 20; + right = viewWidth * 5 / 100; + bottomPosition = viewHeight * 5 / 100; + widthPerct = 'width:80%;'; + //medium devices - tablets + } else if ('ontouchstart' in window || (/tablet/i.test(navigator.userAgent))) { + width = viewWidth * 50 / 100 + 20; + right = viewWidth * 5 / 100; + bottomPosition = viewHeight * 5 / 100; + widthPerct = 'width:50%;'; + } + + //legacy footer notif + if (typeof displayObj['proto'] == STRING_CONSTANTS.UNDEFINED) { + legacy = true; + msgDiv.setAttribute('style', 'display:block;overflow:hidden; bottom:' + bottomPosition + 'px !important;width:' + width + 'px !important;right:' + right + 'px !important;position:fixed;z-index:2147483647;'); + } else { + msgDiv.setAttribute('style', widthPerct + displayObj['iFrameStyle']); + } + } else { + msgDiv.setAttribute('style', displayObj['iFrameStyle']); + } + document.body.appendChild(msgDiv); + var iframe = document.createElement('iframe'); + + var borderRadius = displayObj['br'] == false ? "0" : "8"; + + iframe['frameborder'] = '0px'; + iframe['marginheight'] = '0px'; + iframe['marginwidth'] = '0px'; + iframe['scrolling'] = 'no'; + iframe['id'] = 'wiz-iframe'; + var onClick = targetingMsgJson['display']['onClick']; + var pointerCss = ''; + if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { + pointerCss = 'cursor:pointer;'; + } + + var html; + //direct html + if (targetingMsgJson['msgContent']['type'] === 1) { + html = targetingMsgJson['msgContent']['html']; + html = html.replace('##campaignId##', campaignId); + } else { + var css = '' + + ''; + + var bgColor, textColor, btnBg, leftTd, btColor; + if (targetingMsgJson['display']['theme'] == 'dark') { + bgColor = "#2d2d2e"; + textColor = "#eaeaea"; + btnBg = '#353535'; + leftTd = '#353535'; + btColor = '#ffffff'; + } else { + bgColor = "#ffffff"; + textColor = "#000000"; + leftTd = '#f4f4f4'; + btnBg = '#a5a6a6'; + btColor = '#ffffff'; + } + var titleText = targetingMsgJson['msgContent']['title']; + var descriptionText = targetingMsgJson['msgContent']['description']; + var imageTd = ""; + if (typeof targetingMsgJson['msgContent']['imageUrl'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson['msgContent']['imageUrl'] != '') { + imageTd = ""; + } + var onClickStr = "parent.$WZRK_WR.closeIframe(" + campaignId + ",'" + divId + "');"; + var title = "
" + + "×" + + "
" + + "" + + //""+ + "" + imageTd + "
" + + "
" + titleText + "
"; + var body = "
" + descriptionText + "
"; + html = css + title + body; + } + + + iframe.setAttribute('style', 'z-index: 2147483647; display:block; width: 100% !important; border:0px !important; border-color:none !important;'); + msgDiv.appendChild(iframe); + var ifrm = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument; + var doc = ifrm.document; + + doc.open(); + doc.write(html); + doc.close(); + + function adjustIFrameHeight() { + //adjust iframe and body height of html inside correctly + contentHeight = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv').scrollHeight; + if (displayObj['custom-editor'] !== true && !isBanner) { + contentHeight += 25; + } + document.getElementById("wiz-iframe").contentDocument.body.style.margin = "0px"; + document.getElementById("wiz-iframe").style.height = contentHeight + "px"; + } + + var ua = navigator.userAgent.toLowerCase(); + if (ua.indexOf('safari') !== -1) { + if (ua.indexOf('chrome') > -1) { + iframe.onload = function () { + adjustIFrameHeight(); + var contentDiv = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv'); + setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); + }; + } else { + var inDoc = iframe.contentDocument || iframe.contentWindow; + if (inDoc.document) inDoc = inDoc.document; + // safari iphone 7+ needs this. + adjustIFrameHeight(); + var _timer = setInterval(function () { + if (inDoc.readyState === 'complete') { + clearInterval(_timer); + //adjust iframe and body height of html inside correctly + adjustIFrameHeight(); + var contentDiv = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv'); + setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); + } + }, 10); + } + } else { + iframe.onload = function () { + //adjust iframe and body height of html inside correctly + adjustIFrameHeight(); + var contentDiv = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv'); + setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); + }; + } + }; + + var _callBackCalled = false; + + var showFooterNotification = function (targetingMsgJson) { + + + var onClick = targetingMsgJson['display']['onClick']; + if (wizrocket.hasOwnProperty("notificationCallback") && + typeof wizrocket["notificationCallback"] !== "undefined" && + typeof wizrocket["notificationCallback"] === "function") { + var notificationCallback = wizrocket["notificationCallback"]; + if (!_callBackCalled) { + var inaObj = {}; + inaObj["msgContent"] = targetingMsgJson["msgContent"]; + inaObj["msgId"] = targetingMsgJson["wzrk_id"]; + if (typeof targetingMsgJson['display']['kv'] !== STRING_CONSTANTS.UNDEFINED) { + inaObj["kv"] = targetingMsgJson['display']['kv']; + } + wizrocket["raiseNotificationClicked"] = function () { + if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { + var jsFunc = targetingMsgJson['display']['jsFunc']; + onClick += getCookieParams(); + + //invoke js function call + if (typeof jsFunc != STRING_CONSTANTS.UNDEFINED) { + //track notification clicked event + wiz.fireRequest(onClick); + invokeExternalJs(jsFunc, targetingMsgJson); + return; + } + //pass on the gcookie|page|scookieId for capturing the click event + if (targetingMsgJson['display']['window'] == '1') { + window.open(onClick, '_blank'); + } else { + window.location = onClick; + } + } + }; + wizrocket["raiseNotificationViewed"] = function () { + incrementImpression(targetingMsgJson); + }; + notificationCallback(inaObj); + _callBackCalled = true; + } + } else { + renderFooterNotification(targetingMsgJson); + + } + }; + var exitintentObj; + var showExitIntent = function (event, targetObj) { + var targetingMsgJson; + if (typeof event != STRING_CONSTANTS.UNDEFINED && event['clientY'] > 0) { + return; + } + if (typeof targetObj == STRING_CONSTANTS.UNDEFINED) { + targetingMsgJson = exitintentObj; + } else { + targetingMsgJson = targetObj; + } + + if (document.getElementById("intentPreview") != null) { + return; + } + //dont show exit intent on tablet/mobile - only on desktop + if (typeof targetingMsgJson['display']['layout'] == STRING_CONSTANTS.UNDEFINED && + ((/mobile/i.test(navigator.userAgent)) || (/mini/i.test(navigator.userAgent)) || (/iPad/i.test(navigator.userAgent)) || + ('ontouchstart' in window) || (/tablet/i.test(navigator.userAgent)))) { + return; + } + + var campaignId = targetingMsgJson['wzrk_id'].split('_')[0]; + if (doCampHouseKeeping(targetingMsgJson) == false) { + return; + } + + campaignDivMap[campaignId] = 'intentPreview'; + var legacy = false; + var opacityDiv = document.createElement('div'); + opacityDiv.id = 'intentOpacityDiv'; + opacityDiv.setAttribute('style', 'position: fixed;top: 0;bottom: 0;left: 0;width: 100%;height: 100%;z-index: 2147483646;background: rgba(0,0,0,0.7);'); + document.body.appendChild(opacityDiv); + + var msgDiv = document.createElement('div'); + msgDiv.id = 'intentPreview'; + + if (typeof targetingMsgJson['display']['proto'] == STRING_CONSTANTS.UNDEFINED) { + legacy = true; + msgDiv.setAttribute('style', 'display:block;overflow:hidden;top:55% !important;left:50% !important;position:fixed;z-index:2147483647;width:600px !important;height:600px !important;margin:-300px 0 0 -300px !important;'); + } else { + msgDiv.setAttribute('style', targetingMsgJson['display']['iFrameStyle']); + } + document.body.appendChild(msgDiv); + var iframe = document.createElement('iframe'); + var borderRadius = targetingMsgJson['display']['br'] == false ? "0" : "8"; + iframe.frameborder = '0px'; + iframe.marginheight = '0px'; + iframe.marginwidth = '0px'; + iframe.scrolling = 'no'; + iframe.id = 'wiz-iframe-intent'; + var onClick = targetingMsgJson['display']['onClick']; + var pointerCss = ''; + if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { + pointerCss = 'cursor:pointer;'; + } + var html; + //direct html + if (targetingMsgJson['msgContent']['type'] == 1) { + html = targetingMsgJson['msgContent']['html']; + html = html.replace('##campaignId##', campaignId); + } else { + var css = '' + + ''; + + var bgColor, textColor, btnBg, btColor; + if (targetingMsgJson['display']['theme'] == 'dark') { + bgColor = "#2d2d2e"; + textColor = "#eaeaea"; + btnBg = '#353535'; + btColor = '#ffffff'; + } else { + bgColor = "#ffffff"; + textColor = "#000000"; + btnBg = '#a5a6a6'; + btColor = '#ffffff'; + } + var titleText = targetingMsgJson['msgContent']['title']; + var descriptionText = targetingMsgJson['msgContent']['description']; + var ctaText = ""; + if (typeof targetingMsgJson['msgContent']['ctaText'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson['msgContent']['ctaText'] != '') { + ctaText = ""; + } + + var imageTd = ""; + if (typeof targetingMsgJson['msgContent']['imageUrl'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson['msgContent']['imageUrl'] != '') { + imageTd = "
 + titleText +
"; + } + var onClickStr = "parent.$WZRK_WR.closeIframe(" + campaignId + ",'intentPreview');"; + var title = "
" + + "×" + + "
" + + "
" + titleText + "
"; + var body = "
" + descriptionText + "
" + imageTd + ctaText + + "
"; + html = css + title + body; + } + iframe.setAttribute('style', 'z-index: 2147483647; display:block; height: 100% !important; width: 100% !important;min-height:80px !important;border:0px !important; border-color:none !important;'); + msgDiv.appendChild(iframe); + var ifrm = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument; + var doc = ifrm.document; + + doc.open(); + doc.write(html); + doc.close(); + + var contentDiv = document.getElementById("wiz-iframe-intent").contentDocument.getElementById('contentDiv'); + setupClickUrl(onClick, targetingMsgJson, contentDiv, 'intentPreview', legacy); + + + }; + + + if (!document.body) { + if (wiz_counter < 6) { + wiz_counter++; + setTimeout(wiz.tr, 1000, msg); + } + return; + } + if (typeof msg['inapp_notifs'] != STRING_CONSTANTS.UNDEFINED) { + for (var index = 0; index < msg['inapp_notifs'].length; index++) { + var target_notif = msg['inapp_notifs'][index]; + if (typeof target_notif['display']['wtarget_type'] == STRING_CONSTANTS.UNDEFINED || target_notif['display']['wtarget_type'] == 0) { + showFooterNotification(target_notif); + } else if (target_notif['display']['wtarget_type'] == 1) { // if display['wtarget_type']==1 then exit intent + exitintentObj = target_notif; + window.document.body.onmouseleave = showExitIntent; + } + + } + } + + var mergeEventMap = function (newEvtMap) { + if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { + globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE); + if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { + globalEventsMap = newEvtMap; + return; + } + } + for (var key in newEvtMap) { + if (newEvtMap.hasOwnProperty(key)) { + var oldEvtObj = globalEventsMap[key]; + var newEvtObj = newEvtMap[key]; + if (typeof globalEventsMap[key] != STRING_CONSTANTS.UNDEFINED) { + if (typeof newEvtObj[0] != STRING_CONSTANTS.UNDEFINED && newEvtObj[0] > oldEvtObj[0]) { + globalEventsMap[key] = newEvtObj; + } + } else { + globalEventsMap[key] = newEvtObj; + } + } + } + }; + + + if (wzrk_util.isLocalStorageSupported()) { + try { + if (typeof msg['evpr'] != STRING_CONSTANTS.UNDEFINED) { + var eventsMap = msg['evpr']['events']; + var profileMap = msg['evpr']['profile']; + var syncExpiry = msg['evpr']['expires_in']; + var now = wzrk_util.getNow(); + wiz.setMetaProp('lsTime', now); + wiz.setMetaProp('exTs', syncExpiry); + mergeEventMap(eventsMap); + wiz.saveToLSorCookie(STRING_CONSTANTS.EV_COOKIE, globalEventsMap); + if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { + wiz.addToLocalProfileMap(profileMap, true); + } else { + wiz.addToLocalProfileMap(profileMap, false); + } + } + if (typeof msg['arp'] != STRING_CONSTANTS.UNDEFINED) { + wiz.arp(msg['arp']); + } + if (typeof msg['inapp_stale'] != STRING_CONSTANTS.UNDEFINED) { + var campObj = wzrk_util.getCampaignObject(); + var globalObj = campObj['global']; + if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) { + for (var idx in msg['inapp_stale']) { + if (msg['inapp_stale'].hasOwnProperty(idx)) { + delete globalObj[msg['inapp_stale'][idx]]; + } + } + } + wzrk_util.saveCampaignObject(campObj); + + } + } catch (e) { + wc.e("Unable to persist evrp/arp: " + e); + } + } + }; + + //link - actual link, type could be - "ctr" or "view" + wiz.getWrappedLink = function (link, targetId, type) { + + var data = {}; + data['sendTo'] = link; + data['targetId'] = targetId; + data['epoch'] = wzrk_util.getNow(); + + if (type != null) { + data['type'] = type; + } else { + data['type'] = 'view'; + } + + data = wiz.addSystemDataToObject(data, undefined); + return wiz.addToURL(recorderURL, "d", wiz.compressData(JSON.stringify(data))); + + }; + + + wiz.getMessageTemplate = function () { + var body = ""; + body = body + ''; + body = body + '
'; + return body; + }; + + wiz.getMessageHeadTemplate = function () { + var head = ''; + head = head + ''; + head = head + ''; + head = head + ''; + head = head + ''; + head = head + ""; + return head; + + }; + + + wiz.isChargedEventStructureValid = function (chargedObj) { + if (wzrk_util.isObject(chargedObj)) { + for (var key in chargedObj) { + if (chargedObj.hasOwnProperty(key)) { + + + if (key == "Items") { + if (!wzrk_util.isArray(chargedObj[key])) { + return false; + } + + if (chargedObj[key].length > 16) { + wiz.reportError(522, "Charged Items exceed 16 limit. Actual count: " + chargedObj[key].length + ". Additional items will be dropped."); + } + + for (var itemKey in chargedObj[key]) { + if (chargedObj[key].hasOwnProperty(itemKey)) { // since default array implementation could be overridden - e.g. Teabox site + if (!wzrk_util.isObject(chargedObj[key][itemKey]) || !wiz.isEventStructureFlat(chargedObj[key][itemKey])) { + return false; + } + } + } + } else { //Items + if (wzrk_util.isObject(chargedObj[key]) || wzrk_util.isArray(chargedObj[key])) { + return false; + } else if (wzrk_util.isDateObject(chargedObj[key])) { + chargedObj[key] = wzrk_util.convertToWZRKDate(chargedObj[key]); + } + + } // if key == Items + } + } //for.. + //save charged Id + if (wzrk_util.isString(chargedObj[STRING_CONSTANTS.CHARGED_ID]) || wzrk_util.isNumber(chargedObj[STRING_CONSTANTS.CHARGED_ID])) { + //casting chargeedId to string + var chargedId = chargedObj[STRING_CONSTANTS.CHARGED_ID] + ""; + if (typeof globalChargedId == STRING_CONSTANTS.UNDEFINED) { + globalChargedId = wiz.readFromLSorCookie(STRING_CONSTANTS.CHARGEDID_COOKIE_NAME); + } + if (typeof globalChargedId != STRING_CONSTANTS.UNDEFINED && globalChargedId.trim() === chargedId.trim()) { + //drop event- duplicate charged id + wc.e("Duplicate Charged Id - Dropped" + chargedObj); + return false; + } + globalChargedId = chargedId; + wiz.saveToLSorCookie(STRING_CONSTANTS.CHARGEDID_COOKIE_NAME, chargedId); + } + return true; + } // if object (chargedObject) + return false; + }; + + + //events can't have any nested structure or arrays + wiz.isEventStructureFlat = function (eventObj) { + if (wzrk_util.isObject(eventObj)) { + for (var key in eventObj) { + if (eventObj.hasOwnProperty(key)) { + if (wzrk_util.isObject(eventObj[key]) || wzrk_util.isArray(eventObj[key])) { + return false; + } else if (wzrk_util.isDateObject(eventObj[key])) { + eventObj[key] = wzrk_util.convertToWZRKDate(eventObj[key]); + } + } + } + return true; + } + return false; + + }; + + wiz.isProfileValid = function (profileObj) { + + if (wzrk_util.isObject(profileObj)) { + for (var profileKey in profileObj) { + if (profileObj.hasOwnProperty(profileKey)) { + var valid = true; + var profileVal = profileObj[profileKey]; + + if (typeof profileVal == STRING_CONSTANTS.UNDEFINED) { + delete profileObj[profileKey]; + continue; + } + if (profileKey == 'Gender' && !profileVal.match(/^M$|^F$/)) { + valid = false; + wc.e(wzrk_msg['gender-error']); + } + + if (profileKey == 'Employed' && !profileVal.match(/^Y$|^N$/)) { + valid = false; + wc.e(wzrk_msg['employed-error']); + } + + if (profileKey == 'Married' && !profileVal.match(/^Y$|^N$/)) { + valid = false; + wc.e(wzrk_msg['married-error']); + } + + if (profileKey == 'Education' && !profileVal.match(/^School$|^College$|^Graduate$/)) { + valid = false; + wc.e(wzrk_msg['education-error']); + } + + if (profileKey == 'Age' && typeof profileVal != STRING_CONSTANTS.UNDEFINED) { + if (wzrk_util.isConvertibleToNumber(profileVal)) { + profileObj['Age'] = +profileVal; + } else { + valid = false; + wc.e(wzrk_msg['age-error']); + } + } + + // dob will come in like this - $dt_19470815 or dateObject + if (profileKey == 'DOB') { + if (((!(/^\$D_/).test(profileVal) || (profileVal + "").length != 11)) && !wzrk_util.isDateObject(profileVal)) { + valid = false; + wc.e(wzrk_msg['dob-error']); + } + + if (wzrk_util.isDateObject(profileVal)) { + profileObj[profileKey] = wzrk_util.convertToWZRKDate(profileVal); + } + } else if (wzrk_util.isDateObject(profileVal)) { + profileObj[profileKey] = wzrk_util.convertToWZRKDate(profileVal); + } + + if (profileKey == 'Phone' && !wzrk_util.isObjectEmpty(profileVal)) { + if (profileVal.length > 8 && (profileVal.charAt(0) == '+')) { // valid phone number + profileVal = profileVal.substring(1, profileVal.length); + if (wzrk_util.isConvertibleToNumber(profileVal)) { + profileObj['Phone'] = +profileVal; + } else { + valid = false; + wc.e(wzrk_msg['phone-format-error'] + ". Removed."); + } + } else { + valid = false; + wc.e(wzrk_msg['phone-format-error'] + ". Removed."); + } + } + + + if (!valid) { + delete profileObj[profileKey]; + } + } + } + + } + + return valid; + }; //isProfileValid + + wiz.setDate = function (dt) { + return wzrk_util.setDate(dt); + }; + + wiz.setEnum = function (enumVal) { + if (wzrk_util.isString(enumVal) || wzrk_util.isNumber(enumVal)) { + return "$E_" + enumVal; + } + wc.e(wzrk_msg['enum-format-error']); + }; + + // list of functions that the closure compiler shouldn't rename + // https://developers.google.com/closure/compiler/docs/api-tutorial3 + wiz['s'] = wiz.s; + wiz['is_onloadcalled'] = wiz.is_onloadcalled; + wiz['setDate'] = wiz.setDate; + wiz['enableWebPush'] = wiz.enableWebPush; // support for web push notifications + wiz['setEnum'] = wiz.setEnum; + wiz['tr'] = wiz.tr; + wiz['push'] = wiz.push; + wiz['closeIframe'] = wiz.closeIframe; + wiz['getEmail'] = wiz.getEmail; + wiz['unSubEmail'] = wiz.unSubEmail; + wiz['subEmail'] = wiz.subEmail; + wiz['logout'] = wiz.logout; + wiz['clear'] = wiz.clear; + wizrocket['getCleverTapID'] = wiz.getCleverTapID; + + +// ---------- compression part ---------- + + var LZS = { + + _f: String.fromCharCode, + + getKeyStr: function () { + var key = ""; + var i = 0; + + for (i = 0; i <= 25; i++) { + key = key + String.fromCharCode(i + 65); + } + + for (i = 0; i <= 25; i++) { + key = key + String.fromCharCode(i + 97); + } + + for (var i = 0; i < 10; i++) { + key = key + i; + } + + return key + "+/="; + }, + + convertToFormattedHex: function (byte_arr) { + var hex_str = "", + i, + len, + tmp_hex; + + if (!wzrk_util.isArray(byte_arr)) { + return false; + } + + len = byte_arr.length; + + for (i = 0; i < len; ++i) { + if (byte_arr[i] < 0) { + byte_arr[i] = byte_arr[i] + 256; + } + if (byte_arr[i] === undefined) { + byte_arr[i] = 0; + } + tmp_hex = byte_arr[i].toString(16); + + // Add leading zero. + if (tmp_hex.length == 1) tmp_hex = "0" + tmp_hex; + + // beautification - needed if you're printing this in the console, else keep commented + // if ((i + 1) % 16 === 0) { + // tmp_hex += "\n"; + // } else { + // tmp_hex += " "; + // } + + hex_str += tmp_hex; + } + + return hex_str.trim(); + }, + + convertStringToHex: function (s) { + + var byte_arr = []; + for (var i = 0; i < s.length; i++) { + var value = s.charCodeAt(i); + byte_arr.push(value & 255); + byte_arr.push((value >> 8) & 255); + } + return LZS.convertToFormattedHex(byte_arr); + + }, + + compressToBase64: function (input) { + if (input == null) return ""; + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = LZS.compress(input); + + while (i < input.length * 2) { + + if (i % 2 == 0) { + chr1 = input.charCodeAt(i / 2) >> 8; + chr2 = input.charCodeAt(i / 2) & 255; + if (i / 2 + 1 < input.length) + chr3 = input.charCodeAt(i / 2 + 1) >> 8; + else + chr3 = NaN; + } else { + chr1 = input.charCodeAt((i - 1) / 2) & 255; + if ((i + 1) / 2 < input.length) { + chr2 = input.charCodeAt((i + 1) / 2) >> 8; + chr3 = input.charCodeAt((i + 1) / 2) & 255; + } else + chr2 = chr3 = NaN; + } + i += 3; + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + LZS._keyStr.charAt(enc1) + LZS._keyStr.charAt(enc2) + + LZS._keyStr.charAt(enc3) + LZS._keyStr.charAt(enc4); + + } + + return output; + }, + + + compress: function (uncompressed) { + if (uncompressed == null) return ""; + var i, value, + context_dictionary = {}, + context_dictionaryToCreate = {}, + context_c = "", + context_wc = "", + context_w = "", + context_enlargeIn = 2, // Compensate for the first entry which should not count + context_dictSize = 3, + context_numBits = 2, + context_data_string = "", + context_data_val = 0, + context_data_position = 0, + ii, + f = LZS._f; + + for (ii = 0; ii < uncompressed.length; ii += 1) { + context_c = uncompressed.charAt(ii); + if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) { + context_dictionary[context_c] = context_dictSize++; + context_dictionaryToCreate[context_c] = true; + } + + context_wc = context_w + context_c; + if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) { + context_w = context_wc; + } else { + if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) { + if (context_w.charCodeAt(0) < 256) { + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + } + value = context_w.charCodeAt(0); + for (i = 0; i < 8; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + } else { + value = 1; + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1) | value; + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = 0; + } + value = context_w.charCodeAt(0); + for (i = 0; i < 16; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + // Add wc to the dictionary. + context_dictionary[context_wc] = context_dictSize++; + context_w = String(context_c); + } + } + + // Output the code for w. + if (context_w !== "") { + if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) { + if (context_w.charCodeAt(0) < 256) { + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + } + value = context_w.charCodeAt(0); + for (i = 0; i < 8; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + } else { + value = 1; + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1) | value; + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = 0; + } + value = context_w.charCodeAt(0); + for (i = 0; i < 16; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + delete context_dictionaryToCreate[context_w]; + } else { + value = context_dictionary[context_w]; + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + + + } + context_enlargeIn--; + if (context_enlargeIn == 0) { + context_enlargeIn = Math.pow(2, context_numBits); + context_numBits++; + } + } + + // Mark the end of the stream + value = 2; + for (i = 0; i < context_numBits; i++) { + context_data_val = (context_data_val << 1) | (value & 1); + if (context_data_position == 15) { + context_data_position = 0; + context_data_string += f(context_data_val); + context_data_val = 0; + } else { + context_data_position++; + } + value = value >> 1; + } + + // Flush the last char + while (true) { + context_data_val = (context_data_val << 1); + if (context_data_position == 15) { + context_data_string += f(context_data_val); + break; + } else context_data_position++; + } + return context_data_string; + } + + }; + + LZS._keyStr = LZS.getKeyStr(); + + var wzrk_util = { + //expecting yyyymmdd format either as a number or a string + setDate: function (dt) { + if (wzrk_util.isDateValid(dt)) { + return "$D_" + dt; + } + wc.e(wzrk_msg['date-format-error']); + }, + + isDateObject: function (input) { + return typeof (input) === "object" && (input instanceof Date); + }, + + convertToWZRKDate: function (dateObj) { + return ("$D_" + Math.round(dateObj.getTime() / 1000)); + }, + + isDateValid: function (date) { + var matches = /^(\d{4})(\d{2})(\d{2})$/.exec(date); + if (matches == null) return false; + var d = matches[3]; + var m = matches[2] - 1; + var y = matches[1]; + var composedDate = new Date(y, m, d); + return composedDate.getDate() == d && + composedDate.getMonth() == m && + composedDate.getFullYear() == y; + }, + + isArray: function (input) { + return typeof (input) === "object" && (input instanceof Array); + }, + + isObject: function (input) { + return Object.prototype.toString.call(input) == "[object Object]"; + }, + + isObjectEmpty: function (obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) + return false; + } + return true; + }, + + isString: function (input) { + return (typeof input == 'string' || input instanceof String); + }, + + + // if yes, the convert using +number. + isConvertibleToNumber: function (n) { + return !isNaN(parseFloat(n)) && isFinite(n); + }, + + //from here - http://stackoverflow.com/a/1421988/2456615 + isNumber: function (n) { + return /^-?[\d.]+(?:e-?\d+)?$/.test(n) && typeof n == 'number'; + }, + + arrayContains: function (arr, obj) { + function contains(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) { + return true; + } + } + return false; + } + }, + + getURLParams: function (url) { + var urlParams = {}; + var idx = url.indexOf('?'); + + if (idx > 1) { + + var uri = url.substring(idx + 1); + + + var match, + pl = /\+/g, // Regex for replacing addition symbol with a space + search = /([^&=]+)=?([^&]*)/g, + decode = function (s) { + var replacement = s.replace(pl, " "); + try { + replacement = decodeURIComponent(replacement); + } catch (e) { + //eat + } + return replacement; + }; + + + while (match = search.exec(uri)) { + urlParams[decode(match[1])] = decode(match[2]); + } + + } + return urlParams; + }, + + getDomain: function (url) { + if (url == "") return ""; + var a = document.createElement('a'); + a.href = url; + return a.hostname; + }, + + + //keys can't be greater than 1024 chars, values can't be greater than 1024 chars + removeUnsupportedChars: function (o) { + if (typeof o == "object") { + for (var key in o) { + if (o.hasOwnProperty(key)) { + var sanitizedVal = wzrk_util.removeUnsupportedChars(o[key]); + var sanitizedKey = wzrk_util.isString(key) ? wzrk_util.sanitize(key, unsupportedKeyCharRegex) : key; + + if (wzrk_util.isString(key)) { + sanitizedKey = wzrk_util.sanitize(key, unsupportedKeyCharRegex); + if (sanitizedKey.length > 1024) { + sanitizedKey = sanitizedKey.substring(0, 1024); + $WZRK_WR.reportError(520, sanitizedKey + "... length exceeded 1024 chars. Trimmed."); + } + } else { + sanitizedKey = key; + } + delete o[key]; + o[sanitizedKey] = sanitizedVal; + } + } + } else { + var val; + + if (wzrk_util.isString(o)) { + val = wzrk_util.sanitize(o, unsupportedValueCharRegex); + if (val.length > 1024) { + val = val.substring(0, 1024); + $WZRK_WR.reportError(521, val + "... length exceeded 1024 chars. Trimmed."); + } + } else { + val = o; + } + return val; + } + return o; + }, + + sanitize: function (input, regex) { + return input.replace(regex, ''); + }, + + isLocalStorageSupported: function () { + try { + window.localStorage.setItem('wzrk_debug', '12345678'); + window.localStorage.removeItem('wzrk_debug'); + return 'localStorage' in window && window['localStorage'] !== null; + } catch (e) { + return false; + } + }, + + getCampaignObject: function () { + var campObj = {}; + if (wzrk_util.isLocalStorageSupported()) { + campObj = localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; + if (typeof campObj != STRING_CONSTANTS.UNDEFINED) { + campObj = JSON.parse(decodeURIComponent(campObj).replace(singleQuoteRegex, "\"")); + } else { + campObj = {}; + } + } + return campObj; + }, + + saveCampaignObject: function (campaignObj) { + if (wzrk_util.isLocalStorageSupported()) { + var campObj = JSON.stringify(campaignObj); + localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME] = encodeURIComponent(campObj); + } + }, + + + isPersonalizationActive: function () { + return (wzrk_util.isLocalStorageSupported() && wizrocket['enablePersonalization']) + }, + + getToday: function () { + var t = new Date(); + return t.getFullYear() + "" + t.getMonth() + "" + t.getDay(); + }, + getNow: function () { + return Math.floor(((new Date()).getTime()) / 1000); + } + + }; + +// leading spaces, dot, colon, dollar, single quote, double quote, backslash, trailing spaces + var unsupportedKeyCharRegex = new RegExp("^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$", "g"); + +// leading spaces, single quote, double quote, backslash, trailing spaces + var unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", "g"); + +//used to handle cookies in Opera mini + var doubleQuoteRegex = new RegExp("\"", "g"); + var singleQuoteRegex = new RegExp("\'", "g"); + + + var wzrk_msg = {}; + var wzrk_error_txt = "CleverTap error: "; + var data_not_sent_txt = "This property has been ignored."; + wzrk_msg['embed-error'] = wzrk_error_txt + "Incorrect embed script."; + wzrk_msg['event-error'] = wzrk_error_txt + "Event structure not valid. " + data_not_sent_txt; + wzrk_msg['gender-error'] = wzrk_error_txt + "Gender value should be either M or F. " + data_not_sent_txt; + wzrk_msg['employed-error'] = wzrk_error_txt + "Employed value should be either Y or N. " + data_not_sent_txt; + wzrk_msg['married-error'] = wzrk_error_txt + "Married value should be either Y or N. " + data_not_sent_txt; + wzrk_msg['education-error'] = wzrk_error_txt + "Education value should be either School, College or Graduate. " + data_not_sent_txt; + wzrk_msg['age-error'] = wzrk_error_txt + "Age value should be a number. " + data_not_sent_txt; + wzrk_msg['dob-error'] = wzrk_error_txt + "DOB value should be a Date Object"; + wzrk_msg['obj-arr-error'] = wzrk_error_txt + "Expecting Object array in profile"; + wzrk_msg['date-format-error'] = wzrk_error_txt + "setDate(number). number should be formatted as yyyymmdd"; + wzrk_msg['enum-format-error'] = wzrk_error_txt + "setEnum(value). value should be a string or a number"; + wzrk_msg['phone-format-error'] = wzrk_error_txt + "Phone number should be formatted as +[country code][number]"; + +} // function __wizrocket + +$WZRK_WR = new __wizrocket(); +$CLTP_WR = $WZRK_WR; +$WZRK_WR.init(); //this should always be the last in the JS file, as it needs all vars/functions to be defined to work. + + +/** + * @preserve Copyright WizRocket, Inc. (ver.@timestamp@) + * ____ _ _____ + * / ___| | _____ _____ _ _|_ _|_ _ _ __ + * | | | |/ _ \ \ / / _ \ '__|| |/ _` | '_ \ + * | |___| | __/\ V / __/ | | | (_| | |_) | + * \____|_|\___| \_/ \___|_| |_|\__,_| .__/ + * |_| + * + */ \ No newline at end of file diff --git a/clevertap_sw.js b/clevertap_sw.js new file mode 100644 index 00000000..cf9164d6 --- /dev/null +++ b/clevertap_sw.js @@ -0,0 +1 @@ +importScripts('https://s3-eu-west-1.amazonaws.com/static.wizrocket.com/js/sw_webpush.js'); diff --git a/ct_logo.svg b/ct_logo.svg new file mode 100644 index 00000000..7fb0387d --- /dev/null +++ b/ct_logo.svg @@ -0,0 +1 @@ +Grey \ No newline at end of file diff --git a/dialog.js b/dialog.js new file mode 100644 index 00000000..ca2aa5cb --- /dev/null +++ b/dialog.js @@ -0,0 +1,189 @@ +/** wizAlert(); + parameter: 1 object to specify title etc. + title, body, confirmButtonText, rejectButtonText, confirmButtonColor + function to yield to on click + +
+
+
+
Would you like to Set Up Push Notifications
+
We promise to only send you relevant content and give you great updates
+
+
Powered by
+
+
+ + */ + +function getwzrkPermissionPopup(){ + var wzrkPermissionPopup = { + 'dialogCss': '' + + }; + +// dialog css is taken from the minified main.css + wzrkPermissionPopup.wzrkCreatePopDiv = function(hidePoweredByCT) { + + function createButton (id, text, cls) { + var btn = document.createElement("BUTTON"); + btn.id = id; + btn.setAttribute('class', cls); + var t = document.createTextNode(text); + btn.appendChild(t); + return btn; + } + + function createDiv(id, parent, cls, content) { + + var div = document.createElement('div'); + if(id !== undefined) { + div.id = id; + } + if(cls !== undefined){ + div.setAttribute('class', cls); + } + if(content !== undefined){ + div.innerHTML = content; + } + if(parent !== undefined){ + parent.appendChild(div); + } + return div; + + } + + // wrapper + var msgDiv = createDiv('wzrk_wrapper', undefined, undefined, wzrkPermissionPopup['dialogCss']); + + // overlay div + createDiv(undefined, msgDiv, 'wzrk-overlay wzrk-hidden',undefined); + + // alert wrapper + var msgAlert = createDiv(undefined, msgDiv, 'wzrk-alert wzrk-hidden',undefined); + + // alert title + createDiv(undefined, msgAlert, 'wzrk-alert-heading', 'Would you like to Set Up Push Notifications'); + + // alert body + createDiv(undefined, msgAlert, 'wzrk-alert-body', 'We promise to only send you relevant content and give you great updates'); + + // alert button + var buttonWrapper = createDiv(undefined, msgAlert, 'wzrk-button-container',undefined); + buttonWrapper.appendChild(createButton('wzrk-cancel', 'cancel', 'No thanks')); + buttonWrapper.appendChild(createButton('wzrk-confirm', 'confirm', 'Sign me Up!')); + + if(!hidePoweredByCT){ + // alert powered by + createDiv(undefined, msgAlert, 'wzrk-powered', 'Powered by '); + } + + return msgDiv; + + }; + + +// function to darken color for ok button text + wzrkPermissionPopup.colorLuminance = function(hex, lum) { + // validate hex string + hex = String(hex).replace(/[^0-9a-f]/gi, ''); + if (hex.length < 6) { + hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; + } + lum = lum || 0; + + // convert to decimal and change luminosity + var rgb = "#", c, i; + for (i = 0; i < 3; i++) { + c = parseInt(hex.substr(i*2,2), 16); + c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); + rgb += ("00"+c).substr(c.length); + } + + return rgb; + }; + + wzrkPermissionPopup.showElements = function() { + // set up animations on the parent div + var alertBox = document.getElementsByClassName('wzrk-alert')[0]; + var hiddenElems = document.getElementsByClassName('wzrk-hidden'); + alertBox.classList.add('wiz-show-animate'); + while (hiddenElems.length != 0) { + hiddenElems[0].classList.remove('wzrk-hidden'); + } + }; + + wzrkPermissionPopup.hideElements = function() { + var alertBox = document.getElementsByClassName('wzrk-alert')[0]; + var overlay = document.getElementsByClassName('wzrk-overlay')[0] + + alertBox.classList.remove('wiz-show-animate'); + alertBox.classList.add('wiz-hide-animate'); + overlay.classList.add('wzrk-hidden'); + + setTimeout(function() { + alertBox.classList.add('wzrk-hidden'); + // remove html + var wrapper = document.getElementById('wzrk_wrapper'); + wrapper.parentNode.removeChild(wrapper); + }, 100); + + }; + +// main function to call + wzrkPermissionPopup.wizAlert = function(displayOptions, callbackFunction) { + // inject our (hidden) html into the document + document.getElementsByTagName('body')[0].appendChild(wzrkPermissionPopup.wzrkCreatePopDiv(displayOptions['hidePoweredByCT'])); + // set up the heading text + var heading = document.getElementsByClassName('wzrk-alert-heading')[0]; + heading.innerHTML = displayOptions['title']; + + // set up the body text + var body = document.getElementsByClassName('wzrk-alert-body')[0]; + body.innerHTML = displayOptions['body']; + + // set up the text for the buttons + var confirmButton = document.getElementById('wzrk-confirm'); + confirmButton.innerHTML = displayOptions['confirmButtonText']; + + var rejectButton = document.getElementById('wzrk-cancel'); + rejectButton.innerHTML = displayOptions['rejectButtonText']; + + // add event listeners for the callbackfunction on the button + confirmButton.addEventListener('click', function() { + wzrkPermissionPopup.hideElements(); + // give the animation some time to complete + setTimeout(function() { + callbackFunction(true); + }, 100); + }); + + rejectButton.addEventListener('click', function() { + wzrkPermissionPopup.hideElements(); + // give time for the animation to complete + setTimeout(function() { + callbackFunction(false); + }, 100); + }); + + // set up the custom confirm button color + confirmButton.style.backgroundColor = displayOptions['confirmButtonColor']; + + confirmButton.onmouseover = function() { + confirmButton.style.backgroundColor = + wzrkPermissionPopup.colorLuminance(displayOptions['confirmButtonColor'], -0.04); + }; + + confirmButton.onmouseout = function() { + confirmButton.style.backgroundColor = displayOptions['confirmButtonColor'] || '#f28046'; + }; + + // finally display the popup + wzrkPermissionPopup.showElements(); + + }; + + return wzrkPermissionPopup; +} + +window['wzrkPermissionPopup'] = getwzrkPermissionPopup(); +window['wzrkPermissionPopup']['wizAlert'] = window['wzrkPermissionPopup'].wizAlert; \ No newline at end of file diff --git a/gtm_segment.html b/gtm_segment.html new file mode 100644 index 00000000..075ca9af --- /dev/null +++ b/gtm_segment.html @@ -0,0 +1,47 @@ + \ No newline at end of file diff --git a/localforage.min.js b/localforage.min.js new file mode 100644 index 00000000..ca08579f --- /dev/null +++ b/localforage.min.js @@ -0,0 +1,5 @@ +/** + * Created by ankit on 06/10/16. + */ + +!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.localforage=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g=43)}}).catch(function(){return!1})}function n(a){return"boolean"==typeof ga?ia.resolve(ga):m(a).then(function(a){return ga=a})}function o(a){var b=ha[a.name],c={};c.promise=new ia(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function p(a){var b=ha[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function q(a,b){return new ia(function(c,d){if(a.db){if(!b)return c(a.db);o(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=fa.open.apply(fa,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ja)}catch(c){if("ConstraintError"!==c.name)throw c;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result),p(a)}})}function r(a){return q(a,!1)}function s(a){return q(a,!0)}function t(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.versiona.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function u(a){return new ia(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function v(a){var b=l(atob(a.data));return i([b],{type:a.type})}function w(a){return a&&a.__local_forage_encoded_blob}function x(a){var b=this,c=b._initReady().then(function(){var a=ha[b._dbInfo.name];if(a&&a.dbReady)return a.dbReady});return k(c,a,a),c}function y(a){function b(){return ia.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ha||(ha={});var f=ha[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},ha[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=x);for(var g=[],h=0;h>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function I(a){var b,c=new Uint8Array(a),d="";for(b=0;b>2],d+=ma[(3&c[b])<<4|c[b+1]>>4],d+=ma[(15&c[b+1])<<2|c[b+2]>>6],d+=ma[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function J(a,b){var c="";if(a&&(c=Da.call(a)),a&&("[object ArrayBuffer]"===c||a.buffer&&"[object ArrayBuffer]"===Da.call(a.buffer))){var d,e=pa;a instanceof ArrayBuffer?(d=a,e+=ra):(d=a.buffer,"[object Int8Array]"===c?e+=ta:"[object Uint8Array]"===c?e+=ua:"[object Uint8ClampedArray]"===c?e+=va:"[object Int16Array]"===c?e+=wa:"[object Uint16Array]"===c?e+=ya:"[object Int32Array]"===c?e+=xa:"[object Uint32Array]"===c?e+=za:"[object Float32Array]"===c?e+=Aa:"[object Float64Array]"===c?e+=Ba:b(new Error("Failed to get type for BinaryArray"))),b(e+I(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=na+a.type+"~"+I(this.result);b(pa+sa+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(c){console.error("Couldn't convert value into a JSON string: ",a),b(null,c)}}function K(a){if(a.substring(0,qa)!==pa)return JSON.parse(a);var b,c=a.substring(Ca),d=a.substring(qa,Ca);if(d===sa&&oa.test(c)){var e=c.match(oa);b=e[1],c=c.substring(e[0].length)}var f=H(c);switch(d){case ra:return f;case sa:return i([f],{type:b});case ta:return new Int8Array(f);case ua:return new Uint8Array(f);case va:return new Uint8ClampedArray(f);case wa:return new Int16Array(f);case ya:return new Uint16Array(f);case xa:return new Int32Array(f);case za:return new Uint32Array(f);case Aa:return new Float32Array(f);case Ba:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function L(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ia(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(a){return d(a)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Ea,e}function M(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function N(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;h=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function W(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function X(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;h 60) { + i.event(E_DEL, 'scroll', i.scroll); + var url = targetURL; + i.fireRequest(i.addToURL(url, EVT, EVT_SCROLL)); + } + }; + + + + i.click = function () { + + if(clickCount < 3) { // send only up to 3 click events + clickCount++; + + setTimeout(function(){ + var url = targetURL; + i.fireRequest(i.addToURL(url, EVT, EVT_CLICK)); + }, 100); // wait 100ms before firing. Don't want to capture clicks leading to new pages. + + + } else { + i.event(E_DEL, 'mouseup', i.click); + } + + }; + + i.keypress = function () { + + if(keyPressCount < 3) { // send one only after 4 key presses + keyPressCount++; + } else { + i.event(E_DEL, 'keyup', i.keypress); + var url = targetURL; + i.fireRequest(i.addToURL(url, EVT, EVT_KEYPRESS)); + } + }; + + + i.is_onloadcalled = function() { + return (onloadcalled === 1); + }; + + i.pageloaded = function () { + onloadcalled=1; + + i.g(); // load cookies on pageload + var currLocation = encodeURIComponent(location.href); + var firePageLoadRequest = true; + + if(currLocation == pcookie) { // don't fire if cookie has curr url as value + firePageLoadRequest = false; + } + + var FIFTEEN_MINS_IN_SECS = 60 * 15 //seconds in minute * number of mins + i.createCookie(PCOOKIE_NAME, currLocation, FIFTEEN_MINS_IN_SECS); // self-destruct after 15 mins + + + if(firePageLoadRequest) { + + var deviceWidth = screen.width; + var deviceHeight = screen.height; + var pageLoadUrl = targetURL; + + pageLoadUrl = i.addToURL(pageLoadUrl, "dw", deviceWidth); + pageLoadUrl = i.addToURL(pageLoadUrl, "dh", deviceHeight); + pageLoadUrl = i.addToURL(pageLoadUrl, EVT, EVT_PAGE); + + if (doc.referrer) { + var encodedReferrer = encodeURIComponent(doc.referrer); + pageLoadUrl = i.addToURL(pageLoadUrl, "ref", encodedReferrer); + } + + + var catArray = (typeof _wrc != 'undefined')? _wrc: []; // _wrc is a cat/sub-cat array that is in the parent page + + if(catArray && catArray.length >= 1) { + + var catKVStr = i.encodeKVPairs(catArray); + var encodedCatKVStr = encodeURIComponent(catKVStr); // make it fit to pass in the URL + pageLoadUrl = i.addToURL(pageLoadUrl, "kv", encodedCatKVStr); + } + + i.fireRequest(pageLoadUrl); + + } // if(firePageLoadRequest) + + if(firePageLoadRequest) { + var body = document.body; + var docElement = document.documentElement; + //get document height per - http://stackoverflow.com/questions/1145850/get-height-of-entire-document-with-javascript + var docHeight = Math.max(body.scrollHeight, body.offsetHeight, docElement.clientHeight, docElement.scrollHeight, docElement.offsetHeight); + var deviceHeight = screen.height; + + // if screen height is 60% of document height then fire scroll event + // basically if 60% of doc is already visible then user won't need to scroll, hence we'll fire scroll event + + var heightPercent = (deviceHeight/docHeight)*100; + + if(heightPercent >=60) { + setTimeout(function(){ + var url = targetURL; + i.fireRequest(i.addToURL(url, EVT, EVT_SCROLL)); + }, 2000); // wait 2 seconds before firing. This is to eliminate noise. + + } else { + i.event(E_ADD, 'scroll', i.scroll); // if long doc, then add scroll listener + } + } + + i.event(E_ADD, 'keyup', i.keypress); + i.event(E_ADD, 'mouseup', i.click); + }; + + i.sendSiteEvent = function(siteEventName) { + if(typeof siteEventName != 'undefined') { + var siteEventURL = i.addToURL(targetURL, EVT, EVT_SITE); + siteEventName = siteEventName.replace(/\W/g, '-'); // replace all non-alphanumeric chars with dashes + siteEventURL = i.addToURL(siteEventURL, "st", siteEventName); + i.fireRequest(siteEventURL); + } + + + + } + + i.sendKV = function(kvArr) { // accept array from embedded script on site + i.customKV(kvArr); + } + + // process custom KV stuff + i.customKV = function(customArray) { + + if(typeof customArray != 'undefined') { + + if(customArray.length >= 1) { + + var customURL = i.addToURL(targetURL, EVT, EVT_CUSTOM); + var customKVStr = i.encodeKVPairs(customArray); + var encodedCustomKVStr = encodeURIComponent(customKVStr); // make it fit to pass in the URL + customURL = i.addToURL(customURL, "kv", encodedCustomKVStr); + + i.fireRequest(customURL); + } + } + }; + + // encode the KV array. handles 'undefined' array scenario + // returns the encoded string. + i.encodeKVPairs = function (kvArray) { + var kvString = ""; + + if(typeof kvArray != 'undefined') { + + var EQUAL = "#=#"; + var DELIM = "#&#"; + var COMMA = "#,#"; + + for (var idx = 0; idx < kvArray.length; idx++) { + var eachRow = kvArray[idx]; + var rowValueStr = ""; + + if (eachRow && eachRow.length >= 1) { + var rowKey = eachRow[0]; + rowKey = rowKey.trim(); + rowKey = rowKey.replace(/\W/g, '-'); // replace all non-alphanumeric chars with dashes + rowKey = rowKey.toLowerCase(); + + if(eachRow.length == 1) { // only one item in array + + kvString = kvString + rowKey + DELIM; + } else { + eachRow.shift(); // remove the 1st element which is the key + + for (var j = 0; j < eachRow.length; j++) { + var columnVal = eachRow[j]; + + if (columnVal) { + columnVal = columnVal.trim(); + + if(!(rowKey == "name" || rowKey == "uid" || rowKey == "email")) { // do not touch name, email or uid + columnVal = columnVal.replace(/\W/g, '-'); // replace all non-alphanumeric chars with dashes + columnVal = columnVal.toLowerCase(); + } + + rowValueStr = rowValueStr + columnVal; + + if (j < eachRow.length - 1) { + rowValueStr = rowValueStr + COMMA; + } + } + + } // for + + if (rowValueStr.trim() != "") { // don't add empty values + kvString = kvString + rowKey + EQUAL + rowValueStr; + + if (idx < kvArray.length - 1) { + kvString = kvString + DELIM; // no delimiter for the last one + } + } + + } + } + } // for idx < array.length + + } + + return kvString; + + }; + + + i.g = function () { + gcookie = i.readCookie(GCOOKIE_NAME); + scookie = i.readCookie(SCOOKIE_NAME); + pcookie = i.readCookie(PCOOKIE_NAME); + }; + + i.s = function (n, v) { + var domain = window.location.hostname; + var cookieExpiry = ""; + + if (n == GCOOKIE_NAME) { + var TEN_YEARS_IN_SECS = 86400 * 365 * 10; //seconds in an days * days in an year * number of years + cookieExpiry = TEN_YEARS_IN_SECS; + gcookie = v; + + } else if (n == SCOOKIE_NAME) { + var TWENTY_MINS_IN_SECS = 60 * 20; //seconds in minute * number of mins + cookieExpiry = TWENTY_MINS_IN_SECS; + scookie = v; + } + + i.createBroadCookie(n, v, cookieExpiry, domain); + + }; + + + // sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com" + i.createBroadCookie = function (name, value, seconds, domain) { + + + //To update an existing "broad domain" cookie, we need to know what domain it was actually set on. + //since a retrieved cookie never tells which domain it was set on, we need to set another test cookie + //to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain + //for updating the actual cookie. + + + if(domain) { + var domainParts = domain.split("."); + var broadDomain = ""; + for(var idx = domainParts.length-1; idx >= 0 ; idx--) { + broadDomain = "." + domainParts[idx] + broadDomain; + + + // only needed if the cookie already exists and needs to be updated. See note above. + if(i.readCookie(name)) { + + // no guarantee that browser will delete cookie, hence create short lived cookies with random name + var testCookieName = "test_" + name + Math.floor((Math.random()*100)+1); + i.deleteCookie(testCookieName, broadDomain); // safety purpose + i.createCookie(testCookieName, value, 10, broadDomain); // self-destruct after 10 seconds + if(!i.readCookie(testCookieName)) { // if test cookie not set, then the actual cookie wouldn't have been set on this domain either. + continue; + } else { // else if cookie set, then delete the test and the original cookie + i.deleteCookie(testCookieName, broadDomain); + i.deleteCookie(name, broadDomain); + } + } + + i.deleteCookie(name, broadDomain); //safety purpose + i.createCookie(name, value, seconds, broadDomain); + var tempCookie = i.readCookie(name); + if(tempCookie == value) { + //console.log("Was able to retrieve cookie on: " + broadDomain + "->" + name + "=" + tempCookie); + break; + } + } + } else { + i.createCookie(name, value, seconds, domain); + } + }; + + //read - cookie get-set: http://www.quirksmode.org/js/cookies.html + + i.createCookie = function (name, value, seconds, domain) { + var expires = ""; + var domainStr = ""; + if (seconds) { + var date = new Date(); + date.setTime(date.getTime()+(seconds * 1000)); + + expires = "; expires=" + date.toGMTString(); + } + + if(domain) { + domainStr = "; domain=" + domain; + } + + var cookieStr = name + "=" + value + expires + domainStr + "; path=/"; + document.cookie = cookieStr; + }; + + i.readCookie = function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for(var idx = 0; idx < ca.length; idx++) { + var c = ca[idx]; + while (c.charAt(0)==' ') { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) == 0) { + return c.substring(nameEQ.length, c.length); + } + } + return null; + }; + + i.deleteCookie = function (name, domain) { + var cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + + if(domain) { + cookieStr = cookieStr + " domain=" + domain + ";"; + } + + document.cookie = cookieStr; + }; + + + i.addToURL = function(url, k, v) { + return url + "&" + k + "=" + v; + }; + + + i.fireRequest = function (url) { + if (gcookie != null) { + url = i.addToURL(url, "g", gcookie); + } + if (scookie != null) { + url = i.addToURL(url, "s", scookie); + } + + url = i.addToURL(url, "rnd", new Date().getTime()); // add epoch to beat caching of the URL + + var s = doc.createElement('script'); + s.setAttribute("type", "text/javascript"); + s.setAttribute("src", url); + s.async = true; + doc.getElementsByTagName("head")[0].appendChild(s); + }; + + + // list of functions that the closure compiler shouldn't rename + // https://developers.google.com/closure/compiler/docs/api-tutorial3 + i['s'] = i.s; + i['is_onloadcalled'] = i.is_onloadcalled; + i['sendKV'] = i.sendKV; + i['sendSiteEvent'] = i.sendSiteEvent; + +} // function __wizrocket + +$WZRK_WR = new __wizrocket(); + +// inspired via - https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js && http://javascript.nwbox.com/ContentLoaded/ +// Author: Diego Perini (diego.perini@gmail.com) + +(function (fn) { + + var done = false, top = true, + win = window; + doc = win.document, root = doc.documentElement, + + add = doc.addEventListener ? 'addEventListener' : 'attachEvent', + rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', + pre = doc.addEventListener ? '' : 'on', + + init = function(e) { + if (e.type == 'readystatechange' && doc.readyState != 'complete') return; + (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); + if (!done && (done = true)) fn.call(win, e.type || e); + }, + + poll = function() { + try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } + init('poll'); + }; + + if (doc.readyState == 'complete') fn.call(win, 'lazy'); + else { + if (doc.createEventObject && root.doScroll) { + try { top = !win.frameElement; } catch(e) { } + if (top) poll(); + } + doc[add](pre + 'DOMContentLoaded', init, false); + doc[add](pre + 'readystatechange', init, false); + win[add](pre + 'load', init, false); + } + + +})($WZRK_WR.pageloaded); + +/** + * @preserve Copyright WizRocket Technologies Pvt. Ltd. (ver.@timestamp@) + * _ _ _ + * __ _(_)_____ __ ___ ___| | _____| |_ + * \ \ /\ / / |_ / '__/ _ \ / __| |/ / _ \ __| + * \ V V /| |/ /| | | (_) | (__| < __/ |_ + * \_/\_/ |_/___|_| \___/ \___|_|\_\___|\__| + */ + +/* Tested with the following browsers + Android - + maxthon works + firefox works + opera mini - kv, pg work. scroll, click, kp dont. + ucbrowser - kv, pg work. scroll, click, kp dont. + ucbrowser-mini - works + dolphin - works + chrome - works + stock browser - works + + Windows - + IE10 works + FF works + Chrome works + + MacOS - + FF works + Chrome works + Safari works + Opera works + + iOS- + Chrome works + FF works + */ diff --git a/q.js b/q.js new file mode 100644 index 00000000..e4d195f6 --- /dev/null +++ b/q.js @@ -0,0 +1,315 @@ +//todo - the fetchExperiments call might happen multiple times +//todo - check how many times fetchExperiments is called for brand new user who's not been marked for exp yet. +function __wizrocketx() { + var targetURL = location.protocol + '//foo.com:8080/e?t=1'; + + var i = this; + var doc = document; + var win = window; + var syncTimerId, asyncTimerId; + var syncFallbackTimerId, asyncFallbackTimerId; + + var deliveredSyncResults=0; + var deliveredAsyncResults=0; + + var today = new Date(); + var todayYmd = (today.getYear() + 1900) + "" + (today.getMonth() + 1) + "" + (today.getDate()); + + + var XCOOKIE_NAME = "WZRK_X"; + var bGotResults; + var emptyArr = []; + + + var gcookie, xcookie; + + var GCOOKIE_NAME = "WZRK_G"; + + i.init = function() { + console.log("wzrk_x init called"); + + //todo : if cookie missing then don't even send teh request + gcookie = i.readCookie(GCOOKIE_NAME); + }; + + + i.enableTargeting = function() { + // sync + syncTimerId = setTimeout(function(){ + syncTimerId=undefined; + // call didn't come through, let's try the fallback option + console.log("sync timer timeout"); + + xcookie = i.readCookie(XCOOKIE_NAME); + + if(xcookie != null && xcookie.length === 6) { // if xcookie exists + + syncFallbackTimerId = setTimeout(function() { + //unable to fetch results from the fallback url during the stipulated time + syncFallbackTimerId=undefined; + i.deliverSyncResults(emptyArr); + + }, 500); + + i.fetchExperimentData(i.addToURL(targetURL, "dt", xcookie)); // get the data on the date of the cookie - fallback option + + } else { // no xcookie + i.deliverSyncResults(emptyArr); + } + i.fetchExperimentData(i.addToURL(targetURL, "dt", todayYmd)); // fallback URL call so that data gets cached and cookie gets set for next time + }, 1000); + + + // async + asyncTimerId = setTimeout(function(){ + asyncTimerId=undefined; + // call didn't come through, let's try the fallback option + console.log("async timer timeout"); + + xcookie = i.readCookie(XCOOKIE_NAME); + + if(xcookie != null && xcookie.length === 6) { // if xcookie exists + + asyncFallbackTimerId = setTimeout(function() { + //unable to fetch results from the fallback url during the stipulated time + asyncFallbackTimerId=undefined; + i.deliverAsyncResults(emptyArr); + + }, 500); + + i.fetchExperimentData(i.addToURL(targetURL, "dt", xcookie)); // get the data on the date of the cookie - fallback option + + } else { // no xcookie + i.deliverAsyncResults(emptyArr); + } + i.fetchExperimentData(i.addToURL(targetURL, "dt", todayYmd)); // fallback URL call so that data gets cached and cookie gets set for next time + }, 10000); + + + i.fetchExperimentData(targetURL); + + }; + + + //ensure the wzrk_sync_result method are called one time only for every page reload + i.deliverSyncResults = function (syncResults) { + if(deliveredSyncResults == 0 && typeof(wzrk_sync_results) == typeof(Function)) { + deliveredSyncResults=1; + console.log("about to deliver sync results"); + win.wzrk_sync_results(syncResults); + } + }; + + //ensure the wzrk_async_result method are called one time only for every page reload + i.deliverAsyncResults = function (asyncResults) { + if(deliveredAsyncResults == 0 && typeof(wzrk_async_results) == typeof(Function)) { + deliveredAsyncResults=1; + console.log("about to deliver async results"); + win.wzrk_async_results(asyncResults); + } + }; + + + i.fetchExperimentData = function(url) { + console.log("firing request to fetch experiments"); + i.fireRequest(url); + }; + + + // e.g. {1: "1382812200000|1382898599000|0000-2359-127 * *", 4: "1382812200000|1382898599000|0000-2359-127 * *"} + i.results = function(resultObj) { + + console.log("got main results: " + resultObj); + + var validExps = i.getValidExperiments(resultObj); + + if(typeof syncTimerId != 'undefined') { + clearTimeout(syncTimerId); + console.log("got results before timeout, canceled timer: sync"); + i.deliverSyncResults(validExps); + } + + if(typeof asyncTimerId != 'undefined') { + clearTimeout(asyncTimerId); + console.log("got results before timeout, canceled timer: async"); + i.deliverAsyncResults(validExps); + } + + }; // i.results + + // e.g. {0:20131104, 1: "1382812200000|1382898599000|0000-2359-127 * *", 4: "1382812200000|1382898599000|0000-2359-127 * *"} + i.fbResults = function (resultObj) { + + if(typeof resultObj[0] != 'undefined') { + var dateStr = resultObj[0]; // 0th element contains the request as sent in the request + var THIRTY_DAYS_IN_SECS = 60 * 60 * 24 * 30; + i.createCookie(XCOOKIE_NAME, dateStr,THIRTY_DAYS_IN_SECS); //save a cookie with the last known fetch date of fallback results + } + + var validExps = i.getValidExperiments(resultObj); + + console.log("got the fallback results: " + resultObj); + + if(typeof syncFallbackTimerId != 'undefined') { + clearTimeout(syncFallbackTimerId); + console.log("got results before fallback sync timer timeout, canceling it now"); + i.deliverSyncResults(validExps); + } + + if(typeof asyncTimerId != 'undefined') { + clearTimeout(asyncTimerId); + console.log("got results before async timer timeout, canceling it now"); + i.deliverAsyncResults(validExps); + } + + }; // i.results + + + + i.addToURL = function (url, k, v) { + return url + "&" + k + "=" + v; + }; + + i.fireRequest = function (url) { + if (gcookie != null) { + url = i.addToURL(url, "g", gcookie); + } + + //url = i.addToURL(url, "rnd", new Date().getTime()); // add epoch to beat caching of the URL + + var s = doc.createElement('script'); + s.setAttribute("type", "text/javascript"); + s.setAttribute("src", url); + s.async = true; + doc.getElementsByTagName("head")[0].appendChild(s); + }; + + + //read - cookie get-set: http://www.quirksmode.org/js/cookies.html + i.createCookie = function (name, value, seconds, domain) { + var expires = ""; + var domainStr = ""; + if (seconds) { + var date = new Date(); + date.setTime(date.getTime()+(seconds * 1000)); + expires = "; expires=" + date.toGMTString(); + } + + if(domain) { + domainStr = "; domain=" + domain; + } + + var cookieStr = name + "=" + value + expires + domainStr + "; path=/"; + document.cookie = cookieStr; + }; + + i.readCookie = function (name) { + var nameEQ = name + "="; + var ca = document.cookie.split(';'); + for(var idx = 0; idx < ca.length; idx++) { + var c = ca[idx]; + while (c.charAt(0)==' ') { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) == 0) { + return c.substring(nameEQ.length, c.length); + } + } + return null; + }; + + i.getValidExperiments = function (expObject) { + var validExpArray = []; + var date = new Date(); + for(k in expObject) { + if(k > 0) { // don't process 0 key, since it's used to send date + var v = expObject[k]; + if(i.isExpActive(v, date)) { + validExpArray.push(k); + } + } // k > 0 + } + console.log("Valid experiments: " + validExpArray); + return validExpArray; + }; + + + // to test use isValid("1282597083|1584597083|0000-0000-127 * *", new Date(1382553000000)); + i.isExpActive = function (cronExp, cDate) { + var valid = 0; + + var cTime = cDate.getTime(); // epoch + var cHour = cDate.getHours(); // hour (0-23) + var cMin = cDate.getMinutes(); // min (0-59) + var cHourMin = cHour + "" + cMin; // 1430 + var cMoy = cDate.getMonth(); // month of year (0-11) + var cDom = cDate.getDate(); // day of month (1-31) + var cDay = cDate.getDay(); // day of the week (0-6) Sunday=0 + var cDayBit = Math.pow(2,cDay); + + var expParts = cronExp.split("|"); + var expStartEpoch = expParts[0]; + var expEndEpoch = expParts[1]; + + if((cTime >=expStartEpoch) && (cTime < expEndEpoch)) { // within exp time range + + var timeExpArr = expParts[2].split(" "); // e.g. 900-1030-65,1315-1420-65,1610-2030-65 * * + var dom = timeExpArr[1]; + var moy = timeExpArr[2]; + + if(dom == cDom || dom == '*') { // specific day of month, or valid for ALL days + if(moy == cMoy || moy == '*') { // specific month of year or valid for ALL months + var dayTimeExpArr = timeExpArr[0].split(","); // e.g. 900-1030-65,1315-1420-65,1610-2030-65 + + for(var i=0;i= startTimeSlot || startTimeSlot == 0) && (cHourMin <= endTimeSlot) && (dayBit & cDayBit)) { + valid=1; + break; + } // if + } + } // if moy + } // if dom + + } + return valid; + }; + + i.arrayContains = function (arr, key) { + // see this for best way to check for array -> http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ + if(Object.prototype.toString.call(arr) === '[object Array]') { + var i = arr.length; + while (i--) { + if (arr[i] === key) { + return true; + } + } + } + return false; + }; + + // list of functions that the closure compiler shouldn't rename + // https://developers.google.com/closure/compiler/docs/api-tutorial3 + i['fbResults'] = i.fbResults; + i['results'] = i.results; + i['arrayContains'] = i.arrayContains; + i['enableTargeting'] = i.enableTargeting; + + +} // function wizrocketx + +$WZRK_X = new __wizrocketx(); +$WZRK_X.init(); + +/** + * @preserve Copyright WizRocket Technologies Pvt. Ltd. (ver.@timestamp@) + * _ _ _ __ __ + * __ _(_)_____ __ ___ ___| | _____| |_ \ \/ / + * \ \ /\ / / |_ / '__/ _ \ / __| |/ / _ \ __| \ / + * \ V V /| |/ /| | | (_) | (__| < __/ |_ / \ + * \_/\_/ |_/___|_| \___/ \___|_|\_\___|\__| /_/\_\ + */ diff --git a/sw_webpush.js b/sw_webpush.js new file mode 100644 index 00000000..a322d066 --- /dev/null +++ b/sw_webpush.js @@ -0,0 +1,161 @@ +/** + * Author: Jashan Shewakramani + * Last updated: 27 June 2016 + * Description: Service worker for handling chrome push notifications + * + * NOTES: + * -> "self" refers to the global ServiceWorker Object + * -> This script is registered to the browser from a.js + * -> We're only handling notification clicks; "delivered" is handled by NB + * -> Use Google's closure compiler on http://closure-compiler.appspot.com/ for minifying + */ + +importScripts('https://d2r1yp2w7bby2u.cloudfront.net/js/localforage.min.js'); +// var CACHE_VERSION = 3; +// var CURRENT_CACHES = { +// prefetch: 'prefetch-cache-v' + CACHE_VERSION +// }; + +if(typeof globalRedirectPath === "undefined"){ + // set up some variables we need gobally + var globalNotificationData; + //global redirect path for backward compatibility + var globalRedirectPath; // when showing thr url; we need to log to LC before opening up the deep link +} + +self.addEventListener('install', function(event) { + // force this service worker to become the active service worker; removes any previous implementations or migrations + self.skipWaiting(); + // console.log('Service worker installed', self, event); +}); + +self.addEventListener('activate', function(event) { + // console.log('Service worker activated', self, event); + // Delete all caches that aren't named in CURRENT_CACHES. + // var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { + // return CURRENT_CACHES[key]; + // }); + // + // event.waitUntil( + // caches.keys() + // .then(function(cacheNames) { + // return Promise.all( + // cacheNames.map(function(cacheName) { + // if (expectedCacheNames.indexOf(cacheName) === -1) { + // // If this cache name isn't present in the array of "expected" cache names, then delete it. + // console.log('Deleting out of date cache:', cacheName); + // return caches.delete(cacheName); + // } + // }) + // ); + // }) + // .catch(function(){ + // console.log("Error while clearing cache") + // }) + // ); + console.log('CT Service worker activated') +}); + +self.addEventListener('push', function(event) { + + console.log('Push event: ', event); + // get all the notification data + var notificationData = JSON.parse(event.data.text()); + var title = notificationData['title']; + var notificationOptions = notificationData['notificationOptions']; + var data = notificationOptions['data']; + var key; + if(typeof data !== 'undefined'){ + key = data['wzrk_id']; + } + if(typeof key === 'undefined'){ + key = title; + } + localforage.setItem(key, event.data.text()).then(function(value){ + // console.log("persisted"); + }).catch(function(err) { + // This code runs if there were any errors + console.log("Error in persisting"); + }); + + // two global variables for backward compatibility + globalRedirectPath = notificationData['redirectPath']; + globalNotificationData = notificationData; + + var raiseNotificationViewedPath = notificationData['raiseNotificationViewedPath']; + if(typeof raiseNotificationViewedPath !== "undefined"){ + //raise notification viewed event + fetch(raiseNotificationViewedPath, {'mode': 'no-cors'}); //ignore the response + } + event.waitUntil(self.registration.showNotification(title, notificationOptions)); + +}); + +function onClick(event, redirectPath, notificationData){ + var finalDeepLink = redirectPath; + var silentRequest = true; // are opening up a new window or sending a quiet get request from here? + if (event.action === 'action1') { + // button 1 was clicked + if (typeof notificationData['notificationOptions']['actions'][0]['deepLink'] !== 'undefined') { + finalDeepLink += '&r=' + encodeURIComponent(notificationData['notificationOptions']['actions'][0]['deepLink']); + silentRequest = false; + } + finalDeepLink += '&b=' + encodeURIComponent('button1'); + } else if (event.action === 'action2') { + // the second button was clicked + if (typeof notificationData['notificationOptions']['actions'][1]['deepLink'] !== 'undefined') { + finalDeepLink += '&r=' + encodeURIComponent(notificationData['notificationOptions']['actions'][1]['deepLink']); + silentRequest = false; + } + finalDeepLink += '&b=' + encodeURIComponent('button2'); + } else { + // general click + if (typeof notificationData['deepLink'] !== 'undefined') { + finalDeepLink += '&r=' + encodeURIComponent(notificationData['deepLink']); + silentRequest = false; + } + + finalDeepLink += '&b=' + encodeURIComponent('button0'); + } + + if (silentRequest) { + fireSilentRequest(finalDeepLink); + } else { + clients.openWindow(finalDeepLink); + } + event.notification.close(); +} + +self.addEventListener('notificationclick', function(event) { + var notification = event.notification; + var data = notification['data']; + var key; + if(typeof data !== 'undefined' && data !== null){ + key = data['wzrk_id']; + } + if(typeof key === 'undefined'){ + key = notification['title']; + } + var promise = localforage.getItem(key).then(function(value) { + var notificationData = JSON.parse(value); + var redirectPath = notificationData['redirectPath']; + // console.log("event",event); + // console.log("redirect path: " + redirectPath); + // console.log("notification data: " + notificationData); + onClick(event, redirectPath, notificationData); + }).catch(function(err) { + // This code runs if there were any errors + //onClick below for backward compatibility + onClick(event, globalRedirectPath, globalNotificationData); + console.log(err); + }); + event.waitUntil(promise); +}); + +var fireSilentRequest = function(url) { + // add the silent parameter to the deeplink so that LC knows not to raise an error + url += '&s=true'; + + // use the fetch API to make a silent request (we don't care about the response here) + fetch(url, {'mode': 'no-cors'}); +}; diff --git a/wzrk-shopify.js b/wzrk-shopify.js new file mode 100644 index 00000000..20f752af --- /dev/null +++ b/wzrk-shopify.js @@ -0,0 +1,207 @@ +if(typeof clevertap === "undefined"){ + var clevertap = { + event: [], + profile: [], + account: [], + notifications: [], + onUserLogin: [] + }; +} + +function wzrkShopify(id) { + clevertap.account.push({ + "id": id + }); + clevertap.enablePersonalization = true; // enables Personalization + clevertap.plugin = "shop"; + var wzrk = document.createElement('script'); + wzrk.type = 'text/javascript'; + wzrk.async = true; + wzrk.src = ('https:' == document.location.protocol ? 'https://d2r1yp2w7bby2u.cloudfront.net' : 'http://static.clevertap.com') + '/js/a.js'; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(wzrk, s); + + var removeUnwantedinPrice = function(price){ + var nums = price.split("."); + nums[0] = nums[0].replace(/\D+/g, ''); + + if(nums.length > 1){ + nums[1] = nums[1].replace(/\D+/g, ''); + return (nums[0] + "." + nums[1]); + } + + return nums[0]; + }; + + var fixPrice = function(product_price){ + var price_arr = product_price.split(" "); + if(price_arr.length > 1){ + return parseFloat(parseFloat(removeUnwantedinPrice(price_arr[1])).toFixed(2)); + } + return parseFloat(parseFloat(removeUnwantedinPrice(product_price)).toFixed(2)); + }; + + var push_product_viewed = function() { + clevertap.event.push("Product Viewed", { + "Product name": __wzrk_product_title, + "Category": __wzrk_product_category_name, + "Price": fixPrice(__wzrk_product_price), + "Currency": __wzrk_currency + }); + }; + + var category_viewed = function() { + clevertap.event.push("Category Viewed", { + "Category name": __wzrk_collection_name + }); + }; + + var push_search = function() { + clevertap.event.push("Searched", { + "Term": __wzrk_searchterm + }); + }; + + var push_add_to_cart = function() { + clevertap.event.push("Added To Cart", { + "Product name": __wzrk_product_title, + "Category": __wzrk_product_category_name, + "Price": fixPrice(__wzrk_product_price), + "Currency": __wzrk_currency + }); + }; + + var push_checkout = function() { + var len = Shopify.checkout.line_items.length; + var items = []; + for (i = 0; i < len; i++) { + var obj = {}; + obj["Product_id"] = Shopify.checkout.line_items[i].product_id; + obj["Title"] = Shopify.checkout.line_items[i].title; + obj["Quantity"] = Shopify.checkout.line_items[i].quantity; + obj["Vendor"] = Shopify.checkout.line_items[i].vendor; + items.push(obj); + } + var checkout = Shopify.checkout; + if(typeof checkout !== "undefined"){ + var shipping_address = checkout.shipping_address; + var amount = checkout.total_price; + if(typeof amount !== 'number'){ + amount = parseFloat(amount); + } + if(typeof shipping_address === "undefined"){ + clevertap.event.push("Charged", { + "Amount": amount, + "Currency": checkout.currency, + "Email": checkout.email, + "Charged ID": checkout.order_id, + "Items": items + }); + } else{ + clevertap.event.push("Charged", { + "Amount": amount, + "Currency": checkout.currency, + "Ship_country": shipping_address.country, + "Ship_region": shipping_address.province, + "Ship_city": shipping_address.city, + "Email": checkout.email, + "Charged ID": checkout.order_id, + "Items": items + }); + } + } + }; + + var profile_push_checkout = function() { + if(Shopify.checkout != null){ + if(Shopify.checkout.billing_address != null){ + clevertap.profile.push({ + "Site": { + "Name": Shopify.checkout.billing_address.first_name, + "Email": Shopify.checkout.email + } + }); + } else{ + clevertap.profile.push({ + "Site": { + "Email": Shopify.checkout.email + } + }); + } + } + }; + + if (typeof __wzrk_product_json != "undefined") { + push_product_viewed(); + if(document.getElementsByName("add").length > 0){ + document.getElementsByName("add")[0].onclick = push_add_to_cart; + console.log("added to cart"); + }else{ + var addedToCart = false; + var forms = document.getElementsByTagName("form"); + var patt = /cart\/add$/i; + for (var i = 0; i < forms.length; i++) { + if(patt.test(forms[i].action)){ + var inputs = forms[i].getElementsByTagName("input"); + for (var j = 0; j < inputs.length; j++) { + if(inputs[j].type == "submit"){ + console.log("added to cart"); + inputs[j].onclick = push_add_to_cart; + addedToCart = true; + } + } + if(!addedToCart){ + var buttons = forms[i].getElementsByTagName("button"); + for(j =0; j < buttons.length; j++){ + if(buttons[j].type == "submit"){ + console.log("added to cart"); + buttons[j].onclick = push_add_to_cart; + addedToCart = true; + } + } + } + } + } + } + } + + if (typeof Shopify.checkout !== "undefined") { + var shouldPushCharged = true; + if(localStorage && localStorage.getItem("WZRK_LST_CHID") !== null){ + var lastChargedId = localStorage.getItem("WZRK_LST_CHID"); + var chargedId = "" + Shopify.checkout.order_id; + if(lastChargedId === chargedId){ + shouldPushCharged = false; + } + } + if(shouldPushCharged){ + profile_push_checkout(); + push_checkout(); + if(localStorage){ + localStorage.setItem("WZRK_LST_CHID", "" + Shopify.checkout.order_id); + } + } + } + if (typeof __wzrk_collection_name !== "undefined") { + category_viewed(); + } + if (typeof __wzrk_searchterm !== "undefined") { + push_search(); + } +} + +if (typeof __wzrk_account_id !== "undefined") { + wzrkShopify(__wzrk_account_id); +} else { + if (typeof Shopify !== "undefined") { + (function(){ + var shop = Shopify.shop; + var wzrkShopify = document.createElement('script'); + wzrkShopify.type = 'text/javascript'; + wzrkShopify.async = true; + wzrkShopify.src = "https://api.clevertap.com/js/wzrk-shopify.js?shop=" + shop; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(wzrkShopify, s); + }()); + } +} From 7626031f03055d48b765040eafa6c442a26cc7bd Mon Sep 17 00:00:00 2001 From: Jude Pereira Date: Sat, 23 May 2020 17:41:42 +0200 Subject: [PATCH 02/31] Merge commit '705cc8ffc87cc033e60ee119bdf3b5a44301c4ae' into feature/safari_web_push --- a.js | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 5 deletions(-) diff --git a/a.js b/a.js index 4f577751..7d2cf029 100644 --- a/a.js +++ b/a.js @@ -33,6 +33,7 @@ function __wizrocket() { var LRU_CACHE, LRU_CACHE_SIZE = 100; var chromeAgent; var firefoxAgent; + var safariAgent; // for VAPID web push function urlBase64ToUint8Array(base64String) { @@ -141,10 +142,57 @@ function __wizrocket() { } }; + wiz.setUpWebPushNotifications = function (subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsServiceUrl) { + if(navigator.userAgent.indexOf('Chrome') !== -1 || navigator.userAgent.indexOf('Firefox') !== -1){ + wiz.setUpChromeFirefoxNotifications(subscriptionCallback, serviceWorkerPath); + } else if(navigator.userAgent.indexOf('Safari') !== -1){ + wiz.setUpSafariNotifications(subscriptionCallback, apnsWebPushId, apnsServiceUrl); + } + }; + + /** + * Sets up a service worker for chrome push notifications and sends the data to LC + */ + wiz.setUpSafariNotifications= function (subscriptionCallback, apnsWebPushId, apnsServiceUrl) { + // ensure that proper arguments are passed + if (typeof apnsWebPushId === "undefined") { + wc.e('Ensure that APNS Web Push ID is supplied'); + } + if (typeof apnsServiceUrl === "undefined") { + wc.e('Ensure that APNS Web Push service path is supplied'); + } + if ('safari' in window && 'pushNotification' in window['safari']) { + window['safari']['pushNotification']['requestPermission']( + apnsServiceUrl, + apnsWebPushId, {}, function (subscription) { + if (subscription['permission'] === 'granted') { + var subscriptionData = JSON.parse(JSON.stringify(subscription)); + subscriptionData['endpoint'] = subscription['deviceToken']; + subscriptionData['browser'] = 'Safari'; + + var payload = subscriptionData; + payload = wiz.addSystemDataToObject(payload, true); + payload = JSON.stringify(payload); + var pageLoadUrl = dataPostURL; + pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "data"); + pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(payload)); + wiz.fireRequest(pageLoadUrl); + //set in localstorage + if (wzrk_util.isLocalStorageSupported()) { + localStorage.setItem(STRING_CONSTANTS.WEBPUSH_LS_KEY, 'ok'); + } + wc.l('Safari Web Push registered. Device Token: ' + subscription['deviceToken']); + } else if (subscription.permission === 'denied') { + wc.l('Error subscribing to Safari web push'); + } + }); + } + } + /** * Sets up a service worker for WebPush(chrome/Firefox) push notifications and sends the data to LC */ - wiz.setUpWebPushNotifications = function (subscriptionCallback, serviceWorkerPath) { + wiz.setUpChromeFirefoxNotifications = function (subscriptionCallback, serviceWorkerPath) { if ('serviceWorker' in navigator) { @@ -267,7 +315,7 @@ function __wizrocket() { targetDomain = region + '.' + targetDomain; } - dataPostURL = wz_pr + '//' + targetDomain + '/a?t=95'; + dataPostURL = wz_pr + '//' + targetDomain + '/a?t=96'; recorderURL = wz_pr + '//' + targetDomain + '/r?r=1'; emailURL = wz_pr + '//' + targetDomain + '/e?r=1'; @@ -2061,6 +2109,8 @@ function __wizrocket() { var serviceWorkerPath; var httpsPopupPath; var httpsIframePath; + var apnsWebPushId; + var apnsWebPushServiceUrl; if (displayArgs.length === 1) { if (wzrk_util.isObject(displayArgs[0])) { @@ -2079,6 +2129,8 @@ function __wizrocket() { serviceWorkerPath = notifObj["serviceWorkerPath"]; httpsPopupPath = notifObj["httpsPopupPath"]; httpsIframePath = notifObj["httpsIframePath"]; + apnsWebPushId = notifObj["apnsWebPushId"]; + apnsWebPushServiceUrl = notifObj["apnsWebPushServiceUrl"]; } } else { titleText = displayArgs[0]; @@ -2127,6 +2179,10 @@ function __wizrocket() { firefoxAgent = navigator.userAgent.match(/Firefox\/(\d+)/); if(typeof firefoxAgent === STRING_CONSTANTS.UNDEFINED || parseInt(firefoxAgent[1], 10) < 50) return; + }else if(navigator.userAgent.indexOf('Safari') !== -1){ + safariAgent = navigator.userAgent.match(/Safari\/(\d+)/); + if(typeof safariAgent === STRING_CONSTANTS.UNDEFINED || parseInt(safariAgent[1], 10) < 50) + return; } else { return; } @@ -2140,7 +2196,7 @@ function __wizrocket() { // handle migrations from other services -> chrome notifications may have already been asked for before if (Notification.permission === 'granted') { // skip the dialog and register - wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath); + wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); return; } else if (Notification.permission === 'denied') { // we've lost this profile :'( @@ -2148,7 +2204,7 @@ function __wizrocket() { } if (skipDialog) { - wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath); + wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); return; } } @@ -2244,7 +2300,7 @@ function __wizrocket() { if (typeof okCallback !== "undefined" && typeof okCallback === "function") { okCallback(); } - wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath); + wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); } else { if (typeof rejectCallback !== "undefined" && typeof rejectCallback === "function") { rejectCallback(); From 65dbc32468a9152995d266d7155e1da82c018820 Mon Sep 17 00:00:00 2001 From: bhavita Date: Tue, 26 May 2020 12:53:15 +0530 Subject: [PATCH 03/31] BP-180 : Check if event is discarded while ingestion for web, if yes, drop it --- a.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/a.js b/a.js index 4f577751..04207a65 100644 --- a/a.js +++ b/a.js @@ -542,6 +542,15 @@ function __wizrocket() { wiz.reportError(513, eventName + " is a restricted system event. It cannot be used as an event name."); continue; } + + //ToDo : check in discarded event array + var isDiscarded = false; + if(isDiscarded){ + wiz.reportError(510, eventName + " is a discarded event"); + continue; + } + + var data = {}; data['type'] = "event"; data['evtName'] = wzrk_util.sanitize(eventName, unsupportedKeyCharRegex); @@ -1226,6 +1235,10 @@ function __wizrocket() { }; wizrocket['event'].push = function () { + //Todo : Check from discarded + + + //since arguments is not an array, convert it into an array wiz.processEventArray(Array.prototype.slice.call(arguments)); return 0; From 406cc0dc0c68efc009c5e7f07161e92e6cc964d3 Mon Sep 17 00:00:00 2001 From: bhavita Date: Wed, 27 May 2020 18:42:56 +0530 Subject: [PATCH 04/31] Revert "BP-180 : Check if event is discarded while ingestion for web, if yes, drop it" We would do Web later This reverts commit 2e65a0af --- a.js | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/a.js b/a.js index 04207a65..4f577751 100644 --- a/a.js +++ b/a.js @@ -542,15 +542,6 @@ function __wizrocket() { wiz.reportError(513, eventName + " is a restricted system event. It cannot be used as an event name."); continue; } - - //ToDo : check in discarded event array - var isDiscarded = false; - if(isDiscarded){ - wiz.reportError(510, eventName + " is a discarded event"); - continue; - } - - var data = {}; data['type'] = "event"; data['evtName'] = wzrk_util.sanitize(eventName, unsupportedKeyCharRegex); @@ -1235,10 +1226,6 @@ function __wizrocket() { }; wizrocket['event'].push = function () { - //Todo : Check from discarded - - - //since arguments is not an array, convert it into an array wiz.processEventArray(Array.prototype.slice.call(arguments)); return 0; From cfd794e896fbdc9447f2b535f21548a568af91f0 Mon Sep 17 00:00:00 2001 From: sahil Date: Mon, 1 Jun 2020 12:23:35 +0530 Subject: [PATCH 05/31] oul remaining js files --- wzrk-shopify.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wzrk-shopify.js b/wzrk-shopify.js index 20f752af..9302445e 100644 --- a/wzrk-shopify.js +++ b/wzrk-shopify.js @@ -115,14 +115,14 @@ function wzrkShopify(id) { var profile_push_checkout = function() { if(Shopify.checkout != null){ if(Shopify.checkout.billing_address != null){ - clevertap.profile.push({ + clevertap.onUserLogin.push({ "Site": { "Name": Shopify.checkout.billing_address.first_name, "Email": Shopify.checkout.email } }); } else{ - clevertap.profile.push({ + clevertap.onUserLogin.push({ "Site": { "Email": Shopify.checkout.email } From abae2cbd0d67bd390e4b12c93f90ad992bda3617 Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Mon, 29 Jun 2020 18:19:36 +0530 Subject: [PATCH 06/31] added encode param in a.js --- a.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/a.js b/a.js index 7d2cf029..1f883fee 100644 --- a/a.js +++ b/a.js @@ -1526,15 +1526,15 @@ function __wizrocket() { }; - wiz.unSubEmail = function () { - wiz.handleEmailSubscription("0") + wiz.unSubEmail = function (reEncoded) { + wiz.handleEmailSubscription("0", reEncoded) }; wiz.subEmail = function () { wiz.handleEmailSubscription("1") }; - wiz.handleEmailSubscription = function (subscription) { + wiz.handleEmailSubscription = function (subscription, reEncoded) { var url_params_as_is = wzrk_util.getURLParams(location.href); // can't use url_params as it is in lowercase above var encodedEmailId = url_params_as_is['e']; @@ -1545,6 +1545,9 @@ function __wizrocket() { data['id'] = accountId; //accountId var url = emailURL; + if(reEncoded) { + url = wiz.addToURL(url, "encoded", reEncoded); + } url = wiz.addToURL(url, "e", encodedEmailId); url = wiz.addToURL(url, "d", wiz.compressData(JSON.stringify(data))); if(encodedProfileProps){ From e4284cdade3cee6533c8adddc6c9ac066c06b790 Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Mon, 29 Jun 2020 18:30:29 +0530 Subject: [PATCH 07/31] added encode param in getEmail and resub as well --- a.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/a.js b/a.js index 1f883fee..d2742364 100644 --- a/a.js +++ b/a.js @@ -1521,8 +1521,8 @@ function __wizrocket() { }; - wiz.getEmail = function () { - wiz.handleEmailSubscription('-1'); + wiz.getEmail = function (reEncoded) { + wiz.handleEmailSubscription('-1', reEncoded); }; @@ -1530,8 +1530,8 @@ function __wizrocket() { wiz.handleEmailSubscription("0", reEncoded) }; - wiz.subEmail = function () { - wiz.handleEmailSubscription("1") + wiz.subEmail = function (reEncoded) { + wiz.handleEmailSubscription("1", reEncoded) }; wiz.handleEmailSubscription = function (subscription, reEncoded) { From dd85e150824cb237566f951d774b667182203dfc Mon Sep 17 00:00:00 2001 From: sahil Date: Tue, 7 Jul 2020 13:54:11 +0530 Subject: [PATCH 08/31] reverse merge from develop --- a.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/a.js b/a.js index 7d2cf029..d2742364 100644 --- a/a.js +++ b/a.js @@ -1521,20 +1521,20 @@ function __wizrocket() { }; - wiz.getEmail = function () { - wiz.handleEmailSubscription('-1'); + wiz.getEmail = function (reEncoded) { + wiz.handleEmailSubscription('-1', reEncoded); }; - wiz.unSubEmail = function () { - wiz.handleEmailSubscription("0") + wiz.unSubEmail = function (reEncoded) { + wiz.handleEmailSubscription("0", reEncoded) }; - wiz.subEmail = function () { - wiz.handleEmailSubscription("1") + wiz.subEmail = function (reEncoded) { + wiz.handleEmailSubscription("1", reEncoded) }; - wiz.handleEmailSubscription = function (subscription) { + wiz.handleEmailSubscription = function (subscription, reEncoded) { var url_params_as_is = wzrk_util.getURLParams(location.href); // can't use url_params as it is in lowercase above var encodedEmailId = url_params_as_is['e']; @@ -1545,6 +1545,9 @@ function __wizrocket() { data['id'] = accountId; //accountId var url = emailURL; + if(reEncoded) { + url = wiz.addToURL(url, "encoded", reEncoded); + } url = wiz.addToURL(url, "e", encodedEmailId); url = wiz.addToURL(url, "d", wiz.compressData(JSON.stringify(data))); if(encodedProfileProps){ From 9c9c098e7eaa6d0f0f62f8ced3c55a51d3987742 Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Fri, 24 Jul 2020 18:02:14 +0530 Subject: [PATCH 09/31] bug fixes and a.js --- a.js | 285 ++++++++++++++++++++++++++++++++--------------------------- 1 file changed, 157 insertions(+), 128 deletions(-) diff --git a/a.js b/a.js index d2742364..bbd5eb68 100644 --- a/a.js +++ b/a.js @@ -20,6 +20,7 @@ function __wizrocket() { // to be used for checking whether the script loaded fine and the wiz.init function was called var onloadcalled = 0; // 1 = fired var processingBackup = false; + var unsubGroups = [] var gcookie, scookieObj; var accountId, region; @@ -39,8 +40,8 @@ function __wizrocket() { function urlBase64ToUint8Array(base64String) { var padding = '='.repeat((4 - base64String.length % 4) % 4); var base64 = (base64String + padding) - .replace(/\-/g, '+') - .replace(/_/g, '/') + .replace(/\-/g, '+') + .replace(/_/g, '/') ; var rawData = window.atob(base64); var processedData = [] @@ -207,7 +208,7 @@ function __wizrocket() { } serviceWorkerRegistration['pushManager']['subscribe'](subscribeObj) - ['then'](function (subscription) { + ['then'](function (subscription) { wc.l('Service Worker registered. Endpoint: ' + subscription['endpoint']); // convert the subscription keys to strings; this sets it up nicely for pushing to LC @@ -586,7 +587,7 @@ function __wizrocket() { } if (eventName == "Stayed" || eventName == "UTM Visited" || eventName == "App Launched" || - eventName == "Notification Sent" || eventName == "Notification Viewed" || eventName == "Notification Clicked") { + eventName == "Notification Sent" || eventName == "Notification Viewed" || eventName == "Notification Clicked") { wiz.reportError(513, eventName + " is a restricted system event. It cannot be used as an event name."); continue; } @@ -789,8 +790,8 @@ function __wizrocket() { this.cache = deleteFromObject(key, this.cache); } else if (all_keys.length === this.max) { this.cache = deleteFromObject( - all_keys[0], - this.cache + all_keys[0], + this.cache ); } this.cache[key] = value; @@ -822,8 +823,8 @@ function __wizrocket() { for (var index in all_keys) { if(all_keys.hasOwnProperty(index)) { if ( - this.cache[all_keys[index]] != null && - this.cache[all_keys[index]] === givenVal + this.cache[all_keys[index]] != null && + this.cache[all_keys[index]] === givenVal ) { return all_keys[index]; } @@ -971,11 +972,11 @@ function __wizrocket() { /* - We dont set the arp in cache for deregister requests. - For deregister requests we check for 'skipResARP' flag payload. If present we skip it. + We dont set the arp in cache for deregister requests. + For deregister requests we check for 'skipResARP' flag payload. If present we skip it. - Whenever we get 'isOUL' flag true in payload we delete the existing ARP instead of updating it. - */ + Whenever we get 'isOUL' flag true in payload we delete the existing ARP instead of updating it. + */ wiz.arp = function (jsonMap) { // For unregister calls dont set arp in LS if(typeof jsonMap["skipResARP"] !== STRING_CONSTANTS.UNDEFINED && jsonMap["skipResARP"]) { @@ -984,7 +985,7 @@ function __wizrocket() { } var isOULARP = (typeof jsonMap[STRING_CONSTANTS.IS_OUL] !== STRING_CONSTANTS.UNDEFINED - && jsonMap[STRING_CONSTANTS.IS_OUL] === true) ? true : false; + && jsonMap[STRING_CONSTANTS.IS_OUL] === true) ? true : false; if (wzrk_util.isLocalStorageSupported()) { try { @@ -1067,17 +1068,17 @@ function __wizrocket() { }; /* - anonymousUser => Only GUID present. - foundInCache => Identity used in On User Login is present in LRU_CACHE. So use the guid associated with it. + anonymousUser => Only GUID present. + foundInCache => Identity used in On User Login is present in LRU_CACHE. So use the guid associated with it. - Clear the cache in case on On User Login and Block all the request till we get resume requests flag in the response. - When user is found in Cache or the user is anonymous then dont block any requests. Just clear cache (handleCookieFromCache) + Clear the cache in case on On User Login and Block all the request till we get resume requests flag in the response. + When user is found in Cache or the user is anonymous then dont block any requests. Just clear cache (handleCookieFromCache) - On every On User Login we deregister the token for older User. - If new user is found in Cache then we call deregister function now - Else we call it once we get guid for new user in 'wiz.s' function. - */ + On every On User Login we deregister the token for older User. + If new user is found in Cache then we call deregister function now + Else we call it once we get guid for new user in 'wiz.s' function. + */ wiz.processOUL = function (profileArr) { var sendOULFlag = true; var addToK = function (ids) { @@ -1238,9 +1239,9 @@ function __wizrocket() { if (wzrk_util.isArray(loginArr) && loginArr.length > 0) { var profileObj = loginArr.pop(); var processProfile = typeof profileObj != STRING_CONSTANTS.UNDEFINED && wzrk_util.isObject(profileObj) && - ((typeof profileObj['Site'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Site"]).length > 0) || - (typeof profileObj['Facebook'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Facebook"]).length > 0) || - (typeof profileObj['Google Plus'] != "undefined" && Object.keys(profileObj["Google Plus"]).length > 0)); + ((typeof profileObj['Site'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Site"]).length > 0) || + (typeof profileObj['Facebook'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Facebook"]).length > 0) || + (typeof profileObj['Google Plus'] != "undefined" && Object.keys(profileObj["Google Plus"]).length > 0)); if (processProfile) { setInstantDeleteFlagInK(); wiz.processOUL([profileObj]); @@ -1382,7 +1383,7 @@ function __wizrocket() { }; -// profile like https://developers.google.com/+/api/latest/people + // profile like https://developers.google.com/+/api/latest/people wiz.processGPlusUserObj = function (user) { var profileData = {}; @@ -1530,6 +1531,30 @@ function __wizrocket() { wiz.handleEmailSubscription("0", reEncoded) }; + wiz.unsubEmailGroups = function (reEncoded) { + unsubGroups = [] + var elements = document.getElementsByClassName( + "ct-unsub-group-input-item"); + + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + if(element.name) { + var data = {name: element.name, isUnsubscribed: element.checked} + unsubGroups.push(data) + } + } + + wiz.handleEmailSubscription("2", reEncoded) + }; + + wiz.setSubscriptionGroups = function(value) { + unsubGroups = value + } + + wiz.getSubscriptionGroups = function () { + return unsubGroups + } + wiz.subEmail = function (reEncoded) { wiz.handleEmailSubscription("1", reEncoded) }; @@ -1543,6 +1568,7 @@ function __wizrocket() { if (typeof encodedEmailId !== STRING_CONSTANTS.UNDEFINED) { var data = {}; data['id'] = accountId; //accountId + data['unsubGroups'] = unsubGroups // unsubscribe groups var url = emailURL; if(reEncoded) { @@ -1690,7 +1716,7 @@ function __wizrocket() { if (!wiz.isValueValid(guid)) { guid = wiz.readCookie(STRING_CONSTANTS.GCOOKIE_NAME); if (wiz.isValueValid(guid) && (guid.indexOf('%') === 0 || - guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) { + guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) { guid = null; } if (wiz.isValueValid(guid)) { @@ -1800,7 +1826,7 @@ function __wizrocket() { } var kId_from_LS = wiz.readFromLSorCookie( - STRING_CONSTANTS.KCOOKIE_NAME + STRING_CONSTANTS.KCOOKIE_NAME ); if (kId_from_LS != null && kId_from_LS["id"] && resume) { var guidFromLRUCache = LRU_CACHE.cache[kId_from_LS["id"]]; @@ -1809,8 +1835,8 @@ function __wizrocket() { } } wiz.saveToLSorCookie( - STRING_CONSTANTS.GCOOKIE_NAME, - global + STRING_CONSTANTS.GCOOKIE_NAME, + global ); var lastK = LRU_CACHE.getSecondLastKEY(); @@ -2001,9 +2027,9 @@ function __wizrocket() { return; } if ( - !wiz.isValueValid(gcookie) && - RESP_N < REQ_N - 1 && - tries < MAX_TRIES + !wiz.isValueValid(gcookie) && + RESP_N < REQ_N - 1 && + tries < MAX_TRIES ) { setTimeout(function () { fireRequest(url, tries + 1, skipARP, sendOULFlag); @@ -2331,8 +2357,8 @@ function __wizrocket() { targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] = 1; } var excludeFromFreqCaps = -1, campaignSessionLimit = -1, campaignDailyLimit = -1, - campaignTotalLimit = -1, - totalDailyLimit = -1, totalSessionLimit = -1; + campaignTotalLimit = -1, + totalDailyLimit = -1, totalSessionLimit = -1; if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['efc'] != STRING_CONSTANTS.UNDEFINED) { excludeFromFreqCaps = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['efc'], 10); } @@ -2478,25 +2504,25 @@ function __wizrocket() { if (typeof ctaElement != STRING_CONSTANTS.UNDEFINED) { ctaElement.onclick = - function () { - //invoke js function call - if (typeof jsFunc != STRING_CONSTANTS.UNDEFINED) { - //track notification clicked event - if (typeof isPreview == STRING_CONSTANTS.UNDEFINED) { - wiz.fireRequest(onClick); + function () { + //invoke js function call + if (typeof jsFunc != STRING_CONSTANTS.UNDEFINED) { + //track notification clicked event + if (typeof isPreview == STRING_CONSTANTS.UNDEFINED) { + wiz.fireRequest(onClick); + } + invokeExternalJs(jsFunc, targetingMsgJson); + //close iframe. using -1 for no campaignId + wiz.closeIframe('-1', divId); + return; + } + //pass on the gcookie|page|scookieId for capturing the click event + if (targetingMsgJson['display']['window'] == '1') { + window.open(onClick, '_blank'); + } else { + window.location = onClick; } - invokeExternalJs(jsFunc, targetingMsgJson); - //close iframe. using -1 for no campaignId - wiz.closeIframe('-1', divId); - return; - } - //pass on the gcookie|page|scookieId for capturing the click event - if (targetingMsgJson['display']['window'] == '1') { - window.open(onClick, '_blank'); - } else { - window.location = onClick; } - } } } }; @@ -2604,20 +2630,20 @@ function __wizrocket() { html = html.replace('##campaignId##', campaignId); } else { var css = '' + - ''; + ''; var bgColor, textColor, btnBg, leftTd, btColor; if (targetingMsgJson['display']['theme'] == 'dark') { @@ -2641,12 +2667,12 @@ function __wizrocket() { } var onClickStr = "parent.$WZRK_WR.closeIframe(" + campaignId + ",'" + divId + "');"; var title = "
" + - "×" + - "
" + - "" + - //""+ - "" + imageTd + ""; - } - var onClickStr = "parent.$WZRK_WR.closeIframe(" + campaignId + ",'" + divId + "');"; - var title = "
" + - "×" + - "
" + - "
" + - "
" + titleText + "
"; + "×" + + "
" + + "" + + //""+ + "" + imageTd + "
" + + "
" + titleText + "
"; var body = "
" + descriptionText + "
"; html = css + title + body; } @@ -2711,8 +2737,8 @@ function __wizrocket() { var onClick = targetingMsgJson['display']['onClick']; if (wizrocket.hasOwnProperty("notificationCallback") && - typeof wizrocket["notificationCallback"] !== "undefined" && - typeof wizrocket["notificationCallback"] === "function") { + typeof wizrocket["notificationCallback"] !== "undefined" && + typeof wizrocket["notificationCallback"] === "function") { var notificationCallback = wizrocket["notificationCallback"]; if (!_callBackCalled) { var inaObj = {}; @@ -2769,8 +2795,8 @@ function __wizrocket() { } //dont show exit intent on tablet/mobile - only on desktop if (typeof targetingMsgJson['display']['layout'] == STRING_CONSTANTS.UNDEFINED && - ((/mobile/i.test(navigator.userAgent)) || (/mini/i.test(navigator.userAgent)) || (/iPad/i.test(navigator.userAgent)) || - ('ontouchstart' in window) || (/tablet/i.test(navigator.userAgent)))) { + ((/mobile/i.test(navigator.userAgent)) || (/mini/i.test(navigator.userAgent)) || (/iPad/i.test(navigator.userAgent)) || + ('ontouchstart' in window) || (/tablet/i.test(navigator.userAgent)))) { return; } @@ -2815,20 +2841,20 @@ function __wizrocket() { html = html.replace('##campaignId##', campaignId); } else { var css = '' + - ''; + ''; var bgColor, textColor, btnBg, btColor; if (targetingMsgJson['display']['theme'] == 'dark') { @@ -2855,11 +2881,11 @@ function __wizrocket() { } var onClickStr = "parent.$WZRK_WR.closeIframe(" + campaignId + ",'intentPreview');"; var title = "
" + - "×" + - "
" + - "
" + titleText + "
"; + "×" + + "
" + + "
" + titleText + "
"; var body = "
" + descriptionText + "
" + imageTd + ctaText + - "
"; + "
"; html = css + title + body; } iframe.setAttribute('style', 'z-index: 2147483647; display:block; height: 100% !important; width: 100% !important;min-height:80px !important;border:0px !important; border-color:none !important;'); @@ -3188,13 +3214,16 @@ function __wizrocket() { wiz['closeIframe'] = wiz.closeIframe; wiz['getEmail'] = wiz.getEmail; wiz['unSubEmail'] = wiz.unSubEmail; + wiz['unsubEmailGroups'] = wiz.unsubEmailGroups; + wiz['getSubscriptionGroups'] = wiz.getSubscriptionGroups; + wiz['setSubscriptionGroups'] = wiz.setSubscriptionGroups; wiz['subEmail'] = wiz.subEmail; wiz['logout'] = wiz.logout; wiz['clear'] = wiz.clear; wizrocket['getCleverTapID'] = wiz.getCleverTapID; -// ---------- compression part ---------- + // ---------- compression part ---------- var LZS = { @@ -3221,9 +3250,9 @@ function __wizrocket() { convertToFormattedHex: function (byte_arr) { var hex_str = "", - i, - len, - tmp_hex; + i, + len, + tmp_hex; if (!wzrk_util.isArray(byte_arr)) { return false; @@ -3307,8 +3336,8 @@ function __wizrocket() { } output = output + - LZS._keyStr.charAt(enc1) + LZS._keyStr.charAt(enc2) + - LZS._keyStr.charAt(enc3) + LZS._keyStr.charAt(enc4); + LZS._keyStr.charAt(enc1) + LZS._keyStr.charAt(enc2) + + LZS._keyStr.charAt(enc3) + LZS._keyStr.charAt(enc4); } @@ -3319,19 +3348,19 @@ function __wizrocket() { compress: function (uncompressed) { if (uncompressed == null) return ""; var i, value, - context_dictionary = {}, - context_dictionaryToCreate = {}, - context_c = "", - context_wc = "", - context_w = "", - context_enlargeIn = 2, // Compensate for the first entry which should not count - context_dictSize = 3, - context_numBits = 2, - context_data_string = "", - context_data_val = 0, - context_data_position = 0, - ii, - f = LZS._f; + context_dictionary = {}, + context_dictionaryToCreate = {}, + context_c = "", + context_wc = "", + context_w = "", + context_enlargeIn = 2, // Compensate for the first entry which should not count + context_dictSize = 3, + context_numBits = 2, + context_data_string = "", + context_data_val = 0, + context_data_position = 0, + ii, + f = LZS._f; for (ii = 0; ii < uncompressed.length; ii += 1) { context_c = uncompressed.charAt(ii); @@ -3562,8 +3591,8 @@ function __wizrocket() { var y = matches[1]; var composedDate = new Date(y, m, d); return composedDate.getDate() == d && - composedDate.getMonth() == m && - composedDate.getFullYear() == y; + composedDate.getMonth() == m && + composedDate.getFullYear() == y; }, isArray: function (input) { @@ -3619,17 +3648,17 @@ function __wizrocket() { var match, - pl = /\+/g, // Regex for replacing addition symbol with a space - search = /([^&=]+)=?([^&]*)/g, - decode = function (s) { - var replacement = s.replace(pl, " "); - try { - replacement = decodeURIComponent(replacement); - } catch (e) { - //eat - } - return replacement; - }; + pl = /\+/g, // Regex for replacing addition symbol with a space + search = /([^&=]+)=?([^&]*)/g, + decode = function (s) { + var replacement = s.replace(pl, " "); + try { + replacement = decodeURIComponent(replacement); + } catch (e) { + //eat + } + return replacement; + }; while (match = search.exec(uri)) { @@ -3735,13 +3764,13 @@ function __wizrocket() { }; -// leading spaces, dot, colon, dollar, single quote, double quote, backslash, trailing spaces + // leading spaces, dot, colon, dollar, single quote, double quote, backslash, trailing spaces var unsupportedKeyCharRegex = new RegExp("^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$", "g"); -// leading spaces, single quote, double quote, backslash, trailing spaces + // leading spaces, single quote, double quote, backslash, trailing spaces var unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", "g"); -//used to handle cookies in Opera mini + //used to handle cookies in Opera mini var doubleQuoteRegex = new RegExp("\"", "g"); var singleQuoteRegex = new RegExp("\'", "g"); From 1e96ea2ef4e0e360c3a28233dbece1912a953c2c Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Thu, 6 Aug 2020 18:36:32 +0530 Subject: [PATCH 10/31] PR fixes --- a.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/a.js b/a.js index bbd5eb68..3b41f7d1 100644 --- a/a.js +++ b/a.js @@ -91,6 +91,7 @@ function __wizrocket() { var SCOOKIE_EXP_TIME_IN_SECS = 60 * 20; // 20 mins + var GROUP_SUBSCRIPTION_REQUEST_ID = "2"; var EVT_PING = "ping", EVT_PUSH = "push"; @@ -1544,7 +1545,7 @@ function __wizrocket() { } } - wiz.handleEmailSubscription("2", reEncoded) + wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded) }; wiz.setSubscriptionGroups = function(value) { From cc9883eb415de10c5a00bfffecca944495315504 Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Tue, 18 Aug 2020 17:29:33 +0530 Subject: [PATCH 11/31] a.js changes for enhancements --- a.js | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/a.js b/a.js index 3b41f7d1..d1965b13 100644 --- a/a.js +++ b/a.js @@ -21,6 +21,8 @@ function __wizrocket() { var onloadcalled = 0; // 1 = fired var processingBackup = false; var unsubGroups = [] + var updatedCategoryLong; + var categoryLongKey = "cUsY"; var gcookie, scookieObj; var accountId, region; @@ -1527,7 +1529,6 @@ function __wizrocket() { wiz.handleEmailSubscription('-1', reEncoded); }; - wiz.unSubEmail = function (reEncoded) { wiz.handleEmailSubscription("0", reEncoded) }; @@ -1545,19 +1546,29 @@ function __wizrocket() { } } - wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded) + wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); + }; + + wiz.changeSubscriptionGroups = function (reEncoded) { + wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); + }; + + wiz.setUpdatedCategoryLong = function (profile) { + if(profile[categoryLongKey]) { + updatedCategoryLong = profile[categoryLongKey]; + } }; wiz.setSubscriptionGroups = function(value) { - unsubGroups = value - } + unsubGroups = value; + }; wiz.getSubscriptionGroups = function () { - return unsubGroups - } + return unsubGroups; + }; wiz.subEmail = function (reEncoded) { - wiz.handleEmailSubscription("1", reEncoded) + wiz.handleEmailSubscription("1", reEncoded); }; wiz.handleEmailSubscription = function (subscription, reEncoded) { @@ -1569,7 +1580,10 @@ function __wizrocket() { if (typeof encodedEmailId !== STRING_CONSTANTS.UNDEFINED) { var data = {}; data['id'] = accountId; //accountId - data['unsubGroups'] = unsubGroups // unsubscribe groups + data['unsubGroups'] = unsubGroups; // unsubscribe groups + if(updatedCategoryLong) { + data[categoryLongKey] = updatedCategoryLong; + } var url = emailURL; if(reEncoded) { @@ -3216,8 +3230,10 @@ function __wizrocket() { wiz['getEmail'] = wiz.getEmail; wiz['unSubEmail'] = wiz.unSubEmail; wiz['unsubEmailGroups'] = wiz.unsubEmailGroups; + wiz['changeSubscriptionGroups'] = wiz.changeSubscriptionGroups; wiz['getSubscriptionGroups'] = wiz.getSubscriptionGroups; wiz['setSubscriptionGroups'] = wiz.setSubscriptionGroups; + wiz['setUpdatedCategoryLong'] = wiz.setUpdatedCategoryLong; wiz['subEmail'] = wiz.subEmail; wiz['logout'] = wiz.logout; wiz['clear'] = wiz.clear; From cf9edd6ac24025da0b5fc042f58526a388174de7 Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Thu, 20 Aug 2020 13:45:30 +0530 Subject: [PATCH 12/31] parameterized fetching groups on landing pagE --- a.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/a.js b/a.js index d1965b13..5ead357c 100644 --- a/a.js +++ b/a.js @@ -1525,8 +1525,8 @@ function __wizrocket() { }; - wiz.getEmail = function (reEncoded) { - wiz.handleEmailSubscription('-1', reEncoded); + wiz.getEmail = function (reEncoded, withGroups) { + wiz.handleEmailSubscription('-1', reEncoded, withGroups); }; wiz.unSubEmail = function (reEncoded) { @@ -1549,7 +1549,8 @@ function __wizrocket() { wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); }; - wiz.changeSubscriptionGroups = function (reEncoded) { + wiz.changeSubscriptionGroups = function (reEncoded, updatedGroups) { + wiz.setSubscriptionGroups(updatedGroups); wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); }; @@ -1571,7 +1572,7 @@ function __wizrocket() { wiz.handleEmailSubscription("1", reEncoded); }; - wiz.handleEmailSubscription = function (subscription, reEncoded) { + wiz.handleEmailSubscription = function (subscription, reEncoded, fetchGroups) { var url_params_as_is = wzrk_util.getURLParams(location.href); // can't use url_params as it is in lowercase above var encodedEmailId = url_params_as_is['e']; @@ -1586,6 +1587,9 @@ function __wizrocket() { } var url = emailURL; + if(fetchGroups) { + url = wiz.addToURL(url, "fetchGroups", reEncoded); + } if(reEncoded) { url = wiz.addToURL(url, "encoded", reEncoded); } From 0a82e56874e09e23d935c3437605cdfbaff37d4c Mon Sep 17 00:00:00 2001 From: Mohammed Gadiwala Date: Thu, 20 Aug 2020 16:26:18 +0530 Subject: [PATCH 13/31] fixes --- a.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/a.js b/a.js index 5ead357c..467b5a98 100644 --- a/a.js +++ b/a.js @@ -1588,7 +1588,7 @@ function __wizrocket() { var url = emailURL; if(fetchGroups) { - url = wiz.addToURL(url, "fetchGroups", reEncoded); + url = wiz.addToURL(url, "fetchGroups", fetchGroups); } if(reEncoded) { url = wiz.addToURL(url, "encoded", reEncoded); From 2da6abbdf26cc77ffee36dd4122bbd5cd95e663e Mon Sep 17 00:00:00 2001 From: Navin Nagpal Date: Wed, 23 Sep 2020 14:58:35 +0530 Subject: [PATCH 14/31] Initial commit to support regions for Shopify --- wzrk-shopify.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/wzrk-shopify.js b/wzrk-shopify.js index 9302445e..98efdc72 100644 --- a/wzrk-shopify.js +++ b/wzrk-shopify.js @@ -8,9 +8,13 @@ if(typeof clevertap === "undefined"){ }; } -function wzrkShopify(id) { +function wzrkShopify(id, region) { + if (typeof region === "undefined") { + region = ""; + } clevertap.account.push({ - "id": id + "id": id, + "region": region }); clevertap.enablePersonalization = true; // enables Personalization clevertap.plugin = "shop"; @@ -191,7 +195,8 @@ function wzrkShopify(id) { } if (typeof __wzrk_account_id !== "undefined") { - wzrkShopify(__wzrk_account_id); + // SUC-60553. Region introduced. Pass empty if undefined + wzrkShopify(__wzrk_account_id, __wzrk_region); } else { if (typeof Shopify !== "undefined") { (function(){ From 030e04e1df81fd8b2333791a3a854ae9741f4b8e Mon Sep 17 00:00:00 2001 From: Navin Nagpal Date: Thu, 24 Sep 2020 01:28:57 +0530 Subject: [PATCH 15/31] Using stackName instead of region --- wzrk-shopify.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/wzrk-shopify.js b/wzrk-shopify.js index 98efdc72..dcec4b58 100644 --- a/wzrk-shopify.js +++ b/wzrk-shopify.js @@ -9,15 +9,12 @@ if(typeof clevertap === "undefined"){ } function wzrkShopify(id, region) { - if (typeof region === "undefined") { - region = ""; - } clevertap.account.push({ "id": id, - "region": region }); clevertap.enablePersonalization = true; // enables Personalization clevertap.plugin = "shop"; + clevertap.region = region; var wzrk = document.createElement('script'); wzrk.type = 'text/javascript'; wzrk.async = true; @@ -195,7 +192,10 @@ function wzrkShopify(id, region) { } if (typeof __wzrk_account_id !== "undefined") { - // SUC-60553. Region introduced. Pass empty if undefined + // SUC-60553. Region introduced + if (typeof __wzrk_region === "undefined") { + __wzrk_region = ""; + } wzrkShopify(__wzrk_account_id, __wzrk_region); } else { if (typeof Shopify !== "undefined") { From dfe09c33999e514ed3b52e04c464c73a4fe33051 Mon Sep 17 00:00:00 2001 From: Navin Nagpal Date: Thu, 24 Sep 2020 08:07:37 +0530 Subject: [PATCH 16/31] Empty string check when setting region --- wzrk-shopify.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/wzrk-shopify.js b/wzrk-shopify.js index dcec4b58..f0cfcd16 100644 --- a/wzrk-shopify.js +++ b/wzrk-shopify.js @@ -14,7 +14,9 @@ function wzrkShopify(id, region) { }); clevertap.enablePersonalization = true; // enables Personalization clevertap.plugin = "shop"; - clevertap.region = region; + if (region !== "") { + clevertap.region = region; + } var wzrk = document.createElement('script'); wzrk.type = 'text/javascript'; wzrk.async = true; From 1c5b17a36c86f34e2f55689fcf9f6bdf49fbbae9 Mon Sep 17 00:00:00 2001 From: Navin Nagpal Date: Thu, 24 Sep 2020 13:35:21 +0530 Subject: [PATCH 17/31] Unwanted comma removed --- wzrk-shopify.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wzrk-shopify.js b/wzrk-shopify.js index f0cfcd16..57abe8e2 100644 --- a/wzrk-shopify.js +++ b/wzrk-shopify.js @@ -10,7 +10,7 @@ if(typeof clevertap === "undefined"){ function wzrkShopify(id, region) { clevertap.account.push({ - "id": id, + "id": id }); clevertap.enablePersonalization = true; // enables Personalization clevertap.plugin = "shop"; From 3858e11d397887214f704bf100da82290bde10bf Mon Sep 17 00:00:00 2001 From: Navin Nagpal Date: Thu, 24 Sep 2020 21:55:13 +0530 Subject: [PATCH 18/31] Undefined check for region --- wzrk-shopify.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wzrk-shopify.js b/wzrk-shopify.js index 57abe8e2..0fd4e1d0 100644 --- a/wzrk-shopify.js +++ b/wzrk-shopify.js @@ -14,7 +14,7 @@ function wzrkShopify(id, region) { }); clevertap.enablePersonalization = true; // enables Personalization clevertap.plugin = "shop"; - if (region !== "") { + if (typeof region !== "undefined" && region !== "") { clevertap.region = region; } var wzrk = document.createElement('script'); From 933690a1f25a633e74d58bfb72a51833070ca423 Mon Sep 17 00:00:00 2001 From: Royson Date: Mon, 5 Apr 2021 17:53:26 +0530 Subject: [PATCH 19/31] updated favicon and lc logo for a.js --- ct_logo.svg | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ct_logo.svg b/ct_logo.svg index 7fb0387d..0f268698 100644 --- a/ct_logo.svg +++ b/ct_logo.svg @@ -1 +1,21 @@ -Grey \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + From 35381c5665be5b6e98b60425d619c447e00591ab Mon Sep 17 00:00:00 2001 From: avneesh Date: Wed, 7 Apr 2021 13:05:06 +0530 Subject: [PATCH 20/31] master merge --- ct_logo.svg | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ct_logo.svg b/ct_logo.svg index 7fb0387d..0f268698 100644 --- a/ct_logo.svg +++ b/ct_logo.svg @@ -1 +1,21 @@ -Grey \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + From 5d5a408eac6f4685f92d00b6acf1f00d62f27cf4 Mon Sep 17 00:00:00 2001 From: shubham Date: Mon, 28 Aug 2023 10:14:48 +0530 Subject: [PATCH 21/31] exclude all other from the directory of source repository SNE-39292, SNE-40229 --- a.js | 3831 -------------------------------------------- clevertap_sw.js | 1 - ct_logo.svg | 21 - dialog.js | 189 --- gtm_segment.html | 47 - localforage.min.js | 5 - p.js | 501 ------ q.js | 315 ---- wzrk-shopify.js | 214 --- 9 files changed, 5124 deletions(-) delete mode 100644 a.js delete mode 100644 clevertap_sw.js delete mode 100644 ct_logo.svg delete mode 100644 dialog.js delete mode 100644 gtm_segment.html delete mode 100644 localforage.min.js delete mode 100644 p.js delete mode 100644 q.js delete mode 100644 wzrk-shopify.js diff --git a/a.js b/a.js deleted file mode 100644 index 467b5a98..00000000 --- a/a.js +++ /dev/null @@ -1,3831 +0,0 @@ -function __wizrocket() { - - - var targetDomain = 'wzrkt.com'; - // var targetDomain = 'localhost:3838'; //ALWAYS comment this line before deploying - - var wz_pr = "https:"; - - var dataPostURL, recorderURL, emailURL; - var wiz = this; - // var serviceWorkerPath = '/clevertap_sw.js'; // the service worker is placed in the doc root - var doc = document; - var domain = window.location.hostname; - var broadDomain; - var wc = window.console; - var requestTime = 0, seqNo = 0; - var wzrk_error = {}; //to trap input errors - var wiz_counter = 0; // to keep track of number of times we load the body - var globalCache = {}; - // to be used for checking whether the script loaded fine and the wiz.init function was called - var onloadcalled = 0; // 1 = fired - var processingBackup = false; - var unsubGroups = [] - var updatedCategoryLong; - var categoryLongKey = "cUsY"; - - var gcookie, scookieObj; - var accountId, region; - var campaignDivMap = {}; - var blockRequeust = false, clearCookie = false; - var SCOOKIE_NAME, globalChargedId; - var globalEventsMap, globalProfileMap, currentSessionId; - var storageDelim = "|$|"; - var staleEvtMaxTime = 20 * 60; //20 mins - var COOKIE_EXPIRY = 86400 * 365 * 10; //10 years in seconds. Seconds in an days * days in an year * number of years - var LRU_CACHE, LRU_CACHE_SIZE = 100; - var chromeAgent; - var firefoxAgent; - var safariAgent; - - // for VAPID web push - function urlBase64ToUint8Array(base64String) { - var padding = '='.repeat((4 - base64String.length % 4) % 4); - var base64 = (base64String + padding) - .replace(/\-/g, '+') - .replace(/_/g, '/') - ; - var rawData = window.atob(base64); - var processedData = [] - for (var i=0; i maxLen ? referrer_domain.substring(0, maxLen) : referrer_domain; - data['referrer'] = referrer_domain; - } - - - var utm_source = url_params['utm_source'] || url_params['wzrk_source']; - if (typeof utm_source != STRING_CONSTANTS.UNDEFINED) { - utm_source = utm_source.length > maxLen ? utm_source.substring(0, maxLen) : utm_source; - data['us'] = utm_source; //utm_source - } - - var utm_medium = url_params['utm_medium'] || url_params['wzrk_medium']; - if (typeof utm_medium != STRING_CONSTANTS.UNDEFINED) { - utm_medium = utm_medium.length > maxLen ? utm_medium.substring(0, maxLen) : utm_medium; - data['um'] = utm_medium; //utm_medium - } - - - var utm_campaign = url_params['utm_campaign'] || url_params['wzrk_campaign']; - if (typeof utm_campaign != STRING_CONSTANTS.UNDEFINED) { - utm_campaign = utm_campaign.length > maxLen ? utm_campaign.substring(0, maxLen) : utm_campaign; - data['uc'] = utm_campaign; //utm_campaign - } - - // also independently send wzrk_medium to the backend - if (typeof url_params['wzrk_medium'] != STRING_CONSTANTS.UNDEFINED) { - var wm = url_params['wzrk_medium']; - if (wm.match(/^email$|^social$|^search$/)) { - data['wm'] = wm; //wzrk_medium - } - - } - - } - - data = wiz.addSystemDataToObject(data, undefined); - data['cpg'] = currLocation; - - data[STRING_CONSTANTS.CAMP_COOKIE_NAME] = wiz.getCampaignObjForLc(); - var pageLoadUrl = dataPostURL; - wiz.addFlags(data); - //send dsync flag when page = 1 - if (data['pg'] != STRING_CONSTANTS.UNDEFINED && data['pg'] == 1) { - wiz.overrideDSyncFlag(data); - } - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "page"); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(JSON.stringify(data))); - wiz.saveAndFireRequest(pageLoadUrl, false); - - - // -- ping request logic - - var pingRequest = function () { - var pageLoadUrl = dataPostURL; - var data = {}; - data = wiz.addSystemDataToObject(data, undefined); - - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PING); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(JSON.stringify(data))); - wiz.saveAndFireRequest(pageLoadUrl, false); - }; - - setTimeout(function () { - if (pgCount <= 3) { // send ping for up to 3 pages - pingRequest(); - } - - if (wiz.isPingContinuous()) { - setInterval(function () { - pingRequest(); - }, CONTINUOUS_PING_FREQ_IN_MILLIS); - } - }, FIRST_PING_FREQ_IN_MILLIS); - - // -- ping request logic - - - if (typeof wizrocket['session'] == STRING_CONSTANTS.UNDEFINED) { - - wizrocket['event']['getDetails'] = function (evtName) { - if (!wzrk_util.isPersonalizationActive()) { - return; - } - if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { - globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE); - } - if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { - return; - } - var evtObj = globalEventsMap[evtName]; - var respObj = {}; - - if (typeof evtObj != STRING_CONSTANTS.UNDEFINED) { - respObj['firstTime'] = new Date(evtObj[1] * 1000); - respObj['lastTime'] = new Date(evtObj[2] * 1000); - respObj['count'] = evtObj[0]; - return respObj; - } - - - }; - - wizrocket['profile']['getAttribute'] = function (propName) { - if (!wzrk_util.isPersonalizationActive()) { - return; - } - if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { - globalProfileMap = wiz.readFromLSorCookie(STRING_CONSTANTS.PR_COOKIE); - } - if (typeof globalProfileMap != STRING_CONSTANTS.UNDEFINED) { - return globalProfileMap[propName]; - } - }; - wizrocket['session'] = {}; - wizrocket['session']['getTimeElapsed'] = function () { - if (!wzrk_util.isPersonalizationActive()) { - return; - } - if (typeof scookieObj != STRING_CONSTANTS.UNDEFINED) { - scookieObj = wiz.getSessionCookieObject(); - } - var sessionStart = scookieObj['s']; - if (typeof sessionStart != STRING_CONSTANTS.UNDEFINED) { - var ts = wzrk_util.getNow(); - return Math.floor(ts - sessionStart); - } - }; - - wizrocket['user'] = {}; - wizrocket['user']['getTotalVisits'] = function () { - if (!wzrk_util.isPersonalizationActive()) { - return; - } - var visitCount = wiz.getMetaProp('sc'); - if (typeof visitCount == STRING_CONSTANTS.UNDEFINED) { - visitCount = 1; - } - return visitCount; - }; - - wizrocket['session']['getPageCount'] = function () { - if (!wzrk_util.isPersonalizationActive()) { - return; - } - - if (typeof scookieObj != STRING_CONSTANTS.UNDEFINED) { - scookieObj = wiz.getSessionCookieObject(); - } - return scookieObj['p']; - }; - - wizrocket['user']['getLastVisit'] = function () { - if (!wzrk_util.isPersonalizationActive()) { - return; - } - var prevSession = wiz.getMetaProp('ps'); - if (typeof prevSession != STRING_CONSTANTS.UNDEFINED) { - return new Date(prevSession * 1000); - } - }; - } - onloadcalled = 1; //always the last line in this function - - - }; - - - wiz.readFromLSorCookie = function (property) { - var data; - if (globalCache.hasOwnProperty(property)) { - return globalCache[property]; - } - if (wzrk_util.isLocalStorageSupported()) { - data = localStorage[property]; - } else { - data = wiz.readCookie(property); - } - if (typeof data != STRING_CONSTANTS.UNDEFINED && data !== null && data.trim() != '') { - var value = JSON.parse(decodeURIComponent(data)); - globalCache[property] = value; - return value; - } - }; - - wiz.saveToLSorCookie = function (property, val) { - if (typeof val == STRING_CONSTANTS.UNDEFINED || val == null) { - return; - } - try { - if (wzrk_util.isLocalStorageSupported()) { - localStorage[property] = encodeURIComponent(JSON.stringify(val)); - } else { - if (property === STRING_CONSTANTS.GCOOKIE_NAME) { - wiz.createCookie(property, encodeURIComponent(val), 0, domain); - } else { - wiz.createCookie(property, encodeURIComponent(JSON.stringify(val)), 0, domain); - } - } - globalCache[property] = val; - } catch (e) { - } - }; - - var processEvent = function (data) { - - wiz.addToLocalEventMap(data['evtName']); - data = wiz.addSystemDataToObject(data, undefined); - wiz.addFlags(data); - data[STRING_CONSTANTS.CAMP_COOKIE_NAME] = wiz.getCampaignObjForLc(); - var compressedData = wiz.compressData(JSON.stringify(data)); - - var pageLoadUrl = dataPostURL; - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); - - - wiz.saveAndFireRequest(pageLoadUrl, false); - }; - - wiz.processEventArray = function (eventArr) { - - if (wzrk_util.isArray(eventArr)) { - - /** looping since the events could be fired in quick succession, and we could end up - with multiple pushes without getting a chance to process - */ - while (eventArr.length > 0) { - - var eventName = eventArr.shift(); // take out name of the event - - if (!wzrk_util.isString(eventName)) { - wc.e(wzrk_msg['event-error']); - return; - } - - if (eventName.length > 1024) { - eventName = eventName.substring(0, 1024); - wiz.reportError(510, eventName + "... length exceeded 1024 chars. Trimmed."); - } - - if (eventName == "Stayed" || eventName == "UTM Visited" || eventName == "App Launched" || - eventName == "Notification Sent" || eventName == "Notification Viewed" || eventName == "Notification Clicked") { - wiz.reportError(513, eventName + " is a restricted system event. It cannot be used as an event name."); - continue; - } - var data = {}; - data['type'] = "event"; - data['evtName'] = wzrk_util.sanitize(eventName, unsupportedKeyCharRegex); - - if (eventArr.length != 0) { - var eventObj = eventArr.shift(); - - if (!wzrk_util.isObject(eventObj)) { - eventArr.unshift(eventObj); // put it back if it is not an object - } else { - //check Charged Event vs. other events. - if (eventName == "Charged") { - if (!wiz.isChargedEventStructureValid(eventObj)) { - wiz.reportError(511, "Charged event structure invalid. Not sent."); - continue; - } - } else { - if (!wiz.isEventStructureFlat(eventObj)) { - wiz.reportError(512, eventName + " event structure invalid. Not sent."); - continue; - } - - } - - data['evtData'] = eventObj; - } - } - processEvent(data); - - } - - } - }; - - wiz.addToLocalEventMap = function (evtName) { - if (wzrk_util.isLocalStorageSupported()) { - if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { - globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE); - if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { - globalEventsMap = {}; - } - } - var nowTs = wzrk_util.getNow(); - var evtDetail = globalEventsMap[evtName]; - if (typeof evtDetail != STRING_CONSTANTS.UNDEFINED) { - evtDetail[2] = nowTs; - evtDetail[0]++; - } else { - evtDetail = []; - evtDetail.push(1); - evtDetail.push(nowTs); - evtDetail.push(nowTs); - } - globalEventsMap[evtName] = evtDetail; - wiz.saveToLSorCookie(STRING_CONSTANTS.EV_COOKIE, globalEventsMap); - } - }; - - wiz.addToLocalProfileMap = function (profileObj, override) { - if (wzrk_util.isLocalStorageSupported()) { - if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { - globalProfileMap = wiz.readFromLSorCookie(STRING_CONSTANTS.PR_COOKIE); - if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { - globalProfileMap = {}; - } - } - - //Move props from custom bucket to outside. - if (typeof profileObj['_custom'] != STRING_CONSTANTS.UNDEFINED) { - var keys = profileObj['_custom']; - for (var key in keys) { - if (keys.hasOwnProperty(key)) { - profileObj[key] = keys[key]; - } - } - delete profileObj['_custom']; - } - - for (var prop in profileObj) { - if (profileObj.hasOwnProperty(prop)) { - if (globalProfileMap.hasOwnProperty(prop) && !override) { - continue; - } - globalProfileMap[prop] = profileObj[prop]; - } - } - if (typeof globalProfileMap['_custom'] != STRING_CONSTANTS.UNDEFINED) { - delete globalProfileMap['_custom']; - } - wiz.saveToLSorCookie(STRING_CONSTANTS.PR_COOKIE, globalProfileMap); - } - }; - - wiz.overrideDSyncFlag = function (data) { - if (wzrk_util.isPersonalizationActive()) { - data['dsync'] = true; - } - }; - - wiz.addARPToRequest = function (url, skipResARP) { - if(typeof skipResARP !== STRING_CONSTANTS.UNDEFINED && skipResARP === true) { - var _arp = {}; - _arp["skipResARP"] = true; - return wiz.addToURL(url, 'arp', wiz.compressData(JSON.stringify(_arp))); - } - if (wzrk_util.isLocalStorageSupported() && typeof localStorage[STRING_CONSTANTS.ARP_COOKIE] != STRING_CONSTANTS.UNDEFINED) { - return wiz.addToURL(url, 'arp', wiz.compressData(JSON.stringify(wiz.readFromLSorCookie(STRING_CONSTANTS.ARP_COOKIE)))); - } - return url; - }; - - wiz.addFlags = function (data) { - - //check if cookie should be cleared. - clearCookie = wiz.getAndClearMetaProp(STRING_CONSTANTS.CLEAR); - if (clearCookie !== undefined && clearCookie) { - data['rc'] = true; - wc.d("reset cookie sent in request and cleared from meta for future requests."); - } - if (wzrk_util.isPersonalizationActive()) { - var lastSyncTime = wiz.getMetaProp('lsTime'); - var expirySeconds = wiz.getMetaProp('exTs'); - - //dsync not found in local storage - get data from server - if (typeof lastSyncTime == STRING_CONSTANTS.UNDEFINED || typeof expirySeconds == STRING_CONSTANTS.UNDEFINED) { - data['dsync'] = true; - return; - } - var now = wzrk_util.getNow(); - //last sync time has expired - get fresh data from server - if (lastSyncTime + expirySeconds < now) { - data['dsync'] = true; - } - } - - - }; - - var unregisterTokenForGuid = function (givenGUID) { - var data = {}; - data["type"] = "data"; - if (wiz.isValueValid(givenGUID)) { - data["g"] = givenGUID; - } - data["action"] = "unregister"; - data["id"] = accountId; - - var obj = wiz.getSessionCookieObject(); - - data["s"] = obj["s"]; //Session cookie - var compressedData = wiz.compressData(JSON.stringify(data)); - - var pageLoadUrl = dataPostURL; - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "data"); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); - - wiz.fireRequest(pageLoadUrl, true); - }; - - var LRU_cache = function (max) { - this.max = max; - var keyOrder; - var LRU_CACHE = wiz.readFromLSorCookie(STRING_CONSTANTS.LRU_CACHE); - if (LRU_CACHE) { - var lru_cache = {}; - keyOrder = []; - LRU_CACHE = LRU_CACHE.cache; - for (var entry in LRU_CACHE) { - if(LRU_CACHE.hasOwnProperty(entry)) { - lru_cache[LRU_CACHE[entry][0]] = LRU_CACHE[entry][1]; - keyOrder.push(LRU_CACHE[entry][0]); - } - - } - this.cache = lru_cache; - } else { - this.cache = {}; - keyOrder = []; - } - - this.get = function (key) { - var item = this.cache[key]; - if (item) { - var temp_val = item; - this.cache = deleteFromObject(key, this.cache); - this.cache[key] = item; - keyOrder.push(key); - } - this.saveCacheToLS(this.cache); - return item; - }; - - this.set = function (key, value) { - var item = this.cache[key]; - var all_keys = keyOrder; - if (item != null) { - this.cache = deleteFromObject(key, this.cache); - } else if (all_keys.length === this.max) { - this.cache = deleteFromObject( - all_keys[0], - this.cache - ); - } - this.cache[key] = value; - if (keyOrder[keyOrder.length - 1] !== key) { - keyOrder.push(key); - } - this.saveCacheToLS(this.cache); - }; - - this.saveCacheToLS = function (cache) { - var obj_to_array = []; - var all_keys = keyOrder; - for (var index in all_keys) { - if(all_keys.hasOwnProperty(index)) { - var temp = []; - temp.push(all_keys[index]); - temp.push(cache[all_keys[index]]); - obj_to_array.push(temp); - } - } - wiz.saveToLSorCookie(STRING_CONSTANTS.LRU_CACHE, { - cache: obj_to_array - }); - }; - - this.getKEY = function (givenVal) { - if (givenVal == null) return null; - var all_keys = keyOrder; - for (var index in all_keys) { - if(all_keys.hasOwnProperty(index)) { - if ( - this.cache[all_keys[index]] != null && - this.cache[all_keys[index]] === givenVal - ) { - return all_keys[index]; - } - } - } - return null; - }; - - this.getSecondLastKEY = function () { - var keysArr = keyOrder; - if (keysArr != null && keysArr.length > 1) { - return keysArr[keysArr.length - 2]; - } else { - return -1; - } - }; - - this.getLastKey = function () { - if (keyOrder.length) { - return keyOrder[keyOrder.length - 1]; - } - }; - - - var deleteFromObject = function (key, obj) { - var all_keys = JSON.parse(JSON.stringify(keyOrder)); - var new_cache = {}; - var indexToDelete; - for (var index in all_keys) { - if(all_keys.hasOwnProperty(index)) { - if (all_keys[index] !== key) { - new_cache[all_keys[index]] = obj[all_keys[index]]; - } else { - indexToDelete = index; - } - } - } - all_keys.splice(indexToDelete, 1); - keyOrder = JSON.parse(JSON.stringify(all_keys)); - return new_cache; - }; - }; - - wiz.getCampaignObjForLc = function () { - var campObj = {}; - if (wzrk_util.isLocalStorageSupported()) { - campObj = wzrk_util.getCampaignObject(); - - var resultObj = []; - var globalObj = campObj['global']; - var today = wzrk_util.getToday(); - var dailyObj = campObj[today]; - - if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) { - var campaignIdArray = Object.keys(globalObj); - for (var index in campaignIdArray) { - if (campaignIdArray.hasOwnProperty(index)) { - var dailyC = 0; - var totalC = 0; - var campaignId = campaignIdArray[index]; - if (campaignId == 'tc') { - continue; - } - if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED && typeof dailyObj[campaignId] != STRING_CONSTANTS.UNDEFINED) { - dailyC = dailyObj[campaignId]; - } - if (typeof globalObj != STRING_CONSTANTS.UNDEFINED && typeof globalObj[campaignId] != STRING_CONSTANTS.UNDEFINED) { - totalC = globalObj[campaignId]; - } - var element = [campaignId, dailyC, totalC]; - resultObj.push(element); - } - } - } - var todayC = 0; - if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED && typeof dailyObj['tc'] != STRING_CONSTANTS.UNDEFINED) { - todayC = dailyObj['tc']; - } - resultObj = {"wmp": todayC, 'tlc': resultObj}; - return resultObj; - } - }; - - var handleCookieFromCache = function () { - blockRequeust = false; - wc.d("Block request is false"); - if (wzrk_util.isLocalStorageSupported()) { - delete localStorage[STRING_CONSTANTS.PR_COOKIE]; - delete localStorage[STRING_CONSTANTS.EV_COOKIE]; - delete localStorage[STRING_CONSTANTS.META_COOKIE]; - delete localStorage[STRING_CONSTANTS.ARP_COOKIE]; - delete localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; - delete localStorage[STRING_CONSTANTS.CHARGEDID_COOKIE_NAME]; - } - wiz.deleteCookie(STRING_CONSTANTS.CAMP_COOKIE_NAME, domain); - wiz.deleteCookie(SCOOKIE_NAME, broadDomain); - wiz.deleteCookie(STRING_CONSTANTS.ARP_COOKIE, broadDomain); - scookieObj = ''; - }; - - var deleteUser = function () { - blockRequeust = true; - wc.d("Block request is true"); - globalCache = {}; - if (wzrk_util.isLocalStorageSupported()) { - delete localStorage[STRING_CONSTANTS.GCOOKIE_NAME]; - delete localStorage[STRING_CONSTANTS.KCOOKIE_NAME]; - delete localStorage[STRING_CONSTANTS.PR_COOKIE]; - delete localStorage[STRING_CONSTANTS.EV_COOKIE]; - delete localStorage[STRING_CONSTANTS.META_COOKIE]; - delete localStorage[STRING_CONSTANTS.ARP_COOKIE]; - delete localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; - delete localStorage[STRING_CONSTANTS.CHARGEDID_COOKIE_NAME]; - } - wiz.deleteCookie(STRING_CONSTANTS.GCOOKIE_NAME, broadDomain); - wiz.deleteCookie(STRING_CONSTANTS.CAMP_COOKIE_NAME, domain); - wiz.deleteCookie(STRING_CONSTANTS.KCOOKIE_NAME, domain); - wiz.deleteCookie(SCOOKIE_NAME, broadDomain); - wiz.deleteCookie(STRING_CONSTANTS.ARP_COOKIE, broadDomain); - gcookie = null; - scookieObj = ''; - - }; - - var setInstantDeleteFlagInK = function () { - var k = wiz.readFromLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME); - if (typeof k == STRING_CONSTANTS.UNDEFINED) { - k = {}; - } - k['flag'] = true; - wiz.saveToLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME, k); - }; - - wiz.logout = function () { - wc.d("logout called"); - setInstantDeleteFlagInK(); - }; - - - wiz.clear = function () { - wc.d("clear called. Reset flag has been set."); - deleteUser(); - wiz.setMetaProp(STRING_CONSTANTS.CLEAR, true); - }; - - - /* - We dont set the arp in cache for deregister requests. - For deregister requests we check for 'skipResARP' flag payload. If present we skip it. - - Whenever we get 'isOUL' flag true in payload we delete the existing ARP instead of updating it. - */ - wiz.arp = function (jsonMap) { - // For unregister calls dont set arp in LS - if(typeof jsonMap["skipResARP"] !== STRING_CONSTANTS.UNDEFINED && jsonMap["skipResARP"]) { - wc.d("Update ARP Request rejected", jsonMap); - return null; - } - - var isOULARP = (typeof jsonMap[STRING_CONSTANTS.IS_OUL] !== STRING_CONSTANTS.UNDEFINED - && jsonMap[STRING_CONSTANTS.IS_OUL] === true) ? true : false; - - if (wzrk_util.isLocalStorageSupported()) { - try { - var arpFromStorage = wiz.readFromLSorCookie(STRING_CONSTANTS.ARP_COOKIE); - if (typeof arpFromStorage == STRING_CONSTANTS.UNDEFINED || isOULARP) { - arpFromStorage = {}; - } - - for (var key in jsonMap) { - if (jsonMap.hasOwnProperty(key)) { - if (jsonMap[key] == -1) { - delete arpFromStorage[key]; - } else { - arpFromStorage[key] = jsonMap[key]; - } - } - } - wiz.saveToLSorCookie(STRING_CONSTANTS.ARP_COOKIE, arpFromStorage); - - - } catch (e) { - wc.e("Unable to parse ARP JSON: " + e); - } - - } - }; - - wiz.processProfileArray = function (profileArr) { - if (wzrk_util.isArray(profileArr) && profileArr.length > 0) { - - for (var index in profileArr) { - if(profileArr.hasOwnProperty(index)) { - var outerObj = profileArr[index]; - var data = {}; - var profileObj; - if (typeof outerObj['Site'] != STRING_CONSTANTS.UNDEFINED) { //organic data from the site - profileObj = outerObj['Site']; - if (wzrk_util.isObjectEmpty(profileObj) || !wiz.isProfileValid(profileObj)) { - return; - } - - } else if (typeof outerObj['Facebook'] != STRING_CONSTANTS.UNDEFINED) { //fb connect data - var FbProfileObj = outerObj['Facebook']; - //make sure that the object contains any data at all - - if (!wzrk_util.isObjectEmpty(FbProfileObj) && (!FbProfileObj['error'])) { - profileObj = wiz.processFBUserObj(FbProfileObj); - } - - } else if (typeof outerObj['Google Plus'] != STRING_CONSTANTS.UNDEFINED) { - var GPlusProfileObj = outerObj['Google Plus']; - if (!wzrk_util.isObjectEmpty(GPlusProfileObj) && (!GPlusProfileObj['error'])) { - profileObj = wiz.processGPlusUserObj(GPlusProfileObj); - } - } - if (typeof profileObj != STRING_CONSTANTS.UNDEFINED && (!wzrk_util.isObjectEmpty(profileObj))) { // profile got set from above - data['type'] = "profile"; - if (typeof profileObj['tz'] === STRING_CONSTANTS.UNDEFINED) { - //try to auto capture user timezone if not present - profileObj['tz'] = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; - } - - data['profile'] = profileObj; - wiz.addToLocalProfileMap(profileObj, true); - data = wiz.addSystemDataToObject(data, undefined); - - wiz.addFlags(data); - var compressedData = wiz.compressData(JSON.stringify(data)); - - var pageLoadUrl = dataPostURL; - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); - - wiz.saveAndFireRequest(pageLoadUrl, blockRequeust); - - } - } - } - } - }; - - /* - anonymousUser => Only GUID present. - foundInCache => Identity used in On User Login is present in LRU_CACHE. So use the guid associated with it. - - Clear the cache in case on On User Login and Block all the request till we get resume requests flag in the response. - When user is found in Cache or the user is anonymous then dont block any requests. Just clear cache (handleCookieFromCache) - - - On every On User Login we deregister the token for older User. - If new user is found in Cache then we call deregister function now - Else we call it once we get guid for new user in 'wiz.s' function. - */ - wiz.processOUL = function (profileArr) { - var sendOULFlag = true; - var addToK = function (ids) { - var k = wiz.readFromLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME); - var g = wiz.readFromLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME); - var kId, flag; - var nowDate = new Date(); - if (typeof k == STRING_CONSTANTS.UNDEFINED) { - k = {}; - kId = ids; - } else {/*check if already exists*/ - kId = k['id']; - var anonymousUser = false; - var foundInCache = false; - if (kId == null) { - kId = ids[0]; - anonymousUser = true; - } - - if (LRU_CACHE == null && wzrk_util.isLocalStorageSupported()) { - LRU_CACHE = new LRU_cache(LRU_CACHE_SIZE); - } - - if (anonymousUser) { - if (wiz.isValueValid(g)) { - LRU_CACHE.set(kId, g); - blockRequeust = false; - } - } else { - for (var idx in ids) { - if(ids.hasOwnProperty(idx)) { - var id = ids[idx]; - if (LRU_CACHE.cache[id]) { - kId = id; - foundInCache = true; - break; - } - } - } - } - - if (foundInCache) { - if (kId !== LRU_CACHE.getLastKey()) { - // Same User - handleCookieFromCache(); - } else { - sendOULFlag = false; - } - var g_from_cache = LRU_CACHE.get(kId); - LRU_CACHE.set(kId, g_from_cache); - wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, g_from_cache); - gcookie = g_from_cache; - - var lastK = LRU_CACHE.getSecondLastKEY(); - if(lastK !== -1) { - var lastGUID = LRU_CACHE.cache[lastK]; - unregisterTokenForGuid(lastGUID); - } - } else { - if (!anonymousUser) { - wiz.clear(); - } else { - if (wiz.isValueValid(g)) { - gcookie = g; - wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, g); - sendOULFlag = false; - } - } - kId = ids[0]; - } - } - k['id'] = kId; - wiz.saveToLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME, k); - }; - - if (wzrk_util.isArray(profileArr) && profileArr.length > 0) { - - for (var index in profileArr) { - if(profileArr.hasOwnProperty(index)) { - var outerObj = profileArr[index]; - var data = {}; - var profileObj; - if (typeof outerObj['Site'] != STRING_CONSTANTS.UNDEFINED) { //organic data from the site - profileObj = outerObj['Site']; - if (wzrk_util.isObjectEmpty(profileObj) || !wiz.isProfileValid(profileObj)) { - return; - } - - } else if (typeof outerObj['Facebook'] != STRING_CONSTANTS.UNDEFINED) { //fb connect data - var FbProfileObj = outerObj['Facebook']; - //make sure that the object contains any data at all - - if (!wzrk_util.isObjectEmpty(FbProfileObj) && (!FbProfileObj['error'])) { - profileObj = wiz.processFBUserObj(FbProfileObj); - } - - } else if (typeof outerObj['Google Plus'] != STRING_CONSTANTS.UNDEFINED) { - var GPlusProfileObj = outerObj['Google Plus']; - if (!wzrk_util.isObjectEmpty(GPlusProfileObj) && (!GPlusProfileObj['error'])) { - profileObj = wiz.processGPlusUserObj(GPlusProfileObj); - } - } - if (typeof profileObj != STRING_CONSTANTS.UNDEFINED && (!wzrk_util.isObjectEmpty(profileObj))) { // profile got set from above - data['type'] = "profile"; - if (typeof profileObj['tz'] === STRING_CONSTANTS.UNDEFINED) { - //try to auto capture user timezone if not present - profileObj['tz'] = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; - } - - data['profile'] = profileObj; - var ids = []; - if (wzrk_util.isLocalStorageSupported()) { - if (typeof profileObj['Identity'] != STRING_CONSTANTS.UNDEFINED) { - ids.push(profileObj['Identity']); - } - if (typeof profileObj['Email'] != STRING_CONSTANTS.UNDEFINED) { - ids.push(profileObj['Email']); - } - if (typeof profileObj['GPID'] != STRING_CONSTANTS.UNDEFINED) { - ids.push("GP:" + profileObj['GPID']); - } - if (typeof profileObj['FBID'] != STRING_CONSTANTS.UNDEFINED) { - ids.push("FB:" + profileObj['FBID']); - } - if (ids.length > 0) { - addToK(ids); - } - } - wiz.addToLocalProfileMap(profileObj, true); - data = wiz.addSystemDataToObject(data, undefined); - - wiz.addFlags(data); - // Adding 'isOUL' flag in true for OUL cases which. - // This flag tells LC to create a new arp object. - // Also we will receive the same flag in response arp which tells to delete existing arp object. - if(sendOULFlag) { - data[STRING_CONSTANTS.IS_OUL] = true; - } - - var compressedData = wiz.compressData(JSON.stringify(data)); - - var pageLoadUrl = dataPostURL; - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); - - // Whenever sendOULFlag is true then dont send arp and gcookie (guid in memory in the request) - // Also when this flag is set we will get another flag from LC in arp which tells us to delete arp - // stored in the cache and replace it with the response arp. - wiz.saveAndFireRequest(pageLoadUrl, blockRequeust, sendOULFlag); - - } - } - } - } - }; - - wiz.processLoginArray = function (loginArr) { - if (wzrk_util.isArray(loginArr) && loginArr.length > 0) { - var profileObj = loginArr.pop(); - var processProfile = typeof profileObj != STRING_CONSTANTS.UNDEFINED && wzrk_util.isObject(profileObj) && - ((typeof profileObj['Site'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Site"]).length > 0) || - (typeof profileObj['Facebook'] != STRING_CONSTANTS.UNDEFINED && Object.keys(profileObj["Facebook"]).length > 0) || - (typeof profileObj['Google Plus'] != "undefined" && Object.keys(profileObj["Google Plus"]).length > 0)); - if (processProfile) { - setInstantDeleteFlagInK(); - wiz.processOUL([profileObj]); - } else { - //console.error - wc.e("Profile object is in incorrect format"); - } - } - }; - - wiz.overloadArrayPush = function () { - - if (typeof wizrocket['onUserLogin'] === "undefined") { - wizrocket['onUserLogin'] = []; - } - - wizrocket['onUserLogin'].push = function () { - //since arguments is not an array, convert it into an array - wiz.processLoginArray(Array.prototype.slice.call(arguments)); - return 0; - }; - - if (typeof wizrocket['privacy'] === "undefined") { - wizrocket['privacy'] = []; - } - - wizrocket['privacy'].push = function () { - //since arguments is not an array, convert it into an array - wiz.processPrivacyArray(Array.prototype.slice.call(arguments)); - return 0; - }; - - wizrocket['event'].push = function () { - //since arguments is not an array, convert it into an array - wiz.processEventArray(Array.prototype.slice.call(arguments)); - return 0; - }; - - if (typeof wizrocket['notifications'] === STRING_CONSTANTS.UNDEFINED) - wizrocket['notifications'] = []; - - wizrocket['notifications'].push = function () { - wiz.setUpWebPush(Array.prototype.slice.call(arguments)); - return 0; - }; - - - wizrocket['profile'].push = function () { - //since arguments is not an array, convert it into an array - wiz.processProfileArray(Array.prototype.slice.call(arguments)); - return 0; - }; - wizrocket['logout'] = wiz.logout; - wizrocket['clear'] = wiz.clear; - wiz.processLoginArray(wizrocket['onUserLogin']); // process old stuff from the login array before we overloaded the push method - wiz.processPrivacyArray(wizrocket['privacy']); // process old stuff from the privacy array before we overloaded the push method - wiz.processEventArray(wizrocket['event']); // process old stuff from the event array before we overloaded the push method - wiz.processProfileArray(wizrocket['profile']); // process old stuff from the profile array before we overloaded the push method - wiz.setUpWebPush(wizrocket['notifications']); // process old stuff from notifications array before overload - - // clean up the notifications array - while (wizrocket['notifications'].length > 0) - wizrocket['notifications'].pop(); - }; - - var isOptInRequest = false; - - var dropRequestDueToOptOut = function () { - if (isOptInRequest || !wiz.isValueValid(gcookie) || !wzrk_util.isString(gcookie)) { - isOptInRequest = false; - return false; - } - return gcookie.slice(-3) === STRING_CONSTANTS.OPTOUT_COOKIE_ENDSWITH; - }; - - var addUseIPToRequest = function (pageLoadUrl) { - var useIP = wiz.getMetaProp(STRING_CONSTANTS.USEIP_KEY); - if (typeof useIP !== 'boolean') { - useIP = false; - } - return wiz.addToURL(pageLoadUrl, STRING_CONSTANTS.USEIP_KEY, useIP ? 'true' : 'false'); - }; - - wiz.processPrivacyArray = function (privacyArr) { - if (wzrk_util.isArray(privacyArr) && privacyArr.length > 0) { - var privacyObj = privacyArr[0]; - var data = {}; - var profileObj = {}; - if (privacyObj.hasOwnProperty(STRING_CONSTANTS.OPTOUT_KEY)) { - var optOut = privacyObj[STRING_CONSTANTS.OPTOUT_KEY]; - if (typeof optOut === 'boolean') { - profileObj[STRING_CONSTANTS.CT_OPTOUT_KEY] = optOut; - //should be true when user wants to opt in - isOptInRequest = !optOut; - } - } - if (privacyObj.hasOwnProperty(STRING_CONSTANTS.USEIP_KEY)) { - var useIP = privacyObj[STRING_CONSTANTS.USEIP_KEY]; - if (typeof useIP === 'boolean') { - wiz.setMetaProp(STRING_CONSTANTS.USEIP_KEY, useIP); - } - } - if (!wzrk_util.isObjectEmpty(profileObj)) { - data['type'] = "profile"; - data['profile'] = profileObj; - data = wiz.addSystemDataToObject(data, undefined); - var compressedData = wiz.compressData(JSON.stringify(data)); - var pageLoadUrl = dataPostURL; - pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH); - pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData); - pageLoadUrl = wiz.addToURL(pageLoadUrl, STRING_CONSTANTS.OPTOUT_KEY, optOut ? 'true' : 'false'); - wiz.saveAndFireRequest(pageLoadUrl, blockRequeust); - } - } - }; - - wiz.saveAndFireRequest = function (url, override, sendOULFlag) { - - var now = wzrk_util.getNow(); - url = wiz.addToURL(url, "rn", ++REQ_N); - var data = url + '&i=' + now + "&sn=" + seqNo; - wiz.backUpEvent(data, REQ_N); - - - if (!blockRequeust || override || (clearCookie !== undefined && clearCookie)) { - if (now == requestTime) { - seqNo++; - } else { - requestTime = now; - seqNo = 0; - } - - wiz.fireRequest(data, false, sendOULFlag); - - } else { - wc.d("Not fired due to block request - " + blockRequeust + " or clearCookie - " + clearCookie); - } - - }; - - - // profile like https://developers.google.com/+/api/latest/people - wiz.processGPlusUserObj = function (user) { - - var profileData = {}; - if (typeof user['displayName'] != STRING_CONSTANTS.UNDEFINED) { - profileData['Name'] = user['displayName']; - } - if (typeof user['id'] != STRING_CONSTANTS.UNDEFINED) { - profileData['GPID'] = user['id'] + ""; - } - - if (typeof user['gender'] != STRING_CONSTANTS.UNDEFINED) { - if (user['gender'] == "male") { - profileData['Gender'] = "M"; - } else if (user['gender'] == "female") { - profileData['Gender'] = "F"; - } else if (user['gender'] == "other") { - profileData['Gender'] = "O"; - } - } - - if (typeof user['image'] != STRING_CONSTANTS.UNDEFINED) { - if (user['image']['isDefault'] == false) { - profileData['Photo'] = user['image'].url.split('?sz')[0]; - } - } - - if (typeof user['emails'] != "undefined") { - for (var emailIdx = 0; emailIdx < user['emails'].length; emailIdx++) { - var emailObj = user['emails'][emailIdx]; - if (emailObj.type == 'account') { - profileData['Email'] = emailObj.value; - } - } - } - - - if (typeof user['organizations'] != "undefined") { - profileData['Employed'] = 'N'; - for (var i = 0; i < user['organizations'].length; i++) { - var orgObj = user['organizations'][i]; - if (orgObj.type == 'work') { - profileData['Employed'] = 'Y'; - } - } - } - - - if (typeof user['birthday'] != STRING_CONSTANTS.UNDEFINED) { - var yyyymmdd = user['birthday'].split('-'); //comes in as "1976-07-27" - profileData['DOB'] = $WZRK_WR.setDate(yyyymmdd[0] + yyyymmdd[1] + yyyymmdd[2]); - } - - - if (typeof user['relationshipStatus'] != STRING_CONSTANTS.UNDEFINED) { - profileData['Married'] = 'N'; - if (user['relationshipStatus'] == 'married') { - profileData['Married'] = 'Y'; - } - } - wc.d("gplus usr profile " + JSON.stringify(profileData)); - - return profileData; - }; - - wiz.processFBUserObj = function (user) { - var profileData = {}; - profileData['Name'] = user['name']; - if (typeof user['id'] != STRING_CONSTANTS.UNDEFINED) { - profileData['FBID'] = user['id'] + ""; - } - // Feb 2014 - FB announced over 58 gender options, hence we specifically look for male or female. Rest we don't care. - if (user['gender'] == "male") { - profileData['Gender'] = "M"; - } else if (user['gender'] == "female") { - profileData['Gender'] = "F"; - } else { - profileData['Gender'] = "O"; - } - - var getHighestEducation = function (eduArr) { - if (typeof eduArr != "undefined") { - var college = ""; - var highschool = ""; - - for (var i = 0; i < eduArr.length; i++) { - var edu = eduArr[i]; - if (typeof edu.type != "undefined") { - var type = edu.type; - if (type == "Graduate School") { - return "Graduate"; - } else if (type == "College") { - college = "1"; - } else if (type == "High School") { - highschool = "1"; - } - } - } - - if (college == "1") { - return "College"; - } else if (highschool == "1") { - return "School"; - } - } - - }; - - if (user['relationship_status'] != STRING_CONSTANTS.UNDEFINED) { - profileData['Married'] = 'N'; - if (user['relationship_status'] == 'Married') { - profileData['Married'] = 'Y'; - } - } - - var edu = getHighestEducation(user['education']); - if (typeof edu !== "undefined") { - profileData['Education'] = edu; - } - - var work = (typeof user['work'] !== STRING_CONSTANTS.UNDEFINED) ? user['work'].length : 0; - if (work > 0) { - profileData['Employed'] = 'Y'; - } else { - profileData['Employed'] = 'N'; - } - - if (typeof user['email'] !== "undefined") { - profileData['Email'] = user['email']; - } - - if (typeof user['birthday'] !== "undefined") { - var mmddyy = user['birthday'].split('/'); //comes in as "08/15/1947" - profileData['DOB'] = $WZRK_WR.setDate(mmddyy[2] + mmddyy[0] + mmddyy[1]); - } - return profileData; - }; - - - wiz.getEmail = function (reEncoded, withGroups) { - wiz.handleEmailSubscription('-1', reEncoded, withGroups); - }; - - wiz.unSubEmail = function (reEncoded) { - wiz.handleEmailSubscription("0", reEncoded) - }; - - wiz.unsubEmailGroups = function (reEncoded) { - unsubGroups = [] - var elements = document.getElementsByClassName( - "ct-unsub-group-input-item"); - - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - if(element.name) { - var data = {name: element.name, isUnsubscribed: element.checked} - unsubGroups.push(data) - } - } - - wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); - }; - - wiz.changeSubscriptionGroups = function (reEncoded, updatedGroups) { - wiz.setSubscriptionGroups(updatedGroups); - wiz.handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); - }; - - wiz.setUpdatedCategoryLong = function (profile) { - if(profile[categoryLongKey]) { - updatedCategoryLong = profile[categoryLongKey]; - } - }; - - wiz.setSubscriptionGroups = function(value) { - unsubGroups = value; - }; - - wiz.getSubscriptionGroups = function () { - return unsubGroups; - }; - - wiz.subEmail = function (reEncoded) { - wiz.handleEmailSubscription("1", reEncoded); - }; - - wiz.handleEmailSubscription = function (subscription, reEncoded, fetchGroups) { - - var url_params_as_is = wzrk_util.getURLParams(location.href); // can't use url_params as it is in lowercase above - var encodedEmailId = url_params_as_is['e']; - var encodedProfileProps = url_params_as_is['p']; - - if (typeof encodedEmailId !== STRING_CONSTANTS.UNDEFINED) { - var data = {}; - data['id'] = accountId; //accountId - data['unsubGroups'] = unsubGroups; // unsubscribe groups - if(updatedCategoryLong) { - data[categoryLongKey] = updatedCategoryLong; - } - - var url = emailURL; - if(fetchGroups) { - url = wiz.addToURL(url, "fetchGroups", fetchGroups); - } - if(reEncoded) { - url = wiz.addToURL(url, "encoded", reEncoded); - } - url = wiz.addToURL(url, "e", encodedEmailId); - url = wiz.addToURL(url, "d", wiz.compressData(JSON.stringify(data))); - if(encodedProfileProps){ - url = wiz.addToURL(url, "p", encodedProfileProps); - } - - if (subscription != '-1') { - url = wiz.addToURL(url, "sub", subscription); - } - - wiz.fireRequest(url); - } - }; - - - wiz.reportError = function (code, desc) { - wzrk_error['c'] = code; - wzrk_error['d'] = desc; - wc.e(wzrk_error_txt + code + ": " + desc); - }; - - - //to debug put this in the JS console -> sessionStorage['WZRK_D']=""; - wiz.isDebug = function () { - return ((typeof sessionStorage != STRING_CONSTANTS.UNDEFINED) && sessionStorage['WZRK_D'] == ''); - }; - - wiz.isPingContinuous = function () { - return ((typeof wzrk_d != STRING_CONSTANTS.UNDEFINED) && (wzrk_d['ping'] == 'continuous')); - }; - - - wiz.compressData = function (dataObject) { - wc.d('dobj:' + dataObject); - return LZS.compressToBase64(dataObject); - }; - - - wiz.addSystemDataToObject = function (dataObject, ignoreTrim) { - // ignore trim for chrome notifications; undefined everywhere else - if (typeof ignoreTrim === STRING_CONSTANTS.UNDEFINED) { - dataObject = wzrk_util.removeUnsupportedChars(dataObject); - } - if (!wzrk_util.isObjectEmpty(wzrk_error)) { - dataObject['wzrk_error'] = wzrk_error; - wzrk_error = {}; - } - - dataObject['id'] = accountId; - - //Global cookie - if (wiz.isValueValid(gcookie)) { - dataObject['g'] = gcookie; - } - - var obj = wiz.getSessionCookieObject(); - - dataObject['s'] = obj['s']; //Session cookie - dataObject['pg'] = (typeof obj['p'] == STRING_CONSTANTS.UNDEFINED) ? 1 : obj['p']; //Page count - - return dataObject; - }; - - - wiz.getSessionCookieObject = function () { - var scookieStr = wiz.readCookie(SCOOKIE_NAME); - var obj = {}; - - if (scookieStr != null) { - // converting back single quotes to double for JSON parsing - http://www.iandevlin.com/blog/2012/04/html5/cookies-json-localstorage-and-opera - scookieStr = scookieStr.replace(singleQuoteRegex, "\""); - - obj = JSON.parse(scookieStr); - if (!wzrk_util.isObject(obj)) { - obj = {}; - } else { - if (typeof obj['t'] != STRING_CONSTANTS.UNDEFINED) { // check time elapsed since last request - var lasttime = obj['t']; - var now = wzrk_util.getNow(); - if ((now - lasttime) > (SCOOKIE_EXP_TIME_IN_SECS + 60)) // adding 60 seconds to compensate for in-journey requests - - //ideally the cookie should've died after SCOOKIE_EXP_TIME_IN_SECS but it's still around as we can read - //hence we shouldn't use it. - - obj = {}; - - } - } - } - scookieObj = obj; - return obj; - }; - - - wiz.setSessionCookieObject = function (obj) { - - var objStr = JSON.stringify(obj); - - wiz.createBroadCookie(SCOOKIE_NAME, objStr, SCOOKIE_EXP_TIME_IN_SECS, domain); - - }; - - wiz.isValueValid = function (value) { - if (value == null || value == STRING_CONSTANTS.UNDEFINED) { - return false; - } - return true; - }; - - wiz.getGuid = function () { - var guid = null; - if (wiz.isValueValid(gcookie)) { - return gcookie; - } - if (wzrk_util.isLocalStorageSupported()) { - var value = localStorage[STRING_CONSTANTS.GCOOKIE_NAME]; - if (wiz.isValueValid(value)) { - try { - guid = JSON.parse(decodeURIComponent(value)); - } catch (e) { - wc.d("Cannot parse Gcookie from localstorage - must be encoded " + value); - //assumming guids are of size 32. supporting both formats. - // guid can have encodedURIComponent or be without it. - // 1.56e4078ed15749928c042479ec2b4d47 - breaks on JSON.parse(decodeURIComponent()) - // 2.%2256e4078ed15749928c042479ec2b4d47%22 - if (value.length == 32) { - guid = value; - wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, value); - } else { - wc.e("Illegal guid " + value); - } - } - - // Persist to cookie storage if not present there. - if (wiz.isValueValid(guid)) { - wiz.createBroadCookie(STRING_CONSTANTS.GCOOKIE_NAME, guid, COOKIE_EXPIRY, domain); - } - } - } - if (!wiz.isValueValid(guid)) { - guid = wiz.readCookie(STRING_CONSTANTS.GCOOKIE_NAME); - if (wiz.isValueValid(guid) && (guid.indexOf('%') === 0 || - guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) { - guid = null; - } - if (wiz.isValueValid(guid)) { - wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, guid); - } - } - - return guid; - - }; - - wiz.g = function () { - - gcookie = wiz.getGuid(); - - - if (wzrk_util.isLocalStorageSupported()) { - currentSessionId = wiz.getMetaProp('cs'); - } - }; - - wiz.setMetaProp = function (key, value) { - if (wzrk_util.isLocalStorageSupported()) { - var wzrkMetaObj = wiz.readFromLSorCookie(STRING_CONSTANTS.META_COOKIE); - if (typeof wzrkMetaObj == STRING_CONSTANTS.UNDEFINED) { - wzrkMetaObj = {}; - } - if (value === undefined) { - delete wzrkMetaObj[key]; - } else { - wzrkMetaObj[key] = value; - } - wiz.saveToLSorCookie(STRING_CONSTANTS.META_COOKIE, wzrkMetaObj); - } - }; - - - wiz.getMetaProp = function (key) { - if (wzrk_util.isLocalStorageSupported()) { - var wzrkMetaObj = wiz.readFromLSorCookie(STRING_CONSTANTS.META_COOKIE); - if (typeof wzrkMetaObj != STRING_CONSTANTS.UNDEFINED) { - return wzrkMetaObj[key]; - } - } - }; - wiz.getAndClearMetaProp = function (key) { - var value = wiz.getMetaProp(key); - wiz.setMetaProp(key, undefined); - return value; - }; - - wiz.manageSession = function (session) { - //first time. check if current session id in localstorage is same - //if not same then prev = current and current = this new session - if (typeof currentSessionId === STRING_CONSTANTS.UNDEFINED || currentSessionId !== session) { - var currentSessionInLS = wiz.getMetaProp('cs'); - //if sessionId in meta is undefined - set current to both - if (typeof currentSessionInLS === STRING_CONSTANTS.UNDEFINED) { - wiz.setMetaProp('ps', session); - wiz.setMetaProp('cs', session); - wiz.setMetaProp('sc', 1); - } - //not same as session in local storage. new session - else if (currentSessionInLS !== session) { - wiz.setMetaProp('ps', currentSessionInLS); - wiz.setMetaProp('cs', session); - var sessionCount = wiz.getMetaProp('sc'); - if (typeof sessionCount === STRING_CONSTANTS.UNDEFINED) { - sessionCount = 0; - } - wiz.setMetaProp('sc', sessionCount + 1); - } - currentSessionId = session; - } - }; - - - // call back function used to store global and session ids for the user - //resume - this is used to signal that we can resume sending events to server - // was waiting for the server to reset the cookie. everything was getting written to cookie - wiz.s = function (global, session, resume, respNumber, optOutResponse) { - - if (typeof respNumber === "undefined") { - respNumber = 0; - } - - wiz.removeBackup(respNumber); - - if (respNumber > REQ_N) { - //request for some other user so ignore - return; - } - - if (!wiz.isValueValid(gcookie) || resume || typeof optOutResponse === 'boolean') { - if (!wiz.isValueValid(gcookie)) { - //clear useIP meta prop - wiz.getAndClearMetaProp(STRING_CONSTANTS.USEIP_KEY); - } - wc.d("Cookie was " + gcookie + " set to " + global); - gcookie = global; - // global cookie - - if (global) { - if (wzrk_util.isLocalStorageSupported()) { - if (LRU_CACHE == null) { - LRU_CACHE = new LRU_cache(LRU_CACHE_SIZE); - } - - var kId_from_LS = wiz.readFromLSorCookie( - STRING_CONSTANTS.KCOOKIE_NAME - ); - if (kId_from_LS != null && kId_from_LS["id"] && resume) { - var guidFromLRUCache = LRU_CACHE.cache[kId_from_LS["id"]]; - if (!guidFromLRUCache) { - LRU_CACHE.set(kId_from_LS["id"], global); - } - } - wiz.saveToLSorCookie( - STRING_CONSTANTS.GCOOKIE_NAME, - global - ); - - var lastK = LRU_CACHE.getSecondLastKEY(); - if(lastK !== -1) { - var lastGUID = LRU_CACHE.cache[lastK]; - unregisterTokenForGuid(lastGUID); - } - } - } - - wiz.createBroadCookie(STRING_CONSTANTS.GCOOKIE_NAME, global, COOKIE_EXPIRY, domain); - wiz.saveToLSorCookie(STRING_CONSTANTS.GCOOKIE_NAME, global); - } - - if (resume) { - blockRequeust = false; - wc.d("Resumed requests"); - } - if (wzrk_util.isLocalStorageSupported()) { - wiz.manageSession(session); - } - - // session cookie - var obj = wiz.getSessionCookieObject(); - - // for the race-condition where two responses come back with different session ids. don't write the older session id. - if (typeof obj["s"] == "undefined" || obj["s"] <= session) { - obj["s"] = session; - obj["t"] = wzrk_util.getNow(); // time of last response from server - wiz.setSessionCookieObject(obj); - } - - - if (resume && !processingBackup) { - wiz.processBackupEvents(); - } - - RESP_N = respNumber; - - }; - - wiz.processBackupEvents = function () { - - var backupMap = wiz.readFromLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME); - if (typeof backupMap == 'undefined' || backupMap == null) { - return; - } - processingBackup = true; - for (var idx in backupMap) { - if (backupMap.hasOwnProperty(idx)) { - var backupEvent = backupMap[idx]; - if (typeof backupEvent['fired'] == 'undefined') { - wc.d("Processing backup event : " + backupEvent['q']); - if (typeof backupEvent['q'] != 'undefined') { - wiz.fireRequest(backupEvent['q']); - } - backupEvent['fired'] = true; - } - } - } - wiz.saveToLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME, backupMap); - processingBackup = false; - - }; - - wiz.removeBackup = function (respNo) { - var backupMap = wiz.readFromLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME); - if (typeof backupMap != 'undefined' && backupMap != null && typeof backupMap[respNo] != 'undefined') { - wc.d("del event: " + respNo + " data->" + backupMap[respNo]['q']); - delete backupMap[respNo]; - wiz.saveToLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME, backupMap); - } - }; - - wiz.backUpEvent = function (data, reqNo) { - var backupArr = wiz.readFromLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME); - if (typeof backupArr == 'undefined') { - backupArr = {}; - } - backupArr[reqNo] = {'q': data}; - wiz.saveToLSorCookie(STRING_CONSTANTS.LCOOKIE_NAME, backupArr); - wc.d("stored in " + STRING_CONSTANTS.LCOOKIE_NAME + " reqNo : " + reqNo + "-> " + data); - - }; - - // sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com" - wiz.createBroadCookie = function (name, value, seconds, domain) { - - - //To update an existing "broad domain" cookie, we need to know what domain it was actually set on. - //since a retrieved cookie never tells which domain it was set on, we need to set another test cookie - //to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain - //for updating the actual cookie. - - - if (domain) { - if (typeof broadDomain == STRING_CONSTANTS.UNDEFINED) { // if we don't know the broadDomain yet, then find out - var domainParts = domain.split("."); - var testBroadDomain = ""; - for (var idx = domainParts.length - 1; idx >= 0; idx--) { - testBroadDomain = "." + domainParts[idx] + testBroadDomain; - - // only needed if the cookie already exists and needs to be updated. See note above. - if (wiz.readCookie(name)) { - - // no guarantee that browser will delete cookie, hence create short lived cookies - var testCookieName = "test_" + name + idx; - wiz.createCookie(testCookieName, value, 10, testBroadDomain); // self-destruct after 10 seconds - if (!wiz.readCookie(testCookieName)) { // if test cookie not set, then the actual cookie wouldn't have been set on this domain either. - continue; - } else { // else if cookie set, then delete the test and the original cookie - wiz.deleteCookie(testCookieName, testBroadDomain); - } - } - - wiz.createCookie(name, value, seconds, testBroadDomain); - var tempCookie = wiz.readCookie(name); - if (tempCookie == value) { - broadDomain = testBroadDomain; - //wc.d("Was able to retrieve cookie on: " + testBroadDomain + "->" + name + "=" + tempCookie); - break; - } - } - } else { - wiz.createCookie(name, value, seconds, broadDomain); - } - } else { - wiz.createCookie(name, value, seconds, domain); - } - }; - - //read - cookie get-set: http://www.quirksmode.org/js/cookies.html - - wiz.createCookie = function (name, value, seconds, domain) { - var expires = ""; - var domainStr = ""; - if (seconds) { - var date = new Date(); - date.setTime(date.getTime() + (seconds * 1000)); - - expires = "; expires=" + date.toGMTString(); - } - - if (domain) { - domainStr = "; domain=" + domain; - } - - value = encodeURIComponent(value); - - document.cookie = name + "=" + value + expires + domainStr + "; path=/"; - }; - - wiz.readCookie = function readCookie(name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for (var idx = 0; idx < ca.length; idx++) { - var c = ca[idx]; - while (c.charAt(0) == ' ') { - c = c.substring(1, c.length); - } - if (c.indexOf(nameEQ) == 0) { - return decodeURIComponent(c.substring(nameEQ.length, c.length)); - } - } - return null; - }; - - wiz.deleteCookie = function (name, domain) { - var cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; - - if (domain) { - cookieStr = cookieStr + " domain=" + domain + "; path=/"; - } - - document.cookie = cookieStr; - }; - - - wiz.addToURL = function (url, k, v) { - return url + "&" + k + "=" + encodeURIComponent(v); - }; - - var MAX_TRIES = 50; - - var fireRequest = function (url, tries, skipARP, sendOULFlag) { - if (dropRequestDueToOptOut()) { - wc.d("req dropped due to optout cookie: " + gcookie); - return; - } - if ( - !wiz.isValueValid(gcookie) && - RESP_N < REQ_N - 1 && - tries < MAX_TRIES - ) { - setTimeout(function () { - fireRequest(url, tries + 1, skipARP, sendOULFlag); - }, 50); - return; - } - - if(!sendOULFlag) { - if (wiz.isValueValid(gcookie)) { - //add cookie to url - url = wiz.addToURL(url, "gc", gcookie); - } - url = wiz.addARPToRequest(url, skipARP); - } - // url = addUseIPToRequest(url); - url = wiz.addToURL(url, "r", new Date().getTime()); // add epoch to beat caching of the URL - if (wizrocket.hasOwnProperty("plugin")) { - //used to add plugin name in request parameter - var plugin = wizrocket["plugin"]; - url = wiz.addToURL(url, "ct_pl", plugin); - } - if (url.indexOf("chrome-extension:") != -1) { - url = url.replace("chrome-extension:", "https:"); - } - var s = doc.createElement("script"); - s.setAttribute("type", "text/javascript"); - s.setAttribute("src", url); - s.setAttribute("rel", "nofollow"); - s.async = true; - - doc.getElementsByTagName("head")[0].appendChild(s); - wc.d("req snt -> url: " + url); - }; - - wiz.fireRequest = function (url, skipARP, sendOULFlag) { - fireRequest(url, 1, skipARP, sendOULFlag); - }; - - wiz.closeIframe = function (campaignId, divIdIgnored) { - if (typeof campaignId != STRING_CONSTANTS.UNDEFINED && campaignId != '-1') { - if (wzrk_util.isLocalStorageSupported()) { - var campaignObj = wzrk_util.getCampaignObject(); - - var sessionCampaignObj = campaignObj[currentSessionId]; - if (typeof sessionCampaignObj == STRING_CONSTANTS.UNDEFINED) { - sessionCampaignObj = {}; - campaignObj[currentSessionId] = sessionCampaignObj; - } - sessionCampaignObj[campaignId] = 'dnd'; - wzrk_util.saveCampaignObject(campaignObj); - } - } - if (typeof campaignDivMap != STRING_CONSTANTS.UNDEFINED) { - var divId = campaignDivMap[campaignId]; - if (typeof divId != STRING_CONSTANTS.UNDEFINED) { - document.getElementById(divId).style.display = "none"; - if (divId == 'intentPreview') { - if (document.getElementById('intentOpacityDiv') != null) { - document.getElementById('intentOpacityDiv').style.display = "none"; - } - } - } - } - - - }; - - // helper variable to handle race condition and check when notifications were called - var notifApi = {}; - notifApi.notifEnabledFromApi = false; - - /** - * Function is exposed to customer; called as needed after specific events to set up push notifications - * @param displayArgs array: [titleText, bodyText, okButtonText, rejectButtonText] - */ - wiz.setUpWebPush = function (displayArgs) { - if (webPushEnabled && displayArgs.length > 0) { - wiz.handleNotificationRegistration(displayArgs); - } else if (typeof webPushEnabled === STRING_CONSTANTS.UNDEFINED && displayArgs.length > 0) { - notifApi.notifEnabledFromApi = true; - notifApi.displayArgs = displayArgs.slice(); - } else if (webPushEnabled === false && displayArgs.length > 0) { - wc.e('Make sure push notifications are fully enabled and integrated'); - } - - }; - - wiz.setApplicationServerKey = function(applicationServerKey) { - fcmPublicKey = applicationServerKey; - } - - wiz.handleNotificationRegistration = function (displayArgs) { - - // make sure everything is specified - var titleText; - var bodyText; - var okButtonText; - var rejectButtonText; - var okButtonColor; - var skipDialog; - var askAgainTimeInSeconds; - var okCallback; - var rejectCallback; - var subscriptionCallback; - var hidePoweredByCT; - var serviceWorkerPath; - var httpsPopupPath; - var httpsIframePath; - var apnsWebPushId; - var apnsWebPushServiceUrl; - - if (displayArgs.length === 1) { - if (wzrk_util.isObject(displayArgs[0])) { - var notifObj = displayArgs[0]; - titleText = notifObj["titleText"]; - bodyText = notifObj["bodyText"]; - okButtonText = notifObj["okButtonText"]; - rejectButtonText = notifObj["rejectButtonText"]; - okButtonColor = notifObj["okButtonColor"]; - skipDialog = notifObj["skipDialog"]; - askAgainTimeInSeconds = notifObj["askAgainTimeInSeconds"]; - okCallback = notifObj["okCallback"]; - rejectCallback = notifObj["rejectCallback"]; - subscriptionCallback = notifObj["subscriptionCallback"]; - hidePoweredByCT = notifObj["hidePoweredByCT"]; - serviceWorkerPath = notifObj["serviceWorkerPath"]; - httpsPopupPath = notifObj["httpsPopupPath"]; - httpsIframePath = notifObj["httpsIframePath"]; - apnsWebPushId = notifObj["apnsWebPushId"]; - apnsWebPushServiceUrl = notifObj["apnsWebPushServiceUrl"]; - } - } else { - titleText = displayArgs[0]; - bodyText = displayArgs[1]; - okButtonText = displayArgs[2]; - rejectButtonText = displayArgs[3]; - okButtonColor = displayArgs[4]; - skipDialog = displayArgs[5]; - askAgainTimeInSeconds = displayArgs[6] - } - - if (typeof skipDialog === "undefined") { - skipDialog = false; - } - - if (typeof hidePoweredByCT === "undefined") { - hidePoweredByCT = false; - } - - if (typeof serviceWorkerPath === "undefined") { - serviceWorkerPath = '/clevertap_sw.js'; - } - - // ensure that the browser supports notifications - if (typeof navigator["serviceWorker"] === "undefined") { - return; - } - - // var isHTTP = location.protocol === 'http:' && typeof httpsPopupPath !== "undefined" && - // typeof httpsIframePath !== "undefined"; - - var isHTTP = typeof httpsPopupPath !== "undefined" && typeof httpsIframePath !== "undefined"; - - // make sure the site is on https for chrome notifications - if (location.protocol !== 'https:' && document.location.hostname !== 'localhost' && !isHTTP) { - wc.e("Make sure you are https or localhost to register for notifications"); - return; - } - - // right now, we only support Chrome V50 & higher & Firefox - if (navigator.userAgent.indexOf('Chrome') !== -1) { - chromeAgent = navigator.userAgent.match(/Chrome\/(\d+)/); - if (typeof chromeAgent === STRING_CONSTANTS.UNDEFINED || parseInt(chromeAgent[1], 10) < 50) - return; - }else if(navigator.userAgent.indexOf('Firefox') !== -1){ - firefoxAgent = navigator.userAgent.match(/Firefox\/(\d+)/); - if(typeof firefoxAgent === STRING_CONSTANTS.UNDEFINED || parseInt(firefoxAgent[1], 10) < 50) - return; - }else if(navigator.userAgent.indexOf('Safari') !== -1){ - safariAgent = navigator.userAgent.match(/Safari\/(\d+)/); - if(typeof safariAgent === STRING_CONSTANTS.UNDEFINED || parseInt(safariAgent[1], 10) < 50) - return; - } else { - return; - } - - // we check for the cookie in setUpChromeNotifications(); the tokens may have changed - - if (!isHTTP) { - if (typeof Notification === STRING_CONSTANTS.UNDEFINED) { - return; - } - // handle migrations from other services -> chrome notifications may have already been asked for before - if (Notification.permission === 'granted') { - // skip the dialog and register - wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); - return; - } else if (Notification.permission === 'denied') { - // we've lost this profile :'( - return; - } - - if (skipDialog) { - wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); - return; - } - } - - // make sure the right parameters are passed - if (!titleText || !bodyText || !okButtonText || !rejectButtonText) { - wc.e('Missing input parameters; please specify title, body, ok button and cancel button text'); - return; - } - - // make sure okButtonColor is formatted properly - if (typeof okButtonColor === STRING_CONSTANTS.UNDEFINED || !okButtonColor.match(/^#[a-f\d]{6}$/i)) { - okButtonColor = "#f28046"; // default color for positive button - } - - // make sure the user isn't asked for notifications more than askAgainTimeInSeconds - var now = new Date().getTime() / 1000; - if (typeof (wiz.getMetaProp('notif_last_time')) === STRING_CONSTANTS.UNDEFINED) { - wiz.setMetaProp('notif_last_time', now); - } else { - if (typeof askAgainTimeInSeconds === "undefined") { - // 7 days by default - askAgainTimeInSeconds = 7 * 24 * 60 * 60; - } - - if (now - wiz.getMetaProp('notif_last_time') < askAgainTimeInSeconds) { - return; - } else { - // continue asking - wiz.setMetaProp('notif_last_time', now); - } - } - - if (isHTTP) { - //add the https iframe - var httpsIframe = document.createElement('iframe'); - httpsIframe.setAttribute('style', 'display:none;'); - httpsIframe.setAttribute('src', httpsIframePath); - document.body.appendChild(httpsIframe); - window.addEventListener("message", function (event) { - if (typeof event['data'] !== "undefined") { - try { - var obj = JSON.parse(event['data']); - } catch (e) { - //not a call from our iframe - return; - } - if (typeof obj['state'] !== "undefined") { - if (obj['from'] === "ct" && obj['state'] === "not") { - wiz.addWizAlertJS().onload = function () { - // create our wizrocket popup - wzrkPermissionPopup['wizAlert']({ - 'title': titleText, - 'body': bodyText, - 'confirmButtonText': okButtonText, - 'confirmButtonColor': okButtonColor, - 'rejectButtonText': rejectButtonText, - 'hidePoweredByCT': hidePoweredByCT - }, function (enabled) { // callback function - if (enabled) { - // the user accepted on the dialog box - if (typeof okCallback !== "undefined" && typeof okCallback === "function") { - okCallback(); - } - //redirect to popup.html - window.open(httpsPopupPath); - } else { - if (typeof rejectCallback !== "undefined" && typeof rejectCallback === "function") { - rejectCallback(); - } - } - wiz.removeWizAlertJS(); - }); - } - } - } - } - // console.log(event.origin); - }, false); - } else { - wiz.addWizAlertJS().onload = function () { - // create our wizrocket popup - wzrkPermissionPopup['wizAlert']({ - 'title': titleText, - 'body': bodyText, - 'confirmButtonText': okButtonText, - 'confirmButtonColor': okButtonColor, - 'rejectButtonText': rejectButtonText, - 'hidePoweredByCT': hidePoweredByCT - }, function (enabled) { // callback function - if (enabled) { - // the user accepted on the dialog box - if (typeof okCallback !== "undefined" && typeof okCallback === "function") { - okCallback(); - } - wiz.setUpWebPushNotifications(subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); - } else { - if (typeof rejectCallback !== "undefined" && typeof rejectCallback === "function") { - rejectCallback(); - } - } - wiz.removeWizAlertJS(); - }); - } - } - }; - - wiz.tr = function (msg) { - - var doCampHouseKeeping = function (targetingMsgJson) { - - var campaignId = targetingMsgJson['wzrk_id'].split('_')[0]; - var today = wzrk_util.getToday(); - - if (wzrk_util.isLocalStorageSupported()) { - delete sessionStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; - var campObj = wzrk_util.getCampaignObject(); - - //global session limit. default is 1 - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] == STRING_CONSTANTS.UNDEFINED) { - targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] = 1; - } - var excludeFromFreqCaps = -1, campaignSessionLimit = -1, campaignDailyLimit = -1, - campaignTotalLimit = -1, - totalDailyLimit = -1, totalSessionLimit = -1; - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['efc'] != STRING_CONSTANTS.UNDEFINED) { - excludeFromFreqCaps = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['efc'], 10); - } - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['mdc'] != STRING_CONSTANTS.UNDEFINED) { - campaignSessionLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['mdc'], 10); - } - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tdc'] != STRING_CONSTANTS.UNDEFINED) { - campaignDailyLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tdc'], 10); - } - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tlc'] != STRING_CONSTANTS.UNDEFINED) { - campaignTotalLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['tlc'], 10); - } - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmp'] != STRING_CONSTANTS.UNDEFINED) { - totalDailyLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmp'], 10); - } - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'] != STRING_CONSTANTS.UNDEFINED) { - totalSessionLimit = parseInt(targetingMsgJson[STRING_CONSTANTS.DISPLAY]['wmc'], 10); - } - - - function incrCount(obj, campaignId, excludeFromFreqCaps) { - var currentCount = 0, totalCount = 0; - if (typeof obj[campaignId] != STRING_CONSTANTS.UNDEFINED) { - currentCount = obj[campaignId]; - } - currentCount++; - if (typeof obj['tc'] != STRING_CONSTANTS.UNDEFINED) { - totalCount = obj['tc']; - } - //if exclude from caps then dont add to total counts - if (excludeFromFreqCaps < 0) { - totalCount++; - } - - obj['tc'] = totalCount; - obj[campaignId] = currentCount; - } - - - //session level capping - var sessionObj = campObj[currentSessionId]; - if (typeof sessionObj != STRING_CONSTANTS.UNDEFINED) { - var campaignSessionCount = sessionObj[campaignId]; - var totalSessionCount = sessionObj['tc']; - //dnd - if (campaignSessionCount == 'dnd') { - return false; - } - - //session - if (totalSessionLimit > 0 && totalSessionCount >= totalSessionLimit && excludeFromFreqCaps < 0) { - return false; - } - //campaign session - if (campaignSessionLimit > 0 && campaignSessionCount >= campaignSessionLimit) { - return false; - } - } else { - sessionObj = {}; - campObj[currentSessionId] = sessionObj; - } - - //daily level capping - var dailyObj = campObj[today]; - if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED) { - var campaignDailyCount = dailyObj[campaignId]; - var totalDailyCount = dailyObj['tc']; - //daily - if (totalDailyLimit > 0 && totalDailyCount >= totalDailyLimit && excludeFromFreqCaps < 0) { - return false; - } - //campaign daily - if (campaignDailyLimit > 0 && campaignDailyCount >= campaignDailyLimit) { - return false; - } - } else { - dailyObj = {}; - campObj[today] = dailyObj; - } - - var globalObj = campObj[STRING_CONSTANTS.GLOBAL]; - if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) { - var campaignTotalCount = globalObj[campaignId]; - //campaign total - if (campaignTotalLimit > 0 && campaignTotalCount >= campaignTotalLimit) { - return false; - } - } else { - globalObj = {}; - campObj[STRING_CONSTANTS.GLOBAL] = globalObj; - } - - - } - //delay - if (typeof targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay'] > 0) { - var delay = targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay']; - targetingMsgJson[STRING_CONSTANTS.DISPLAY]['delay'] = 0; - setTimeout(wiz.tr, delay * 1000, msg); - return false; - } - - incrCount(sessionObj, campaignId, excludeFromFreqCaps); - incrCount(dailyObj, campaignId, excludeFromFreqCaps); - incrCount(globalObj, campaignId, excludeFromFreqCaps); - - //get ride of stale sessions and day entries - var newCampObj = {}; - newCampObj[currentSessionId] = sessionObj; - newCampObj[today] = dailyObj; - newCampObj[STRING_CONSTANTS.GLOBAL] = globalObj; - wzrk_util.saveCampaignObject(newCampObj); - - - }; - - var getCookieParams = function () { - if (!wiz.isValueValid(gcookie)) { - gcookie = wiz.getGuid(); - } - if (scookieObj == null) { - scookieObj = wiz.getSessionCookieObject(); - } - return '&t=wc&d=' + encodeURIComponent(LZS.compressToBase64(gcookie + '|' + scookieObj['p'] + '|' + scookieObj['s'])); - }; - - var setupClickEvent = function (onClick, targetingMsgJson, contentDiv, divId, isLegacy) { - if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { - var ctaElement; - if (isLegacy) { - ctaElement = contentDiv; - } else { - var jsCTAElements = contentDiv.getElementsByClassName('jsCT_CTA'); - if (typeof jsCTAElements != STRING_CONSTANTS.UNDEFINED && jsCTAElements.length == 1) { - ctaElement = jsCTAElements[0]; - } - } - var jsFunc = targetingMsgJson['display']['jsFunc']; - var isPreview = targetingMsgJson['display']['preview']; - if (typeof isPreview == STRING_CONSTANTS.UNDEFINED) { - onClick += getCookieParams(); - } - - if (typeof ctaElement != STRING_CONSTANTS.UNDEFINED) { - ctaElement.onclick = - function () { - //invoke js function call - if (typeof jsFunc != STRING_CONSTANTS.UNDEFINED) { - //track notification clicked event - if (typeof isPreview == STRING_CONSTANTS.UNDEFINED) { - wiz.fireRequest(onClick); - } - invokeExternalJs(jsFunc, targetingMsgJson); - //close iframe. using -1 for no campaignId - wiz.closeIframe('-1', divId); - return; - } - //pass on the gcookie|page|scookieId for capturing the click event - if (targetingMsgJson['display']['window'] == '1') { - window.open(onClick, '_blank'); - } else { - window.location = onClick; - } - } - } - } - }; - - var invokeExternalJs = function (jsFunc, targetingMsgJson) { - var func = window.parent[jsFunc]; - if (typeof func == "function") { - if (typeof targetingMsgJson['display']['kv'] !== STRING_CONSTANTS.UNDEFINED) { - func(targetingMsgJson['display']['kv']); - } else { - func(); - } - } - }; - - var setupClickUrl = function (onClick, targetingMsgJson, contentDiv, divId, isLegacy) { - incrementImpression(targetingMsgJson); - setupClickEvent(onClick, targetingMsgJson, contentDiv, divId, isLegacy); - }; - - var incrementImpression = function (targetingMsgJson) { - var data = {}; - data['type'] = "event"; - data['evtName'] = "Notification Viewed"; - data['evtData'] = {"wzrk_id": targetingMsgJson['wzrk_id']}; - processEvent(data); - }; - - var renderFooterNotification = function (targetingMsgJson) { - var campaignId = targetingMsgJson['wzrk_id'].split('_')[0]; - var displayObj = targetingMsgJson['display']; - - if (displayObj['layout'] == 1) { - return showExitIntent(undefined, targetingMsgJson); - } - if (doCampHouseKeeping(targetingMsgJson) == false) { - return; - } - - var divId = 'wizParDiv' + displayObj['layout']; - - if (document.getElementById(divId) != null) { - return; - } - campaignDivMap[campaignId] = divId; - var isBanner = displayObj['layout'] == 2; - var msgDiv = document.createElement('div'); - msgDiv.id = divId; - var viewHeight = window.innerHeight; - var viewWidth = window.innerWidth; - var legacy = false; - - - if (!isBanner) { - var marginBottom = viewHeight * 5 / 100; - var contentHeight = 10; - var right = viewWidth * 5 / 100; - var bottomPosition = contentHeight + marginBottom; - var width = viewWidth * 30 / 100 + 20; - var widthPerct = 'width:30%;'; - //for small devices - mobile phones - if ((/mobile/i.test(navigator.userAgent) || (/mini/i.test(navigator.userAgent))) && /iPad/i.test(navigator.userAgent) == false) { - width = viewWidth * 85 / 100 + 20; - right = viewWidth * 5 / 100; - bottomPosition = viewHeight * 5 / 100; - widthPerct = 'width:80%;'; - //medium devices - tablets - } else if ('ontouchstart' in window || (/tablet/i.test(navigator.userAgent))) { - width = viewWidth * 50 / 100 + 20; - right = viewWidth * 5 / 100; - bottomPosition = viewHeight * 5 / 100; - widthPerct = 'width:50%;'; - } - - //legacy footer notif - if (typeof displayObj['proto'] == STRING_CONSTANTS.UNDEFINED) { - legacy = true; - msgDiv.setAttribute('style', 'display:block;overflow:hidden; bottom:' + bottomPosition + 'px !important;width:' + width + 'px !important;right:' + right + 'px !important;position:fixed;z-index:2147483647;'); - } else { - msgDiv.setAttribute('style', widthPerct + displayObj['iFrameStyle']); - } - } else { - msgDiv.setAttribute('style', displayObj['iFrameStyle']); - } - document.body.appendChild(msgDiv); - var iframe = document.createElement('iframe'); - - var borderRadius = displayObj['br'] == false ? "0" : "8"; - - iframe['frameborder'] = '0px'; - iframe['marginheight'] = '0px'; - iframe['marginwidth'] = '0px'; - iframe['scrolling'] = 'no'; - iframe['id'] = 'wiz-iframe'; - var onClick = targetingMsgJson['display']['onClick']; - var pointerCss = ''; - if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { - pointerCss = 'cursor:pointer;'; - } - - var html; - //direct html - if (targetingMsgJson['msgContent']['type'] === 1) { - html = targetingMsgJson['msgContent']['html']; - html = html.replace('##campaignId##', campaignId); - } else { - var css = '' + - ''; - - var bgColor, textColor, btnBg, leftTd, btColor; - if (targetingMsgJson['display']['theme'] == 'dark') { - bgColor = "#2d2d2e"; - textColor = "#eaeaea"; - btnBg = '#353535'; - leftTd = '#353535'; - btColor = '#ffffff'; - } else { - bgColor = "#ffffff"; - textColor = "#000000"; - leftTd = '#f4f4f4'; - btnBg = '#a5a6a6'; - btColor = '#ffffff'; - } - var titleText = targetingMsgJson['msgContent']['title']; - var descriptionText = targetingMsgJson['msgContent']['description']; - var imageTd = ""; - if (typeof targetingMsgJson['msgContent']['imageUrl'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson['msgContent']['imageUrl'] != '') { - imageTd = "
" + - //""+ - "" + imageTd + "
" + - "
" + titleText + "
"; - var body = "
" + descriptionText + "
"; - html = css + title + body; - } - - - iframe.setAttribute('style', 'z-index: 2147483647; display:block; width: 100% !important; border:0px !important; border-color:none !important;'); - msgDiv.appendChild(iframe); - var ifrm = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument; - var doc = ifrm.document; - - doc.open(); - doc.write(html); - doc.close(); - - function adjustIFrameHeight() { - //adjust iframe and body height of html inside correctly - contentHeight = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv').scrollHeight; - if (displayObj['custom-editor'] !== true && !isBanner) { - contentHeight += 25; - } - document.getElementById("wiz-iframe").contentDocument.body.style.margin = "0px"; - document.getElementById("wiz-iframe").style.height = contentHeight + "px"; - } - - var ua = navigator.userAgent.toLowerCase(); - if (ua.indexOf('safari') !== -1) { - if (ua.indexOf('chrome') > -1) { - iframe.onload = function () { - adjustIFrameHeight(); - var contentDiv = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv'); - setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); - }; - } else { - var inDoc = iframe.contentDocument || iframe.contentWindow; - if (inDoc.document) inDoc = inDoc.document; - // safari iphone 7+ needs this. - adjustIFrameHeight(); - var _timer = setInterval(function () { - if (inDoc.readyState === 'complete') { - clearInterval(_timer); - //adjust iframe and body height of html inside correctly - adjustIFrameHeight(); - var contentDiv = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv'); - setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); - } - }, 10); - } - } else { - iframe.onload = function () { - //adjust iframe and body height of html inside correctly - adjustIFrameHeight(); - var contentDiv = document.getElementById("wiz-iframe").contentDocument.getElementById('contentDiv'); - setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); - }; - } - }; - - var _callBackCalled = false; - - var showFooterNotification = function (targetingMsgJson) { - - - var onClick = targetingMsgJson['display']['onClick']; - if (wizrocket.hasOwnProperty("notificationCallback") && - typeof wizrocket["notificationCallback"] !== "undefined" && - typeof wizrocket["notificationCallback"] === "function") { - var notificationCallback = wizrocket["notificationCallback"]; - if (!_callBackCalled) { - var inaObj = {}; - inaObj["msgContent"] = targetingMsgJson["msgContent"]; - inaObj["msgId"] = targetingMsgJson["wzrk_id"]; - if (typeof targetingMsgJson['display']['kv'] !== STRING_CONSTANTS.UNDEFINED) { - inaObj["kv"] = targetingMsgJson['display']['kv']; - } - wizrocket["raiseNotificationClicked"] = function () { - if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { - var jsFunc = targetingMsgJson['display']['jsFunc']; - onClick += getCookieParams(); - - //invoke js function call - if (typeof jsFunc != STRING_CONSTANTS.UNDEFINED) { - //track notification clicked event - wiz.fireRequest(onClick); - invokeExternalJs(jsFunc, targetingMsgJson); - return; - } - //pass on the gcookie|page|scookieId for capturing the click event - if (targetingMsgJson['display']['window'] == '1') { - window.open(onClick, '_blank'); - } else { - window.location = onClick; - } - } - }; - wizrocket["raiseNotificationViewed"] = function () { - incrementImpression(targetingMsgJson); - }; - notificationCallback(inaObj); - _callBackCalled = true; - } - } else { - renderFooterNotification(targetingMsgJson); - - } - }; - var exitintentObj; - var showExitIntent = function (event, targetObj) { - var targetingMsgJson; - if (typeof event != STRING_CONSTANTS.UNDEFINED && event['clientY'] > 0) { - return; - } - if (typeof targetObj == STRING_CONSTANTS.UNDEFINED) { - targetingMsgJson = exitintentObj; - } else { - targetingMsgJson = targetObj; - } - - if (document.getElementById("intentPreview") != null) { - return; - } - //dont show exit intent on tablet/mobile - only on desktop - if (typeof targetingMsgJson['display']['layout'] == STRING_CONSTANTS.UNDEFINED && - ((/mobile/i.test(navigator.userAgent)) || (/mini/i.test(navigator.userAgent)) || (/iPad/i.test(navigator.userAgent)) || - ('ontouchstart' in window) || (/tablet/i.test(navigator.userAgent)))) { - return; - } - - var campaignId = targetingMsgJson['wzrk_id'].split('_')[0]; - if (doCampHouseKeeping(targetingMsgJson) == false) { - return; - } - - campaignDivMap[campaignId] = 'intentPreview'; - var legacy = false; - var opacityDiv = document.createElement('div'); - opacityDiv.id = 'intentOpacityDiv'; - opacityDiv.setAttribute('style', 'position: fixed;top: 0;bottom: 0;left: 0;width: 100%;height: 100%;z-index: 2147483646;background: rgba(0,0,0,0.7);'); - document.body.appendChild(opacityDiv); - - var msgDiv = document.createElement('div'); - msgDiv.id = 'intentPreview'; - - if (typeof targetingMsgJson['display']['proto'] == STRING_CONSTANTS.UNDEFINED) { - legacy = true; - msgDiv.setAttribute('style', 'display:block;overflow:hidden;top:55% !important;left:50% !important;position:fixed;z-index:2147483647;width:600px !important;height:600px !important;margin:-300px 0 0 -300px !important;'); - } else { - msgDiv.setAttribute('style', targetingMsgJson['display']['iFrameStyle']); - } - document.body.appendChild(msgDiv); - var iframe = document.createElement('iframe'); - var borderRadius = targetingMsgJson['display']['br'] == false ? "0" : "8"; - iframe.frameborder = '0px'; - iframe.marginheight = '0px'; - iframe.marginwidth = '0px'; - iframe.scrolling = 'no'; - iframe.id = 'wiz-iframe-intent'; - var onClick = targetingMsgJson['display']['onClick']; - var pointerCss = ''; - if (onClick != '' && typeof onClick != STRING_CONSTANTS.UNDEFINED) { - pointerCss = 'cursor:pointer;'; - } - var html; - //direct html - if (targetingMsgJson['msgContent']['type'] == 1) { - html = targetingMsgJson['msgContent']['html']; - html = html.replace('##campaignId##', campaignId); - } else { - var css = '' + - ''; - - var bgColor, textColor, btnBg, btColor; - if (targetingMsgJson['display']['theme'] == 'dark') { - bgColor = "#2d2d2e"; - textColor = "#eaeaea"; - btnBg = '#353535'; - btColor = '#ffffff'; - } else { - bgColor = "#ffffff"; - textColor = "#000000"; - btnBg = '#a5a6a6'; - btColor = '#ffffff'; - } - var titleText = targetingMsgJson['msgContent']['title']; - var descriptionText = targetingMsgJson['msgContent']['description']; - var ctaText = ""; - if (typeof targetingMsgJson['msgContent']['ctaText'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson['msgContent']['ctaText'] != '') { - ctaText = ""; - } - - var imageTd = ""; - if (typeof targetingMsgJson['msgContent']['imageUrl'] != STRING_CONSTANTS.UNDEFINED && targetingMsgJson['msgContent']['imageUrl'] != '') { - imageTd = "
 + titleText +
"; - } - var onClickStr = "parent.$WZRK_WR.closeIframe(" + campaignId + ",'intentPreview');"; - var title = "
" + - "×" + - "
" + - "
" + titleText + "
"; - var body = "
" + descriptionText + "
" + imageTd + ctaText + - "
"; - html = css + title + body; - } - iframe.setAttribute('style', 'z-index: 2147483647; display:block; height: 100% !important; width: 100% !important;min-height:80px !important;border:0px !important; border-color:none !important;'); - msgDiv.appendChild(iframe); - var ifrm = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument; - var doc = ifrm.document; - - doc.open(); - doc.write(html); - doc.close(); - - var contentDiv = document.getElementById("wiz-iframe-intent").contentDocument.getElementById('contentDiv'); - setupClickUrl(onClick, targetingMsgJson, contentDiv, 'intentPreview', legacy); - - - }; - - - if (!document.body) { - if (wiz_counter < 6) { - wiz_counter++; - setTimeout(wiz.tr, 1000, msg); - } - return; - } - if (typeof msg['inapp_notifs'] != STRING_CONSTANTS.UNDEFINED) { - for (var index = 0; index < msg['inapp_notifs'].length; index++) { - var target_notif = msg['inapp_notifs'][index]; - if (typeof target_notif['display']['wtarget_type'] == STRING_CONSTANTS.UNDEFINED || target_notif['display']['wtarget_type'] == 0) { - showFooterNotification(target_notif); - } else if (target_notif['display']['wtarget_type'] == 1) { // if display['wtarget_type']==1 then exit intent - exitintentObj = target_notif; - window.document.body.onmouseleave = showExitIntent; - } - - } - } - - var mergeEventMap = function (newEvtMap) { - if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { - globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE); - if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) { - globalEventsMap = newEvtMap; - return; - } - } - for (var key in newEvtMap) { - if (newEvtMap.hasOwnProperty(key)) { - var oldEvtObj = globalEventsMap[key]; - var newEvtObj = newEvtMap[key]; - if (typeof globalEventsMap[key] != STRING_CONSTANTS.UNDEFINED) { - if (typeof newEvtObj[0] != STRING_CONSTANTS.UNDEFINED && newEvtObj[0] > oldEvtObj[0]) { - globalEventsMap[key] = newEvtObj; - } - } else { - globalEventsMap[key] = newEvtObj; - } - } - } - }; - - - if (wzrk_util.isLocalStorageSupported()) { - try { - if (typeof msg['evpr'] != STRING_CONSTANTS.UNDEFINED) { - var eventsMap = msg['evpr']['events']; - var profileMap = msg['evpr']['profile']; - var syncExpiry = msg['evpr']['expires_in']; - var now = wzrk_util.getNow(); - wiz.setMetaProp('lsTime', now); - wiz.setMetaProp('exTs', syncExpiry); - mergeEventMap(eventsMap); - wiz.saveToLSorCookie(STRING_CONSTANTS.EV_COOKIE, globalEventsMap); - if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) { - wiz.addToLocalProfileMap(profileMap, true); - } else { - wiz.addToLocalProfileMap(profileMap, false); - } - } - if (typeof msg['arp'] != STRING_CONSTANTS.UNDEFINED) { - wiz.arp(msg['arp']); - } - if (typeof msg['inapp_stale'] != STRING_CONSTANTS.UNDEFINED) { - var campObj = wzrk_util.getCampaignObject(); - var globalObj = campObj['global']; - if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) { - for (var idx in msg['inapp_stale']) { - if (msg['inapp_stale'].hasOwnProperty(idx)) { - delete globalObj[msg['inapp_stale'][idx]]; - } - } - } - wzrk_util.saveCampaignObject(campObj); - - } - } catch (e) { - wc.e("Unable to persist evrp/arp: " + e); - } - } - }; - - //link - actual link, type could be - "ctr" or "view" - wiz.getWrappedLink = function (link, targetId, type) { - - var data = {}; - data['sendTo'] = link; - data['targetId'] = targetId; - data['epoch'] = wzrk_util.getNow(); - - if (type != null) { - data['type'] = type; - } else { - data['type'] = 'view'; - } - - data = wiz.addSystemDataToObject(data, undefined); - return wiz.addToURL(recorderURL, "d", wiz.compressData(JSON.stringify(data))); - - }; - - - wiz.getMessageTemplate = function () { - var body = ""; - body = body + ''; - body = body + '
'; - return body; - }; - - wiz.getMessageHeadTemplate = function () { - var head = ''; - head = head + ''; - head = head + ''; - head = head + ''; - head = head + ''; - head = head + ""; - return head; - - }; - - - wiz.isChargedEventStructureValid = function (chargedObj) { - if (wzrk_util.isObject(chargedObj)) { - for (var key in chargedObj) { - if (chargedObj.hasOwnProperty(key)) { - - - if (key == "Items") { - if (!wzrk_util.isArray(chargedObj[key])) { - return false; - } - - if (chargedObj[key].length > 16) { - wiz.reportError(522, "Charged Items exceed 16 limit. Actual count: " + chargedObj[key].length + ". Additional items will be dropped."); - } - - for (var itemKey in chargedObj[key]) { - if (chargedObj[key].hasOwnProperty(itemKey)) { // since default array implementation could be overridden - e.g. Teabox site - if (!wzrk_util.isObject(chargedObj[key][itemKey]) || !wiz.isEventStructureFlat(chargedObj[key][itemKey])) { - return false; - } - } - } - } else { //Items - if (wzrk_util.isObject(chargedObj[key]) || wzrk_util.isArray(chargedObj[key])) { - return false; - } else if (wzrk_util.isDateObject(chargedObj[key])) { - chargedObj[key] = wzrk_util.convertToWZRKDate(chargedObj[key]); - } - - } // if key == Items - } - } //for.. - //save charged Id - if (wzrk_util.isString(chargedObj[STRING_CONSTANTS.CHARGED_ID]) || wzrk_util.isNumber(chargedObj[STRING_CONSTANTS.CHARGED_ID])) { - //casting chargeedId to string - var chargedId = chargedObj[STRING_CONSTANTS.CHARGED_ID] + ""; - if (typeof globalChargedId == STRING_CONSTANTS.UNDEFINED) { - globalChargedId = wiz.readFromLSorCookie(STRING_CONSTANTS.CHARGEDID_COOKIE_NAME); - } - if (typeof globalChargedId != STRING_CONSTANTS.UNDEFINED && globalChargedId.trim() === chargedId.trim()) { - //drop event- duplicate charged id - wc.e("Duplicate Charged Id - Dropped" + chargedObj); - return false; - } - globalChargedId = chargedId; - wiz.saveToLSorCookie(STRING_CONSTANTS.CHARGEDID_COOKIE_NAME, chargedId); - } - return true; - } // if object (chargedObject) - return false; - }; - - - //events can't have any nested structure or arrays - wiz.isEventStructureFlat = function (eventObj) { - if (wzrk_util.isObject(eventObj)) { - for (var key in eventObj) { - if (eventObj.hasOwnProperty(key)) { - if (wzrk_util.isObject(eventObj[key]) || wzrk_util.isArray(eventObj[key])) { - return false; - } else if (wzrk_util.isDateObject(eventObj[key])) { - eventObj[key] = wzrk_util.convertToWZRKDate(eventObj[key]); - } - } - } - return true; - } - return false; - - }; - - wiz.isProfileValid = function (profileObj) { - - if (wzrk_util.isObject(profileObj)) { - for (var profileKey in profileObj) { - if (profileObj.hasOwnProperty(profileKey)) { - var valid = true; - var profileVal = profileObj[profileKey]; - - if (typeof profileVal == STRING_CONSTANTS.UNDEFINED) { - delete profileObj[profileKey]; - continue; - } - if (profileKey == 'Gender' && !profileVal.match(/^M$|^F$/)) { - valid = false; - wc.e(wzrk_msg['gender-error']); - } - - if (profileKey == 'Employed' && !profileVal.match(/^Y$|^N$/)) { - valid = false; - wc.e(wzrk_msg['employed-error']); - } - - if (profileKey == 'Married' && !profileVal.match(/^Y$|^N$/)) { - valid = false; - wc.e(wzrk_msg['married-error']); - } - - if (profileKey == 'Education' && !profileVal.match(/^School$|^College$|^Graduate$/)) { - valid = false; - wc.e(wzrk_msg['education-error']); - } - - if (profileKey == 'Age' && typeof profileVal != STRING_CONSTANTS.UNDEFINED) { - if (wzrk_util.isConvertibleToNumber(profileVal)) { - profileObj['Age'] = +profileVal; - } else { - valid = false; - wc.e(wzrk_msg['age-error']); - } - } - - // dob will come in like this - $dt_19470815 or dateObject - if (profileKey == 'DOB') { - if (((!(/^\$D_/).test(profileVal) || (profileVal + "").length != 11)) && !wzrk_util.isDateObject(profileVal)) { - valid = false; - wc.e(wzrk_msg['dob-error']); - } - - if (wzrk_util.isDateObject(profileVal)) { - profileObj[profileKey] = wzrk_util.convertToWZRKDate(profileVal); - } - } else if (wzrk_util.isDateObject(profileVal)) { - profileObj[profileKey] = wzrk_util.convertToWZRKDate(profileVal); - } - - if (profileKey == 'Phone' && !wzrk_util.isObjectEmpty(profileVal)) { - if (profileVal.length > 8 && (profileVal.charAt(0) == '+')) { // valid phone number - profileVal = profileVal.substring(1, profileVal.length); - if (wzrk_util.isConvertibleToNumber(profileVal)) { - profileObj['Phone'] = +profileVal; - } else { - valid = false; - wc.e(wzrk_msg['phone-format-error'] + ". Removed."); - } - } else { - valid = false; - wc.e(wzrk_msg['phone-format-error'] + ". Removed."); - } - } - - - if (!valid) { - delete profileObj[profileKey]; - } - } - } - - } - - return valid; - }; //isProfileValid - - wiz.setDate = function (dt) { - return wzrk_util.setDate(dt); - }; - - wiz.setEnum = function (enumVal) { - if (wzrk_util.isString(enumVal) || wzrk_util.isNumber(enumVal)) { - return "$E_" + enumVal; - } - wc.e(wzrk_msg['enum-format-error']); - }; - - // list of functions that the closure compiler shouldn't rename - // https://developers.google.com/closure/compiler/docs/api-tutorial3 - wiz['s'] = wiz.s; - wiz['is_onloadcalled'] = wiz.is_onloadcalled; - wiz['setDate'] = wiz.setDate; - wiz['enableWebPush'] = wiz.enableWebPush; // support for web push notifications - wiz['setEnum'] = wiz.setEnum; - wiz['tr'] = wiz.tr; - wiz['push'] = wiz.push; - wiz['closeIframe'] = wiz.closeIframe; - wiz['getEmail'] = wiz.getEmail; - wiz['unSubEmail'] = wiz.unSubEmail; - wiz['unsubEmailGroups'] = wiz.unsubEmailGroups; - wiz['changeSubscriptionGroups'] = wiz.changeSubscriptionGroups; - wiz['getSubscriptionGroups'] = wiz.getSubscriptionGroups; - wiz['setSubscriptionGroups'] = wiz.setSubscriptionGroups; - wiz['setUpdatedCategoryLong'] = wiz.setUpdatedCategoryLong; - wiz['subEmail'] = wiz.subEmail; - wiz['logout'] = wiz.logout; - wiz['clear'] = wiz.clear; - wizrocket['getCleverTapID'] = wiz.getCleverTapID; - - - // ---------- compression part ---------- - - var LZS = { - - _f: String.fromCharCode, - - getKeyStr: function () { - var key = ""; - var i = 0; - - for (i = 0; i <= 25; i++) { - key = key + String.fromCharCode(i + 65); - } - - for (i = 0; i <= 25; i++) { - key = key + String.fromCharCode(i + 97); - } - - for (var i = 0; i < 10; i++) { - key = key + i; - } - - return key + "+/="; - }, - - convertToFormattedHex: function (byte_arr) { - var hex_str = "", - i, - len, - tmp_hex; - - if (!wzrk_util.isArray(byte_arr)) { - return false; - } - - len = byte_arr.length; - - for (i = 0; i < len; ++i) { - if (byte_arr[i] < 0) { - byte_arr[i] = byte_arr[i] + 256; - } - if (byte_arr[i] === undefined) { - byte_arr[i] = 0; - } - tmp_hex = byte_arr[i].toString(16); - - // Add leading zero. - if (tmp_hex.length == 1) tmp_hex = "0" + tmp_hex; - - // beautification - needed if you're printing this in the console, else keep commented - // if ((i + 1) % 16 === 0) { - // tmp_hex += "\n"; - // } else { - // tmp_hex += " "; - // } - - hex_str += tmp_hex; - } - - return hex_str.trim(); - }, - - convertStringToHex: function (s) { - - var byte_arr = []; - for (var i = 0; i < s.length; i++) { - var value = s.charCodeAt(i); - byte_arr.push(value & 255); - byte_arr.push((value >> 8) & 255); - } - return LZS.convertToFormattedHex(byte_arr); - - }, - - compressToBase64: function (input) { - if (input == null) return ""; - var output = ""; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; - - input = LZS.compress(input); - - while (i < input.length * 2) { - - if (i % 2 == 0) { - chr1 = input.charCodeAt(i / 2) >> 8; - chr2 = input.charCodeAt(i / 2) & 255; - if (i / 2 + 1 < input.length) - chr3 = input.charCodeAt(i / 2 + 1) >> 8; - else - chr3 = NaN; - } else { - chr1 = input.charCodeAt((i - 1) / 2) & 255; - if ((i + 1) / 2 < input.length) { - chr2 = input.charCodeAt((i + 1) / 2) >> 8; - chr3 = input.charCodeAt((i + 1) / 2) & 255; - } else - chr2 = chr3 = NaN; - } - i += 3; - - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; - - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; - } - - output = output + - LZS._keyStr.charAt(enc1) + LZS._keyStr.charAt(enc2) + - LZS._keyStr.charAt(enc3) + LZS._keyStr.charAt(enc4); - - } - - return output; - }, - - - compress: function (uncompressed) { - if (uncompressed == null) return ""; - var i, value, - context_dictionary = {}, - context_dictionaryToCreate = {}, - context_c = "", - context_wc = "", - context_w = "", - context_enlargeIn = 2, // Compensate for the first entry which should not count - context_dictSize = 3, - context_numBits = 2, - context_data_string = "", - context_data_val = 0, - context_data_position = 0, - ii, - f = LZS._f; - - for (ii = 0; ii < uncompressed.length; ii += 1) { - context_c = uncompressed.charAt(ii); - if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) { - context_dictionary[context_c] = context_dictSize++; - context_dictionaryToCreate[context_c] = true; - } - - context_wc = context_w + context_c; - if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) { - context_w = context_wc; - } else { - if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) { - if (context_w.charCodeAt(0) < 256) { - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - } - value = context_w.charCodeAt(0); - for (i = 0; i < 8; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - } else { - value = 1; - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1) | value; - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = 0; - } - value = context_w.charCodeAt(0); - for (i = 0; i < 16; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - // Add wc to the dictionary. - context_dictionary[context_wc] = context_dictSize++; - context_w = String(context_c); - } - } - - // Output the code for w. - if (context_w !== "") { - if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) { - if (context_w.charCodeAt(0) < 256) { - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - } - value = context_w.charCodeAt(0); - for (i = 0; i < 8; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - } else { - value = 1; - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1) | value; - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = 0; - } - value = context_w.charCodeAt(0); - for (i = 0; i < 16; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - delete context_dictionaryToCreate[context_w]; - } else { - value = context_dictionary[context_w]; - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - - - } - context_enlargeIn--; - if (context_enlargeIn == 0) { - context_enlargeIn = Math.pow(2, context_numBits); - context_numBits++; - } - } - - // Mark the end of the stream - value = 2; - for (i = 0; i < context_numBits; i++) { - context_data_val = (context_data_val << 1) | (value & 1); - if (context_data_position == 15) { - context_data_position = 0; - context_data_string += f(context_data_val); - context_data_val = 0; - } else { - context_data_position++; - } - value = value >> 1; - } - - // Flush the last char - while (true) { - context_data_val = (context_data_val << 1); - if (context_data_position == 15) { - context_data_string += f(context_data_val); - break; - } else context_data_position++; - } - return context_data_string; - } - - }; - - LZS._keyStr = LZS.getKeyStr(); - - var wzrk_util = { - //expecting yyyymmdd format either as a number or a string - setDate: function (dt) { - if (wzrk_util.isDateValid(dt)) { - return "$D_" + dt; - } - wc.e(wzrk_msg['date-format-error']); - }, - - isDateObject: function (input) { - return typeof (input) === "object" && (input instanceof Date); - }, - - convertToWZRKDate: function (dateObj) { - return ("$D_" + Math.round(dateObj.getTime() / 1000)); - }, - - isDateValid: function (date) { - var matches = /^(\d{4})(\d{2})(\d{2})$/.exec(date); - if (matches == null) return false; - var d = matches[3]; - var m = matches[2] - 1; - var y = matches[1]; - var composedDate = new Date(y, m, d); - return composedDate.getDate() == d && - composedDate.getMonth() == m && - composedDate.getFullYear() == y; - }, - - isArray: function (input) { - return typeof (input) === "object" && (input instanceof Array); - }, - - isObject: function (input) { - return Object.prototype.toString.call(input) == "[object Object]"; - }, - - isObjectEmpty: function (obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) - return false; - } - return true; - }, - - isString: function (input) { - return (typeof input == 'string' || input instanceof String); - }, - - - // if yes, the convert using +number. - isConvertibleToNumber: function (n) { - return !isNaN(parseFloat(n)) && isFinite(n); - }, - - //from here - http://stackoverflow.com/a/1421988/2456615 - isNumber: function (n) { - return /^-?[\d.]+(?:e-?\d+)?$/.test(n) && typeof n == 'number'; - }, - - arrayContains: function (arr, obj) { - function contains(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) { - return true; - } - } - return false; - } - }, - - getURLParams: function (url) { - var urlParams = {}; - var idx = url.indexOf('?'); - - if (idx > 1) { - - var uri = url.substring(idx + 1); - - - var match, - pl = /\+/g, // Regex for replacing addition symbol with a space - search = /([^&=]+)=?([^&]*)/g, - decode = function (s) { - var replacement = s.replace(pl, " "); - try { - replacement = decodeURIComponent(replacement); - } catch (e) { - //eat - } - return replacement; - }; - - - while (match = search.exec(uri)) { - urlParams[decode(match[1])] = decode(match[2]); - } - - } - return urlParams; - }, - - getDomain: function (url) { - if (url == "") return ""; - var a = document.createElement('a'); - a.href = url; - return a.hostname; - }, - - - //keys can't be greater than 1024 chars, values can't be greater than 1024 chars - removeUnsupportedChars: function (o) { - if (typeof o == "object") { - for (var key in o) { - if (o.hasOwnProperty(key)) { - var sanitizedVal = wzrk_util.removeUnsupportedChars(o[key]); - var sanitizedKey = wzrk_util.isString(key) ? wzrk_util.sanitize(key, unsupportedKeyCharRegex) : key; - - if (wzrk_util.isString(key)) { - sanitizedKey = wzrk_util.sanitize(key, unsupportedKeyCharRegex); - if (sanitizedKey.length > 1024) { - sanitizedKey = sanitizedKey.substring(0, 1024); - $WZRK_WR.reportError(520, sanitizedKey + "... length exceeded 1024 chars. Trimmed."); - } - } else { - sanitizedKey = key; - } - delete o[key]; - o[sanitizedKey] = sanitizedVal; - } - } - } else { - var val; - - if (wzrk_util.isString(o)) { - val = wzrk_util.sanitize(o, unsupportedValueCharRegex); - if (val.length > 1024) { - val = val.substring(0, 1024); - $WZRK_WR.reportError(521, val + "... length exceeded 1024 chars. Trimmed."); - } - } else { - val = o; - } - return val; - } - return o; - }, - - sanitize: function (input, regex) { - return input.replace(regex, ''); - }, - - isLocalStorageSupported: function () { - try { - window.localStorage.setItem('wzrk_debug', '12345678'); - window.localStorage.removeItem('wzrk_debug'); - return 'localStorage' in window && window['localStorage'] !== null; - } catch (e) { - return false; - } - }, - - getCampaignObject: function () { - var campObj = {}; - if (wzrk_util.isLocalStorageSupported()) { - campObj = localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME]; - if (typeof campObj != STRING_CONSTANTS.UNDEFINED) { - campObj = JSON.parse(decodeURIComponent(campObj).replace(singleQuoteRegex, "\"")); - } else { - campObj = {}; - } - } - return campObj; - }, - - saveCampaignObject: function (campaignObj) { - if (wzrk_util.isLocalStorageSupported()) { - var campObj = JSON.stringify(campaignObj); - localStorage[STRING_CONSTANTS.CAMP_COOKIE_NAME] = encodeURIComponent(campObj); - } - }, - - - isPersonalizationActive: function () { - return (wzrk_util.isLocalStorageSupported() && wizrocket['enablePersonalization']) - }, - - getToday: function () { - var t = new Date(); - return t.getFullYear() + "" + t.getMonth() + "" + t.getDay(); - }, - getNow: function () { - return Math.floor(((new Date()).getTime()) / 1000); - } - - }; - - // leading spaces, dot, colon, dollar, single quote, double quote, backslash, trailing spaces - var unsupportedKeyCharRegex = new RegExp("^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$", "g"); - - // leading spaces, single quote, double quote, backslash, trailing spaces - var unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", "g"); - - //used to handle cookies in Opera mini - var doubleQuoteRegex = new RegExp("\"", "g"); - var singleQuoteRegex = new RegExp("\'", "g"); - - - var wzrk_msg = {}; - var wzrk_error_txt = "CleverTap error: "; - var data_not_sent_txt = "This property has been ignored."; - wzrk_msg['embed-error'] = wzrk_error_txt + "Incorrect embed script."; - wzrk_msg['event-error'] = wzrk_error_txt + "Event structure not valid. " + data_not_sent_txt; - wzrk_msg['gender-error'] = wzrk_error_txt + "Gender value should be either M or F. " + data_not_sent_txt; - wzrk_msg['employed-error'] = wzrk_error_txt + "Employed value should be either Y or N. " + data_not_sent_txt; - wzrk_msg['married-error'] = wzrk_error_txt + "Married value should be either Y or N. " + data_not_sent_txt; - wzrk_msg['education-error'] = wzrk_error_txt + "Education value should be either School, College or Graduate. " + data_not_sent_txt; - wzrk_msg['age-error'] = wzrk_error_txt + "Age value should be a number. " + data_not_sent_txt; - wzrk_msg['dob-error'] = wzrk_error_txt + "DOB value should be a Date Object"; - wzrk_msg['obj-arr-error'] = wzrk_error_txt + "Expecting Object array in profile"; - wzrk_msg['date-format-error'] = wzrk_error_txt + "setDate(number). number should be formatted as yyyymmdd"; - wzrk_msg['enum-format-error'] = wzrk_error_txt + "setEnum(value). value should be a string or a number"; - wzrk_msg['phone-format-error'] = wzrk_error_txt + "Phone number should be formatted as +[country code][number]"; - -} // function __wizrocket - -$WZRK_WR = new __wizrocket(); -$CLTP_WR = $WZRK_WR; -$WZRK_WR.init(); //this should always be the last in the JS file, as it needs all vars/functions to be defined to work. - - -/** - * @preserve Copyright WizRocket, Inc. (ver.@timestamp@) - * ____ _ _____ - * / ___| | _____ _____ _ _|_ _|_ _ _ __ - * | | | |/ _ \ \ / / _ \ '__|| |/ _` | '_ \ - * | |___| | __/\ V / __/ | | | (_| | |_) | - * \____|_|\___| \_/ \___|_| |_|\__,_| .__/ - * |_| - * - */ \ No newline at end of file diff --git a/clevertap_sw.js b/clevertap_sw.js deleted file mode 100644 index cf9164d6..00000000 --- a/clevertap_sw.js +++ /dev/null @@ -1 +0,0 @@ -importScripts('https://s3-eu-west-1.amazonaws.com/static.wizrocket.com/js/sw_webpush.js'); diff --git a/ct_logo.svg b/ct_logo.svg deleted file mode 100644 index 0f268698..00000000 --- a/ct_logo.svg +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/dialog.js b/dialog.js deleted file mode 100644 index ca2aa5cb..00000000 --- a/dialog.js +++ /dev/null @@ -1,189 +0,0 @@ -/** wizAlert(); - parameter: 1 object to specify title etc. - title, body, confirmButtonText, rejectButtonText, confirmButtonColor - function to yield to on click - -
-
-
-
Would you like to Set Up Push Notifications
-
We promise to only send you relevant content and give you great updates
-
-
Powered by
-
-
- - */ - -function getwzrkPermissionPopup(){ - var wzrkPermissionPopup = { - 'dialogCss': '' - - }; - -// dialog css is taken from the minified main.css - wzrkPermissionPopup.wzrkCreatePopDiv = function(hidePoweredByCT) { - - function createButton (id, text, cls) { - var btn = document.createElement("BUTTON"); - btn.id = id; - btn.setAttribute('class', cls); - var t = document.createTextNode(text); - btn.appendChild(t); - return btn; - } - - function createDiv(id, parent, cls, content) { - - var div = document.createElement('div'); - if(id !== undefined) { - div.id = id; - } - if(cls !== undefined){ - div.setAttribute('class', cls); - } - if(content !== undefined){ - div.innerHTML = content; - } - if(parent !== undefined){ - parent.appendChild(div); - } - return div; - - } - - // wrapper - var msgDiv = createDiv('wzrk_wrapper', undefined, undefined, wzrkPermissionPopup['dialogCss']); - - // overlay div - createDiv(undefined, msgDiv, 'wzrk-overlay wzrk-hidden',undefined); - - // alert wrapper - var msgAlert = createDiv(undefined, msgDiv, 'wzrk-alert wzrk-hidden',undefined); - - // alert title - createDiv(undefined, msgAlert, 'wzrk-alert-heading', 'Would you like to Set Up Push Notifications'); - - // alert body - createDiv(undefined, msgAlert, 'wzrk-alert-body', 'We promise to only send you relevant content and give you great updates'); - - // alert button - var buttonWrapper = createDiv(undefined, msgAlert, 'wzrk-button-container',undefined); - buttonWrapper.appendChild(createButton('wzrk-cancel', 'cancel', 'No thanks')); - buttonWrapper.appendChild(createButton('wzrk-confirm', 'confirm', 'Sign me Up!')); - - if(!hidePoweredByCT){ - // alert powered by - createDiv(undefined, msgAlert, 'wzrk-powered', 'Powered by '); - } - - return msgDiv; - - }; - - -// function to darken color for ok button text - wzrkPermissionPopup.colorLuminance = function(hex, lum) { - // validate hex string - hex = String(hex).replace(/[^0-9a-f]/gi, ''); - if (hex.length < 6) { - hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; - } - lum = lum || 0; - - // convert to decimal and change luminosity - var rgb = "#", c, i; - for (i = 0; i < 3; i++) { - c = parseInt(hex.substr(i*2,2), 16); - c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); - rgb += ("00"+c).substr(c.length); - } - - return rgb; - }; - - wzrkPermissionPopup.showElements = function() { - // set up animations on the parent div - var alertBox = document.getElementsByClassName('wzrk-alert')[0]; - var hiddenElems = document.getElementsByClassName('wzrk-hidden'); - alertBox.classList.add('wiz-show-animate'); - while (hiddenElems.length != 0) { - hiddenElems[0].classList.remove('wzrk-hidden'); - } - }; - - wzrkPermissionPopup.hideElements = function() { - var alertBox = document.getElementsByClassName('wzrk-alert')[0]; - var overlay = document.getElementsByClassName('wzrk-overlay')[0] - - alertBox.classList.remove('wiz-show-animate'); - alertBox.classList.add('wiz-hide-animate'); - overlay.classList.add('wzrk-hidden'); - - setTimeout(function() { - alertBox.classList.add('wzrk-hidden'); - // remove html - var wrapper = document.getElementById('wzrk_wrapper'); - wrapper.parentNode.removeChild(wrapper); - }, 100); - - }; - -// main function to call - wzrkPermissionPopup.wizAlert = function(displayOptions, callbackFunction) { - // inject our (hidden) html into the document - document.getElementsByTagName('body')[0].appendChild(wzrkPermissionPopup.wzrkCreatePopDiv(displayOptions['hidePoweredByCT'])); - // set up the heading text - var heading = document.getElementsByClassName('wzrk-alert-heading')[0]; - heading.innerHTML = displayOptions['title']; - - // set up the body text - var body = document.getElementsByClassName('wzrk-alert-body')[0]; - body.innerHTML = displayOptions['body']; - - // set up the text for the buttons - var confirmButton = document.getElementById('wzrk-confirm'); - confirmButton.innerHTML = displayOptions['confirmButtonText']; - - var rejectButton = document.getElementById('wzrk-cancel'); - rejectButton.innerHTML = displayOptions['rejectButtonText']; - - // add event listeners for the callbackfunction on the button - confirmButton.addEventListener('click', function() { - wzrkPermissionPopup.hideElements(); - // give the animation some time to complete - setTimeout(function() { - callbackFunction(true); - }, 100); - }); - - rejectButton.addEventListener('click', function() { - wzrkPermissionPopup.hideElements(); - // give time for the animation to complete - setTimeout(function() { - callbackFunction(false); - }, 100); - }); - - // set up the custom confirm button color - confirmButton.style.backgroundColor = displayOptions['confirmButtonColor']; - - confirmButton.onmouseover = function() { - confirmButton.style.backgroundColor = - wzrkPermissionPopup.colorLuminance(displayOptions['confirmButtonColor'], -0.04); - }; - - confirmButton.onmouseout = function() { - confirmButton.style.backgroundColor = displayOptions['confirmButtonColor'] || '#f28046'; - }; - - // finally display the popup - wzrkPermissionPopup.showElements(); - - }; - - return wzrkPermissionPopup; -} - -window['wzrkPermissionPopup'] = getwzrkPermissionPopup(); -window['wzrkPermissionPopup']['wizAlert'] = window['wzrkPermissionPopup'].wizAlert; \ No newline at end of file diff --git a/gtm_segment.html b/gtm_segment.html deleted file mode 100644 index 075ca9af..00000000 --- a/gtm_segment.html +++ /dev/null @@ -1,47 +0,0 @@ - \ No newline at end of file diff --git a/localforage.min.js b/localforage.min.js deleted file mode 100644 index ca08579f..00000000 --- a/localforage.min.js +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Created by ankit on 06/10/16. - */ - -!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.localforage=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g=43)}}).catch(function(){return!1})}function n(a){return"boolean"==typeof ga?ia.resolve(ga):m(a).then(function(a){return ga=a})}function o(a){var b=ha[a.name],c={};c.promise=new ia(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function p(a){var b=ha[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function q(a,b){return new ia(function(c,d){if(a.db){if(!b)return c(a.db);o(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=fa.open.apply(fa,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ja)}catch(c){if("ConstraintError"!==c.name)throw c;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result),p(a)}})}function r(a){return q(a,!1)}function s(a){return q(a,!0)}function t(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.versiona.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function u(a){return new ia(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function v(a){var b=l(atob(a.data));return i([b],{type:a.type})}function w(a){return a&&a.__local_forage_encoded_blob}function x(a){var b=this,c=b._initReady().then(function(){var a=ha[b._dbInfo.name];if(a&&a.dbReady)return a.dbReady});return k(c,a,a),c}function y(a){function b(){return ia.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ha||(ha={});var f=ha[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},ha[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=x);for(var g=[],h=0;h>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function I(a){var b,c=new Uint8Array(a),d="";for(b=0;b>2],d+=ma[(3&c[b])<<4|c[b+1]>>4],d+=ma[(15&c[b+1])<<2|c[b+2]>>6],d+=ma[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function J(a,b){var c="";if(a&&(c=Da.call(a)),a&&("[object ArrayBuffer]"===c||a.buffer&&"[object ArrayBuffer]"===Da.call(a.buffer))){var d,e=pa;a instanceof ArrayBuffer?(d=a,e+=ra):(d=a.buffer,"[object Int8Array]"===c?e+=ta:"[object Uint8Array]"===c?e+=ua:"[object Uint8ClampedArray]"===c?e+=va:"[object Int16Array]"===c?e+=wa:"[object Uint16Array]"===c?e+=ya:"[object Int32Array]"===c?e+=xa:"[object Uint32Array]"===c?e+=za:"[object Float32Array]"===c?e+=Aa:"[object Float64Array]"===c?e+=Ba:b(new Error("Failed to get type for BinaryArray"))),b(e+I(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=na+a.type+"~"+I(this.result);b(pa+sa+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(c){console.error("Couldn't convert value into a JSON string: ",a),b(null,c)}}function K(a){if(a.substring(0,qa)!==pa)return JSON.parse(a);var b,c=a.substring(Ca),d=a.substring(qa,Ca);if(d===sa&&oa.test(c)){var e=c.match(oa);b=e[1],c=c.substring(e[0].length)}var f=H(c);switch(d){case ra:return f;case sa:return i([f],{type:b});case ta:return new Int8Array(f);case ua:return new Uint8Array(f);case va:return new Uint8ClampedArray(f);case wa:return new Int16Array(f);case ya:return new Uint16Array(f);case xa:return new Int32Array(f);case za:return new Uint32Array(f);case Aa:return new Float32Array(f);case Ba:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function L(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ia(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(a){return d(a)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Ea,e}function M(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function N(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;h=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function W(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function X(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;h 60) { - i.event(E_DEL, 'scroll', i.scroll); - var url = targetURL; - i.fireRequest(i.addToURL(url, EVT, EVT_SCROLL)); - } - }; - - - - i.click = function () { - - if(clickCount < 3) { // send only up to 3 click events - clickCount++; - - setTimeout(function(){ - var url = targetURL; - i.fireRequest(i.addToURL(url, EVT, EVT_CLICK)); - }, 100); // wait 100ms before firing. Don't want to capture clicks leading to new pages. - - - } else { - i.event(E_DEL, 'mouseup', i.click); - } - - }; - - i.keypress = function () { - - if(keyPressCount < 3) { // send one only after 4 key presses - keyPressCount++; - } else { - i.event(E_DEL, 'keyup', i.keypress); - var url = targetURL; - i.fireRequest(i.addToURL(url, EVT, EVT_KEYPRESS)); - } - }; - - - i.is_onloadcalled = function() { - return (onloadcalled === 1); - }; - - i.pageloaded = function () { - onloadcalled=1; - - i.g(); // load cookies on pageload - var currLocation = encodeURIComponent(location.href); - var firePageLoadRequest = true; - - if(currLocation == pcookie) { // don't fire if cookie has curr url as value - firePageLoadRequest = false; - } - - var FIFTEEN_MINS_IN_SECS = 60 * 15 //seconds in minute * number of mins - i.createCookie(PCOOKIE_NAME, currLocation, FIFTEEN_MINS_IN_SECS); // self-destruct after 15 mins - - - if(firePageLoadRequest) { - - var deviceWidth = screen.width; - var deviceHeight = screen.height; - var pageLoadUrl = targetURL; - - pageLoadUrl = i.addToURL(pageLoadUrl, "dw", deviceWidth); - pageLoadUrl = i.addToURL(pageLoadUrl, "dh", deviceHeight); - pageLoadUrl = i.addToURL(pageLoadUrl, EVT, EVT_PAGE); - - if (doc.referrer) { - var encodedReferrer = encodeURIComponent(doc.referrer); - pageLoadUrl = i.addToURL(pageLoadUrl, "ref", encodedReferrer); - } - - - var catArray = (typeof _wrc != 'undefined')? _wrc: []; // _wrc is a cat/sub-cat array that is in the parent page - - if(catArray && catArray.length >= 1) { - - var catKVStr = i.encodeKVPairs(catArray); - var encodedCatKVStr = encodeURIComponent(catKVStr); // make it fit to pass in the URL - pageLoadUrl = i.addToURL(pageLoadUrl, "kv", encodedCatKVStr); - } - - i.fireRequest(pageLoadUrl); - - } // if(firePageLoadRequest) - - if(firePageLoadRequest) { - var body = document.body; - var docElement = document.documentElement; - //get document height per - http://stackoverflow.com/questions/1145850/get-height-of-entire-document-with-javascript - var docHeight = Math.max(body.scrollHeight, body.offsetHeight, docElement.clientHeight, docElement.scrollHeight, docElement.offsetHeight); - var deviceHeight = screen.height; - - // if screen height is 60% of document height then fire scroll event - // basically if 60% of doc is already visible then user won't need to scroll, hence we'll fire scroll event - - var heightPercent = (deviceHeight/docHeight)*100; - - if(heightPercent >=60) { - setTimeout(function(){ - var url = targetURL; - i.fireRequest(i.addToURL(url, EVT, EVT_SCROLL)); - }, 2000); // wait 2 seconds before firing. This is to eliminate noise. - - } else { - i.event(E_ADD, 'scroll', i.scroll); // if long doc, then add scroll listener - } - } - - i.event(E_ADD, 'keyup', i.keypress); - i.event(E_ADD, 'mouseup', i.click); - }; - - i.sendSiteEvent = function(siteEventName) { - if(typeof siteEventName != 'undefined') { - var siteEventURL = i.addToURL(targetURL, EVT, EVT_SITE); - siteEventName = siteEventName.replace(/\W/g, '-'); // replace all non-alphanumeric chars with dashes - siteEventURL = i.addToURL(siteEventURL, "st", siteEventName); - i.fireRequest(siteEventURL); - } - - - - } - - i.sendKV = function(kvArr) { // accept array from embedded script on site - i.customKV(kvArr); - } - - // process custom KV stuff - i.customKV = function(customArray) { - - if(typeof customArray != 'undefined') { - - if(customArray.length >= 1) { - - var customURL = i.addToURL(targetURL, EVT, EVT_CUSTOM); - var customKVStr = i.encodeKVPairs(customArray); - var encodedCustomKVStr = encodeURIComponent(customKVStr); // make it fit to pass in the URL - customURL = i.addToURL(customURL, "kv", encodedCustomKVStr); - - i.fireRequest(customURL); - } - } - }; - - // encode the KV array. handles 'undefined' array scenario - // returns the encoded string. - i.encodeKVPairs = function (kvArray) { - var kvString = ""; - - if(typeof kvArray != 'undefined') { - - var EQUAL = "#=#"; - var DELIM = "#&#"; - var COMMA = "#,#"; - - for (var idx = 0; idx < kvArray.length; idx++) { - var eachRow = kvArray[idx]; - var rowValueStr = ""; - - if (eachRow && eachRow.length >= 1) { - var rowKey = eachRow[0]; - rowKey = rowKey.trim(); - rowKey = rowKey.replace(/\W/g, '-'); // replace all non-alphanumeric chars with dashes - rowKey = rowKey.toLowerCase(); - - if(eachRow.length == 1) { // only one item in array - - kvString = kvString + rowKey + DELIM; - } else { - eachRow.shift(); // remove the 1st element which is the key - - for (var j = 0; j < eachRow.length; j++) { - var columnVal = eachRow[j]; - - if (columnVal) { - columnVal = columnVal.trim(); - - if(!(rowKey == "name" || rowKey == "uid" || rowKey == "email")) { // do not touch name, email or uid - columnVal = columnVal.replace(/\W/g, '-'); // replace all non-alphanumeric chars with dashes - columnVal = columnVal.toLowerCase(); - } - - rowValueStr = rowValueStr + columnVal; - - if (j < eachRow.length - 1) { - rowValueStr = rowValueStr + COMMA; - } - } - - } // for - - if (rowValueStr.trim() != "") { // don't add empty values - kvString = kvString + rowKey + EQUAL + rowValueStr; - - if (idx < kvArray.length - 1) { - kvString = kvString + DELIM; // no delimiter for the last one - } - } - - } - } - } // for idx < array.length - - } - - return kvString; - - }; - - - i.g = function () { - gcookie = i.readCookie(GCOOKIE_NAME); - scookie = i.readCookie(SCOOKIE_NAME); - pcookie = i.readCookie(PCOOKIE_NAME); - }; - - i.s = function (n, v) { - var domain = window.location.hostname; - var cookieExpiry = ""; - - if (n == GCOOKIE_NAME) { - var TEN_YEARS_IN_SECS = 86400 * 365 * 10; //seconds in an days * days in an year * number of years - cookieExpiry = TEN_YEARS_IN_SECS; - gcookie = v; - - } else if (n == SCOOKIE_NAME) { - var TWENTY_MINS_IN_SECS = 60 * 20; //seconds in minute * number of mins - cookieExpiry = TWENTY_MINS_IN_SECS; - scookie = v; - } - - i.createBroadCookie(n, v, cookieExpiry, domain); - - }; - - - // sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com" - i.createBroadCookie = function (name, value, seconds, domain) { - - - //To update an existing "broad domain" cookie, we need to know what domain it was actually set on. - //since a retrieved cookie never tells which domain it was set on, we need to set another test cookie - //to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain - //for updating the actual cookie. - - - if(domain) { - var domainParts = domain.split("."); - var broadDomain = ""; - for(var idx = domainParts.length-1; idx >= 0 ; idx--) { - broadDomain = "." + domainParts[idx] + broadDomain; - - - // only needed if the cookie already exists and needs to be updated. See note above. - if(i.readCookie(name)) { - - // no guarantee that browser will delete cookie, hence create short lived cookies with random name - var testCookieName = "test_" + name + Math.floor((Math.random()*100)+1); - i.deleteCookie(testCookieName, broadDomain); // safety purpose - i.createCookie(testCookieName, value, 10, broadDomain); // self-destruct after 10 seconds - if(!i.readCookie(testCookieName)) { // if test cookie not set, then the actual cookie wouldn't have been set on this domain either. - continue; - } else { // else if cookie set, then delete the test and the original cookie - i.deleteCookie(testCookieName, broadDomain); - i.deleteCookie(name, broadDomain); - } - } - - i.deleteCookie(name, broadDomain); //safety purpose - i.createCookie(name, value, seconds, broadDomain); - var tempCookie = i.readCookie(name); - if(tempCookie == value) { - //console.log("Was able to retrieve cookie on: " + broadDomain + "->" + name + "=" + tempCookie); - break; - } - } - } else { - i.createCookie(name, value, seconds, domain); - } - }; - - //read - cookie get-set: http://www.quirksmode.org/js/cookies.html - - i.createCookie = function (name, value, seconds, domain) { - var expires = ""; - var domainStr = ""; - if (seconds) { - var date = new Date(); - date.setTime(date.getTime()+(seconds * 1000)); - - expires = "; expires=" + date.toGMTString(); - } - - if(domain) { - domainStr = "; domain=" + domain; - } - - var cookieStr = name + "=" + value + expires + domainStr + "; path=/"; - document.cookie = cookieStr; - }; - - i.readCookie = function readCookie(name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for(var idx = 0; idx < ca.length; idx++) { - var c = ca[idx]; - while (c.charAt(0)==' ') { - c = c.substring(1, c.length); - } - if (c.indexOf(nameEQ) == 0) { - return c.substring(nameEQ.length, c.length); - } - } - return null; - }; - - i.deleteCookie = function (name, domain) { - var cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; - - if(domain) { - cookieStr = cookieStr + " domain=" + domain + ";"; - } - - document.cookie = cookieStr; - }; - - - i.addToURL = function(url, k, v) { - return url + "&" + k + "=" + v; - }; - - - i.fireRequest = function (url) { - if (gcookie != null) { - url = i.addToURL(url, "g", gcookie); - } - if (scookie != null) { - url = i.addToURL(url, "s", scookie); - } - - url = i.addToURL(url, "rnd", new Date().getTime()); // add epoch to beat caching of the URL - - var s = doc.createElement('script'); - s.setAttribute("type", "text/javascript"); - s.setAttribute("src", url); - s.async = true; - doc.getElementsByTagName("head")[0].appendChild(s); - }; - - - // list of functions that the closure compiler shouldn't rename - // https://developers.google.com/closure/compiler/docs/api-tutorial3 - i['s'] = i.s; - i['is_onloadcalled'] = i.is_onloadcalled; - i['sendKV'] = i.sendKV; - i['sendSiteEvent'] = i.sendSiteEvent; - -} // function __wizrocket - -$WZRK_WR = new __wizrocket(); - -// inspired via - https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js && http://javascript.nwbox.com/ContentLoaded/ -// Author: Diego Perini (diego.perini@gmail.com) - -(function (fn) { - - var done = false, top = true, - win = window; - doc = win.document, root = doc.documentElement, - - add = doc.addEventListener ? 'addEventListener' : 'attachEvent', - rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', - pre = doc.addEventListener ? '' : 'on', - - init = function(e) { - if (e.type == 'readystatechange' && doc.readyState != 'complete') return; - (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); - if (!done && (done = true)) fn.call(win, e.type || e); - }, - - poll = function() { - try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } - init('poll'); - }; - - if (doc.readyState == 'complete') fn.call(win, 'lazy'); - else { - if (doc.createEventObject && root.doScroll) { - try { top = !win.frameElement; } catch(e) { } - if (top) poll(); - } - doc[add](pre + 'DOMContentLoaded', init, false); - doc[add](pre + 'readystatechange', init, false); - win[add](pre + 'load', init, false); - } - - -})($WZRK_WR.pageloaded); - -/** - * @preserve Copyright WizRocket Technologies Pvt. Ltd. (ver.@timestamp@) - * _ _ _ - * __ _(_)_____ __ ___ ___| | _____| |_ - * \ \ /\ / / |_ / '__/ _ \ / __| |/ / _ \ __| - * \ V V /| |/ /| | | (_) | (__| < __/ |_ - * \_/\_/ |_/___|_| \___/ \___|_|\_\___|\__| - */ - -/* Tested with the following browsers - Android - - maxthon works - firefox works - opera mini - kv, pg work. scroll, click, kp dont. - ucbrowser - kv, pg work. scroll, click, kp dont. - ucbrowser-mini - works - dolphin - works - chrome - works - stock browser - works - - Windows - - IE10 works - FF works - Chrome works - - MacOS - - FF works - Chrome works - Safari works - Opera works - - iOS- - Chrome works - FF works - */ diff --git a/q.js b/q.js deleted file mode 100644 index e4d195f6..00000000 --- a/q.js +++ /dev/null @@ -1,315 +0,0 @@ -//todo - the fetchExperiments call might happen multiple times -//todo - check how many times fetchExperiments is called for brand new user who's not been marked for exp yet. -function __wizrocketx() { - var targetURL = location.protocol + '//foo.com:8080/e?t=1'; - - var i = this; - var doc = document; - var win = window; - var syncTimerId, asyncTimerId; - var syncFallbackTimerId, asyncFallbackTimerId; - - var deliveredSyncResults=0; - var deliveredAsyncResults=0; - - var today = new Date(); - var todayYmd = (today.getYear() + 1900) + "" + (today.getMonth() + 1) + "" + (today.getDate()); - - - var XCOOKIE_NAME = "WZRK_X"; - var bGotResults; - var emptyArr = []; - - - var gcookie, xcookie; - - var GCOOKIE_NAME = "WZRK_G"; - - i.init = function() { - console.log("wzrk_x init called"); - - //todo : if cookie missing then don't even send teh request - gcookie = i.readCookie(GCOOKIE_NAME); - }; - - - i.enableTargeting = function() { - // sync - syncTimerId = setTimeout(function(){ - syncTimerId=undefined; - // call didn't come through, let's try the fallback option - console.log("sync timer timeout"); - - xcookie = i.readCookie(XCOOKIE_NAME); - - if(xcookie != null && xcookie.length === 6) { // if xcookie exists - - syncFallbackTimerId = setTimeout(function() { - //unable to fetch results from the fallback url during the stipulated time - syncFallbackTimerId=undefined; - i.deliverSyncResults(emptyArr); - - }, 500); - - i.fetchExperimentData(i.addToURL(targetURL, "dt", xcookie)); // get the data on the date of the cookie - fallback option - - } else { // no xcookie - i.deliverSyncResults(emptyArr); - } - i.fetchExperimentData(i.addToURL(targetURL, "dt", todayYmd)); // fallback URL call so that data gets cached and cookie gets set for next time - }, 1000); - - - // async - asyncTimerId = setTimeout(function(){ - asyncTimerId=undefined; - // call didn't come through, let's try the fallback option - console.log("async timer timeout"); - - xcookie = i.readCookie(XCOOKIE_NAME); - - if(xcookie != null && xcookie.length === 6) { // if xcookie exists - - asyncFallbackTimerId = setTimeout(function() { - //unable to fetch results from the fallback url during the stipulated time - asyncFallbackTimerId=undefined; - i.deliverAsyncResults(emptyArr); - - }, 500); - - i.fetchExperimentData(i.addToURL(targetURL, "dt", xcookie)); // get the data on the date of the cookie - fallback option - - } else { // no xcookie - i.deliverAsyncResults(emptyArr); - } - i.fetchExperimentData(i.addToURL(targetURL, "dt", todayYmd)); // fallback URL call so that data gets cached and cookie gets set for next time - }, 10000); - - - i.fetchExperimentData(targetURL); - - }; - - - //ensure the wzrk_sync_result method are called one time only for every page reload - i.deliverSyncResults = function (syncResults) { - if(deliveredSyncResults == 0 && typeof(wzrk_sync_results) == typeof(Function)) { - deliveredSyncResults=1; - console.log("about to deliver sync results"); - win.wzrk_sync_results(syncResults); - } - }; - - //ensure the wzrk_async_result method are called one time only for every page reload - i.deliverAsyncResults = function (asyncResults) { - if(deliveredAsyncResults == 0 && typeof(wzrk_async_results) == typeof(Function)) { - deliveredAsyncResults=1; - console.log("about to deliver async results"); - win.wzrk_async_results(asyncResults); - } - }; - - - i.fetchExperimentData = function(url) { - console.log("firing request to fetch experiments"); - i.fireRequest(url); - }; - - - // e.g. {1: "1382812200000|1382898599000|0000-2359-127 * *", 4: "1382812200000|1382898599000|0000-2359-127 * *"} - i.results = function(resultObj) { - - console.log("got main results: " + resultObj); - - var validExps = i.getValidExperiments(resultObj); - - if(typeof syncTimerId != 'undefined') { - clearTimeout(syncTimerId); - console.log("got results before timeout, canceled timer: sync"); - i.deliverSyncResults(validExps); - } - - if(typeof asyncTimerId != 'undefined') { - clearTimeout(asyncTimerId); - console.log("got results before timeout, canceled timer: async"); - i.deliverAsyncResults(validExps); - } - - }; // i.results - - // e.g. {0:20131104, 1: "1382812200000|1382898599000|0000-2359-127 * *", 4: "1382812200000|1382898599000|0000-2359-127 * *"} - i.fbResults = function (resultObj) { - - if(typeof resultObj[0] != 'undefined') { - var dateStr = resultObj[0]; // 0th element contains the request as sent in the request - var THIRTY_DAYS_IN_SECS = 60 * 60 * 24 * 30; - i.createCookie(XCOOKIE_NAME, dateStr,THIRTY_DAYS_IN_SECS); //save a cookie with the last known fetch date of fallback results - } - - var validExps = i.getValidExperiments(resultObj); - - console.log("got the fallback results: " + resultObj); - - if(typeof syncFallbackTimerId != 'undefined') { - clearTimeout(syncFallbackTimerId); - console.log("got results before fallback sync timer timeout, canceling it now"); - i.deliverSyncResults(validExps); - } - - if(typeof asyncTimerId != 'undefined') { - clearTimeout(asyncTimerId); - console.log("got results before async timer timeout, canceling it now"); - i.deliverAsyncResults(validExps); - } - - }; // i.results - - - - i.addToURL = function (url, k, v) { - return url + "&" + k + "=" + v; - }; - - i.fireRequest = function (url) { - if (gcookie != null) { - url = i.addToURL(url, "g", gcookie); - } - - //url = i.addToURL(url, "rnd", new Date().getTime()); // add epoch to beat caching of the URL - - var s = doc.createElement('script'); - s.setAttribute("type", "text/javascript"); - s.setAttribute("src", url); - s.async = true; - doc.getElementsByTagName("head")[0].appendChild(s); - }; - - - //read - cookie get-set: http://www.quirksmode.org/js/cookies.html - i.createCookie = function (name, value, seconds, domain) { - var expires = ""; - var domainStr = ""; - if (seconds) { - var date = new Date(); - date.setTime(date.getTime()+(seconds * 1000)); - expires = "; expires=" + date.toGMTString(); - } - - if(domain) { - domainStr = "; domain=" + domain; - } - - var cookieStr = name + "=" + value + expires + domainStr + "; path=/"; - document.cookie = cookieStr; - }; - - i.readCookie = function (name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for(var idx = 0; idx < ca.length; idx++) { - var c = ca[idx]; - while (c.charAt(0)==' ') { - c = c.substring(1, c.length); - } - if (c.indexOf(nameEQ) == 0) { - return c.substring(nameEQ.length, c.length); - } - } - return null; - }; - - i.getValidExperiments = function (expObject) { - var validExpArray = []; - var date = new Date(); - for(k in expObject) { - if(k > 0) { // don't process 0 key, since it's used to send date - var v = expObject[k]; - if(i.isExpActive(v, date)) { - validExpArray.push(k); - } - } // k > 0 - } - console.log("Valid experiments: " + validExpArray); - return validExpArray; - }; - - - // to test use isValid("1282597083|1584597083|0000-0000-127 * *", new Date(1382553000000)); - i.isExpActive = function (cronExp, cDate) { - var valid = 0; - - var cTime = cDate.getTime(); // epoch - var cHour = cDate.getHours(); // hour (0-23) - var cMin = cDate.getMinutes(); // min (0-59) - var cHourMin = cHour + "" + cMin; // 1430 - var cMoy = cDate.getMonth(); // month of year (0-11) - var cDom = cDate.getDate(); // day of month (1-31) - var cDay = cDate.getDay(); // day of the week (0-6) Sunday=0 - var cDayBit = Math.pow(2,cDay); - - var expParts = cronExp.split("|"); - var expStartEpoch = expParts[0]; - var expEndEpoch = expParts[1]; - - if((cTime >=expStartEpoch) && (cTime < expEndEpoch)) { // within exp time range - - var timeExpArr = expParts[2].split(" "); // e.g. 900-1030-65,1315-1420-65,1610-2030-65 * * - var dom = timeExpArr[1]; - var moy = timeExpArr[2]; - - if(dom == cDom || dom == '*') { // specific day of month, or valid for ALL days - if(moy == cMoy || moy == '*') { // specific month of year or valid for ALL months - var dayTimeExpArr = timeExpArr[0].split(","); // e.g. 900-1030-65,1315-1420-65,1610-2030-65 - - for(var i=0;i= startTimeSlot || startTimeSlot == 0) && (cHourMin <= endTimeSlot) && (dayBit & cDayBit)) { - valid=1; - break; - } // if - } - } // if moy - } // if dom - - } - return valid; - }; - - i.arrayContains = function (arr, key) { - // see this for best way to check for array -> http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ - if(Object.prototype.toString.call(arr) === '[object Array]') { - var i = arr.length; - while (i--) { - if (arr[i] === key) { - return true; - } - } - } - return false; - }; - - // list of functions that the closure compiler shouldn't rename - // https://developers.google.com/closure/compiler/docs/api-tutorial3 - i['fbResults'] = i.fbResults; - i['results'] = i.results; - i['arrayContains'] = i.arrayContains; - i['enableTargeting'] = i.enableTargeting; - - -} // function wizrocketx - -$WZRK_X = new __wizrocketx(); -$WZRK_X.init(); - -/** - * @preserve Copyright WizRocket Technologies Pvt. Ltd. (ver.@timestamp@) - * _ _ _ __ __ - * __ _(_)_____ __ ___ ___| | _____| |_ \ \/ / - * \ \ /\ / / |_ / '__/ _ \ / __| |/ / _ \ __| \ / - * \ V V /| |/ /| | | (_) | (__| < __/ |_ / \ - * \_/\_/ |_/___|_| \___/ \___|_|\_\___|\__| /_/\_\ - */ diff --git a/wzrk-shopify.js b/wzrk-shopify.js deleted file mode 100644 index 0fd4e1d0..00000000 --- a/wzrk-shopify.js +++ /dev/null @@ -1,214 +0,0 @@ -if(typeof clevertap === "undefined"){ - var clevertap = { - event: [], - profile: [], - account: [], - notifications: [], - onUserLogin: [] - }; -} - -function wzrkShopify(id, region) { - clevertap.account.push({ - "id": id - }); - clevertap.enablePersonalization = true; // enables Personalization - clevertap.plugin = "shop"; - if (typeof region !== "undefined" && region !== "") { - clevertap.region = region; - } - var wzrk = document.createElement('script'); - wzrk.type = 'text/javascript'; - wzrk.async = true; - wzrk.src = ('https:' == document.location.protocol ? 'https://d2r1yp2w7bby2u.cloudfront.net' : 'http://static.clevertap.com') + '/js/a.js'; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(wzrk, s); - - var removeUnwantedinPrice = function(price){ - var nums = price.split("."); - nums[0] = nums[0].replace(/\D+/g, ''); - - if(nums.length > 1){ - nums[1] = nums[1].replace(/\D+/g, ''); - return (nums[0] + "." + nums[1]); - } - - return nums[0]; - }; - - var fixPrice = function(product_price){ - var price_arr = product_price.split(" "); - if(price_arr.length > 1){ - return parseFloat(parseFloat(removeUnwantedinPrice(price_arr[1])).toFixed(2)); - } - return parseFloat(parseFloat(removeUnwantedinPrice(product_price)).toFixed(2)); - }; - - var push_product_viewed = function() { - clevertap.event.push("Product Viewed", { - "Product name": __wzrk_product_title, - "Category": __wzrk_product_category_name, - "Price": fixPrice(__wzrk_product_price), - "Currency": __wzrk_currency - }); - }; - - var category_viewed = function() { - clevertap.event.push("Category Viewed", { - "Category name": __wzrk_collection_name - }); - }; - - var push_search = function() { - clevertap.event.push("Searched", { - "Term": __wzrk_searchterm - }); - }; - - var push_add_to_cart = function() { - clevertap.event.push("Added To Cart", { - "Product name": __wzrk_product_title, - "Category": __wzrk_product_category_name, - "Price": fixPrice(__wzrk_product_price), - "Currency": __wzrk_currency - }); - }; - - var push_checkout = function() { - var len = Shopify.checkout.line_items.length; - var items = []; - for (i = 0; i < len; i++) { - var obj = {}; - obj["Product_id"] = Shopify.checkout.line_items[i].product_id; - obj["Title"] = Shopify.checkout.line_items[i].title; - obj["Quantity"] = Shopify.checkout.line_items[i].quantity; - obj["Vendor"] = Shopify.checkout.line_items[i].vendor; - items.push(obj); - } - var checkout = Shopify.checkout; - if(typeof checkout !== "undefined"){ - var shipping_address = checkout.shipping_address; - var amount = checkout.total_price; - if(typeof amount !== 'number'){ - amount = parseFloat(amount); - } - if(typeof shipping_address === "undefined"){ - clevertap.event.push("Charged", { - "Amount": amount, - "Currency": checkout.currency, - "Email": checkout.email, - "Charged ID": checkout.order_id, - "Items": items - }); - } else{ - clevertap.event.push("Charged", { - "Amount": amount, - "Currency": checkout.currency, - "Ship_country": shipping_address.country, - "Ship_region": shipping_address.province, - "Ship_city": shipping_address.city, - "Email": checkout.email, - "Charged ID": checkout.order_id, - "Items": items - }); - } - } - }; - - var profile_push_checkout = function() { - if(Shopify.checkout != null){ - if(Shopify.checkout.billing_address != null){ - clevertap.onUserLogin.push({ - "Site": { - "Name": Shopify.checkout.billing_address.first_name, - "Email": Shopify.checkout.email - } - }); - } else{ - clevertap.onUserLogin.push({ - "Site": { - "Email": Shopify.checkout.email - } - }); - } - } - }; - - if (typeof __wzrk_product_json != "undefined") { - push_product_viewed(); - if(document.getElementsByName("add").length > 0){ - document.getElementsByName("add")[0].onclick = push_add_to_cart; - console.log("added to cart"); - }else{ - var addedToCart = false; - var forms = document.getElementsByTagName("form"); - var patt = /cart\/add$/i; - for (var i = 0; i < forms.length; i++) { - if(patt.test(forms[i].action)){ - var inputs = forms[i].getElementsByTagName("input"); - for (var j = 0; j < inputs.length; j++) { - if(inputs[j].type == "submit"){ - console.log("added to cart"); - inputs[j].onclick = push_add_to_cart; - addedToCart = true; - } - } - if(!addedToCart){ - var buttons = forms[i].getElementsByTagName("button"); - for(j =0; j < buttons.length; j++){ - if(buttons[j].type == "submit"){ - console.log("added to cart"); - buttons[j].onclick = push_add_to_cart; - addedToCart = true; - } - } - } - } - } - } - } - - if (typeof Shopify.checkout !== "undefined") { - var shouldPushCharged = true; - if(localStorage && localStorage.getItem("WZRK_LST_CHID") !== null){ - var lastChargedId = localStorage.getItem("WZRK_LST_CHID"); - var chargedId = "" + Shopify.checkout.order_id; - if(lastChargedId === chargedId){ - shouldPushCharged = false; - } - } - if(shouldPushCharged){ - profile_push_checkout(); - push_checkout(); - if(localStorage){ - localStorage.setItem("WZRK_LST_CHID", "" + Shopify.checkout.order_id); - } - } - } - if (typeof __wzrk_collection_name !== "undefined") { - category_viewed(); - } - if (typeof __wzrk_searchterm !== "undefined") { - push_search(); - } -} - -if (typeof __wzrk_account_id !== "undefined") { - // SUC-60553. Region introduced - if (typeof __wzrk_region === "undefined") { - __wzrk_region = ""; - } - wzrkShopify(__wzrk_account_id, __wzrk_region); -} else { - if (typeof Shopify !== "undefined") { - (function(){ - var shop = Shopify.shop; - var wzrkShopify = document.createElement('script'); - wzrkShopify.type = 'text/javascript'; - wzrkShopify.async = true; - wzrkShopify.src = "https://api.clevertap.com/js/wzrk-shopify.js?shop=" + shop; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(wzrkShopify, s); - }()); - } -} From 9e45f9fe36544bc81e87a75a682f61513bff718e Mon Sep 17 00:00:00 2001 From: shubham Date: Thu, 31 Aug 2023 14:54:40 +0530 Subject: [PATCH 22/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 36 +++++ .github/workflows/sw_release.yml | 38 +++++ package.json | 1 + sw_rollup.config.js | 35 +++++ sw_webpush.js | 261 ++++++++++++++++--------------- 5 files changed, 241 insertions(+), 130 deletions(-) create mode 100644 .github/workflows/sw_build.yml create mode 100644 .github/workflows/sw_release.yml create mode 100644 sw_rollup.config.js diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml new file mode 100644 index 00000000..f423df3b --- /dev/null +++ b/.github/workflows/sw_build.yml @@ -0,0 +1,36 @@ +name: Test and build +on: + push: + branches: + - master + - develop + pull_request: + branches: + - master + - develop + types: [opened, synchronize, reopened] +jobs: + build: + runs-on: macos-latest + steps: + - uses: actions/checkout@v2 + - name: Use node.js version 10.x + uses: actions/setup-node@v2.1.2 + with: + node-version: '10.x' + - name: Get yarn cache directory path + id: yarn-cache-dir-path + run: echo "::set-output name=dir::$(yarn cache dir)" + - uses: actions/cache@v2 + id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) + with: + path: ${{ steps.yarn-cache-dir-path.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: Install packages + run: yarn + - name: Run unit tests + run: yarn run test:coverage + - name: Build package + run: yarn run build diff --git a/.github/workflows/sw_release.yml b/.github/workflows/sw_release.yml new file mode 100644 index 00000000..fcc387aa --- /dev/null +++ b/.github/workflows/sw_release.yml @@ -0,0 +1,38 @@ +name: Release to npm and s3 +on: + release: + types: [published] +jobs: + build: + runs-on: macos-latest + steps: + - uses: actions/checkout@v2 + - name: Use node.js version 10.x + uses: actions/setup-node@v2.1.2 + with: + node-version: '10.x' + - name: Get yarn cache directory path + id: yarn-cache-dir-path + run: echo "::set-output name=dir::$(yarn cache dir)" + - uses: actions/cache@v2 + id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) + with: + path: ${{ steps.yarn-cache-dir-path.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: Install packages + run: yarn + - name: Run unit tests + run: yarn run test:coverage + - name: Build package + run: yarn run build_sw + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v1 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ secrets.AWS_REGION }} + - name: Copy file to S3 + run: | + aws s3 cp sw_webpush.min.js s3://${{ secrets.S3_BUCKET_PATH }} diff --git a/package.json b/package.json index f8f5ffd8..36ab8b5e 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "main": "clevertap.js", "scripts": { "build": "rollup --config rollup.config.js", + "build_sw": "rollup --config sw_rollup.config.js", "test": "eslint --fix test && jest", "test:coverage": "rm -rf coverage && jest --coverage" }, diff --git a/sw_rollup.config.js b/sw_rollup.config.js new file mode 100644 index 00000000..5133996c --- /dev/null +++ b/sw_rollup.config.js @@ -0,0 +1,35 @@ +import resolve from '@rollup/plugin-node-resolve' +import babel from '@rollup/plugin-babel' +import replace from '@rollup/plugin-replace' +import { eslint } from 'rollup-plugin-eslint' +import { terser } from 'rollup-plugin-terser' +import { version } from './package.json' +import sourcemaps from 'rollup-plugin-sourcemaps' + +export default { + input: 'sw_webpush.js', + output: [ + { + name: 'sw_webpush', + file: 'sw_webpush.min.js', + format: 'umd', + plugins: [terser()] + } + ], + plugins: [ + resolve(), + sourcemaps(), + eslint({ + fix: true, + throwOnError: true + }), + replace({ + preventAssignment: true, + delimiters: ['', ''], + $$PACKAGE_VERSION$$: version + }), + babel({ + babelHelpers: 'bundled' + }) + ] +} diff --git a/sw_webpush.js b/sw_webpush.js index a322d066..afca707a 100644 --- a/sw_webpush.js +++ b/sw_webpush.js @@ -1,3 +1,6 @@ +/* eslint-disable handle-callback-err */ +/* eslint-disable no-use-before-define */ +/* eslint-disable no-undef */ /** * Author: Jashan Shewakramani * Last updated: 27 June 2016 @@ -10,152 +13,150 @@ * -> Use Google's closure compiler on http://closure-compiler.appspot.com/ for minifying */ -importScripts('https://d2r1yp2w7bby2u.cloudfront.net/js/localforage.min.js'); +importScripts('https://d2r1yp2w7bby2u.cloudfront.net/js/localforage.min.js') // var CACHE_VERSION = 3; // var CURRENT_CACHES = { // prefetch: 'prefetch-cache-v' + CACHE_VERSION // }; -if(typeof globalRedirectPath === "undefined"){ - // set up some variables we need gobally - var globalNotificationData; - //global redirect path for backward compatibility - var globalRedirectPath; // when showing thr url; we need to log to LC before opening up the deep link +if (typeof globalRedirectPath === 'undefined') { + // set up some variables we need gobally + var globalNotificationData + // global redirect path for backward compatibility + var globalRedirectPath // when showing thr url; we need to log to LC before opening up the deep link } -self.addEventListener('install', function(event) { - // force this service worker to become the active service worker; removes any previous implementations or migrations - self.skipWaiting(); - // console.log('Service worker installed', self, event); -}); +self.addEventListener('install', function (event) { + // force this service worker to become the active service worker; removes any previous implementations or migrations + self.skipWaiting() + // console.log('Service worker installed', self, event); +}) -self.addEventListener('activate', function(event) { - // console.log('Service worker activated', self, event); - // Delete all caches that aren't named in CURRENT_CACHES. - // var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { - // return CURRENT_CACHES[key]; - // }); - // - // event.waitUntil( - // caches.keys() - // .then(function(cacheNames) { - // return Promise.all( - // cacheNames.map(function(cacheName) { - // if (expectedCacheNames.indexOf(cacheName) === -1) { - // // If this cache name isn't present in the array of "expected" cache names, then delete it. - // console.log('Deleting out of date cache:', cacheName); - // return caches.delete(cacheName); - // } - // }) - // ); - // }) - // .catch(function(){ - // console.log("Error while clearing cache") - // }) - // ); - console.log('CT Service worker activated') -}); +self.addEventListener('activate', function (event) { + // console.log('Service worker activated', self, event); + // Delete all caches that aren't named in CURRENT_CACHES. + // var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { + // return CURRENT_CACHES[key]; + // }); + // + // event.waitUntil( + // caches.keys() + // .then(function(cacheNames) { + // return Promise.all( + // cacheNames.map(function(cacheName) { + // if (expectedCacheNames.indexOf(cacheName) === -1) { + // // If this cache name isn't present in the array of "expected" cache names, then delete it. + // console.log('Deleting out of date cache:', cacheName); + // return caches.delete(cacheName); + // } + // }) + // ); + // }) + // .catch(function(){ + // console.log("Error while clearing cache") + // }) + // ); + console.log('CT Service worker activated') +}) -self.addEventListener('push', function(event) { +self.addEventListener('push', function (event) { + console.log('Push event: ', event) + // get all the notification data + var notificationData = JSON.parse(event.data.text()) + var title = notificationData.title + var notificationOptions = notificationData.notificationOptions + var data = notificationOptions.data + var key + if (typeof data !== 'undefined') { + key = data.wzrk_id + } + if (typeof key === 'undefined') { + key = title + } + localforage.setItem(key, event.data.text()).then(function (value) { + // console.log("persisted"); + }).catch(function (err) { + // This code runs if there were any errors + console.log('Error in persisting') + }) - console.log('Push event: ', event); - // get all the notification data - var notificationData = JSON.parse(event.data.text()); - var title = notificationData['title']; - var notificationOptions = notificationData['notificationOptions']; - var data = notificationOptions['data']; - var key; - if(typeof data !== 'undefined'){ - key = data['wzrk_id']; - } - if(typeof key === 'undefined'){ - key = title; - } - localforage.setItem(key, event.data.text()).then(function(value){ - // console.log("persisted"); - }).catch(function(err) { - // This code runs if there were any errors - console.log("Error in persisting"); - }); + // two global variables for backward compatibility + globalRedirectPath = notificationData.redirectPath + globalNotificationData = notificationData - // two global variables for backward compatibility - globalRedirectPath = notificationData['redirectPath']; - globalNotificationData = notificationData; + var raiseNotificationViewedPath = notificationData.raiseNotificationViewedPath + if (typeof raiseNotificationViewedPath !== 'undefined') { + // raise notification viewed event + fetch(raiseNotificationViewedPath, { mode: 'no-cors' }) // ignore the response + } + event.waitUntil(self.registration.showNotification(title, notificationOptions)) +}) - var raiseNotificationViewedPath = notificationData['raiseNotificationViewedPath']; - if(typeof raiseNotificationViewedPath !== "undefined"){ - //raise notification viewed event - fetch(raiseNotificationViewedPath, {'mode': 'no-cors'}); //ignore the response +function onClick (event, redirectPath, notificationData) { + var finalDeepLink = redirectPath + var silentRequest = true // are opening up a new window or sending a quiet get request from here? + if (event.action === 'action1') { + // button 1 was clicked + if (typeof notificationData.notificationOptions.actions[0].deepLink !== 'undefined') { + finalDeepLink += '&r=' + encodeURIComponent(notificationData.notificationOptions.actions[0].deepLink) + silentRequest = false } - event.waitUntil(self.registration.showNotification(title, notificationOptions)); - -}); - -function onClick(event, redirectPath, notificationData){ - var finalDeepLink = redirectPath; - var silentRequest = true; // are opening up a new window or sending a quiet get request from here? - if (event.action === 'action1') { - // button 1 was clicked - if (typeof notificationData['notificationOptions']['actions'][0]['deepLink'] !== 'undefined') { - finalDeepLink += '&r=' + encodeURIComponent(notificationData['notificationOptions']['actions'][0]['deepLink']); - silentRequest = false; - } - finalDeepLink += '&b=' + encodeURIComponent('button1'); - } else if (event.action === 'action2') { - // the second button was clicked - if (typeof notificationData['notificationOptions']['actions'][1]['deepLink'] !== 'undefined') { - finalDeepLink += '&r=' + encodeURIComponent(notificationData['notificationOptions']['actions'][1]['deepLink']); - silentRequest = false; - } - finalDeepLink += '&b=' + encodeURIComponent('button2'); - } else { - // general click - if (typeof notificationData['deepLink'] !== 'undefined') { - finalDeepLink += '&r=' + encodeURIComponent(notificationData['deepLink']); - silentRequest = false; - } - - finalDeepLink += '&b=' + encodeURIComponent('button0'); + finalDeepLink += '&b=' + encodeURIComponent('button1') + } else if (event.action === 'action2') { + // the second button was clicked + if (typeof notificationData.notificationOptions.actions[1].deepLink !== 'undefined') { + finalDeepLink += '&r=' + encodeURIComponent(notificationData.notificationOptions.actions[1].deepLink) + silentRequest = false } - - if (silentRequest) { - fireSilentRequest(finalDeepLink); - } else { - clients.openWindow(finalDeepLink); + finalDeepLink += '&b=' + encodeURIComponent('button2') + } else { + // general click + if (typeof notificationData.deepLink !== 'undefined') { + finalDeepLink += '&r=' + encodeURIComponent(notificationData.deepLink) + silentRequest = false } - event.notification.close(); + + finalDeepLink += '&b=' + encodeURIComponent('button0') + } + + if (silentRequest) { + fireSilentRequest(finalDeepLink) + } else { + clients.openWindow(finalDeepLink) + } + event.notification.close() } -self.addEventListener('notificationclick', function(event) { - var notification = event.notification; - var data = notification['data']; - var key; - if(typeof data !== 'undefined' && data !== null){ - key = data['wzrk_id']; - } - if(typeof key === 'undefined'){ - key = notification['title']; - } - var promise = localforage.getItem(key).then(function(value) { - var notificationData = JSON.parse(value); - var redirectPath = notificationData['redirectPath']; - // console.log("event",event); - // console.log("redirect path: " + redirectPath); - // console.log("notification data: " + notificationData); - onClick(event, redirectPath, notificationData); - }).catch(function(err) { - // This code runs if there were any errors - //onClick below for backward compatibility - onClick(event, globalRedirectPath, globalNotificationData); - console.log(err); - }); - event.waitUntil(promise); -}); +self.addEventListener('notificationclick', function (event) { + var notification = event.notification + var data = notification.data + var key + if (typeof data !== 'undefined' && data !== null) { + key = data.wzrk_id + } + if (typeof key === 'undefined') { + key = notification.title + } + var promise = localforage.getItem(key).then(function (value) { + var notificationData = JSON.parse(value) + var redirectPath = notificationData.redirectPath + // console.log("event",event); + // console.log("redirect path: " + redirectPath); + // console.log("notification data: " + notificationData); + onClick(event, redirectPath, notificationData) + }).catch(function (err) { + // This code runs if there were any errors + // onClick below for backward compatibility + onClick(event, globalRedirectPath, globalNotificationData) + console.log(err) + }) + event.waitUntil(promise) +}) -var fireSilentRequest = function(url) { - // add the silent parameter to the deeplink so that LC knows not to raise an error - url += '&s=true'; +var fireSilentRequest = function (url) { + // add the silent parameter to the deeplink so that LC knows not to raise an error + url += '&s=true' - // use the fetch API to make a silent request (we don't care about the response here) - fetch(url, {'mode': 'no-cors'}); -}; + // use the fetch API to make a silent request (we don't care about the response here) + fetch(url, { mode: 'no-cors' }) +} \ No newline at end of file From ce6b8aeb06edf5f70ae8f5f18af1121202c3291d Mon Sep 17 00:00:00 2001 From: shubham Date: Thu, 31 Aug 2023 14:58:40 +0530 Subject: [PATCH 23/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 2 +- .github/workflows/sw_release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml index f423df3b..536415d3 100644 --- a/.github/workflows/sw_build.yml +++ b/.github/workflows/sw_build.yml @@ -1,4 +1,4 @@ -name: Test and build +name: Build SW Webpush on: push: branches: diff --git a/.github/workflows/sw_release.yml b/.github/workflows/sw_release.yml index fcc387aa..28b5cd2e 100644 --- a/.github/workflows/sw_release.yml +++ b/.github/workflows/sw_release.yml @@ -1,4 +1,4 @@ -name: Release to npm and s3 +name: Release sw_webpush.min.js to s3 on: release: types: [published] From b715d7a26a37224d41a638df0625412b0f39b998 Mon Sep 17 00:00:00 2001 From: shubham Date: Thu, 31 Aug 2023 15:00:02 +0530 Subject: [PATCH 24/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_release.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/sw_release.yml b/.github/workflows/sw_release.yml index 28b5cd2e..8a4f38ab 100644 --- a/.github/workflows/sw_release.yml +++ b/.github/workflows/sw_release.yml @@ -29,10 +29,10 @@ jobs: run: yarn run build_sw - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 - with: - aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} - aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - aws-region: ${{ secrets.AWS_REGION }} + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ secrets.AWS_REGION }} - name: Copy file to S3 run: | aws s3 cp sw_webpush.min.js s3://${{ secrets.S3_BUCKET_PATH }} From 9870164a03c88e03025fdb574b9e19849486f4cf Mon Sep 17 00:00:00 2001 From: shubham Date: Thu, 31 Aug 2023 15:05:16 +0530 Subject: [PATCH 25/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml index 536415d3..9daa096d 100644 --- a/.github/workflows/sw_build.yml +++ b/.github/workflows/sw_build.yml @@ -33,4 +33,4 @@ jobs: - name: Run unit tests run: yarn run test:coverage - name: Build package - run: yarn run build + run: yarn run build_sw From 3186ae57dceba10ffd48da2448a0ea4bd28cdcd5 Mon Sep 17 00:00:00 2001 From: shubham Date: Thu, 31 Aug 2023 15:07:02 +0530 Subject: [PATCH 26/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 2 -- .github/workflows/sw_release.yml | 2 -- 2 files changed, 4 deletions(-) diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml index 9daa096d..9d40f3f9 100644 --- a/.github/workflows/sw_build.yml +++ b/.github/workflows/sw_build.yml @@ -30,7 +30,5 @@ jobs: ${{ runner.os }}-yarn- - name: Install packages run: yarn - - name: Run unit tests - run: yarn run test:coverage - name: Build package run: yarn run build_sw diff --git a/.github/workflows/sw_release.yml b/.github/workflows/sw_release.yml index 8a4f38ab..bb84b202 100644 --- a/.github/workflows/sw_release.yml +++ b/.github/workflows/sw_release.yml @@ -23,8 +23,6 @@ jobs: ${{ runner.os }}-yarn- - name: Install packages run: yarn - - name: Run unit tests - run: yarn run test:coverage - name: Build package run: yarn run build_sw - name: Configure AWS credentials From 8f33ba7219a007347b7ec769c368390d336a0609 Mon Sep 17 00:00:00 2001 From: shubham Date: Fri, 1 Sep 2023 11:16:35 +0530 Subject: [PATCH 27/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml index 9d40f3f9..ebff5a8f 100644 --- a/.github/workflows/sw_build.yml +++ b/.github/workflows/sw_build.yml @@ -32,3 +32,8 @@ jobs: run: yarn - name: Build package run: yarn run build_sw + - name: Create Artifact + uses: actions/upload-artifact@v3 + with: + name: test + path: 'sw_webpush.min.js' From b936d077e7ce6e60e56f53a4c29e4b75fb98308d Mon Sep 17 00:00:00 2001 From: shubham Date: Fri, 1 Sep 2023 11:17:59 +0530 Subject: [PATCH 28/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml index ebff5a8f..8c29bef1 100644 --- a/.github/workflows/sw_build.yml +++ b/.github/workflows/sw_build.yml @@ -33,7 +33,7 @@ jobs: - name: Build package run: yarn run build_sw - name: Create Artifact - uses: actions/upload-artifact@v3 - with: - name: test - path: 'sw_webpush.min.js' + uses: actions/upload-artifact@v3 + with: + name: test + path: 'sw_webpush.min.js' From c3bc36b5042310b11328021fb8d3549e6d4e0cc6 Mon Sep 17 00:00:00 2001 From: shubham Date: Fri, 1 Sep 2023 11:22:56 +0530 Subject: [PATCH 29/31] add pipeline to minify sw_webpush.js and upload it to s3 path --- .github/workflows/sw_build.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/sw_build.yml b/.github/workflows/sw_build.yml index 8c29bef1..9d40f3f9 100644 --- a/.github/workflows/sw_build.yml +++ b/.github/workflows/sw_build.yml @@ -32,8 +32,3 @@ jobs: run: yarn - name: Build package run: yarn run build_sw - - name: Create Artifact - uses: actions/upload-artifact@v3 - with: - name: test - path: 'sw_webpush.min.js' From a32e4ef31e5d83f74815ea5916fcc16ff3d6d470 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Thu, 11 Jan 2024 12:21:44 +0530 Subject: [PATCH 30/31] updated min.js file --- sw_webpush.js | 2 +- sw_webpush.min.js | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 sw_webpush.min.js diff --git a/sw_webpush.js b/sw_webpush.js index afca707a..96b84e89 100644 --- a/sw_webpush.js +++ b/sw_webpush.js @@ -159,4 +159,4 @@ var fireSilentRequest = function (url) { // use the fetch API to make a silent request (we don't care about the response here) fetch(url, { mode: 'no-cors' }) -} \ No newline at end of file +} diff --git a/sw_webpush.min.js b/sw_webpush.min.js new file mode 100644 index 00000000..ecaf522a --- /dev/null +++ b/sw_webpush.min.js @@ -0,0 +1 @@ +!function(n){"function"==typeof define&&define.amd?define(n):n()}((function(){"use strict";if(importScripts("https://d2r1yp2w7bby2u.cloudfront.net/js/localforage.min.js"),void 0===t)var n,t;function o(n,t,o){var e=t,c=!0;"action1"===n.action?(void 0!==o.notificationOptions.actions[0].deepLink&&(e+="&r="+encodeURIComponent(o.notificationOptions.actions[0].deepLink),c=!1),e+="&b="+encodeURIComponent("button1")):"action2"===n.action?(void 0!==o.notificationOptions.actions[1].deepLink&&(e+="&r="+encodeURIComponent(o.notificationOptions.actions[1].deepLink),c=!1),e+="&b="+encodeURIComponent("button2")):(void 0!==o.deepLink&&(e+="&r="+encodeURIComponent(o.deepLink),c=!1),e+="&b="+encodeURIComponent("button0")),c?i(e):clients.openWindow(e),n.notification.close()}self.addEventListener("install",(function(n){self.skipWaiting()})),self.addEventListener("activate",(function(n){console.log("CT Service worker activated")})),self.addEventListener("push",(function(o){console.log("Push event: ",o);var i,e=JSON.parse(o.data.text()),c=e.title,a=e.notificationOptions,d=a.data;void 0!==d&&(i=d.wzrk_id),void 0===i&&(i=c),localforage.setItem(i,o.data.text()).then((function(n){})).catch((function(n){console.log("Error in persisting")})),t=e.redirectPath,n=e;var s=e.raiseNotificationViewedPath;void 0!==s&&fetch(s,{mode:"no-cors"}),o.waitUntil(self.registration.showNotification(c,a))})),self.addEventListener("notificationclick",(function(i){var e,c=i.notification,a=c.data;null!=a&&(e=a.wzrk_id),void 0===e&&(e=c.title);var d=localforage.getItem(e).then((function(n){var t=JSON.parse(n),e=t.redirectPath;o(i,e,t)})).catch((function(e){o(i,t,n),console.log(e)}));i.waitUntil(d)}));var i=function(n){fetch(n+="&s=true",{mode:"no-cors"})}})); From 6d267a3e22706da59398e04ac768e73299a7bd14 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Thu, 11 Jan 2024 12:56:23 +0530 Subject: [PATCH 31/31] updated sw file and min file --- sw_webpush.js | 28 +--------------------------- sw_webpush.min.js | 2 +- 2 files changed, 2 insertions(+), 28 deletions(-) diff --git a/sw_webpush.js b/sw_webpush.js index 96b84e89..1f239548 100644 --- a/sw_webpush.js +++ b/sw_webpush.js @@ -29,33 +29,10 @@ if (typeof globalRedirectPath === 'undefined') { self.addEventListener('install', function (event) { // force this service worker to become the active service worker; removes any previous implementations or migrations self.skipWaiting() - // console.log('Service worker installed', self, event); + console.log('CT Service worker installed') }) self.addEventListener('activate', function (event) { - // console.log('Service worker activated', self, event); - // Delete all caches that aren't named in CURRENT_CACHES. - // var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { - // return CURRENT_CACHES[key]; - // }); - // - // event.waitUntil( - // caches.keys() - // .then(function(cacheNames) { - // return Promise.all( - // cacheNames.map(function(cacheName) { - // if (expectedCacheNames.indexOf(cacheName) === -1) { - // // If this cache name isn't present in the array of "expected" cache names, then delete it. - // console.log('Deleting out of date cache:', cacheName); - // return caches.delete(cacheName); - // } - // }) - // ); - // }) - // .catch(function(){ - // console.log("Error while clearing cache") - // }) - // ); console.log('CT Service worker activated') }) @@ -140,9 +117,6 @@ self.addEventListener('notificationclick', function (event) { var promise = localforage.getItem(key).then(function (value) { var notificationData = JSON.parse(value) var redirectPath = notificationData.redirectPath - // console.log("event",event); - // console.log("redirect path: " + redirectPath); - // console.log("notification data: " + notificationData); onClick(event, redirectPath, notificationData) }).catch(function (err) { // This code runs if there were any errors diff --git a/sw_webpush.min.js b/sw_webpush.min.js index ecaf522a..d402637b 100644 --- a/sw_webpush.min.js +++ b/sw_webpush.min.js @@ -1 +1 @@ -!function(n){"function"==typeof define&&define.amd?define(n):n()}((function(){"use strict";if(importScripts("https://d2r1yp2w7bby2u.cloudfront.net/js/localforage.min.js"),void 0===t)var n,t;function o(n,t,o){var e=t,c=!0;"action1"===n.action?(void 0!==o.notificationOptions.actions[0].deepLink&&(e+="&r="+encodeURIComponent(o.notificationOptions.actions[0].deepLink),c=!1),e+="&b="+encodeURIComponent("button1")):"action2"===n.action?(void 0!==o.notificationOptions.actions[1].deepLink&&(e+="&r="+encodeURIComponent(o.notificationOptions.actions[1].deepLink),c=!1),e+="&b="+encodeURIComponent("button2")):(void 0!==o.deepLink&&(e+="&r="+encodeURIComponent(o.deepLink),c=!1),e+="&b="+encodeURIComponent("button0")),c?i(e):clients.openWindow(e),n.notification.close()}self.addEventListener("install",(function(n){self.skipWaiting()})),self.addEventListener("activate",(function(n){console.log("CT Service worker activated")})),self.addEventListener("push",(function(o){console.log("Push event: ",o);var i,e=JSON.parse(o.data.text()),c=e.title,a=e.notificationOptions,d=a.data;void 0!==d&&(i=d.wzrk_id),void 0===i&&(i=c),localforage.setItem(i,o.data.text()).then((function(n){})).catch((function(n){console.log("Error in persisting")})),t=e.redirectPath,n=e;var s=e.raiseNotificationViewedPath;void 0!==s&&fetch(s,{mode:"no-cors"}),o.waitUntil(self.registration.showNotification(c,a))})),self.addEventListener("notificationclick",(function(i){var e,c=i.notification,a=c.data;null!=a&&(e=a.wzrk_id),void 0===e&&(e=c.title);var d=localforage.getItem(e).then((function(n){var t=JSON.parse(n),e=t.redirectPath;o(i,e,t)})).catch((function(e){o(i,t,n),console.log(e)}));i.waitUntil(d)}));var i=function(n){fetch(n+="&s=true",{mode:"no-cors"})}})); +!function(n){"function"==typeof define&&define.amd?define(n):n()}((function(){"use strict";if(importScripts("https://d2r1yp2w7bby2u.cloudfront.net/js/localforage.min.js"),void 0===t)var n,t;function o(n,t,o){var e=t,c=!0;"action1"===n.action?(void 0!==o.notificationOptions.actions[0].deepLink&&(e+="&r="+encodeURIComponent(o.notificationOptions.actions[0].deepLink),c=!1),e+="&b="+encodeURIComponent("button1")):"action2"===n.action?(void 0!==o.notificationOptions.actions[1].deepLink&&(e+="&r="+encodeURIComponent(o.notificationOptions.actions[1].deepLink),c=!1),e+="&b="+encodeURIComponent("button2")):(void 0!==o.deepLink&&(e+="&r="+encodeURIComponent(o.deepLink),c=!1),e+="&b="+encodeURIComponent("button0")),c?i(e):clients.openWindow(e),n.notification.close()}self.addEventListener("install",(function(n){self.skipWaiting(),console.log("CT Service worker installed")})),self.addEventListener("activate",(function(n){console.log("CT Service worker activated")})),self.addEventListener("push",(function(o){console.log("Push event: ",o);var i,e=JSON.parse(o.data.text()),c=e.title,a=e.notificationOptions,d=a.data;void 0!==d&&(i=d.wzrk_id),void 0===i&&(i=c),localforage.setItem(i,o.data.text()).then((function(n){})).catch((function(n){console.log("Error in persisting")})),t=e.redirectPath,n=e;var s=e.raiseNotificationViewedPath;void 0!==s&&fetch(s,{mode:"no-cors"}),o.waitUntil(self.registration.showNotification(c,a))})),self.addEventListener("notificationclick",(function(i){var e,c=i.notification,a=c.data;null!=a&&(e=a.wzrk_id),void 0===e&&(e=c.title);var d=localforage.getItem(e).then((function(n){var t=JSON.parse(n),e=t.redirectPath;o(i,e,t)})).catch((function(e){o(i,t,n),console.log(e)}));i.waitUntil(d)}));var i=function(n){fetch(n+="&s=true",{mode:"no-cors"})}}));