<commit_before>// (c) 2016 osmcz-app, https://github.com/osmcz/osmcz

var osmcz = osmcz || {};
osmcz.activeLayer = function (map, baseLayers, overlays, controls) {
    // -- constructor --

    var style = {
        "clickable": true,
        "color": "#00D",
        "fillColor": "#00D",

        radius: 4,
        weight: 0,
        opacity: 1,
        fillOpacity: 0.2
    };
    var hoverStyle = {
        "fillOpacity": 0.5
    };

    //The later - the more priority https://www.mapbox.com/maki/
    var icons = {
        amenity: {
            restaurant: 'restaurant',
            fuel: 'fuel',
            toilets: 'toilets',
            telephone: 'telephone',
            fast_food: 'fast-food',
            bank: 'bank',
            atm: 'bank',
            waste_disposal: 'waste-basket',
            pub: 'beer',
            post_office: 'post',
            post_box: 'post',
            pharmacy: 'hospital',
            doctors: 'hospital',
            bar: 'bar',
            cafe: 'cafe',
            car_rental: 'car',
            school: 'school',
            college: 'college',
            bicycle_parking: 'bicycle',
            university: 'college',
            library: 'library',
            theatre: 'theatre',
            public_building: 'town-hall',
        },
        highway: {
            bus_stop: 'bus'
        },
        leisure: {
            playground: 'playground',
        },
        railway: {
            station: 'rail-24',
            halt: 'rail-24',
            tram_stop: 'rail-light'
        },
        shop: {
            '*': 'shop',
            chemist: 'pharmacy',
            grocery: 'grocery',
            supermarket: 'grocery',
            convenience: 'grocery'
        },
        station: {
            subway: 'rail-metro'
        },
        tourism: {
            guest_house: 'lodging',
            hostel: 'lodging',
            hotel: 'lodging'
        },
        historic: {
            monument: 'monument',
            memorial: 'monument'
        },
        man_made: {
            surveillance: 'camera'
        },
        place: {
            city: 'square-18',
            town: 'square-stroked-16',
            village: 'circle-8'
        },
        information: {
            guidepost: 'guidepost'
        }
    };

    function getIcon(tags) {
        var name = false;
        for (var key in tags) {
            var val = tags[key];
            if (icons[key] && icons[key][val])
                name = icons[key][val];
            else if (icons[key] && icons[key]['*'])
                name = icons[key]['*'];
        }

        var pc = name ? name.split('-') : 0;
//         var iconBaseUrl = 'https://cdn.rawgit.com/mapbox/maki/v0.5.0/renders/';
        var iconBaseUrl = 'https://cdn.rawgit.com/osmcz/maki/osmcz_v1/renders/';
//         var iconBaseUrl = 'http://localhost/maki/renders/';

        if (name && IsNumeric(pc[pc.length - 1])) {

            var icName = name.substring(0, name.length - pc[pc.length - 1].length);
            var icSize = parseInt(pc[pc.length - 1]);
            var size = [icSize, icSize];

            if (icSize <= 12) {
                var iconUrl = iconBaseUrl + icName + '12';
            } else if (icSize > 12 && icSize <= 18) {
                var iconUrl = iconBaseUrl + icName + '18';
            } else {
                var iconUrl = iconBaseUrl + icName + '24';
            }

        } else if (name && !IsNumeric(pc[pc.length - 1])) {
            var iconUrl = iconBaseUrl + name + '-18';
            var size = [18, 18];

        } else {
            var iconUrl = iconBaseUrl + 'circle-stroked-12';
            var size = [10, 10];
        }

        return L.icon({
            iconUrl: iconUrl + '.png',
            iconRetinaUrl: iconUrl + '@2x.png',
            iconSize: size,
            popupAnchor: [0, -9]
        });
    }

    var timeout;
    var permanentlyDisplayed = false;
    var marker = L.circleMarker([0,0]);

    var geojsonURL = 'http://tile.poloha.net/json/{z}/{x}/{y}';
    var geojsonTileLayer = new L.TileLayer.GeoJSON(geojsonURL, {
            maxZoom: 25,
            code: 'A'
            //clipTiles: true,
            //unique: function (feature) {                return feature.osm_id;            }
        }, {
            style: style,

            pointToLayer: function (feature, latlng) {
                return L.marker(latlng, {icon: getIcon(feature.properties.tags)});
            },

            onEachFeature: function (feature, layer) {

                if (!(layer instanceof L.Point)) {
                    layer.on('click', function (event) {
                        console.log('click', event);
                        if (event.target && event.target.feature) {
                            clearTimeout(timeout);
                            permanentlyDisplayed = true;
                            openPoiPanel(event.target.feature, event.target.options.icon.options.iconUrl);
                        }
                    });

                    layer.on('mouseover', function (event) {
                        if (permanentlyDisplayed)
                            return;

                        if (event.target && event.target.feature) {
                            clearTimeout(timeout);
                            timeout = setTimeout(function () {
                                openPoiPanel(event.target.feature, event.target.options.icon.options.iconUrl);
                            }, 100);
                        }
                    });
                    layer.on('mouseout', function (event) {
                        if (!permanentlyDisplayed) {
                            clearTimeout(timeout);
                            timeout = setTimeout(function () {
                                defaultPoiPanel();
                            }, 300);
                        }
                    });
                }
            }
        }
    );

    //add as overlay
    overlays["Aktivní vrstva"] = geojsonTileLayer;

    map.on('layeradd', function (event) {
        if (event.layer == geojsonTileLayer) {
            $('#map-container').addClass('searchbar-on');
            defaultPoiPanel();
        }
    });
    map.on('layerremove', function (event) {
        if (event.layer == geojsonTileLayer) {
            $('#map-container').removeClass('searchbar-on');
        }
    });

    //reset panel
    function resetPanel(){
        defaultPoiPanel();
        permanentlyDisplayed = false;
        map.removeLayer(marker);
    }
    $('#map-searchbar').on('click', '.close', resetPanel);
    map.on('click', resetPanel);

    function IsNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    function openPoiPanel(feature, icon) {
        $('#map-searchbar').html(template(feature, icon));
    }

    function defaultPoiPanel() {
        $('#map-searchbar').html("Najeďte myší na bod zájmu
nebo klikněte pro trvalé zobrazení.");

    }

    function template(feature, icon) {
        var id = feature.properties.osm_id;
        var osm_type = feature.properties.osm_type;
        var name = {};
        var contact = {};
        var payment = {};
        var building = {};

        var tpl = [];
        tpl.push(permanentlyDisplayed ? '×' : '');
        tpl.push('
');
        tpl.push(' ');
        tpl.push(feature.properties.tags.name || 'Bod zájmu');
        tpl.push('
');

        $.each(feature.properties.tags, function (k, v) {
            if (k.match(/^name:/))
                name[k] = v;
            else if (k.match(/^payment:/))
                payment[k] = v;
            else if (k.match(/^contact:/) || k.match(/^phone/) || k.match(/^email/))
                contact[k] = v;
            else if (k.match(/^building/))
                building[k] = v;
            else if (k.match(/^wikipedia/)) {
                tpl.push('' + k + ' = '+ v + '');
                tpl.push('
');
            }
            else if (!k.match(/^addr:/) &&
                     !k.match(/^ref:ruian:/)
                    ) {
                tpl.push('' + k + ' = ');
                tpl.push(v.match(/^https?:\/\/.+/) ? ('' + v + '') : v);
                tpl.push('
');
            }
        });

        var section = function (obj, label) {
            if (Object.keys(obj).length) {
                tpl.push('
' + label + '
');
                $.each(obj, function (k, v) {
                    tpl.push('' + k + ' = ');
                    tpl.push(v.match(/^https?:\/\/.+/) ? ('' + v + '') : v);
                    tpl.push('
');
                });
                tpl.pop(); //remove last br
            }
        };

        section(name, 'Další jména:');
        section(payment, 'Možnosti platby:');
        section(contact, 'Kontakty:');
        section(building, 'Budova:');

        tpl.push('
osm ID: ' + osm_type + '/' + id + '
');
        tpl.push('

');

        if (permanentlyDisplayed) {
            var lon = feature.geometry.coordinates[0];
            var lat = feature.geometry.coordinates[1];

            marker.setLatLng([lat, lon]).addTo(map);

            if (feature.mapillary) {
                setTimeout(function () { //after dom is created
                    showMapillary();
                }, 0);
            }
            else {
                //TODO - limit=10 & choose the best oriented photo
                $.ajax({
                    url: 'http://api.mapillary.com/v1/im/close?lat=' + lat + '&lon=' + lon + '&distance=30&limit=1',
                    dataType: 'json',
                    jsonp: false,
                    global: false,
                    success: function (data) {
                        feature.mapillary = data;
                        showMapillary();
                    }
                });
            }
        }

        var mpTpl = '
Nejbližší foto
'
            + ''
            + ''
            + '';
        function showMapillary() {
            var mp = $('#mapillary-photo');
            if (id = mp.attr('data-osm-id') && feature.mapillary.length) {
                mp.html(mpTpl.replace(/_key/g, feature.mapillary[0].key));
            }
        };

        return tpl.join('');
    }

};
<commit_msg>active-layer: sort general keys #76<commit_after>// (c) 2016 osmcz-app, https://github.com/osmcz/osmcz

var osmcz = osmcz || {};
osmcz.activeLayer = function (map, baseLayers, overlays, controls) {
    // -- constructor --

    var style = {
        "clickable": true,
        "color": "#00D",
        "fillColor": "#00D",

        radius: 4,
        weight: 0,
        opacity: 1,
        fillOpacity: 0.2
    };
    var hoverStyle = {
        "fillOpacity": 0.5
    };

    //The later - the more priority https://www.mapbox.com/maki/
    var icons = {
        amenity: {
            restaurant: 'restaurant',
            fuel: 'fuel',
            toilets: 'toilets',
            telephone: 'telephone',
            fast_food: 'fast-food',
            bank: 'bank',
            atm: 'bank',
            waste_disposal: 'waste-basket',
            pub: 'beer',
            post_office: 'post',
            post_box: 'post',
            pharmacy: 'hospital',
            doctors: 'hospital',
            bar: 'bar',
            cafe: 'cafe',
            car_rental: 'car',
            school: 'school',
            college: 'college',
            bicycle_parking: 'bicycle',
            university: 'college',
            library: 'library',
            theatre: 'theatre',
            public_building: 'town-hall',
        },
        highway: {
            bus_stop: 'bus'
        },
        leisure: {
            playground: 'playground',
        },
        railway: {
            station: 'rail-24',
            halt: 'rail-24',
            tram_stop: 'rail-light'
        },
        shop: {
            '*': 'shop',
            chemist: 'pharmacy',
            grocery: 'grocery',
            supermarket: 'grocery',
            convenience: 'grocery'
        },
        station: {
            subway: 'rail-metro'
        },
        tourism: {
            guest_house: 'lodging',
            hostel: 'lodging',
            hotel: 'lodging'
        },
        historic: {
            monument: 'monument',
            memorial: 'monument'
        },
        man_made: {
            surveillance: 'camera'
        },
        place: {
            city: 'square-18',
            town: 'square-stroked-16',
            village: 'circle-8'
        },
        information: {
            guidepost: 'guidepost'
        }
    };

    function getIcon(tags) {
        var name = false;
        for (var key in tags) {
            var val = tags[key];
            if (icons[key] && icons[key][val])
                name = icons[key][val];
            else if (icons[key] && icons[key]['*'])
                name = icons[key]['*'];
        }

        var pc = name ? name.split('-') : 0;
//         var iconBaseUrl = 'https://cdn.rawgit.com/mapbox/maki/v0.5.0/renders/';
        var iconBaseUrl = 'https://cdn.rawgit.com/osmcz/maki/osmcz_v1/renders/';
//         var iconBaseUrl = 'http://localhost/maki/renders/';

        if (name && IsNumeric(pc[pc.length - 1])) {

            var icName = name.substring(0, name.length - pc[pc.length - 1].length);
            var icSize = parseInt(pc[pc.length - 1]);
            var size = [icSize, icSize];

            if (icSize <= 12) {
                var iconUrl = iconBaseUrl + icName + '12';
            } else if (icSize > 12 && icSize <= 18) {
                var iconUrl = iconBaseUrl + icName + '18';
            } else {
                var iconUrl = iconBaseUrl + icName + '24';
            }

        } else if (name && !IsNumeric(pc[pc.length - 1])) {
            var iconUrl = iconBaseUrl + name + '-18';
            var size = [18, 18];

        } else {
            var iconUrl = iconBaseUrl + 'circle-stroked-12';
            var size = [10, 10];
        }

        return L.icon({
            iconUrl: iconUrl + '.png',
            iconRetinaUrl: iconUrl + '@2x.png',
            iconSize: size,
            popupAnchor: [0, -9]
        });
    }

    var timeout;
    var permanentlyDisplayed = false;
    var marker = L.circleMarker([0,0]);

    var geojsonURL = 'http://tile.poloha.net/json/{z}/{x}/{y}';
    var geojsonTileLayer = new L.TileLayer.GeoJSON(geojsonURL, {
            maxZoom: 25,
            code: 'A'
            //clipTiles: true,
            //unique: function (feature) {                return feature.osm_id;            }
        }, {
            style: style,

            pointToLayer: function (feature, latlng) {
                return L.marker(latlng, {icon: getIcon(feature.properties.tags)});
            },

            onEachFeature: function (feature, layer) {

                if (!(layer instanceof L.Point)) {
                    layer.on('click', function (event) {
                        console.log('click', event);
                        if (event.target && event.target.feature) {
                            clearTimeout(timeout);
                            permanentlyDisplayed = true;
                            openPoiPanel(event.target.feature, event.target.options.icon.options.iconUrl);
                        }
                    });

                    layer.on('mouseover', function (event) {
                        if (permanentlyDisplayed)
                            return;

                        if (event.target && event.target.feature) {
                            clearTimeout(timeout);
                            timeout = setTimeout(function () {
                                openPoiPanel(event.target.feature, event.target.options.icon.options.iconUrl);
                            }, 100);
                        }
                    });
                    layer.on('mouseout', function (event) {
                        if (!permanentlyDisplayed) {
                            clearTimeout(timeout);
                            timeout = setTimeout(function () {
                                defaultPoiPanel();
                            }, 300);
                        }
                    });
                }
            }
        }
    );

    //add as overlay
    overlays["Aktivní vrstva"] = geojsonTileLayer;

    map.on('layeradd', function (event) {
        if (event.layer == geojsonTileLayer) {
            $('#map-container').addClass('searchbar-on');
            defaultPoiPanel();
        }
    });
    map.on('layerremove', function (event) {
        if (event.layer == geojsonTileLayer) {
            $('#map-container').removeClass('searchbar-on');
        }
    });

    //reset panel
    function resetPanel(){
        defaultPoiPanel();
        permanentlyDisplayed = false;
        map.removeLayer(marker);
    }
    $('#map-searchbar').on('click', '.close', resetPanel);
    map.on('click', resetPanel);

    function IsNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    function openPoiPanel(feature, icon) {
        $('#map-searchbar').html(template(feature, icon));
    }

    function defaultPoiPanel() {
        $('#map-searchbar').html("Najeďte myší na bod zájmu
nebo klikněte pro trvalé zobrazení.");

    }

    function template(feature, icon) {
        var id = feature.properties.osm_id;
        var osm_type = feature.properties.osm_type;
        var general = []; // store k,v objects in array to allow sort them
        var name = {};
        var contact = {};
        var payment = {};
        var building = {};

        var tpl = [];
        tpl.push(permanentlyDisplayed ? '×' : '');
        tpl.push('
');
        tpl.push(' ');
        tpl.push(feature.properties.tags.name || 'Bod zájmu');
        tpl.push('
');

        $.each(feature.properties.tags, function (k, v) {
            if (k.match(/^name:/))
                name[k] = v;
            else if (k.match(/^payment:/))
                payment[k] = v;
            else if (k.match(/^contact:/) || k.match(/^phone/) || k.match(/^email/))
                contact[k] = v;
            else if (k.match(/^building/))
                building[k] = v;
            else if (!k.match(/^addr:/) &&
                     !k.match(/^ref:ruian:/)
                    )
                general.push({k:k, v:v});
        });

        // sort the array
        general.sort(function(a, b){
          var nameA=a.k, nameB=b.k
          if (nameA < nameB) //sort string ascending
            return -1
          if (nameA > nameB)
            return 1
          return 0 //default return value (no sorting)
          });

        if (general.length) {
            for (var i in general)
            {
                var k = general[i].k;
                var v = general[i].v;
                if (k.match(/^wikipedia/)) {
                    tpl.push('' + k + ' = '+ v + '');
                }
                else {
                    tpl.push('' + k + ' = ');
                    tpl.push(v.match(/^https?:\/\/.+/) ? ('' + v + '') : v);
                }
                tpl.push('
');
            };
        };

        var section = function (obj, label) {
            if (Object.keys(obj).length) {
                tpl.push('
' + label + '
');
                $.each(obj, function (k, v) {
                    tpl.push('' + k + ' = ');
                    tpl.push(v.match(/^https?:\/\/.+/) ? ('' + v + '') : v);
                    tpl.push('
');
                });
                tpl.pop(); //remove last br
            }
        };

        section(name, 'Další jména:');
        section(payment, 'Možnosti platby:');
        section(contact, 'Kontakty:');
        section(building, 'Budova:');

        tpl.push('
osm ID: ' + osm_type + '/' + id + '
');
        tpl.push('

');

        if (permanentlyDisplayed) {
            var lon = feature.geometry.coordinates[0];
            var lat = feature.geometry.coordinates[1];

            marker.setLatLng([lat, lon]).addTo(map);

            if (feature.mapillary) {
                setTimeout(function () { //after dom is created
                    showMapillary();
                }, 0);
            }
            else {
                //TODO - limit=10 & choose the best oriented photo
                $.ajax({
                    url: 'http://api.mapillary.com/v1/im/close?lat=' + lat + '&lon=' + lon + '&distance=30&limit=1',
                    dataType: 'json',
                    jsonp: false,
                    global: false,
                    success: function (data) {
                        feature.mapillary = data;
                        showMapillary();
                    }
                });
            }
        }

        var mpTpl = '
Nejbližší foto
'
            + ''
            + ''
            + '';
        function showMapillary() {
            var mp = $('#mapillary-photo');
            if (id = mp.attr('data-osm-id') && feature.mapillary.length) {
                mp.html(mpTpl.replace(/_key/g, feature.mapillary[0].key));
            }
        };

        return tpl.join('');
    }

};
<|endoftext|>


<commit_before>'use strict';

function calcFactory(spec) {
  const DISPLAY = document.querySelector(spec.display);
  const BUTTONS = document.querySelector(spec.buttons);
  let gEntriesArray  = [];
  let gHasDecimal    = false;
  let gLastNumber    = null;  // gLastNumber is null at startup and after CA and CE
  let gLastOp        = "";
  let gLastEntryType = "digit"; // digit or operation

  const Calculator = {
    init () {
      if (!BUTTONS)
        throw new Error("Invalid initialization parameter: buttons.");
      if (!DISPLAY)
        throw new Error("Invalid initialization parameter: display.");
      $(BUTTONS).off('click.calculator', this.buttonPressHandler.bind(this));
      $(BUTTONS).on('click.calculator', this.buttonPressHandler.bind(this));
      // BUTTONS.removeEventListener('click', this.buttonPressHandler.bind(this));
      // BUTTONS.addEventListener("click", this.buttonPressHandler.bind(this));
    },

    addToEntriesArray (entry) {
      gEntriesArray.push(entry);
    },

    clearEntriesArray () {
      gEntriesArray = [];
    },

    getEntriesArray () {
      return gEntriesArray.slice();
    },

    setLastOp (op) {
      gLastOp = op;
      return gLastOp;
    },

    getLastOp () {
      return gLastOp;
    },

    setLastNumber (nb) {
      gLastNumber = nb;
    },

    getLastNumber () {
      return gLastNumber;
    },

    setLastEntryType (type) {
      gLastEntryType = type;
    },

    getLastEntryType () {
      return gLastEntryType;
    },

    setHasDecimal (has) {
      gHasDecimal = has;
    },

    getHasDecimal () {
      return gHasDecimal;
    },

    // Set or get display area text
    updateDisplay (target, str) {
      var container = $(target);
      if (str === undefined)
        return container.text() || "";
      else
        container.text(str);
    },

    operation (display, op) {
      // if no digits entered previously, do nothing.
      if (gLastNumber === null)
        return display;

      gLastOp = op;
      gLastEntryType = 'operation';
      return display;
    },

    plusminus (display) {
      if (gLastNumber === null)
        return display;

      gLastNumber *= -1;
      return display[0] === '-' ? display.slice(1): '-' + display;
    },

    decimal (display) {
      // no current number
      if (gLastNumber === null) {
        display = "0.";
        gHasDecimal = true;
      }
      else { // number has no decimal
        if (!gHasDecimal) {
          display = display + '.';
          gHasDecimal = true;
        }
        else { //if number ends with decimal, then toggle, otherwise do nothing
          if (display[display.length-1] === '.') {
            display = display.substr(0, display.length-1);
            gHasDecimal = false;
          }
        }
      }
      gLastNumber = Number(display);
      gLastOp = "";
      gLastEntryType = "digit";
      return display;
    },

    digit (display, dgt) {
      if (gLastEntryType === 'operation') {
        if (gLastOp && gLastNumber !== null) {
          gEntriesArray.push(gLastNumber);
          gEntriesArray.push(gLastOp);
        }
        display = dgt;
        gHasDecimal = false;
      } // last entry was a digit so keep appending to number.
      else {
        if (Number(display) === 0 && !gHasDecimal)
          //prevents leading zero
          display = dgt;
        else
          display = display + dgt;
      }

      gLastNumber = Number(display);
      gLastOp = "";
      gLastEntryType = 'digit';
      return display;
    },

    clearEntry (display) {
      if (gLastNumber !== null) {
        gLastNumber = null;
        gHasDecimal = false;
        gLastEntryType = "digit";
        gLastOp = "";
      }
      return ""; // returns "" as display
    },

    clearAll (display) {
      if (gLastNumber !== null) {
        gLastNumber = null;
        gHasDecimal = false;
        gLastEntryType = "digit";
        gLastOp = "";
      }
      gEntriesArray = [];
      return ""; // returns "" as display
    },

    buttonPressHandler (e) {
        var nextDisplay = "";
        var currentDisplay = this.updateDisplay(DISPLAY);
        if (e.target.tagName === 'BUTTON') {
          switch (e.target.textContent) {
            case 'CE': nextDisplay = this.clearEntry(currentDisplay);
                      break;
            case 'AC': nextDisplay = this.clearAll(currentDisplay);
                      break;
            case '=': //calculate final result and display it
                      break;
            case '+': //addition
            case '-': //substraction
            case '\u00F7': //division
            case '\u00D7': //multiplication
                      nextDisplay = this.operation(currentDisplay, e.target.textContent);
                      break;
            case '\u00B1': //toggle +/-
                      nextDisplay = this.plusminus(currentDisplay);
                      break;
            case '.': //decimal
                      nextDisplay = this.decimal(currentDisplay);
                      break;
            default:  //last entry was an operation, then save the current number and operation
                      nextDisplay = this.digit(currentDisplay, e.target.textContent);
          }
          // console.log("Entries: ", gEntriesArray);
          // console.log("Last entry, number, op: ", gLastEntryType + " / " + gLastNumber + " / " + gLastOp);
          this.updateDisplay(DISPLAY, nextDisplay);
        }
        e.stopPropagation();
    }
  };

  var calcObj = Object.create(Calculator);
  try {
    calcObj.init();
  }
  catch (err) {
    window.alert(err);
  }
  return calcObj;
}
<commit_msg>Changed behavior of decimal key pressed after operation key<commit_after>'use strict';

function calcFactory(spec) {
  const DISPLAY = document.querySelector(spec.display);
  const BUTTONS = document.querySelector(spec.buttons);
  let gEntriesArray  = [];
  let gHasDecimal    = false;
  let gLastNumber    = null;  // gLastNumber is null at startup and after CA and CE
  let gLastOp        = "";
  let gLastEntryType = "digit"; // digit or operation

  const Calculator = {
    init () {
      if (!BUTTONS)
        throw new Error("Invalid initialization parameter: buttons.");
      if (!DISPLAY)
        throw new Error("Invalid initialization parameter: display.");
      $(BUTTONS).off('click.calculator', this.buttonPressHandler.bind(this));
      $(BUTTONS).on('click.calculator', this.buttonPressHandler.bind(this));
      // BUTTONS.removeEventListener('click', this.buttonPressHandler.bind(this));
      // BUTTONS.addEventListener("click", this.buttonPressHandler.bind(this));
    },

    addToEntriesArray (entry) {
      gEntriesArray.push(entry);
    },

    clearEntriesArray () {
      gEntriesArray = [];
    },

    getEntriesArray () {
      return gEntriesArray.slice();
    },

    setLastOp (op) {
      gLastOp = op;
      return gLastOp;
    },

    getLastOp () {
      return gLastOp;
    },

    setLastNumber (nb) {
      gLastNumber = nb;
    },

    getLastNumber () {
      return gLastNumber;
    },

    setLastEntryType (type) {
      gLastEntryType = type;
    },

    getLastEntryType () {
      return gLastEntryType;
    },

    setHasDecimal (has) {
      gHasDecimal = has;
    },

    getHasDecimal () {
      return gHasDecimal;
    },

    // Set or get display area text
    updateDisplay (target, str) {
      var container = $(target);
      if (str === undefined)
        return container.text() || "";
      else
        container.text(str);
    },

    operation (display, op) {
      // if no digits entered previously, do nothing.
      if (gLastNumber === null)
        return display;

      gLastOp = op;
      gLastEntryType = 'operation';
      return display;
    },

    plusminus (display) {
      if (gLastNumber === null)
        return display;

      gLastNumber *= -1;
      gLastEntryType = "digit";
      return display[0] === '-' ? display.slice(1): '-' + display;
    },

    decimal (display) {
      if (gLastEntryType === 'operation') {
        if (gLastOp && gLastNumber !== null) {
          gEntriesArray.push(gLastNumber);
          gEntriesArray.push(gLastOp);
        }
        display = "0.";
        gHasDecimal = true;
      }
      else { // last key pressed was not an operation key, then...
        // no current number
        if (gLastNumber === null) {
          display = "0.";
          gHasDecimal = true;
        }
        else { // number has no decimal
          if (!gHasDecimal) {
            display = display + '.';
            gHasDecimal = true;
          }
          else { //if number ends with decimal, then toggle, otherwise do nothing
            if (display[display.length-1] === '.') {
              display = display.substr(0, display.length-1);
              gHasDecimal = false;
            }
          }
        }
      }
      gLastNumber = Number(display);
      gLastOp = "";
      gLastEntryType = "digit";
      return display;
    },

    digit (display, dgt) {
      if (gLastEntryType === 'operation') {
        if (gLastOp && gLastNumber !== null) {
          gEntriesArray.push(gLastNumber);
          gEntriesArray.push(gLastOp);
        }
        display = dgt;
        gHasDecimal = false;
      } // last entry was a digit so keep appending to number.
      else {
        if (Number(display) === 0 && !gHasDecimal)
          //prevents leading zero
          display = dgt;
        else
          display = display + dgt;
      }

      gLastNumber = Number(display);
      gLastOp = "";
      gLastEntryType = 'digit';
      return display;
    },

    clearEntry (display) {
      if (gLastNumber !== null) {
        gLastNumber = null;
        gHasDecimal = false;
        gLastEntryType = "digit";
        gLastOp = "";
      }
      return ""; // returns "" as display
    },

    clearAll (display) {
      if (gLastNumber !== null) {
        gLastNumber = null;
        gHasDecimal = false;
        gLastEntryType = "digit";
        gLastOp = "";
      }
      gEntriesArray = [];
      return ""; // returns "" as display
    },

    buttonPressHandler (e) {
        var nextDisplay = "";
        var currentDisplay = this.updateDisplay(DISPLAY);
        if (e.target.tagName === 'BUTTON') {
          switch (e.target.textContent) {
            case 'CE': nextDisplay = this.clearEntry(currentDisplay);
                      break;
            case 'AC': nextDisplay = this.clearAll(currentDisplay);
                      break;
            case '=': //calculate final result and display it
                      break;
            case '+': //addition
            case '-': //substraction
            case '\u00F7': //division
            case '\u00D7': //multiplication
                      nextDisplay = this.operation(currentDisplay, e.target.textContent);
                      break;
            case '\u00B1': //toggle +/-
                      nextDisplay = this.plusminus(currentDisplay);
                      break;
            case '.': //decimal
                      nextDisplay = this.decimal(currentDisplay);
                      break;
            default:  //last entry was an operation, then save the current number and operation
                      nextDisplay = this.digit(currentDisplay, e.target.textContent);
          }
          // console.log("Entries: ", gEntriesArray);
          // console.log("Last entry, number, op: ", gLastEntryType + " / " + gLastNumber + " / " + gLastOp);
          this.updateDisplay(DISPLAY, nextDisplay);
        }
        e.stopPropagation();
    }
  };

  var calcObj = Object.create(Calculator);
  try {
    calcObj.init();
  }
  catch (err) {
    window.alert(err);
  }
  return calcObj;
}
<|endoftext|>


<commit_before>var PIECES = { BISHOP : "bishop", KNIGHT : "knight", ROOK : "rook", KING : "king", QUEEN : "queen", PAWN : "pawn" };
var COLUMN_INDEX = "abcdefgh";
var BLACK = "black";
var WHITE = "white";
var BLACK_SQUARE_COLOR = "#80681F";
var WHITE_SQUARE_COLOR = "#D6AD33";

/**
 * Creates a new Chessboard
 */
function Chessboard(cols, rows) {
	this.board = new Array(rows);
	this.blackPieces = new Array(16);
	this.whitePieces = new Array(16);

	this.pieceSelected = null;
	this.turn = WHITE;

	var color = BLACK_SQUARE_COLOR;

	// Initialize the board:
	for(var i = 0; i < rows; i++) {
		this.board[i] = new Array(cols);

		for(var j = 0; j < cols; j++) {
			this.board[i][j] = new ChessSquare(color, i, j);

			// Toggle color
			color = (color == BLACK_SQUARE_COLOR) ? WHITE_SQUARE_COLOR : BLACK_SQUARE_COLOR;
		}

		// Toggle color
		color = color == BLACK_SQUARE_COLOR ? WHITE_SQUARE_COLOR : BLACK_SQUARE_COLOR;
	}

	// Initialize the pieces (2 rooks, 2 knights, 2 bishops, 1 king, 1 queen, 8 pawns)
	this.blackPieces[0] = new ChessPiece(BLACK, PIECES.ROOK, this.board[7][0]);
	this.blackPieces[1] = new ChessPiece(BLACK, PIECES.ROOK, this.board[7][7]);
	this.blackPieces[2] = new ChessPiece(BLACK, PIECES.KNIGHT, this.board[7][1]);
	this.blackPieces[3] = new ChessPiece(BLACK, PIECES.KNIGHT, this.board[7][6]);
	this.blackPieces[4] = new ChessPiece(BLACK, PIECES.BISHOP, this.board[7][2]);
	this.blackPieces[5] = new ChessPiece(BLACK, PIECES.BISHOP, this.board[7][5]);
	this.blackPieces[6] = new ChessPiece(BLACK, PIECES.KING, this.board[7][3]);
	this.blackPieces[7] = new ChessPiece(BLACK, PIECES.QUEEN, this.board[7][4]);
	this.blackPieces[8] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][0]);
	this.blackPieces[9] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][1]);
	this.blackPieces[10] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][2]);
	this.blackPieces[11] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][3]);
	this.blackPieces[12] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][4]);
	this.blackPieces[13] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][5]);
	this.blackPieces[14] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][6]);
	this.blackPieces[15] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][7]);

	this.whitePieces[0] = new ChessPiece(WHITE, PIECES.ROOK, this.board[0][0]);
	this.whitePieces[1] = new ChessPiece(WHITE, PIECES.ROOK, this.board[0][7]);
	this.whitePieces[2] = new ChessPiece(WHITE, PIECES.KNIGHT, this.board[0][1]);
	this.whitePieces[3] = new ChessPiece(WHITE, PIECES.KNIGHT, this.board[0][6]);
	this.whitePieces[4] = new ChessPiece(WHITE, PIECES.BISHOP, this.board[0][2]);
	this.whitePieces[5] = new ChessPiece(WHITE, PIECES.BISHOP, this.board[0][5]);
	this.whitePieces[6] = new ChessPiece(WHITE, PIECES.KING, this.board[0][3]);
	this.whitePieces[7] = new ChessPiece(WHITE, PIECES.QUEEN, this.board[0][4]);
	this.whitePieces[8] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][0]);
	this.whitePieces[9] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][1]);
	this.whitePieces[10] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][2]);
	this.whitePieces[11] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][3]);
	this.whitePieces[12] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][4]);
	this.whitePieces[13] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][5]);
	this.whitePieces[14] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][6]);
	this.whitePieces[15] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][7]);

	this.selectPiece = function(cellId) {
		var row = cellId.substring(0, 1);
		var col = cellId.substring(1);

		var square = this.board[row-1][col-1];
		if(square.piece != null && square.piece.color == this.turn) {
			console.log("Selecting " + square.piece.color + " " + square.piece.type);

			square.selected = true;
			this.pieceSelected = square.piece;
		}

		// Update view
		this.updateView();
	}

	this.movePiece = function(cellId) {
		console.log("Moving " + this.pieceSelected.color + " " + this.pieceSelected.type + " to: " + cellId);

		var row = cellId.substring(0, 1);
		var col = cellId.substring(1);

		var square = this.board[row-1][col-1];

		// Move the piece:
		this.pieceSelected.square.selected = false;
		this.pieceSelected.square.piece = null;
		this.pieceSelected.square = square;
		square.piece = this.pieceSelected;

		this.pieceSelected = null;
		this.turn = this.turn == WHITE ? BLACK : WHITE;

		// Update view:
		this.updateView();
	}

	// HTML of the board:
	this.toHTML = function() {
		var table = document.createElement("table");
		table.cellSpacing = "0";
		table.cellPadding = "0";

		for(var i = this.board.length; i >= 1; i--) {
			var row = document.createElement("tr");
			for(var j = 1; j <= this.board[i-1].length ; j++) {
				var square = this.board[i-1][j-1];

				var cell = document.createElement("td");
				cell.id = i + "" + j;
				cell.style.backgroundColor = square.selected ? "#39a7d4" : square.color;
				cell.style.width = cell.style.height = "50px";
				cell.style.cursor = "pointer";
				cell.style.textAlign = "center";

				cell.piece = this.board[i-1][j-1].piece;

				// Set the listener:
				if(this.pieceSelected == null) {
					cell.onclick = function(chessboard, id) { return function() { chessboard.selectPiece(id); } }(this, cell.id);
				} else {
					cell.onclick = function(chessboard, id) { return function() { chessboard.movePiece(id); } }(this, cell.id);
				}

				if (square.piece != null){
					var pieceImage = document.createElement("img");
					pieceImage.src = square.piece.background;
					cell.appendChild(pieceImage);
				}

				row.appendChild(cell);
			}

			table.appendChild(row);
		}

		return table;
	}

	this.updateView = function() {
		console.log("Refreshing view.");

		// Show the board
		var chessboard = document.getElementById("chessboard");

		// Clear the previous board
		while(chessboard.firstChild) {
			chessboard.removeChild(chessboard.firstChild);
		}

		// Show the current board:
		chessboard.appendChild(this.toHTML());
	}
}

