"use strict";(function(e){if(typeof define==="function"&&define["amd"]){define(["exports"],e)}else{e(window["jleader"]={})}})(function(e,t){var n,r="_jleaderPeers",a="_jleaderMaster",i="_jleaderHeartbeat",o=[],s=(new Date)["getTime"]()+":"+(Math["random"]()*1e9|0);if((n=window["localStorage"])===t){throw new Error("localStorage is not found")}if(!JSON){throw new Error("JSON support not found")}function f(e,t){if(window["addEventListener"]){window["addEventListener"](e,t)}else{window["attachEvent"]("on"+e,t)}}function l(e,t){var r=n[e];if(r){return r[0]==="["||r[0]==="{"?JSON["parse"](r):r}else{return t}}function c(e,t){if(typeof t==="object"){t=JSON["stringify"](t)}n[e]=t}e["id"]=s;function u(e){d("Firing subscribers. Master",e);for(var t=o["length"]-1;t>=0;t--){o[t](e)}}e["isMaster"]=![];e["announce"]=function(){d("Announcing peer",s);var t=l(r,{});t[s]=(new Date)["getTime"]();c(r,t);d("Peers",t);function i(){d("Unload peer",s);var t=l(r,{});delete t[s];c(r,t);d("Unload master",e["isMaster"]);if(e["isMaster"]){n["removeItem"](a)}}f("unload",i);if(!n[a]){e["elect"]()}f("storage",function(t){if(!t){t=window["event"]}if(t["key"]!==a){return}if(t["newValue"]!==null&&n[a]!==s){e["isMaster"]=![]}else if(t["newValue"]===null){e["elect"]()}u(e["isMaster"])});e["heartbeat"]();d("Master",n[a]);return e};e["elect"]=function(){var t=l(r,{}),n=(new Date)["getTime"](),a;d("Candidate peers",t);for(var i in t){if(t[i]+15e3<n){continue}a=i;break}if(a==s){d("We are elected as master",s);e["electMe"]();delete t[a];c(r,t)}};e["electMe"]=function(){n[a]=s;e["isMaster"]=!![];u(!![])};e["heartbeat"]=function(){var t=(new Date)["getTime"](),a=1e4,o=n[i]||0,f=l(r,{});d("Heartbeat value",o);if(parseInt(o)+5e3<t){d("Heartbeat is out of date. Electing new master");e["elect"]()}if(e["isMaster"]){n[i]=t;var u={};for(var w in f){if(f[w]+15e3>t){u[w]=f[w]}else{d("Peer",w,"is out-of-date")}}c(r,u);a=1500}else{f[s]=t;d("Updating peer heartbeat",t);c(r,f)}setTimeout(function(){e["heartbeat"]()},a)};e["subscribe"]=function(e){o["push"](e)};e["debug"]=![];function d(){if(e["debug"]&&console!==t){console["log"]["apply"](console,[new Date]["concat"](Array["prototype"]["slice"]["call"](arguments)))}}});
//# sourceMappingURL=jleader.js.map
