Преглед на файлове

TREEJS:use ajax based filters

Piotr Labudda преди 11 години
родител
ревизия
8238bcacad
променени са 7 файла, в които са добавени 2062 реда и са изтрити 198 реда
  1. 1 1
      SE/VERSION
  2. 1 1
      SE/procesy/proces.php
  3. 0 4
      SE/se-lib/Tree.php
  4. 2 0
      SE/se-lib/tmpl/_layout_gora.php
  5. 56 0
      SE/stuff/lodash.min.js
  6. 1496 0
      SE/stuff/superagent.js
  7. 506 192
      SE/superedit-TREEJS.php

+ 1 - 1
SE/VERSION

@@ -1 +1 @@
-3.10.4
+3.10.5

+ 1 - 1
SE/procesy/proces.php

@@ -150,7 +150,7 @@ echo'<br />';
 $TREE = array();
 echo'<div id="tree"></div>';
 
-
+	session_write_close();// End the current session and store session data. Below $_SESSION is read-only.
 	$dbgExecTime->log('show...');
 
 	if ($tree_procesy_filter->get_arg('filtr_view') == 'NOWY') {

+ 0 - 4
SE/se-lib/Tree.php

@@ -723,10 +723,6 @@ jQuery(document).ready(function(){
 	var nodes = jQuery('.ajax-reopen');
 	if (nodes.length) nodes.click();
 
-	if (jQuery.browser.msie) {
-		// TODO: add message: view not work in IE
-	}
-
 	jQuery('.wsk-help').popover({trigger:'hover', html:true, placement:'top'});
 	//jQuery('.wsk-long-desc').modal();
 });

+ 2 - 0
SE/se-lib/tmpl/_layout_gora.php

@@ -22,6 +22,8 @@
 	<script src="stuff/notify.min.js"></script>
 	<script src="stuff/jquery-ui-1.10.4.custom.min.js"></script>
 	<script src="stuff/jquery.hotkeys.js"></script>
+	<script src="stuff/lodash.min.js"></script>
+	<script src="stuff/superagent.js"></script>
 	<style type="text/css">
 .typepsecial .selectize-input { width:366px; padding:4px 6px; }
 .typepsecial .selectize-control::before {

+ 56 - 0
SE/stuff/lodash.min.js

@@ -0,0 +1,56 @@
+/**
+ * @license
+ * Lo-Dash 2.4.1 (Custom Build) lodash.com/license | Underscore.js 1.5.2 underscorejs.org/LICENSE
+ * Build: `lodash modern -o ./dist/lodash.js`
+ */
+;(function(){function n(n,t,e){e=(e||0)-1;for(var r=n?n.length:0;++e<r;)if(n[e]===t)return e;return-1}function t(t,e){var r=typeof e;if(t=t.l,"boolean"==r||null==e)return t[e]?0:-1;"number"!=r&&"string"!=r&&(r="object");var u="number"==r?e:m+e;return t=(t=t[r])&&t[u],"object"==r?t&&-1<n(t,e)?0:-1:t?0:-1}function e(n){var t=this.l,e=typeof n;if("boolean"==e||null==n)t[n]=true;else{"number"!=e&&"string"!=e&&(e="object");var r="number"==e?n:m+n,t=t[e]||(t[e]={});"object"==e?(t[r]||(t[r]=[])).push(n):t[r]=true
+}}function r(n){return n.charCodeAt(0)}function u(n,t){for(var e=n.m,r=t.m,u=-1,o=e.length;++u<o;){var i=e[u],a=r[u];if(i!==a){if(i>a||typeof i=="undefined")return 1;if(i<a||typeof a=="undefined")return-1}}return n.n-t.n}function o(n){var t=-1,r=n.length,u=n[0],o=n[r/2|0],i=n[r-1];if(u&&typeof u=="object"&&o&&typeof o=="object"&&i&&typeof i=="object")return false;for(u=f(),u["false"]=u["null"]=u["true"]=u.undefined=false,o=f(),o.k=n,o.l=u,o.push=e;++t<r;)o.push(n[t]);return o}function i(n){return"\\"+U[n]
+}function a(){return h.pop()||[]}function f(){return g.pop()||{k:null,l:null,m:null,"false":false,n:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,o:null}}function l(n){n.length=0,h.length<_&&h.push(n)}function c(n){var t=n.l;t&&c(t),n.k=n.l=n.m=n.object=n.number=n.string=n.o=null,g.length<_&&g.push(n)}function p(n,t,e){t||(t=0),typeof e=="undefined"&&(e=n?n.length:0);var r=-1;e=e-t||0;for(var u=Array(0>e?0:e);++r<e;)u[r]=n[t+r];return u}function s(e){function h(n,t,e){if(!n||!V[typeof n])return n;
+t=t&&typeof e=="undefined"?t:tt(t,e,3);for(var r=-1,u=V[typeof n]&&Fe(n),o=u?u.length:0;++r<o&&(e=u[r],false!==t(n[e],e,n)););return n}function g(n,t,e){var r;if(!n||!V[typeof n])return n;t=t&&typeof e=="undefined"?t:tt(t,e,3);for(r in n)if(false===t(n[r],r,n))break;return n}function _(n,t,e){var r,u=n,o=u;if(!u)return o;for(var i=arguments,a=0,f=typeof e=="number"?2:i.length;++a<f;)if((u=i[a])&&V[typeof u])for(var l=-1,c=V[typeof u]&&Fe(u),p=c?c.length:0;++l<p;)r=c[l],"undefined"==typeof o[r]&&(o[r]=u[r]);
+return o}function U(n,t,e){var r,u=n,o=u;if(!u)return o;var i=arguments,a=0,f=typeof e=="number"?2:i.length;if(3<f&&"function"==typeof i[f-2])var l=tt(i[--f-1],i[f--],2);else 2<f&&"function"==typeof i[f-1]&&(l=i[--f]);for(;++a<f;)if((u=i[a])&&V[typeof u])for(var c=-1,p=V[typeof u]&&Fe(u),s=p?p.length:0;++c<s;)r=p[c],o[r]=l?l(o[r],u[r]):u[r];return o}function H(n){var t,e=[];if(!n||!V[typeof n])return e;for(t in n)me.call(n,t)&&e.push(t);return e}function J(n){return n&&typeof n=="object"&&!Te(n)&&me.call(n,"__wrapped__")?n:new Q(n)
+}function Q(n,t){this.__chain__=!!t,this.__wrapped__=n}function X(n){function t(){if(r){var n=p(r);be.apply(n,arguments)}if(this instanceof t){var o=nt(e.prototype),n=e.apply(o,n||arguments);return wt(n)?n:o}return e.apply(u,n||arguments)}var e=n[0],r=n[2],u=n[4];return $e(t,n),t}function Z(n,t,e,r,u){if(e){var o=e(n);if(typeof o!="undefined")return o}if(!wt(n))return n;var i=ce.call(n);if(!K[i])return n;var f=Ae[i];switch(i){case T:case F:return new f(+n);case W:case P:return new f(n);case z:return o=f(n.source,C.exec(n)),o.lastIndex=n.lastIndex,o
+}if(i=Te(n),t){var c=!r;r||(r=a()),u||(u=a());for(var s=r.length;s--;)if(r[s]==n)return u[s];o=i?f(n.length):{}}else o=i?p(n):U({},n);return i&&(me.call(n,"index")&&(o.index=n.index),me.call(n,"input")&&(o.input=n.input)),t?(r.push(n),u.push(o),(i?St:h)(n,function(n,i){o[i]=Z(n,t,e,r,u)}),c&&(l(r),l(u)),o):o}function nt(n){return wt(n)?ke(n):{}}function tt(n,t,e){if(typeof n!="function")return Ut;if(typeof t=="undefined"||!("prototype"in n))return n;var r=n.__bindData__;if(typeof r=="undefined"&&(De.funcNames&&(r=!n.name),r=r||!De.funcDecomp,!r)){var u=ge.call(n);
+De.funcNames||(r=!O.test(u)),r||(r=E.test(u),$e(n,r))}if(false===r||true!==r&&1&r[1])return n;switch(e){case 1:return function(e){return n.call(t,e)};case 2:return function(e,r){return n.call(t,e,r)};case 3:return function(e,r,u){return n.call(t,e,r,u)};case 4:return function(e,r,u,o){return n.call(t,e,r,u,o)}}return Mt(n,t)}function et(n){function t(){var n=f?i:this;if(u){var h=p(u);be.apply(h,arguments)}return(o||c)&&(h||(h=p(arguments)),o&&be.apply(h,o),c&&h.length<a)?(r|=16,et([e,s?r:-4&r,h,null,i,a])):(h||(h=arguments),l&&(e=n[v]),this instanceof t?(n=nt(e.prototype),h=e.apply(n,h),wt(h)?h:n):e.apply(n,h))
+}var e=n[0],r=n[1],u=n[2],o=n[3],i=n[4],a=n[5],f=1&r,l=2&r,c=4&r,s=8&r,v=e;return $e(t,n),t}function rt(e,r){var u=-1,i=st(),a=e?e.length:0,f=a>=b&&i===n,l=[];if(f){var p=o(r);p?(i=t,r=p):f=false}for(;++u<a;)p=e[u],0>i(r,p)&&l.push(p);return f&&c(r),l}function ut(n,t,e,r){r=(r||0)-1;for(var u=n?n.length:0,o=[];++r<u;){var i=n[r];if(i&&typeof i=="object"&&typeof i.length=="number"&&(Te(i)||yt(i))){t||(i=ut(i,t,e));var a=-1,f=i.length,l=o.length;for(o.length+=f;++a<f;)o[l++]=i[a]}else e||o.push(i)}return o
+}function ot(n,t,e,r,u,o){if(e){var i=e(n,t);if(typeof i!="undefined")return!!i}if(n===t)return 0!==n||1/n==1/t;if(n===n&&!(n&&V[typeof n]||t&&V[typeof t]))return false;if(null==n||null==t)return n===t;var f=ce.call(n),c=ce.call(t);if(f==D&&(f=q),c==D&&(c=q),f!=c)return false;switch(f){case T:case F:return+n==+t;case W:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case z:case P:return n==oe(t)}if(c=f==$,!c){var p=me.call(n,"__wrapped__"),s=me.call(t,"__wrapped__");if(p||s)return ot(p?n.__wrapped__:n,s?t.__wrapped__:t,e,r,u,o);
+if(f!=q)return false;if(f=n.constructor,p=t.constructor,f!=p&&!(dt(f)&&f instanceof f&&dt(p)&&p instanceof p)&&"constructor"in n&&"constructor"in t)return false}for(f=!u,u||(u=a()),o||(o=a()),p=u.length;p--;)if(u[p]==n)return o[p]==t;var v=0,i=true;if(u.push(n),o.push(t),c){if(p=n.length,v=t.length,(i=v==p)||r)for(;v--;)if(c=p,s=t[v],r)for(;c--&&!(i=ot(n[c],s,e,r,u,o)););else if(!(i=ot(n[v],s,e,r,u,o)))break}else g(t,function(t,a,f){return me.call(f,a)?(v++,i=me.call(n,a)&&ot(n[a],t,e,r,u,o)):void 0}),i&&!r&&g(n,function(n,t,e){return me.call(e,t)?i=-1<--v:void 0
+});return u.pop(),o.pop(),f&&(l(u),l(o)),i}function it(n,t,e,r,u){(Te(t)?St:h)(t,function(t,o){var i,a,f=t,l=n[o];if(t&&((a=Te(t))||Pe(t))){for(f=r.length;f--;)if(i=r[f]==t){l=u[f];break}if(!i){var c;e&&(f=e(l,t),c=typeof f!="undefined")&&(l=f),c||(l=a?Te(l)?l:[]:Pe(l)?l:{}),r.push(t),u.push(l),c||it(l,t,e,r,u)}}else e&&(f=e(l,t),typeof f=="undefined"&&(f=t)),typeof f!="undefined"&&(l=f);n[o]=l})}function at(n,t){return n+he(Re()*(t-n+1))}function ft(e,r,u){var i=-1,f=st(),p=e?e.length:0,s=[],v=!r&&p>=b&&f===n,h=u||v?a():s;
+for(v&&(h=o(h),f=t);++i<p;){var g=e[i],y=u?u(g,i,e):g;(r?!i||h[h.length-1]!==y:0>f(h,y))&&((u||v)&&h.push(y),s.push(g))}return v?(l(h.k),c(h)):u&&l(h),s}function lt(n){return function(t,e,r){var u={};e=J.createCallback(e,r,3),r=-1;var o=t?t.length:0;if(typeof o=="number")for(;++r<o;){var i=t[r];n(u,i,e(i,r,t),t)}else h(t,function(t,r,o){n(u,t,e(t,r,o),o)});return u}}function ct(n,t,e,r,u,o){var i=1&t,a=4&t,f=16&t,l=32&t;if(!(2&t||dt(n)))throw new ie;f&&!e.length&&(t&=-17,f=e=false),l&&!r.length&&(t&=-33,l=r=false);
+var c=n&&n.__bindData__;return c&&true!==c?(c=p(c),c[2]&&(c[2]=p(c[2])),c[3]&&(c[3]=p(c[3])),!i||1&c[1]||(c[4]=u),!i&&1&c[1]&&(t|=8),!a||4&c[1]||(c[5]=o),f&&be.apply(c[2]||(c[2]=[]),e),l&&we.apply(c[3]||(c[3]=[]),r),c[1]|=t,ct.apply(null,c)):(1==t||17===t?X:et)([n,t,e,r,u,o])}function pt(n){return Be[n]}function st(){var t=(t=J.indexOf)===Wt?n:t;return t}function vt(n){return typeof n=="function"&&pe.test(n)}function ht(n){var t,e;return n&&ce.call(n)==q&&(t=n.constructor,!dt(t)||t instanceof t)?(g(n,function(n,t){e=t
+}),typeof e=="undefined"||me.call(n,e)):false}function gt(n){return We[n]}function yt(n){return n&&typeof n=="object"&&typeof n.length=="number"&&ce.call(n)==D||false}function mt(n,t,e){var r=Fe(n),u=r.length;for(t=tt(t,e,3);u--&&(e=r[u],false!==t(n[e],e,n)););return n}function bt(n){var t=[];return g(n,function(n,e){dt(n)&&t.push(e)}),t.sort()}function _t(n){for(var t=-1,e=Fe(n),r=e.length,u={};++t<r;){var o=e[t];u[n[o]]=o}return u}function dt(n){return typeof n=="function"}function wt(n){return!(!n||!V[typeof n])
+}function jt(n){return typeof n=="number"||n&&typeof n=="object"&&ce.call(n)==W||false}function kt(n){return typeof n=="string"||n&&typeof n=="object"&&ce.call(n)==P||false}function xt(n){for(var t=-1,e=Fe(n),r=e.length,u=Xt(r);++t<r;)u[t]=n[e[t]];return u}function Ct(n,t,e){var r=-1,u=st(),o=n?n.length:0,i=false;return e=(0>e?Ie(0,o+e):e)||0,Te(n)?i=-1<u(n,t,e):typeof o=="number"?i=-1<(kt(n)?n.indexOf(t,e):u(n,t,e)):h(n,function(n){return++r<e?void 0:!(i=n===t)}),i}function Ot(n,t,e){var r=true;t=J.createCallback(t,e,3),e=-1;
+var u=n?n.length:0;if(typeof u=="number")for(;++e<u&&(r=!!t(n[e],e,n)););else h(n,function(n,e,u){return r=!!t(n,e,u)});return r}function Nt(n,t,e){var r=[];t=J.createCallback(t,e,3),e=-1;var u=n?n.length:0;if(typeof u=="number")for(;++e<u;){var o=n[e];t(o,e,n)&&r.push(o)}else h(n,function(n,e,u){t(n,e,u)&&r.push(n)});return r}function It(n,t,e){t=J.createCallback(t,e,3),e=-1;var r=n?n.length:0;if(typeof r!="number"){var u;return h(n,function(n,e,r){return t(n,e,r)?(u=n,false):void 0}),u}for(;++e<r;){var o=n[e];
+if(t(o,e,n))return o}}function St(n,t,e){var r=-1,u=n?n.length:0;if(t=t&&typeof e=="undefined"?t:tt(t,e,3),typeof u=="number")for(;++r<u&&false!==t(n[r],r,n););else h(n,t);return n}function Et(n,t,e){var r=n?n.length:0;if(t=t&&typeof e=="undefined"?t:tt(t,e,3),typeof r=="number")for(;r--&&false!==t(n[r],r,n););else{var u=Fe(n),r=u.length;h(n,function(n,e,o){return e=u?u[--r]:--r,t(o[e],e,o)})}return n}function Rt(n,t,e){var r=-1,u=n?n.length:0;if(t=J.createCallback(t,e,3),typeof u=="number")for(var o=Xt(u);++r<u;)o[r]=t(n[r],r,n);
+else o=[],h(n,function(n,e,u){o[++r]=t(n,e,u)});return o}function At(n,t,e){var u=-1/0,o=u;if(typeof t!="function"&&e&&e[t]===n&&(t=null),null==t&&Te(n)){e=-1;for(var i=n.length;++e<i;){var a=n[e];a>o&&(o=a)}}else t=null==t&&kt(n)?r:J.createCallback(t,e,3),St(n,function(n,e,r){e=t(n,e,r),e>u&&(u=e,o=n)});return o}function Dt(n,t,e,r){if(!n)return e;var u=3>arguments.length;t=J.createCallback(t,r,4);var o=-1,i=n.length;if(typeof i=="number")for(u&&(e=n[++o]);++o<i;)e=t(e,n[o],o,n);else h(n,function(n,r,o){e=u?(u=false,n):t(e,n,r,o)
+});return e}function $t(n,t,e,r){var u=3>arguments.length;return t=J.createCallback(t,r,4),Et(n,function(n,r,o){e=u?(u=false,n):t(e,n,r,o)}),e}function Tt(n){var t=-1,e=n?n.length:0,r=Xt(typeof e=="number"?e:0);return St(n,function(n){var e=at(0,++t);r[t]=r[e],r[e]=n}),r}function Ft(n,t,e){var r;t=J.createCallback(t,e,3),e=-1;var u=n?n.length:0;if(typeof u=="number")for(;++e<u&&!(r=t(n[e],e,n)););else h(n,function(n,e,u){return!(r=t(n,e,u))});return!!r}function Bt(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=-1;
+for(t=J.createCallback(t,e,3);++o<u&&t(n[o],o,n);)r++}else if(r=t,null==r||e)return n?n[0]:v;return p(n,0,Se(Ie(0,r),u))}function Wt(t,e,r){if(typeof r=="number"){var u=t?t.length:0;r=0>r?Ie(0,u+r):r||0}else if(r)return r=zt(t,e),t[r]===e?r:-1;return n(t,e,r)}function qt(n,t,e){if(typeof t!="number"&&null!=t){var r=0,u=-1,o=n?n.length:0;for(t=J.createCallback(t,e,3);++u<o&&t(n[u],u,n);)r++}else r=null==t||e?1:Ie(0,t);return p(n,r)}function zt(n,t,e,r){var u=0,o=n?n.length:u;for(e=e?J.createCallback(e,r,1):Ut,t=e(t);u<o;)r=u+o>>>1,e(n[r])<t?u=r+1:o=r;
+return u}function Pt(n,t,e,r){return typeof t!="boolean"&&null!=t&&(r=e,e=typeof t!="function"&&r&&r[t]===n?null:t,t=false),null!=e&&(e=J.createCallback(e,r,3)),ft(n,t,e)}function Kt(){for(var n=1<arguments.length?arguments:arguments[0],t=-1,e=n?At(Ve(n,"length")):0,r=Xt(0>e?0:e);++t<e;)r[t]=Ve(n,t);return r}function Lt(n,t){var e=-1,r=n?n.length:0,u={};for(t||!r||Te(n[0])||(t=[]);++e<r;){var o=n[e];t?u[o]=t[e]:o&&(u[o[0]]=o[1])}return u}function Mt(n,t){return 2<arguments.length?ct(n,17,p(arguments,2),null,t):ct(n,1,null,null,t)
+}function Vt(n,t,e){function r(){c&&ve(c),i=c=p=v,(g||h!==t)&&(s=Ue(),a=n.apply(l,o),c||i||(o=l=null))}function u(){var e=t-(Ue()-f);0<e?c=_e(u,e):(i&&ve(i),e=p,i=c=p=v,e&&(s=Ue(),a=n.apply(l,o),c||i||(o=l=null)))}var o,i,a,f,l,c,p,s=0,h=false,g=true;if(!dt(n))throw new ie;if(t=Ie(0,t)||0,true===e)var y=true,g=false;else wt(e)&&(y=e.leading,h="maxWait"in e&&(Ie(t,e.maxWait)||0),g="trailing"in e?e.trailing:g);return function(){if(o=arguments,f=Ue(),l=this,p=g&&(c||!y),false===h)var e=y&&!c;else{i||y||(s=f);var v=h-(f-s),m=0>=v;
+m?(i&&(i=ve(i)),s=f,a=n.apply(l,o)):i||(i=_e(r,v))}return m&&c?c=ve(c):c||t===h||(c=_e(u,t)),e&&(m=true,a=n.apply(l,o)),!m||c||i||(o=l=null),a}}function Ut(n){return n}function Gt(n,t,e){var r=true,u=t&&bt(t);t&&(e||u.length)||(null==e&&(e=t),o=Q,t=n,n=J,u=bt(t)),false===e?r=false:wt(e)&&"chain"in e&&(r=e.chain);var o=n,i=dt(o);St(u,function(e){var u=n[e]=t[e];i&&(o.prototype[e]=function(){var t=this.__chain__,e=this.__wrapped__,i=[e];if(be.apply(i,arguments),i=u.apply(n,i),r||t){if(e===i&&wt(i))return this;
+i=new o(i),i.__chain__=t}return i})})}function Ht(){}function Jt(n){return function(t){return t[n]}}function Qt(){return this.__wrapped__}e=e?Y.defaults(G.Object(),e,Y.pick(G,A)):G;var Xt=e.Array,Yt=e.Boolean,Zt=e.Date,ne=e.Function,te=e.Math,ee=e.Number,re=e.Object,ue=e.RegExp,oe=e.String,ie=e.TypeError,ae=[],fe=re.prototype,le=e._,ce=fe.toString,pe=ue("^"+oe(ce).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),se=te.ceil,ve=e.clearTimeout,he=te.floor,ge=ne.prototype.toString,ye=vt(ye=re.getPrototypeOf)&&ye,me=fe.hasOwnProperty,be=ae.push,_e=e.setTimeout,de=ae.splice,we=ae.unshift,je=function(){try{var n={},t=vt(t=re.defineProperty)&&t,e=t(n,n,n)&&t
+}catch(r){}return e}(),ke=vt(ke=re.create)&&ke,xe=vt(xe=Xt.isArray)&&xe,Ce=e.isFinite,Oe=e.isNaN,Ne=vt(Ne=re.keys)&&Ne,Ie=te.max,Se=te.min,Ee=e.parseInt,Re=te.random,Ae={};Ae[$]=Xt,Ae[T]=Yt,Ae[F]=Zt,Ae[B]=ne,Ae[q]=re,Ae[W]=ee,Ae[z]=ue,Ae[P]=oe,Q.prototype=J.prototype;var De=J.support={};De.funcDecomp=!vt(e.a)&&E.test(s),De.funcNames=typeof ne.name=="string",J.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:N,variable:"",imports:{_:J}},ke||(nt=function(){function n(){}return function(t){if(wt(t)){n.prototype=t;
+var r=new n;n.prototype=null}return r||e.Object()}}());var $e=je?function(n,t){M.value=t,je(n,"__bindData__",M)}:Ht,Te=xe||function(n){return n&&typeof n=="object"&&typeof n.length=="number"&&ce.call(n)==$||false},Fe=Ne?function(n){return wt(n)?Ne(n):[]}:H,Be={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},We=_t(Be),qe=ue("("+Fe(We).join("|")+")","g"),ze=ue("["+Fe(Be).join("")+"]","g"),Pe=ye?function(n){if(!n||ce.call(n)!=q)return false;var t=n.valueOf,e=vt(t)&&(e=ye(t))&&ye(e);return e?n==e||ye(n)==e:ht(n)
+}:ht,Ke=lt(function(n,t,e){me.call(n,e)?n[e]++:n[e]=1}),Le=lt(function(n,t,e){(me.call(n,e)?n[e]:n[e]=[]).push(t)}),Me=lt(function(n,t,e){n[e]=t}),Ve=Rt,Ue=vt(Ue=Zt.now)&&Ue||function(){return(new Zt).getTime()},Ge=8==Ee(d+"08")?Ee:function(n,t){return Ee(kt(n)?n.replace(I,""):n,t||0)};return J.after=function(n,t){if(!dt(t))throw new ie;return function(){return 1>--n?t.apply(this,arguments):void 0}},J.assign=U,J.at=function(n){for(var t=arguments,e=-1,r=ut(t,true,false,1),t=t[2]&&t[2][t[1]]===n?1:r.length,u=Xt(t);++e<t;)u[e]=n[r[e]];
+return u},J.bind=Mt,J.bindAll=function(n){for(var t=1<arguments.length?ut(arguments,true,false,1):bt(n),e=-1,r=t.length;++e<r;){var u=t[e];n[u]=ct(n[u],1,null,null,n)}return n},J.bindKey=function(n,t){return 2<arguments.length?ct(t,19,p(arguments,2),null,n):ct(t,3,null,null,n)},J.chain=function(n){return n=new Q(n),n.__chain__=true,n},J.compact=function(n){for(var t=-1,e=n?n.length:0,r=[];++t<e;){var u=n[t];u&&r.push(u)}return r},J.compose=function(){for(var n=arguments,t=n.length;t--;)if(!dt(n[t]))throw new ie;
+return function(){for(var t=arguments,e=n.length;e--;)t=[n[e].apply(this,t)];return t[0]}},J.constant=function(n){return function(){return n}},J.countBy=Ke,J.create=function(n,t){var e=nt(n);return t?U(e,t):e},J.createCallback=function(n,t,e){var r=typeof n;if(null==n||"function"==r)return tt(n,t,e);if("object"!=r)return Jt(n);var u=Fe(n),o=u[0],i=n[o];return 1!=u.length||i!==i||wt(i)?function(t){for(var e=u.length,r=false;e--&&(r=ot(t[u[e]],n[u[e]],null,true)););return r}:function(n){return n=n[o],i===n&&(0!==i||1/i==1/n)
+}},J.curry=function(n,t){return t=typeof t=="number"?t:+t||n.length,ct(n,4,null,null,null,t)},J.debounce=Vt,J.defaults=_,J.defer=function(n){if(!dt(n))throw new ie;var t=p(arguments,1);return _e(function(){n.apply(v,t)},1)},J.delay=function(n,t){if(!dt(n))throw new ie;var e=p(arguments,2);return _e(function(){n.apply(v,e)},t)},J.difference=function(n){return rt(n,ut(arguments,true,true,1))},J.filter=Nt,J.flatten=function(n,t,e,r){return typeof t!="boolean"&&null!=t&&(r=e,e=typeof t!="function"&&r&&r[t]===n?null:t,t=false),null!=e&&(n=Rt(n,e,r)),ut(n,t)
+},J.forEach=St,J.forEachRight=Et,J.forIn=g,J.forInRight=function(n,t,e){var r=[];g(n,function(n,t){r.push(t,n)});var u=r.length;for(t=tt(t,e,3);u--&&false!==t(r[u--],r[u],n););return n},J.forOwn=h,J.forOwnRight=mt,J.functions=bt,J.groupBy=Le,J.indexBy=Me,J.initial=function(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=u;for(t=J.createCallback(t,e,3);o--&&t(n[o],o,n);)r++}else r=null==t||e?1:t||r;return p(n,0,Se(Ie(0,u-r),u))},J.intersection=function(){for(var e=[],r=-1,u=arguments.length,i=a(),f=st(),p=f===n,s=a();++r<u;){var v=arguments[r];
+(Te(v)||yt(v))&&(e.push(v),i.push(p&&v.length>=b&&o(r?e[r]:s)))}var p=e[0],h=-1,g=p?p.length:0,y=[];n:for(;++h<g;){var m=i[0],v=p[h];if(0>(m?t(m,v):f(s,v))){for(r=u,(m||s).push(v);--r;)if(m=i[r],0>(m?t(m,v):f(e[r],v)))continue n;y.push(v)}}for(;u--;)(m=i[u])&&c(m);return l(i),l(s),y},J.invert=_t,J.invoke=function(n,t){var e=p(arguments,2),r=-1,u=typeof t=="function",o=n?n.length:0,i=Xt(typeof o=="number"?o:0);return St(n,function(n){i[++r]=(u?t:n[t]).apply(n,e)}),i},J.keys=Fe,J.map=Rt,J.mapValues=function(n,t,e){var r={};
+return t=J.createCallback(t,e,3),h(n,function(n,e,u){r[e]=t(n,e,u)}),r},J.max=At,J.memoize=function(n,t){function e(){var r=e.cache,u=t?t.apply(this,arguments):m+arguments[0];return me.call(r,u)?r[u]:r[u]=n.apply(this,arguments)}if(!dt(n))throw new ie;return e.cache={},e},J.merge=function(n){var t=arguments,e=2;if(!wt(n))return n;if("number"!=typeof t[2]&&(e=t.length),3<e&&"function"==typeof t[e-2])var r=tt(t[--e-1],t[e--],2);else 2<e&&"function"==typeof t[e-1]&&(r=t[--e]);for(var t=p(arguments,1,e),u=-1,o=a(),i=a();++u<e;)it(n,t[u],r,o,i);
+return l(o),l(i),n},J.min=function(n,t,e){var u=1/0,o=u;if(typeof t!="function"&&e&&e[t]===n&&(t=null),null==t&&Te(n)){e=-1;for(var i=n.length;++e<i;){var a=n[e];a<o&&(o=a)}}else t=null==t&&kt(n)?r:J.createCallback(t,e,3),St(n,function(n,e,r){e=t(n,e,r),e<u&&(u=e,o=n)});return o},J.omit=function(n,t,e){var r={};if(typeof t!="function"){var u=[];g(n,function(n,t){u.push(t)});for(var u=rt(u,ut(arguments,true,false,1)),o=-1,i=u.length;++o<i;){var a=u[o];r[a]=n[a]}}else t=J.createCallback(t,e,3),g(n,function(n,e,u){t(n,e,u)||(r[e]=n)
+});return r},J.once=function(n){var t,e;if(!dt(n))throw new ie;return function(){return t?e:(t=true,e=n.apply(this,arguments),n=null,e)}},J.pairs=function(n){for(var t=-1,e=Fe(n),r=e.length,u=Xt(r);++t<r;){var o=e[t];u[t]=[o,n[o]]}return u},J.partial=function(n){return ct(n,16,p(arguments,1))},J.partialRight=function(n){return ct(n,32,null,p(arguments,1))},J.pick=function(n,t,e){var r={};if(typeof t!="function")for(var u=-1,o=ut(arguments,true,false,1),i=wt(n)?o.length:0;++u<i;){var a=o[u];a in n&&(r[a]=n[a])
+}else t=J.createCallback(t,e,3),g(n,function(n,e,u){t(n,e,u)&&(r[e]=n)});return r},J.pluck=Ve,J.property=Jt,J.pull=function(n){for(var t=arguments,e=0,r=t.length,u=n?n.length:0;++e<r;)for(var o=-1,i=t[e];++o<u;)n[o]===i&&(de.call(n,o--,1),u--);return n},J.range=function(n,t,e){n=+n||0,e=typeof e=="number"?e:+e||1,null==t&&(t=n,n=0);var r=-1;t=Ie(0,se((t-n)/(e||1)));for(var u=Xt(t);++r<t;)u[r]=n,n+=e;return u},J.reject=function(n,t,e){return t=J.createCallback(t,e,3),Nt(n,function(n,e,r){return!t(n,e,r)
+})},J.remove=function(n,t,e){var r=-1,u=n?n.length:0,o=[];for(t=J.createCallback(t,e,3);++r<u;)e=n[r],t(e,r,n)&&(o.push(e),de.call(n,r--,1),u--);return o},J.rest=qt,J.shuffle=Tt,J.sortBy=function(n,t,e){var r=-1,o=Te(t),i=n?n.length:0,p=Xt(typeof i=="number"?i:0);for(o||(t=J.createCallback(t,e,3)),St(n,function(n,e,u){var i=p[++r]=f();o?i.m=Rt(t,function(t){return n[t]}):(i.m=a())[0]=t(n,e,u),i.n=r,i.o=n}),i=p.length,p.sort(u);i--;)n=p[i],p[i]=n.o,o||l(n.m),c(n);return p},J.tap=function(n,t){return t(n),n
+},J.throttle=function(n,t,e){var r=true,u=true;if(!dt(n))throw new ie;return false===e?r=false:wt(e)&&(r="leading"in e?e.leading:r,u="trailing"in e?e.trailing:u),L.leading=r,L.maxWait=t,L.trailing=u,Vt(n,t,L)},J.times=function(n,t,e){n=-1<(n=+n)?n:0;var r=-1,u=Xt(n);for(t=tt(t,e,1);++r<n;)u[r]=t(r);return u},J.toArray=function(n){return n&&typeof n.length=="number"?p(n):xt(n)},J.transform=function(n,t,e,r){var u=Te(n);if(null==e)if(u)e=[];else{var o=n&&n.constructor;e=nt(o&&o.prototype)}return t&&(t=J.createCallback(t,r,4),(u?St:h)(n,function(n,r,u){return t(e,n,r,u)
+})),e},J.union=function(){return ft(ut(arguments,true,true))},J.uniq=Pt,J.values=xt,J.where=Nt,J.without=function(n){return rt(n,p(arguments,1))},J.wrap=function(n,t){return ct(t,16,[n])},J.xor=function(){for(var n=-1,t=arguments.length;++n<t;){var e=arguments[n];if(Te(e)||yt(e))var r=r?ft(rt(r,e).concat(rt(e,r))):e}return r||[]},J.zip=Kt,J.zipObject=Lt,J.collect=Rt,J.drop=qt,J.each=St,J.eachRight=Et,J.extend=U,J.methods=bt,J.object=Lt,J.select=Nt,J.tail=qt,J.unique=Pt,J.unzip=Kt,Gt(J),J.clone=function(n,t,e,r){return typeof t!="boolean"&&null!=t&&(r=e,e=t,t=false),Z(n,t,typeof e=="function"&&tt(e,r,1))
+},J.cloneDeep=function(n,t,e){return Z(n,true,typeof t=="function"&&tt(t,e,1))},J.contains=Ct,J.escape=function(n){return null==n?"":oe(n).replace(ze,pt)},J.every=Ot,J.find=It,J.findIndex=function(n,t,e){var r=-1,u=n?n.length:0;for(t=J.createCallback(t,e,3);++r<u;)if(t(n[r],r,n))return r;return-1},J.findKey=function(n,t,e){var r;return t=J.createCallback(t,e,3),h(n,function(n,e,u){return t(n,e,u)?(r=e,false):void 0}),r},J.findLast=function(n,t,e){var r;return t=J.createCallback(t,e,3),Et(n,function(n,e,u){return t(n,e,u)?(r=n,false):void 0
+}),r},J.findLastIndex=function(n,t,e){var r=n?n.length:0;for(t=J.createCallback(t,e,3);r--;)if(t(n[r],r,n))return r;return-1},J.findLastKey=function(n,t,e){var r;return t=J.createCallback(t,e,3),mt(n,function(n,e,u){return t(n,e,u)?(r=e,false):void 0}),r},J.has=function(n,t){return n?me.call(n,t):false},J.identity=Ut,J.indexOf=Wt,J.isArguments=yt,J.isArray=Te,J.isBoolean=function(n){return true===n||false===n||n&&typeof n=="object"&&ce.call(n)==T||false},J.isDate=function(n){return n&&typeof n=="object"&&ce.call(n)==F||false
+},J.isElement=function(n){return n&&1===n.nodeType||false},J.isEmpty=function(n){var t=true;if(!n)return t;var e=ce.call(n),r=n.length;return e==$||e==P||e==D||e==q&&typeof r=="number"&&dt(n.splice)?!r:(h(n,function(){return t=false}),t)},J.isEqual=function(n,t,e,r){return ot(n,t,typeof e=="function"&&tt(e,r,2))},J.isFinite=function(n){return Ce(n)&&!Oe(parseFloat(n))},J.isFunction=dt,J.isNaN=function(n){return jt(n)&&n!=+n},J.isNull=function(n){return null===n},J.isNumber=jt,J.isObject=wt,J.isPlainObject=Pe,J.isRegExp=function(n){return n&&typeof n=="object"&&ce.call(n)==z||false
+},J.isString=kt,J.isUndefined=function(n){return typeof n=="undefined"},J.lastIndexOf=function(n,t,e){var r=n?n.length:0;for(typeof e=="number"&&(r=(0>e?Ie(0,r+e):Se(e,r-1))+1);r--;)if(n[r]===t)return r;return-1},J.mixin=Gt,J.noConflict=function(){return e._=le,this},J.noop=Ht,J.now=Ue,J.parseInt=Ge,J.random=function(n,t,e){var r=null==n,u=null==t;return null==e&&(typeof n=="boolean"&&u?(e=n,n=1):u||typeof t!="boolean"||(e=t,u=true)),r&&u&&(t=1),n=+n||0,u?(t=n,n=0):t=+t||0,e||n%1||t%1?(e=Re(),Se(n+e*(t-n+parseFloat("1e-"+((e+"").length-1))),t)):at(n,t)
+},J.reduce=Dt,J.reduceRight=$t,J.result=function(n,t){if(n){var e=n[t];return dt(e)?n[t]():e}},J.runInContext=s,J.size=function(n){var t=n?n.length:0;return typeof t=="number"?t:Fe(n).length},J.some=Ft,J.sortedIndex=zt,J.template=function(n,t,e){var r=J.templateSettings;n=oe(n||""),e=_({},e,r);var u,o=_({},e.imports,r.imports),r=Fe(o),o=xt(o),a=0,f=e.interpolate||S,l="__p+='",f=ue((e.escape||S).source+"|"+f.source+"|"+(f===N?x:S).source+"|"+(e.evaluate||S).source+"|$","g");n.replace(f,function(t,e,r,o,f,c){return r||(r=o),l+=n.slice(a,c).replace(R,i),e&&(l+="'+__e("+e+")+'"),f&&(u=true,l+="';"+f+";\n__p+='"),r&&(l+="'+((__t=("+r+"))==null?'':__t)+'"),a=c+t.length,t
+}),l+="';",f=e=e.variable,f||(e="obj",l="with("+e+"){"+l+"}"),l=(u?l.replace(w,""):l).replace(j,"$1").replace(k,"$1;"),l="function("+e+"){"+(f?"":e+"||("+e+"={});")+"var __t,__p='',__e=_.escape"+(u?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+l+"return __p}";try{var c=ne(r,"return "+l).apply(v,o)}catch(p){throw p.source=l,p}return t?c(t):(c.source=l,c)},J.unescape=function(n){return null==n?"":oe(n).replace(qe,gt)},J.uniqueId=function(n){var t=++y;return oe(null==n?"":n)+t
+},J.all=Ot,J.any=Ft,J.detect=It,J.findWhere=It,J.foldl=Dt,J.foldr=$t,J.include=Ct,J.inject=Dt,Gt(function(){var n={};return h(J,function(t,e){J.prototype[e]||(n[e]=t)}),n}(),false),J.first=Bt,J.last=function(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=u;for(t=J.createCallback(t,e,3);o--&&t(n[o],o,n);)r++}else if(r=t,null==r||e)return n?n[u-1]:v;return p(n,Ie(0,u-r))},J.sample=function(n,t,e){return n&&typeof n.length!="number"&&(n=xt(n)),null==t||e?n?n[at(0,n.length-1)]:v:(n=Tt(n),n.length=Se(Ie(0,t),n.length),n)
+},J.take=Bt,J.head=Bt,h(J,function(n,t){var e="sample"!==t;J.prototype[t]||(J.prototype[t]=function(t,r){var u=this.__chain__,o=n(this.__wrapped__,t,r);return u||null!=t&&(!r||e&&typeof t=="function")?new Q(o,u):o})}),J.VERSION="2.4.1",J.prototype.chain=function(){return this.__chain__=true,this},J.prototype.toString=function(){return oe(this.__wrapped__)},J.prototype.value=Qt,J.prototype.valueOf=Qt,St(["join","pop","shift"],function(n){var t=ae[n];J.prototype[n]=function(){var n=this.__chain__,e=t.apply(this.__wrapped__,arguments);
+return n?new Q(e,n):e}}),St(["push","reverse","sort","unshift"],function(n){var t=ae[n];J.prototype[n]=function(){return t.apply(this.__wrapped__,arguments),this}}),St(["concat","slice","splice"],function(n){var t=ae[n];J.prototype[n]=function(){return new Q(t.apply(this.__wrapped__,arguments),this.__chain__)}}),J}var v,h=[],g=[],y=0,m=+new Date+"",b=75,_=40,d=" \t\x0B\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000",w=/\b__p\+='';/g,j=/\b(__p\+=)''\+/g,k=/(__e\(.*?\)|\b__t\))\+'';/g,x=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,C=/\w*$/,O=/^\s*function[ \n\r\t]+\w/,N=/<%=([\s\S]+?)%>/g,I=RegExp("^["+d+"]*0+(?=.$)"),S=/($^)/,E=/\bthis\b/,R=/['\n\r\t\u2028\u2029\\]/g,A="Array Boolean Date Function Math Number Object RegExp String _ attachEvent clearTimeout isFinite isNaN parseInt setTimeout".split(" "),D="[object Arguments]",$="[object Array]",T="[object Boolean]",F="[object Date]",B="[object Function]",W="[object Number]",q="[object Object]",z="[object RegExp]",P="[object String]",K={};
+K[B]=false,K[D]=K[$]=K[T]=K[F]=K[W]=K[q]=K[z]=K[P]=true;var L={leading:false,maxWait:0,trailing:false},M={configurable:false,enumerable:false,value:null,writable:false},V={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false},U={"\\":"\\","'":"'","\n":"n","\r":"r","\t":"t","\u2028":"u2028","\u2029":"u2029"},G=V[typeof window]&&window||this,H=V[typeof exports]&&exports&&!exports.nodeType&&exports,J=V[typeof module]&&module&&!module.nodeType&&module,Q=J&&J.exports===H&&H,X=V[typeof global]&&global;!X||X.global!==X&&X.window!==X||(G=X);
+var Y=s();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(G._=Y, define(function(){return Y})):H&&J?Q?(J.exports=Y)._=Y:H._=Y:G._=Y}).call(this);

