<commit_before>var map;
var markers = [];

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -33.114274, lng: -68.480041},
        zoom: 19
    });
    map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
}

function load_data(){
    query       = "SELECT * FROM SOL_TYPE_DUST_OAP_TEMPSAMPLE LIMIT 1";
    enc_query   = encodeURIComponent(query);
    $.getJSON("jsonp/" + enc_query, create_paths);
    //setTimeout(load_data(), 1000000);
}

function create_paths(data){
    console.log(data)
    for (var i=0; i < data.length; i++) {
        var myLatLng = new google.maps.LatLng(
                                data[i].value.latitude,
                                data[i].value.longitude);
        if (markerExists(myLatLng)==0){
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
            });
            markers.push(marker);
        }
    }
}

function markerExists(LatLng){
    for( i=0; i<markers.length; i++ ) {
        if (markers[i].getPosition().toString() == LatLng.toString())
          return 1;
    }
    return 0;
}
<commit_msg>Now quering HR_NEIGHB<commit_after>var map;
var markers = [];

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -33.114274, lng: -68.480041},
        zoom: 19
    });
    map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
}

function load_data(){
    query       = "SELECT * FROM SOL_TYPE_DUST_NOTIF_HRNEIGHBORS WHERE \"site\"='ARG_junin' LIMIT 2";
    enc_query   = encodeURIComponent(query);
    $.getJSON("jsonp/" + enc_query, create_paths);
    //setTimeout(load_data(), 1000000);
}

function create_paths(data){
    console.log(data)
    for (var i=0; i < data.length; i++) {
        var myLatLng = new google.maps.LatLng(
                                data[i].value.latitude,
                                data[i].value.longitude);
        if (markerExists(myLatLng)==0){
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
            });
            markers.push(marker);
        }
        for (var j=0; j<data.neighbors.length; j++){
           alert(data.neighbors[j])
        }
    }
}

function markerExists(LatLng){
    for( i=0; i<markers.length; i++ ) {
        if (markers[i].getPosition().toString() == LatLng.toString())
          return 1;
    }
    return 0;
}
<|endoftext|>


<commit_before>var xls =  {
    save: function(data, dirname, filename, sheetname, successCallback, errorCallback){
        /*  Modelo dos parâmetros
            var data = [
                            {id:"1", name:"claudio"} ,
                            {id:"2", name:"marta"} ,
                            {id:"3", name:"isabela"}
                       ];
            dirname = "ExcelAPI";
            filename = "file-example.xls";
            sheetname = "Plan1";
        */

        cordova.exec(
            successCallback,// callback de sucesso
            errorCallback,  // callback de erro
            'Xls',          // Classe java onde o código se encontra
            'saveXLS',      // Nome da action da classe que será chamada
            [{              // Array de parâmetros
                "data"     : data,
                "dirname"  : dirname,
                "filename" : filename,
                "sheetname": sheetname
            }]
        );
    }
}//fim do objeto

module.exports = xls;<commit_msg>Fixed an error<commit_after>cordova.define("net.claudiomedeiros.xls.Xls", function(require, exports, module) {
    var xls =  {
        save: function(data, dirname, filename, sheetname, successCallback, errorCallback){
            /*  Modelo dos parâmetros
                var data = [
                    {id:"1", name:"claudio"} ,
                    {id:"2", name:"marta"} ,
                    {id:"3", name:"isabela"}
                ];
                dirname = "ExcelAPI";
                filename = "file-example.xls";
                sheetname = "Plan1";
            */

            cordova.exec(
                successCallback,// callback de sucesso
                errorCallback,  // callback de erro
                'Xls',          // Classe java onde o código se encontra
                'saveXLS',      // Nome da action da classe que será chamada
                [{              // Array de parâmetros
                    "data"     : data,
                    "dirname"  : dirname,
                    "filename" : filename,
                    "sheetname": sheetname
                }]
            );
        }
    }//fim do objeto

    module.exports = xls;
});<|endoftext|>


<commit_before>/**
 * Yepnope JS
 *
 * Version 0.1.2
 *
 * by Alex Sexton - @SlexAxton
 *
 * Tri-Licensed WTFPL, BSD, & MIT
 *
 * Feature-test driven script loader on top of LABJS
 */
(function(window, doc, undefined){
// Save old $LAB value
var $LAB,
    old$LAB = window.$LAB,
    toString = {}.toString,
    test = {
      isArray: Array.isArray || function( obj ) {
        return toString.call(obj) == "[object Array]";
      },
      isObject: function(obj) {
        // Lame object detection, but don't pass it stupid stuff?
        return typeof obj == "object";
      },
      isString: function(s) {
        return typeof s == "string";
      }
    },
    prefixes = {
      'css': function(resource) {
        resource.forceCSS = true;
        return resource;
      }
    };

// LABJS 1.0.3
(function(q){function M(g,e){var h=/^\w+\:\/\//,j;if(typeof g!=r)g="";if(typeof e!=r)e="";j=(h.test(g)?"":e)+g;return(h.test(j)?"":j.charAt(0)==="/"?Y:Z)+j}function G(g,e){function h(a,b){if(a[w]&&a[w]!==$&&a[w]!=="loaded"||b[A])return k;a[aa]=a[H]=f;return i}function j(a,b,d){if((d=!!d)||h(a,b)){b[A]=i;for(var c in n)if(n[N](c)&&!n[c][A])return;ba=i;ca()}}function s(a){if(B.call(a[C])===O){a[C]();a[C]=f}}function ra(a,b){if(h(a,b)){b[o]=i;D(function(){t[b[E]].removeChild(a);s(b)},0)}}function sa(a,
b){if(a[w]===4){a[H]=P;b[o]=i;D(function(){s(b)},0)}}function Q(a,b,d,c,l,p){var x=a[E];D(function(){if("item"in t[x]){if(!t[x][0]){D(arguments.callee,25);return}t[x]=t[x][0]}var u=m.createElement(da);if(typeof d==r)u.type=d;if(typeof c==r)u.charset=c;if(B.call(l)===O){u[aa]=u[H]=function(){l(u,a)};u.src=b}t[x].insertBefore(u,x===z?t[x].firstChild:f);if(typeof p==r){u.text=p;j(u,a,i)}},0)}function ea(a,b,d,c){R[a[S]]=i;Q(a,b,d,c,j)}function fa(a,b,d,c){var l=arguments;if(v&&a[o]==f){a[o]=k;Q(a,b,
ga,c,ra)}else if(!v&&a[o]!=f&&!a[o])a[C]=function(){fa.apply(f,l)};else v||ea.apply(f,l)}function ha(a,b,d,c){var l=arguments,p;if(v&&a[o]==f){a[o]=k;p=a.xhr=ia?new ia("Microsoft.XMLHTTP"):new q.XMLHttpRequest;p[H]=function(){sa(p,a)};p.open("GET",b);p.send("")}else if(!v&&a[o]!=f&&!a[o])a[C]=function(){ha.apply(f,l)};else if(!v){R[a[S]]=i;Q(a,b,d,c,f,a.xhr.responseText);a.xhr=f}}function ja(a){if(a.allowDup==f)a.allowDup=e.dupe;var b=a.type,d=a.charset,c=a.allowDup;a=M(a.src,ta);var l=M(a).indexOf(Y)===
0;if(typeof d!=r)d=f;c=!!c;if(c=!c){if(!(c=R[a]!=f)){if(!(c=v&&n[a]))a:{for(var p=-1;c=ua[++p];)if(typeof c.src==r&&a===M(c.src)&&c.type!==ga){c=i;break a}c=k}c=c}c=c}if(c)n[a]!=f&&n[a][o]&&!n[a][A]&&l&&j(f,n[a],i);else{if(n[a]==f)n[a]={};c=n[a];if(c[E]==f)c[E]=va;c[A]=k;c[S]=a;T=i;if(!I&&ka&&l)ha(c,a,b,d);else!I&&la?fa(c,a,b,d):ea(c,a,b,d)}}function U(a){g&&!I&&J.push(a);if(!g||F)a()}function ma(a){var b=[],d;for(d=-1;++d<a.length;)if(B.call(a[d])===wa)b=b.concat(ma(a[d]));else b[b.length]=a[d];
return b}g=!!g;if(e==f)e=y;var ba=k,F=g&&e[K],la=F&&e.cache,I=F&&e.order,ka=F&&e.xhr,xa=e[V],va=e.which,ta=e.base,ca=P,T=k,L,v=i,n={},J=[],W=f;F=la||ka||I;L={script:function(){na(W);var a=ma(arguments),b=L,d;if(xa)for(d=-1;++d<a.length;){if(d===0)U(function(){ja(typeof a[0]==r?{src:a[0]}:a[0])});else b=b.script(a[d]);b=b.wait()}else U(function(){for(d=-1;++d<a.length;)ja(typeof a[d]==r?{src:a[d]}:a[d])});W=D(function(){v=k},5);return b},wait:function(a){na(W);v=k;B.call(a)===O||(a=P);var b=G(i,e),
d=b.trigger,c=function(){try{a()}catch(p){}d()};delete b.trigger;var l=function(){if(T&&!ba)ca=c;else c()};g&&!T?J.push(l):U(l);return b}};if(g)L.trigger=function(){for(var a,b=-1;a=J[++b];)a();J=[]};return L}function oa(g){var e,h={},j={UseCachePreload:"cache",UseLocalXHR:"xhr",UsePreloading:K,AlwaysPreserveOrder:V,AllowDuplicates:"dupe"},s={AppendTo:E,BasePath:"base"};for(e in j)s[e]=j[e];h.order=!!y.order;for(e in s)if(s[N](e)&&y[s[e]]!=f)h[s[e]]=g[e]!=f?g[e]:y[s[e]];for(e in j)if(j[N](e))h[j[e]]=
!!h[j[e]];if(!h[K])h.cache=h.order=h.xhr=k;h.which=h.which===z||h.which===X?h.which:z;return h}var r="string",z="head",X="body",da="script",w="readyState",o="preloaddone",C="loadtrigger",S="srcuri",K="preload",$="complete",A="done",E="which",V="preserve",H="onreadystatechange",aa="onload",N="hasOwnProperty",ga="script/cache",O="[object Function]",wa="[object Array]",f=null,i=true,k=false,m=q.document,ia=q.ActiveXObject,D=q.setTimeout,na=q.clearTimeout,B=Object.prototype.toString,P=function(){},t=
{},R={},Z=/^[^?#]*\//.exec(q.location.href)[0],Y=/^\w+\:\/\/\/?[^\/]+/.exec(Z)[0],ua=m.getElementsByTagName(da),pa=q.opera&&B.call(q.opera)=="[object Opera]",qa="MozAppearance"in m.documentElement.style,y={cache:!(qa||pa),order:qa||pa,xhr:i,dupe:i,base:"",which:z};y[V]=k;y[K]=i;t[z]=m.head||m.getElementsByTagName(z);t[X]=m.getElementsByTagName(X);q.$LAB={setGlobalDefaults:function(g){y=oa(g)},setOptions:function(g){return G(k,oa(g))},script:function(){return G().script.apply(f,arguments)},wait:function(){return G().wait.apply(f,
arguments)}};(function(g,e,h){if(m[w]==f&&m[g]){m[w]="loading";m[g](e,h=function(){m.removeEventListener(e,h,k);m[w]=$},k)}})("addEventListener","DOMContentLoaded")})(window);

// Remove LAB from the window
$LAB        = window.$LAB;
window.$LAB = old$LAB;

// Yepnope
window.yepnope = function(needs, currentLabChain){
  var i,
      need,
      nlen = needs.length,
      // start the chain as a plain instance
      labChain = currentLabChain || $LAB;

  function satisfyPrefixes(url) {
    // make sure we have a url
    if (url) {
      // split all prefixes out
      var parts = url.split('!'),
          pLen  = parts.length,
          res = {
            url: parts[pLen-1],
            prefixes: (pLen > 1) ? parts.slice(0, pLen-1) : undefined
          },
          mFunc;

      // loop through prefixes
      // if there are none, this automatically gets skipped
      for (var i = 0; i < pLen-1; i++) {
        mFunc = prefixes[parts[i]];
        if (mFunc) {
          res = mFunc(res);
        }
      }

      // return the final url
      return res;
    }
    return false;
  }

  function loadScriptOrStyle (inc, callback, labChain, testResult) {
    // run through our set of prefixes
    var resource = satisfyPrefixes(inc);
    console.log(resource);
    // if no object is returned or the url is empty/false just exit the load
    if (!resource || !resource.url) {
      return labChain;
    }

    var inc       = resource.url,
        incLen    = inc.length,
        forceCss  = resource.forceCSS;

    // If it's specifically css with the prefix, just inject it (useful for weird extensions and cachebusted urls, etc)
    // Also do this if it ends in a .css extension
    if (incLen > 4 && (forceCss || inc.substr(incLen-4) === '.css')) {
      var docHead   = doc.getElementsByTagName("head")[0] || doc.documentElement,
          styleElem = doc.createElement('link'),
          origInc   = inc;

      // add our src to it
      styleElem.href = inc;
      styleElem.rel  = 'stylesheet';
      styleElem.type = 'text/css';

      // inject the file
      docHead.insertBefore(styleElem, docHead.firstChild);

      // call the callback
      if (callback) {
        callback(origInc, testResult);
      }
    }
    // Otherwise assume that it's a script
    else {
      // Don't do a callback if it didn't have one
      labChain = labChain.script(inc);

      // Call the callback if we have one (via the labjs wait)
      if (callback) {
        labChain = labChain.wait(function(){
          // pass the callback the unique loaded script
          callback(inc, testResult);
        });
      }
    }

    return labChain;
  }

  function loadFromTestObject(testObject, labChain) {
      var testResult = !!(testObject.test),
          needGroup = (testResult) ? testObject.yep : testObject.nope;

      // If it's a string
      if (test.isString(needGroup)) {
        // Just load the script of style
        labChain = loadScriptOrStyle(needGroup, testObject.callback, labChain, testResult);
      }
      // If it's an array
      else if (test.isArray(needGroup)) {
        // Grab each thing out of it
        for (var i = 0; i < needGroup.length; i++) {
          // Load each thing
          labChain = loadScriptOrStyle(needGroup[i], testObject.callback, labChain, testResult);
        }
      }

      // Alias 'both' as 'load' so it's more semantic sometimes
      if (testObject.both && !testObject.load) {
        testObject.load = testObject.both;
      }

      // get anything in the load object as well
      if (test.isString(testObject.load)) {
        // Just load the script of style
        labChain = loadScriptOrStyle(testObject.load, testObject.callback, labChain, testResult);
      }
      // If it's an array
      else if (test.isArray(testObject.load)) {
        // Grab each thing out of it
        for (var i = 0; i < testObject.load.length; i++) {
          // Load each thing
          labChain = loadScriptOrStyle(testObject.load[i], testObject.callback, labChain, testResult);
        }
      }

      return labChain;
  }

  // Someone just decides to load a single script or css file as a string
  if (test.isString(needs)) {
    labChain = loadScriptOrStyle(needs, false, labChain);
  }
  // Normal case is likely an array of different types of loading options
  else if (test.isArray(needs)) {
    // go through the list of needs
    for(i=0; i < nlen; i++) {
      need = needs[i];

      // if it's a string, just load it
      if (test.isString(need)) {
        labChain = loadScriptOrStyle(need, false, labChain);
      }
      // if it's an array, call our function recursively
      else if (test.isArray(need)) {
        labChain = window.yepnope(need, labChain);
      }
      // if it's an object, use our modernizr logic to win
      else if (test.isObject(need)) {
        labChain = loadFromTestObject(need, labChain);
      }
    }
  }
  // Allow a single object to be passed in
  else if (test.isObject(needs)) {
    labChain = loadFromTestObject(needs, labChain);
  }

  // allow more loading on this chain
  return labChain;
};

window.yepnope.addPrefix = function(prefix, callback) {
  prefixes[prefix] = callback;
};

})(this, this.document);
<commit_msg>Added hooks for forcing JS, bypassing all includes, and adding automatic callbacks.<commit_after>/**
 * Yepnope JS
 *
 * Version 0.1.2
 *
 * by Alex Sexton - @SlexAxton
 *
 * Tri-Licensed WTFPL, BSD, & MIT
 *
 * Feature-test driven script loader on top of LABJS
 */
(function(window, doc, undefined){
// Save old $LAB value
var $LAB,
    old$LAB = window.$LAB,
    toString = {}.toString,
    test = {
      isArray: Array.isArray || function( obj ) {
        return toString.call(obj) == "[object Array]";
      },
      isObject: function(obj) {
        // Lame object detection, but don't pass it stupid stuff?
        return typeof obj == "object";
      },
      isString: function(s) {
        return typeof s == "string";
      }
    },
    prefixes = {
      'css': function(resource) {
        resource.forceCSS = true;
        return resource;
      }
    };

// LABJS 1.0.3
(function(q){function M(g,e){var h=/^\w+\:\/\//,j;if(typeof g!=r)g="";if(typeof e!=r)e="";j=(h.test(g)?"":e)+g;return(h.test(j)?"":j.charAt(0)==="/"?Y:Z)+j}function G(g,e){function h(a,b){if(a[w]&&a[w]!==$&&a[w]!=="loaded"||b[A])return k;a[aa]=a[H]=f;return i}function j(a,b,d){if((d=!!d)||h(a,b)){b[A]=i;for(var c in n)if(n[N](c)&&!n[c][A])return;ba=i;ca()}}function s(a){if(B.call(a[C])===O){a[C]();a[C]=f}}function ra(a,b){if(h(a,b)){b[o]=i;D(function(){t[b[E]].removeChild(a);s(b)},0)}}function sa(a,
b){if(a[w]===4){a[H]=P;b[o]=i;D(function(){s(b)},0)}}function Q(a,b,d,c,l,p){var x=a[E];D(function(){if("item"in t[x]){if(!t[x][0]){D(arguments.callee,25);return}t[x]=t[x][0]}var u=m.createElement(da);if(typeof d==r)u.type=d;if(typeof c==r)u.charset=c;if(B.call(l)===O){u[aa]=u[H]=function(){l(u,a)};u.src=b}t[x].insertBefore(u,x===z?t[x].firstChild:f);if(typeof p==r){u.text=p;j(u,a,i)}},0)}function ea(a,b,d,c){R[a[S]]=i;Q(a,b,d,c,j)}function fa(a,b,d,c){var l=arguments;if(v&&a[o]==f){a[o]=k;Q(a,b,
ga,c,ra)}else if(!v&&a[o]!=f&&!a[o])a[C]=function(){fa.apply(f,l)};else v||ea.apply(f,l)}function ha(a,b,d,c){var l=arguments,p;if(v&&a[o]==f){a[o]=k;p=a.xhr=ia?new ia("Microsoft.XMLHTTP"):new q.XMLHttpRequest;p[H]=function(){sa(p,a)};p.open("GET",b);p.send("")}else if(!v&&a[o]!=f&&!a[o])a[C]=function(){ha.apply(f,l)};else if(!v){R[a[S]]=i;Q(a,b,d,c,f,a.xhr.responseText);a.xhr=f}}function ja(a){if(a.allowDup==f)a.allowDup=e.dupe;var b=a.type,d=a.charset,c=a.allowDup;a=M(a.src,ta);var l=M(a).indexOf(Y)===
0;if(typeof d!=r)d=f;c=!!c;if(c=!c){if(!(c=R[a]!=f)){if(!(c=v&&n[a]))a:{for(var p=-1;c=ua[++p];)if(typeof c.src==r&&a===M(c.src)&&c.type!==ga){c=i;break a}c=k}c=c}c=c}if(c)n[a]!=f&&n[a][o]&&!n[a][A]&&l&&j(f,n[a],i);else{if(n[a]==f)n[a]={};c=n[a];if(c[E]==f)c[E]=va;c[A]=k;c[S]=a;T=i;if(!I&&ka&&l)ha(c,a,b,d);else!I&&la?fa(c,a,b,d):ea(c,a,b,d)}}function U(a){g&&!I&&J.push(a);if(!g||F)a()}function ma(a){var b=[],d;for(d=-1;++d<a.length;)if(B.call(a[d])===wa)b=b.concat(ma(a[d]));else b[b.length]=a[d];
return b}g=!!g;if(e==f)e=y;var ba=k,F=g&&e[K],la=F&&e.cache,I=F&&e.order,ka=F&&e.xhr,xa=e[V],va=e.which,ta=e.base,ca=P,T=k,L,v=i,n={},J=[],W=f;F=la||ka||I;L={script:function(){na(W);var a=ma(arguments),b=L,d;if(xa)for(d=-1;++d<a.length;){if(d===0)U(function(){ja(typeof a[0]==r?{src:a[0]}:a[0])});else b=b.script(a[d]);b=b.wait()}else U(function(){for(d=-1;++d<a.length;)ja(typeof a[d]==r?{src:a[d]}:a[d])});W=D(function(){v=k},5);return b},wait:function(a){na(W);v=k;B.call(a)===O||(a=P);var b=G(i,e),
d=b.trigger,c=function(){try{a()}catch(p){}d()};delete b.trigger;var l=function(){if(T&&!ba)ca=c;else c()};g&&!T?J.push(l):U(l);return b}};if(g)L.trigger=function(){for(var a,b=-1;a=J[++b];)a();J=[]};return L}function oa(g){var e,h={},j={UseCachePreload:"cache",UseLocalXHR:"xhr",UsePreloading:K,AlwaysPreserveOrder:V,AllowDuplicates:"dupe"},s={AppendTo:E,BasePath:"base"};for(e in j)s[e]=j[e];h.order=!!y.order;for(e in s)if(s[N](e)&&y[s[e]]!=f)h[s[e]]=g[e]!=f?g[e]:y[s[e]];for(e in j)if(j[N](e))h[j[e]]=
!!h[j[e]];if(!h[K])h.cache=h.order=h.xhr=k;h.which=h.which===z||h.which===X?h.which:z;return h}var r="string",z="head",X="body",da="script",w="readyState",o="preloaddone",C="loadtrigger",S="srcuri",K="preload",$="complete",A="done",E="which",V="preserve",H="onreadystatechange",aa="onload",N="hasOwnProperty",ga="script/cache",O="[object Function]",wa="[object Array]",f=null,i=true,k=false,m=q.document,ia=q.ActiveXObject,D=q.setTimeout,na=q.clearTimeout,B=Object.prototype.toString,P=function(){},t=
{},R={},Z=/^[^?#]*\//.exec(q.location.href)[0],Y=/^\w+\:\/\/\/?[^\/]+/.exec(Z)[0],ua=m.getElementsByTagName(da),pa=q.opera&&B.call(q.opera)=="[object Opera]",qa="MozAppearance"in m.documentElement.style,y={cache:!(qa||pa),order:qa||pa,xhr:i,dupe:i,base:"",which:z};y[V]=k;y[K]=i;t[z]=m.head||m.getElementsByTagName(z);t[X]=m.getElementsByTagName(X);q.$LAB={setGlobalDefaults:function(g){y=oa(g)},setOptions:function(g){return G(k,oa(g))},script:function(){return G().script.apply(f,arguments)},wait:function(){return G().wait.apply(f,
arguments)}};(function(g,e,h){if(m[w]==f&&m[g]){m[w]="loading";m[g](e,h=function(){m.removeEventListener(e,h,k);m[w]=$},k)}})("addEventListener","DOMContentLoaded")})(window);

// Remove LAB from the window
$LAB        = window.$LAB;
window.$LAB = old$LAB;

// Yepnope
window.yepnope = function(needs, currentLabChain){
  var i,
      need,
      nlen = needs.length,
      // start the chain as a plain instance
      labChain = currentLabChain || $LAB;

  function satisfyPrefixes(url) {
    // make sure we have a url
    if (url) {
      // split all prefixes out
      var parts = url.split('!'),
          pLen  = parts.length,
          res = {
            url: parts[pLen-1],
            prefixes: (pLen > 1) ? parts.slice(0, pLen-1) : undefined
          },
          mFunc;

      // loop through prefixes
      // if there are none, this automatically gets skipped
      for (var i = 0; i < pLen-1; i++) {
        mFunc = prefixes[parts[i]];
        if (mFunc) {
          res = mFunc(res);
        }
      }

      // return the final url
      return res;
    }
    return false;
  }

  function loadScriptOrStyle (input, callback, labChain, testResult) {
    // run through our set of prefixes
    var resource = satisfyPrefixes(input);

    // if no object is returned or the url is empty/false just exit the load
    if (!resource || !resource.url) {
      return labChain;
    }

    var inc          = resource.url,
        incLen       = inc.length,
        instead      = resource.instead,
        autoCallback = resource.autoCallback,
        forceJS      = resource.forceJS,
        forceCSS     = resource.forceCSS;

    // if someone is overriding all normal functionality
    if (instead) {
      return instead(input, callback, labChain, restResult);
    }
    // If it's specifically css with the prefix, just inject it (useful for weird extensions and cachebusted urls, etc)
    // Also do this if it ends in a .css extension
    else if (incLen > 4 && (forceCSS || (!forceJS && inc.substr(incLen-4) === '.css'))) {
      var docHead   = doc.getElementsByTagName("head")[0] || doc.documentElement,
          styleElem = doc.createElement('link'),
          origInc   = inc;

      // add our src to it
      styleElem.href = inc;
      styleElem.rel  = 'stylesheet';
      styleElem.type = 'text/css';

      // inject the file
      docHead.insertBefore(styleElem, docHead.firstChild);

      // call the callback
      if (callback) {
        callback(origInc, testResult);
      }
      if (autoCallback) {
        autoCallback(origInc, testResult);
      }
    }
    // Otherwise assume that it's a script
    else {
      // Don't do a callback if it didn't have one
      labChain = labChain.script(inc);

      // Call the callback if we have one (via the labjs wait)
      if (callback) {
        labChain = labChain.wait(function(){
          // pass the callback the unique loaded script
          callback(inc, testResult);
        });
      }
    }

    return labChain;
  }

  function loadFromTestObject(testObject, labChain) {
      var testResult = !!(testObject.test),
          needGroup = (testResult) ? testObject.yep : testObject.nope;

      // If it's a string
      if (test.isString(needGroup)) {
        // Just load the script of style
        labChain = loadScriptOrStyle(needGroup, testObject.callback, labChain, testResult);
      }
      // If it's an array
      else if (test.isArray(needGroup)) {
        // Grab each thing out of it
        for (var i = 0; i < needGroup.length; i++) {
          // Load each thing
          labChain = loadScriptOrStyle(needGroup[i], testObject.callback, labChain, testResult);
        }
      }

      // Alias 'both' as 'load' so it's more semantic sometimes
      if (testObject.both && !testObject.load) {
        testObject.load = testObject.both;
      }

      // get anything in the load object as well
      if (test.isString(testObject.load)) {
        // Just load the script of style
        labChain = loadScriptOrStyle(testObject.load, testObject.callback, labChain, testResult);
      }
      // If it's an array
      else if (test.isArray(testObject.load)) {
        // Grab each thing out of it
        for (var i = 0; i < testObject.load.length; i++) {
          // Load each thing
          labChain = loadScriptOrStyle(testObject.load[i], testObject.callback, labChain, testResult);
        }
      }

      return labChain;
  }

  // Someone just decides to load a single script or css file as a string
  if (test.isString(needs)) {
    labChain = loadScriptOrStyle(needs, false, labChain);
  }
  // Normal case is likely an array of different types of loading options
  else if (test.isArray(needs)) {
    // go through the list of needs
    for(i=0; i < nlen; i++) {
      need = needs[i];

      // if it's a string, just load it
      if (test.isString(need)) {
        labChain = loadScriptOrStyle(need, false, labChain);
      }
      // if it's an array, call our function recursively
      else if (test.isArray(need)) {
        labChain = window.yepnope(need, labChain);
      }
      // if it's an object, use our modernizr logic to win
      else if (test.isObject(need)) {
        labChain = loadFromTestObject(need, labChain);
      }
    }
  }
  // Allow a single object to be passed in
  else if (test.isObject(needs)) {
    labChain = loadFromTestObject(needs, labChain);
  }

  // allow more loading on this chain
  return labChain;
};

window.yepnope.addPrefix = function(prefix, callback) {
  prefixes[prefix] = callback;
};

})(this, this.document);
<|endoftext|>


<commit_before>// @flow
import jsdom from 'mocha-jsdom';
import React from 'react'
import { mount, render } from 'enzyme'

import { resetStyled, expectCSSMatches } from './utils'
import ThemeProvider from '../models/ThemeProvider'

let styled

describe('theming', () => {
  beforeEach(() => {
    styled = resetStyled()
  })

  it('should inject props.theme into a styled component', () => {
    const Comp = styled.div`
      color: ${props => props.theme.color};
    `
    const theme = { color: 'black' }
    render(
      <ThemeProvider theme={theme}>
        <Comp />
      </ThemeProvider>
    )
    expectCSSMatches(`.a { color: ${theme.color}; }`)
  })

  it('should inject props.theme into a styled component multiple levels deep', () => {
    const Comp = styled.div`
      color: ${props => props.theme.color};
    `
    const theme = { color: 'black' }
    render(
      <ThemeProvider theme={theme}>

            <Comp />

      </ThemeProvider>
    )
    expectCSSMatches(`.a { color: ${theme.color}; }`)
  })

  it('should properly allow a component to fallback to its default props when a theme is not provided', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.test.color};
    `

    Comp1.defaultProps = {
      theme: {
        test: {
          color: "purple"
        }
      }
    }
    render(

        <Comp1 />

    )
    expectCSSMatches(`.a { color: purple; }`)
  })

  it('should properly set the theme with an empty object when no teme is provided and no defaults are set', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `
    render(

        <Comp1 />

    )
    expectCSSMatches(`.a { color: ; }`)
  })

  it('should only inject props.theme into styled components within its child component tree', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `
    const Comp2 = styled.div`
      background: ${props => props.theme.color};
    `

    const theme = { color: 'black' }
    render(

        <ThemeProvider theme={theme}>

            <Comp1 />

        </ThemeProvider>
        <Comp2 />

    )
    expectCSSMatches(`.a { color: ${theme.color}; } .b { background: ; }`)
  })

  it('should inject props.theme into all styled components within the child component tree', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `
    const Comp2 = styled.div`
      background: ${props => props.theme.color};
    `
    const theme = { color: 'black' }
    render(
      <ThemeProvider theme={theme}>

            <Comp1 />

          <Comp2 />

      </ThemeProvider>
    )
    expectCSSMatches(`.a { color: ${theme.color}; } .b { background: ${theme.color}; }`)
  })

  it('should inject new CSS when the theme changes', () => {
    const Comp = styled.div`
      color: ${props => props.theme.color};
    `
    const originalTheme = { color: 'black' }
    const newTheme = { color: 'blue' }
    let theme = originalTheme
    // Force render the component
    const renderComp = () => {
      render(
        <ThemeProvider theme={theme}>
          <Comp />
        </ThemeProvider>
      )
    }
    renderComp()
    const initialCSS = expectCSSMatches(`.a { color: ${theme.color}; }`)
    // Change the theme
    theme = newTheme
    renderComp()
    expectCSSMatches(`${initialCSS}.b { color: ${newTheme.color}; }`)
  })
})

describe('jsdom', () => {
  jsdom()

  beforeEach(() => {
    styled = resetStyled()
  })

  it('should properly render with the same theme from default props on re-render', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      }
    }
    const wrapper = mount(
      <Comp1 />
    )
    expectCSSMatches(`.a { color: purple; }`)

    wrapper.update();
    expectCSSMatches(`.a { color: purple; }`)
  })

  it('should properly update style if theme is changed', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      }
    }
    const wrapper = mount(
      <Comp1 />
    )
    expectCSSMatches(`.a { color: purple; }`)

    wrapper.setProps({ theme: { color: 'pink' } })
    expectCSSMatches(`.a { color: purple; }.b { color: pink; }`)
  })
})
<commit_msg>Rename test suite for jsdom theming tests<commit_after>// @flow
import jsdom from 'mocha-jsdom';
import React from 'react'
import { mount, render } from 'enzyme'

import { resetStyled, expectCSSMatches } from './utils'
import ThemeProvider from '../models/ThemeProvider'

let styled

describe('theming', () => {
  beforeEach(() => {
    styled = resetStyled()
  })

  it('should inject props.theme into a styled component', () => {
    const Comp = styled.div`
      color: ${props => props.theme.color};
    `
    const theme = { color: 'black' }
    render(
      <ThemeProvider theme={theme}>
        <Comp />
      </ThemeProvider>
    )
    expectCSSMatches(`.a { color: ${theme.color}; }`)
  })

  it('should inject props.theme into a styled component multiple levels deep', () => {
    const Comp = styled.div`
      color: ${props => props.theme.color};
    `
    const theme = { color: 'black' }
    render(
      <ThemeProvider theme={theme}>

            <Comp />

      </ThemeProvider>
    )
    expectCSSMatches(`.a { color: ${theme.color}; }`)
  })

  it('should properly allow a component to fallback to its default props when a theme is not provided', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.test.color};
    `

    Comp1.defaultProps = {
      theme: {
        test: {
          color: "purple"
        }
      }
    }
    render(

        <Comp1 />

    )
    expectCSSMatches(`.a { color: purple; }`)
  })

  it('should properly set the theme with an empty object when no teme is provided and no defaults are set', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `
    render(

        <Comp1 />

    )
    expectCSSMatches(`.a { color: ; }`)
  })

  it('should only inject props.theme into styled components within its child component tree', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `
    const Comp2 = styled.div`
      background: ${props => props.theme.color};
    `

    const theme = { color: 'black' }
    render(

        <ThemeProvider theme={theme}>

            <Comp1 />

        </ThemeProvider>
        <Comp2 />

    )
    expectCSSMatches(`.a { color: ${theme.color}; } .b { background: ; }`)
  })

  it('should inject props.theme into all styled components within the child component tree', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `
    const Comp2 = styled.div`
      background: ${props => props.theme.color};
    `
    const theme = { color: 'black' }
    render(
      <ThemeProvider theme={theme}>

            <Comp1 />

          <Comp2 />

      </ThemeProvider>
    )
    expectCSSMatches(`.a { color: ${theme.color}; } .b { background: ${theme.color}; }`)
  })

  it('should inject new CSS when the theme changes', () => {
    const Comp = styled.div`
      color: ${props => props.theme.color};
    `
    const originalTheme = { color: 'black' }
    const newTheme = { color: 'blue' }
    let theme = originalTheme
    // Force render the component
    const renderComp = () => {
      render(
        <ThemeProvider theme={theme}>
          <Comp />
        </ThemeProvider>
      )
    }
    renderComp()
    const initialCSS = expectCSSMatches(`.a { color: ${theme.color}; }`)
    // Change the theme
    theme = newTheme
    renderComp()
    expectCSSMatches(`${initialCSS}.b { color: ${newTheme.color}; }`)
  })
})

describe('theming (jsdom)', () => {
  jsdom()

  beforeEach(() => {
    styled = resetStyled()
  })

  it('should properly render with the same theme from default props on re-render', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      }
    }
    const wrapper = mount(
      <Comp1 />
    )
    expectCSSMatches(`.a { color: purple; }`)

    wrapper.update();
    expectCSSMatches(`.a { color: purple; }`)
  })

  it('should properly update style if theme is changed', () => {
    const Comp1 = styled.div`
      color: ${props => props.theme.color};
    `

    Comp1.defaultProps = {
      theme: {
        color: "purple"
      }
    }
    const wrapper = mount(
      <Comp1 />
    )
    expectCSSMatches(`.a { color: purple; }`)

    wrapper.setProps({ theme: { color: 'pink' } })
    expectCSSMatches(`.a { color: purple; }.b { color: pink; }`)
  })
})
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var cfg                 = require('nconf'),
        when                = require('when'),
        _                   = require('underscore'),
        url                 = require('url'),
        provider            = require('../../providers').configProvider,
        debug               = require('debug')('panda:api:settings'),
        processors          = {},
        propertyMap         = {},
        allowedReadSettings = ['app:postUrl', 'app:pageUrl'];

    propertyMap = {
        title:'app:title',
        description:'app:description',
        postsPerPage:'app:postsPerPage',
        url: 'url'
    };

    processors.host = function (properties, name, value) {
        properties.url = url.format({ host:value, protocol:'http' });
    };

    module.exports.index = function (req, res) {
        debug('reading basic settings');

        var urlCfg      = url.parse(cfg.get('url')),
            settings    = {
                host:           urlCfg.host,
                title:          cfg.get(propertyMap.title),
                description:    cfg.get(propertyMap.description),
                postsPerPage:   cfg.get(propertyMap.postsPerPage)
            };

        res.json(settings);
    };

    module.exports.show = function (req, res) {
        debug('reading configuration value %j', req.param.setting);

        return (req.setting) ? res.json({ key: req.params.setting, value: req.setting }) : res.send(404);
    };

    module.exports.load = function (id, fn) {
        if (_.contains(allowedReadSettings, id)) {
            fn(null, cfg.get(id));
        } else {
            fn();
        }
    };

    module.exports.create = function (req, res) {
        var promises = [];

        // Properties pre-processing
        if (_.size(processors)) {
            _.each(req.body, function (value, property) {
                if (property in processors) {
                    processors[property](req.body, property, value);
                }
            });
        }

        _.each(req.body, function (value, property) {

            if (property in propertyMap && cfg.get(propertyMap[property]) !== value) {

                debug('updating setting value %j : %j', propertyMap[property], value);

                promises.push(
                    provider.saveConfig(propertyMap[property], value)
                        .then(cfg.set.bind(cfg, propertyMap[property], value))
                );
            }
        });

        when.all(promises)
            .done(
                module.exports.index.bind(null, req, res),
                res.send.bind(res, 500)
            );
    };

}());<commit_msg>Configuration change notification<commit_after>(function () {
    'use strict';

    var cfg                 = require('nconf'),
        when                = require('when'),
        _                   = require('underscore'),
        url                 = require('url'),
        provider            = require('../../providers').configProvider,
        debug               = require('debug')('panda:api:settings'),
        processors          = {},
        propertyMap         = {},
        allowedReadSettings = ['app:postUrl', 'app:pageUrl'];

    propertyMap = {
        title:'app:title',
        description:'app:description',
        postsPerPage:'app:postsPerPage',
        url: 'url'
    };

    processors.host = function (properties, name, value) {
        properties.url = url.format({ host:value, protocol:'http' });
    };

    module.exports.index = function (req, res) {
        debug('reading basic settings');

        var urlCfg      = url.parse(cfg.get('url')),
            settings    = {
                host:           urlCfg.host,
                title:          cfg.get(propertyMap.title),
                description:    cfg.get(propertyMap.description),
                postsPerPage:   cfg.get(propertyMap.postsPerPage)
            };

        res.json(settings);
    };

    module.exports.show = function (req, res) {
        debug('reading configuration value %j', req.param.setting);

        return (req.setting) ? res.json({ key: req.params.setting, value: req.setting }) : res.send(404);
    };

    module.exports.load = function (id, fn) {
        if (_.contains(allowedReadSettings, id)) {
            fn(null, cfg.get(id));
        } else {
            fn();
        }
    };

    module.exports.create = function (req, res) {
        var promises = [];

        // Properties pre-processing
        if (_.size(processors)) {
            _.each(req.body, function (value, property) {
                if (property in processors) {
                    processors[property](req.body, property, value);
                }
            });
        }

        _.each(req.body, function (value, property) {

            if (property in propertyMap && cfg.get(propertyMap[property]) !== value) {

                debug('updating setting value %j : %j', propertyMap[property], value);

                promises.push(
                    provider.saveConfig(propertyMap[property], value)
                        .then(function () {
                            cfg.set(propertyMap[property], value);
                            cfg.notify('set:' + propertyMap[property]);
                        })
                );
            }
        });

        when.all(promises)
            .done(
                module.exports.index.bind(null, req, res),
                res.send.bind(res, 500)
            );
    };

}());<|endoftext|>


<commit_before>(function(){
    webix.ui({
        rows:[
            getViewHeader(),
            { cols:[
                 { type:"clean" },
                 { width:300, type:"clean", rows:[
                    { view:"template", type:"line", height:50 },
                    { view:"template", type:"line" }
                 ]},
                 { width:700, rows:[
                       { view:"template", type:"line", height:50 },
                       { view:"scrollview", scroll:"y",
                              body:{
                                  rows:[
                                      { template:"Scroll down for the next verse", height:30, type:"clean" },
                                      { template:"Scroll down for the next verse", height:30, type:"clean" },
                                      { template:"Scroll down for the next verse", height:30, type:"clean" },
                                  ]
                              } //end of scrollview body
                          },
                       { type:"clean", rows:[
                            { type:"clean", height:70, cols:[
                                { type:"clean", width:70 },
                                { view:"textarea", placeholder:"Write a message...", height:70 },
                                { type:"clean", width:70 }
                            ]},
                            { type:"clean", height:35, cols:[
                                { type:"clean", width:70 },
                                { view:"button", value:"Send", inputWidth:100 }
                            ]},
                       ]}]
                 },
                 { type:"clean" }
            ]},
            { type:"clean", height:50 }
        ]
    });
})();<commit_msg>sample: shaping layout<commit_after>(function(){
    webix.ui({ type:"clean",
        rows:[
            getViewHeader(),
            { type:"space", margin:1, padding:1, cols:[
                 { type:"clean" },
                 { width:300, type:"clean", rows:[
                    { type:"clean", height:40, cols:[
                        { view:"search", placeholder:"Search..." },
                        { view:"button", id:"chat_menu_btn", type:"icon", icon:"mail", width:50, onContext:{} }
                    ]},
                    { view:"template", type:"line" }
                 ]},
                 { width:700, rows:[
                       { view:"template", type:"line", height:50 },
                       { view:"scrollview", scroll:"y",
                              body:{
                                  rows:[
                                      { template:"Scroll down for the next verse", height:30, type:"clean" },
                                      { template:"Scroll down for the next verse", height:30, type:"clean" },
                                      { template:"Scroll down for the next verse", height:30, type:"clean" },
                                  ]
                              } //end of scrollview body
                          },
                       { type:"clean", rows:[
                            { type:"clean", height:70, cols:[
                                { type:"clean", width:70 },
                                { view:"textarea", placeholder:"Write a message...", height:70 },
                                { type:"clean", width:70 }
                            ]},
                            { type:"clean", height:35, cols:[
                                { type:"clean", width:70 },
                                { view:"button", value:"Send", inputWidth:100 }
                            ]},
                       ]}]
                 },
                 { type:"clean" }
            ]},
            { type:"clean", height:50 }
        ]
    });

    webix.ui({
        view:"contextmenu",
        id:"chat_contextmenu",
        data: [{ value:"New dialog" }]
    });

    $$('chat_contextmenu').attachTo($$('chat_menu_btn').$view);
})();<|endoftext|>


<commit_before>var scrollingExample = {
    box: {
        id: "clip",
        className: "clip",
        children: {
            id: "image",
            className: "image"
        }
    },
    constraints: [
        "clip.left == 0",
        "clip.top == 0",
        "clip.right == 300",
        "clip.bottom == 300",
        // Specify the bounds of the image and hint its position.
        "image.right == image.left + 800 !strong",
        "image.bottom == image.top + 800 !strong",
        "image.left == 0 !weak",
        "image.top == 0 !weak"
    ],
    motionConstraints: [
        // Ensure that the image stays within the clip with springs.
        // XXX: We can't yet express motion constraints relative to other linear variables.
        [ "image.left", "<=", 0 ],//"clip.left" ],
        [ "image.top", "<=", 0 ],//"clip.top" ],
        [ "image.bottom", ">=", 300],//"clip.bottom" ],
        [ "image.right", ">=", 300]//"clip.right" ],
    ],
    manipulators: [
        { box: "clip", x: "image.left", y: "image.top" }
    ]
}

Slalom.Serialization.assemble(scrollingExample, document.body);
<commit_msg>Improve commentary for 2d scrolling example.<commit_after>var scrollingExample = {
    // Create two nested boxes. The outer box is a clip, and the inner box is an image to
    // pan around.
    box: {
        id: "clip",
        className: "clip",
        children: {
            id: "image",
            className: "image"
        }
    },
    constraints: [
        // The clip is going to be 300x300.
        "clip.left == 0",
        "clip.top == 0",
        "clip.right == 300",
        "clip.bottom == 300",
        // Specify the bounds of the image and hint its position; the image is 800x800.
        // We don't really need to specify the constraint strengths here, but it helps
        // to make clearer which constraints we expect to be violated.
        "image.right == image.left + 800 !strong",
        "image.bottom == image.top + 800 !strong",
        "image.left == 0 !weak",
        "image.top == 0 !weak"
    ],
    motionConstraints: [
        // Ensure that the image stays within the clip with springs.
        // XXX: We can't yet express motion constraints relative to other linear variables; would rather use clip.right instead of "300" here.
        [ "image.left", "<=", 0 ],
        [ "image.top", "<=", 0 ],
        [ "image.bottom", ">=", 300],
        [ "image.right", ">=", 300]
    ],
    manipulators: [
        // Create a manipulator that listens for events on the box "clip" and manipulates
        // "image.left" and "image.top" for the x and y components of a pan.
        { box: "clip", x: "image.left", y: "image.top" }
    ]
}

Slalom.Serialization.assemble(scrollingExample, document.body);
<|endoftext|>


<commit_before>var ZipEntry = require("./zipEntry"),
    Headers = require("./headers"),
    Utils = require("./util");

module.exports = function(/*String|Buffer*/input, /*Number*/inputType) {
    var entryList = [],
        entryTable = {},
        _comment = new Buffer(0),
        filename = "",
        fs = require("fs"),
        inBuffer = null,
        mainHeader = new Headers.MainHeader();

    if (inputType == Utils.Constants.FILE) {
        // is a filename
        filename = input;
        inBuffer = fs.readFileSync(filename);
        readMainHeader();
    } else if (inputType == Utils.Constants.BUFFER) {
        // is a memory buffer
        inBuffer = input;
        readMainHeader();
    } else {
        // none. is a new file
    }

    function readEntries() {
        entryTable = {};
        entryList = new Array(mainHeader.diskEntries);  // total number of entries
        var index = mainHeader.offset;  // offset of first CEN header
        for(var i = 0; i < entryList.length; i++) {

            var tmp = index,
                entry = new ZipEntry(inBuffer);
            entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);

            entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);

            if (entry.header.extraLength) {
                entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength);
            }

            if (entry.header.commentLength)
                entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);

            index += entry.header.entryHeaderSize;

            entryList[i] = entry;
            entryTable[entry.entryName] = entry;
        }
    }

    function readMainHeader() {
        var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size
            n = Math.max(0, i - 0xFFFF), // 0xFFFF is the max zip file comment length
            endOffset = 0; // Start offset of the END header

        for (i; i >= n; i--) {
            if (inBuffer[i] != 0x50) continue; // quick check that the byte is 'P'
            if (inBuffer.readUInt32LE(i) == Utils.Constants.ENDSIG) { // "PK\005\006"
                endOffset = i;
                break;
            }
        }
        if (!endOffset)
            throw Utils.Errors.INVALID_FORMAT;

        mainHeader.loadFromBinary(inBuffer.slice(endOffset, endOffset + Utils.Constants.ENDHDR));
        if (mainHeader.commentLength) {
            _comment = inBuffer.slice(endOffset + Utils.Constants.ENDHDR);
        }
        readEntries();
    }

    return {
        /**
         * Returns an array of ZipEntry objects existent in the current opened archive
         * @return Array
         */
        get entries () {
            return entryList;
        },

        /**
         * Archive comment
         * @return {String}
         */
        get comment () { return _comment.toString(); },
        set comment(val) {
            mainHeader.commentLength = val.length;
            _comment = val;
        },

        /**
         * Returns a reference to the entry with the given name or null if entry is inexistent
         *
         * @param entryName
         * @return ZipEntry
         */
        getEntry : function(/*String*/entryName) {
            return entryTable[entryName] || null;
        },

        /**
         * Adds the given entry to the entry list
         *
         * @param entry
         */
        setEntry : function(/*ZipEntry*/entry) {
            entryList.push(entry);
            entryTable[entry.entryName] = entry;
            mainHeader.totalEntries = entryList.length;
        },

        /**
         * Removes the entry with the given name from the entry list.
         *
         * If the entry is a directory, then all nested files and directories will be removed
         * @param entryName
         */
        deleteEntry : function(/*String*/entryName) {
            var entry = entryTable[entryName];
            if (entry && entry.isDirectory) {
                var _self = this;
                this.getEntryChildren(entry).forEach(function(child) {
                    if (child.entryName != entryName) {
                        _self.deleteEntry(child.entryName)
                    }
                })
            }
            entryList.splice(entryList.indexOf(entry), 1);
            delete(entryTable[entryName]);
            mainHeader.totalEntries = entryList.length;
        },

        /**
         *  Iterates and returns all nested files and directories of the given entry
         *
         * @param entry
         * @return Array
         */
        getEntryChildren : function(/*ZipEntry*/entry) {
            if (entry.isDirectory) {
                var list = [],
                    name = entry.entryName,
                    len = name.length;

                entryList.forEach(function(zipEntry) {
                    if (zipEntry.entryName.substr(0, len) == name) {
                        list.push(zipEntry);
                    }
                });
                return list;
            }
            return []
        },

        /**
         * Returns the zip file
         *
         * @return Buffer
         */
        compressToBuffer : function() {
            if (entryList.length > 1) {
                entryList.sort(function(a, b) {
                    var nameA = a.entryName.toLowerCase();
                    var nameB = b.entryName.toLowerCase();
                    if (nameA < nameB) {return -1}
                    if (nameA > nameB) {return 1}
                    return 0;
                });
            }

            var totalSize = 0,
                dataBlock = [],
                entryHeaders = [],
                dindex = 0;

            mainHeader.size = 0;
            mainHeader.offset = 0;

            entryList.forEach(function(entry) {
                entry.header.offset = dindex;

                // compress data and set local and entry header accordingly. Reason why is called first
                var compressedData = entry.getCompressedData();
                // data header
                var dataHeader = entry.header.dataHeaderToBinary();
                var postHeader = new Buffer(entry.entryName + entry.extra.toString());
                var dataLength = dataHeader.length + postHeader.length + compressedData.length;

                dindex += dataLength;

                dataBlock.push(dataHeader);
                dataBlock.push(postHeader);
                dataBlock.push(compressedData);

                var entryHeader = entry.packHeader();
                entryHeaders.push(entryHeader);
                mainHeader.size += entryHeader.length;
                totalSize += (dataLength + entryHeader.length);
            });

            totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
            // point to end of data and begining of central directory first record
            mainHeader.offset = dindex;

            dindex = 0;
            var outBuffer = new Buffer(totalSize);
            dataBlock.forEach(function(content) {
                content.copy(outBuffer, dindex); // write data blocks
                dindex += content.length;
            });
            entryHeaders.forEach(function(content) {
                content.copy(outBuffer, dindex); // write central directory entries
                dindex += content.length;
            });

            var mh = mainHeader.toBinary();
            if (_comment) {
                _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
            }

            mh.copy(outBuffer, dindex); // write main header

            return outBuffer
        },

        toAsyncBuffer : function(/*Function*/onSuccess,/*Function*/onFail,/*Function*/onItemStart,/*Function*/onItemEnd) {
            if (entryList.length > 1) {
                entryList.sort(function(a, b) {
                    var nameA = a.entryName.toLowerCase();
                    var nameB = b.entryName.toLowerCase();
                    if (nameA > nameB) {return -1}
                    if (nameA < nameB) {return 1}
                    return 0;
                });
            }

            var totalSize = 0,
                dataBlock = [],
                entryHeaders = [],
                dindex = 0;

            mainHeader.size = 0;
            mainHeader.offset = 0;

            var compress=function(entryList){
                var self=arguments.callee;
                var entry;
                if(entryList.length){
                    var entry=entryList.pop();
                    var name=entry.entryName + entry.extra.toString();
                    if(onItemStart)onItemStart(name);
                    entry.getCompressedDataAsync(function(compressedData){
                        if(onItemEnd)onItemEnd(name);

                        entry.header.offset = dindex;
                        // data header
                        var dataHeader = entry.header.dataHeaderToBinary();
                        var postHeader = new Buffer(name);
                        var dataLength = dataHeader.length + postHeader.length + compressedData.length;

                        dindex += dataLength;

                        dataBlock.push(dataHeader);
                        dataBlock.push(postHeader);
                        dataBlock.push(compressedData);

                        var entryHeader = entry.packHeader();
                        entryHeaders.push(entryHeader);
                        mainHeader.size += entryHeader.length;
                        totalSize += (dataLength + entryHeader.length);

                        if(entryList.length){
                            self(entryList);
                        }else{

                            totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
                            // point to end of data and begining of central directory first record
                            mainHeader.offset = dindex;

                            dindex = 0;
                            var outBuffer = new Buffer(totalSize);
                            dataBlock.forEach(function(content) {
                                content.copy(outBuffer, dindex); // write data blocks
                                dindex += content.length;
                            });
                            entryHeaders.forEach(function(content) {
                                content.copy(outBuffer, dindex); // write central directory entries
                                dindex += content.length;
                            });

                            var mh = mainHeader.toBinary();
                            if (_comment) {
                                _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
                            }

                            mh.copy(outBuffer, dindex); // write main header

                            onSuccess(outBuffer);
                        }
                    });
                }
            };

            compress(entryList);
        }
    }
};
<commit_msg>Fixed a bug where empty ZIP files were being treated as invalid.<commit_after>var ZipEntry = require("./zipEntry"),
    Headers = require("./headers"),
    Utils = require("./util");

module.exports = function(/*String|Buffer*/input, /*Number*/inputType) {
    var entryList = [],
        entryTable = {},
        _comment = new Buffer(0),
        filename = "",
        fs = require("fs"),
        inBuffer = null,
        mainHeader = new Headers.MainHeader();

    if (inputType == Utils.Constants.FILE) {
        // is a filename
        filename = input;
        inBuffer = fs.readFileSync(filename);
        readMainHeader();
    } else if (inputType == Utils.Constants.BUFFER) {
        // is a memory buffer
        inBuffer = input;
        readMainHeader();
    } else {
        // none. is a new file
    }

    function readEntries() {
        entryTable = {};
        entryList = new Array(mainHeader.diskEntries);  // total number of entries
        var index = mainHeader.offset;  // offset of first CEN header
        for(var i = 0; i < entryList.length; i++) {

            var tmp = index,
                entry = new ZipEntry(inBuffer);
            entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);

            entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);

            if (entry.header.extraLength) {
                entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength);
            }

            if (entry.header.commentLength)
                entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);

            index += entry.header.entryHeaderSize;

            entryList[i] = entry;
            entryTable[entry.entryName] = entry;
        }
    }

    function readMainHeader() {
        var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size
            n = Math.max(0, i - 0xFFFF), // 0xFFFF is the max zip file comment length
            endOffset = -1; // Start offset of the END header

        for (i; i >= n; i--) {
            if (inBuffer[i] != 0x50) continue; // quick check that the byte is 'P'
            if (inBuffer.readUInt32LE(i) == Utils.Constants.ENDSIG) { // "PK\005\006"
                endOffset = i;
                break;
            }
        }
        if (!~endOffset)
            throw Utils.Errors.INVALID_FORMAT;

        mainHeader.loadFromBinary(inBuffer.slice(endOffset, endOffset + Utils.Constants.ENDHDR));
        if (mainHeader.commentLength) {
            _comment = inBuffer.slice(endOffset + Utils.Constants.ENDHDR);
        }
        readEntries();
    }

    return {
        /**
         * Returns an array of ZipEntry objects existent in the current opened archive
         * @return Array
         */
        get entries () {
            return entryList;
        },

        /**
         * Archive comment
         * @return {String}
         */
        get comment () { return _comment.toString(); },
        set comment(val) {
            mainHeader.commentLength = val.length;
            _comment = val;
        },

        /**
         * Returns a reference to the entry with the given name or null if entry is inexistent
         *
         * @param entryName
         * @return ZipEntry
         */
        getEntry : function(/*String*/entryName) {
            return entryTable[entryName] || null;
        },

        /**
         * Adds the given entry to the entry list
         *
         * @param entry
         */
        setEntry : function(/*ZipEntry*/entry) {
            entryList.push(entry);
            entryTable[entry.entryName] = entry;
            mainHeader.totalEntries = entryList.length;
        },

        /**
         * Removes the entry with the given name from the entry list.
         *
         * If the entry is a directory, then all nested files and directories will be removed
         * @param entryName
         */
        deleteEntry : function(/*String*/entryName) {
            var entry = entryTable[entryName];
            if (entry && entry.isDirectory) {
                var _self = this;
                this.getEntryChildren(entry).forEach(function(child) {
                    if (child.entryName != entryName) {
                        _self.deleteEntry(child.entryName)
                    }
                })
            }
            entryList.splice(entryList.indexOf(entry), 1);
            delete(entryTable[entryName]);
            mainHeader.totalEntries = entryList.length;
        },

        /**
         *  Iterates and returns all nested files and directories of the given entry
         *
         * @param entry
         * @return Array
         */
        getEntryChildren : function(/*ZipEntry*/entry) {
            if (entry.isDirectory) {
                var list = [],
                    name = entry.entryName,
                    len = name.length;

                entryList.forEach(function(zipEntry) {
                    if (zipEntry.entryName.substr(0, len) == name) {
                        list.push(zipEntry);
                    }
                });
                return list;
            }
            return []
        },

        /**
         * Returns the zip file
         *
         * @return Buffer
         */
        compressToBuffer : function() {
            if (entryList.length > 1) {
                entryList.sort(function(a, b) {
                    var nameA = a.entryName.toLowerCase();
                    var nameB = b.entryName.toLowerCase();
                    if (nameA < nameB) {return -1}
                    if (nameA > nameB) {return 1}
                    return 0;
                });
            }

            var totalSize = 0,
                dataBlock = [],
                entryHeaders = [],
                dindex = 0;

            mainHeader.size = 0;
            mainHeader.offset = 0;

            entryList.forEach(function(entry) {
                entry.header.offset = dindex;

                // compress data and set local and entry header accordingly. Reason why is called first
                var compressedData = entry.getCompressedData();
                // data header
                var dataHeader = entry.header.dataHeaderToBinary();
                var postHeader = new Buffer(entry.entryName + entry.extra.toString());
                var dataLength = dataHeader.length + postHeader.length + compressedData.length;

                dindex += dataLength;

                dataBlock.push(dataHeader);
                dataBlock.push(postHeader);
                dataBlock.push(compressedData);

                var entryHeader = entry.packHeader();
                entryHeaders.push(entryHeader);
                mainHeader.size += entryHeader.length;
                totalSize += (dataLength + entryHeader.length);
            });

            totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
            // point to end of data and begining of central directory first record
            mainHeader.offset = dindex;

            dindex = 0;
            var outBuffer = new Buffer(totalSize);
            dataBlock.forEach(function(content) {
                content.copy(outBuffer, dindex); // write data blocks
                dindex += content.length;
            });
            entryHeaders.forEach(function(content) {
                content.copy(outBuffer, dindex); // write central directory entries
                dindex += content.length;
            });

            var mh = mainHeader.toBinary();
            if (_comment) {
                _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
            }

            mh.copy(outBuffer, dindex); // write main header

            return outBuffer
        },

        toAsyncBuffer : function(/*Function*/onSuccess,/*Function*/onFail,/*Function*/onItemStart,/*Function*/onItemEnd) {
            if (entryList.length > 1) {
                entryList.sort(function(a, b) {
                    var nameA = a.entryName.toLowerCase();
                    var nameB = b.entryName.toLowerCase();
                    if (nameA > nameB) {return -1}
                    if (nameA < nameB) {return 1}
                    return 0;
                });
            }

            var totalSize = 0,
                dataBlock = [],
                entryHeaders = [],
                dindex = 0;

            mainHeader.size = 0;
            mainHeader.offset = 0;

            var compress=function(entryList){
                var self=arguments.callee;
                var entry;
                if(entryList.length){
                    var entry=entryList.pop();
                    var name=entry.entryName + entry.extra.toString();
                    if(onItemStart)onItemStart(name);
                    entry.getCompressedDataAsync(function(compressedData){
                        if(onItemEnd)onItemEnd(name);

                        entry.header.offset = dindex;
                        // data header
                        var dataHeader = entry.header.dataHeaderToBinary();
                        var postHeader = new Buffer(name);
                        var dataLength = dataHeader.length + postHeader.length + compressedData.length;

                        dindex += dataLength;

                        dataBlock.push(dataHeader);
                        dataBlock.push(postHeader);
                        dataBlock.push(compressedData);

                        var entryHeader = entry.packHeader();
                        entryHeaders.push(entryHeader);
                        mainHeader.size += entryHeader.length;
                        totalSize += (dataLength + entryHeader.length);

                        if(entryList.length){
                            self(entryList);
                        }else{

                            totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
                            // point to end of data and begining of central directory first record
                            mainHeader.offset = dindex;

                            dindex = 0;
                            var outBuffer = new Buffer(totalSize);
                            dataBlock.forEach(function(content) {
                                content.copy(outBuffer, dindex); // write data blocks
                                dindex += content.length;
                            });
                            entryHeaders.forEach(function(content) {
                                content.copy(outBuffer, dindex); // write central directory entries
                                dindex += content.length;
                            });

                            var mh = mainHeader.toBinary();
                            if (_comment) {
                                _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
                            }

                            mh.copy(outBuffer, dindex); // write main header

                            onSuccess(outBuffer);
                        }
                    });
                }
            };

            compress(entryList);
        }
    }
};
<|endoftext|>


<commit_before>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015 Clinton Health Access Initiative (CHAI)/MoHCDGEC Tanzania.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.   See the GNU Affero General Public License for more details.
 */

angular.module('vaccine-inventory', ['openlmis','ngGrid', 'ngTable','ui.bootstrap','angularCombine','ui.bootstrap.modal','ui.bootstrap.pagination'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
            when('/stock-adjustment', {controller:StockAdjustmentController, templateUrl:'partials/stock-adjustment.html',resolve:StockAdjustmentController.resolve}).
            when('/receive', {controller:ReceiveStockController, templateUrl:'partials/receive-stock.html',reloadOnSearch:false,resolve:ReceiveStockController.resolve}).
            when('/transfer-in', {controller:ReceiveStockController, templateUrl:'partials/receive-stock.html',reloadOnSearch:false,resolve:ReceiveStockController.resolve}).
            when('/mass-distribution', {controller:MassDistributionController, templateUrl:'partials/mass-distribution.html',reloadOnSearch:false,resolve:MassDistributionController.resolve}).
            when('/configuration', {controller:VaccineInventoryConfigurationController, templateUrl:'partials/configuration.html',reloadOnSearch:false,resolve:VaccineInventoryConfigurationController.resolve}).
            when('/vaccine-fimbaniorecasting', {controller:VaccineForecastingController, templateUrl:'partials/vaccine-forecast.html',reloadOnSearch:false,resolve:VaccineForecastingController.resolve}).
            when('/transfer-out', {controller:TransferOutController, templateUrl:'partials/transfer-out-partial.html',reloadOnSearch:false,resolve:TransferOutController.resolve}).
            when('/view-issue-voucher', {controller:ViewIssueVoucherController, templateUrl:'partials/view-issue-voucher.html',reloadOnSearch:false,resolve:ViewIssueVoucherController.resolve}).

            otherwise({redirectTo:'/public/pages/vaccine/dashboard/index.html#/dashboard'});
    }]).run(function ($rootScope, AuthorizationService) {

     }).config(function(angularCombineConfigProvider) {
        angularCombineConfigProvider.addConf(/filter-/, '/public/pages/reports/shared/filters.html');
    }).filter('positive', function() {
               return function(input) {
                   if (!input) {
                       return 0;
                   }

                   return Math.abs(input);
               };
    });<commit_msg>Fix forecasting link<commit_after>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015 Clinton Health Access Initiative (CHAI)/MoHCDGEC Tanzania.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.   See the GNU Affero General Public License for more details.
 */

