Skip to content

Instantly share code, notes, and snippets.

@stripedpurple
Last active November 14, 2019 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stripedpurple/26527718fb1e42ad78df9af7947c169d to your computer and use it in GitHub Desktop.
Save stripedpurple/26527718fb1e42ad78df9af7947c169d to your computer and use it in GitHub Desktop.
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n():"function"==typeof define&&define.amd?define(n):n()}(0,function(){"use strict";function e(e){var n=this.constructor;return this.then(function(t){return n.resolve(e()).then(function(){return t})},function(t){return n.resolve(e()).then(function(){return n.reject(t)})})}function n(e){return!(!e||"undefined"==typeof e.length)}function t(){}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=undefined,this._deferreds=[],c(e,this)}function r(e,n){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,o._immediateFn(function(){var t=1===e._state?n.onFulfilled:n.onRejected;if(null!==t){var o;try{o=t(e._value)}catch(r){return void f(n.promise,r)}i(n.promise,o)}else(1===e._state?i:f)(n.promise,e._value)})):e._deferreds.push(n)}function i(e,n){try{if(n===e)throw new TypeError("A promise cannot be resolved with itself.");if(n&&("object"==typeof n||"function"==typeof n)){var t=n.then;if(n instanceof o)return e._state=3,e._value=n,void u(e);if("function"==typeof t)return void c(function(e,n){return function(){e.apply(n,arguments)}}(t,n),e)}e._state=1,e._value=n,u(e)}catch(r){f(e,r)}}function f(e,n){e._state=2,e._value=n,u(e)}function u(e){2===e._state&&0===e._deferreds.length&&o._immediateFn(function(){e._handled||o._unhandledRejectionFn(e._value)});for(var n=0,t=e._deferreds.length;t>n;n++)r(e,e._deferreds[n]);e._deferreds=null}function c(e,n){var t=!1;try{e(function(e){t||(t=!0,i(n,e))},function(e){t||(t=!0,f(n,e))})}catch(o){if(t)return;t=!0,f(n,o)}}var a=setTimeout;o.prototype["catch"]=function(e){return this.then(null,e)},o.prototype.then=function(e,n){var o=new this.constructor(t);return r(this,new function(e,n,t){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof n?n:null,this.promise=t}(e,n,o)),o},o.prototype["finally"]=e,o.all=function(e){return new o(function(t,o){function r(e,n){try{if(n&&("object"==typeof n||"function"==typeof n)){var u=n.then;if("function"==typeof u)return void u.call(n,function(n){r(e,n)},o)}i[e]=n,0==--f&&t(i)}catch(c){o(c)}}if(!n(e))return o(new TypeError("Promise.all accepts an array"));var i=Array.prototype.slice.call(e);if(0===i.length)return t([]);for(var f=i.length,u=0;i.length>u;u++)r(u,i[u])})},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o(function(n){n(e)})},o.reject=function(e){return new o(function(n,t){t(e)})},o.race=function(e){return new o(function(t,r){if(!n(e))return r(new TypeError("Promise.race accepts an array"));for(var i=0,f=e.length;f>i;i++)o.resolve(e[i]).then(t,r)})},o._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){a(e,0)},o._unhandledRejectionFn=function(e){void 0!==console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype["finally"]||(l.Promise.prototype["finally"]=e):l.Promise=o});(function(root,factory){if(typeof define==="function"&&define.amd){define([],function(){return root.CallTrack=factory()})}else{root.CallTrack=factory()}})(typeof self!=="undefined"?self:this,function(){Array.prototype.findIndex=Array.prototype.findIndex||function(callback){if(this===null){throw new TypeError("Array.prototype.findIndex called on null or undefined")}else if(typeof callback!=="function"){throw new TypeError("callback must be a function")}var list=Object(this);var length=list.length>>>0;var thisArg=arguments[1];for(var i=0;i<length;i++){if(callback.call(thisArg,list[i],i,list)){return i}}return-1};var CallTrack={association:1933,active:true,regex:"",continuousNumberSwap:false,rules:[],brandedTerms:[""],ignoredIPs:[],imgPath:"",numbersToReplace:[],socialSites:{facebook:["facebook.com","fb.com","test.facebook.com"],twitter:["twitter.com","t.co"],linkedin:["linkedin.com","lnkd.in"],instagram:["instagram.com"],pinterest:["pinterest.com"],"google+":["googleplus.com","plus.google.com"],youtube:["youtube.com"],tumblr:["tumblr.com"],yelp:["yelp.com"]},ga:{term:null,source:null,medium:null},referrer:undefined,init:function(){if(!this.active)return;this.parseRules=this.parseRules.bind(this);this.replace=this.replace.bind(this);this.parseInfo=this.parseInfo.bind(this);this.referrer=CallTrack._.getReferrer();this.info().then(this.parseInfo).then(this.parseRules).then(this.replace);if(this.continuousNumberSwap){var origBody=document.body.innerHTML;setInterval(function(){if(origBody!=document.body.innerHTML){origBody=document.body.innerHTML;CallTrack.replace()}},5e3)}},info:function(){var vm=this;return new Promise(function(resolve,reject){var info=vm.Cookie.get("fx_info",true);if(!info||vm._.getUrlParameter("gclid")){vm._.ajax({type:"POST",url:("https:"==document.location.protocol?"https://":"http://")+"us-east1-idyllic-vehicle-159522.cloudfunctions.net/mcfx-visitor-information",data:JSON.stringify({referrer:vm.referrer}),headers:{"Content-Type":"application/json"}}).then(function(response){var info=JSON.parse(response);vm.Cookie.set("fx_info",info,{expires:7});resolve(info)},function(err){reject(err)})}else{resolve(info)}})},parseInfo:function(info){CallTrack.ga=info;var source=CallTrack._.getUrlParameter("utm_source");var medium=CallTrack._.getUrlParameter("utm_medium");if(source){CallTrack.ga.source=source;CallTrack.Cookie.set("utm_source",source,{expires:1})}else if(CallTrack.Cookie.get("utm_source")){CallTrack.ga.source=CallTrack.Cookie.get("utm_source")}if(medium){CallTrack.ga.medium=medium;CallTrack.Cookie.set("utm_source",medium,{expires:1})}else if(CallTrack.Cookie.get("utm_medium")){CallTrack.ga.medium=CallTrack.Cookie.get("utm_medium")}return CallTrack.ga},parseRules:function(){var cache=CallTrack.Cookie.get("MCFXNumberSwap",true);if(cache){CallTrack.numbersToReplace=CallTrack.addRegexRules(cache);return cache}var numbersMatched=[];var numbersToReplace=[];CallTrack.rules.forEach(function(rule){if(-1!==numbersMatched.findIndex(function(number){return number===rule.number.join(":")}))return;if(CallTrack.matchRule(rule)){numbersToReplace.push(rule);numbersMatched.push(rule.number.join(":"))}});CallTrack.Cookie.set("MCFXNumberSwap",numbersToReplace,{expires:7});CallTrack.numbersToReplace=CallTrack.addRegexRules(numbersToReplace);return numbersToReplace},matchRule:function(rule){switch(rule.type){case"referrer":return CallTrack.matchReferrer(rule);case"search":return CallTrack.matchSearch(rule);case"social":return CallTrack.matchSocial(rule);case"landingPage":return CallTrack.matchLandingPage(rule);case"urlParam":case"landingParam":return CallTrack.matchUrlParam(rule);case"cookie":return CallTrack.matchCookie(rule);case"direct":return CallTrack.isDirect(rule);case"source":return CallTrack.matchSource(rule);case"region":return CallTrack.matchRegion(rule);case"city":return CallTrack.matchCity(rule);case"country":return CallTrack.matchCountry(rule)}},replace:function(rules){if(rules.length===0)return;if(CallTrack.ignoredIPs.length>0&&CallTrack.ignoredIPs.indexOf(CallTrack.ga.ip)!==-1){return}var content=document.querySelector("body");if(!content){if(!CallTrack.continuousNumberSwap){setTimeout(function(){CallTrack.replace(rules)},100)}return}var iterator=document.createNodeIterator(content,NodeFilter.SHOW_TEXT,CallTrack.testNode,true);var node=iterator.nextNode();while(node){node=iterator.nextNode()}var images=document.querySelectorAll(".img-phone-swap");images.forEach(function(image){image.setAttribute("src",CallTrack.numbersToReplace[0].imgPath)})},testNode:function(node){if(node.nodeType!==3){return NodeFilter.FILTER_SKIP}for(var i=0;i<CallTrack.numbersToReplace.length;i++){var rule=CallTrack.numbersToReplace[i];var skipCauseEmpty=false;for(var n=0;n<rule.number.length;n++){if(!rule.number[n]||rule.number[n]===null||rule.number[n]===""||rule.number[n].length<2){skipCauseEmpty=true;break}}if(!skipCauseEmpty&&rule.search.test(node.textContent)){if(rule.replace.toLowerCase()==="queue"){CallTrack.Queue.type=rule.type;CallTrack.Queue.getNumber().then(function(number){if(number)return CallTrack.Queue.modifyReplacement(number,i)}).then(function(rule){CallTrack.modifyNode(node,rule)})}else{CallTrack.modifyNode(node,rule)}break}}return NodeFilter.FILTER_ACCEPT},modifyNode:function(node,rule){node.nodeValue=node.nodeValue.replace(rule.search,rule.replace);if("undefined"!==typeof node.parentElement&&node.parentElement!==null){var href=node.parentElement.getAttribute("href");if(href!==null&&href.substr(0,4)==="tel:"){node.parentElement.setAttribute("href","tel:"+rule.tel)}}},addRegexRules:function(rules){var re=/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/;return rules.map(function(rule){if(rule.replace.toLowerCase==="queue")return rule;var replace=rule.replace.replace("+1","");rule.search=new RegExp(rule.number.join("|").replace(/(?=[()+ ])/g,"\\"),"gi");rule.replace=replace.replace(re,CallTrack.regex);rule.tel="+1"+replace.replace(re,"$1$2$3");var path=CallTrack.imgPath===""||CallTrack.imgPath[CallTrack.imgPath.length-1]!=="/"?CallTrack.imgPath+"/":CallTrack.imgPath;rule.imgPath=path+replace.replace(re,"$1$2$3")+".png";return rule})},isOrganic:function(){return CallTrack.ga.medium==="organic"},isDirect:function(){return CallTrack.ga.source==="direct"},isBranded:function(){if(CallTrack.ga!=null){for(var j=0;j<CallTrack.brandedTerms.length;j++){if(CallTrack.ga.term.toLowerCase().indexOf(CallTrack.brandedTerms[j].toLowerCase())!=-1)return true}}return false},isPPC:function(){return CallTrack.ga.medium==="ppc"},matchReferrer:function(rule){if(rule.match==="all")return true;return CallTrack.referrer!=null&&CallTrack.referrer.indexOf(rule.match)!=-1},matchSearch:function(rule){if(CallTrack.matchSource(rule)){if(CallTrack.matchMedium(rule)){if(CallTrack.matchSegment(rule)){return true}}}return false},matchMedium:function(rule){var match=rule.match;if("undefined"!==typeof rule.matchValue){var m=rule.matchValue.split("-");match=m[0].trim()}if(match==="all")return true;if(match==="organic")return CallTrack.isOrganic();if(match==="paid"||match==="ppc")return CallTrack.isPPC();if(match==="notprov")return CallTrack.matchSegment("notprov")},matchSegment:function(rule){var match=rule.match;if("undefined"!==typeof rule.matchValue){var m=rule.matchValue.split("-");match=m[1].trim()}if(match==="all")return true;if(match==="branded")return CallTrack.isBranded();if(match==="unbranded")return!CallTrack.isBranded();if(match==="notprov")return CallTrack.ga.term==="not provided";if(CallTrack.ga.term==="not provided")return false},matchSocial:function(rule){if(!CallTrack.referrer||CallTrack.referrer=="")return false;var referringDomain=CallTrack.referrer.split("/")[2];referringDomain=referringDomain.replace(/^www\./i,"");if(!referringDomain||referringDomain=="")return false;if(rule.match!=="all"){return-1!==CallTrack.socialSites[rule.match].findIndex(function(d){return d===referringDomain})}else for(var domains in CallTrack.socialSites){if(-1!==domains.findIndex(function(d){return d===referringDomain})){return true}}return false},matchLandingPage:function(rule){return window.location.pathname==rule.match},matchUrlParam:function(rule){var param=CallTrack._.getUrlParameter(rule.match);if(param===null)return false;if(param==="")return true;return param.indexOf(rule.matchValue)!==-1},matchCookie:function(rule){var param=CallTrack.Cookie.get(rule.match);if(param===null)return false;if(param==="")return true;return param.indexOf(rule.matchValue)!==-1},matchRegion:function(rule){if(rule.matchValue!=="equals"){return rule.match.toLowerCase()===CallTrack.ga.location.region?false:true}return rule.match.toLowerCase()===CallTrack.ga.location.region},matchCity:function(rule){var matchTo=rule.match.toLowerCase().split(","),isCity,isRegion;if(rule.matchValue!=="equals"){if(matchTo.length===2){isCity=matchTo[0].toLowerCase().trim()===CallTrack.ga.location.city,isRegion=matchTo[1].toLowerCase().trim()===CallTrack.ga.location.city;return isCity&&isRegion?false:true}return matchTo[0].toLowerCase().trim()===CallTrack.ga.location.city?false:true}if(matchTo.length===2){isCity=matchTo[0].toLowerCase().trim()===CallTrack.ga.location.city,isRegion=matchTo[1].toLowerCase().trim()===CallTrack.ga.location.city;return isCity&&isRegion}return matchTo[0].toLowerCase().trim()===CallTrack.ga.location.city},matchCountry:function(rule){if(rule.matchValue!=="equals"){return rule.match.toUpperCase()===CallTrack.ga.location.country?false:true}return rule.match.toUpperCase()===CallTrack.ga.location.country},matchSource:function(rule){if(rule.match==="all"){return true}return CallTrack.ga.source==rule.match},Cookie:{converter:function(){},defaults:{path:"/"},set:function(key,value,attributes){if(typeof document==="undefined"){return}attributes=CallTrack.Cookie.extend({domain:"."+CallTrack._.getDomainName()},CallTrack.Cookie.defaults,attributes);if(typeof attributes.expires==="number"){attributes.expires=new Date(new Date*1+attributes.expires*864e5)}attributes.expires=attributes.expires?attributes.expires.toUTCString():"";try{var result=JSON.stringify(value);if(/^[\{\[]/.test(result)){value=result}}catch(e){}value=CallTrack.Cookie.converter.write?CallTrack.Cookie.converter.write(value,key):encodeURIComponent(String(value)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent);key=encodeURIComponent(String(key)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var stringifiedAttributes="";for(var attributeName in attributes){if(!attributes[attributeName]){continue}stringifiedAttributes+="; "+attributeName;if(attributes[attributeName]===true){continue}stringifiedAttributes+="="+attributes[attributeName].split(";")[0]}return document.cookie=key+"="+value+stringifiedAttributes},get:function(key,json){if(typeof document==="undefined"){return}var jar={};var cookies=document.cookie?document.cookie.split("; "):[];var i=0;for(;i<cookies.length;i++){var parts=cookies[i].split("=");var cookie=parts.slice(1).join("=");if(!json&&cookie.charAt(0)==='"'){cookie=cookie.slice(1,-1)}try{var name=CallTrack.Cookie.decode(parts[0]);cookie=(CallTrack.Cookie.converter.read||CallTrack.Cookie.converter)(cookie,name)||CallTrack.Cookie.decode(cookie);if(json){try{cookie=JSON.parse(cookie)}catch(e){}}jar[name]=cookie;if(key===name){break}}catch(e){}}return key?jar[key]:jar},extend:function(){var i=0;var result={};for(;i<arguments.length;i++){var attributes=arguments[i];for(var key in attributes){result[key]=attributes[key]}}return result},decode:function(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}},Queue:{type:null,getNumber:function(){return new Promise(function(resolve,reject){CallTrack._.ajax({type:"POST",url:("https:"==document.location.protocol?"https://":"http://")+"api.leadmanagerfx.com/phonelease/get/"+CallTrack.association,data:CallTrack.Queue.generateUniqueRequest(),headers:{"Content-type":"application/x-www-form-urlencoded"}}).then(function(response){response=JSON.parse(response);var expires=response.expires;var number=response.number;CallTrack.Cookie.set("ctfxExpires",expires,{expires:365*2});resolve(number)},function(err){reject(err)})})},modifyReplacement:function(number,ruleIndex){var rules=CallTrack.Cookie.get("MCFXNumberSwap",true);rules[ruleIndex].replace=number;CallTrack.Cookie.set("MCFXNumberSwap",rules,{expires:7});CallTrack.numbersToReplace=CallTrack.addRegexRules(rules);return rules[ruleIndex]},generateUniqueRequest:function(){var request=null;if(CallTrack.Cookie.get("ctfxRequest")!=null&&!CallTrack.Queue.isExpired()){request=CallTrack.Cookie.get("ctfxRequest")}else{var visits=Number(CallTrack.Cookie.get("fx_count"));var id=CallTrack.Cookie.get("fx_uuid");var type=CallTrack.Queue.type;var data="";data+="ga_count="+visits+"&";data+="ga_id="+id+"&";data+="page="+window.location.href.replace(/^(?:\/\/|[^\/]+)*/,"")+"&";data+="&fx_document_title="+encodeURIComponent(document.title);data+="&fx_referrer="+encodeURIComponent(CallTrack._.getReferrer());data+="&type="+type;CallTrack.Cookie.set("ctfxRequest",data,{expires:365*2});request=data}return request},isExpired:function(){var expires=CallTrack.Cookie.get("ctfxExpires");if(expires==null){return true}return parseInt((new Date).getTime()/1e3)-parseInt(expires)>0}},_:{getUrlParameter:function(name){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regex=new RegExp("[\\?&]"+name+"=([^&#]*)");var results=regex.exec(location.search);return results===null?null:decodeURIComponent(results[1].replace(/\+/g," "))},getReferrer:function(){var ref=document.referrer,cookieRef=CallTrack.Cookie.get("fx_referrer");if(cookieRef!=undefined){ref=cookieRef}else{CallTrack.Cookie.set("fx_referrer",ref,{expires:7})}return ref},ajax:function(args){args.type=args.type.toUpperCase()||"GET";return new Promise(function(resolve,reject){var req=new XMLHttpRequest;req.open(args.type,args.url);if(args.headers){Object.keys(args.headers).forEach(function(header){req.setRequestHeader(header,args.headers[header])})}req.onload=function(){if(req.status==200){resolve(req.response)}else{reject(Error(req.statusText))}};req.onerror=function(){reject(Error("Network Error"))};if(args.data)req.send(args.data);else req.send()})},uuid4:function(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options==="binary"?new Array(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||CallTrack._.rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii]}}return buf||CallTrack._.bytesToUuid(rnds)},bytesToUuid:function(buf,offset){if(!this.byteToHex){this.byteToHex=[];for(var i=0;i<256;++i){this.byteToHex[i]=(i+256).toString(16).substr(1)}}var i=offset||0;var bth=this.byteToHex;return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join("")},rng:function(){var getRandomValues=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){var rnds8=new Uint8Array(16);getRandomValues(rnds8);return rnds8}else{var rnds=new Array(16);for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;rnds[i]=r>>>((i&3)<<3)&255}return rnds}},getDomainName:function(){if(typeof CallTrack._.domain!=="undefined"&&CallTrack._.domain!=="")return CallTrack._.domain;var i=0,domain=document.domain,p=domain.split("."),s="_gd"+(new Date).getTime();while(i<p.length-1&&document.cookie.indexOf(s+"="+s)==-1){domain=p.slice(-1-++i).join(".");document.cookie=s+"="+s+";domain="+domain+";"}document.cookie=s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";CallTrack._.domain=domain;return CallTrack._.domain}}};CallTrack.init();return CallTrack});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment