diff --git a/bin/joola.io.js b/bin/joola.io.js index 241c67b..d32f3c9 100644 --- a/bin/joola.io.js +++ b/bin/joola.io.js @@ -77,7 +77,7 @@ Object.defineProperty(joolaio, 'APITOKEN', { joolaio.dispatch.users.verifyAPIToken(joolaio.APITOKEN, function (err, user) { joolaio.USER = user; - joolaio.TOKEN = user.token._; + //joolaio.TOKEN = user.token._; }); } }); @@ -237,9 +237,8 @@ joolaio.init = function (options, callback) { joolaio.dispatch.users.verifyAPIToken(joolaio._apitoken, function (err, user) { joolaio.USER = user; - joolaio.TOKEN = user.token._; - joolaio.events.emit('core.init.finish'); + joolaio.events.emit('ready'); if (typeof callback === 'function') return callback(null, joolaio); }); @@ -289,9 +288,9 @@ joolaio.set = function (key, value, callback) { return callback(new Error('Failed to verify API Token')); joolaio.USER = user; - joolaio.TOKEN = user.token._; - if (typeof callback === 'function') + if (typeof callback === 'function'){ return callback(null); + } }); } else if (key === 'token') { @@ -1050,7 +1049,8 @@ api.getJSON = function (options, objOptions, callback) { var routeID = options.path + '-' + joolaio.common.uuid(); - objOptions._token = joolaio.TOKEN; + if (joolaio.TOKEN) + objOptions._token = joolaio.TOKEN; if (!objOptions._token) objOptions.APIToken = joolaio.APITOKEN; objOptions._path = options.path; diff --git a/bin/joola.io.min.js b/bin/joola.io.min.js index 9d0f56d..fd27f50 100644 --- a/bin/joola.io.min.js +++ b/bin/joola.io.min.js @@ -1,4 +1,4 @@ -(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){callback=callback||emptyfunc;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.options.token){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){if(err)return callback(err);if(!user)return callback(new Error("Failed to verify API Token"));joolaio.USER=user;joolaio.TOKEN=user.token._;if(typeof callback==="function")return callback(null)})}else if(key==="token"){joolaio._token=joolaio.options._token;joolaio.USER=null;joolaio.APIToken=null;joolaio.dispatch.users.getByToken(joolaio._token,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,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,querystring:42,"socket.io-browserify":57,url:51}],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:54,url:51}],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:55}],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.mixin=function(origin,add,overwrite){if(!add||typeof add!=="object")return origin;var keys=Object.keys(add);var i=0;while(i-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:54,eventemitter2:55}],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-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){callback=callback||emptyfunc;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;if(user.token&&user.token._)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.options.token){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){if(err)return callback(err);if(!user)return callback(new Error("Failed to verify API Token"));joolaio.USER=user;joolaio.events.emit("ready");if(typeof callback==="function")return callback(null)})}else if(key==="token"){joolaio._token=joolaio.options._token;joolaio.USER=null;joolaio.APIToken=null;joolaio.dispatch.users.getByToken(joolaio._token,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,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,querystring:42,"socket.io-browserify":57,url:51}],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){return _callback(err,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:54,url:51}],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:55}],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.mixin=function(origin,add,overwrite){if(!add||typeof add!=="object")return origin;var keys=Object.keys(add);var i=0;while(i-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:54,eventemitter2:55}],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:54}],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);var linear=!(message.dimensions&&message.dimensions.length>0&&message.dimensions[0].datatype=="date");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:message.dimensions[0].datatype==="date"?"datetime":"category",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;var nameBased=false;var y;self.chart.series[serIndex].points.forEach(function(point,pIndex){if(point){if(datapoint.x){if(point.x.getTime()==datapoint.x.getTime()){y=self.chart.series[serIndex].data[pIndex].y;found=true;if(y!=datapoint.y)self.chart.series[serIndex].data[pIndex].update(datapoint.y)}}else{nameBased=true;if(point.name==datapoint.name){y=self.chart.series[serIndex].data[pIndex].y;found=true;if(y!=datapoint.y)self.chart.series[serIndex].data[pIndex].update(datapoint.y)}}}});if(!found){if(nameBased)self.chart.series[serIndex].addPoint({name:datapoint.name,y:datapoint.y},true);else 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:56,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:54,moment:56,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=augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer._useTypedArrays&&typeof Uint8Array==="function"&&subject instanceof Uint8Array){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); diff --git a/index.js b/index.js index 6219ea5..accc2b7 100644 --- a/index.js +++ b/index.js @@ -75,7 +75,7 @@ Object.defineProperty(joolaio, 'APITOKEN', { joolaio.dispatch.users.verifyAPIToken(joolaio.APITOKEN, function (err, user) { joolaio.USER = user; - joolaio.TOKEN = user.token._; + //joolaio.TOKEN = user.token._; }); } }); @@ -235,9 +235,8 @@ joolaio.init = function (options, callback) { joolaio.dispatch.users.verifyAPIToken(joolaio._apitoken, function (err, user) { joolaio.USER = user; - joolaio.TOKEN = user.token._; - joolaio.events.emit('core.init.finish'); + joolaio.events.emit('ready'); if (typeof callback === 'function') return callback(null, joolaio); }); @@ -287,9 +286,9 @@ joolaio.set = function (key, value, callback) { return callback(new Error('Failed to verify API Token')); joolaio.USER = user; - joolaio.TOKEN = user.token._; - if (typeof callback === 'function') + if (typeof callback === 'function'){ return callback(null); + } }); } else if (key === 'token') { diff --git a/lib/common/api.js b/lib/common/api.js index 3c44be3..a83967a 100644 --- a/lib/common/api.js +++ b/lib/common/api.js @@ -237,7 +237,8 @@ api.getJSON = function (options, objOptions, callback) { var routeID = options.path + '-' + joolaio.common.uuid(); - objOptions._token = joolaio.TOKEN; + if (joolaio.TOKEN) + objOptions._token = joolaio.TOKEN; if (!objOptions._token) objOptions.APIToken = joolaio.APITOKEN; objOptions._path = options.path;