angular.module('vaccine-inventory', ['openlmis','ngGrid', 'ngTable','ui.bootstrap','angularCombine','ui.bootstrap.modal','ui.bootstrap.pagination'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
            when('/stock-adjustment', {controller:StockAdjustmentController, templateUrl:'partials/stock-adjustment.html',resolve:StockAdjustmentController.resolve}).
            when('/receive', {controller:ReceiveStockController, templateUrl:'partials/receive-stock.html',reloadOnSearch:false,resolve:ReceiveStockController.resolve}).
            when('/transfer-in', {controller:ReceiveStockController, templateUrl:'partials/receive-stock.html',reloadOnSearch:false,resolve:ReceiveStockController.resolve}).
            when('/mass-distribution', {controller:MassDistributionController, templateUrl:'partials/mass-distribution.html',reloadOnSearch:false,resolve:MassDistributionController.resolve}).
            when('/configuration', {controller:VaccineInventoryConfigurationController, templateUrl:'partials/configuration.html',reloadOnSearch:false,resolve:VaccineInventoryConfigurationController.resolve}).
            when('/vaccine-forecasting', {controller:VaccineForecastingController, templateUrl:'partials/vaccine-forecast.html',reloadOnSearch:false,resolve:VaccineForecastingController.resolve}).
            when('/transfer-out', {controller:TransferOutController, templateUrl:'partials/transfer-out-partial.html',reloadOnSearch:false,resolve:TransferOutController.resolve}).
            when('/view-issue-voucher', {controller:ViewIssueVoucherController, templateUrl:'partials/view-issue-voucher.html',reloadOnSearch:false,resolve:ViewIssueVoucherController.resolve}).

            otherwise({redirectTo:'/public/pages/vaccine/dashboard/index.html#/dashboard'});
    }]).run(function ($rootScope, AuthorizationService) {

     }).config(function(angularCombineConfigProvider) {
        angularCombineConfigProvider.addConf(/filter-/, '/public/pages/reports/shared/filters.html');
    }).filter('positive', function() {
               return function(input) {
                   if (!input) {
                       return 0;
                   }

                   return Math.abs(input);
               };
    });<|endoftext|>