+ 1496 - 0
SE/stuff/superagent.js

@@ -0,0 +1,1496 @@
+;(function(){
+
+/**
+ * Require the given path.
+ *
+ * @param {String} path
+ * @return {Object} exports
+ * @api public
+ */
+
+function require(path, parent, orig) {
+  var resolved = require.resolve(path);
+
+  // lookup failed
+  if (null == resolved) {
+    orig = orig || path;
+    parent = parent || 'root';
+    var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
+    err.path = orig;
+    err.parent = parent;
+    err.require = true;
+    throw err;
+  }
+
+  var module = require.modules[resolved];
+
+  // perform real require()
+  // by invoking the module's
+  // registered function
+  if (!module._resolving && !module.exports) {
+    var mod = {};
+    mod.exports = {};
+    mod.client = mod.component = true;
+    module._resolving = true;
+    module.call(this, mod.exports, require.relative(resolved), mod);
+    delete module._resolving;
+    module.exports = mod.exports;
+  }
+
+  return module.exports;
+}
+
+/**
+ * Registered modules.
+ */
+
+require.modules = {};
+
+/**
+ * Registered aliases.
+ */
+
+require.aliases = {};
+
+/**
+ * Resolve `path`.
+ *
+ * Lookup:
+ *
+ *   - PATH/index.js
+ *   - PATH.js
+ *   - PATH
+ *
+ * @param {String} path
+ * @return {String} path or null
+ * @api private
+ */
+
+require.resolve = function(path) {
+  if (path.charAt(0) === '/') path = path.slice(1);
+
+  var paths = [
+    path,
+    path + '.js',
+    path + '.json',
+    path + '/index.js',
+    path + '/index.json'
+  ];
+
+  for (var i = 0; i < paths.length; i++) {
+    var path = paths[i];
+    if (require.modules.hasOwnProperty(path)) return path;
+    if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
+  }
+};
+
+/**
+ * Normalize `path` relative to the current path.
+ *
+ * @param {String} curr
+ * @param {String} path
+ * @return {String}
+ * @api private
+ */
+
+require.normalize = function(curr, path) {
+  var segs = [];
+
+  if ('.' != path.charAt(0)) return path;
+
+  curr = curr.split('/');
+  path = path.split('/');
+
+  for (var i = 0; i < path.length; ++i) {
+    if ('..' == path[i]) {
+      curr.pop();
+    } else if ('.' != path[i] && '' != path[i]) {
+      segs.push(path[i]);
+    }
+  }
+
+  return curr.concat(segs).join('/');
+};
+
+/**
+ * Register module at `path` with callback `definition`.
+ *
+ * @param {String} path
+ * @param {Function} definition
+ * @api private
+ */
+
+require.register = function(path, definition) {
+  require.modules[path] = definition;
+};
+
+/**
+ * Alias a module definition.
+ *
+ * @param {String} from
+ * @param {String} to
+ * @api private
+ */
+
+require.alias = function(from, to) {
+  if (!require.modules.hasOwnProperty(from)) {
+    throw new Error('Failed to alias "' + from + '", it does not exist');
+  }
+  require.aliases[to] = from;
+};
+
+/**
+ * Return a require function relative to the `parent` path.
+ *
+ * @param {String} parent
+ * @return {Function}
+ * @api private
+ */
+
+require.relative = function(parent) {
+  var p = require.normalize(parent, '..');
+
+  /**
+   * lastIndexOf helper.
+   */
+
+  function lastIndexOf(arr, obj) {
+    var i = arr.length;
+    while (i--) {
+      if (arr[i] === obj) return i;
+    }
+    return -1;
+  }
+
+  /**
+   * The relative require() itself.
+   */
+
+  function localRequire(path) {
+    var resolved = localRequire.resolve(path);
+    return require(resolved, parent, path);
+  }
+
+  /**
+   * Resolve relative to the parent.
+   */
+
+  localRequire.resolve = function(path) {
+    var c = path.charAt(0);
+    if ('/' == c) return path.slice(1);
+    if ('.' == c) return require.normalize(p, path);
+
+    // resolve deps by returning
+    // the dep in the nearest "deps"
+    // directory
+    var segs = parent.split('/');
+    var i = lastIndexOf(segs, 'deps') + 1;
+    if (!i) i = 0;
+    path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
+    return path;
+  };
+
+  /**
+   * Check if module is defined at `path`.
+   */
+
+  localRequire.exists = function(path) {
+    return require.modules.hasOwnProperty(localRequire.resolve(path));
+  };
+
+  return localRequire;
+};
+require.register("component-emitter/index.js", function(exports, require, module){
+
+/**
+ * Expose `Emitter`.
+ */
+
+module.exports = Emitter;
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+  if (obj) return mixin(obj);
+};
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+  for (var key in Emitter.prototype) {
+    obj[key] = Emitter.prototype[key];
+  }
+  return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on =
+Emitter.prototype.addEventListener = function(event, fn){
+  this._callbacks = this._callbacks || {};
+  (this._callbacks[event] = this._callbacks[event] || [])
+    .push(fn);
+  return this;
+};
+
+/**
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.once = function(event, fn){
+  var self = this;
+  this._callbacks = this._callbacks || {};
+
+  function on() {
+    self.off(event, on);
+    fn.apply(this, arguments);
+  }
+
+  on.fn = fn;
+  this.on(event, on);
+  return this;
+};
+
+/**
+ * Remove the given callback for `event` or all
+ * registered callbacks.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners =
+Emitter.prototype.removeEventListener = function(event, fn){
+  this._callbacks = this._callbacks || {};
+
+  // all
+  if (0 == arguments.length) {
+    this._callbacks = {};
+    return this;
+  }
+
+  // specific event
+  var callbacks = this._callbacks[event];
+  if (!callbacks) return this;
+
+  // remove all handlers
+  if (1 == arguments.length) {
+    delete this._callbacks[event];
+    return this;
+  }
+
+  // remove specific handler
+  var cb;
+  for (var i = 0; i < callbacks.length; i++) {
+    cb = callbacks[i];
+    if (cb === fn || cb.fn === fn) {
+      callbacks.splice(i, 1);
+      break;
+    }
+  }
+  return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function(event){
+  this._callbacks = this._callbacks || {};
+  var args = [].slice.call(arguments, 1)
+    , callbacks = this._callbacks[event];
+
+  if (callbacks) {
+    callbacks = callbacks.slice(0);
+    for (var i = 0, len = callbacks.length; i < len; ++i) {
+      callbacks[i].apply(this, args);
+    }
+  }
+
+  return this;
+};
+
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
+
+Emitter.prototype.listeners = function(event){
+  this._callbacks = this._callbacks || {};
+  return this._callbacks[event] || [];
+};
+
+/**
+ * Check if this emitter has `event` handlers.
+ *
+ * @param {String} event
+ * @return {Boolean}
+ * @api public
+ */
+
+Emitter.prototype.hasListeners = function(event){
+  return !! this.listeners(event).length;
+};
+
+});
+require.register("component-reduce/index.js", function(exports, require, module){
+
+/**
+ * Reduce `arr` with `fn`.
+ *
+ * @param {Array} arr
+ * @param {Function} fn
+ * @param {Mixed} initial
+ *
+ * TODO: combatible error handling?
+ */
+
+module.exports = function(arr, fn, initial){  
+  var idx = 0;
+  var len = arr.length;
+  var curr = arguments.length == 3
+    ? initial
+    : arr[idx++];
+
+  while (idx < len) {
+    curr = fn.call(null, curr, arr[idx], ++idx, arr);
+  }
+  
+  return curr;
+};
+});
+require.register("superagent/lib/client.js", function(exports, require, module){
+/**
+ * Module dependencies.
+ */
+
+var Emitter = require('emitter');
+var reduce = require('reduce');
+
+/**
+ * Root reference for iframes.
+ */
+
+var root = 'undefined' == typeof window
+  ? this
+  : window;
+
+/**
+ * Noop.
+ */
+
+function noop(){};
+
+/**
+ * Check if `obj` is a host object,
+ * we don't want to serialize these :)
+ *
+ * TODO: future proof, move to compoent land
+ *
+ * @param {Object} obj
+ * @return {Boolean}
+ * @api private
+ */
+
+function isHost(obj) {
+  var str = {}.toString.call(obj);
+
+  switch (str) {
+    case '[object File]':
+    case '[object Blob]':
+    case '[object FormData]':
+      return true;
+    default:
+      return false;
+  }
+}
+
+/**
+ * Determine XHR.
+ */
+
+function getXHR() {
+  if (root.XMLHttpRequest
+    && ('file:' != root.location.protocol || !root.ActiveXObject)) {
+    return new XMLHttpRequest;
+  } else {
+    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
+    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
+    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
+    try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
+  }
+  return false;
+}
+
+/**
+ * Removes leading and trailing whitespace, added to support IE.
+ *
+ * @param {String} s
+ * @return {String}
+ * @api private
+ */
+
+var trim = ''.trim
+  ? function(s) { return s.trim(); }
+  : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
+
+/**
+ * Check if `obj` is an object.
+ *
+ * @param {Object} obj
+ * @return {Boolean}
+ * @api private
+ */
+
+function isObject(obj) {
+  return obj === Object(obj);
+}
+
+/**
+ * Serialize the given `obj`.
+ *
+ * @param {Object} obj
+ * @return {String}
+ * @api private
+ */
+
+function serialize(obj) {
+  if (!isObject(obj)) return obj;
+  var pairs = [];
+  for (var key in obj) {
+    if (null != obj[key]) {
+      pairs.push(encodeURIComponent(key)
+        + '=' + encodeURIComponent(obj[key]));
+    }
+  }
+  return pairs.join('&');
+}
+
+/**
+ * Expose serialization method.
+ */
+
+ request.serializeObject = serialize;
+
+ /**
+  * Parse the given x-www-form-urlencoded `str`.
+  *
+  * @param {String} str
+  * @return {Object}
+  * @api private
+  */
+
+function parseString(str) {
+  var obj = {};
+  var pairs = str.split('&');
+  var parts;
+  var pair;
+
+  for (var i = 0, len = pairs.length; i < len; ++i) {
+    pair = pairs[i];
+    parts = pair.split('=');
+    obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
+  }
+
+  return obj;
+}
+
+/**
+ * Expose parser.
+ */
+
+request.parseString = parseString;
+
+/**
+ * Default MIME type map.
+ *
+ *     superagent.types.xml = 'application/xml';
+ *
+ */
+
+request.types = {
+  html: 'text/html',
+  json: 'application/json',
+  xml: 'application/xml',
+  urlencoded: 'application/x-www-form-urlencoded',
+  'form': 'application/x-www-form-urlencoded',
+  'form-data': 'application/x-www-form-urlencoded'
+};
+
+/**
+ * Default serialization map.
+ *
+ *     superagent.serialize['application/xml'] = function(obj){
+ *       return 'generated xml here';
+ *     };
+ *
+ */
+
+ request.serialize = {
+   'application/x-www-form-urlencoded': serialize,
+   'application/json': JSON.stringify
+ };
+
+ /**
+  * Default parsers.
+  *
+  *     superagent.parse['application/xml'] = function(str){
+  *       return { object parsed from str };
+  *     };
+  *
+  */
+
+request.parse = {
+  'application/x-www-form-urlencoded': parseString,
+  'application/json': JSON.parse
+};
+
+/**
+ * Parse the given header `str` into
+ * an object containing the mapped fields.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
+ */
+
+function parseHeader(str) {
+  var lines = str.split(/\r?\n/);
+  var fields = {};
+  var index;
+  var line;
+  var field;
+  var val;
+
+  lines.pop(); // trailing CRLF
+
+  for (var i = 0, len = lines.length; i < len; ++i) {
+    line = lines[i];
+    index = line.indexOf(':');
+    field = line.slice(0, index).toLowerCase();
+    val = trim(line.slice(index + 1));
+    fields[field] = val;
+  }
+
+  return fields;
+}
+
+/**
+ * Return the mime type for the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+function type(str){
+  return str.split(/ *; */).shift();
+};
+
+/**
+ * Return header field parameters.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
+ */
+
+function params(str){
+  return reduce(str.split(/ *; */), function(obj, str){
+    var parts = str.split(/ *= */)
+      , key = parts.shift()
+      , val = parts.shift();
+
+    if (key && val) obj[key] = val;
+    return obj;
+  }, {});
+};
+
+/**
+ * Initialize a new `Response` with the given `xhr`.
+ *
+ *  - set flags (.ok, .error, etc)
+ *  - parse header
+ *
+ * Examples:
+ *
+ *  Aliasing `superagent` as `request` is nice:
+ *
+ *      request = superagent;
+ *
+ *  We can use the promise-like API, or pass callbacks:
+ *
+ *      request.get('/').end(function(res){});
+ *      request.get('/', function(res){});
+ *
+ *  Sending data can be chained:
+ *
+ *      request
+ *        .post('/user')
+ *        .send({ name: 'tj' })
+ *        .end(function(res){});
+ *
+ *  Or passed to `.send()`:
+ *
+ *      request
+ *        .post('/user')
+ *        .send({ name: 'tj' }, function(res){});
+ *
+ *  Or passed to `.post()`:
+ *
+ *      request
+ *        .post('/user', { name: 'tj' })
+ *        .end(function(res){});
+ *
+ * Or further reduced to a single call for simple cases:
+ *
+ *      request
+ *        .post('/user', { name: 'tj' }, function(res){});
+ *
+ * @param {XMLHTTPRequest} xhr
+ * @param {Object} options
+ * @api private
+ */
+
+function Response(req, options) {
+  options = options || {};
+  this.req = req;
+  this.xhr = this.req.xhr;
+  this.text = this.req.method !='HEAD' 
+     ? this.xhr.responseText 
+     : null;
+  this.setStatusProperties(this.xhr.status);
+  this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
+  // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
+  // getResponseHeader still works. so we get content-type even if getting
+  // other headers fails.
+  this.header['content-type'] = this.xhr.getResponseHeader('content-type');
+  this.setHeaderProperties(this.header);
+  this.body = this.req.method != 'HEAD'
+    ? this.parseBody(this.text)
+    : null;
+}
+
+/**
+ * Get case-insensitive `field` value.
+ *
+ * @param {String} field
+ * @return {String}
+ * @api public
+ */
+
+Response.prototype.get = function(field){
+  return this.header[field.toLowerCase()];
+};
+
+/**
+ * Set header related properties:
+ *
+ *   - `.type` the content type without params
+ *
+ * A response of "Content-Type: text/plain; charset=utf-8"
+ * will provide you with a `.type` of "text/plain".
+ *
+ * @param {Object} header
+ * @api private
+ */
+
+Response.prototype.setHeaderProperties = function(header){
+  // content-type
+  var ct = this.header['content-type'] || '';
+  this.type = type(ct);
+
+  // params
+  var obj = params(ct);
+  for (var key in obj) this[key] = obj[key];
+};
+
+/**
+ * Parse the given body `str`.
+ *
+ * Used for auto-parsing of bodies. Parsers
+ * are defined on the `superagent.parse` object.
+ *
+ * @param {String} str
+ * @return {Mixed}
+ * @api private
+ */
+
+Response.prototype.parseBody = function(str){
+  var parse = request.parse[this.type];
+  return parse && str && str.length
+    ? parse(str)
+    : null;
+};
+
+/**
+ * Set flags such as `.ok` based on `status`.
+ *
+ * For example a 2xx response will give you a `.ok` of __true__
+ * whereas 5xx will be __false__ and `.error` will be __true__. The
+ * `.clientError` and `.serverError` are also available to be more
+ * specific, and `.statusType` is the class of error ranging from 1..5
+ * sometimes useful for mapping respond colors etc.
+ *
+ * "sugar" properties are also defined for common cases. Currently providing:
+ *
+ *   - .noContent
+ *   - .badRequest
+ *   - .unauthorized
+ *   - .notAcceptable
+ *   - .notFound
+ *
+ * @param {Number} status
+ * @api private
+ */
+
+Response.prototype.setStatusProperties = function(status){
+  var type = status / 100 | 0;
+
+  // status / class
+  this.status = status;
+  this.statusType = type;
+
+  // basics
+  this.info = 1 == type;
+  this.ok = 2 == type;
+  this.clientError = 4 == type;
+  this.serverError = 5 == type;
+  this.error = (4 == type || 5 == type)
+    ? this.toError()
+    : false;
+
+  // sugar
+  this.accepted = 202 == status;
+  this.noContent = 204 == status || 1223 == status;
+  this.badRequest = 400 == status;
+  this.unauthorized = 401 == status;
+  this.notAcceptable = 406 == status;
+  this.notFound = 404 == status;
+  this.forbidden = 403 == status;
+};
+
+/**
+ * Return an `Error` representative of this response.
+ *
+ * @return {Error}
+ * @api public
+ */
+
+Response.prototype.toError = function(){
+  var req = this.req;
+  var method = req.method;
+  var url = req.url;
+
+  var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
+  var err = new Error(msg);
+  err.status = this.status;
+  err.method = method;
+  err.url = url;
+
+  return err;
+};
+
+/**
+ * Expose `Response`.
+ */
+
+request.Response = Response;
+
+/**
+ * Initialize a new `Request` with the given `method` and `url`.
+ *
+ * @param {String} method
+ * @param {String} url
+ * @api public
+ */
+
+function Request(method, url) {
+  var self = this;
+  Emitter.call(this);
+  this._query = this._query || [];
+  this.method = method;
+  this.url = url;
+  this.header = {};
+  this._header = {};
+  this.on('end', function(){
+    var err = null;
+    var res = null;
+
+    try {
+      res = new Response(self); 
+    } catch(e) {
+      err = new Error('Parser is unable to parse the response');
+      err.parse = true;
+      err.original = e;
+    }
+
+    self.callback(err, res);
+  });
+}
+
+/**
+ * Mixin `Emitter`.
+ */
+
+Emitter(Request.prototype);
+
+/**
+ * Allow for extension
+ */
+
+Request.prototype.use = function(fn) {
+  fn(this);
+  return this;
+}
+
+/**
+ * Set timeout to `ms`.
+ *
+ * @param {Number} ms
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.timeout = function(ms){
+  this._timeout = ms;
+  return this;
+};
+
+/**
+ * Clear previous timeout.
+ *
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.clearTimeout = function(){
+  this._timeout = 0;
+  clearTimeout(this._timer);
+  return this;
+};
+
+/**
+ * Abort the request, and clear potential timeout.
+ *
+ * @return {Request}
+ * @api public
+ */
+
+Request.prototype.abort = function(){
+  if (this.aborted) return;
+  this.aborted = true;
+  this.xhr.abort();
+  this.clearTimeout();
+  this.emit('abort');
+  return this;
+};
+
+/**
+ * Set header `field` to `val`, or multiple fields with one object.
+ *
+ * Examples:
+ *
+ *      req.get('/')
+ *        .set('Accept', 'application/json')
+ *        .set('X-API-Key', 'foobar')
+ *        .end(callback);
+ *
+ *      req.get('/')
+ *        .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
+ *        .end(callback);
+ *
+ * @param {String|Object} field
+ * @param {String} val
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.set = function(field, val){
+  if (isObject(field)) {
+    for (var key in field) {
+      this.set(key, field[key]);
+    }
+    return this;
+  }
+  this._header[field.toLowerCase()] = val;
+  this.header[field] = val;
+  return this;
+};
+
+/**
+ * Remove header `field`.
+ *
+ * Example:
+ *
+ *      req.get('/')
+ *        .unset('User-Agent')
+ *        .end(callback);
+ *
+ * @param {String} field
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.unset = function(field){
+  delete this._header[field.toLowerCase()];
+  delete this.header[field];
+  return this;
+};
+
+/**
+ * Get case-insensitive header `field` value.
+ *
+ * @param {String} field
+ * @return {String}
+ * @api private
+ */
+
+Request.prototype.getHeader = function(field){
+  return this._header[field.toLowerCase()];
+};
+
+/**
+ * Set Content-Type to `type`, mapping values from `request.types`.
+ *
+ * Examples:
+ *
+ *      superagent.types.xml = 'application/xml';
+ *
+ *      request.post('/')
+ *        .type('xml')
+ *        .send(xmlstring)
+ *        .end(callback);
+ *
+ *      request.post('/')
+ *        .type('application/xml')
+ *        .send(xmlstring)
+ *        .end(callback);
+ *
+ * @param {String} type
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.type = function(type){
+  this.set('Content-Type', request.types[type] || type);
+  return this;
+};
+
+/**
+ * Set Accept to `type`, mapping values from `request.types`.
+ *
+ * Examples:
+ *
+ *      superagent.types.json = 'application/json';
+ *
+ *      request.get('/agent')
+ *        .accept('json')
+ *        .end(callback);
+ *
+ *      request.get('/agent')
+ *        .accept('application/json')
+ *        .end(callback);
+ *
+ * @param {String} accept
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.accept = function(type){
+  this.set('Accept', request.types[type] || type);
+  return this;
+};
+
+/**
+ * Set Authorization field value with `user` and `pass`.
+ *
+ * @param {String} user
+ * @param {String} pass
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.auth = function(user, pass){
+  var str = btoa(user + ':' + pass);
+  this.set('Authorization', 'Basic ' + str);
+  return this;
+};
+
+/**
+* Add query-string `val`.
+*
+* Examples:
+*
+*   request.get('/shoes')
+*     .query('size=10')
+*     .query({ color: 'blue' })
+*
+* @param {Object|String} val
+* @return {Request} for chaining
+* @api public
+*/
+
+Request.prototype.query = function(val){
+  if ('string' != typeof val) val = serialize(val);
+  if (val) this._query.push(val);
+  return this;
+};
+
+/**
+ * Write the field `name` and `val` for "multipart/form-data"
+ * request bodies.
+ *
+ * ``` js
+ * request.post('/upload')
+ *   .field('foo', 'bar')
+ *   .end(callback);
+ * ```
+ *
+ * @param {String} name
+ * @param {String|Blob|File} val
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.field = function(name, val){
+  if (!this._formData) this._formData = new FormData();
+  this._formData.append(name, val);
+  return this;
+};
+
+/**
+ * Queue the given `file` as an attachment to the specified `field`,
+ * with optional `filename`.
+ *
+ * ``` js
+ * request.post('/upload')
+ *   .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
+ *   .end(callback);
+ * ```
+ *
+ * @param {String} field
+ * @param {Blob|File} file
+ * @param {String} filename
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.attach = function(field, file, filename){
+  if (!this._formData) this._formData = new FormData();
+  this._formData.append(field, file, filename);
+  return this;
+};
+
+/**
+ * Send `data`, defaulting the `.type()` to "json" when
+ * an object is given.
+ *
+ * Examples:
+ *
+ *       // querystring
+ *       request.get('/search')
+ *         .end(callback)
+ *
+ *       // multiple data "writes"
+ *       request.get('/search')
+ *         .send({ search: 'query' })
+ *         .send({ range: '1..5' })
+ *         .send({ order: 'desc' })
+ *         .end(callback)
+ *
+ *       // manual json
+ *       request.post('/user')
+ *         .type('json')
+ *         .send('{"name":"tj"})
+ *         .end(callback)
+ *
+ *       // auto json
+ *       request.post('/user')
+ *         .send({ name: 'tj' })
+ *         .end(callback)
+ *
+ *       // manual x-www-form-urlencoded
+ *       request.post('/user')
+ *         .type('form')
+ *         .send('name=tj')
+ *         .end(callback)
+ *
+ *       // auto x-www-form-urlencoded
+ *       request.post('/user')
+ *         .type('form')
+ *         .send({ name: 'tj' })
+ *         .end(callback)
+ *
+ *       // defaults to x-www-form-urlencoded
+  *      request.post('/user')
+  *        .send('name=tobi')
+  *        .send('species=ferret')
+  *        .end(callback)
+ *
+ * @param {String|Object} data
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.send = function(data){
+  var obj = isObject(data);
+  var type = this.getHeader('Content-Type');
+
+  // merge
+  if (obj && isObject(this._data)) {
+    for (var key in data) {
+      this._data[key] = data[key];
+    }
+  } else if ('string' == typeof data) {
+    if (!type) this.type('form');
+    type = this.getHeader('Content-Type');
+    if ('application/x-www-form-urlencoded' == type) {
+      this._data = this._data
+        ? this._data + '&' + data
+        : data;
+    } else {
+      this._data = (this._data || '') + data;
+    }
+  } else {
+    this._data = data;
+  }
+
+  if (!obj) return this;
+  if (!type) this.type('json');
+  return this;
+};
+
+/**
+ * Invoke the callback with `err` and `res`
+ * and handle arity check.
+ *
+ * @param {Error} err
+ * @param {Response} res
+ * @api private
+ */
+
+Request.prototype.callback = function(err, res){
+  var fn = this._callback;
+  this.clearTimeout();
+  if (2 == fn.length) return fn(err, res);
+  if (err) return this.emit('error', err);
+  fn(res);
+};
+
+/**
+ * Invoke callback with x-domain error.
+ *
+ * @api private
+ */
+
+Request.prototype.crossDomainError = function(){
+  var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
+  err.crossDomain = true;
+  this.callback(err);
+};
+
+/**
+ * Invoke callback with timeout error.
+ *
+ * @api private
+ */
+
+Request.prototype.timeoutError = function(){
+  var timeout = this._timeout;
+  var err = new Error('timeout of ' + timeout + 'ms exceeded');
+  err.timeout = timeout;
+  this.callback(err);
+};
+
+/**
+ * Enable transmission of cookies with x-domain requests.
+ *
+ * Note that for this to work the origin must not be
+ * using "Access-Control-Allow-Origin" with a wildcard,
+ * and also must set "Access-Control-Allow-Credentials"
+ * to "true".
+ *
+ * @api public
+ */
+
+Request.prototype.withCredentials = function(){
+  this._withCredentials = true;
+  return this;
+};
+
+/**
+ * Initiate request, invoking callback `fn(res)`
+ * with an instanceof `Response`.
+ *
+ * @param {Function} fn
+ * @return {Request} for chaining
+ * @api public
+ */
+
+Request.prototype.end = function(fn){
+  var self = this;
+  var xhr = this.xhr = getXHR();
+  var query = this._query.join('&');
+  var timeout = this._timeout;
+  var data = this._formData || this._data;
+
+  // store callback
+  this._callback = fn || noop;
+
+  // state change
+  xhr.onreadystatechange = function(){
+    if (4 != xhr.readyState) return;
+    if (0 == xhr.status) {
+      if (self.aborted) return self.timeoutError();
+      return self.crossDomainError();
+    }
+    self.emit('end');
+  };
+
+  // progress
+  if (xhr.upload) {
+    xhr.upload.onprogress = function(e){
+      e.percent = e.loaded / e.total * 100;
+      self.emit('progress', e);
+    };
+  }
+
+  // timeout
+  if (timeout && !this._timer) {
+    this._timer = setTimeout(function(){
+      self.abort();
+    }, timeout);
+  }
+
+  // querystring
+  if (query) {
+    query = request.serializeObject(query);
+    this.url += ~this.url.indexOf('?')
+      ? '&' + query
+      : '?' + query;
+  }
+
+  // initiate request
+  xhr.open(this.method, this.url, true);
+
+  // CORS
+  if (this._withCredentials) xhr.withCredentials = true;
+
+  // body
+  if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
+    // serialize stuff
+    var serialize = request.serialize[this.getHeader('Content-Type')];
+    if (serialize) data = serialize(data);
+  }
+
+  // set header fields
+  for (var field in this.header) {
+    if (null == this.header[field]) continue;
+    xhr.setRequestHeader(field, this.header[field]);
+  }
+
+  // send stuff
+  this.emit('request', this);
+  xhr.send(data);
+  return this;
+};
+
+/**
+ * Expose `Request`.
+ */
+
+request.Request = Request;
+
+/**
+ * Issue a request:
+ *
+ * Examples:
+ *
+ *    request('GET', '/users').end(callback)
+ *    request('/users').end(callback)
+ *    request('/users', callback)
+ *
+ * @param {String} method
+ * @param {String|Function} url or callback
+ * @return {Request}
+ * @api public
+ */
+
+function request(method, url) {
+  // callback
+  if ('function' == typeof url) {
+    return new Request('GET', method).end(url);
+  }
+
+  // url first
+  if (1 == arguments.length) {
+    return new Request('GET', method);
+  }
+
+  return new Request(method, url);
+}
+
+/**
+ * GET `url` with optional callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed|Function} data or fn
+ * @param {Function} fn
+ * @return {Request}
+ * @api public
+ */
+
+request.get = function(url, data, fn){
+  var req = request('GET', url);
+  if ('function' == typeof data) fn = data, data = null;
+  if (data) req.query(data);
+  if (fn) req.end(fn);
+  return req;
+};
+
+/**
+ * HEAD `url` with optional callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed|Function} data or fn
+ * @param {Function} fn
+ * @return {Request}
+ * @api public
+ */
+
+request.head = function(url, data, fn){
+  var req = request('HEAD', url);
+  if ('function' == typeof data) fn = data, data = null;
+  if (data) req.send(data);
+  if (fn) req.end(fn);
+  return req;
+};
+
+/**
+ * DELETE `url` with optional callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Function} fn
+ * @return {Request}
+ * @api public
+ */
+
+request.del = function(url, fn){
+  var req = request('DELETE', url);
+  if (fn) req.end(fn);
+  return req;
+};
+
+/**
+ * PATCH `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed} data
+ * @param {Function} fn
+ * @return {Request}
+ * @api public
+ */
+
+request.patch = function(url, data, fn){
+  var req = request('PATCH', url);
+  if ('function' == typeof data) fn = data, data = null;
+  if (data) req.send(data);
+  if (fn) req.end(fn);
+  return req;
+};
+
+/**
+ * POST `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed} data
+ * @param {Function} fn
+ * @return {Request}
+ * @api public
+ */
+
+request.post = function(url, data, fn){
+  var req = request('POST', url);
+  if ('function' == typeof data) fn = data, data = null;
+  if (data) req.send(data);
+  if (fn) req.end(fn);
+  return req;
+};
+
+/**
+ * PUT `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed|Function} data or fn
+ * @param {Function} fn
+ * @return {Request}
+ * @api public
+ */
+
+request.put = function(url, data, fn){
+  var req = request('PUT', url);
+  if ('function' == typeof data) fn = data, data = null;
+  if (data) req.send(data);
+  if (fn) req.end(fn);
+  return req;
+};
+
+/**
+ * Expose `request`.
+ */
+
+module.exports = request;
+
+});
+
+
+
+
+require.alias("component-emitter/index.js", "superagent/deps/emitter/index.js");
+require.alias("component-emitter/index.js", "emitter/index.js");
+
+require.alias("component-reduce/index.js", "superagent/deps/reduce/index.js");
+require.alias("component-reduce/index.js", "reduce/index.js");
+
+require.alias("superagent/lib/client.js", "superagent/index.js");if (typeof exports == "object") {
+  module.exports = require("superagent");
+} else if (typeof define == "function" && define.amd) {
+  define([], function(){ return require("superagent"); });
+} else {
+  this["superagent"] = require("superagent");
+}})();