/**
 * Create a new Chessboard Square.
 * The properties of a square are its color, row and column.
 * A square is initialized with a null piece on it.
 */
function ChessSquare(color, row, column) {
	this.color = color;
	this.row = row;
	this.column = column;
	this.selected = false;

	// Initialize with a null piece:
	this.piece = null;
}

function ChessPiece(color, type, square) {
	this.color = color;
	this.type = type;
	this.square = square;
	this.background = "resources/images/" + color + "_" + type + ".png";

	this.square.piece = this;
}

function initChessmaster() {
	// Create the board
	var board = new Chessboard(8, 8);
	board.updateView();
}<commit_msg>Made a few small fixes<commit_after>var PIECES = { BISHOP : "bishop", KNIGHT : "knight", ROOK : "rook", KING : "king", QUEEN : "queen", PAWN : "pawn" };
var COLUMN_INDEX = "abcdefgh";
var BLACK = "black";
var WHITE = "white";
var BLACK_SQUARE_COLOR = "#80681F";
var WHITE_SQUARE_COLOR = "#D6AD33";

/**
 * Creates a new Chessboard
 */
function Chessboard(cols, rows) {
	this.board = new Array(rows);
	this.blackPieces = new Array(16);
	this.whitePieces = new Array(16);

	this.pieceSelected = null;
	this.turn = WHITE;

	var color = BLACK_SQUARE_COLOR;

	// Initialize the board:
	for(var i = 0; i < rows; i++) {
		this.board[i] = new Array(cols);

		for(var j = 0; j < cols; j++) {
			this.board[i][j] = new ChessSquare(color, i, j);

			// Toggle color
			color = (color == BLACK_SQUARE_COLOR) ? WHITE_SQUARE_COLOR : BLACK_SQUARE_COLOR;
		}

		// Toggle color
		color = color == BLACK_SQUARE_COLOR ? WHITE_SQUARE_COLOR : BLACK_SQUARE_COLOR;
	}

	// Initialize the pieces (2 rooks, 2 knights, 2 bishops, 1 king, 1 queen, 8 pawns)
	this.blackPieces[0] = new ChessPiece(BLACK, PIECES.ROOK, this.board[7][0]);
	this.blackPieces[1] = new ChessPiece(BLACK, PIECES.ROOK, this.board[7][7]);
	this.blackPieces[2] = new ChessPiece(BLACK, PIECES.KNIGHT, this.board[7][1]);
	this.blackPieces[3] = new ChessPiece(BLACK, PIECES.KNIGHT, this.board[7][6]);
	this.blackPieces[4] = new ChessPiece(BLACK, PIECES.BISHOP, this.board[7][2]);
	this.blackPieces[5] = new ChessPiece(BLACK, PIECES.BISHOP, this.board[7][5]);
	this.blackPieces[6] = new ChessPiece(BLACK, PIECES.KING, this.board[7][3]);
	this.blackPieces[7] = new ChessPiece(BLACK, PIECES.QUEEN, this.board[7][4]);
	this.blackPieces[8] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][0]);
	this.blackPieces[9] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][1]);
	this.blackPieces[10] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][2]);
	this.blackPieces[11] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][3]);
	this.blackPieces[12] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][4]);
	this.blackPieces[13] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][5]);
	this.blackPieces[14] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][6]);
	this.blackPieces[15] = new ChessPiece(BLACK, PIECES.PAWN, this.board[6][7]);

	this.whitePieces[0] = new ChessPiece(WHITE, PIECES.ROOK, this.board[0][0]);
	this.whitePieces[1] = new ChessPiece(WHITE, PIECES.ROOK, this.board[0][7]);
	this.whitePieces[2] = new ChessPiece(WHITE, PIECES.KNIGHT, this.board[0][1]);
	this.whitePieces[3] = new ChessPiece(WHITE, PIECES.KNIGHT, this.board[0][6]);
	this.whitePieces[4] = new ChessPiece(WHITE, PIECES.BISHOP, this.board[0][2]);
	this.whitePieces[5] = new ChessPiece(WHITE, PIECES.BISHOP, this.board[0][5]);
	this.whitePieces[6] = new ChessPiece(WHITE, PIECES.KING, this.board[0][3]);
	this.whitePieces[7] = new ChessPiece(WHITE, PIECES.QUEEN, this.board[0][4]);
	this.whitePieces[8] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][0]);
	this.whitePieces[9] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][1]);
	this.whitePieces[10] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][2]);
	this.whitePieces[11] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][3]);
	this.whitePieces[12] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][4]);
	this.whitePieces[13] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][5]);
	this.whitePieces[14] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][6]);
	this.whitePieces[15] = new ChessPiece(WHITE, PIECES.PAWN, this.board[1][7]);

	this.selectPiece = function(cellId) {
		var row = cellId.substring(0, 1);
		var col = cellId.substring(1);

		var square = this.board[row-1][col-1];
		if(square.piece.color == this.turn) {
			console.log("Selecting " + square.piece.color + " " + square.piece.type);

			square.selected = true;
			this.pieceSelected = square.piece;
		}

		// Update view
		this.updateView();
	}

	this.movePiece = function(cellId) {
		console.log("Moving " + this.pieceSelected.color + " " + this.pieceSelected.type + " to: " + cellId);

		var row = cellId.substring(0, 1);
		var col = cellId.substring(1);

		var square = this.board[row-1][col-1];

		// Move the piece:
		this.pieceSelected.square.selected = false;
		this.pieceSelected.square.piece = null;
		this.pieceSelected.square = square;
		square.piece = this.pieceSelected;

		this.pieceSelected = null;
		this.turn = this.turn == WHITE ? BLACK : WHITE;

		// Update view:
		this.updateView();
	}

	// HTML of the board:
	this.toHTML = function() {
		var table = document.createElement("table");
		table.cellSpacing = "0";
		table.cellPadding = "0";

		for(var i = this.board.length; i >= 1; i--) {
			var row = document.createElement("tr");
			for(var j = 1; j <= this.board[i-1].length ; j++) {
				var square = this.board[i-1][j-1];

				var cell = document.createElement("td");
				cell.id = i + "" + j;
				cell.style.backgroundColor = square.selected ? "#39a7d4" : square.color;
				cell.style.width = cell.style.height = "50px";
				cell.style.cursor = "pointer";
				cell.style.textAlign = "center";

				// Set the listener:
				if(this.pieceSelected == null && square.piece != null) {
					cell.onclick = function(chessboard, id) { return function() { chessboard.selectPiece(id); } }(this, cell.id);
				} else if(this.pieceSelected != null){
					cell.onclick = function(chessboard, id) { return function() { chessboard.movePiece(id); } }(this, cell.id);
				}

				if (square.piece != null){
					var pieceImage = document.createElement("img");
					pieceImage.src = square.piece.background;
					cell.appendChild(pieceImage);
				}

				row.appendChild(cell);
			}

			table.appendChild(row);
		}

		return table;
	}

	this.updateView = function() {
		console.log("Refreshing view.");

		// Show the board
		var chessboard = document.getElementById("chessboard");

		// Clear the previous board
		while(chessboard.firstChild) {
			chessboard.removeChild(chessboard.firstChild);
		}

		// Show the current board:
		chessboard.appendChild(this.toHTML());
	}
}

/**
 * Create a new Chessboard Square.
 * The properties of a square are its color, row and column.
 * A square is initialized with a null piece on it.
 */
function ChessSquare(color, row, column) {
	this.color = color;
	this.row = row;
	this.column = column;
	this.selected = false;

	// Initialize with a null piece:
	this.piece = null;
}

function ChessPiece(color, type, square) {
	this.color = color;
	this.type = type;
	this.square = square;
	this.background = "resources/images/" + color + "_" + type + ".png";

	this.square.piece = this;
}

function initChessmaster() {
	// Create the board
	var board = new Chessboard(8, 8);
	board.updateView();
}<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * Builds a repository.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

'use strict';

const ChipperVersion = require( '../common/ChipperVersion' );
const execute = require( '../common/execute' );
const gruntCommand = require( '../common/gruntCommand' );
const assert = require( 'assert' );
const winston = require( 'winston' );

/**
 * Builds a repository.
 * @public
 *
 * @param {string} repo
 * @param {Object} [options]
 * @returns {Promise.<string>} - The stdout of the build
 */
module.exports = async function( repo, options ) {
  const {
    brands = [ 'phet' ],
    locales = 'en',
    allHTML = true,
    debugHTML = true, // Desired in almost all perennial builds, so set to true here
    uglify = true,
    mangle = true,
    lint = true,
    thumbnails = false,
    twitterCard = false
  } = options || {};

  winston.info( `building ${repo}` );

  const chipperVersion = ChipperVersion.getFromRepository();
  const args = [];

  // Chipper "1.0" (it was called such) had version 0.0.0 in its package.json
  if ( chipperVersion.major === 0 && chipperVersion.minor === 0 ) {
    assert( brands.length === 1, 'chipper 0.0.0 cannot build multiple brands at a time' );
    if ( lint ) {
      args.push( 'lint-all' );
    }
    args.push( 'clean' );
    args.push( 'build' );
    if ( thumbnails ) {
      args.push( 'generate-thumbnails' );
    }
    if ( twitterCard ) {
      args.push( 'generate-twitter-card' );
    }
    args.push( `--brand=${brands[ 0 ]}` );
    args.push( `--locales=${locales}` );
    if ( !uglify ) {
      args.push( '--uglify=false' );
    }
    if ( !mangle ) {
      args.push( '--mangle=false' );
    }
    if ( allHTML && brands[ 0 ] !== 'phet-io' ) {
      args.push( '--allHTML' );
    }
    if ( debugHTML ) {
      args.push( '--debugHTML' );
    }
  }
  // Chipper 2.0
  else if ( chipperVersion.major === 2 && chipperVersion.minor === 0 ) {
    args.push( `--brands=${brands.join( ',' )}` );
    args.push( `--locales=${locales}` );
    if ( !uglify ) {
      args.push( '--uglify=false' );
    }
    if ( !mangle ) {
      args.push( '--mangle=false' );
    }
    if ( !lint ) {
      args.push( '--lint=false' );
    }
    if ( allHTML ) {
      args.push( '--allHTML' );
    }
    if ( debugHTML ) {
      args.push( '--debugHTML' );
    }
  }
  else {
    throw new Error( `unsupported chipper version: ${chipperVersion.toString()}` );
  }

  const result = await execute( gruntCommand, args, `../${repo}` );

  // Examine output to see if getDependencies (in chipper) notices any missing phet-io things.
  // Fail out if so. Detects that specific error message.
  if ( result.includes( 'WARNING404' ) ) {
    throw new Error( 'phet-io dependencies missing' );
  }

  return result;
};
<commit_msg>only error "phet-io dependencies missing" if building phet-io brand, https://github.com/phetsims/perennial/issues/182<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * Builds a repository.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

'use strict';

const ChipperVersion = require( '../common/ChipperVersion' );
const execute = require( '../common/execute' );
const gruntCommand = require( '../common/gruntCommand' );
const assert = require( 'assert' );
const winston = require( 'winston' );

/**
 * Builds a repository.
 * @public
 *
 * @param {string} repo
 * @param {Object} [options]
 * @returns {Promise.<string>} - The stdout of the build
 */
module.exports = async function( repo, options ) {
  const {
    brands = [ 'phet' ],
    locales = 'en',
    allHTML = true,
    debugHTML = true, // Desired in almost all perennial builds, so set to true here
    uglify = true,
    mangle = true,
    lint = true,
    thumbnails = false,
    twitterCard = false
  } = options || {};

  winston.info( `building ${repo}` );

  const chipperVersion = ChipperVersion.getFromRepository();
  const args = [];

  // Chipper "1.0" (it was called such) had version 0.0.0 in its package.json
  if ( chipperVersion.major === 0 && chipperVersion.minor === 0 ) {
    assert( brands.length === 1, 'chipper 0.0.0 cannot build multiple brands at a time' );
    if ( lint ) {
      args.push( 'lint-all' );
    }
    args.push( 'clean' );
    args.push( 'build' );
    if ( thumbnails ) {
      args.push( 'generate-thumbnails' );
    }
    if ( twitterCard ) {
      args.push( 'generate-twitter-card' );
    }
    args.push( `--brand=${brands[ 0 ]}` );
    args.push( `--locales=${locales}` );
    if ( !uglify ) {
      args.push( '--uglify=false' );
    }
    if ( !mangle ) {
      args.push( '--mangle=false' );
    }
    if ( allHTML && brands[ 0 ] !== 'phet-io' ) {
      args.push( '--allHTML' );
    }
    if ( debugHTML ) {
      args.push( '--debugHTML' );
    }
  }
  // Chipper 2.0
  else if ( chipperVersion.major === 2 && chipperVersion.minor === 0 ) {
    args.push( `--brands=${brands.join( ',' )}` );
    args.push( `--locales=${locales}` );
    if ( !uglify ) {
      args.push( '--uglify=false' );
    }
    if ( !mangle ) {
      args.push( '--mangle=false' );
    }
    if ( !lint ) {
      args.push( '--lint=false' );
    }
    if ( allHTML ) {
      args.push( '--allHTML' );
    }
    if ( debugHTML ) {
      args.push( '--debugHTML' );
    }
  }
  else {
    throw new Error( `unsupported chipper version: ${chipperVersion.toString()}` );
  }

  const result = await execute( gruntCommand, args, `../${repo}` );

  // Examine output to see if getDependencies (in chipper) notices any missing phet-io things.
  // Fail out if so. Detects that specific error message.
  if ( brands.includes( 'phet-io' ) && result.includes( 'WARNING404' ) ) {
    throw new Error( 'phet-io dependencies missing' );
  }

  return result;
};
<|endoftext|>


<commit_before>define(["js/core/Bindable", "flow"], function (Bindable, flow) {

    var routeStripper = /^#?!?\/?/,
        undef,
        emptyCallback = function () {
        };

    var History = Bindable.inherit("js.core.History", {

        ctor: function () {
            this.callBase();
            this.$routers = [];
            this.$processUrl = true;

            this.$history = [];
        },

        defaults: {
            interval: 50
        },

        // TODO: make this bindable so that i can call this.fragment.triggerChange()

        /***
         * @Bindable
         * @return {String}
         */
        fragment: function() {
            return this.$fragment;
        }.on('change:fragment'),

        /***
         * determinate the current fragment
         * @return {String} the current fragment without the starting #/
         * @private
         */
        _getFragment: function () {
            var fragment;

            if (this.runsInBrowser()) {
                fragment = decodeURIComponent(window.location.hash);
            } else {
                fragment = this.$history[this.$history.length - 1] || "";
            }

            return fragment.replace(routeStripper, '');
        },

        start: function (callback, initialHash) {

            var self = this;
            this.$checkUrlFn = function () {
                self.checkUrl.apply(self, arguments);
            };

            if (this.runsInBrowser()) {
                // we're on a browser
                if ("onhashchange" in window) {
                    if (window.addEventListener) {
                        window.addEventListener('hashchange',
                            this.$checkUrlFn, false);
                    } else {
                        window.attachEvent('onhashchange', this.$checkUrlFn);
                    }
                } else {
                    // polling
                    this.$checkUrlInterval = setInterval(this.$checkUrlFn, this.$.interval);
                }
            } else {
                // rendering on node
                this.$history.push(initialHash || "");
            }

            this.navigate(this._getFragment(), true, true, callback);
            this.$processUrl = true;
        },

        stop: function () {
            if (typeof window !== "undefined") {
                if ("onhashchange" in window) {
                    if (window.removeEventListener) {
                        window.removeEventListener('hashchange',
                            this.$checkUrlFn, false);
                    } else {
                        window.detachEvent('onhashchange', this.$checkUrlFn);
                    }
                } else {
                    // polling
                    clearInterval(this.$checkUrlInterval);
                }
            }
        },

        addRouter: function (router) {
            this.$routers.push(router);
        },

        checkUrl: function (e) {

            if (this.$processUrl) {
                var currentFragment = this._getFragment();
                if (currentFragment == this.$fragment) {
                    return false;
                }

                this.navigate(currentFragment, true, true, emptyCallback);
            }

            this.$processUrl = true;

        },

        triggerRoute: function (fragment, callback) {

            var routeExecutionStack = [];

            for (var i = 0; i < this.$routers.length; i++) {
                routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment));
            }

            if (routeExecutionStack.length === 0) {
                console.log("no route for '" + fragment + "' found.");
                // no route found but
                if (callback) {
                    // execute callback
                    callback();
                }
            } else {
                flow()
                    .seqEach(routeExecutionStack, function(routingFunction, cb){
                        routingFunction(cb);
                    })
                    .exec(callback)
            }
        },

        navigate: function (fragment, createHistoryEntry, triggerRoute, callback) {

            var self = this;

            if (!callback && createHistoryEntry instanceof Function) {
                callback = createHistoryEntry;
                createHistoryEntry = null;
            }

            if (!callback && triggerRoute instanceof Function) {
                callback = triggerRoute;
                triggerRoute = null;
            }

            if (createHistoryEntry == undef || createHistoryEntry == null) {
                createHistoryEntry = true;
            }

            if (triggerRoute == undef || triggerRoute == null) {
                triggerRoute = true;
            }

            var eventData = {
                fragment: fragment,
                createHistoryEntry: createHistoryEntry,
                triggerRoute: triggerRoute
            };

            this.trigger(History.EVENTS.NAVIGATION_START, eventData);

            this.$processUrl = false;

            if (createHistoryEntry) {
                if (this.runsInBrowser()) {
                    window.location.hash = "/" + fragment;
                } else {
                    this.checkUrl(null);
                }
                this.$history.push(fragment);
            } else {
                if (this.runsInBrowser()) {
                    // replace hash
                    window.location.replace("#/" + fragment);
                }
                this.$history[this.$history.length - 1] = fragment;

            }

            if(this.$fragment !== fragment){
                this.$fragment = fragment;
                this.trigger('change:fragment', this.$fragment);
            }

            if (triggerRoute) {
                this.triggerRoute(fragment, function() {
                    self.trigger(History.EVENTS.NAVIGATION_COMPLETE, eventData);
                    if (callback) {
                        callback.apply(arguments);
                    }
                });
            } else {
                this.trigger(History.EVENTS.NAVIGATION_COMPLETE, eventData);
            }
        }
    });

    History.EVENTS = {
        NAVIGATION_START: "navigationStart",
        NAVIGATION_COMPLETE: "navigationComplete"
    };

    return History;
});<commit_msg>fixed scrolling for fragment change ...<commit_after>define(["js/core/Bindable", "flow"], function (Bindable, flow) {

    var routeStripper = /^#?!?\/?/,
        undef,
        scrollPositions = {},
        emptyCallback = function () {
        };

    var History = Bindable.inherit("js.core.History", {

        ctor: function () {
            this.callBase();
            this.$routers = [];
            this.$processUrl = true;

            this.$history = [];
        },

        defaults: {
            interval: 50
        },

        // TODO: make this bindable so that i can call this.fragment.triggerChange()

        /***
         * @Bindable
         * @return {String}
         */
        fragment: function() {
            return this.$fragment;
        }.on('change:fragment'),

        /***
         * determinate the current fragment
         * @return {String} the current fragment without the starting #/
         * @private
         */
        _getFragment: function () {
            var fragment;

            if (this.runsInBrowser()) {
                fragment = decodeURIComponent(window.location.hash);
            } else {
                fragment = this.$history[this.$history.length - 1] || "";
            }

            return fragment.replace(routeStripper, '');
        },

        start: function (callback, initialHash) {

            var self = this;
            this.$checkUrlFn = function () {
                self.checkUrl.apply(self, arguments);
            };

            if (this.runsInBrowser()) {
                // we're on a browser
                if ("onhashchange" in window) {
                    if (window.addEventListener) {
                        window.addEventListener('hashchange',
                            this.$checkUrlFn, false);
                    } else {
                        window.attachEvent('onhashchange', this.$checkUrlFn);
                    }
                } else {
                    // polling
                    this.$checkUrlInterval = setInterval(this.$checkUrlFn, this.$.interval);
                }
            } else {
                // rendering on node
                this.$history.push(initialHash || "");
            }

            this.navigate(this._getFragment(), true, true, callback);
            this.$processUrl = true;
        },

        stop: function () {
            if (typeof window !== "undefined") {
                if ("onhashchange" in window) {
                    if (window.removeEventListener) {
                        window.removeEventListener('hashchange',
                            this.$checkUrlFn, false);
                    } else {
                        window.detachEvent('onhashchange', this.$checkUrlFn);
                    }
                } else {
                    // polling
                    clearInterval(this.$checkUrlInterval);
                }
            }
        },

        addRouter: function (router) {
            this.$routers.push(router);
        },

        checkUrl: function (e) {

            if (this.$processUrl) {
                var currentFragment = this._getFragment();
                if (currentFragment == this.$fragment) {
                    return false;
                }
                this.navigate(currentFragment, true, true, emptyCallback);
            }

            this.$processUrl = true;

        },

        triggerRoute: function (fragment, callback) {

            var routeExecutionStack = [];

            for (var i = 0; i < this.$routers.length; i++) {
                routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment));
            }

            if (routeExecutionStack.length === 0) {
                console.log("no route for '" + fragment + "' found.");
                // no route found but
                if (callback) {
                    // execute callback
                    callback();
                }
            } else {
                flow()
                    .seqEach(routeExecutionStack, function(routingFunction, cb){
                        routingFunction(cb);
                    })
                    .exec(callback)
            }
        },

        navigate: function (fragment, createHistoryEntry, triggerRoute, callback) {
            console.log(window.scrollY, scrollPositions[fragment]);
            var self = this;

            if (!callback && createHistoryEntry instanceof Function) {
                callback = createHistoryEntry;
                createHistoryEntry = null;
            }

            if (!callback && triggerRoute instanceof Function) {
                callback = triggerRoute;
                triggerRoute = null;
            }

            if (createHistoryEntry == undef || createHistoryEntry == null) {
                createHistoryEntry = true;
            }

            if (triggerRoute == undef || triggerRoute == null) {
                triggerRoute = true;
            }

            var eventData = {
                fragment: fragment,
                createHistoryEntry: createHistoryEntry,
                triggerRoute: triggerRoute
            };

            this.trigger(History.EVENTS.NAVIGATION_START, eventData);

            this.$processUrl = false;

            if (createHistoryEntry) {
                if (this.runsInBrowser()) {
                    window.location.hash = "/" + fragment;
                } else {
                    this.checkUrl(null);
                }
                this.$history.push(fragment);
            } else {
                if (this.runsInBrowser()) {
                    // replace hash
                    window.location.replace("#/" + fragment);
                }
                this.$history[this.$history.length - 1] = fragment;

            }
            var scrollToTop = false;
            if(this.$fragment !== fragment){
                if(this.runsInBrowser()){
                    if(this.$fragment && window.scrollY !== scrollPositions[fragment]){
                        scrollToTop = true;
                        scrollPositions[this.$fragment] = window.scrollY;
                    }
                }
                this.$fragment = fragment;
                this.trigger('change:fragment', this.$fragment);
            }

            if (triggerRoute) {
                this.triggerRoute(fragment, function() {
                    self.trigger(History.EVENTS.NAVIGATION_COMPLETE, eventData);
                    if (callback) {
                        callback.apply(arguments);
                    }
                    if(scrollPositions[fragment] === undefined){
                        scrollPositions[fragment] = 0;
                    }
                    if(scrollToTop){
                        window.scrollTo(0,0);
                    }

                });
            } else {
                this.trigger(History.EVENTS.NAVIGATION_COMPLETE, eventData);
            }

        }
    });

    History.EVENTS = {
        NAVIGATION_START: "navigationStart",
        NAVIGATION_COMPLETE: "navigationComplete"
    };

    return History;
});<|endoftext|>


<commit_before>(function($) {
     window['Devtools'] = { //window represents the browser window
        //by putting it in window, it's essentially greating a global variable

        // development settings.
        //VERSION: 0.1,

        defaults: {
            logging: false,  // false to turn off logging
            production: false
        },

	get_rid : function(name) {

        var rids = {
            "rulesets": {"prod": "b507199x0.prod",
                          "dev": "b507199x0.dev"
            },
            "bootstrap":{"prod": "b507199x1.prod",
                          "dev": "b507199x1.dev"
            },
            "cloud_os":{"prod": "a169x625.prod",
                          "dev": "a169x625.prod"
            }
        };

	    return this.defaults.production ? rids[name].prod : rids[name].dev;
	},

    rid_eci: null, //fleet_eci
    rid_summary: {}, //vehicle_summary
    rid_list: [], //vehicles

    log: function() {
        if (this.defaults.logging && console && console.log) {
            [].unshift.call(arguments, "Devtools:"); // arguments is Array-like, it's not an Array
            console.log.apply(console, arguments);
        }
    },

    getProfile: function(channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
            Devtools.log("Retrieving profile for user");

        return CloudOS.skyCloud("a169x676", "get_all_me", {}, function(res) { //fix this up. what rule is this calling?
            CloudOS.clean(res);
            if(typeof cb !== "undefined"){
                cb(res);
            }
        },
        {"eci": channel});
    },

    bootstrapped: function(cb,options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("bootstrapped ??");
        return CloudOS.skyCloud(Devtools.get_rid("bootstrap"), "testingReturns", {}, function(json) {
            Devtools.log("Displaying testingReturns", json);
            cb(json);
        }, {"eci":eci});
    },

    getRulesets: function(cb, options) //almost like getProfile in fuse-api.js
    {

        cb = cb || function(){};
        options = options || {};
        //var rid = "rulesets";
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showRulesets", {}, function(json) {
            Devtools.log("Displaying rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    status: function(cb, options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        //return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "rulesetList", {}, function(json) {
        return CloudOS.skyCloud(Devtools.get_rid("cloud_os"), "rulesetList", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
// ---------- account ----------
    // this is called in _layouts/code.html when the account is created
    initAccount: function(attrs, cb, options)
        {
        cb = cb || function(){};
        options = options || {};
        attrs = attrs || {};
            Devtools.log("Initializing account for user with attributes ", attrs);

            return CloudOS.raiseEvent("devtools", "bootstrap", {}, {}, function(response)
            {
        // note that because the channel is create asynchronously, processing callback does
        // NOT mean the channel exists.
        //        Devtools.log("account initialized");
        if(response.length < 1) {
            throw "Account initialization failed";
        }
        cb(response);
            });
        },

    about: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Getting info about pico ");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "aboutPico", {}, function(json) {
            Devtools.log("This pico: ", json);
            cb(json);
        }, {"eci":eci});
    },

//---------the functions for updating rulesets

    updateUrl: function(rid, url, cb, options) //basing this off of updateCarvoyantVehicle
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating the URL");
        return CloudOS.raiseEvent("devtools", "update_url", json, {}, function(json) {
            Devtools.log("Directive from updating URL", json);
            cb(json);
        }, {"eci":eci});
    },

    flushRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Flushing RID " + rid);
        return CloudOS.raiseEvent("devtools", "flush_rid", json, {}, function(json) {
            Devtools.log("Directive from Flushing Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    deleteRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Deleting RID " + rid);
        return CloudOS.raiseEvent("devtools", "delete_rid", json, {}, function(json) {
            Devtools.log("Directive from Deleting Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    showInstalledRulesets: function(cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledRulesets", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    installRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing rulesets");
        return CloudOS.raiseEvent("devtools", "install_rulesets", json, {}, function(json) {
            Devtools.log("Directive from installing rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    uninstallRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Uninstalling rulesets");
        return CloudOS.raiseEvent("devtools", "uninstall_rulesets", json, {}, function(json) {
            Devtools.log("Directive from uninstalling rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
    RegisterRuleset: function(url,cb,options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {rulesetURL: url}; // json for attribute thats passed to the ruleset as eventattribute
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Registering rulesets");
        return CloudOS.raiseEvent("devtools", "register_ruleset", json, {}, function(json) {
            Devtools.log("Directive from register ruleset", json);
            cb(json);
        }, {"eci":eci});
    },

    //--------------------------------Channels mannagement----------------------
    showInstalledChannels: function(cb, options) // copied PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledChannels", {}, function(json) {
            Devtools.log("Displaying installed channels", json);
            cb(json);
        }, {"eci":eci});
    },
    installChannel: function(channel_name, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("devtools", "create_channel", parameters,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
       }, {"eci":eci});
    },
    uninstallChannel: function(ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {channelID:ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Destroy channels");
        return CloudOS.raiseEvent("devtools", "channel_destroy", json,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
        }, {"eci":eci});

    },
    //---------------------------------Authorize Client mannagement----------------
    authorizeClient: function(app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("authorizing clientlient ");
       return CloudOS.raiseEvent("devtools", "authorize_client", app_Data,{}, function(json) {
           Devtools.log("Directive from AuthorizeClient", json);
           cb(json);
       }, {"eci":eci});
    },
	showAthorizedClients: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the showing clients");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showClients", {}, function(json) {
            Devtools.log("Displaying athorize clients", json);
            cb(json);
        }, {"eci":eci});
    },
    removeClient: function(app_ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {"appECI":app_ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("remove client");
        console.log("attributes",json);
        return CloudOS.raiseEvent("devtools", "remove_client", json,{}, function(json) {
           Devtools.log("Directive from remove client", json);
           cb(json);
        }, {"eci":eci});
    },
    updateClient: function(app_ECI, app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        app_Data["appECI"]=app_ECI;
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating client");
        return CloudOS.raiseEvent("devtools", "update_client", app_Data, {}, function(json) {
            Devtools.log("Directive from updating Client", json);
            cb(json);
        }, {"eci":eci});
    },

    showScheduledEvents: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show scheduled events");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showScheduleEvents", {}, function(json) {
            Devtools.log("Displaying scheduled events", json);
            cb(json);
        }, {"eci":eci});
    },
    scheduleEvent: function(Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("scheduling event");
       return CloudOS.raiseEvent("devtools", "event_scheduled", Data,{}, function(json) {
           Devtools.log("Directive from ScheduleEvent", json);
           cb(json);
       }, {"eci":eci});
    },
    //-------------------Subscriptions--------------------
    showSubscriptions: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Subscriptions");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showSubscriptions", {}, function(json) {
            Devtools.log("Displaying showSubscriptions", json);
            cb(json);
        }, {"eci":eci});
    },
    showIncoming: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Incoming");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showIncoming", {}, function(json) {
            Devtools.log("Displaying showIncoming", json);
            cb(json);
        }, {"eci":eci});
    },
    showOutGoing: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show OutGoing");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showOutGoing", {}, function(json) {
            Devtools.log("Displaying showOutGoing", json);
            cb(json);
        }, {"eci":eci});
    },

   //TESTING CODE WRITTEN IN NANO MANAGER
   scheduleEvent: function(data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("nano_manager", "scheduled_event", data,{}, function(json) {
           Devtools.log("Creating a scheduled event", json);
           cb(json);
       }, {"eci":eci});
    }