<commit_before>(function() {

  function userEntryDefaultFormatter(entry) {
    var markup = "";
    if (entry.displayIcon && entry.type) {
      if (entry.type == "USER_TYPE") {
        markup += "";
      } else if (entry.type == "GROUP_TYPE") {
        markup += "";
      }
    }
    markup += entry.displayLabel;
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  function docEntryDefaultFormatter(doc) {
    var markup = "

";
    markup += "
";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += "	";
    markup += doc.title;
    if (doc.warn_message) {
      markup += ""
    }
    if (doc.path) {
      markup += "" + doc.path + "";
    }
    markup += "

"
    return markup;
  }

  function dirEntryDefaultFormatter(entry) {
    var markup = entry.displayLabel;
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  function dirEntryDefaultFormatter(entry) {
    var markup = entry.displayLabel;
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  var userSelectionDefaultFormatter = userEntryDefaultFormatter;

  function docSelectionDefaultFormatter(doc) {
    var markup = "";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += getDocLinkElt(doc);
    if (doc.warn_message) {
      markup += ""
    }
    return markup;
  }

  var dirSelectionDefaultFormatter = dirEntryDefaultFormatter;

  function getOperationName(params) {
    var opName = params.operationId;
    if (typeof (opName) == 'undefined' || opName == '') {
      if (params.directoryName && params.directoryName.length > 0) {
        opName = 'Directory.SuggestEntries';
      } else {
        opName = 'Document.PageProvider';
      }
    }
    return opName;
  }

  function getDocLinkElt(doc) {
    if (doc.contextParameters) {
      var url = doc.contextParameters.documentURL;
      var markup = "" + doc.title + ""
      return markup;
    } else {
      return doc.title;
    }
  }

  function getUrlWithConversationId(url) {
    return url + "?conversationId=" + currentConversationId;
  }

  function configureOperationParameters(op, params, query) {
    var temp = {};
    jQuery.extend(temp, params);
    temp.lang = currentUserLang;
    if (params.operationId == 'Directory.SuggestEntries') {
      // build default operation for Directory
      temp.searchTerm = query.term;
    } else if (params.operationId == 'UserGroup.Suggestion') {
      temp.searchTerm = query.term;
      temp.searchType = params.userSuggestionSearchType;
    } else if (params.operationId == 'Document.PageProvider') {
      // build default operation for Document
      temp.searchTerm = query.term + "%";
      temp.query = params.query;
      temp.providerName = params.pageProviderName;
      temp.page = "0";
      temp.pageSize = "20";
    } else {
      // custom operation, pass at least the query term
      temp.searchTerm = query.term;
    }
    if (typeof currentConversationId != 'undefined') {
      // Give needed info to restore Seam context
      op.addParameter("id", getOperationName(params));
      op.addParameter("conversationId", currentConversationId);
      op.opts.automationParams.context = temp;
    } else {
      op.addParameters(temp);
    }
  }

  function fillResult(results, data, params) {
    if (typeof(data.length) != "undefined") {
      // default result parsing for Directory entries
      for (i = 0; i < data.length; i++) {
        var entry = data[i];
        results.push(entry);
      }
    } else if (typeof(data.entries) != "undefined") {
      // default result parsing for Documents
      for (i = 0; i < data.entries.length; i++) {
        var doc = data.entries[i];
        results.push(doc);
      }
    } else {
      alert("Error with suggestion widget");
    }
  }

  function getDefaultLabel(item) {
    if (item.displayLabel) {
      return item.displayLabel;
    } else {
      return item.title;
    }
  }

  function getDefaultId(item) {
    if (item.computedId) {
      return item.computedId;
    } else if (item.uid) {
      return item.uid;
    } else {
      return item.id;
    }
  }

  function initSelect2Widget(el) {
    // retrieve parameters from Html
    var elid = el.attr("id");
    var params = {};

    var paramId = (elid + "_params").split(":").join("\\:");
    var paramsHolder = jQuery("#" + paramId);
    params = JSON.parse(paramsHolder.val());

    var readonly = params.readonly == 'true';
    var required = params.required == 'true';

    var initId = (elid + "_init").split(":").join("\\:");
    var initHolder = jQuery("#" + initId);
    var initDoc = null;
    try {
      initDoc = JSON.parse(initHolder.val());
    } catch (err) {
      // console.log("Unable to parse initvalue", err, initHolder.val())
    }

    // set style on select
    el.css("width", params.width);

    // determine operation name
    var opName = getOperationName(params);

    // define automation params
    var automationParams = {
      "documentSchemas" : params.documentSchemas
    };

    if (params.repository) {
      automationParams.repository = params.repository;
    }

    // init Automation Operation
    var op = null;
    if (typeof currentConversationId != 'undefined') {
      // If Seam context is available, let's restore it
      op = jQuery().automation('Seam.RunOperation', automationParams);
    } else {
      op = jQuery().automation(opName, automationParams);
    }

    // detect if we need custom selection formatting
    var selectionFormatterFunction = null;
    if (params.selectionFormatter && params.selectionFormatter.length > 0) {
      selectionFormatterFunction = eval(params.selectionFormatter);
    }
    // detect if we need custom suggestion formatting
    var suggestionFormatterFunction = null;
    if (params.suggestionFormatter && params.suggestionFormatter.length > 0) {
      suggestionFormatterFunction = eval(params.suggestionFormatter);
    }

    // build select2 parameters
    var select2_params = {
      containerCssClass : params.containerCssClass,
      dropdownCssClass : params.dropdownCssClass,
      minimumInputLength : params.minChars,
      query : function(query) {

        configureOperationParameters(op, params, query);

        op.execute(function(data, textStatus, xhr) {
          var results = [];
          fillResult(results, data, params)
          query.callback({
            results : results
          });
        });
      }
    }

    // append custom selection formatter if needed
    if (selectionFormatterFunction != null) {
      select2_params.formatSelection = selectionFormatterFunction;
    } else {
      select2_params.formatSelection = function(doc) {
        if (select2_params.labelFieldName != null) {
          return doc.properties[select2_params.labelFieldName];
        } else {
          return getDefaultLabel(doc)
        }
      };
    }
    // append custom suggestion formatter if needed
    if (suggestionFormatterFunction != null) {
      select2_params.formatResult = suggestionFormatterFunction;
    } else {
      select2_params.formatResult = getDefaultLabel;
    }

    // append id formatter if needed
    if (params.idProperty && params.idProperty.length > 0) {
      select2_params.id = function(doc) {
        return doc.properties[params.idProperty];
      };
    } else if (params.idFunction) {
      select2_params.id = eval(params.idFunction);
    } else if (params.prefixed) {
      select2_params.id = function(item) {
        return item.prefixed_id;
      };
    } else {
      select2_params.id = getDefaultId;
    }

    if (initDoc != null) {
      select2_params.initSelection = function(element, callback) {
        callback(initDoc);
      };
    }

    if (params.multiple == 'true') {
      select2_params.maximumSelectionSize = params.maximumSelectionSize;
      select2_params.multiple = true;
    }

    if (params.placeholder && !readonly) {
      select2_params.placeholder = params.placeholder;
      select2_params.allowClear = !required;
    }

    // init select2
    el.select2(select2_params);

    // view or edit mode
    if (readonly) {
      el.select2("readonly", true);
    }

    if (!readonly) {

      // Make selected items sortable
      if (params.multiple == 'true' && params.orderable == 'true') {
        el.select2("container").find("ul.select2-choices").sortable({
          containment : 'parent',
          start : function() {
            el.select2("onSortStart");
          },
          update : function() {
            el.select2("onSortEnd");
          }
        });
      }

      // Handle onclick widget property
      el.on("select2-opening", function(e) {
        if (params.onclick) {
          eval(params.onclick);
        }
      });

      // trigger for safeEdit restore
      el.on("change", function(e) {
        if (e) {
          if (e.added) {
            var newValue;
            if (select2_params.multiple) {
              var newObj = JSON.parse(initHolder.val());
              newObj.push(e.added);
              var newValue = JSON.stringify(newObj);
            } else {
              newValue = JSON.stringify(e.added);
            }
            initHolder.val(newValue);
          }

          if (e.removed) {
            var removedId = select2_params.id(e.removed);
            if (select2_params.multiple) {
              var newValue = '';
              var tempObj = JSON.parse(initHolder.val());
              jQuery.each(tempObj, function(index, result) {
                if (result) {
                  if (select2_params.id(result) == removedId) {
                    tempObj.splice(index, 1);
                  }
                }
              });
              newValue = JSON.stringify(tempObj);
              initHolder.val(newValue);
            } else {
              if (initHolder.val() == removedId) {
                initHolder.val('');
              }
            }
          }
        }

        // ReRender any jsf component if needed.
        if (params.reRenderFunctionName) {
          window[params.reRenderFunctionName]();
        }

        // Handle onchange widget property
        if (params.onchange) {
          eval(params.onchange);
        }

      });
    }

    var $parentForm = jQuery(el).closest("form");
    if ($parentForm.hasClass("safeEditEnabled")) {
        // Register postRestore function for safeEdit
        jQuery(el).closest("form").registerPostRestoreCallBacks(function(data) {
          initSelect2Widget(jQuery(el));
        });
      }
  }

  window.initSelect2AjaxWidget = function initSelect2AjaxWidget(widgetId, index) {

    var selector = "input[type='hidden'][id$=";

    if (index != null && index.length > 0) {
      selector = selector + index + "\\:";
    }
    selector = selector + widgetId + "_select2]";

    jQuery(selector).each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });

  }

  window.initSelect2Widgets = function initSelect2Widgets() {
    jQuery("input[type='hidden'][id$=select2]").each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });
  }

})();
<commit_msg>NXP-13698: remove dupe dirEntryDefaultFormatter<commit_after>(function() {

  function userEntryDefaultFormatter(entry) {
    var markup = "";
    if (entry.displayIcon && entry.type) {
      if (entry.type == "USER_TYPE") {
        markup += "";
      } else if (entry.type == "GROUP_TYPE") {
        markup += "";
      }
    }
    markup += entry.displayLabel;
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  function docEntryDefaultFormatter(doc) {
    var markup = "

";
    markup += "
";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += "	";
    markup += doc.title;
    if (doc.warn_message) {
      markup += ""
    }
    if (doc.path) {
      markup += "" + doc.path + "";
    }
    markup += "

"
    return markup;
  }

  function dirEntryDefaultFormatter(entry) {
    var markup = entry.displayLabel;
    if (entry.warn_message) {
      markup += ""
    }
    return markup;
  }

  var userSelectionDefaultFormatter = userEntryDefaultFormatter;

  function docSelectionDefaultFormatter(doc) {
    var markup = "";
    if (doc.properties && doc.properties['common:icon']) {
      markup += ""
    }
    markup += getDocLinkElt(doc);
    if (doc.warn_message) {
      markup += ""
    }
    return markup;
  }

  var dirSelectionDefaultFormatter = dirEntryDefaultFormatter;

  function getOperationName(params) {
    var opName = params.operationId;
    if (typeof (opName) == 'undefined' || opName == '') {
      if (params.directoryName && params.directoryName.length > 0) {
        opName = 'Directory.SuggestEntries';
      } else {
        opName = 'Document.PageProvider';
      }
    }
    return opName;
  }

  function getDocLinkElt(doc) {
    if (doc.contextParameters) {
      var url = doc.contextParameters.documentURL;
      var markup = "" + doc.title + ""
      return markup;
    } else {
      return doc.title;
    }
  }

  function getUrlWithConversationId(url) {
    return url + "?conversationId=" + currentConversationId;
  }

  function configureOperationParameters(op, params, query) {
    var temp = {};
    jQuery.extend(temp, params);
    temp.lang = currentUserLang;
    if (params.operationId == 'Directory.SuggestEntries') {
      // build default operation for Directory
      temp.searchTerm = query.term;
    } else if (params.operationId == 'UserGroup.Suggestion') {
      temp.searchTerm = query.term;
      temp.searchType = params.userSuggestionSearchType;
    } else if (params.operationId == 'Document.PageProvider') {
      // build default operation for Document
      temp.searchTerm = query.term + "%";
      temp.query = params.query;
      temp.providerName = params.pageProviderName;
      temp.page = "0";
      temp.pageSize = "20";
    } else {
      // custom operation, pass at least the query term
      temp.searchTerm = query.term;
    }
    if (typeof currentConversationId != 'undefined') {
      // Give needed info to restore Seam context
      op.addParameter("id", getOperationName(params));
      op.addParameter("conversationId", currentConversationId);
      op.opts.automationParams.context = temp;
    } else {
      op.addParameters(temp);
    }
  }

  function fillResult(results, data, params) {
    if (typeof(data.length) != "undefined") {
      // default result parsing for Directory entries
      for (i = 0; i < data.length; i++) {
        var entry = data[i];
        results.push(entry);
      }
    } else if (typeof(data.entries) != "undefined") {
      // default result parsing for Documents
      for (i = 0; i < data.entries.length; i++) {
        var doc = data.entries[i];
        results.push(doc);
      }
    } else {
      alert("Error with suggestion widget");
    }
  }

  function getDefaultLabel(item) {
    if (item.displayLabel) {
      return item.displayLabel;
    } else {
      return item.title;
    }
  }

  function getDefaultId(item) {
    if (item.computedId) {
      return item.computedId;
    } else if (item.uid) {
      return item.uid;
    } else {
      return item.id;
    }
  }

  function initSelect2Widget(el) {
    // retrieve parameters from Html
    var elid = el.attr("id");
    var params = {};

    var paramId = (elid + "_params").split(":").join("\\:");
    var paramsHolder = jQuery("#" + paramId);
    params = JSON.parse(paramsHolder.val());

    var readonly = params.readonly == 'true';
    var required = params.required == 'true';

    var initId = (elid + "_init").split(":").join("\\:");
    var initHolder = jQuery("#" + initId);
    var initDoc = null;
    try {
      initDoc = JSON.parse(initHolder.val());
    } catch (err) {
      // console.log("Unable to parse initvalue", err, initHolder.val())
    }

    // set style on select
    el.css("width", params.width);

    // determine operation name
    var opName = getOperationName(params);

    // define automation params
    var automationParams = {
      "documentSchemas" : params.documentSchemas
    };

    if (params.repository) {
      automationParams.repository = params.repository;
    }

    // init Automation Operation
    var op = null;
    if (typeof currentConversationId != 'undefined') {
      // If Seam context is available, let's restore it
      op = jQuery().automation('Seam.RunOperation', automationParams);
    } else {
      op = jQuery().automation(opName, automationParams);
    }

    // detect if we need custom selection formatting
    var selectionFormatterFunction = null;
    if (params.selectionFormatter && params.selectionFormatter.length > 0) {
      selectionFormatterFunction = eval(params.selectionFormatter);
    }
    // detect if we need custom suggestion formatting
    var suggestionFormatterFunction = null;
    if (params.suggestionFormatter && params.suggestionFormatter.length > 0) {
      suggestionFormatterFunction = eval(params.suggestionFormatter);
    }

    // build select2 parameters
    var select2_params = {
      containerCssClass : params.containerCssClass,
      dropdownCssClass : params.dropdownCssClass,
      minimumInputLength : params.minChars,
      query : function(query) {

        configureOperationParameters(op, params, query);

        op.execute(function(data, textStatus, xhr) {
          var results = [];
          fillResult(results, data, params)
          query.callback({
            results : results
          });
        });
      }
    }

    // append custom selection formatter if needed
    if (selectionFormatterFunction != null) {
      select2_params.formatSelection = selectionFormatterFunction;
    } else {
      select2_params.formatSelection = function(doc) {
        if (select2_params.labelFieldName != null) {
          return doc.properties[select2_params.labelFieldName];
        } else {
          return getDefaultLabel(doc)
        }
      };
    }
    // append custom suggestion formatter if needed
    if (suggestionFormatterFunction != null) {
      select2_params.formatResult = suggestionFormatterFunction;
    } else {
      select2_params.formatResult = getDefaultLabel;
    }

    // append id formatter if needed
    if (params.idProperty && params.idProperty.length > 0) {
      select2_params.id = function(doc) {
        return doc.properties[params.idProperty];
      };
    } else if (params.idFunction) {
      select2_params.id = eval(params.idFunction);
    } else if (params.prefixed) {
      select2_params.id = function(item) {
        return item.prefixed_id;
      };
    } else {
      select2_params.id = getDefaultId;
    }

    if (initDoc != null) {
      select2_params.initSelection = function(element, callback) {
        callback(initDoc);
      };
    }

    if (params.multiple == 'true') {
      select2_params.maximumSelectionSize = params.maximumSelectionSize;
      select2_params.multiple = true;
    }

    if (params.placeholder && !readonly) {
      select2_params.placeholder = params.placeholder;
      select2_params.allowClear = !required;
    }

    // init select2
    el.select2(select2_params);

    // view or edit mode
    if (readonly) {
      el.select2("readonly", true);
    }

    if (!readonly) {

      // Make selected items sortable
      if (params.multiple == 'true' && params.orderable == 'true') {
        el.select2("container").find("ul.select2-choices").sortable({
          containment : 'parent',
          start : function() {
            el.select2("onSortStart");
          },
          update : function() {
            el.select2("onSortEnd");
          }
        });
      }

      // Handle onclick widget property
      el.on("select2-opening", function(e) {
        if (params.onclick) {
          eval(params.onclick);
        }
      });

      // trigger for safeEdit restore
      el.on("change", function(e) {
        if (e) {
          if (e.added) {
            var newValue;
            if (select2_params.multiple) {
              var newObj = JSON.parse(initHolder.val());
              newObj.push(e.added);
              var newValue = JSON.stringify(newObj);
            } else {
              newValue = JSON.stringify(e.added);
            }
            initHolder.val(newValue);
          }

          if (e.removed) {
            var removedId = select2_params.id(e.removed);
            if (select2_params.multiple) {
              var newValue = '';
              var tempObj = JSON.parse(initHolder.val());
              jQuery.each(tempObj, function(index, result) {
                if (result) {
                  if (select2_params.id(result) == removedId) {
                    tempObj.splice(index, 1);
                  }
                }
              });
              newValue = JSON.stringify(tempObj);
              initHolder.val(newValue);
            } else {
              if (initHolder.val() == removedId) {
                initHolder.val('');
              }
            }
          }
        }

        // ReRender any jsf component if needed.
        if (params.reRenderFunctionName) {
          window[params.reRenderFunctionName]();
        }

        // Handle onchange widget property
        if (params.onchange) {
          eval(params.onchange);
        }

      });
    }

    var $parentForm = jQuery(el).closest("form");
    if ($parentForm.hasClass("safeEditEnabled")) {
        // Register postRestore function for safeEdit
        jQuery(el).closest("form").registerPostRestoreCallBacks(function(data) {
          initSelect2Widget(jQuery(el));
        });
      }
  }

  window.initSelect2AjaxWidget = function initSelect2AjaxWidget(widgetId, index) {

    var selector = "input[type='hidden'][id$=";

    if (index != null && index.length > 0) {
      selector = selector + index + "\\:";
    }
    selector = selector + widgetId + "_select2]";

    jQuery(selector).each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });

  }

  window.initSelect2Widgets = function initSelect2Widgets() {
    jQuery("input[type='hidden'][id$=select2]").each(function(idx, el) {
      initSelect2Widget(jQuery(el));
    });
  }

})();
<|endoftext|>