+ 506 - 192
SE/superedit-TREEJS.php

@@ -1,21 +1,115 @@
 <?php
 
+Lib::loadClass('ProcesHelper');
+Lib::loadClass('DebugExecutionTime');
+Lib::loadClass('Tree');
+Lib::loadClass('TreeHelper');
+Lib::loadClass('App');
+Lib::loadClass('Filter');
+
+function TREEJS__ajaxTask__idsList($args) {
+	$zasobID = V::get('ZASOB_ID', 0, $args, 'int');
+	if ($zasobID <= 0) {
+		throw new HttpException("Wrong param ZASOB_ID", 400);
+	}
+	$id = V::get('id', 0, $args, 'int');
+	if ($id <= 0) {
+		throw new HttpException("Wrong param id", 400);
+	}
+	$zasobObj = ProcesHelper::getZasobTableInfo($zasobID);
+	if (!$zasobObj) {
+		throw new HttpException("Zasob TABELA ID={$zasobID} nie istnieje", 404);
+	}
+	$tblName = $zasobObj->DESC;
+
+	$db = DB::getDB();
+	$r = $db->get_by_id($tblName, $id);
+	if (!$r) {
+		throw new HttpException("Rekord ID={$id} nie istnieje", 404);
+	}
+
+	$wsk = array();
+	$ids_conf_arr = array();
+	$ids_conf_arr['DEVICES'] = array('id_col'=>"T_DEVICE_SERIAL",'allowed_cols'=>"ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_DEVICE_SERIAL,T_DEVICE_INFO,A_STATUS,S_OTHER_INFO");
+	$ids_conf_arr['TELBOXES'] = array('id_col'=>"T_TELBOX_NAME",'allowed_cols'=>"ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIGHBOUR_OUT,T_TELBOX_NAME,A_STATUS,S_OTHER_INFO");
+	if (!empty($ids_conf_arr)) {
+		$external_ids = array();
+		foreach ($ids_conf_arr as $k_table_name => $v_cnf) {
+			$cur_cnf = new stdClass();
+			$cur_cnf->id_col = V::get('id_col', 'ID', $v_cnf);
+			$cur_cnf->search_col = V::get('search_col', 'ID_PROJECT', $v_cnf);
+			$cur_cnf->search_col_regex = V::get('search_col_regex', '', $v_cnf);
+			$sql_id_col = $cur_cnf->id_col;
+			$sql_where = "";
+			if ($cur_cnf->search_col_regex) {
+				$sql_where = "`{$cur_cnf->search_col}` like '".str_replace('$ID', $r->ID, $cur_cnf->search_col_regex)."'";
+			} else {
+				$sql_where = "`{$cur_cnf->search_col}`='{$r->ID}'";
+			}
+
+			$db = DB::getDB();
+			$sql = "select t.`{$sql_id_col}`
+				from `{$k_table_name}` as t
+				where {$sql_where}
+			";
+			$res = $db->query($sql);
+			while ($r_wsk = $db->fetch($res)) {
+				$wsk[] = (object)array('name'=>$r_wsk->$sql_id_col, 'table'=>$k_table_name);
+			}
+		}
+	}
+	$response = new stdClass();
+	$response->ids = $wsk;
+	return $response;
+}
 
 function TREEJS() {
 global $result,$thiss;
 
+$ajaxTask = V::get('_ajaxTask', '', $_GET);
+$funName = "TREEJS__ajaxTask__{$ajaxTask}";
+if (function_exists($funName)) {
+	try {
+		$response = $funName($_GET);
+	}
+	catch (HttpException $e) {
+		$response = new stdClass();
+		$response->type = 'error';
+		$response->msg = $e->getMessage();
+		$response->errorCode = $e->getCode();
+
+		Http::sendHeaderByCode($e->getCode());
+	}
+	catch (Exception $e) {
+		$response = new stdClass();
+		$response->type = 'error';
+		$response->msg = $e->getMessage();
+		$response->errorCode = $e->getCode();
+	}
+
+	header('Content-type: application/json');
+	if (!$response) $response = new stdClass();
+	echo json_encode($response);
+	exit;
+}
+
 $zasobID = V::get('ZASOB_ID', 0, $_GET, 'int');
 if ($zasobID <= 0) {
 	echo 'Wrong param ZASOB_ID';
 	return;
 }
 
+$TEST_TREE_LAZY_LOAD = ('1' == V::get('TEST_TREE_LAZY_LOAD', '', $_GET));
+$DBG_TIME = ('1' == V::get('DBG_TIME', '', $_GET));
+$dbgExecTime = new DebugExecutionTime();
+if ($DBG_TIME) $dbgExecTime->activate();
+$dbgExecTime->log('start');
+
 echo "&lt;&lt;".'<a href="' . "index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$zasobID}" . '" title="Powrot">Powrot do tabeli</a>';
 
 $conf = null;
 
 $tblName = '';
-Lib::loadClass('ProcesHelper');
 $zasobObj = ProcesHelper::getZasobTableInfo($zasobID);
 if (!$zasobObj) {
 	echo "Zasob TABELA ID={$zasobID} nie istnieje";
@@ -24,23 +118,17 @@ if (!$zasobObj) {
 $tblName = $zasobObj->DESC;
 
 $allowed_tables_conf = array();
-$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI'] = array('set_parent_id_col'=>'P_ID');
-$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI']['params'] = array();
-$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI']['params']['show_item_callback']='tree_callback__show_item_from_IN7_MK_BAZA_DYSTRYBUCJI';
-$allowed_tables_conf ['IN7_MK_BAZA_DYSTRYBUCJI']['params']['ajax']='NIE';
+$allowed_tables_conf['IN7_MK_BAZA_DYSTRYBUCJI'] = array('set_parent_id_col'=>'P_ID');
+$allowed_tables_conf['IN7_MK_BAZA_DYSTRYBUCJI']['params'] = array();
+$allowed_tables_conf['IN7_MK_BAZA_DYSTRYBUCJI']['params']['show_item_callback'] = 'tree_callback__show_item_from_IN7_MK_BAZA_DYSTRYBUCJI';
+$allowed_tables_conf['IN7_MK_BAZA_DYSTRYBUCJI']['params']['ajax'] ='NIE';
 
 if (!array_key_exists($tblName, $allowed_tables_conf)) {
 	echo'<p>'."Brak dostepu".'</p>';
 }
 $conf = $allowed_tables_conf[$tblName];
 
-require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
-Lib::loadClass('V');
-Lib::loadClass('DB');
-Lib::loadClass('Tree');
-Lib::loadClass('TreeHelper');
 
-Lib::loadClass('App');
 echo'<style type="text/css">'."
 .btn-box{margin:0 2px 0 0;padding:0 3px;background:#bbb;color:#fff;text-decoration:none;border:0;font-weight:bold;}
 .btn-box-blue{background:#3A3AFF;color:#fff;}
@@ -62,70 +150,32 @@ echo'<style type="text/css">'."
 .filters nobr select,
 .filters nobr button{margin:0 1px;padding:0 2px;font-size:13px;}
 
+.tree-wrap li.tree-close dd ul {display:block;}
+.tree-wrap li.tree-close dd ul,
+.tree-wrap dd ul { background:url(stuff/i/t-ul-green.gif) 0 0 repeat-y; }
+.tree-wrap .btn {outline:none;}
+
 ".'</style>'."\n";
 App::show_head_css();
 App::show_head_js();
 
 
-function tree_callback__show_item_from_IN7_MK_BAZA_DYSTRYBUCJI( &$r, &$tree ) {
+function tree_callback__show_item_from_IN7_MK_BAZA_DYSTRYBUCJI(&$r, &$tree) {
 	$zasobID = V::get('ZASOB_ID', 0, $_GET, 'int');
 	// TODO: btn-box zasob type from PARENT_ID
 	$cls = array();
 	if (($search_id = $tree->get_param('search_id')) > 0 && $search_id == $r->ID) {
-		$cls []= 'search_id';
+		$cls[] = 'search_id';
 	}
 	$cls = (!empty($cls))? ' class="'.implode(' ', $cls).'"' : '';
 
-	{// $wsk == ids
-		$wsk = array();
-		if ($tree->get_param('filtr_ids')) {
-			/*
-[DEVICES]
-id_col="T_DEVICE_SERIAL"
-allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_DEVICE_SERIAL,T_DEVICE_INFO,A_STATUS_EV,S_OTHER_INFO"
-
-[TELBOXES]
-id_col="T_TELBOX_NAME"
-allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIGHBOUR_OUT,T_TELBOX_NAME,A_STATUS,S_OTHER_INFO"
-			*/
-			$ids_conf_arr = array();
-			$ids_conf_arr ['DEVICES']= array('id_col'=>"T_DEVICE_SERIAL",'allowed_cols'=>"ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_DEVICE_SERIAL,T_DEVICE_INFO,A_STATUS,S_OTHER_INFO");
-			$ids_conf_arr ['TELBOXES']= array('id_col'=>"T_TELBOX_NAME",'allowed_cols'=>"ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIGHBOUR_OUT,T_TELBOX_NAME,A_STATUS,S_OTHER_INFO");
-			if (!empty($ids_conf_arr)) {
-				$external_ids = array();
-				foreach ($ids_conf_arr as $k_table_name => $v_cnf) {
-					$cur_cnf = new stdClass();
-					$cur_cnf->id_col = V::get('id_col', 'ID', $v_cnf);
-					$cur_cnf->search_col = V::get('search_col', 'ID_PROJECT', $v_cnf);
-					$cur_cnf->search_col_regex = V::get('search_col_regex', '', $v_cnf);
-					$sql_id_col = $cur_cnf->id_col;
-					$sql_where = "";
-					if ($cur_cnf->search_col_regex) {
-						$sql_where = "`".$cur_cnf->search_col."` like '".str_replace('$ID', $zasob->ID, $cur_cnf->search_col_regex)."'";
-					} else {
-						$sql_where = "`".$cur_cnf->search_col."`='".$r->ID."'";
-					}
-
-					$sql = "select t.`".$sql_id_col."`
-						from `".$k_table_name."` as t
-						where ".$sql_where."
-					";
-					$res = DB::query( $sql );
-					while ($r_wsk = DB::fetch( $res )) {
-						$wsk []= (object)array('name'=>$r_wsk->$sql_id_col, 'table'=>$k_table_name);
-					}
-				}//end foreach
-			}
-		}
-	}
-
 	echo'<dl'.$cls.'>';
 	echo'<dt>';
 
 	$out_id = ($r->ID < 10)? '&nbsp;'.$r->ID.'' : $r->ID;
-	echo'<a href="'."index.php?MENU_INIT=TREEJS&ZASOB_ID={$zasobID}&filtr_id=".$r->ID."#TREE".$r->ID.'" class="item_id btn-box">'.$out_id.'</a>';
+	echo'<a href="'."index.php?MENU_INIT=TREEJS&ZASOB_ID={$zasobID}&filtr_id={$r->ID}#TREE{$r->ID}" . '" class="item_id btn-box">'.$out_id.'</a>';
 
-	echo'<a href="'."index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$zasobID}#EDIT/{$r->ID}".'" class="btn" title="'."Edit".'">'."E".'</a>';
+	echo'<a href="'."index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$zasobID}#EDIT/{$r->ID}".'" class="btn btn-mini btn-link" title="'."Edit".'">'."E".'</a>';
 
 	//if ($r->has_childrens) {
 	//	if (!$tree->get_param('rozwin')) {
@@ -135,7 +185,7 @@ allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIG
 	//}
 
 	// TODO: edycja nie działa - bierze ostatni edytowany rekord
-	//echo' <a href="'."?FUNCTION_INIT=IN7_MK_BAZA_DYSTRYBUCJI_EDIT&ARG1=EDIT&ARG1_VAL=".$r->ID.'" class="btn-box">'."E".'</a>';
+	//echo' <a href="'."?FUNCTION_INIT=IN7_MK_BAZA_DYSTRYBUCJI_EDIT&ARG1=EDIT&ARG1_VAL={$r->ID}".'" class="btn-box">'."E".'</a>';
 
 	$st_status_bg = '';
 	if ($r->A_STATUS == 'NORMAL') {
@@ -159,30 +209,17 @@ allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIG
 		echo' <font size="-1">'.$r->M_DIST_INVENTOR.'</font>';
 	echo'</span>';
 
+	$htmlTreeId = $tree->get_param('htmlTreeId');
+	echo ' <button class="btn btn-mini btn-link" onclick="' . "return {$htmlTreeId}_ids(this, {$r->ID});" . '">IDS</button>';
+
 	echo'</dt>';
-	if (!empty($wsk)) {
-		echo'<dd>';
-		echo'<ul>';
-		$wsk_cnt = count( $wsk );
-		foreach ($wsk as $w) {
-			echo'<li'.((--$wsk_cnt)? '' : ' class="last"').'>';
-				echo'<p>';
-				//TODO: test: echo ' <span class="btn-box btn-box-silver">'.".".$w->CW_ID.".".'</span>';
-				echo ' <span class="silver">'.$w->table.'</span>';
-				echo' <b>'.$w->name.'</b>';
-				echo'</p>';
-			echo'</li>';
-		}
-		echo'</dd>';
-	}
 	echo'</dl>'."\n";
 }
 
 
 {// tree filter
 	$tbl = $tblName;
-	Lib::loadClass('Filter');
-	$tree_filter = new Filter( $_GET, $tbl, 'session' );
+	$tree_filter = new Filter($_GET, $tbl, 'session');
 
 	if ($tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') {
 		{ // filtr_status
@@ -191,165 +228,442 @@ allowed_cols="ID,CRM_LISTA_ZASOBOW_ID:CLZ_ID,T_TELBOX_NEIGHBOUR_IN,T_TELBOX_NEIG
 			$filtr['WAITING'] = 'WAITING';
 			$filtr['NORMAL'] = 'NORMAL';
 			// TODO: add js search without page reload, add #TREE{ID}
-			$tree_filter->add_filter( 'filtr_status', $filtr, 'WSZYSTKIE', 'Status' );
+			$tree_filter->add_filter('filtr_status', $filtr, 'WSZYSTKIE', 'Status');
 		}
 		{// filtr_id
 			$filtr = array('search');
-			$tree_filter->add_filter( 'filtr_id', $filtr, '', 'Filtruj ID' );
+			$tree_filter->add_filter('filtr_id', $filtr, '', 'Filtruj ID');
 		}
 		{ // filtr_search_id
 			$filtr = array('search');
 			// TODO: add js search without page reload, add #TREE{ID}
-			$tree_filter->add_filter( 'filtr_search_id', $filtr, '', 'Wyszukaj ID' );
+			$tree_filter->add_filter('filtr_search_id', $filtr, '', 'Wyszukaj ID');
 		}
 		{ // filtr_ids
 			$filtr = array();
 			$filtr['SHOW'] = '0';
 			$filtr['HIDE'] = '1';
-			$tree_filter->add_filter( 'filtr_ids', $filtr, 'HIDE', 'IDS' );
+			$tree_filter->add_filter('filtr_ids', $filtr, 'HIDE', 'IDS');
 		}
 	}
 }// tree filter
 
 $tree_filter->_save_args();
 
+	session_write_close();// End the current session and store session data. Below $_SESSION is read-only.
 
+	$htmlTreeId = "tree" . md5(time());
+	echo '<div id="' . $htmlTreeId . '">';
+
+if(0){// RMME
 	echo'<div class="filters">';
-		echo'<form action="'."".'" method="get" style="margin:0;padding:0;">';
+		echo'<form action="'."".'" method="get" onsubmit="return false;" id="' . $htmlTreeId . '_filters" style="margin:0;padding:0;">';
 		//echo'<input type="hidden" name="'."FUNCTION_INIT".'" value="'."TREEJS".'" />';
 		echo'<input type="hidden" name="'."MENU_INIT".'" value="'."TREEJS".'" />';
 		echo'<input type="hidden" name="'."ZASOB_ID".'" value="'."{$zasobID}".'" />';
-		$tree_filter->show_filters();
-if(0){
-		{// save profile - btn
-			echo'<nobr>';
-				echo'<input type="submit" name="save_profile" value="'."Save".'" title="'."Save profile".'" />';
-			echo'</nobr>';
-		}
-		{// load profile - btn
-			echo'<nobr>';
-				echo'<input type="submit" name="load_profile" value="'."Load".'" title="'."Load profile".'" />';
-			echo'</nobr>';
-		}
-}
+		//$tree_filter->show_filters(array('submit_function'=>$htmlTreeId . '_filters(this)'));
 		echo'</form>';
 	echo'</div>';
+}
+
+?>
+<div class="filters">
+	<form action="" method="get" onsubmit="return false;" id="<?php echo "{$htmlTreeId}_filters"; ?>" style="margin:0;padding:0;">
+		<input type="hidden" name="MENU_INIT" value="TREEJS">
+		<input type="hidden" name="ZASOB_ID" value="636">
+		<nobr style="float:right;margin:-9999px 0 0 -9999px;">
+			<input type="submit" value="submit">
+		</nobr>
+		<nobr> Status
+			<select name="filtr_status" onchange="<?php echo "{$htmlTreeId}_filters(this);"; ?>">
+				<option value="WSZYSTKIE">WSZYSTKIE</option>
+				<option value="WAITING">WAITING .. NORMAL</option>
+				<option value="NORMAL">NORMAL</option>
+			</select>
+		</nobr>
+		<div class="btnseparator"></div>
+		<nobr>Filtruj ID
+			<input type="text" name="filtr_id" value="" class="i" size="4" onchange="<?php echo "return {$htmlTreeId}_filters(this);"; ?>">
+			<input type="image" src="icon/search.png" ale="Szukaj" title="Szukaj" onclick="<?php echo "return {$htmlTreeId}_filters(this);"; ?>">
+		</nobr>
+		<div class="btnseparator"></div>
+		<nobr>
+			<input type="hidden" name="filtr_clear" value="0">
+			<input type="reset" value="Wyczyść filtr" onclick="<?php echo "{$htmlTreeId}_filters(this, {clear:true});"; ?>">
+		</nobr>
+	</form>
+</div>
+<?php
 
-if(0){// test-tree-js
-	$items = array();
-	$sql = "select p.ID, p.P_ID
-			, p.`A_STATUS`
-			, p.`M_DIST_TYPE`
-			, p.`M_DIST_DESC`
-			, p.`M_DISTRIBUTOR`
-			, p.`M_DIST_INVENTOR`
-		from `".$tblName."` as p
-		where
-			p.P_ID!='-1' and p.P_ID!=''
-	";
-	$res = DB::query( $sql );
-	while ($r = DB::fetch( $res )) {
-		$r->sub = array();
-		$r->P_ID = trim($r->P_ID);
-		$r->P_ID = str_replace(' ', ',', $r->P_ID);
-		$v_parents = array();
-		$v_parents_test = explode(',', $r->P_ID);
-		foreach ($v_parents_test as $v_id) {
-			$v_id = intval(trim($v_id));
-			if ($v_id > 0) {
-				$v_parents []= $v_id;
+	if ($TEST_TREE_LAZY_LOAD) {
+		$dbgExecTime->log('start-lazy-load');
+		$items = array();
+		$db = DB::getDB();
+		$sql = "select p.ID, p.P_ID
+				, p.`A_STATUS`
+				, p.`M_DIST_TYPE`
+				, p.`M_DIST_DESC`
+				, p.`M_DISTRIBUTOR`
+				, p.`M_DIST_INVENTOR`
+			from `{$tblName}` as p
+			where
+				p.P_ID!='-1' and p.P_ID!=''
+		";
+		$res = $db->query($sql);
+		$dbgExecTime->log('lazy-execute-sql', array('lazy-load'));
+		while ($r = $db->fetch($res)) {
+			$r->sub = array();
+			$r->P_ID = trim($r->P_ID);
+			$r->P_ID = str_replace(' ', ',', $r->P_ID);
+			$v_parents = array();
+			$v_parents_test = explode(',', $r->P_ID);
+			foreach ($v_parents_test as $v_id) {
+				$v_id = intval(trim($v_id));
+				if ($v_id > 0) {
+					$v_parents[] = $v_id;
+				}
+			}
+			if (empty($v_parents)) {
+				$r->P_ID = 0;
+			} else {
+				$r->P_ID = $v_parents;
+			}
+			$items[$r->ID] = $r;
+		}
+		$dbgExecTime->log('lazy-load-sql', array('lazy-load'));
+
+		// set root for tree $pro_tree
+		$pro_tree = array();
+		foreach ($items as $k_id => $r) {
+			if ($r->P_ID == 0) {
+				$pro_tree[$r->ID] = array();
+				$v_id = $r->P_ID;
+				if (array_key_exists($v_id, $items)) {
+					$items[$v_id]->sub[$r->ID] = true;
+				}
+			} else {// array
+				foreach ($r->P_ID as $v_id) {
+					if (array_key_exists($v_id, $items)) {
+						$items[$v_id]->sub[$r->ID] = true;
+					}
+				}
+			}
+		}
+		ksort($pro_tree);
+
+		// set up has_childrens
+		foreach ($items as $k_id => $r) {
+			$items[$k_id]->has_childrens = !empty($r->sub);
+		}
+		
+
+		// build tree by P_ID - array or 0
+		function TREEJS_create_project_tree_rec($p_id, &$items) {
+			static $rec_ind;
+			$rec_ind++;
+			$ret = array();
+			if (!array_key_exists($p_id, $items)) {
+				return false;
+			} else {
+				$r = $items[$p_id];
+				if (empty($r->sub)) {
+					return false;
+				}
+				foreach ($r->sub as $k_id => $v) {
+					$ret[$k_id] = TREEJS_create_project_tree_rec($k_id, $items);
+				}
+				return $ret;
+			}
+		}
+		//$pro_tree = TREEJS_create_project_tree_rec($pro_tree, $items);
+		foreach ($pro_tree as $k_id => $v_childrens) {
+			if (array_key_exists($k_id, $items)) {
+				$pro_tree[$k_id] = TREEJS_create_project_tree_rec($k_id, $items);
 			}
-		}//end foreach
-		if (empty($v_parents)) {
-			$r->P_ID = 0;
+		}
+		$dbgExecTime->log('end-lazy-load', array('lazy-load'));
+	}
+
+	$tree = new Tree($tblName);
+	$tree->set_param('htmlTreeId', $htmlTreeId);
+	$tree->setProfiler($dbgExecTime);
+	if (($p_id_col = V::get('set_parent_id_col', '', $conf)) != '') {
+		$tree->set_parent_id_col($p_id_col);
+	}
+	if (!empty($conf['params'])) {
+		foreach ($conf['params'] as $k_param => $v_param) {
+			$tree->set_param($k_param, $v_param);
+		}
+	}
+	$tree->set_param('filtr_status', $tree_filter->get_arg('filtr_status'));
+
+	$dbgExecTime->log('start-show-tree');
+	if ($TEST_TREE_LAZY_LOAD) {
+		$tree->show_css();
+		$tree->show_js();
+		echo "\n".'<div class="tree-wrap">'."\n";
+		$tree->show_rec_by_tree($pro_tree, $items);
+		echo '</div>'."\n";
+	}
+	else {
+		if ($tree_filter->get_arg('filtr_id') != 0) {
+			$tree->showSubTree($tree_filter->get_arg('filtr_id'));
+		} else if ($tree_filter->get_arg('filtr_search_id') > 0) {
+			$tree->showSearchNode($tree_filter->get_arg('filtr_search_id'));
 		} else {
-			$r->P_ID = $v_parents;
+			$tree->show();
 		}
-		$items[$r->ID] = $r;
 	}
+	$dbgExecTime->log('end-show-tree', array('show-tree'));
+
+	echo '</div>';
+	?>
+<script>
+window['<?php echo $htmlTreeId; ?>TreeStruct'] = <?php echo json_encode($pro_tree); ?>;
+window['<?php echo $htmlTreeId; ?>TreeItems'] = <?php echo json_encode($items); ?>;
+
+// show/hide ids list - btn state txt
+var BTN_TXT_LOADING = 'IDS (loading...)',
+	BTN_TXT_SHOW = 'IDS (pokaż)',
+	BTN_TXT_HIDE = 'IDS (ukryj)';
+	BTN_TXT_NO_DATA = 'IDS (brak danych)';
+
+function <?php echo $htmlTreeId; ?>_reload(fltrs) {
+	var tree = jQuery('#<?php echo $htmlTreeId; ?>').find('.tree-wrap');
+
+	if (fltrs.filtr_status) {
+		if (-1 == _.indexOf(['NORMAL', 'WAITING'], fltrs.filtr_status)) {
+			fltrs.filtr_status = null;
+		}
+	}
+
+	var isFltrsActive = false;
+	if (!_.isEmpty(fltrs.filtr_id)) isFltrsActive = true;
+	if (fltrs.filtr_status) isFltrsActive = true;
+
+	if (!isFltrsActive) {
+		tree.find('li').removeClass('hide');
+		return;
+	} else {
+		tree.find('li').addClass('hide');
+	}
+
+	var treeStruct = window['<?php echo $htmlTreeId; ?>TreeStruct'];
+	var treeItems = window['<?php echo $htmlTreeId; ?>TreeItems'];
 
-	// set root for tree $pro_tree
-	$pro_tree = array();
-	foreach ($items as $k_id => $r) {
-		if ($r->P_ID == 0) {
-			$pro_tree [ $r->ID ] = array();
-			$v_id = $r->P_ID;
-			if (array_key_exists($v_id, $items)) {
-				$items[$v_id]->sub [$r->ID] = true;
+	if (fltrs.filtr_id) {
+		var j, ids = [], idsTmp = fltrs.filtr_id.replace(' ', '').split(',');
+		for (var i = 0; i < idsTmp.length; i++) {
+			j = _.parseInt(idsTmp[i], 10);
+			if (_.isNumber(j) && j > 0 && !_.isNaN(j)) {
+				ids.push(j);
 			}
-		} else {// array
-			foreach ($r->P_ID as $v_id) {
-				if (array_key_exists($v_id, $items)) {
-					$items[$v_id]->sub [$r->ID] = true;
+		}
+		fltrs.filtr_id = ids;
+	}
+
+	filteredIds = [];
+	if (!_.isEmpty(fltrs.filtr_id)) {
+		var curId, item, itemIsOk,
+			todoStack = _.map(fltrs.filtr_id, function(num) { return num; });
+		var limit = 1000;
+		while (!_.isEmpty(todoStack)) {
+			curId = todoStack.shift();
+			if (curId in filteredIds) continue;
+
+			item = (curId in treeItems)? treeItems[curId] : null;
+			if (!item) continue;
+
+			filteredIds[curId] = true;
+
+			var pid = _.parseInt(item['P_ID'], 10);
+			if (pid > 0) {
+				todoStack.push(pid);
+			}
+
+			if (limit-- < 1) break;
+		}
+
+		var limit = 10000;
+		todoStack = _.map(fltrs.filtr_id, function(num) { return num; });
+		while (!_.isEmpty(todoStack)) {
+			curId = todoStack.shift();
+			if (curId in filteredIds && -1 == fltrs.filtr_id.indexOf(curId)) {
+				continue;
+			}
+
+			item = (curId in treeItems)? treeItems[curId] : null;
+			if (!item) continue;
+
+			itemIsOk = false;
+			if (fltrs.filtr_status) {
+				if ('NORMAL' == fltrs.filtr_status) {
+					if ('NORMAL' === item['A_STATUS']) {
+						itemIsOk = true;
+					}
+				}
+				else if ('WAITING' == fltrs.filtr_status) {
+					if ('WAITING' === item['A_STATUS']) {
+						itemIsOk = true;
+					}
+					else if ('NORMAL' === item['A_STATUS']) {
+						itemIsOk = true;
+					}
 				}
-			}//end foreach
+			}
+			else {
+				itemIsOk = true;
+			}
+			filteredIds[curId] = itemIsOk;
+
+			var toAdd = [];
+			if (true === item['has_childrens']) {
+				for (i in item['sub']) {
+					//if (id in filteredIds) continue;
+					//if (-1 !== toAdd.indexOf(id)) continue;
+					//if (-1 !== todoStack.indexOf(id)) continue;
+					toAdd.push(i);
+				}
+			}
+			if (_.isEmpty(toAdd)) {
+				continue;
+			}
+			
+			todoStack = _.union(todoStack, toAdd);
+			if (limit-- < 1) break;
 		}
-	}//end foreach
-	ksort($pro_tree);
-
-	// set up has_childrens
-	foreach ($items as $k_id => $r) {
-		$items[$k_id]->has_childrens = !empty($r->sub);
-	}//end foreach
-	
-
-	// build tree by P_ID - array or 0
-	function TREEJS_create_project_tree_rec( $p_id, &$items ) {
-		static $rec_ind;
-		$rec_ind++;
-		$ret = array();
-		if (!array_key_exists($p_id, $items)) {
-			return false;
-		} else {
-			$r = $items[$p_id];
-			if (empty($r->sub)) {
-				return false;
+	}
+
+	if (_.isEmpty(fltrs.filtr_id)) {
+		if (fltrs.filtr_status) {
+			var item, itemIsOk;
+			for (var curId in treeItems) {
+				item = treeItems[curId];
+				if (item) {
+					itemIsOk = false;
+					if ('NORMAL' === item['A_STATUS']) {
+						itemIsOk = true;
+					}
+					if ('WAITING' == fltrs.filtr_status) {
+						if ('WAITING' === item['A_STATUS']) {
+							itemIsOk = true;
+						}
+					}
+					filteredIds[curId] = itemIsOk;
+				}
 			}
-			foreach ($r->sub as $k_id => $v) {
-				$ret [$k_id] = TREEJS_create_project_tree_rec( $k_id, $items );
-			}//end foreach
-			return $ret;
 		}
 	}
-	//$pro_tree = TREEJS_create_project_tree_rec( $pro_tree, $items );
-	foreach ($pro_tree as $k_id => $v_childrens) {
-		if (array_key_exists($k_id, $items)) {
-			$pro_tree[$k_id] = TREEJS_create_project_tree_rec( $k_id, $items );
+	for (var i in filteredIds) {
+		if (filteredIds[i]) {
+			jQuery('#TREE' + i)	
+				.removeClass('hide')
+				.removeClass('tree-close');
 		}
 	}
-}// test-tree-js
+}
+
+function <?php echo $htmlTreeId; ?>_filters(el, params) {
+	if (!el || !el.form) return false;
+	var params = params || {};
+	if (params.clear) {
+		<?php echo $htmlTreeId; ?>_reload({});
+		return;
+	}
 
-$tree = new Tree( $tblName );
-if (($p_id_col = V::get('set_parent_id_col', '', $conf)) != '') {
-	$tree->set_parent_id_col( $p_id_col );
+	var frm = el.form;
+	var fltrs = {};
+	if (frm['filtr_status'] && frm['filtr_status'].value) {
+		fltrs['filtr_status'] = frm['filtr_status'].value;
+	}
+	if (frm['filtr_id'] && frm['filtr_id'].value) {
+		fltrs['filtr_id'] = frm['filtr_id'].value;
+	}
+	<?php echo $htmlTreeId; ?>_reload(fltrs);
+	return false;
 }
-if (!empty($conf['params'])) {
-	foreach ($conf['params'] as $k_param => $v_param) {
-		$tree->set_param($k_param, $v_param);
-	}//end foreach
+
+function <?php echo $htmlTreeId; ?>_setIds(btnNode, id, idsList) {
+	var idsList = idsList || [];
+
+	var ddNode = btnNode.parentNode.nextSibling;
+	if (!ddNode) {
+		ddNode = document.createElement('dd');
+		btnNode.parentNode.parentNode.insertBefore(ddNode, btnNode.parentNode.nextSibling);
+	}
+
+	if (_.isEmpty(idsList)) {
+		btnNode.innerHTML = BTN_TXT_NO_DATA;
+		ddNode.innerHTML = '';
+		return;
+	}
+
+	var ulNode = document.createElement('ul');
+	_.each(idsList, function(item) {
+		var liNode = document.createElement('li');
+		var pNode = document.createElement('p');
+		if (!_.isEmpty(item.table)) {
+			var spanNode = document.createElement('span');
+			spanNode.className = 'btn-box btn-box-silver';
+			spanNode.appendChild(document.createTextNode(item.table));
+			pNode.appendChild(spanNode);
+		}
+		var bNode = document.createElement('b');
+		bNode.appendChild(document.createTextNode(item.name));
+
+		pNode.appendChild(bNode);
+		liNode.appendChild(pNode);
+		ulNode.appendChild(liNode);
+	})
+	if (ulNode.lastChild) {
+		ulNode.lastChild.className = 'tree-last';
+	}
+	btnNode.innerHTML = BTN_TXT_HIDE;
+	ddNode.innerHTML = '';
+	ddNode.appendChild(ulNode);
 }
-$tree->set_param('filtr_status', $tree_filter->get_arg('filtr_status'));
-$tree->set_param('filtr_ids', ($tree_filter->get_arg('filtr_ids') == 'SHOW'));
-
-if(0){// test-tree-js
-$tree->show_css();
-$tree->show_js();
-echo "\n".'<div class="tree-wrap">'."\n";
-$tree->show_rec_by_tree($pro_tree, $items);
-echo '</div>'."\n";
-
-return;
-echo'<br /><hr /><br />';
-
-// TODO: rm
-}// test-tree-js
-if ($tree_filter->get_arg('filtr_id') != 0) {
-	$tree->showSubTree( $tree_filter->get_arg('filtr_id') );
-} else if ($tree_filter->get_arg('filtr_search_id') > 0) {
-	$tree->showSearchNode( $tree_filter->get_arg('filtr_search_id') );
-} else {
-	$tree->show();
+function <?php echo $htmlTreeId; ?>_ids(btnNode, id) {
+	var item = (id in window['<?php echo $htmlTreeId; ?>TreeItems'])? window['<?php echo $htmlTreeId; ?>TreeItems'][id] : null;
+	if (!item) return;
+
+	if (null == btnNode.parentNode.nextSibling) {
+		var ddNode = document.createElement('dd');
+		btnNode.parentNode.parentNode.insertBefore(ddNode, btnNode.parentNode.nextSibling);
+	}
+
+	if (BTN_TXT_HIDE === btnNode.innerHTML) {
+		btnNode.innerHTML = BTN_TXT_SHOW;
+		btnNode.parentNode.nextSibling.className='hide';
+	} else if (BTN_TXT_SHOW === btnNode.innerHTML) {
+		btnNode.innerHTML = BTN_TXT_HIDE;
+		btnNode.parentNode.nextSibling.className='';
+	} else if (BTN_TXT_LOADING === btnNode.innerHTML) {
+	} else if (BTN_TXT_NO_DATA === btnNode.innerHTML) {
+	} else {// INIT is default state
+		btnNode.innerHTML = BTN_TXT_LOADING;
+		superagent
+			.get('index.php')
+			.query({FUNCTION_INIT: '<?php echo __FUNCTION__; ?>'})
+			.query({ZASOB_ID: '<?php echo V::get('ZASOB_ID', 0, $_GET, 'int'); ?>'})
+			.query({HEADER_NOT_INIT: 'YES'})
+			.query({_ajaxTask: 'idsList'})
+			.query({id: id})
+			.end(function(error, res) {
+				if (res.ok && 'ids' in res.body) {
+					<?php echo $htmlTreeId; ?>_setIds(btnNode, id, res.body.ids);
+				} else {
+					<?php echo $htmlTreeId; ?>_setIds(btnNode, id, {ids: []});
+				}
+			});
+	}
+	return false;
 }
+</script>
+	<?php
 
+	if($DBG_TIME){
+		$dbgExecTime->log('end');
+		$dbgExecTime->printDebug();
+	}
 
 }