//
}; //closes the "window" inside the function DON'T DELETE

//----------------------------------

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj === null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
                if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;

        }

})(jQuery);
<commit_msg>subscriptions<commit_after>(function($) {
     window['Devtools'] = { //window represents the browser window
        //by putting it in window, it's essentially greating a global variable

        // development settings.
        //VERSION: 0.1,

        defaults: {
            logging: false,  // false to turn off logging
            production: false
        },

	get_rid : function(name) {

        var rids = {
            "rulesets": {"prod": "b507199x0.prod",
                          "dev": "b507199x0.dev"
            },
            "bootstrap":{"prod": "b507199x1.prod",
                          "dev": "b507199x1.dev"
            },
            "cloud_os":{"prod": "a169x625.prod",
                          "dev": "a169x625.prod"
            }
        };

	    return this.defaults.production ? rids[name].prod : rids[name].dev;
	},

    rid_eci: null, //fleet_eci
    rid_summary: {}, //vehicle_summary
    rid_list: [], //vehicles

    log: function() {
        if (this.defaults.logging && console && console.log) {
            [].unshift.call(arguments, "Devtools:"); // arguments is Array-like, it's not an Array
            console.log.apply(console, arguments);
        }
    },

    getProfile: function(channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
            Devtools.log("Retrieving profile for user");

        return CloudOS.skyCloud("a169x676", "get_all_me", {}, function(res) { //fix this up. what rule is this calling?
            CloudOS.clean(res);
            if(typeof cb !== "undefined"){
                cb(res);
            }
        },
        {"eci": channel});
    },

    bootstrapped: function(cb,options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("bootstrapped ??");
        return CloudOS.skyCloud(Devtools.get_rid("bootstrap"), "testingReturns", {}, function(json) {
            Devtools.log("Displaying testingReturns", json);
            cb(json);
        }, {"eci":eci});
    },

    getRulesets: function(cb, options) //almost like getProfile in fuse-api.js
    {

        cb = cb || function(){};
        options = options || {};
        //var rid = "rulesets";
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showRulesets", {}, function(json) {
            Devtools.log("Displaying rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    status: function(cb, options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        //return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "rulesetList", {}, function(json) {
        return CloudOS.skyCloud(Devtools.get_rid("cloud_os"), "rulesetList", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
// ---------- account ----------
    // this is called in _layouts/code.html when the account is created
    initAccount: function(attrs, cb, options)
        {
        cb = cb || function(){};
        options = options || {};
        attrs = attrs || {};
            Devtools.log("Initializing account for user with attributes ", attrs);

            return CloudOS.raiseEvent("devtools", "bootstrap", {}, {}, function(response)
            {
        // note that because the channel is create asynchronously, processing callback does
        // NOT mean the channel exists.
        //        Devtools.log("account initialized");
        if(response.length < 1) {
            throw "Account initialization failed";
        }
        cb(response);
            });
        },

    about: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Getting info about pico ");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "aboutPico", {}, function(json) {
            Devtools.log("This pico: ", json);
            cb(json);
        }, {"eci":eci});
    },

//---------the functions for updating rulesets

    updateUrl: function(rid, url, cb, options) //basing this off of updateCarvoyantVehicle
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating the URL");
        return CloudOS.raiseEvent("devtools", "update_url", json, {}, function(json) {
            Devtools.log("Directive from updating URL", json);
            cb(json);
        }, {"eci":eci});
    },

    flushRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Flushing RID " + rid);
        return CloudOS.raiseEvent("devtools", "flush_rid", json, {}, function(json) {
            Devtools.log("Directive from Flushing Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    deleteRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Deleting RID " + rid);
        return CloudOS.raiseEvent("devtools", "delete_rid", json, {}, function(json) {
            Devtools.log("Directive from Deleting Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    showInstalledRulesets: function(cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledRulesets", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    installRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing rulesets");
        return CloudOS.raiseEvent("devtools", "install_rulesets", json, {}, function(json) {
            Devtools.log("Directive from installing rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    uninstallRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Uninstalling rulesets");
        return CloudOS.raiseEvent("devtools", "uninstall_rulesets", json, {}, function(json) {
            Devtools.log("Directive from uninstalling rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
    RegisterRuleset: function(url,cb,options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {rulesetURL: url}; // json for attribute thats passed to the ruleset as eventattribute
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Registering rulesets");
        return CloudOS.raiseEvent("devtools", "register_ruleset", json, {}, function(json) {
            Devtools.log("Directive from register ruleset", json);
            cb(json);
        }, {"eci":eci});
    },

    //--------------------------------Channels mannagement----------------------
    showInstalledChannels: function(cb, options) // copied PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledChannels", {}, function(json) {
            Devtools.log("Displaying installed channels", json);
            cb(json);
        }, {"eci":eci});
    },
    installChannel: function(channel_name, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("devtools", "create_channel", parameters,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
       }, {"eci":eci});
    },
    uninstallChannel: function(ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {channelID:ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Destroy channels");
        return CloudOS.raiseEvent("devtools", "channel_destroy", json,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
        }, {"eci":eci});

    },
    //---------------------------------Authorize Client mannagement----------------
    authorizeClient: function(app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("authorizing clientlient ");
       return CloudOS.raiseEvent("devtools", "authorize_client", app_Data,{}, function(json) {
           Devtools.log("Directive from AuthorizeClient", json);
           cb(json);
       }, {"eci":eci});
    },
	showAthorizedClients: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the showing clients");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showClients", {}, function(json) {
            Devtools.log("Displaying athorize clients", json);
            cb(json);
        }, {"eci":eci});
    },
    removeClient: function(app_ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {"appECI":app_ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("remove client");
        console.log("attributes",json);
        return CloudOS.raiseEvent("devtools", "remove_client", json,{}, function(json) {
           Devtools.log("Directive from remove client", json);
           cb(json);
        }, {"eci":eci});
    },
    updateClient: function(app_ECI, app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        app_Data["appECI"]=app_ECI;
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating client");
        return CloudOS.raiseEvent("devtools", "update_client", app_Data, {}, function(json) {
            Devtools.log("Directive from updating Client", json);
            cb(json);
        }, {"eci":eci});
    },

    showScheduledEvents: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show scheduled events");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showScheduleEvents", {}, function(json) {
            Devtools.log("Displaying scheduled events", json);
            cb(json);
        }, {"eci":eci});
    },
    scheduleEvent: function(Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("scheduling event");
       return CloudOS.raiseEvent("devtools", "event_scheduled", Data,{}, function(json) {
           Devtools.log("Directive from ScheduleEvent", json);
           cb(json);
       }, {"eci":eci});
    },
    //-------------------Subscriptions--------------------
    showSubscriptions: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Subscriptions");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showSubscriptions", {}, function(json) {
            Devtools.log("Displaying showSubscriptions", json);
            cb(json);
        }, {"eci":eci});
    },
    showIncoming: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Incoming");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showIncoming", {}, function(json) {
            Devtools.log("Displaying showIncoming", json);
            cb(json);
        }, {"eci":eci});
    },
    showOutGoing: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show OutGoing");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showOutGoing", {}, function(json) {
            Devtools.log("Displaying showOutGoing", json);
            cb(json);
        }, {"eci":eci});
    },
    ApproveSubscription: function(event_channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("approve subscription");
       return CloudOS.raiseEvent("devtools", "incoming_request_approved", event_channel,{}, function(json) {
           Devtools.log("Directive from ApproveSubscription", json);
           cb(json);
       }, {"eci":eci});
    },

   //TESTING CODE WRITTEN IN NANO MANAGER
   scheduleEvent: function(data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("nano_manager", "scheduled_event", data,{}, function(json) {
           Devtools.log("Creating a scheduled event", json);
           cb(json);
       }, {"eci":eci});
    }
//
}; //closes the "window" inside the function DON'T DELETE

//----------------------------------

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj === null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
                if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;

        }

})(jQuery);
<|endoftext|>