(function(){if(void 0!==window._background)console.warn('content: Stop here, cause a second Tampermonkey instance was detected!\nThis can be caused by using "document.write" at Userscripts.\nSee https://code.google.com/p/chromium/issues/detail?id=253388 for more information');else{var q={_background:!0,Converter:null,Eventing:null,D:!1,CV:!1,USV:!1};(function(){for(var c in q)q.hasOwnProperty(c)&&(window[c]=q[c])})();var H=function(){var c={},e={webkitStorageInfo:!0,JSHINT:!0,webkitIDBTransaction:!0,
webkitIDBRequest:!0,webkitIDBObjectStore:!0,webkitIDBKeyRange:!0,webkitIDBIndex:!0,webkitIDBFactory:!0,webkitIDBDatabase:!0,webkitIDBCursor:!0,webkitIndexedDB:!0},b=Object.getOwnPropertyNames(window),a;a=window;for(var d=[];a=Object.getPrototypeOf(a);)d=d.concat(Object.getOwnPropertyNames(a));a=d;for(var d=0,f=null;f=a[d];d++)e[f]||q[f]||(2<f.length&&"on"===f.substr(0,2)?c[f]={proto:!0,event:!0}:c[f]={proto:!0});for(d=0;f=b[d];d++)e[f]||q[f]||c[f]||(c[f]={window:!0});return c};Registry.require("prepare");
Registry.require("xmlhttprequest");Registry.require("convert");Registry.require("helper");var k=Registry.get("helper"),s=k.clean;Converter=Registry.get("convert");var I={scriptBlocker:!1,proxy:!1},r=null,m=!1,t=!1,z=!1,u=!1,A=function(){D&&console.log("content: detected DOMContentLoaded "+Eventing.contextId);z=!0;m&&g.sendMessage("Context.domContentLoaded = true; if (typeof runAllLoadListeners !== 'undefined') runAllLoadListeners();")},B=function(c){u||(D&&console.log("content: first DOMNodeInserted "+
Eventing.contextId),u=!0)},g=function(){var c={},e=k.createUUID();return{backupProps:function(){var b=["var backup = {safeWindow: {},safeDocument: {},String: String,Array: Array,Uint8Array: Uint8Array,JSON: JSON,Math: Math,Event: Event,MutationEvent: MutationEvent,console: console,location: location,eval: eval};(",function(){["createEvent","createElement","dispatchEvent","addEventListener","removeEventListener"].forEach(function(a){var b=document[a];backup.safeDocument[a]=function(){return b.apply(document,
arguments)}})}.toString(),")();(",function(){"postMessage addEventListener removeEventListener setTimeout setInterval clearTimeout clearInterval alert confirm encodeURIComponent decodeURIComponent escape unescape atob btoa".split(" ").forEach(function(a){var b=window[a];backup.safeWindow[a]=function(){return b.apply(window,arguments)}})}.toString(),')();try { Object.defineProperties(window, {"',e,'": {enumerable: false,writable: false,configurable: false,value: backup}}); } catch (e) {}'].join(""),
a=document.createElement("script");a.textContent=["(function TM_back() {",b,"})();"].join("");(document.head||document.body||document.documentElement||document).appendChild(a);a.parentNode.removeChild(a)},initEnv:function(){var b=["var Context = (function() {\nvar self = {};\nwith (self) {\nvar copy = function(src) {\nvar props = Object.getOwnPropertyNames(src);\nfor (var ii=0, kk=null; (kk=props[ii]) !== undefined; ii++) {\nself[kk] = src[kk];\n};\n};","copy(window['"+e+"']);","copy({\nContext: self,\nexec: function(s) { (new Function(['with (this) { (function() {', s, '})();}'].join(''))).call(self); },\nV:\nfalse\n,\nENV:\nfalse\n,\nTS:\nfalse\n,\nD:",
D?"true":"false",",\nConverter:",k.serialize(Converter),",\nuse:",JSON.stringify(I),",\nwindowProps:",JSON.stringify(H()),",\nisIncognito:",chrome.extension.inIncognitoContext,",\n_background: false,\nEventing: (",k.serialize(C),")()\n});","Eventing.init('"+Eventing.contextId+"', self);","var cleanup = function(evt) {\nEventing.cleanup();\nsafeWindow.removeEventListener('unload', cleanup, false);\n};\nsafeWindow.addEventListener.apply('unload', cleanup, false);\n};\nreturn self;\n})();"].join("\n"),
a=document.createElement("script");a.textContent=["(function TM_mother() {",b,"})();"].join("");(document.head||document.body||document.documentElement||document).appendChild(a);a.parentNode.removeChild(a)},sendMessage:function(b){Eventing.fireEvent(b)},getResponseId:function(b){var a=0;if(b){for(;0==a||void 0!=c[a];)a=k.createUUID();c[a]=b}return a},runResponse:function(b,a){for(var d in c)if(d==b){var f="";try{if(f=JSON.parse(Converter.decode(a)),c[d])c[d](f);else console.log("Warn: content: responseId "+
d+" is undefined!!!")}catch(v){console.log("content: Json parse error (runResponse):"+v+"\n"+a)}c[d]=null;return}console.log("WARN: responseId "+b+" not found!")}}}(),J=function(){var c=Context.tmCE,e=function(a){return void 0===a||null===a?a:String(a)},b={},a=[],d=[],f={key:"##REPLACE_KEY##",clean:function(){b={};a=[];d=[]},runUpdateListeners:function(a,b,c){for(var f=0;f<d.length;f++){var e=d[f];try{e(a,b,c)}catch(l){console.log("emu: Error (runUpdateListeners):"+l+"\n"+e.toString())}}},runRequestHandlers:function(b,
d,e,w){for(var n=0;n<a.length;n++){var l=a[n];try{l(b,d,function(a){c.onResponse(f.key,w,e,JSON.stringify(a))})}catch(g){console.log("emu: Error (runRequestHandlers):"+g+"\n"+l.toString())}}},runContentRequestHandlers:function(b,d,e,w){for(var n=0;n<a.length;n++){var l=a[n];try{l(b,d,function(a){c.onContentResponse(f.key,w,e,JSON.stringify(a))})}catch(g){console.log("emu: Error (runContentRequestHandlers):"+g+"\n"+l.toString())}}},runRequest:function(a,b,c){try{var d=JSON.parse(Converter.decode(b));
f.runRequestHandlers(d.request,d.sender,a,c)}catch(e){console.log("emu: Json parse error (runRequest):"+e+"\n"+b)}},runContentRequest:function(a,b,c){try{var d=JSON.parse(Converter.decode(b));f.runContentRequestHandlers(d.request,d.sender,a,c)}catch(e){console.log("emu: Json parse error (runContentRequest):"+e+"\n"+b)}},runResponse:function(a,d){try{for(var c in b)if(c==a){var f="";try{f=JSON.parse(Converter.decode(d)),b[c](f)}catch(e){console.log("emu: Json parse error (runResponse):"+e+"\n"+d)}delete b[c];
return}}catch(l){console.log("emu: Json parse error (runResponse):"+l+"\n"+d)}console.log("WARN: emu: responseId "+a+" not found!")},runConnectResponse:function(a,d){try{for(var c in b)if(c==a){var f="",e=!1;try{f=JSON.parse(Converter.decode(d)),b[c](f),e=f.onDisconnect}catch(l){console.log("emu: Json parse error (runConnectResponse):"+l+"\n"+d)}e&&(b[c]=null);return}}catch(g){console.log("emu: Json parse error (runConnectResponse):"+g+"\n"+d)}console.log("WARN: emu: responseId "+a+" not found!")},
getResponseId:function(a){var d=0;if(a){for(;0==d||void 0!=b[d];)d=((new Date).getTime()+Math.floor(19831206*Math.random()+1)).toString();b[d]=a}return d},extension:{getURL:function(a){return e(c.getUrl(f.key,a))},connect:function(a){var b=[],d=[],e={notifyListeners:function(a,b){for(var d=0;d<a.length;d++)a[d](b)},postMessage:function(a){c.sendExtensionPortMessage(f.key,JSON.stringify(a),g)},onMessage:{addListener:function(a){b.push(a)}},onDisconnect:{addListener:function(a){d.push(a)}},disconnect:function(){e=
d=b=null}},g=f.getResponseId(function(a){a.onMessage?e&&e.notifyListeners(b,a.msg):a.onDisconnect&&e&&(e.notifyListeners(d),e=null)});c.sendExtensionConnect(f.key,JSON.stringify(a),g);return e},sendMessage:function(a,b){var d=f.getResponseId(b);c.sendExtensionMessage(f.key,JSON.stringify(a),d)},onMessage:{addListener:function(b){a.push(b)}}},i18n:{getMessage:function(){for(var a=[],b=0;b<arguments.length;b++)a.push(arguments[b]);a=c.getMessage(f.key,JSON.stringify(a));return e(a)}},tabs:{sendMessage:function(a,
b,d){d=f.getResponseId(d);c.sendTabsRequest(f.key,a,JSON.stringify(b),d)},create:function(a){c.createTab(f.key,JSON.stringify(a))},query:function(a,b){var d=f.getResponseId(b);c.queryTab(f.key,JSON.stringify(a),d)},update:function(a,b){c.updateTab(f.key,a,b)},onUpdated:{addListener:function(a){d.push(a)}}}};return f},E=function(){var c={ports:{},getArgs:function(c){return c},log:function(c){_background?console.log("content: "+c):Eventing.fireEvent({fn:"log",args:"page: "+c})},onContentResponse:function(e,
b,a,d){_background?g.runResponse(a,Converter.encode(d)):Eventing.fireEvent({fn:"onContentResponse",args:c.getArgs(arguments)})},onResponse:function(e,b,a,d){if(_background)try{var f=Converter.encode(d);g.sendMessage("Context.chromeEmu.runResponse('"+a+"', \""+f+'")')}catch(v){console.log("Error: processing onResponse")}else Eventing.fireEvent({fn:"onResponse",args:c.getArgs(arguments)})},onConnectResponse:function(e,b,a,d){if(_background)try{var f=Converter.encode(d);g.sendMessage("Context.chromeEmu.runConnectResponse('"+
a+"', \""+f+'")')}catch(v){console.log("Error: processing onConnectResponse")}else Eventing.fireEvent({fn:"onConnectResponse",args:c.getArgs(arguments)})},onContentRequest:function(c,b,a){_background?c.id&&this.id&&c.id!=this.id||(c=Converter.encode(JSON.stringify({sender:b,request:c})),g.sendMessage("Context.chromeEmu.runContentRequest('"+a+"', \""+c+'", 0);')):console.log("Warn: onContentRequest from non BG not supported")},onMessage:function(c,b,a){_background?c.id&&this.id&&c.id!=this.id||(c=
Converter.encode(JSON.stringify({sender:b,request:c})),g.sendMessage("Context.chromeEmu.runRequest('"+a+"', \""+c+'", 0)')):console.log("Warn: onMessage from non BG not supported")},runUpdateListener:function(){console.log("WARN: not supported!")},getUrl:function(){console.log("WARN: not supported!")},sendExtensionMessage:function(e,b,a){if(_background){var d=JSON.parse(b);d.responseId=a;chrome.extension.sendMessage(d,function(b){c.onResponse(e,0,a,JSON.stringify(b))});d=null}else Eventing.fireEvent({fn:"sendExtensionMessage",
args:c.getArgs(arguments)})},sendExtensionConnect:function(e,b,a){if(_background){var d=JSON.parse(b);d.responseId=a;var f=chrome.extension.connect({name:d});f.onMessage.addListener(function(b){c.onConnectResponse(e,0,a,JSON.stringify({onMessage:!0,msg:b}))});f.onDisconnect.addListener(function(b){c.onConnectResponse(e,0,a,JSON.stringify({onDisconnect:!0}));d=null});c.ports[a]=f}else Eventing.fireEvent({fn:"sendExtensionConnect",args:c.getArgs(arguments)})},sendExtensionPortMessage:function(e,b,a){if(_background){var d=
c.ports[a];if(d){var f=JSON.parse(b);f.responseId=a;d.postMessage(f)}else this.log("Error: sendExtensionPortMessage unable to find port "+a)}else Eventing.fireEvent({fn:"sendExtensionPortMessage",args:c.getArgs(arguments)})},sendTabsRequest:function(){console.log("WARN: not supported!")},createTab:function(){console.log("WARN: not supported!")},queryTab:function(){console.log("WARN: not supported!")},updateTab:function(){console.log("WARN: not supported!")},onUpdated:function(){console.log("WARN: not supported!")},
getMessage:function(){console.log("WARN: not supported!")},storageKey:function(){console.log("WARN: not supported!")},storageRemoveItem:function(){console.log("WARN: not supported!")},storageSetItem:function(){console.log("WARN: not supported!")},storageGetItem:function(){console.log("WARN: not supported!")},storageLength:function(){console.log("WARN: not supported!")}};return c},p=new E,C=function(){var c=function(a){return Context.exec(a)},e={safeWindow:window,safeDocument:document},b={topframe:window.self===
window.top,contextId:null,rEventId:null,sEventId:null,eventSource:null,log:function(a,b,c,e){console.log((_background?"content":"page")+":"+a,b,c,e)},postMessageEventSource:{executor:c,element:{dispatchEvent:function(a){return e.safeWindow.postMessage.apply(document,[a,"*"])},addEventListener:function(a,b){return e.safeWindow.addEventListener("message",function(c){c.source==window&&c.data.id==a&&b(c)},!1)},removeEventListener:function(a,b){return e.safeWindow.removeEventListener("message",b)}},event:{encode:function(a,
b){return{id:a,json:JSON.stringify(b)}},decode:function(a){return JSON.parse(a.data.json)}}},standardEventSource:{executor:c,element:{dispatchEvent:function(){return e.safeDocument.dispatchEvent.apply(document,arguments)},addEventListener:function(){return e.safeDocument.addEventListener.apply(document,arguments)},removeEventListener:function(){return e.safeDocument.removeEventListener.apply(document,arguments)}},event:{encode:function(a,b){var c=e.safeDocument.createEvent("MutationEvent");c.initMutationEvent(a,
!1,!1,null,null,null,Converter.encodeR(JSON.stringify(b)),c.ADDITION);return c},decode:function(a){return JSON.parse(Converter.decodeR(a.attrName))}}},init:function(a,c){e=c||e;b.contextId=a;b.contextId?(_background?(b.rEventId="TM_toContent",b.sEventId="TM_toPage",b.eventHandler=b.eventHandlerContent):(b.rEventId="TM_toPage",b.sEventId="TM_toContent",b.eventHandler=b.eventHandlerPage),b.eventSource=b.standardEventSource,b.registerListener()):b.log("Eventing.init() failed!!!")},fireEvent:function(a,
c){void 0==c&&(c=b.sEventId+b.contextId);try{var f=b.eventSource.event.encode(c,a);b.eventSource.element.dispatchEvent(f)}catch(e){b.log("Error: fire event",c,"->",a,e)}},registerListener:function(){b.eventSource.element.addEventListener(b.rEventId+b.contextId,b.eventHandler,!1)},eventHandlerPage:function(a){try{var c=b.eventSource.event.decode(a);try{b.eventSource.executor(c)}catch(e){console.log("page: Error: processing event! ",e.message,{fn:c})}}catch(g){b.log("Error: retrieving event!",g.message),
b.log(a)}},eventHandlerContent:function(a){try{var c=b.eventSource.event.decode(a);try{for(var e=[],g=0,h;void 0!==(h=c.args[g]);g++)e.push(h);p[c.fn].apply(this,e)}catch(k){b.log("Error: processing event!",k.message,c)}}catch(m){b.log("Error: retrieving event!",m.message),b.log(a)}},cleanup:function(){b.eventSource&&b.eventSource.element.removeEventListener(b.rEventId+b.contextId,b.eventHandler,!1)}};return b};Eventing=new C;var h={init:function(){window.addEventListener("load",h.runHlp,!1);window.addEventListener("DOMNodeInserted",
h.runHlp,!1);window.addEventListener("DOMContentLoaded",h.runHlp,!1)},runHlp:function(c){m||(h.cleanupHlp(),h.run())},run:function(){if(!m){var c;c=""+("var logLevel = "+r+";\n");var e="";try{e="("+Registry.getRaw("environment.js")+")();\n"}catch(b){}var a="Context.chromeEmu = ("+k.serialize(J)+")();\n",d="Context.tmCE = ("+k.serialize(E)+")();\nvar Event = function() {};\n",f="var TM_context_id = '"+Eventing.contextId+"';\n",h="";g.sendMessage("console.log('Tampermonkey started');");z?(h+="Context.loadHappened = true;\nContext.domContentLoaded = true;\n",
D&&console.log("content: Start ENV with DOMContentLoaded "+Eventing.contextId)):u&&(h="Context.loadHappened = true;\n",D&&console.log("content: Start ENV with loadHappened "+Eventing.contextId));g.sendMessage("(function () { "+c+f+d+a+e+h+"})();");m=!0}},cleanupHlp:function(){m||(window.removeEventListener("load",h.runHlp,!1),window.removeEventListener("DOMNodeInserted",h.runHlp,!1),window.removeEventListener("DOMContentLoaded",h.runHlp,!1))}},x=function(c){chrome.extension.sendMessage({method:"unLoad",
id:Eventing.contextId,topframe:Eventing.topframe,forced:!!c,url:window.location.origin+window.location.pathname,params:window.location.search+window.location.hash},function(b){});try{Eventing.cleanup(),h.cleanupHlp()}catch(e){console.log("cleanup: Error: "+e.message)}window.removeEventListener("DOMContentLoaded",A,!1);window.removeEventListener("DOMNodeInserted",B,!1);window.removeEventListener("unload",x,!1);null!=s?(s.finalize(),s=null):console.log("content: Warning: multiple unload events detected!!!")},
F=function(c,e,b){if(!m)return window.setTimeout(function(){F(c,e,b)},10),!0;if(t){var a=g.getResponseId(b);p.onContentRequest(c,e,a)}else"getSrc"==c.method?b({src:k.getSource(document)}):"reload"==c.method?window.location.reload():"confirm"==c.method?window.setTimeout(function(){var a=confirm(c.msg);b({confirm:a})},100):"showMsg"==c.method&&window.setTimeout(function(){window.setTimeout(function(){alert(c.msg)},1);b({})},100);return!0};window.addEventListener("DOMContentLoaded",A,!1);window.addEventListener("DOMNodeInserted",
B,!1);var y=1,G=function(){g.backupProps();p.id=k.createUUID();window.addEventListener("unload",x,!1);chrome.extension.onMessage.addListener(F);chrome.extension.sendMessage({method:"prepare",id:p.id,raw:[],topframe:Eventing.topframe,url:window.location.origin+window.location.pathname,params:window.location.search+window.location.hash},function(c){void 0===c?(D&&console.debug("content: _early_ execution, connection to bg failed -> retry!"),window.setTimeout(G,y),y*=2):(r=c.logLevel,D|=60<=r,c.enabledScriptsCount?
(Eventing.init(p.id),g.initEnv(),D&&console.log("content: Started ("+Eventing.contextId+", "+window.location.origin+window.location.pathname+")"),m&&g.sendMessage("Context.adjustLogLevel("+r+");\n"),D&&console.log("content: start event processing for "+Eventing.contextId+" ("+c.enabledScriptsCount+" to run)"),t=!0,h.runHlp()):(D&&console.log("content: disable event processing for "+p.id),h.cleanupHlp(),x(!0),t=!1,m=!0))})};(function(c){var e=function(){"prerender"!==document.webkitVisibilityState&&
(document.removeEventListener("webkitvisibilitychange",e,!1),c())};"prerender"!==document.webkitVisibilityState?c():document.addEventListener("webkitvisibilitychange",e,!1)})(G)}})();
