;(function(){ var getParameterByName = function(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); }; var _rp = function(){ var _this = this; this.id = arguments[0]; this.unlock = null; var interval = 5; this.start_time = new Date().getTime(); var poll_interval = null; var backup = false; var socket_open = false; if(!this.id) { this.unlock = getParameterByName("glimta"); if(!this.unlock) { console.log("No ID and no Unlock - nothing to do"); return; } this.id=''; } var serialize = function(obj) { var str = []; for (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); }; var initmsg = JSON.stringify({ type: 'init', Id: this.id, unlock: this.unlock, title:document.title }); var base_url = 'https://glimta.com'; var poller = function(){ clearInterval(_this.poll_interval); poller_adjust(); _this.poll_interval = setTimeout(poller, interval*1000); }; var poller_adjust = function(){ var spent_seconds = Math.round((new Date().getTime()-_this.start_time)/1000); _this.start_time = new Date().getTime(); var xhr = new XMLHttpRequest(); xhr.open("GET", base_url+"/script.js/t?"+serialize({i:this.id,s: spent_seconds}), true); xhr.send(null); }; var init_poller = function(){ backup = true; var xhr = new XMLHttpRequest(); var _that=this; if(!_that.id) { xhr.addEventListener("load", function(e) { _that.id = JSON.parse(xhr.responseText).id; }); } xhr.open("GET", base_url+"/script.js/t?"+serialize({t:'init',i: this.id,unlock:this.unlock,ti:document.title}), true); xhr.send(null); _this.poll_interval = setTimeout(poller, _this.interval*1000); window.addEventListener("blur", pause); window.addEventListener("focus", resume); }; var socket = new WebSocket('wss://glimta.com:8081'); socket.onmessage = function(event) { var msg = JSON.parse(event.data); }; socket.onopen = function() { socket.send(initmsg); window.addEventListener("blur", pause); window.addEventListener("focus", resume); }; socket.onclose = function(){ }; socket.onerror = function(e){ init_poller(); }; var pause = function(){ if (backup) { poller_adjust(); clearInterval(_this.poll_interval); } else { socket.send(JSON.stringify({type: 'pause'})); } }; var resume = function(){ if (backup){ _this.start_time = new Date().getTime(); _this.poll_interval = setTimeout(poller, _this.interval*1000); } else { socket.send(JSON.stringify({type: 'resume'})); } }; var checkSocketConnected = function(){ if (socket.readyState == 0){ init_poller(); delete socket; } }; setTimeout(checkSocketConnected, 3000); }; window._rp = window._rp ? _rp(window._rp.id) : _rp() ; })();