diff --git a/bin/joola.io.js b/bin/joola.io.js index 67f8a97..e883db6 100644 --- a/bin/joola.io.js +++ b/bin/joola.io.js @@ -1,5 +1,5 @@ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o-1||scr.src.indexOf("joola.io.min.js")>-1){var parts=require("url").parse(scr.src);joolaio.options.host=parts.protocol+"//"+parts.host;if(parts.query){var qs=require("querystring").parse(parts.query);if(qs&&qs.APIToken){joolaio.options.APIToken=qs.APIToken}}}}})}joolaio.init=function(options,callback){joolaio.options=joolaio.common.extend(joolaio.options,options);joolaio.options.isBrowser=isBrowser();function browser3rd(callback){var expected=0;function done(){expected--;if(expected<=0)return callback(null)}if(joolaio.options.isBrowser){if(typeof jQuery==="undefined"){var script=document.createElement("script");expected++;script.onload=function(){script=document.createElement("script");expected++;script.onload=function(){var script=document.createElement("script");expected++;script.onload=function(){done()};script.src="/js/highcharts.js";document.head.appendChild(script);done()};script.src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js";document.head.appendChild(script);done()};script.src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js";document.head.appendChild(script)}else if(typeof Highcharts==="undefined"){script=document.createElement("script");expected++;script.onload=function(){done()};script.src="//code.highcharts.com/highcharts.js";document.head.appendChild(script)}var css=document.createElement("link");expected++;css.onload=function(){done()};css.rel="stylesheet";css.href=joolaio.options.host+"/joola.io.css";document.head.appendChild(css);if(expected===0)return done()}else{return done()}}browser3rd(function(){if(options.token){joolaio._token=options.token}else{if(typeof location!=="undefined"){var qs=require("querystring");var parts=qs.parse(location.search.substring(1,location.search.length));if(parts.token)joolaio._token=parts.token}}joolaio.events.emit("core.init.start");joolaio.logger.info("Starting joola.io client SDK, version "+joolaio.VERSION);if(!joolaio.options.host&&joolaio.options.isBrowser){joolaio.options.host=location.protocol+"//"+location.host}if(!joolaio.options.host)throw new Error("joola.io host not specified");var io=require("socket.io-browserify");joolaio.io=io;joolaio.io.socket=joolaio.io.connect(joolaio.options.host);joolaio.dispatch.buildstub(function(err){if(err)return callback(err);if(joolaio.options.token){joolaio.dispatch.users.getByToken(joolaio._token,function(err,user){if(err)return callback(err);joolaio.USER=user;joolaio.TOKEN=joolaio._token;joolaio.events.emit("core.init.finish");if(callback)return callback(null,joolaio)})}else if(joolaio.options.APIToken){joolaio._apitoken=joolaio.options.APIToken;joolaio.USER=null;joolaio._token=null;joolaio.dispatch.users.verifyAPIToken(joolaio._apitoken,function(err,user){joolaio.USER=user;joolaio.TOKEN=user.token._;joolaio.events.emit("core.init.finish");if(typeof callback==="function")return callback(null,joolaio)})}else{joolaio.events.emit("core.init.finish");joolaio.events.emit("ready");if(typeof callback==="function")return callback(null,joolaio)}});if(joolaio.options.debug&&joolaio.options.debug.functions&&joolaio.options.debug.functions.enabled)[joolaio].forEach(function(obj){joolaio.common.hookEvents(obj,function(event){})});if(joolaio.options.debug.enabled&&joolaio.options.debug.events)joolaio.events.onAny(function(){if(joolaio.options.debug.events.enabled)joolaio.logger.debug("Event raised: "+this.event);if(joolaio.options.debug.events.enabled&&joolaio.options.debug.events.trace)console.trace()})})};if(joolaio.options.APIToken){joolaio.init({})}joolaio.set=function(key,value,callback){joolaio.options[key]=value;if(key==="APIToken"){joolaio._apitoken=joolaio.options.APIToken;joolaio.USER=null;joolaio._token=null;joolaio.dispatch.users.verifyAPIToken(joolaio._apitoken,function(err,user){joolaio.USER=user;joolaio.TOKEN=user.token._;if(typeof callback==="function")return callback(null)})}};joolaio.get=function(key){return joolaio.options[key]}}).call(this,require("/home/itay/dev/joola.io.sdk/node_modules/process/browser.js"),typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./lib/common/api":3,"./lib/common/dispatch":4,"./lib/common/events":5,"./lib/common/globals":6,"./lib/common/index":7,"./lib/common/logger":8,"./lib/viz/index":21,"./package.json":59,"/home/itay/dev/joola.io.sdk/node_modules/process/browser.js":56,querystring:41,"socket.io-browserify":57,url:50}],2:[function(require,module,exports){var stIsIE=false;sorttable={init:function(){if(arguments.callee.done)return;arguments.callee.done=true;if(_timer)clearInterval(_timer);if(!document.createElement||!document.getElementsByTagName)return;sorttable.DATE_RE=/^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;forEach(document.getElementsByTagName("table"),function(table){if(table.className.search(/\bsortable\b/)!=-1){sorttable.makeSortable(table)}})},makeSortable:function(table){if(table.getElementsByTagName("thead").length==0){the=document.createElement("thead");the.appendChild(table.rows[0]);table.insertBefore(the,table.firstChild)}if(table.tHead==null)table.tHead=table.getElementsByTagName("thead")[0];if(table.tHead.rows.length!=1)return;sortbottomrows=[];for(var i=0;i5':" ▴";this.appendChild(sortrevind);return}if(this.className.search(/\bsorttable_sorted_reverse\b/)!=-1){sorttable.reverse(this.sorttable_tbody);this.className=this.className.replace("sorttable_sorted_reverse","sorttable_sorted");this.removeChild(document.getElementById("sorttable_sortrevind"));sortfwdind=document.createElement("span");sortfwdind.id="sorttable_sortfwdind";sortfwdind.innerHTML=stIsIE?' 6':" ▾";this.appendChild(sortfwdind);return}theadrow=this.parentNode;forEach(theadrow.childNodes,function(cell){if(cell.nodeType==1){cell.className=cell.className.replace("sorttable_sorted_reverse","");cell.className=cell.className.replace("sorttable_sorted","")}});sortfwdind=document.getElementById("sorttable_sortfwdind");if(sortfwdind){sortfwdind.parentNode.removeChild(sortfwdind)}sortrevind=document.getElementById("sorttable_sortrevind");if(sortrevind){sortrevind.parentNode.removeChild(sortrevind)}this.className+=" sorttable_sorted";sortfwdind=document.createElement("span");sortfwdind.id="sorttable_sortfwdind";sortfwdind.innerHTML=stIsIE?' 6':" ▾";this.appendChild(sortfwdind);row_array=[];col=this.sorttable_columnindex;rows=this.sorttable_tbody.rows;for(var j=0;j12){return sorttable.sort_ddmm}else if(second>12){return sorttable.sort_mmdd}else{sortfn=sorttable.sort_ddmm}}}}return sortfn},getInnerText:function(node){if(!node)return"";hasInputs=typeof node.getElementsByTagName=="function"&&node.getElementsByTagName("input").length;if(node.getAttribute("sorttable_customkey")!=null){return node.getAttribute("sorttable_customkey")}else if(typeof node.textContent!="undefined"&&!hasInputs){return node.textContent.replace(/^\s+|\s+$/g,"")}else if(typeof node.innerText!="undefined"&&!hasInputs){return node.innerText.replace(/^\s+|\s+$/g,"")}else if(typeof node.text!="undefined"&&!hasInputs){return node.text.replace(/^\s+|\s+$/g,"")}else{switch(node.nodeType){case 3:if(node.nodeName.toLowerCase()=="input"){return node.value.replace(/^\s+|\s+$/g,"")}case 4:return node.nodeValue.replace(/^\s+|\s+$/g,"");break;case 1:case 11:var innerText="";for(var i=0;i=0;i--){tbody.appendChild(newrows[i])}delete newrows},sort_numeric:function(a,b){aa=parseFloat(a[0].replace(/[^0-9.-]/g,""));if(isNaN(aa))aa=0;bb=parseFloat(b[0].replace(/[^0-9.-]/g,""));if(isNaN(bb))bb=0;return aa-bb},sort_alpha:function(a,b){if(a[0]==b[0])return 0;if(a[0]0){var q=list[i];list[i]=list[i+1];list[i+1]=q;swap=true}}t--;if(!swap)break;for(var i=t;i>b;--i){if(comp_func(list[i],list[i-1])<0){var q=list[i];list[i]=list[i-1];list[i-1]=q;swap=true}}b++}}};if(document.addEventListener){document.addEventListener("DOMContentLoaded",sorttable.init,false)}if(/WebKit/i.test(navigator.userAgent)){var _timer=setInterval(function(){if(/loaded|complete/.test(document.readyState)){sorttable.init()}},10)}window.onload=sorttable.init;function dean_addEvent(element,type,handler){if(element.addEventListener){element.addEventListener(type,handler,false)}else{if(!handler.$$guid)handler.$$guid=dean_addEvent.guid++;if(!element.events)element.events={};var handlers=element.events[type];if(!handlers){handlers=element.events[type]={};if(element["on"+type]){handlers[0]=element["on"+type]}}handlers[handler.$$guid]=handler;element["on"+type]=handleEvent}}dean_addEvent.guid=1;function removeEvent(element,type,handler){if(element.removeEventListener){element.removeEventListener(type,handler,false)}else{if(element.events&&element.events[type]){delete element.events[type][handler.$$guid]}}}function handleEvent(event){var returnValue=true;event=event||fixEvent(((this.ownerDocument||this.document||this).parentWindow||window).event);var handlers=this.events[event.type];for(var i in handlers){this.$$handleEvent=handlers[i];if(this.$$handleEvent(event)===false){returnValue=false}}return returnValue}function fixEvent(event){event.preventDefault=fixEvent.preventDefault;event.stopPropagation=fixEvent.stopPropagation;return event}fixEvent.preventDefault=function(){this.returnValue=false};fixEvent.stopPropagation=function(){this.cancelBubble=true};if(!Array.forEach){Array.forEach=function(array,block,context){for(var i=0;i0)_args[_fn.inputs[0]]=joolaio.USER.workspace;Object.keys(args).forEach(function(arg){if(argCounter<_fn.inputs.length-shouldAppendWorkspace){args[_fn.inputs[argCounter+shouldAppendWorkspace]]=args[arg];_args[_fn.inputs[argCounter+shouldAppendWorkspace]]=args[arg]}delete args[arg];argCounter++});args=_args;joolaio.logger.debug("["+endpoints+":"+fn+"] called with: "+JSON.stringify(args));var _callback=ce.clone(callback);try{joolaio.api.fetch(_fn.name,args,function(err,result){if(result&&result.result){return _callback(err,result.result)}else{return _callback(err)}})}catch(ex){return _callback(ex)}};if(!joolaio[endpoints])joolaio[endpoints]={};if(!joolaio[endpoints][fn])joolaio[endpoints][fn]=dispatch[endpoints][fn]})});return callback(null)})}catch(ex){return callback(ex)}}},{cloneextend:53,url:50}],5:[function(require,module,exports){var EventEmitter2=require("eventemitter2").EventEmitter2;var _events=new EventEmitter2({wildcard:true,newListener:true});_events._id="events";module.exports=exports=_events},{eventemitter2:54}],6:[function(require,module,exports){(function(global){global.emptyfunc=function(){};joolaio.timezone=function(tz){if(tz)joolaio.options.timezoneOffset=tz;var offset=0;if(joolaio.options.timezoneOffset)offset=joolaio.options.timezoneOffset||(new Date).getTimezoneOffset()/60*-1;return offset}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],7:[function(require,module,exports){var util=require("util"),ce=require("cloneextend");var common=util;common._id="common";module.exports=exports=common;common.extend=common._extend;require("./modifiers");common.hookEvents=function(obj){if(!obj)return;var name,fn,obj_id;if(obj._id)obj_id=obj._id;for(name in obj){fn=obj[name];if(name.substring(0,1)=="_")continue;if(typeof fn==="function"&&name!=="hookEvents"){obj[name]=function(name,fn){var args=arguments;return function(){var self=this;var timeID="Function "+(obj_id?obj_id+".":"")+name;if(joolaio.options.debug.functions.enabled&&console.time)console.time(timeID);var result=fn.apply(self,arguments);if(joolaio.options.debug.functions.enabled&&console.time){console.timeEnd(timeID)}return result}}(name,fn)}else if(typeof fn==="object")this.hookEvents(fn)}};common.uuid=function(){var uuid="";var possible="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(var i=0;i<9;i++)uuid+=possible.charAt(Math.floor(Math.random()*possible.length));return uuid};common.stringify=function(obj,callback){return callback(null,JSON.stringify(obj))};common.parse=function(string,callback){return callback(null,JSON.parse(string))};common.hash=function(string){return require("crypto").createHash("md5").update(string).digest("hex")}},{"./modifiers":9,cloneextend:53,crypto:26,util:52}],8:[function(require,module,exports){var logger=exports;logger._id="logger";logger._log=function(level,message,callback){switch(level){case"debug":case"info":case"warn":case"error":break;case"silly":level="debug";break;default:break}if(!joolaio.options.debug.enabled)return;if(typeof message==="object")message="["+(new Date).format("hh:nn:ss.fff")+"] "+JSON.stringify(message);else message="["+(new Date).format("hh:nn:ss.fff")+"] "+message;if(joolaio.options.isBrowser&&console.debug){if(["silly","debug"].indexOf(level)==-1)console[level](message);else if(joolaio.options.debug.enabled&&["silly","debug"].indexOf(level)>-1)console[level](message)}else console.log(message);if(callback)return callback(null)};logger.silly=function(message,callback){return this._log("silly",message,callback)};logger.info=function(message,callback){return this._log("info",message,callback)};logger.debug=function(message,callback){return this._log("debug",message,callback)};logger.warn=function(message,callback){return this._log("warn",message,callback)};logger.error=function(message,callback){return this._log("error",message,callback)}},{}],9:[function(require,module,exports){Date.prototype.format=function(formatString){var formatDate=this;var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var yyyy=formatDate.getFullYear();var yy=yyyy.toString().substring(2);var m=formatDate.getMonth()+1;var mm=m<10?"0"+m:m;var mmm=months[m-1];var d=formatDate.getDate();var dd=d<10?"0"+d:d;var fff=formatDate.getMilliseconds().toString();fff=fff<100?fff<10?"00"+fff:+"0"+fff:fff;var h=formatDate.getHours();var hh=h<10?"0"+h:h;var n=formatDate.getMinutes();var nn=n<10?"0"+n:n;var s=formatDate.getSeconds();var ss=s<10?"0"+s:s;formatString=formatString.replace(/yyyy/i,yyyy);formatString=formatString.replace(/yy/i,yy);formatString=formatString.replace(/mmm/i,mmm);formatString=formatString.replace(/mm/i,mm);formatString=formatString.replace(/m/i,m);formatString=formatString.replace(/dd/i,dd);formatString=formatString.replace(/d/i,d);formatString=formatString.replace(/hh/i,hh);formatString=formatString.replace(/nn/i,nn);formatString=formatString.replace(/ss/i,ss);formatString=formatString.replace(/fff/i,fff);return formatString};Date.dateDiff=function(datepart,fromdate,todate){datepart=datepart.toLowerCase();var diff=todate-fromdate;var divideBy={w:6048e5,d:864e5,h:36e5,n:6e4,s:1e3};return Math.floor(diff/divideBy[datepart])};Object.defineProperty(Error.prototype,"toJSON",{value:function(){var alt={};Object.getOwnPropertyNames(this).forEach(function(key){alt[key]=this[key]},this);return alt},configurable:true})},{}],10:[function(require,module,exports){var EventEmitter2=require("eventemitter2").EventEmitter2;var ce=require("cloneextend"),_events=new EventEmitter2({wildcard:true,newListener:true});var Canvas=module.exports=function(options,callback){if(!callback)callback=function(){};joolaio.events.emit("canvas.init.start");this._super={};for(var x in require("./_proto")){this[x]=require("./_proto")[x];this._super[x]=require("./_proto")[x]}for(var y in _events){this[y]=_events[y];this._super[y]=_events[y]}var self=this;this._id="_canvas";this.uuid=joolaio.common.uuid();this.options={container:null,$container:null,visualizations:{},state:{}};this.verify=function(options,callback){return this._super.verify(options,callback)};this.prepareQuery=function(query){var _query=ce.extend({},query);if(self.options.query){_query=joolaio.common.extend(self.options.query,_query)}if(self.options.datepicker){var _datepicker=$(self.options.datepicker).DatePicker();_query.timeframe={};_query.timeframe.start=_datepicker.base_fromdate;_query.timeframe.end=_datepicker.base_todate}return _query};this.draw=function(options,callback){var self=this;if(self.options.datepicker)$(self.options.datepicker).DatePicker({});if(self.options.viz&&self.options.viz.length>0){self.options.viz.forEach(function(viz){viz.query=self.prepareQuery(viz.query);switch(viz.type){case"Metric":$(viz.container).Metric(viz);break;default:break}})}if(typeof callback==="function")return callback(null,self)};this.addVisualization=function(viz){this.options.visualizations[viz.uuid]=viz};try{joolaio.common.mixin(self.options,options,true);self.verify(self.options,function(err){if(err)return callback(err);self.options.$container=$(self.options.container);self.markContainer(self.options.$container,[{type:"canvas"},{uuid:self.uuid}],function(err){if(err)return callback(err);joolaio.viz.onscreen.push(self);joolaio.events.emit("canvas.init.finish",self);if(typeof callback==="function"){return callback(null,self)}})})}catch(err){return self.onError(err,callback)}return self};joolaio.events.on("core.init.finish",function(){if(typeof jQuery!="undefined"){$.fn.Canvas=function(options,callback){var result=null;var uuid=this.attr("jio-uuid");if(!uuid){if(!options)options={};options.container=this.get(0);result=new joolaio.viz.Canvas(options,function(err,canvas){if(err)throw new Error("Failed to initialize canvas.",err);canvas.draw(options,callback)}).options.$container}else{var found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;result=viz}})}return result}}})},{"./_proto":20,cloneextend:53,eventemitter2:54}],11:[function(require,module,exports){var _=require("underscore");var DatePicker=module.exports=function(options,callback){if(!callback)callback=function(){};joolaio.events.emit("datepicker.init.start");this._super={};for(var x in require("./_proto")){this[x]=require("./_proto")[x];this._super[x]=require("./_proto")[x]}var self=this;this.addDays=function(o,days){return new Date(o.getFullYear(),o.getMonth(),o.getDate()+days)};this.fixDate=function(timestamp,zero){var offset=-1*(timestamp.getTimezoneOffset()/60);var date=timestamp;var year=date.getUTCFullYear();var month=date.getUTCMonth()+1;var day=date.getUTCDate();var hours=date.getUTCHours();var minutes=date.getUTCMinutes();var seconds=date.getUTCSeconds();var bAddDay=false;hours=hours+offset;var fixedDate=null;if(!zero)fixedDate=new Date(year+"-"+month+"-"+day+" "+hours+":"+minutes+" GMT");else fixedDate=new Date(year+"-"+month+"-"+day+" "+"00"+":"+"00"+" GMT");if(fixedDate=="Invalid Date"){if(!zero){fixedDate=new Date;fixedDate.setFullYear(year,month-1,day);fixedDate.setHours(parseInt(hours));fixedDate.setMinutes(parseInt(minutes));fixedDate.setSeconds(parseInt(seconds))}else{fixedDate=new Date;fixedDate.setFullYear(year,month-1,day);fixedDate.setHours(parseInt(hours));fixedDate.setMinutes(0);fixedDate.setSeconds(0)}}if(bAddDay)fixedDate.setDate(fixedDate.getDate()+1);var fixedDate_utc=new Date(fixedDate.getUTCFullYear(),fixedDate.getUTCMonth(),fixedDate.getUTCDate(),fixedDate.getUTCHours(),fixedDate.getUTCMinutes(),fixedDate.getUTCSeconds());return fixedDate};this._id="_datepicker";this.uuid=joolaio.common.uuid();this.options={canvas:null,container:null,$container:null,comparePeriod:false};this.currentMode="base-from";this.original_base_fromdate=null;this.original_base_todate=null;this.original_compare_fromdate=null;this.original_compare_todate=null;this.min_date=new Date;this.min_date.setMonth(this.min_date.getMonth()-6);this.max_date=new Date;this.base_todate=new Date(this.max_date);this.base_fromdate=self.addDays(this.base_todate,-30);if(this.base_fromdate');var $last_day=$('
Past Day
');var $last_week=$('
Past Week
');var $last_month=$('
Past Month
');var $custom=$('
Custom
');$group.append(bindKey($last_day));$group.append(bindKey($last_week));$group.append(bindKey($last_month));$group.append(bindPopUp($custom));return $group};this.draw=function(options,callback){var $container=self.options.$container;var $table=$('
'+""+''+''+""+"
");$container.append($table);var $dates=$table.find(".dates");$dates.append(''+self.formatDate(self.base_fromdate)+"");$dates.append(" - ");$dates.append(''+self.formatDate(self.base_todate)+"");$dates.append('");if(self.comparePeriod)$container.find(".dates .compare").show();else $container.find(".dates .compare").hide();var $item=$('');$item.append(''+''+''+"
");$container.append($item);var $optionscontainer=$(".optionscontainer");$optionscontainer.append('
Date Range:'+''+"
");$optionscontainer.append('
');$optionscontainer.append('
'+''+" - "+''+"
");$optionscontainer.append('
'+'Compare to past'+"
");$optionscontainer.append('
'+''+" - "+''+"
");$optionscontainer.append(""+'
'+'
'+'Cancel
');var $calendars=$container.find(".calendars");$item=$(""+''+''+''+''+''+"
");$calendars.append($item);$(".datetable-prev").append('");$(".datetable-prev .prev").off("click");$(".datetable-prev .prev").on("click",function(e){e.stopPropagation();var currentLeftCellDate=$($(".datepicker")[0]).datepicker("getDate");if(currentLeftCellDate.setMonth(currentLeftCellDate.getMonth())'+'"+"");$(".datetable-next .next").off("click");$(".datetable-next .next").on("click",function(e){e.stopPropagation();var currentRightCellDate=$($(".datepicker")[2]).datepicker("getDate");if(currentRightCellDate.setMonth(currentRightCellDate.getMonth()+1)>self.max_date)return;currentRightCellDate=new Date(currentRightCellDate);var selectedDate=new Date(currentRightCellDate);$(".datepicker").each(function(index,item){var localdate=new Date(selectedDate);localdate.setMonth(localdate.getMonth()-(2-index));$(item).datepicker("setDate",localdate)})});var currentClickIndex=0;$(".datepicker").datepicker({dayNamesMin:["S","M","T","W","T","F","S"],firstDay:0,beforeShowDay:function(date){return self.drawCell(date)},onSelect:function(dateText,inst){$optionscontainer.find(".selector").val("custom");switch(self.currentMode){case"base-from":self.currentMode="base-to";self.base_fromdate=new Date(dateText);self.base_todate=new Date(dateText);var _checkLimit=new Date(self.min_date);_checkLimit.setUTCHours(0,0,0,0);_checkLimit.setDate(_checkLimit.getDate()+1);if(self.base_fromdate.getTime()<=_checkLimit.getTime()){$(".compareoption .checker").attr("disabled","disabled")}else{if($(".compareoption .checker").is(":disabled")){$(".compareoption .checker").removeAttr("disabled")}}$($(".daterange.baserange .dateoption")[0]).val(self.formatDate(self.base_fromdate));$($(".daterange.baserange .dateoption")[0]).removeClass("invalid");$($(".daterange.baserange .dateoption")[1]).val(self.formatDate(self.base_fromdate));$($(".daterange.baserange .dateoption")[1]).removeClass("invalid");break;case"base-to":self.base_todate=new Date(dateText);$($(".daterange.baserange .dateoption")[1]).val(self.formatDate(self.base_todate));$($(".daterange.baserange .dateoption")[1]).removeClass("invalid");if(self.isCompareChecked){self.currentMode="compare-from"}else{self.currentMode="base-from"}break;case"compare-from":self.compare_fromdate=new Date(dateText);self.compare_todate=new Date(dateText);$($(".daterange.comparerange .dateoption")[0]).val(self.formatDate(self.compare_fromdate));$($(".daterange.comparerange .dateoption")[0]).removeClass("invalid");$($(".daterange.comparerange .dateoption")[1]).val(self.formatDate(self.compare_fromdate));$($(".daterange.comparerange .dateoption")[1]).removeClass("invalid");self.currentMode="compare-to";break;case"compare-to":self.compare_todate=new Date(dateText);$($(".daterange.comparerange .dateoption")[1]).val(self.formatDate(self.compare_todate));$($(".daterange.comparerange .dateoption")[1]).removeClass("invalid");self.currentMode="base-from";break;default:break}self.handleChange()}});$(".datepicker").find('a[href="#"]').each(function(index,item){$(this).on("click",function(event){event.stopPropagation()})});$(".datepicker").each(function(index,item){var selectedDate=new Date(self.base_todate.getFullYear(),self.base_todate.getMonth(),1);selectedDate.setMonth(selectedDate.getMonth()-(2-index));$(item).datepicker("setDate",selectedDate)});$($(".daterange.baserange .dateoption")[0]).focus(function(e){self.currentMode="base-from";self.handleChange()});$($(".daterange.baserange .dateoption")[0]).blur(function(e){$($(".daterange.baserange .dateoption")[0]).val(self.formatDate(self.base_fromdate));$(this).removeClass("invalid");$(".btn.apply").removeClass("disabled");$(".btn.apply").prop("disabled",false);self.currentMode="base-from";self.handleChange()});$($(".daterange.baserange .dateoption")[0]).keyup(function(e){if(new Date($(this).val())=="Invalid Date"||new Date($(this).val())>self.base_todate||new Date($(this).val())>self.max_date||new Date($(this).val())self.max_date||new Date($(this).val())self.compare_todate||new Date($(this).val())>self.max_date||new Date($(this).val())self.base_todate||new Date($(this).val())>self.max_date||new Date($(this).val())=this.max_date)return[false,"daycell disabled"];if(date<=this.min_date)return[false,"daycell disabled"];if(this.currentMode=="base-to"){if(date=this.base_fromdate&&date<=this.base_todate&&(date>=this.compare_fromdate&&date<=this.compare_todate))return[true,"daycell basencompare inrange"];if(date>=this.compare_fromdate&&date<=this.compare_todate)return[true,"daycell compare inrange"];if(date>this.base_todate&&this.currentMode!="base-to"){return[false,"daycell compare disabled"]}}if(date==this.base_fromdate)return[true,"daycell inrange selected fromdate"];if(date==this.base_todate)return[true,"daycell inrange selected todate"];if(date>=this.base_fromdate&&date<=this.base_todate)return[true,"daycell inrange"];switch(this.currentMode){case"base-from":break;case"base-to":break;case"compare-from":break;case"compare-to":break;default:break}return[true,"daycell"]};this.handleChange=function(options){var self=this;var $datebox=$('[jio-type="datepicker"]');$(".datepicker").not(this).each(function(){$(this).datepicker("refresh")});$($(".daterange.baserange .dateoption")[1]).removeClass("active");$($(".daterange.comparerange .dateoption")[0]).removeClass("active");$($(".daterange.comparerange .dateoption")[1]).removeClass("active");switch(this.currentMode){case"base-from":if(self.base_fromdateself.max_date){self.base_fromdate=self.max_date;$($(".daterange.baserange .dateoption")[0]).val(self.formatDate(self.base_fromdate))}$($(".daterange.baserange .dateoption")[0]).addClass("active");$($(".daterange.baserange .dateoption")[1]).removeClass("active");$($(".daterange.comparerange .dateoption")[0]).removeClass("active");$($(".daterange.comparerange .dateoption")[1]).removeClass("active");break;case"base-to":if(self.base_todateself.max_date){self.base_todate=self.max_date;$($(".daterange.baserange .dateoption")[1]).val(self.formatDate(self.base_todate))}$($(".daterange.baserange .dateoption")[0]).removeClass("active");$($(".daterange.baserange .dateoption")[1]).addClass("active");$($(".daterange.comparerange .dateoption")[0]).removeClass("active");$($(".daterange.comparerange .dateoption")[1]).removeClass("active");break;case"compare-from":if(self.compare_fromdateself.max_date){self.compare_fromdate=self.max_date;$($(".daterange.comparerange .dateoption")[0]).val(self.formatDate(self.compare_fromdate))}$($(".daterange.baserange .dateoption")[0]).removeClass("active");$($(".daterange.baserange .dateoption")[1]).removeClass("active");$($(".daterange.comparerange .dateoption")[0]).addClass("active");$($(".daterange.comparerange .dateoption")[1]).removeClass("active");break;case"compare-to":if(self.compare_todateself.max_date){self.compare_todate=self.max_date;$($(".daterange.comparerange .dateoption")[1]).val(self.formatDate(self.compare_todate))}$($(".daterange.baserange .dateoption")[0]).removeClass("active");$($(".daterange.baserange .dateoption")[1]).removeClass("active");$($(".daterange.comparerange .dateoption")[0]).removeClass("active");$($(".daterange.comparerange .dateoption")[1]).addClass("active");break;default:break}if((self.compare_fromdate>self.base_todate||self.compare_todate>self.base_todate)&&this.isCompareChecked){var rangelength=Date.dateDiff("d",self.base_fromdate,self.base_todate);self.compare_todate=self.addDays(self.base_fromdate,-1);self.compare_fromdate=self.addDays(self.compare_todate,-1*rangelength);if(self.compare_fromdate'+'
');return $html};this.draw=function(options,callback){this.options.query.dimensions=[];this.options.query.metrics=this.options.query.metrics.splice(0,1);return this._super.fetch(this.options.query,function(err,message){if(err){if(typeof callback==="function")return callback(err);return}var value;if(message.documents&&message.documents.length>0)value=message.documents[0].fvalues[message.metrics[0].key];else value=0;if(!value)value=0;if(!self.drawn){self.options.$container.append(self.template());self.options.$container.find(".caption").text(self.options.caption||"");self.drawn=true;self.options.$container.find(".value").text(value);if(typeof callback==="function")return callback(null,self)}else if(self.options.query.realtime){self.options.$container.find(".value").text(value)}})};try{joolaio.common.mixin(self.options,options,true);self.verify(self.options,function(err){if(err)return callback(err);self.options.$container=$(self.options.container);self.markContainer(self.options.$container,[{type:"metric"},{uuid:self.uuid}],function(err){if(err)return callback(err);joolaio.viz.onscreen.push(self);if(!self.options.canvas){var elem=self.options.$container.parent();if(elem.attr("jio-type")=="canvas"){self.options.canvas=$(elem).Canvas()}}if(self.options.canvas){self.options.canvas.addVisualization(self);self.options.canvas.on("datechange",function(e){console.log("metric","datechange",e)})}joolaio.events.emit("metric.init.finish",self);if(typeof callback==="function")return callback(null,self)})})}catch(err){callback(err);return self.onError(err,callback)}return self};joolaio.events.on("core.init.finish",function(){var found;if(typeof jQuery!="undefined"){$.fn.Metric=function(options,callback){var result=null;var uuid=this.attr("jio-uuid");if(!uuid||options&&options.force){if(options&&options.force&&uuid){var existing=null;found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;existing=viz}});if(found&&existing){existing.destroy()}}if(!options)options={};options.container=this.get(0);result=new joolaio.viz.Metric(options,function(err,metric){if(err)throw err;metric.draw(options,callback)}).options.$container}else{found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;result=viz}})}return result}}})},{"./_proto":20,cloneextend:53}],14:[function(require,module,exports){var _=require("underscore");var MiniTable=module.exports=function(options,callback){if(!callback)callback=function(){};joolaio.events.emit("minitable.init.start");this._super={};for(var x in require("./_proto")){this[x]=require("./_proto")[x];this._super[x]=require("./_proto")[x]}var self=this;this._id="_minitable";this.uuid=joolaio.common.uuid();this.options={legend:true,container:null,$container:null,query:null};this.chartDrawn=false;this.verify=function(options,callback){return this._super.verify(options,callback)};this.template=function(){var $html=$(''+""+""+""+""+"
");return $html};this.sort=function(key,callback){if(typeof callback==="function")return callback(null)};this._draw=function(callback){if(typeof callback==="function")return callback(null)};this.draw=function(options,callback){return this._super.fetch(this.options.query,function(err,message){if(err){if(typeof callback==="function")return callback(err);else throw err;return}var $col,$tr,trs;var series=self._super.makeTableChartSeries(message.dimensions,message.metrics,message.documents);if(!self.drawn){self.drawn=true;var $html=self.template();var $thead=$($html.find("thead"));var $head_tr=$('');message.dimensions.forEach(function(d){var $th=$('');$th.text(d.name);$head_tr.append($th)});message.metrics.forEach(function(m){var $th=$('');$th.text(m.name);$head_tr.append($th)});$thead.append($head_tr);$html.append($thead);var $tbody=$($html.find("tbody"));series.forEach(function(ser,serIndex){ser.data.forEach(function(point){var $tr=$("");var index=0;message.dimensions.forEach(function(d){var $td=$('');$td.text(point[index++]);$tr.append($td)});message.metrics.forEach(function(m){var $td=$('');$td.text(point[index++]);$tr.append($td)});$tbody.append($tr)})});$html.append($tbody);self.options.$container.append($html);self.tablesort=new Tablesort($html.get(0),{descending:true,current:$html.find("th")[1]});if(typeof callback==="function")return callback(null)}else if(self.options.query.realtime){trs=self.options.$container.find("tbody").find("tr"); -var existingkeys=[];series[0].data.forEach(function(point){var index=0;var key="";var found=false;message.dimensions.forEach(function(d){key+=point[index++]});existingkeys.push(key);for(var i=0;i");index=0;message.dimensions.forEach(function(d){var $td=$('');$td.text(point[index++]);$tr.append($td)});message.metrics.forEach(function(m){var $td=$('');$td.text(point[index++]);$tr.append($td)});$tbody.append($tr)}});for(var i=0;i0){self.tablesort.refresh();var limit=5;trs=self.options.$container.find("tbody tr");for(var z=0;zlimit)$elem.remove()}}})};try{joolaio.common.mixin(self.options,options,true);self.verify(self.options,function(err){if(err)return callback(err);self.options.$container=$(self.options.container);self.markContainer(self.options.$container,[{type:"minitable"},{uuid:self.uuid}],function(err){if(err)return callback(err);joolaio.viz.onscreen.push(self);joolaio.events.emit("minitable.init.finish",self);if(typeof callback==="function")return callback(null,self)})})}catch(err){callback(err);return self.onError(err,callback)}return self};joolaio.events.on("core.init.finish",function(){if(typeof jQuery!="undefined"){$.fn.MiniTable=function(options,callback){var result=null;var uuid=this.attr("jio-uuid");if(!uuid){if(!options)options={};options.container=this.get(0);result=new joolaio.viz.MiniTable(options,function(err,minitable){minitable.draw(options,callback)}).options.$container}else{var found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;result=viz}})}return result}}})},{"./_proto":20,underscore:58}],15:[function(require,module,exports){var _=require("underscore");var Pie=module.exports=function(options,callback){if(!callback)callback=function(){};joolaio.events.emit("pie.init.start");this._super={};for(var x in require("./_proto")){this[x]=require("./_proto")[x];this._super[x]=require("./_proto")[x]}var self=this;this._id="_pie";this.uuid=joolaio.common.uuid();this.options={legend:true,container:null,$container:null,query:null};this.chartDrawn=false;this.verify=function(options,callback){return this._super.verify(options,callback)};this.draw=function(options,callback){return this._super.fetch(this.options.query,function(err,message){if(err){if(typeof callback==="function")return callback(err);return}var series=self._super.makePieChartSeries(message.dimensions,message.metrics,message.documents);if(!self.chartDrawn){var chartOptions=joolaio.common.extend({title:{text:null},chart:{marginTop:0,marginBottom:0,marginLeft:0,marginRight:0,spacingTop:0,spacingBottom:0,spacingLeft:0,spacingRight:0,borderWidth:0,plotBorderWidth:0,type:"pie",backgroundColor:"transparent"},series:series,legend:{enabled:true},credits:{enabled:false},exporting:{enabled:true},plotOptions:{pie:{allowPointSelect:true,cursor:"pointer",dataLabels:{enabled:false,color:"#000000",connectorColor:"#000000",format:"{point.name}: {point.percentage:.1f} %"},showInLegend:true}}},self.options.chart);self.chart=self.options.$container.highcharts(chartOptions);self.chart=self.chart.highcharts();self.chartDrawn=true;if(typeof callback==="function")return callback(null)}else if(self.options.query.realtime){series.forEach(function(ser,serIndex){var found=false;self.chart.series[serIndex].points.forEach(function(point){var exist=_.find(ser.data,function(p){point.update(p[1]);return p[0]==point.name});if(!exist)point.remove()});ser.data.forEach(function(point){var exist=_.find(self.chart.series[serIndex].points,function(p){return p.name==point[0]});if(!exist)self.chart.series[serIndex].addPoint([point[0],point[1]])})})}})};try{joolaio.common.mixin(self.options,options,true);self.verify(self.options,function(err){if(err)return callback(err);self.options.$container=$(self.options.container);self.markContainer(self.options.$container,[{type:"pie"},{uuid:self.uuid}],function(err){if(err)return callback(err);joolaio.viz.onscreen.push(self);joolaio.events.emit("pie.init.finish",self);if(typeof callback==="function")return callback(null,self)})})}catch(err){callback(err);return self.onError(err,callback)}return self};joolaio.events.on("core.init.finish",function(){var found;if(typeof jQuery!="undefined"){$.fn.Pie=function(options,callback){var result=null;var uuid=this.attr("jio-uuid");if(!uuid||options.force){if(options.force&&uuid){var existing=null;found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;existing=viz}});if(found&&existing){existing.destroy()}}if(!options)options={};options.container=this.get(0);result=new joolaio.viz.Pie(options,function(err,pie){pie.draw(options,callback)}).options.$container}else{found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;result=viz}})}return result}}})},{"./_proto":20,underscore:58}],16:[function(require,module,exports){var _=require("underscore");var PunchCard=module.exports=function(options,callback){if(!callback)callback=function(){};joolaio.events.emit("punchcard.init.start");this._super={};for(var x in require("./_proto")){this[x]=require("./_proto")[x];this._super[x]=require("./_proto")[x]}var self=this;this._id="_punchcard";this.uuid=joolaio.common.uuid();this.options={legend:true,container:null,$container:null,query:null};this.chartDrawn=false;this.verify=function(options,callback){return this._super.verify(options,callback)};this.makeSeries=function(dimensions,metrics,documents){var maxValue;var minValue;documents.forEach(function(document){var value=document.values[metrics[0].key];if(!maxValue)maxValue=value;if(!minValue)minValue=value;if(value>maxValue)maxValue=value;if(value'+""+""+""+""+"");return $html};this.sort=function(key,callback){if(typeof callback==="function")return callback(null)};this._draw=function(callback){if(typeof callback==="function")return callback(null)};this.draw=function(options,callback){return this._super.fetch(this.options.query,function(err,message){if(err){if(typeof callback==="function")return callback(err);else throw err;return}var $col,$tr,trs;var series=self._super.makeTableChartSeries(message.dimensions,message.metrics,message.documents);if(!self.drawn){self.drawn=true;var $html=self.template();var $thead=$($html.find("thead"));var $head_tr=$('');message.dimensions.forEach(function(d){var $th=$('');$th.text(d.name);$head_tr.append($th)});message.metrics.forEach(function(m){var $th=$('');$th.text(m.name);$head_tr.append($th)});$thead.append($head_tr);$html.append($thead);var $tbody=$($html.find("tbody"));series.forEach(function(ser,serIndex){ser.data.forEach(function(point){var $tr=$("");var index=0;message.dimensions.forEach(function(d){var $td=$('');$td.text(point[index++]);$tr.append($td)});message.metrics.forEach(function(m){var $td=$('');$td.text(point[index++]);$tr.append($td)});$tbody.append($tr)})});$html.append($tbody);self.options.$container.append($html);self.tablesort=new Tablesort($html.get(0),{descending:true,current:$html.find("th")[1]});if(typeof callback==="function")return callback(null)}else if(self.options.query.realtime){trs=self.options.$container.find("tbody").find("tr");var existingkeys=[];series[0].data.forEach(function(point){var index=0;var key="";var found=false;message.dimensions.forEach(function(d){key+=point[index++]});existingkeys.push(key);for(var i=0;i");index=0;message.dimensions.forEach(function(d){var $td=$('');$td.text(point[index++]);$tr.append($td)});message.metrics.forEach(function(m){var $td=$('');$td.text(point[index++]);$tr.append($td)});$tbody.append($tr)}});for(var i=0;i0){self.tablesort.refresh();var limit=self.options.limit||5;trs=self.options.$container.find("tbody tr");for(var z=0;zlimit)$elem.remove()}}})};try{joolaio.common.mixin(self.options,options,true);self.verify(self.options,function(err){if(err)return callback(err);self.options.$container=$(self.options.container);self.markContainer(self.options.$container,[{type:"table"},{uuid:self.uuid}],function(err){if(err)return callback(err);joolaio.viz.onscreen.push(self);joolaio.events.emit("table.init.finish",self);if(typeof callback==="function")return callback(null,self)})})}catch(err){callback(err);return self.onError(err,callback)}return self};joolaio.events.on("core.init.finish",function(){var found;if(typeof jQuery!="undefined"){$.fn.Table=function(options,callback){var result=null;var uuid=this.attr("jio-uuid");if(!uuid||options.force){if(options.force&&uuid){var existing=null;found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;existing=viz}});if(found&&existing){existing.destroy()}}if(!options)options={};options.container=this.get(0);result=new joolaio.viz.Table(options,function(err,table){if(err)console.error(err);table.draw(options,callback)}).options.$container}else{found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;result=viz}})}return result}}})},{"./_proto":20,underscore:58}],19:[function(require,module,exports){var moment=require("moment");var _=require("underscore");var Timeline=module.exports=function(options,callback){if(!callback)callback=function(){};joolaio.events.emit("timeline.init.start");this._super={};for(var x in require("./_proto")){this[x]=require("./_proto")[x];this._super[x]=require("./_proto")[x]}var self=this;this._id="_timeline";this.uuid=joolaio.common.uuid();this.options={legend:true,canvas:null,container:null,$container:null,query:null};this.chartDrawn=false;this.realtimeQueries=[];this.verify=function(options,callback){return this._super.verify(options,callback)};this.draw=function(options,callback){self.stop();return this._super.fetch(self,this.options.query,function(err,message){if(err){console.log("err",err);if(typeof callback==="function")return callback(err);return}if(message.realtime&&self.realtimeQueries.indexOf(message.realtime)==-1)self.realtimeQueries.push(message.realtime);var series=self._super.makeChartTimelineSeries(message.dimensions,message.metrics,message.documents);if(!self.chartDrawn){var chartOptions=joolaio.common.extend({title:{text:null},chart:{marginTop:0,marginBottom:0,marginLeft:0,marginRight:0,spacingTop:0,spacingBottom:0,spacingLeft:0,spacingRight:0,borderWidth:0,plotBorderWidth:0,type:"area"},series:series,xAxis:{type:"datetime",endOnTick:false,tickWidth:0,dateTimeLabelFormats:{day:"%B %e"},labels:{enabled:true,style:{color:"#b3b3b1"}}},yAxis:{endOnTick:false,title:{text:null},labels:{enabled:true,style:{color:"#b3b3b1"}},gridLineDashStyle:"Dot"},legend:{enabled:false},credits:{enabled:false},exporting:{enabled:true},plotOptions:{column:{allowPointSelect:true},series:{turboThreshold:message.documents.length+1e3,color:"#333333",fillOpacity:.1,lineWidth:3,connectNulls:true,marker:{enabled:false,symbol:"circle",states:{hover:{enabled:true}}}}}},self.options.chart);self.chart=self.options.$container.highcharts(chartOptions);self.chart=self.chart.highcharts();self.chartDrawn=true;if(typeof callback==="function")return callback(null)}else if(self.options.query.realtime){series.forEach(function(ser,serIndex){ser.data.forEach(function(datapoint){var found=false;self.chart.series[serIndex].points.forEach(function(point){if(point){if(point.x.getTime()==datapoint.x.getTime()){var y=self.chart.series[serIndex].data[self.chart.series[serIndex].data.length-1].y;found=true;if(y!=datapoint.y)self.chart.series[serIndex].data[self.chart.series[serIndex].data.length-1].update(datapoint.y)}}});if(!found){self.chart.series[serIndex].addPoint({x:datapoint.x,y:datapoint.y},true,true)}})})}})};try{joolaio.common.mixin(self.options,options,true);self.verify(self.options,function(err){if(err)return callback(err);self.options.$container=$(self.options.container);self.markContainer(self.options.$container,[{type:"timeline"},{uuid:self.uuid}],function(err){if(err)return callback(err);joolaio.viz.onscreen.push(self);if(!self.options.canvas){var elem=self.options.$container.parent();if(elem.attr("jio-type")=="canvas"){self.options.canvas=$(elem).Canvas()}}if(self.options.canvas){self.options.canvas.addVisualization(self);self.options.canvas.on("datechange",function(dates){self.options.query.timeframe={};self.options.query.timeframe.start=new Date(dates.base_fromdate);self.options.query.timeframe.end=new Date(dates.base_todate);self.draw(self.options)})}joolaio.events.emit("timeline.init.finish",self);if(typeof callback==="function")return callback(null,self)})})}catch(err){callback(err);return self.onError(err,callback)}return self};joolaio.events.on("core.init.finish",function(){var found;if(typeof jQuery!="undefined"){$.fn.Timeline=function(options,callback){var result=null;var uuid=this.attr("jio-uuid");if(!uuid||options.force){if(options.force&&uuid){var existing=null;found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;existing=viz}});if(found&&existing){existing.destroy()}}if(!options)options={};options.container=this.get(0);result=new joolaio.viz.Timeline(options,function(err,timeline){if(err)throw err;timeline.draw(options,callback)}).options.$container}else{found=false;joolaio.viz.onscreen.forEach(function(viz){if(viz.uuid==uuid&&!found){found=true;result=viz}})}return result}}})},{"./_proto":20,moment:55,underscore:58}],20:[function(require,module,exports){var ce=require("cloneextend"),moment=require("moment"),_=require("underscore");var proto=exports;proto._id="_proto";proto.stop=function(){if(this.realtimeQueries){this.realtimeQueries.forEach(function(q){joolaio.logger.debug("Stopping realtime query ["+q+"].");joolaio.query.stop(q)})}};proto.destroy=function(container,obj){if(this.realtimeQueries){this.realtimeQueries.forEach(function(q){joolaio.logger.debug("Stopping realtime query ["+q+"].");joolaio.query.stop(q)})}this.options.$container.empty()};proto.markContainer=function(container,attr,callback){if(!callback)callback=function(){};try{container.attr("jio-domain","joolaio");attr.forEach(function(a){Object.keys(a).forEach(function(key){container.attr("jio-"+key,a[key])})})}catch(ex){return callback(ex)}return callback(null)};proto.get=function(key){return this.options[key]};proto.set=function(key,value){this.options[key]=value};proto.verify=function(options,callback){if(!options.container)return callback(new Error("no container specified for timeline."));var $container=$(options.container);if($container===null)return callback(new Error("cannot find container for the timeline."));return callback(null)};proto.fetch=function(context,query,callback){if(!callback&&context&&query){callback=query;query=context}var _query=ce.clone(query);if(context&&context.options&&context.options.canvas){context.options.query.interval=context.options.query.interval||context.options.canvas.options.query.interval;context.options.query.timeframe=context.options.query.timeframe||context.options.canvas.options.query.timeframe}if(_query.timeframe&&typeof _query.timeframe==="object"){_query.timeframe.start.setHours(_query.timeframe.start.getHours()+joolaio.timezone(joolaio.options.timezoneOffset));_query.timeframe.end.setHours(_query.timeframe.end.getHours()+joolaio.timezone(joolaio.options.timezoneOffset))}joolaio.dispatch.query.fetch(_query,function(err,message){if(err)return callback(err);if(message&&message.query&&message.query.ts&&message.query.ts.duration)joolaio.logger.debug("fetch took: "+message.query.ts.duration.toString()+"ms, results: "+(message&&message.documents?message.documents.length.toString():"n/a"));return callback(null,message)})};proto.makeChartTimelineSeries=function(dimensions,metrics,documents){var series=[];if(!metrics)return series;function fixOffset(date){var _date=new Date(date);_date.setHours(_date.getHours()+2*moment().zone()/60);return new Date(_date)}var exist=_.find(dimensions,function(d){return d.datatype==="date"});metrics.forEach(function(metric,index){series[index]={name:metric.name,data:[]};documents.forEach(function(document){var x=document.fvalues[dimensions[0].key];var nameBased=true;if(dimensions[0].datatype==="date"){x=new Date(document.fvalues[dimensions[0].key]);nameBased=false}if(nameBased){series[index].data.push({name:x,y:document.values[metrics[index].key]?document.values[metrics[index].key]:0})}else{series[index].data.push({x:x,y:document.values[metrics[index].key]?document.values[metrics[index].key]:0})}})});return series};proto.makePieChartSeries=function(dimensions,metrics,documents){var series=[];if(!metrics)return series;metrics.forEach(function(metric,index){series[index]={name:metric.name,data:[]};documents.forEach(function(document){series[index].data.push([document.fvalues[dimensions[0].key],document.values[metrics[index].key]?document.values[metrics[index].key]:0])})});return series};proto.makeTableChartSeries=function(dimensions,metrics,documents){var series=[];if(!metrics)return series;series[0]={data:[]};documents.forEach(function(document){var point=[];dimensions.forEach(function(d){point.push(document.fvalues[d.key])});metrics.forEach(function(m){point.push(document.fvalues[m.key]?document.fvalues[m.key]:0)});series[0].data.push(point)});return series};proto.makeGeoSeries=function(dimensions,metrics,documents){var results=[];results.push(["Country",metrics[0].name]);if(dimensions[0].datatype=="ip"){documents.forEach(function(document){if(document.fvalues[dimensions[0].key]&&document.fvalues[dimensions[0].key]!="(not set)")results.push([document.fvalues[dimensions[0].key].country,document.fvalues[metrics[0].key]])})}else return results;return google.visualization.arrayToDataTable(results)};proto.baseHTML=function(callback){return callback(null,"
")};proto.onError=function(err,callback){if(err&&err.message)joolaio.logger.error(err.message);else joolaio.logger.error(err);return callback(err)};proto.find=function(obj){}},{cloneextend:53,moment:55,underscore:58}],21:[function(require,module,exports){var viz=exports;viz._id="viz";viz.DatePicker=require("./DatePicker");viz.Canvas=require("./Canvas");viz.Sparkline=require("./Sparkline");viz.Metric=require("./Metric");viz.Geo=require("./Geo");viz.Pie=require("./Pie");viz.MiniTable=require("./MiniTable");viz.PunchCard=require("./PunchCard");viz.Table=require("./Table");viz.Timeline=require("./Timeline");viz.onscreen=[];viz.stam=function(callback){return viz.pickers.init(callback)}},{"./Canvas":10,"./DatePicker":11,"./Geo":12,"./Metric":13,"./MiniTable":14,"./Pie":15,"./PunchCard":16,"./Sparkline":17,"./Table":18,"./Timeline":19}],22:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;Buffer._useTypedArrays=function(){if(typeof Uint8Array!=="function"||typeof ArrayBuffer!=="function")return false;try{var arr=new Uint8Array(0);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;if(encoding==="base64"&&type==="string"){subject=stringtrim(subject);while(subject.length%4!==0){subject=subject+"="}}var length;if(type==="number")length=coerce(subject);else if(type==="string")length=Buffer.byteLength(subject,encoding);else if(type==="object")length=coerce(subject.length);else throw new Error("First argument needs to be a number, array or string.");var buf;if(Buffer._useTypedArrays){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer._useTypedArrays&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){for(i=0;iremaining){length=remaining}}var strLen=string.length;assert(strLen%2===0,"Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=_hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=_utf8Write(this,string,offset,length);break;case"ascii":ret=_asciiWrite(this,string,offset,length);break;case"binary":ret=_binaryWrite(this,string,offset,length);break;case"base64":ret=_base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=_utf16leWrite(this,string,offset,length);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toString=function(encoding,start,end){var self=this;encoding=String(encoding||"utf8").toLowerCase();start=Number(start)||0;end=end!==undefined?Number(end):end=self.length;if(end===start)return"";var ret;switch(encoding){case"hex":ret=_hexSlice(self,start,end);break;case"utf8":case"utf-8":ret=_utf8Slice(self,start,end);break;case"ascii":ret=_asciiSlice(self,start,end);break;case"binary":ret=_binarySlice(self,start,end);break;case"base64":ret=_base64Slice(self,start,end);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=_utf16leSlice(self,start,end);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;assert(end>=start,"sourceEnd < sourceStart");assert(target_start>=0&&target_start=0&&start=0&&end<=source.length,"sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_startlen)end=len;var out="";for(var i=start;i=this.length)return;return this[offset]};function _readUInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1=len)return;var val;if(littleEndian){val=buf[offset];if(offset+1=len)return;var val;if(littleEndian){if(offset+2>>0)}else{if(offset+1>>0)}return val}Buffer.prototype.readUInt32LE=function(offset,noAssert){return _readUInt32(this,offset,true,noAssert)};Buffer.prototype.readUInt32BE=function(offset,noAssert){return _readUInt32(this,offset,false,noAssert)};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset=this.length)return;var neg=this[offset]&128;if(neg)return(255-this[offset]+1)*-1;else return this[offset]};function _readInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1=len)return;var val=_readUInt16(buf,offset,littleEndian,true);var neg=val&32768;if(neg)return(65535-val+1)*-1;else return val}Buffer.prototype.readInt16LE=function(offset,noAssert){return _readInt16(this,offset,true,noAssert)};Buffer.prototype.readInt16BE=function(offset,noAssert){return _readInt16(this,offset,false,noAssert)};function _readInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3=len)return;var val=_readUInt32(buf,offset,littleEndian,true);var neg=val&2147483648;if(neg)return(4294967295-val+1)*-1;else return val}Buffer.prototype.readInt32LE=function(offset,noAssert){return _readInt32(this,offset,true,noAssert)};Buffer.prototype.readInt32BE=function(offset,noAssert){return _readInt32(this,offset,false,noAssert)};function _readFloat(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+3=this.length)return;this[offset]=value};function _writeUInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1=len)return;for(var i=0,j=Math.min(len-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){_writeUInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){_writeUInt16(this,value,offset,false,noAssert)};function _writeUInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3=len)return;for(var i=0,j=Math.min(len-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){_writeUInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){_writeUInt32(this,value,offset,false,noAssert)};Buffer.prototype.writeInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset=this.length)return;if(value>=0)this.writeUInt8(value,offset,noAssert);else this.writeUInt8(255+value+1,offset,noAssert)};function _writeInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1=len)return;if(value>=0)_writeUInt16(buf,value,offset,littleEndian,noAssert);else _writeUInt16(buf,65535+value+1,offset,littleEndian,noAssert)}Buffer.prototype.writeInt16LE=function(value,offset,noAssert){_writeInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){_writeInt16(this,value,offset,false,noAssert)};function _writeInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3=len)return;if(value>=0)_writeUInt32(buf,value,offset,littleEndian,noAssert);else _writeUInt32(buf,4294967295+value+1,offset,littleEndian,noAssert)}Buffer.prototype.writeInt32LE=function(value,offset,noAssert){_writeInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){_writeInt32(this,value,offset,false,noAssert)};function _writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3=len)return;ieee754.write(buf,value,offset,littleEndian,23,4)}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){_writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){_writeFloat(this,value,offset,false,noAssert)};function _writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+7=len)return;ieee754.write(buf,value,offset,littleEndian,52,8)}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){_writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){_writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(typeof value==="string"){value=value.charCodeAt(0)}assert(typeof value==="number"&&!isNaN(value),"value is not a number");assert(end>=start,"end < start");if(end===start)return;if(this.length===0)return;assert(start>=0&&start=0&&end<=this.length,"end out of bounds");for(var i=start;i"};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array==="function"){if(Buffer._useTypedArrays){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i=len)return len;if(index>=0)return index;index+=len;if(index>=0)return index;return 0}function coerce(length){length=~~Math.ceil(+length);return length<0?0:length}function isArray(subject){return(Array.isArray||function(subject){return Object.prototype.toString.call(subject)==="[object Array]"})(subject)}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){var pos;for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}function verifuint(value,max){assert(typeof value==="number","cannot write a non-number as a number");assert(value>=0,"specified a negative value for writing an unsigned value");assert(value<=max,"value is larger than maximum value for type");assert(Math.floor(value)===value,"value has a fractional component")}function verifsint(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value");assert(Math.floor(value)===value,"value has a fractional component")}function verifIEEE754(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value")}function assert(test,message){if(!test)throw new Error(message||"Failed assertion")}},{"base64-js":23,ieee754:24}],23:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var ZERO="0".charCodeAt(0);var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}module.exports.toByteArray=b64ToByteArray;module.exports.fromByteArray=uint8ToBase64})()},{}],24:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],25:[function(require,module,exports){var Buffer=require("buffer").Buffer;var intSize=4;var zeroBuffer=new Buffer(intSize);zeroBuffer.fill(0);var chrsz=8;function toArray(buf,bigEndian){if(buf.length%intSize!==0){var len=buf.length+(intSize-buf.length%intSize);buf=Buffer.concat([buf,zeroBuffer],len)}var arr=[];var fn=bigEndian?buf.readInt32BE:buf.readInt32LE;for(var i=0;iblocksize){key=fn(key)}else if(key.length>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":25}],28:[function(require,module,exports){(function(){var _global=this;var mathRNG,whatwgRNG;mathRNG=function(size){var bytes=new Array(size);var r;for(var i=0,r;i>>((i&3)<<3)&255}return bytes};if(_global.crypto&&crypto.getRandomValues){whatwgRNG=function(size){var bytes=new Uint8Array(size);crypto.getRandomValues(bytes);return bytes}}module.exports=whatwgRNG||mathRNG})()},{}],29:[function(require,module,exports){var helpers=require("./helpers");function core_sha1(x,len){x[len>>5]|=128<<24-len%32;x[(len+64>>9<<4)+15]=len;var w=Array(80);var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;var e=-1009589776;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function rol(num,cnt){return num<>>32-cnt}module.exports=function sha1(buf){return helpers.hash(buf,core_sha1,20,true)}},{"./helpers":25}],30:[function(require,module,exports){var helpers=require("./helpers");var safe_add=function(x,y){var lsw=(x&65535)+(y&65535);var msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535};var S=function(X,n){return X>>>n|X<<32-n};var R=function(X,n){return X>>>n};var Ch=function(x,y,z){return x&y^~x&z};var Maj=function(x,y,z){return x&y^x&z^y&z};var Sigma0256=function(x){return S(x,2)^S(x,13)^S(x,22)};var Sigma1256=function(x){return S(x,6)^S(x,11)^S(x,25)};var Gamma0256=function(x){return S(x,7)^S(x,18)^R(x,3)};var Gamma1256=function(x){return S(x,17)^S(x,19)^R(x,10)};var core_sha256=function(m,l){var K=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298);var HASH=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225);var W=new Array(64);var a,b,c,d,e,f,g,h,i,j;var T1,T2;m[l>>5]|=128<<24-l%32;m[(l+64>>9<<4)+15]=l;for(var i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);console.trace()}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],32:[function(require,module,exports){var http=module.exports;var EventEmitter=require("events").EventEmitter;var Request=require("./lib/request");var url=require("url");http.request=function(params,cb){if(typeof params==="string"){params=url.parse(params)}if(!params)params={};if(!params.host&&!params.port){params.port=parseInt(window.location.port,10)}if(!params.host&¶ms.hostname){params.host=params.hostname}if(!params.scheme)params.scheme=window.location.protocol.split(":")[0];if(!params.host){params.host=window.location.hostname||window.location.host}if(/:/.test(params.host)){if(!params.port){params.port=params.host.split(":")[1]}params.host=params.host.split(":")[0]}if(!params.port)params.port=params.scheme=="https"?443:80;var req=new Request(new xhrHttp,params);if(cb)req.on("response",cb);return req};http.get=function(params,cb){params.method="GET";var req=http.request(params,cb);req.end();return req};http.Agent=function(){};http.Agent.defaultMaxSockets=4;var xhrHttp=function(){if(typeof window==="undefined"){throw new Error("no window object present")}else if(window.XMLHttpRequest){return window.XMLHttpRequest}else if(window.ActiveXObject){var axs=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"];for(var i=0;ithis.offset){this.emit("data",respBody.slice(this.offset));this.offset=respBody.length}};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{stream:43,util:52}],35:[function(require,module,exports){(function(){var object=typeof exports!="undefined"?exports:this;var chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function InvalidCharacterError(message){this.message=message}InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";object.btoa||(object.btoa=function(input){for(var block,charCode,idx=0,map=chars,output="";input.charAt(idx|0)||(map="=",idx%1);output+=map.charAt(63&block>>8-idx%1*8)){charCode=input.charCodeAt(idx+=3/4);if(charCode>255){throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.")}block=block<<8|charCode}return output});object.atob||(object.atob=function(input){input=input.replace(/=+$/,"");if(input.length%4==1){throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.")}for(var bc=0,bs,buffer,idx=0,output="";buffer=input.charAt(idx++);~buffer&&(bs=bc%4?bs*64+buffer:buffer,bc++%4)?output+=String.fromCharCode(255&bs>>(-2*bc&6)):0){buffer=chars.indexOf(buffer)}return output})})()},{}],36:[function(require,module,exports){var http=require("http");var https=module.exports;for(var key in http){if(http.hasOwnProperty(key))https[key]=http[key]}https.request=function(params,cb){if(!params)params={};params.scheme="https";return http.request.call(this,params,cb)}},{http:32}],37:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],38:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^ -~]/,regexSeparators=/\x2E|\u3002|\uFF0E|\uFF61/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw RangeError(errors[type])}function map(array,fn){var length=array.length;while(length--){array[length]=fn(array[length])}return array}function mapDomain(string,fn){return map(string.split(regexSeparators),fn).join(".")}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=55296&&value<=56319&&counter65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q0&&len>maxKeys){len=maxKeys}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],40:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return obj[k].map(function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],45:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./transform.js");var inherits=require("inherits");inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./transform.js":47,inherits:37}],46:[function(require,module,exports){(function(process){module.exports=Readable;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var Stream=require("./index.js");var Buffer=require("buffer").Buffer;var setImmediate=require("process/browser.js").nextTick;var StringDecoder;var inherits=require("inherits");inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(isNaN(n)||n===null){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);var ret;if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode&&!er){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)setImmediate(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;setImmediate(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;setImmediate(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,offset,i);this.charReceived+=i-offset;offset=i;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(i==buffer.length)return charStr;buffer=buffer.slice(i,buffer.length);break}var lenIncomplete=this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-lenIncomplete,end);this.charReceived=lenIncomplete;end-=lenIncomplete}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);this.charBuffer.write(charStr.charAt(charStr.length-1),this.encoding);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}return i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){var incomplete=this.charReceived=buffer.length%2;this.charLength=incomplete?2:0;return incomplete}function base64DetectIncompleteChar(buffer){var incomplete=this.charReceived=buffer.length%3;this.charLength=incomplete?3:0;return incomplete}},{buffer:22}],50:[function(require,module,exports){(function(){"use strict";var punycode=require("punycode");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,delims=["<",">",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","~","`"].concat(delims),autoEscape=["'"].concat(delims),nonHostChars=["%","/","?",";","#"].concat(unwise).concat(autoEscape),nonAuthChars=["/","@","?","#"].concat(delims),hostnameMaxLen=255,hostnamePartPattern=/^[a-zA-Z0-9][a-z0-9A-Z_-]{0,62}$/,hostnamePartStart=/^([a-zA-Z0-9][a-z0-9A-Z_-]{0,62})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},pathedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"ftp:":true,"gopher:":true,"file:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&typeof url==="object"&&url.href)return url;if(typeof url!=="string"){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var out={},rest=url;rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();out.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);out.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var atSign=rest.indexOf("@");if(atSign!==-1){var auth=rest.slice(0,atSign);var hasAuth=true;for(var i=0,l=nonAuthChars.length;ihostnameMaxLen){out.hostname=""}else if(!ipv6Hostname){var hostparts=out.hostname.split(/\./);for(var i=0,l=hostparts.length;i127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}out.hostname=validParts.join(".");break}}}}out.hostname=out.hostname.toLowerCase();if(!ipv6Hostname){var domainArray=out.hostname.split(".");var newOut=[];for(var i=0;i0?source.host.split("@"):false;if(authInHost){source.auth=authInHost.shift();source.host=source.hostname=authInHost.shift()}}source.search=relative.search;source.query=relative.query;if(source.pathname!==undefined||source.search!==undefined){source.path=(source.pathname?source.pathname:"")+(source.search?source.search:"")}source.href=urlFormat(source);return source}if(!srcPath.length){delete source.pathname;if(!source.search){source.path="/"+source.search}else{delete source.path}source.href=urlFormat(source);return source}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(source.host||relative.host)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last=="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){source.hostname=source.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=source.host&&source.host.indexOf("@")>0?source.host.split("@"):false;if(authInHost){source.auth=authInHost.shift();source.host=source.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||source.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}source.pathname=srcPath.join("/");if(source.pathname!==undefined||source.search!==undefined){source.path=(source.pathname?source.pathname:"")+(source.search?source.search:"")}source.auth=relative.auth||source.auth;source.slashes=source.slashes||relative.slashes;source.href=urlFormat(source);return source}function parseHost(host){var out={};var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){out.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)out.hostname=host;return out}})()},{punycode:38,querystring:41}],51:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],52:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array) -})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("/home/itay/dev/joola.io.sdk/node_modules/process/browser.js"),typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":51,"/home/itay/dev/joola.io.sdk/node_modules/process/browser.js":56,inherits:37}],53:[function(require,module,exports){function replace(a,b){if(!b){return a}var key;for(key in b){if(b.hasOwnProperty(key)){a[key]=b[key]}}return a}exports.replace=replace;function add(a,b){if(!b){return a}var key;for(key in b){if(b.hasOwnProperty(key)){if(typeof a[key]==="undefined"||a[key]===null){a[key]=b[key]}}}return a}exports.add=add;function extend(a,b,context,newobjs,aparent,aname,haveaparent){if(a==b){return a}if(!b){return a}var key,clean_context=false,return_sublevel=false,b_pos;if(!haveaparent){aparent={a:a};aname="a"}if(!context){clean_context=true;context=[];newobjs=[]}b_pos=context.indexOf(b);if(b_pos==-1){context.push(b);newobjs.push([aparent,aname])}else{return newobjs[b_pos][0][newobjs[b_pos][1]]}for(key in b){if(b.hasOwnProperty(key)){if(typeof a[key]==="undefined"){if(typeof b[key]==="object"){if(b[key]instanceof Array){a[key]=extend([],b[key],context,newobjs,a,key,true)}else if(b[key]===null){a[key]=null}else if(b[key]instanceof Date){a[key]=new b[key].constructor;a[key].setTime(b[key].getTime())}else{a[key]=extend({},b[key],context,newobjs,a,key,true)}}else{a[key]=b[key]}}else if(typeof a[key]==="object"&&a[key]!==null){a[key]=extend(a[key],b[key],context,newobjs,a,key,true)}else{a[key]=b[key]}}}if(clean_context){context=null;newobjs=null}if(!haveaparent){aparent=null;return a}if(typeof a==="object"&&!(a instanceof Array)){}return a}exports.extend=extend;function extenduptolevel(a,b,levels,context,newobjs,aparent,aname,haveaparent){if(a==b){return a}if(!b){return a}var key,clean_context=false,return_sublevel=false;if(!haveaparent){aparent={a:a};aname="a"}if(!context){clean_context=true;context=[];newobjs=[]}b_pos=context.indexOf(b);if(b_pos==-1){context.push(b);newobjs.push([aparent,aname])}else{return newobjs[b_pos][0][newobjs[b_pos][1]]}for(key in b){if(b.hasOwnProperty(key)){if(typeof a[key]==="undefined"){if(typeof b[key]==="object"&&levels>0){if(b[key]instanceof Array){a[key]=extenduptolevel([],b[key],levels-1,context,newobjs,a,key,true)}else if(b[key]===null){a[key]=null}else if(b[key]instanceof Date){a[key]=new b[key].constructor;a[key].setTime(b[key].getTime())}else{a[key]=extenduptolevel({},b[key],levels-1,context,newobjs,a,key,true)}}else{a[key]=b[key]}}else if(typeof a[key]==="object"&&a[key]!==null&&levels>0){a[key]=extenduptolevel(a[key],b[key],levels-1,context,newobjs,a,key,true)}else{a[key]=b[key]}}}if(clean_context){context=null;newobjs=null}if(!haveaparent){aparent=null;return a}if(typeof a==="object"&&!(a instanceof Array)){}return a}exports.extenduptolevel=extenduptolevel;function clone(obj){if(typeof obj==="object"){if(obj===null){return null}if(obj instanceof Array){return extend([],obj)}else if(obj instanceof Date){var t=new obj.constructor;t.setTime(obj.getTime());return t}else{return extend({},obj)}}return obj}exports.clone=clone;function cloneextend(obj,exteddata){if(typeof obj==="object"){if(obj===null){return null}return extend(clone(obj),exteddata)}return obj}exports.cloneextend=cloneextend;function cloneuptolevel(obj,level){if(typeof obj==="object"){if(obj===null){return null}if(obj instanceof Array){return extenduptolevel([],obj,level)}return extenduptolevel({},obj,level)}return obj}exports.cloneuptolevel=cloneuptolevel;function foreach(object,block,context){if(object){if(typeof object==="object"&&object instanceof Array)return object.forEach(object,block,context);else{if(object)for(var key in object){if(object.hasOwnProperty(key)){if(block.call(context,object[key],key,object)===false)break}}}}}exports.foreach=foreach},{}],54:[function(require,module,exports){(function(process){!function(exports,undefined){var isArray=Array.isArray?Array.isArray:function _isArray(obj){return Object.prototype.toString.call(obj)==="[object Array]"};var defaultMaxListeners=10;function init(){this._events={};if(this._conf){configure.call(this,this._conf)}}function configure(conf){if(conf){this._conf=conf;conf.delimiter&&(this.delimiter=conf.delimiter);conf.maxListeners&&(this._events.maxListeners=conf.maxListeners);conf.wildcard&&(this.wildcard=conf.wildcard);conf.newListener&&(this.newListener=conf.newListener);if(this.wildcard){this.listenerTree={}}}}function EventEmitter(conf){this._events={};this.newListener=false;configure.call(this,conf)}function searchListenerTree(handlers,type,tree,i){if(!tree){return[]}var listeners=[],leaf,len,branch,xTree,xxTree,isolatedBranch,endReached,typeLength=type.length,currentType=type[i],nextType=type[i+1];if(i===typeLength&&tree._listeners){if(typeof tree._listeners==="function"){handlers&&handlers.push(tree._listeners);return[tree]}else{for(leaf=0,len=tree._listeners.length;leaf0&&tree._listeners.length>m){tree._listeners.warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",tree._listeners.length);console.trace()}}}return true}name=type.shift()}return true}EventEmitter.prototype.delimiter=".";EventEmitter.prototype.setMaxListeners=function(n){this._events||init.call(this);this._events.maxListeners=n;if(!this._conf)this._conf={};this._conf.maxListeners=n};EventEmitter.prototype.event="";EventEmitter.prototype.once=function(event,fn){this.many(event,1,fn);return this};EventEmitter.prototype.many=function(event,ttl,fn){var self=this;if(typeof fn!=="function"){throw new Error("many only accepts instances of Function")}function listener(){if(--ttl===0){self.off(event,listener)}fn.apply(this,arguments)}listener._origin=fn;this.on(event,listener);return self};EventEmitter.prototype.emit=function(){this._events||init.call(this);var type=arguments[0];if(type==="newListener"&&!this.newListener){if(!this._events.newListener){return false}}if(this._all){var l=arguments.length;var args=new Array(l-1);for(var i=1;i1)switch(arguments.length){case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:var l=arguments.length;var args=new Array(l-1);for(var i=1;i0||this._all}else{return this._all}};EventEmitter.prototype.on=function(type,listener){if(typeof type==="function"){this.onAny(type);return this}if(typeof listener!=="function"){throw new Error("on only accepts instances of Function")}this._events||init.call(this);this.emit("newListener",type,listener);if(this.wildcard){growListenerTree.call(this,type,listener);return this}if(!this._events[type]){this._events[type]=listener}else if(typeof this._events[type]==="function"){this._events[type]=[this._events[type],listener]}else if(isArray(this._events[type])){this._events[type].push(listener);if(!this._events[type].warned){var m=defaultMaxListeners;if(typeof this._events.maxListeners!=="undefined"){m=this._events.maxListeners}if(m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);console.trace()}}}return this};EventEmitter.prototype.onAny=function(fn){if(!this._all){this._all=[]}if(typeof fn!=="function"){throw new Error("onAny only accepts instances of Function")}this._all.push(fn);return this};EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prototype.off=function(type,listener){if(typeof listener!=="function"){throw new Error("removeListener only takes instances of Function")}var handlers,leafs=[];if(this.wildcard){var ns=typeof type==="string"?type.split(this.delimiter):type.slice();leafs=searchListenerTree.call(this,null,ns,this.listenerTree,0)}else{if(!this._events[type])return this;handlers=this._events[type];leafs.push({_listeners:handlers})}for(var iLeaf=0;iLeaf0){fns=this._all;for(i=0,l=fns.length;i=0?"+":"-";return sign+leftZeroFill(Math.abs(y),6)},gg:function(){return leftZeroFill(this.weekYear()%100,2)},gggg:function(){return leftZeroFill(this.weekYear(),4)},ggggg:function(){return leftZeroFill(this.weekYear(),5)},GG:function(){return leftZeroFill(this.isoWeekYear()%100,2)},GGGG:function(){return leftZeroFill(this.isoWeekYear(),4)},GGGGG:function(){return leftZeroFill(this.isoWeekYear(),5)},e:function(){return this.weekday()},E:function(){return this.isoWeekday()},a:function(){return this.lang().meridiem(this.hours(),this.minutes(),true)},A:function(){return this.lang().meridiem(this.hours(),this.minutes(),false)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return toInt(this.milliseconds()/100)},SS:function(){return leftZeroFill(toInt(this.milliseconds()/10),2)},SSS:function(){return leftZeroFill(this.milliseconds(),3)},SSSS:function(){return leftZeroFill(this.milliseconds(),3)},Z:function(){var a=-this.zone(),b="+";if(a<0){a=-a;b="-"}return b+leftZeroFill(toInt(a/60),2)+":"+leftZeroFill(toInt(a)%60,2)},ZZ:function(){var a=-this.zone(),b="+";if(a<0){a=-a;b="-"}return b+leftZeroFill(toInt(a/60),2)+leftZeroFill(toInt(a)%60,2)},z:function(){return this.zoneAbbr()},zz:function(){return this.zoneName()},X:function(){return this.unix()},Q:function(){return this.quarter()}},lists=["months","monthsShort","weekdays","weekdaysShort","weekdaysMin"];function defaultParsingFlags(){return{empty:false,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:false,invalidMonth:null,invalidFormat:false,userInvalidated:false,iso:false}}function padToken(func,count){return function(a){return leftZeroFill(func.call(this,a),count)}}function ordinalizeToken(func,period){return function(a){return this.lang().ordinal(func.call(this,a),period)}}while(ordinalizeTokens.length){i=ordinalizeTokens.pop();formatTokenFunctions[i+"o"]=ordinalizeToken(formatTokenFunctions[i],i)}while(paddedTokens.length){i=paddedTokens.pop();formatTokenFunctions[i+i]=padToken(formatTokenFunctions[i],2)}formatTokenFunctions.DDDD=padToken(formatTokenFunctions.DDD,3);function Language(){}function Moment(config){checkOverflow(config);extend(this,config)}function Duration(duration){var normalizedInput=normalizeObjectUnits(duration),years=normalizedInput.year||0,months=normalizedInput.month||0,weeks=normalizedInput.week||0,days=normalizedInput.day||0,hours=normalizedInput.hour||0,minutes=normalizedInput.minute||0,seconds=normalizedInput.second||0,milliseconds=normalizedInput.millisecond||0;this._milliseconds=+milliseconds+seconds*1e3+minutes*6e4+hours*36e5;this._days=+days+weeks*7;this._months=+months+years*12;this._data={};this._bubble()}function extend(a,b){for(var i in b){if(b.hasOwnProperty(i)){a[i]=b[i]}}if(b.hasOwnProperty("toString")){a.toString=b.toString}if(b.hasOwnProperty("valueOf")){a.valueOf=b.valueOf}return a}function cloneMoment(m){var result={},i;for(i in m){if(m.hasOwnProperty(i)&&momentProperties.hasOwnProperty(i)){result[i]=m[i]}}return result}function absRound(number){if(number<0){return Math.ceil(number)}else{return Math.floor(number)}}function leftZeroFill(number,targetLength,forceSign){var output=""+Math.abs(number),sign=number>=0;while(output.length=0){value=Math.floor(coercedNumber)}else{value=Math.ceil(coercedNumber)}}return value}function daysInMonth(year,month){return new Date(Date.UTC(year,month+1,0)).getUTCDate()}function daysInYear(year){return isLeapYear(year)?366:365}function isLeapYear(year){return year%4===0&&year%100!==0||year%400===0}function checkOverflow(m){var overflow;if(m._a&&m._pf.overflow===-2){overflow=m._a[MONTH]<0||m._a[MONTH]>11?MONTH:m._a[DATE]<1||m._a[DATE]>daysInMonth(m._a[YEAR],m._a[MONTH])?DATE:m._a[HOUR]<0||m._a[HOUR]>23?HOUR:m._a[MINUTE]<0||m._a[MINUTE]>59?MINUTE:m._a[SECOND]<0||m._a[SECOND]>59?SECOND:m._a[MILLISECOND]<0||m._a[MILLISECOND]>999?MILLISECOND:-1;if(m._pf._overflowDayOfYear&&(overflowDATE)){overflow=DATE}m._pf.overflow=overflow}}function isValid(m){if(m._isValid==null){m._isValid=!isNaN(m._d.getTime())&&m._pf.overflow<0&&!m._pf.empty&&!m._pf.invalidMonth&&!m._pf.nullInput&&!m._pf.invalidFormat&&!m._pf.userInvalidated;if(m._strict){m._isValid=m._isValid&&m._pf.charsLeftOver===0&&m._pf.unusedTokens.length===0}}return m._isValid}function normalizeLanguage(key){return key?key.toLowerCase().replace("_","-"):key}function makeAs(input,model){return model._isUTC?moment(input).zone(model._offset||0):moment(input).local()}extend(Language.prototype,{set:function(config){var prop,i;for(i in config){prop=config[i];if(typeof prop==="function"){this[i]=prop}else{this["_"+i]=prop}}},_months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),months:function(m){return this._months[m.month()]},_monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),monthsShort:function(m){return this._monthsShort[m.month()]},monthsParse:function(monthName){var i,mom,regex;if(!this._monthsParse){this._monthsParse=[]}for(i=0;i<12;i++){if(!this._monthsParse[i]){mom=moment.utc([2e3,i]);regex="^"+this.months(mom,"")+"|^"+this.monthsShort(mom,"");this._monthsParse[i]=new RegExp(regex.replace(".",""),"i")}if(this._monthsParse[i].test(monthName)){return i}}},_weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdays:function(m){return this._weekdays[m.day()]},_weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysShort:function(m){return this._weekdaysShort[m.day()]},_weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),weekdaysMin:function(m){return this._weekdaysMin[m.day()]},weekdaysParse:function(weekdayName){var i,mom,regex;if(!this._weekdaysParse){this._weekdaysParse=[]}for(i=0;i<7;i++){if(!this._weekdaysParse[i]){mom=moment([2e3,1]).day(i);regex="^"+this.weekdays(mom,"")+"|^"+this.weekdaysShort(mom,"")+"|^"+this.weekdaysMin(mom,"");this._weekdaysParse[i]=new RegExp(regex.replace(".",""),"i")}if(this._weekdaysParse[i].test(weekdayName)){return i}}},_longDateFormat:{LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D YYYY",LLL:"MMMM D YYYY LT",LLLL:"dddd, MMMM D YYYY LT"},longDateFormat:function(key){var output=this._longDateFormat[key];if(!output&&this._longDateFormat[key.toUpperCase()]){output=this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(val){return val.slice(1)});this._longDateFormat[key]=output}return output},isPM:function(input){return(input+"").toLowerCase().charAt(0)==="p"},_meridiemParse:/[ap]\.?m?\.?/i,meridiem:function(hours,minutes,isLower){if(hours>11){return isLower?"pm":"PM"}else{return isLower?"am":"AM"}},_calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},calendar:function(key,mom){var output=this._calendar[key];return typeof output==="function"?output.apply(mom):output},_relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},relativeTime:function(number,withoutSuffix,string,isFuture){var output=this._relativeTime[string];return typeof output==="function"?output(number,withoutSuffix,string,isFuture):output.replace(/%d/i,number)},pastFuture:function(diff,output){var format=this._relativeTime[diff>0?"future":"past"];return typeof format==="function"?format(output):format.replace(/%s/i,output)},ordinal:function(number){return this._ordinal.replace("%d",number)},_ordinal:"%d",preparse:function(string){return string},postformat:function(string){return string},week:function(mom){return weekOfYear(mom,this._week.dow,this._week.doy).week},_week:{dow:0,doy:6},_invalidDate:"Invalid date",invalidDate:function(){return this._invalidDate}});function loadLang(key,values){values.abbr=key;if(!languages[key]){languages[key]=new Language}languages[key].set(values); -return languages[key]}function unloadLang(key){delete languages[key]}function getLangDefinition(key){var i=0,j,lang,next,split,get=function(k){if(!languages[k]&&hasModule){try{require("./lang/"+k)}catch(e){}}return languages[k]};if(!key){return moment.fn._lang}if(!isArray(key)){lang=get(key);if(lang){return lang}key=[key]}while(i0){lang=get(split.slice(0,j).join("-"));if(lang){return lang}if(next&&next.length>=j&&compareArrays(split,next,true)>=j-1){break}j--}i++}return moment.fn._lang}function removeFormattingTokens(input){if(input.match(/\[[\s\S]/)){return input.replace(/^\[|\]$/g,"")}return input.replace(/\\/g,"")}function makeFormatFunction(format){var array=format.match(formattingTokens),i,length;for(i=0,length=array.length;i=0&&localFormattingTokens.test(format)){format=format.replace(localFormattingTokens,replaceLongDateFormatTokens);localFormattingTokens.lastIndex=0;i-=1}return format}function getParseRegexForToken(token,config){var a,strict=config._strict;switch(token){case"DDDD":return parseTokenThreeDigits;case"YYYY":case"GGGG":case"gggg":return strict?parseTokenFourDigits:parseTokenOneToFourDigits;case"Y":case"G":case"g":return parseTokenSignedNumber;case"YYYYYY":case"YYYYY":case"GGGGG":case"ggggg":return strict?parseTokenSixDigits:parseTokenOneToSixDigits;case"S":if(strict){return parseTokenOneDigit}case"SS":if(strict){return parseTokenTwoDigits}case"SSS":if(strict){return parseTokenThreeDigits}case"DDD":return parseTokenOneToThreeDigits;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return parseTokenWord;case"a":case"A":return getLangDefinition(config._l)._meridiemParse;case"X":return parseTokenTimestampMs;case"Z":case"ZZ":return parseTokenTimezone;case"T":return parseTokenT;case"SSSS":return parseTokenDigits;case"MM":case"DD":case"YY":case"GG":case"gg":case"HH":case"hh":case"mm":case"ss":case"ww":case"WW":return strict?parseTokenTwoDigits:parseTokenOneOrTwoDigits;case"M":case"D":case"d":case"H":case"h":case"m":case"s":case"w":case"W":case"e":case"E":return parseTokenOneOrTwoDigits;default:a=new RegExp(regexpEscape(unescapeFormat(token.replace("\\","")),"i"));return a}}function timezoneMinutesFromString(string){string=string||"";var possibleTzMatches=string.match(parseTokenTimezone)||[],tzChunk=possibleTzMatches[possibleTzMatches.length-1]||[],parts=(tzChunk+"").match(parseTimezoneChunker)||["-",0,0],minutes=+(parts[1]*60)+toInt(parts[2]);return parts[0]==="+"?-minutes:minutes}function addTimeToArrayFromToken(token,input,config){var a,datePartArray=config._a;switch(token){case"M":case"MM":if(input!=null){datePartArray[MONTH]=toInt(input)-1}break;case"MMM":case"MMMM":a=getLangDefinition(config._l).monthsParse(input);if(a!=null){datePartArray[MONTH]=a}else{config._pf.invalidMonth=input}break;case"D":case"DD":if(input!=null){datePartArray[DATE]=toInt(input)}break;case"DDD":case"DDDD":if(input!=null){config._dayOfYear=toInt(input)}break;case"YY":datePartArray[YEAR]=toInt(input)+(toInt(input)>68?1900:2e3);break;case"YYYY":case"YYYYY":case"YYYYYY":datePartArray[YEAR]=toInt(input);break;case"a":case"A":config._isPm=getLangDefinition(config._l).isPM(input);break;case"H":case"HH":case"h":case"hh":datePartArray[HOUR]=toInt(input);break;case"m":case"mm":datePartArray[MINUTE]=toInt(input);break;case"s":case"ss":datePartArray[SECOND]=toInt(input);break;case"S":case"SS":case"SSS":case"SSSS":datePartArray[MILLISECOND]=toInt(("0."+input)*1e3);break;case"X":config._d=new Date(parseFloat(input)*1e3);break;case"Z":case"ZZ":config._useUTC=true;config._tzm=timezoneMinutesFromString(input);break;case"w":case"ww":case"W":case"WW":case"d":case"dd":case"ddd":case"dddd":case"e":case"E":token=token.substr(0,1);case"gg":case"gggg":case"GG":case"GGGG":case"GGGGG":token=token.substr(0,2);if(input){config._w=config._w||{};config._w[token]=input}break}}function dateFromConfig(config){var i,date,input=[],currentDate,yearToUse,fixYear,w,temp,lang,weekday,week;if(config._d){return}currentDate=currentDateArray(config);if(config._w&&config._a[DATE]==null&&config._a[MONTH]==null){fixYear=function(val){var int_val=parseInt(val,10);return val?val.length<3?int_val>68?1900+int_val:2e3+int_val:int_val:config._a[YEAR]==null?moment().weekYear():config._a[YEAR]};w=config._w;if(w.GG!=null||w.W!=null||w.E!=null){temp=dayOfYearFromWeeks(fixYear(w.GG),w.W||1,w.E,4,1)}else{lang=getLangDefinition(config._l);weekday=w.d!=null?parseWeekday(w.d,lang):w.e!=null?parseInt(w.e,10)+lang._week.dow:0;week=parseInt(w.w,10)||1;if(w.d!=null&&weekdaydaysInYear(yearToUse)){config._pf._overflowDayOfYear=true}date=makeUTCDate(yearToUse,0,config._dayOfYear);config._a[MONTH]=date.getUTCMonth();config._a[DATE]=date.getUTCDate()}for(i=0;i<3&&config._a[i]==null;++i){config._a[i]=input[i]=currentDate[i]}for(;i<7;i++){config._a[i]=input[i]=config._a[i]==null?i===2?1:0:config._a[i]}input[HOUR]+=toInt((config._tzm||0)/60);input[MINUTE]+=toInt((config._tzm||0)%60);config._d=(config._useUTC?makeUTCDate:makeDate).apply(null,input)}function dateFromObject(config){var normalizedInput;if(config._d){return}normalizedInput=normalizeObjectUnits(config._i);config._a=[normalizedInput.year,normalizedInput.month,normalizedInput.day,normalizedInput.hour,normalizedInput.minute,normalizedInput.second,normalizedInput.millisecond];dateFromConfig(config)}function currentDateArray(config){var now=new Date;if(config._useUTC){return[now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate()]}else{return[now.getFullYear(),now.getMonth(),now.getDate()]}}function makeDateFromStringAndFormat(config){config._a=[];config._pf.empty=true;var lang=getLangDefinition(config._l),string=""+config._i,i,parsedInput,tokens,token,skipped,stringLength=string.length,totalParsedInputLength=0;tokens=expandFormat(config._f,lang).match(formattingTokens)||[];for(i=0;i0){config._pf.unusedInput.push(skipped)}string=string.slice(string.indexOf(parsedInput)+parsedInput.length);totalParsedInputLength+=parsedInput.length}if(formatTokenFunctions[token]){if(parsedInput){config._pf.empty=false}else{config._pf.unusedTokens.push(token)}addTimeToArrayFromToken(token,parsedInput,config)}else if(config._strict&&!parsedInput){config._pf.unusedTokens.push(token)}}config._pf.charsLeftOver=stringLength-totalParsedInputLength;if(string.length>0){config._pf.unusedInput.push(string)}if(config._isPm&&config._a[HOUR]<12){config._a[HOUR]+=12}if(config._isPm===false&&config._a[HOUR]===12){config._a[HOUR]=0}dateFromConfig(config);checkOverflow(config)}function unescapeFormat(s){return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(matched,p1,p2,p3,p4){return p1||p2||p3||p4})}function regexpEscape(s){return s.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function makeDateFromStringAndArray(config){var tempConfig,bestMoment,scoreToBeat,i,currentScore;if(config._f.length===0){config._pf.invalidFormat=true;config._d=new Date(NaN);return}for(i=0;i0;args[4]=lang;return substituteTimeAgo.apply({},args)}function weekOfYear(mom,firstDayOfWeek,firstDayOfWeekOfYear){var end=firstDayOfWeekOfYear-firstDayOfWeek,daysToDayOfWeek=firstDayOfWeekOfYear-mom.day(),adjustedMoment;if(daysToDayOfWeek>end){daysToDayOfWeek-=7}if(daysToDayOfWeekfirstDayOfWeekOfYear?7:0)-(d0?year:year-1,dayOfYear:dayOfYear>0?dayOfYear:daysInYear(year-1)+dayOfYear}}function makeMoment(config){var input=config._i,format=config._f;if(input===null){return moment.invalid({nullInput:true})}if(typeof input==="string"){config._i=input=getLangDefinition().preparse(input)}if(moment.isMoment(input)){config=cloneMoment(input);config._d=new Date(+input._d)}else if(format){if(isArray(format)){makeDateFromStringAndArray(config)}else{makeDateFromStringAndFormat(config)}}else{makeDateFromInput(config)}return new Moment(config)}moment=function(input,format,lang,strict){var c;if(typeof lang==="boolean"){strict=lang;lang=undefined}c={};c._isAMomentObject=true;c._i=input;c._f=format;c._l=lang;c._strict=strict;c._isUTC=false;c._pf=defaultParsingFlags();return makeMoment(c)};moment.utc=function(input,format,lang,strict){var c;if(typeof lang==="boolean"){strict=lang;lang=undefined}c={};c._isAMomentObject=true;c._useUTC=true;c._isUTC=true;c._l=lang;c._i=input;c._f=format;c._strict=strict;c._pf=defaultParsingFlags();return makeMoment(c).utc()};moment.unix=function(input){return moment(input*1e3)};moment.duration=function(input,key){var duration=input,match=null,sign,ret,parseIso;if(moment.isDuration(input)){duration={ms:input._milliseconds,d:input._days,M:input._months}}else if(typeof input==="number"){duration={};if(key){duration[key]=input}else{duration.milliseconds=input}}else if(!!(match=aspNetTimeSpanJsonRegex.exec(input))){sign=match[1]==="-"?-1:1;duration={y:0,d:toInt(match[DATE])*sign,h:toInt(match[HOUR])*sign,m:toInt(match[MINUTE])*sign,s:toInt(match[SECOND])*sign,ms:toInt(match[MILLISECOND])*sign}}else if(!!(match=isoDurationRegex.exec(input))){sign=match[1]==="-"?-1:1;parseIso=function(inp){var res=inp&&parseFloat(inp.replace(",","."));return(isNaN(res)?0:res)*sign};duration={y:parseIso(match[2]),M:parseIso(match[3]),d:parseIso(match[4]),h:parseIso(match[5]),m:parseIso(match[6]),s:parseIso(match[7]),w:parseIso(match[8])}}ret=new Duration(duration);if(moment.isDuration(input)&&input.hasOwnProperty("_lang")){ret._lang=input._lang}return ret};moment.version=VERSION;moment.defaultFormat=isoFormat;moment.updateOffset=function(){};moment.lang=function(key,values){var r;if(!key){return moment.fn._lang._abbr}if(values){loadLang(normalizeLanguage(key),values)}else if(values===null){unloadLang(key);key="en"}else if(!languages[key]){getLangDefinition(key)}r=moment.duration.fn._lang=moment.fn._lang=getLangDefinition(key);return r._abbr};moment.langData=function(key){if(key&&key._lang&&key._lang._abbr){key=key._lang._abbr}return getLangDefinition(key)};moment.isMoment=function(obj){return obj instanceof Moment||obj!=null&&obj.hasOwnProperty("_isAMomentObject")};moment.isDuration=function(obj){return obj instanceof Duration};for(i=lists.length-1;i>=0;--i){makeList(lists[i])}moment.normalizeUnits=function(units){return normalizeUnits(units)};moment.invalid=function(flags){var m=moment.utc(NaN);if(flags!=null){extend(m._pf,flags)}else{m._pf.userInvalidated=true}return m};moment.parseZone=function(input){return moment(input).parseZone()};extend(moment.fn=Moment.prototype,{clone:function(){return moment(this)},valueOf:function(){return+this._d+(this._offset||0)*6e4},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().lang("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var m=moment(this).utc();if(00}return false},parsingFlags:function(){return extend({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(){return this.zone(0)},local:function(){this.zone(0);this._isUTC=false;return this},format:function(inputString){var output=formatMoment(this,inputString||moment.defaultFormat);return this.lang().postformat(output)},add:function(input,val){var dur;if(typeof input==="string"){dur=moment.duration(+val,input)}else{dur=moment.duration(input,val)}addOrSubtractDurationFromMoment(this,dur,1);return this},subtract:function(input,val){var dur;if(typeof input==="string"){dur=moment.duration(+val,input)}else{dur=moment.duration(input,val)}addOrSubtractDurationFromMoment(this,dur,-1);return this},diff:function(input,units,asFloat){var that=makeAs(input,this),zoneDiff=(this.zone()-that.zone())*6e4,diff,output;units=normalizeUnits(units);if(units==="year"||units==="month"){diff=(this.daysInMonth()+that.daysInMonth())*432e5;output=(this.year()-that.year())*12+(this.month()-that.month());output+=(this-moment(this).startOf("month")-(that-moment(that).startOf("month")))/diff;output-=(this.zone()-moment(this).startOf("month").zone()-(that.zone()-moment(that).startOf("month").zone()))*6e4/diff;if(units==="year"){output=output/12}}else{diff=this-that;output=units==="second"?diff/1e3:units==="minute"?diff/6e4:units==="hour"?diff/36e5:units==="day"?(diff-zoneDiff)/864e5:units==="week"?(diff-zoneDiff)/6048e5:diff}return asFloat?output:absRound(output)},from:function(time,withoutSuffix){return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix)},fromNow:function(withoutSuffix){return this.from(moment(),withoutSuffix)},calendar:function(){var sod=makeAs(moment(),this).startOf("day"),diff=this.diff(sod,"days",true),format=diff<-6?"sameElse":diff<-1?"lastWeek":diff<0?"lastDay":diff<1?"sameDay":diff<2?"nextDay":diff<7?"nextWeek":"sameElse";return this.format(this.lang().calendar(format,this))},isLeapYear:function(){return isLeapYear(this.year())},isDST:function(){return this.zone()+moment(input).startOf(units)},isBefore:function(input,units){units=typeof units!=="undefined"?units:"millisecond";return+this.clone().startOf(units)<+moment(input).startOf(units)},isSame:function(input,units){units=units||"ms";return+this.clone().startOf(units)===+makeAs(input,this).startOf(units)},min:function(other){other=moment.apply(null,arguments);return otherthis?this:other},zone:function(input){var offset=this._offset||0;if(input!=null){if(typeof input==="string"){input=timezoneMinutesFromString(input)}if(Math.abs(input)<16){input=input*60}this._offset=input;this._isUTC=true;if(offset!==input){addOrSubtractDurationFromMoment(this,moment.duration(offset-input,"m"),1,true)}}else{return this._isUTC?offset:this._d.getTimezoneOffset()}return this},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},parseZone:function(){if(this._tzm){this.zone(this._tzm)}else if(typeof this._i==="string"){this.zone(this._i)}return this},hasAlignedHourOffset:function(input){if(!input){input=0}else{input=moment(input).zone()}return(this.zone()-input)%60===0},daysInMonth:function(){return daysInMonth(this.year(),this.month())},dayOfYear:function(input){var dayOfYear=round((moment(this).startOf("day")-moment(this).startOf("year"))/864e5)+1;return input==null?dayOfYear:this.add("d",input-dayOfYear)},quarter:function(){return Math.ceil((this.month()+1)/3)},weekYear:function(input){var year=weekOfYear(this,this.lang()._week.dow,this.lang()._week.doy).year;return input==null?year:this.add("y",input-year)},isoWeekYear:function(input){var year=weekOfYear(this,1,4).year;return input==null?year:this.add("y",input-year)},week:function(input){var week=this.lang().week(this);return input==null?week:this.add("d",(input-week)*7)},isoWeek:function(input){var week=weekOfYear(this,1,4).week;return input==null?week:this.add("d",(input-week)*7)},weekday:function(input){var weekday=(this.day()+7-this.lang()._week.dow)%7;return input==null?weekday:this.add("d",input-weekday)},isoWeekday:function(input){return input==null?this.day()||7:this.day(this.day()%7?input:input-7)},get:function(units){units=normalizeUnits(units);return this[units]()},set:function(units,value){units=normalizeUnits(units);if(typeof this[units]==="function"){this[units](value)}return this},lang:function(key){if(key===undefined){return this._lang}else{this._lang=getLangDefinition(key);return this}}});function makeGetterAndSetter(name,key){moment.fn[name]=moment.fn[name+"s"]=function(input){var utc=this._isUTC?"UTC":"";if(input!=null){this._d["set"+utc+key](input);moment.updateOffset(this);return this}else{return this._d["get"+utc+key]()}}}for(i=0;i0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.once=noop;process.off=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],57:[function(require,module,exports){(function(){var io=module.exports;(function(exports,global){var io=exports;io.version="0.8.6";io.protocol=1;io.transports=[];io.j=[];io.sockets={};io.connect=function(host,details){var uri=io.util.parseUri(host),uuri,socket;if(global&&global.location){uri.protocol=uri.protocol||global.location.protocol.slice(0,-1);uri.host=uri.host||(global.document?global.document.domain:global.location.hostname);uri.port=uri.port||global.location.port}uuri=io.util.uniqueUri(uri);var options={host:uri.host,secure:"https"==uri.protocol,port:uri.port||("https"==uri.protocol?443:80),query:uri.query||""};io.util.merge(options,details);if(options["force new connection"]||!io.sockets[uuri]){socket=new io.Socket(options)}if(!options["force new connection"]&&socket){io.sockets[uuri]=socket}socket=socket||io.sockets[uuri];return socket.of(uri.path.length>1?uri.path:"")}})("object"===typeof module?module.exports:this.io={},this);(function(exports,global){var util=exports.util={};var re=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];util.parseUri=function(str){var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}return uri};util.uniqueUri=function(uri){var protocol=uri.protocol,host=uri.host,port=uri.port;if("document"in global){host=host||document.domain;port=port||(protocol=="https"&&document.location.protocol!=="https:"?443:document.location.port)}else{host=host||"localhost";if(!port&&protocol=="https"){port=443}}return(protocol||"http")+"://"+host+":"+(port||80)};util.query=function(base,addition){var query=util.chunkQuery(base||""),components=[];util.merge(query,util.chunkQuery(addition||""));for(var part in query){if(query.hasOwnProperty(part)){components.push(part+"="+query[part])}}return components.length?"?"+components.join("&"):""};util.chunkQuery=function(qs){var query={},params=qs.split("&"),i=0,l=params.length,kv;for(;iarr2.length?arr:arr2,shortest=arr.length>arr2.length?arr2:arr;for(var i=0,l=shortest.length;i0&&remaining.splice(0,1)[0]!=self.transport.name){}if(remaining.length){connect(remaining)}else{self.publish("connect_failed")}}}},self.options["connect timeout"])}})}connect();self.once("connect",function(){clearTimeout(self.connectTimeoutTimer);fn&&typeof fn=="function"&&fn()})});return this};Socket.prototype.packet=function(data){if(this.connected&&!this.doBuffer){this.transport.packet(data)}else{this.buffer.push(data)}return this};Socket.prototype.setBuffer=function(v){this.doBuffer=v;if(!v&&this.connected&&this.buffer.length){this.transport.payload(this.buffer);this.buffer=[]}};Socket.prototype.disconnect=function(){if(this.connected){if(this.open){this.of("").packet({type:"disconnect"})}this.onDisconnect("booted")}return this};Socket.prototype.disconnectSync=function(){var xhr=io.util.request(),uri=this.resource+"/"+io.protocol+"/"+this.sessionid;xhr.open("GET",uri,true);this.onDisconnect("booted")};Socket.prototype.isXDomain=function(){var port=global.location.port||("https:"==global.location.protocol?443:80);return this.options.host!==global.location.hostname||this.options.port!=port};Socket.prototype.onConnect=function(){if(!this.connected){this.connected=true;this.connecting=false;if(!this.doBuffer){this.setBuffer(false)}this.emit("connect")}};Socket.prototype.onOpen=function(){this.open=true};Socket.prototype.onClose=function(){this.open=false};Socket.prototype.onPacket=function(packet){this.of(packet.endpoint).onPacket(packet)};Socket.prototype.onError=function(err){if(err&&err.advice){if(err.advice==="reconnect"&&this.connected){this.disconnect();this.reconnect()}}this.publish("error",err&&err.reason?err.reason:err)};Socket.prototype.onDisconnect=function(reason){var wasConnected=this.connected;this.connected=false;this.connecting=false;this.open=false;if(wasConnected){this.transport.close();this.transport.clearTimeouts();this.publish("disconnect",reason);if("booted"!=reason&&this.options.reconnect&&!this.reconnecting){this.reconnect()}}};Socket.prototype.reconnect=function(){this.reconnecting=true;this.reconnectionAttempts=0;this.reconnectionDelay=this.options["reconnection delay"];var self=this,maxAttempts=this.options["max reconnection attempts"],tryMultiple=this.options["try multiple transports"],limit=this.options["reconnection limit"];function reset(){if(self.connected){for(var i in self.namespaces){if(self.namespaces.hasOwnProperty(i)&&""!==i){self.namespaces[i].packet({type:"connect"})}}self.publish("reconnect",self.transport.name,self.reconnectionAttempts)}self.removeListener("connect_failed",maybeReconnect);self.removeListener("connect",maybeReconnect);self.reconnecting=false;delete self.reconnectionAttempts;delete self.reconnectionDelay;delete self.reconnectionTimer;delete self.redoTransports;self.options["try multiple transports"]=tryMultiple}function maybeReconnect(){if(!self.reconnecting){return}if(self.connected){return reset()}if(self.connecting&&self.reconnecting){return self.reconnectionTimer=setTimeout(maybeReconnect,1e3)}if(self.reconnectionAttempts++>=maxAttempts){if(!self.redoTransports){self.on("connect_failed",maybeReconnect);self.options["try multiple transports"]=true;self.transport=self.getTransport();self.redoTransports=true;self.connect()}else{self.publish("reconnect_failed");reset()}}else{if(self.reconnectionDelay=10};Flashsocket.xdomainCheck=function(){return true};if(typeof window!="undefined"){WEB_SOCKET_DISABLE_AUTO_INITIALIZATION=true}io.transports.push("flashsocket")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);if("undefined"!=typeof window){var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+" 1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if(typeof j.readyState!=D&&j.readyState=="complete"||typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body)){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return Y[0]>X[0]||Y[0]==X[0]&&Y[1]>X[1]||Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=ad&&typeof ad=="string"?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab= 10.0.0 is required.");return}if(location.protocol=="file:"){console.error("WARNING: web-socket-js doesn't work in file:///... URL "+"unless you set Flash Security Settings properly. "+"Open the page via Web server i.e. http://...") -}WebSocket=function(url,protocols,proxyHost,proxyPort,headers){var self=this;self.__id=WebSocket.__nextId++;WebSocket.__instances[self.__id]=self;self.readyState=WebSocket.CONNECTING;self.bufferedAmount=0;self.__events={};if(!protocols){protocols=[]}else if(typeof protocols=="string"){protocols=[protocols]}setTimeout(function(){WebSocket.__addTask(function(){WebSocket.__flash.create(self.__id,url,protocols,proxyHost||null,proxyPort||0,headers||null)})},0)};WebSocket.prototype.send=function(data){if(this.readyState==WebSocket.CONNECTING){throw"INVALID_STATE_ERR: Web Socket connection has not been established"}var result=WebSocket.__flash.send(this.__id,encodeURIComponent(data));if(result<0){return true}else{this.bufferedAmount+=result;return false}};WebSocket.prototype.close=function(){if(this.readyState==WebSocket.CLOSED||this.readyState==WebSocket.CLOSING){return}this.readyState=WebSocket.CLOSING;WebSocket.__flash.close(this.__id)};WebSocket.prototype.addEventListener=function(type,listener,useCapture){if(!(type in this.__events)){this.__events[type]=[]}this.__events[type].push(listener)};WebSocket.prototype.removeEventListener=function(type,listener,useCapture){if(!(type in this.__events))return;var events=this.__events[type];for(var i=events.length-1;i>=0;--i){if(events[i]===listener){events.splice(i,1);break}}};WebSocket.prototype.dispatchEvent=function(event){var events=this.__events[event.type]||[];for(var i=0;i");this.doc.close();this.doc.parentWindow.s=this;var iframeC=this.doc.createElement("div");iframeC.className="socketio";this.doc.body.appendChild(iframeC);this.iframe=this.doc.createElement("iframe");iframeC.appendChild(this.iframe);var self=this,query=io.util.query(this.socket.options.query,"t="+ +new Date);this.iframe.src=this.prepareUrl()+query;io.util.on(window,"unload",function(){self.destroy()})};HTMLFile.prototype._=function(data,doc){this.onData(data);try{var script=doc.getElementsByTagName("script")[0];script.parentNode.removeChild(script)}catch(e){}};HTMLFile.prototype.destroy=function(){if(this.iframe){try{this.iframe.src="about:blank"}catch(e){}this.doc=null;this.iframe.parentNode.removeChild(this.iframe);this.iframe=null;CollectGarbage()}};HTMLFile.prototype.close=function(){this.destroy();return io.Transport.XHR.prototype.close.call(this)};HTMLFile.check=function(){if("ActiveXObject"in window){try{var a=new ActiveXObject("htmlfile");return a&&io.Transport.XHR.check()}catch(e){}}return false};HTMLFile.xdomainCheck=function(){return false};io.transports.push("htmlfile")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);(function(exports,io,global){exports["xhr-polling"]=XHRPolling;function XHRPolling(){io.Transport.XHR.apply(this,arguments)}io.util.inherit(XHRPolling,io.Transport.XHR);io.util.merge(XHRPolling,io.Transport.XHR);XHRPolling.prototype.name="xhr-polling";XHRPolling.prototype.open=function(){var self=this;io.Transport.XHR.prototype.open.call(self);return false};function empty(){}XHRPolling.prototype.get=function(){if(!this.open)return;var self=this;function stateChange(){if(this.readyState==4){this.onreadystatechange=empty;if(this.status==200){self.onData(this.responseText);self.get()}else{self.onClose()}}}function onload(){this.onload=empty;self.onData(this.responseText);self.get()}this.xhr=this.request();if(global.XDomainRequest&&this.xhr instanceof XDomainRequest){this.xhr.onload=this.xhr.onerror=onload}else{this.xhr.onreadystatechange=stateChange}this.xhr.send(null)};XHRPolling.prototype.onClose=function(){io.Transport.XHR.prototype.onClose.call(this);if(this.xhr){this.xhr.onreadystatechange=this.xhr.onload=empty;try{this.xhr.abort()}catch(e){}this.xhr=null}};XHRPolling.prototype.ready=function(socket,fn){var self=this;io.util.defer(function(){fn.call(self)})};io.transports.push("xhr-polling")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this);(function(exports,io,global){var indicator=global.document&&"MozAppearance"in global.document.documentElement.style;exports["jsonp-polling"]=JSONPPolling;function JSONPPolling(socket){io.Transport["xhr-polling"].apply(this,arguments);this.index=io.j.length;var self=this;io.j.push(function(msg){self._(msg)})}io.util.inherit(JSONPPolling,io.Transport["xhr-polling"]);JSONPPolling.prototype.name="jsonp-polling";JSONPPolling.prototype.post=function(data){var self=this,query=io.util.query(this.socket.options.query,"t="+ +new Date+"&i="+this.index);if(!this.form){var form=document.createElement("form"),area=document.createElement("textarea"),id=this.iframeId="socketio_iframe_"+this.index,iframe;form.className="socketio";form.style.position="absolute";form.style.top="-1000px";form.style.left="-1000px";form.target=id;form.method="POST";form.setAttribute("accept-charset","utf-8");area.name="d";form.appendChild(area);document.body.appendChild(form);this.form=form;this.area=area}this.form.action=this.prepareUrl()+query;function complete(){initIframe();self.socket.setBuffer(false)}function initIframe(){if(self.iframe){self.form.removeChild(self.iframe)}try{iframe=document.createElement('