<commit_before>var actions = require('./actions');
import {
  normalize,
  arrayOf
} from 'normalizr';
import {
  boardsSchema
} from './board-schema';
import Immutable from 'seamless-immutable';

const initialRepositoryState = Immutable({
  boards: {},
  cardsList: {},
  cards: {}
});

function deserialize(state, action) {
  const normalizedBoard = normalize(action, {
    boards: arrayOf(boardsSchema)
  });
  //merge new entities into state
  return state.merge(normalizedBoard.entities);
}
/*
* Function to deal with creating a board, cardslist, or card and
* adding it to state
* params state- old state before merge
* params action- action with data to update state
*/
function createBoard(state, action) {
  //normalize boards
  const normalizedBoard = normalize(action, {
    boards: arrayOf(boardsSchema)
  });
  //create empty object
  var newState = {};
  //if there is a board
  if (normalizedBoard.entities.boards){
    //merge and store in newstate
    newState.boards = state.boards.merge(normalizedBoard.entities.boards);
  }
  //if there is a cardsList
  if (normalizedBoard.entities.cardsList) {
    //merge and store in newstate
    newState.cardsList = state.cardsList.merge(normalizedBoard.entities.cardsList);
  }
  //if there is a card
  if (normalizedBoard.entities.cards) {
    //merge and store in newstate
    newState.cards = state.cards.merge(normalizedBoard.entities.cards);
  }
  return state.merge(newState);
}
/*
* Function to deal with deleting a board, cardslist or card
* and removing it from state
* params state- old state before merge
* params action- action with data to update state
*/
function deleteBoard(state, action) {
  //normalize boards
  const normalizedBoard = normalize(action, {
    boards: arrayOf(boardsSchema)
  });
  //create empty object
  var newState = {};
  //if there is a board
  if (normalizedBoard.entities.boards){
    //remove it from state and store in newstate
    newState.boards = Immutable.without(state.boards,
        Object.keys(normalizedBoard.entities.boards));
  }
  //if there is a cardsList
  if (normalizedBoard.entities.cardsList) {
    //remove it from state and store in newstate
    newState.cardsList = Immutable.without(state.cardsList,
       Object.keys(normalizedBoard.entities.boards));
  }
  //if there is a card
  if (normalizedBoard.entities.cards) {
    //remove it from state and store in newstate
    newState.cards = Immutable.without(state.cards,
       Object.keys(normalizedBoard.entities.cards));
  }
  return state = Immutable({
    boards: newState.boards || {},
    cardsList: newState.cardsList || {},
    cards: newState.cards || {}
  });
}

function trelloReducer(state, action) {
  state = state || initialRepositoryState;
  //reducer for adding a board
  if (action.type === actions.BOARD_DESERIALIZATION ||
    action.type === actions.FIND_BOARDS_SUCCESS) {
    return deserialize(state, action);
    //reducer for adding a b
  } else if (action.type === actions.CREATE_BOARD_SUCCESS ||
    action.type === actions.CREATE_CARDLIST_SUCCESS ||
    action.type === actions.CREATE_CARD_SUCCESS) {
    return createBoard(state, action);
  } else if (action.type === actions.DELETE_BOARD_SUCCESS ||
    action.type === actions.DELETE_CARDSLIST_SUCCESS ||
    action.type === action.type === actions.DELETE_CARDS_SUCCESS) {
    return deleteBoard(state, action);
  } else {
    return state;
  }
}
exports.trelloReducer = trelloReducer;
<commit_msg>Changed from arrayof boardschema to just the object boardschema for create and delete board to fix minor bug.<commit_after>var actions = require('./actions');
import {
  normalize,
  arrayOf
} from 'normalizr';
import {
  boardsSchema
} from './board-schema';
import Immutable from 'seamless-immutable';

const initialRepositoryState = Immutable({
  boards: {},
  cardsList: {},
  cards: {}
});

function deserialize(state, action) {
  const normalizedBoard = normalize(action, {
    boards: arrayOf(boardsSchema)
  });
  //merge new entities into state
  return state.merge(normalizedBoard.entities);
}
/*
* Function to deal with creating a board, cardslist, or card and
* adding it to state
* params state- old state before merge
* params action- action with data to update state
*/
function createBoard(state, action) {
  //normalize boards
  const normalizedBoard = normalize(action, {
    boards: boardsSchema
  });
  //create empty object
  var newState = {};
  //if there is a board
  if (normalizedBoard.entities.boards){
    //merge and store in newstate
    newState.boards = state.boards.merge(normalizedBoard.entities.boards);
  }
  //if there is a cardsList
  if (normalizedBoard.entities.cardsList) {
    //merge and store in newstate
    newState.cardsList = state.cardsList.merge(normalizedBoard.entities.cardsList);
  }
  //if there is a card
  if (normalizedBoard.entities.cards) {
    //merge and store in newstate
    newState.cards = state.cards.merge(normalizedBoard.entities.cards);
  }
  return state.merge(newState);
}
/*
* Function to deal with deleting a board, cardslist or card
* and removing it from state
* params state- old state before merge
* params action- action with data to update state
*/
function deleteBoard(state, action) {
  //normalize boards
  const normalizedBoard = normalize(action, {
    boards: boardsSchema
  });
  //create empty object
  var newState = {};
  //if there is a board
  if (normalizedBoard.entities.boards){
    //remove it from state and store in newstate
    newState.boards = Immutable.without(state.boards,
        Object.keys(normalizedBoard.entities.boards));
  }
  //if there is a cardsList
  if (normalizedBoard.entities.cardsList) {
    //remove it from state and store in newstate
    newState.cardsList = Immutable.without(state.cardsList,
       Object.keys(normalizedBoard.entities.boards));
  }
  //if there is a card
  if (normalizedBoard.entities.cards) {
    //remove it from state and store in newstate
    newState.cards = Immutable.without(state.cards,
       Object.keys(normalizedBoard.entities.cards));
  }
  return state = Immutable({
    boards: newState.boards || {},
    cardsList: newState.cardsList || {},
    cards: newState.cards || {}
  });
}

function trelloReducer(state, action) {
  state = state || initialRepositoryState;
  //reducer for adding a board
  if (action.type === actions.BOARD_DESERIALIZATION ||
    action.type === actions.FIND_BOARDS_SUCCESS) {
    return deserialize(state, action);
    //reducer for adding a b
  } else if (action.type === actions.CREATE_BOARD_SUCCESS ||
    action.type === actions.CREATE_CARDLIST_SUCCESS ||
    action.type === actions.CREATE_CARD_SUCCESS) {
    return createBoard(state, action);
  } else if (action.type === actions.DELETE_BOARD_SUCCESS ||
    action.type === actions.DELETE_CARDSLIST_SUCCESS ||
    action.type === action.type === actions.DELETE_CARDS_SUCCESS) {
    return deleteBoard(state, action);
  } else {
    return state;
  }
}
exports.trelloReducer = trelloReducer;
<|endoftext|>


<commit_before>/*
 * freepano - WebGL panorama viewer
 *
 * Copyright (c) 2014 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Kevin Velickovic <k.velickovic@foxel.ch>
 *
 *
 * Contributor(s):
 *
 *      Luc Deschenaux <l.deschenaux@foxel.ch>
 *      Alexandre Kraft
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

// Plugin constructor
function Map(options)
{
    if (!(this instanceof Map)) {
      return new Map(options);
    }

    // merge specified options with default options and extend this instance
    $.extend(true,this,Map.prototype.defaults,options);

    // Initialize plugin
    this.init();
}

// Extend plugin prototype
$.extend(true, Map.prototype, {

    // default values
    defaults: {
        // active
        active: true,

        // leaflet defaults
        leaflet: {

            // see http://leafletjs.com/reference.html#tilelayer-options
            tileLayer: {

                url_template: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',

                options: {
                     attribution: '© OpenStreetMap contributors'
                }

            },

            origin: [51.505, -0.09], // default geographical coordinates

            zoom: {
                base: 4,
                min: 3,
                max: 25,
                native: 18,
                bounds: 18
            },

            // see http://leafletjs.com/reference.html#map-zoompanoptions
            zoompan_options: undefined,

            icon: {
                iconUrl: 'img/marker_icon.png', // marker icon url
                shadowUrl: 'img/marker_shadow.png', // marker shadow image url
                iconSize: [22.5, 36.25], // marker size
                shadowSize: [40.75, 36.25], // marker shadow size
                iconAnchor: [22.5/2, 36.25], // point corresponding to marker's location
                shadowAnchor: [22.5/2, 36.25],
                popupAnchor: [0, 0] // point from which menu should popup relative to the iconAnchor
            },

            icon_highlighted: {
                iconUrl:     'img/marker_icon_highlight.png',
                shadowUrl:   'img/marker_shadow.png'
            }
        }
    },

    show: function map_show() {

        var map=this;
        var panorama = map.panorama;

        // map container exists ?
        if (map.container && map.container.length) {
            // then show map if hidden and/or return
            if (!$(map.container).is(':visible')) {
                map.container.show();
                map.callback('ready');
            }
            return;
        }

        // Append map
        map.container = $('
',{'class':'map'});
        $(panorama.container).append(map.container);

        // Create leaflet map object
        var leaflet = map.leaflet.instance = L.map(map.container[0], {
            keyboard: false,
            scrollWheelZoom: true,
            minZoom: map.leaflet.zoom.min,
            maxZoom: map.leaflet.zoom.max
        }).setView(map.leaflet.origin, map.leaflet.zoom.base, map.leaflet.zoompan_options);

        // add a tile layer
        L.tileLayer(map.leaflet.tileLayer.url_template, $.extend(true,{},map.leaflet.tileLayer.options,{
            minZoom: map.leaflet.zoom.min,
            maxZoom: map.leaflet.zoom.max,
            maxNativeZoom: map.leaflet.zoom.native
        })).addTo(leaflet);

        // Create marker icon
        map.markerIcon = L.icon(map.leaflet.icon);

        // Create highlighted marker icon
        map.markerIcon_Highlighted = L.icon($.extend(true,{},map.leaflet.icon,map.leaflet.icon_highlighted));

        var markers = map.markers = [];

        // Iterate over panoramas and create markers
        $.each(panorama.list.images, function( index, image ) {

            // No geo coordinates
            if (image.coords === undefined || image.coords === null)
                return;

            // Use initial image if set and currentImage is not defined
            if (panorama.list.currentImage === undefined && panorama.list.initialImage !== undefined)
                panorama.list.currentImage = panorama.list.initialImage;

            // Use first image if currentImage is not defined
            else if (panorama.list.currentImage === undefined)
                panorama.list.currentImage = Object.keys(panorama.list.images)[0];

            // set marker icon
            var icon = (panorama.list.currentImage==index) ?
              map.markerIcon_Highlighted :
              map.markerIcon;

            // Create marker
            var marker = L.marker([image.coords.lat, image.coords.lon], {icon: icon})
            .on('click', function(e) {

                var panorama=e.target.panorama.instance;
                var map=panorama.map.instance;

                // Check if panorama has changed, then change it
                var changed = (e.target.panorama.index != panorama.list.currentImage);

                if (changed) {

                  // Reset current marker to default icon
                  if (map.currentMarker) {
                    map.currentMarker.setIcon(map.markerIcon);
                  }

                  // Set target marker icon
                  e.target.setIcon(map.markerIcon_Highlighted);

                  map.currentMarker=e.target;
                  panorama.list.show(e.target.panorama.index);

                }

                // Spread event
                $(map).trigger('markerclick',{changed:changed,target:e.target.panorama.index});

            });

            if (panorama.list.currentImage==index) {
              map.currentMarker=marker;
            }

            // Reference panorama instance and list index
            marker.panorama={
              instance: panorama,
              index: index
            };

            // Add marker to array
            markers.push( marker )

            // Add marker to map
            marker.addTo(leaflet)

        });

        // No elligible markers
        if (markers.length == 0) {
            this.hide();
            return;
        }

        // Create makers featureGroup
        var markersGroup = new L.featureGroup(markers);

        // Fit map to markers
        leaflet.fitBounds(markersGroup.getBounds());

        // Unzoom from bounds
        if (leaflet.getZoom() > map.leaflet.zoom.bounds)
            leaflet.setZoom(map.leaflet.zoom.bounds);
        else
            leaflet.setZoom(leaflet.getZoom()-1);

        // map is ready
        map.callback('ready');

    }, // map_show

    hide: function map_hide() {
        $('.map',this.panorama.container).hide();
    },

    remove: function map_remove() {
        $('.map',this.panorama.container).remove();
    },

    on_panorama_ready: function map_on_panorama_ready() {

        var panorama=this;

        // skip Map instantiation if map preferences undefined in panorama
        if (panorama.map!==undefined) {

          // or if map is already instantiated
          if (!(panorama.map.instance instanceof Map)) {

            // instantiate map
            var map=panorama.map.instance=new Map($.extend(true,{

              // pass panorama instance pointer to map instance
              panorama: panorama

            },panorama.map));

          }

          if (map && map.active) map.show();

          panorama.map.instance.updateCurrentMarker();

        }

    }, // map_on_panorama_ready

    init: function map_init() {

        var map=this;

        // set watcher for active flag
        watch(map,['active'], function() {
            if (map.active)
                map.show();
            else
                map.hide();
        });

    }, // map_init

    updateCurrentMarker: function(){
      var map=this;
      var currentImage=map.panorama.list.currentImage;
      map.currentMarker.setIcon(map.markerIcon);
      $.each(map.markers,function(){
        var marker=this;
        if (marker.panorama.index==currentImage) {
          map.currentMarker=marker;
          marker.setIcon(map.markerIcon_Highlighted);
          return false;
        }
      });
    },

    callback: function map_callback(e) {

        var map=this;
        if (typeof(e)=='string') {
          e={
            type: e,
            target: map
          }
        }

        var method='on'+e.type;
        if (map[method]) {
          if (map[method].apply(map,[e])===false) {
            return false;
          }
        }

    } // map_callback

});

// subscribe to panorama events
Panorama.prototype.setupCallback(Map.prototype);
<commit_msg>map.js: dont try to update current marker when map is not instantiated<commit_after>/*
 * freepano - WebGL panorama viewer
 *
 * Copyright (c) 2014 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Kevin Velickovic <k.velickovic@foxel.ch>
 *
 *
 * Contributor(s):
 *
 *      Luc Deschenaux <l.deschenaux@foxel.ch>
 *      Alexandre Kraft
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

// Plugin constructor
function Map(options)
{
    if (!(this instanceof Map)) {
      return new Map(options);
    }

    // merge specified options with default options and extend this instance
    $.extend(true,this,Map.prototype.defaults,options);

    // Initialize plugin
    this.init();
}

// Extend plugin prototype
$.extend(true, Map.prototype, {

    // default values
    defaults: {
        // active
        active: true,

        // leaflet defaults
        leaflet: {

            // see http://leafletjs.com/reference.html#tilelayer-options
            tileLayer: {

                url_template: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',

                options: {
                     attribution: '© OpenStreetMap contributors'
                }

            },

            origin: [51.505, -0.09], // default geographical coordinates

            zoom: {
                base: 4,
                min: 3,
                max: 25,
                native: 18,
                bounds: 18
            },

            // see http://leafletjs.com/reference.html#map-zoompanoptions
            zoompan_options: undefined,

            icon: {
                iconUrl: 'img/marker_icon.png', // marker icon url
                shadowUrl: 'img/marker_shadow.png', // marker shadow image url
                iconSize: [22.5, 36.25], // marker size
                shadowSize: [40.75, 36.25], // marker shadow size
                iconAnchor: [22.5/2, 36.25], // point corresponding to marker's location
                shadowAnchor: [22.5/2, 36.25],
                popupAnchor: [0, 0] // point from which menu should popup relative to the iconAnchor
            },

            icon_highlighted: {
                iconUrl:     'img/marker_icon_highlight.png',
                shadowUrl:   'img/marker_shadow.png'
            }
        }
    },

    show: function map_show() {

        var map=this;
        var panorama = map.panorama;

        // map container exists ?
        if (map.container && map.container.length) {
            // then show map if hidden and/or return
            if (!$(map.container).is(':visible')) {
                map.container.show();
                map.callback('ready');
            }
            return;
        }

        // Append map
        map.container = $('
',{'class':'map'});
        $(panorama.container).append(map.container);

        // Create leaflet map object
        var leaflet = map.leaflet.instance = L.map(map.container[0], {
            keyboard: false,
            scrollWheelZoom: true,
            minZoom: map.leaflet.zoom.min,
            maxZoom: map.leaflet.zoom.max
        }).setView(map.leaflet.origin, map.leaflet.zoom.base, map.leaflet.zoompan_options);

        // add a tile layer
        L.tileLayer(map.leaflet.tileLayer.url_template, $.extend(true,{},map.leaflet.tileLayer.options,{
            minZoom: map.leaflet.zoom.min,
            maxZoom: map.leaflet.zoom.max,
            maxNativeZoom: map.leaflet.zoom.native
        })).addTo(leaflet);

        // Create marker icon
        map.markerIcon = L.icon(map.leaflet.icon);

        // Create highlighted marker icon
        map.markerIcon_Highlighted = L.icon($.extend(true,{},map.leaflet.icon,map.leaflet.icon_highlighted));

        var markers = map.markers = [];

        // Iterate over panoramas and create markers
        $.each(panorama.list.images, function( index, image ) {

            // No geo coordinates
            if (image.coords === undefined || image.coords === null)
                return;

            // Use initial image if set and currentImage is not defined
            if (panorama.list.currentImage === undefined && panorama.list.initialImage !== undefined)
                panorama.list.currentImage = panorama.list.initialImage;

            // Use first image if currentImage is not defined
            else if (panorama.list.currentImage === undefined)
                panorama.list.currentImage = Object.keys(panorama.list.images)[0];

            // set marker icon
            var icon = (panorama.list.currentImage==index) ?
              map.markerIcon_Highlighted :
              map.markerIcon;

            // Create marker
            var marker = L.marker([image.coords.lat, image.coords.lon], {icon: icon})
            .on('click', function(e) {

                var panorama=e.target.panorama.instance;
                var map=panorama.map.instance;

                // Check if panorama has changed, then change it
                var changed = (e.target.panorama.index != panorama.list.currentImage);

                if (changed) {

                  // Reset current marker to default icon
                  if (map.currentMarker) {
                    map.currentMarker.setIcon(map.markerIcon);
                  }

                  // Set target marker icon
                  e.target.setIcon(map.markerIcon_Highlighted);

                  map.currentMarker=e.target;
                  panorama.list.show(e.target.panorama.index);

                }

                // Spread event
                $(map).trigger('markerclick',{changed:changed,target:e.target.panorama.index});

            });

            if (panorama.list.currentImage==index) {
              map.currentMarker=marker;
            }

            // Reference panorama instance and list index
            marker.panorama={
              instance: panorama,
              index: index
            };

            // Add marker to array
            markers.push( marker )

            // Add marker to map
            marker.addTo(leaflet)

        });

        // No elligible markers
        if (markers.length == 0) {
            this.hide();
            return;
        }

        // Create makers featureGroup
        var markersGroup = new L.featureGroup(markers);

        // Fit map to markers
        leaflet.fitBounds(markersGroup.getBounds());

        // Unzoom from bounds
        if (leaflet.getZoom() > map.leaflet.zoom.bounds)
            leaflet.setZoom(map.leaflet.zoom.bounds);
        else
            leaflet.setZoom(leaflet.getZoom()-1);

        // map is ready
        map.callback('ready');

    }, // map_show

    hide: function map_hide() {
        $('.map',this.panorama.container).hide();
    },

    remove: function map_remove() {
        $('.map',this.panorama.container).remove();
    },

    on_panorama_ready: function map_on_panorama_ready() {

        var panorama=this;

        // skip Map instantiation if map preferences undefined in panorama
        if (panorama.map!==undefined) {

          // or if map is already instantiated
          if (!(panorama.map.instance instanceof Map)) {

            // instantiate map
            panorama.map.instance=new Map($.extend(true,{

              // pass panorama instance pointer to map instance
              panorama: panorama

            },panorama.map));

          }

          if (panorama.map.instance && panorama.map.instance.active) {
            panorama.map.instance.show();
            pnaorama.map.instance.updateCurrentMarker();
          }

        }

    }, // map_on_panorama_ready

    init: function map_init() {

        var map=this;

        // set watcher for active flag
        watch(map,['active'], function() {
            if (map.active)
                map.show();
            else
                map.hide();
        });

    }, // map_init

    updateCurrentMarker: function(){
      var map=this;
      var currentImage=map.panorama.list.currentImage;
      map.currentMarker.setIcon(map.markerIcon);
      $.each(map.markers,function(){
        var marker=this;
        if (marker.panorama.index==currentImage) {
          map.currentMarker=marker;
          marker.setIcon(map.markerIcon_Highlighted);
          return false;
        }
      });
    },

    callback: function map_callback(e) {

        var map=this;
        if (typeof(e)=='string') {
          e={
            type: e,
            target: map
          }
        }

        var method='on'+e.type;
        if (map[method]) {
          if (map[method].apply(map,[e])===false) {
            return false;
          }
        }

    } // map_callback

});

// subscribe to panorama events
Panorama.prototype.setupCallback(Map.prototype);
<|endoftext|>


<commit_before>// mouseIsPressed is a variable. in this example
// the state of it gets checked every time draw is called
// so the ellipse keeps growing as you hold down the mouse

// var d = 10;

// function setup() {
//   createCanvas(600, 400);
// }

// function draw() {
//   background(200);
//   if (mouseIsPressed) {
//     d++;
//   }
//   ellipse(width/2, height/2, d, d);
// }

// compare to below!
// mousePressed is a function that gets called
// once for each click of the mouse. so each click
// makes the mouse grow, but you must release and click
// again to keep increasing the size.

var d = "hello";

function setup() {
  createCanvas(600, 400);
}

function draw() {
  background(200);
  text(d, 50, 50);
  print("ab" > "ae");
  print("ab" < "ae");
}

<commit_msg>added mousePressed() example<commit_after>// mouseIsPressed is a variable. in this example
// the state of it gets checked every time draw is called
// so the ellipse keeps growing as you hold down the mouse

var d = 10;

function setup() {
  createCanvas(600, 400);
}

function draw() {
  background(200);
  // if (mouseIsPressed) {
  //   d++;
  // }

  ellipse(width/2, height/2, d, d);
}

// function mousePressed(){
//   d++;
//   return false;
// }

// compare to below!
// mousePressed is a function that gets called
// once for each click of the mouse. so each click
// makes the mouse grow, but you must release and click
// again to keep increasing the size.

// var d = "hello";
//
// function setup() {
//   createCanvas(600, 400);
// }
//
// function draw() {
//   background(200);
//   text(d, 50, 50);
//   print("ab" > "ae");
//   print("ab" < "ae");
// }
<|endoftext|>


<commit_before>jQuery.fn.versionSelector = function(versions, sizes) {
    $(this).each(function() {
        new jQuery.versionSelector(this, versions, sizes);
    })
}

jQuery.versionSelector = function(element, versions, sizes) {
    var _this = this,
        guid = 0;

    this.init = function() {
        this.selects = [];
        this.inputs = [];
        this.unknownSize = false;

        this.gemVersions = [];
        for (var i=0, l = versions.length; i < l; i++) {
            switch (versions[i].name.toLowerCase()) {
                case 'ruby':
                    this.rubyVersions = versions[i];
                    break;
                case 'rails':
                    this.railsVersions = versions[i];
                    break;
                default:
                    this.gemVersions.push(versions[i]);
            }
        };
    }

    this.bindEvents = function() {
        $('.preset', element).click(this.presetClick);
        $('#download, #browse').click(this.downloadClick);
    }

    this.downloadClick = function() {
        if (_this.unknownSize) $('.build-message').show()
    }

    this.presetClick = function() {
        if ($(this).hasClass('preset_ruby')) {
            _this.setHrefs([
                [_this.railsVersions.href, _this.railsVersions.versions[0]],
                [_this.rubyVersions.href, _this.rubyVersions.versions[0]]
            ]);
            _this.close();
        } else if ($(this).hasClass('preset_rails')) {
            _this.setHrefs([
                [_this.railsVersions.href, _this.railsVersions.versions[0]]
            ]);
            _this.close();
        } else {
            _this.open();
        }

        $('.preset_selected', element).removeClass('preset_selected');
        $(this).addClass('preset_selected');
    }

    this.close = function() {
        if (this.$form) {
            this.$form.slideUp('slow');
        }
    }

    this.open = function() {
        if (!this.$form) {
            this.render();
        }
        this.$form.slideDown('slow');
        this.rebuildHrefs();
    }

    this.render = function() {
        if (this.$form) return;
        var div = document.createElement('div'),
            item,
            col1 = document.createElement('div'),
            col2 = document.createElement('div'),
            h3 = document.createElement('h3'),
            clear = document.createElement('div');
        div.className = 'packages';
        div.style.display = 'none';
        col1.className = 'column';
        col2.className = 'column';
        clear.className = 'clear';
        h3.innerHTML = 'Gems';

        item = this.renderItem(this.selects, this.inputs, this.railsVersions, true);
        div.appendChild(item);
        item = this.renderItem(this.selects, this.inputs, this.rubyVersions, true)
        div.appendChild(item);
        div.appendChild(h3);
        div.appendChild(col1);
        div.appendChild(col2);
        div.appendChild(clear);

        for (var i=0, l = this.gemVersions.length; i < l; i++) {
            item = this.renderItem(this.selects, this.inputs, this.gemVersions[i]);
            var target = i < l / 2 ? col1 : col2;
            target.appendChild(item);
        };
        this.element.appendChild(div);
        this.$form = $(div);
        this.bindRendered();
    }

    this.bindRendered = function() {
        $(this.selects).each(function() {
            $(this).change(function() {_this.rebuildHrefs()});
        })
        $(this.inputs).each(function() {
            $(this).click(function() {_this.rebuildHrefs()});
        })
    }

    this.renderItem = function(selects, inputs, version, checked) {
        var p = document.createElement('p'),
            id = guid++, select, input, option, versions = version.versions;
        p.innerHTML =
            '<input type="checkbox" id="item_' + id + '" />'
            + '' + version.name + ' ';
        if (versions.length > 1) {
            p.innerHTML += '<select id="item_select_' + id + '"></select>';
            select = p.getElementsByTagName('select')[0];
            for (var i=0, l = versions.length; i < l; i++) {
                option = document.createElement('option');
                option.value = versions[i];
                option.innerHTML = versions[i];
                select.appendChild(option);
            };
        } else {
            p.innerHTML += '<input type="hidden" value="' + versions[0] + '"> ' + versions[0];
            select = p.getElementsByTagName('input')[1];
        }
        $(select).data('href', version.href);
        input = p.getElementsByTagName('input')[0];
        if (checked) input.checked = input.defaultChecked = true;
        inputs.push(input);
        selects.push(select);
        return p;
    }

    this.rebuildHrefs = function() {
        var items = [], select;
        for (var i=0, l = this.inputs.length; i < l; i++) {
            if(this.inputs[i].checked) {
                select = this.selects[i];
                items.push([$(select).data('href'), select.value]);
            }
        };
        this.setHrefs(items);
    }

    this.setHrefs = function(items) {
        var parts = [], item, path;
        for (var i=0, l = items.length; i < l; i++) {
            item = items[i]
            parts[parts.length] = item[0].replace(/[_-]/g, '') + '-' + item[1].replace(/[_-]/g, '');
        };
        path = parts.join('_');
        if (parts.length) {
            $('#download').attr('href', '/doc/' + path + '/rdoc.zip');
            $('#browse').attr('href', '/doc/' + path + '/');
        } else {
            $('#download').attr('href', '#');
            $('#browse').attr('href', '#');
        }
        $('#size').html('Zip, ' + (this.sizes[path] || 'unknown size'));
        this.unknownSize = !this.sizes[path];
    }

    this.element = element;
    this.sizes = sizes;
    this.init();
    this.bindEvents();
}
<commit_msg>do not show popup for empty request<commit_after>jQuery.fn.versionSelector = function(versions, sizes) {
    $(this).each(function() {
        new jQuery.versionSelector(this, versions, sizes);
    })
}

jQuery.versionSelector = function(element, versions, sizes) {
    var _this = this,
        guid = 0;

    this.init = function() {
        this.selects = [];
        this.inputs = [];
        this.unknownSize = false;

        this.gemVersions = [];
        for (var i=0, l = versions.length; i < l; i++) {
            switch (versions[i].name.toLowerCase()) {
                case 'ruby':
                    this.rubyVersions = versions[i];
                    break;
                case 'rails':
                    this.railsVersions = versions[i];
                    break;
                default:
                    this.gemVersions.push(versions[i]);
            }
        };
    }

    this.bindEvents = function() {
        $('.preset', element).click(this.presetClick);
        $('#download, #browse').click(this.downloadClick);
    }

    this.downloadClick = function() {
        if (_this.unknownSize) $('.build-message').show()
    }

    this.presetClick = function() {
        if ($(this).hasClass('preset_ruby')) {
            _this.setHrefs([
                [_this.railsVersions.href, _this.railsVersions.versions[0]],
                [_this.rubyVersions.href, _this.rubyVersions.versions[0]]
            ]);
            _this.close();
        } else if ($(this).hasClass('preset_rails')) {
            _this.setHrefs([
                [_this.railsVersions.href, _this.railsVersions.versions[0]]
            ]);
            _this.close();
        } else {
            _this.open();
        }

        $('.preset_selected', element).removeClass('preset_selected');
        $(this).addClass('preset_selected');
    }

    this.close = function() {
        if (this.$form) {
            this.$form.slideUp('slow');
        }
    }

    this.open = function() {
        if (!this.$form) {
            this.render();
        }
        this.$form.slideDown('slow');
        this.rebuildHrefs();
    }

    this.render = function() {
        if (this.$form) return;
        var div = document.createElement('div'),
            item,
            col1 = document.createElement('div'),
            col2 = document.createElement('div'),
            h3 = document.createElement('h3'),
            clear = document.createElement('div');
        div.className = 'packages';
        div.style.display = 'none';
        col1.className = 'column';
        col2.className = 'column';
        clear.className = 'clear';
        h3.innerHTML = 'Gems';

        item = this.renderItem(this.selects, this.inputs, this.railsVersions, true);
        div.appendChild(item);
        item = this.renderItem(this.selects, this.inputs, this.rubyVersions, true)
        div.appendChild(item);
        div.appendChild(h3);
        div.appendChild(col1);
        div.appendChild(col2);
        div.appendChild(clear);

        for (var i=0, l = this.gemVersions.length; i < l; i++) {
            item = this.renderItem(this.selects, this.inputs, this.gemVersions[i]);
            var target = i < l / 2 ? col1 : col2;
            target.appendChild(item);
        };
        this.element.appendChild(div);
        this.$form = $(div);
        this.bindRendered();
    }

    this.bindRendered = function() {
        $(this.selects).each(function() {
            $(this).change(function() {_this.rebuildHrefs()});
        })
        $(this.inputs).each(function() {
            $(this).click(function() {_this.rebuildHrefs()});
        })
    }

    this.renderItem = function(selects, inputs, version, checked) {
        var p = document.createElement('p'),
            id = guid++, select, input, option, versions = version.versions;
        p.innerHTML =
            '<input type="checkbox" id="item_' + id + '" />'
            + '' + version.name + ' ';
        if (versions.length > 1) {
            p.innerHTML += '<select id="item_select_' + id + '"></select>';
            select = p.getElementsByTagName('select')[0];
            for (var i=0, l = versions.length; i < l; i++) {
                option = document.createElement('option');
                option.value = versions[i];
                option.innerHTML = versions[i];
                select.appendChild(option);
            };
        } else {
            p.innerHTML += '<input type="hidden" value="' + versions[0] + '"> ' + versions[0];
            select = p.getElementsByTagName('input')[1];
        }
        $(select).data('href', version.href);
        input = p.getElementsByTagName('input')[0];
        if (checked) input.checked = input.defaultChecked = true;
        inputs.push(input);
        selects.push(select);
        return p;
    }

    this.rebuildHrefs = function() {
        var items = [], select;
        for (var i=0, l = this.inputs.length; i < l; i++) {
            if(this.inputs[i].checked) {
                select = this.selects[i];
                items.push([$(select).data('href'), select.value]);
            }
        };
        this.setHrefs(items);
    }

    this.setHrefs = function(items) {
        var parts = [], item, path;
        for (var i=0, l = items.length; i < l; i++) {
            item = items[i]
            parts[parts.length] = item[0].replace(/[_-]/g, '') + '-' + item[1].replace(/[_-]/g, '');
        };
        path = parts.join('_');
        if (parts.length) {
            $('#download').attr('href', '/doc/' + path + '/rdoc.zip');
            $('#browse').attr('href', '/doc/' + path + '/');
            this.unknownSize = !this.sizes[path];
        } else {
            $('#download').attr('href', '#');
            $('#browse').attr('href', '#');
            this.unknownSize = false;
        }
        $('#size').html('Zip, ' + (this.sizes[path] || 'unknown size'));
    }

    this.element = element;
    this.sizes = sizes;
    this.init();
    this.bindEvents();
}
<|endoftext|>


<commit_before>(function() {
	// Insert a script tag pointing at the desired version of jQuery

	// Get the version from the url
	var jqueryRE = /[\\?&]jquery=([^&#]*)/,
		results = jqueryRE.exec( location.search ),
		version = "",
		jq,
		myScriptTag = document.getElementsByTagName( "script" )[document.getElementsByTagName( "script" ).length - 1],
		baseUrl = myScriptTag.src.replace( /(.*)\/.*$/, "$1/" ),
		url = baseUrl + "jquery-1.7.1.js";

	if( results ) {
		version = decodeURIComponent(results[results.length - 1].replace(/\+/g, " "));
	} else {
		version = "1.6.4";
	}

	switch( version ) {
		case "1.6.4":
			url = baseUrl + "jquery-1.6.4.js";
			break;
		case "1.7.2":
			url = baseUrl + "jquery-1.7.2.js";
			break;
		default:
			url = "http://code.jquery.com/jquery-"+version+".js";
			break;
	}

	document.write( "<script src='" + url + "'></script>" );

	if ( parseInt( version.replace( /\./g, "" ), 10 ) < 170 && window.define && window.define.amd ) {
		document.write( '<script>define( "jquery", [], function () { return jQuery; } );</script>' );
	}
}());<commit_msg>Default to 1.7.1 Pick up local for 1.6.4, 1.7.1, 1.7.2 CDN versions for the rest<commit_after>(function() {
	// Insert a script tag pointing at the desired version of jQuery

	// Get the version from the url
	var jqueryRE = /[\\?&]jquery=([^&#]*)/,
		results = jqueryRE.exec( location.search ),
		version = "1.7.1",
		myScriptTag = document.getElementsByTagName( "script" )[document.getElementsByTagName( "script" ).length - 1],
		baseUrl = myScriptTag.src.replace( /(.*)\/.*$/, "$1/" ),
		url;

	if( results ) {
		version = decodeURIComponent(results[results.length - 1].replace(/\+/g, " "));
	}

	switch( version ) {
		// Local versions
		case "1.6.4":
		case "1.7.1":
		case "1.7.2":
			url = baseUrl + "jquery-" + version + ".js";
			break;
		// CDN versions
		default:
			url = "http://code.jquery.com/jquery-"+version+".js";
			break;
	}

	document.write( "<script src='" + url + "'></script>" );

	if ( parseInt( version.replace( /\./g, "" ), 10 ) < 170 && window.define && window.define.amd ) {
		document.write( '<script>define( "jquery", [], function () { return jQuery; } );</script>' );
	}
}());<|endoftext|>


<commit_before>// Copyright (c) 2010-2014 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
//
// See https://wiki.mozilla.org/Extension_Manager:Bootstrapped_Extensions
// for details.
"use strict";

const global = this;

var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;

function module(uri) Cu.import(uri, {});

const DEBUG = true;

__defineGetter__("BOOTSTRAP", () => "resource://" + moduleName + "/bootstrap.jsm");

var { AddonManager } = module("resource://gre/modules/AddonManager.jsm");
var { XPCOMUtils }   = module("resource://gre/modules/XPCOMUtils.jsm");
var { Services }     = module("resource://gre/modules/Services.jsm");

var Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback");

const resourceProto = Services.io.getProtocolHandler("resource")
                              .QueryInterface(Ci.nsIResProtocolHandler);
const categoryManager = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
const manager = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);

const BOOTSTRAP_CONTRACT = "@dactyl.googlecode.com/base/bootstrap";

var name = "dactyl";

function reportError(e) {
    let stack = e.stack || Error().stack;
    dump("\n" + name + ": bootstrap: " + e + "\n" + stack + "\n");
    Cu.reportError(e);
    Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
                                       .logStringMessage(stack);
}
function debug(...args) {
    if (DEBUG)
        dump(name + ": " + args.join(", ") + "\n");
}

function httpGet(uri) {
    let xmlhttp = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
    xmlhttp.overrideMimeType("text/plain");
    xmlhttp.open("GET", uri.spec || uri, false);
    xmlhttp.send(null);
    return xmlhttp;
}

let moduleName;
let initialized = false;
let addon = null;
let addonData = null;
let basePath = null;
let bootstrap;
let bootstrap_jsm;
let components = {};
let getURI = null;

let JSMLoader = {
    SANDBOX: Cu.nukeSandbox,

    get addon() addon,

    currentModule: null,

    factories: [],

    get name() name,

    get module() moduleName,

    globals: {},
    modules: {},

    times: {
        all: 0,
        add: function add(major, minor, delta) {
            this.all += delta;

            this[major] = (this[major] || 0) + delta;
            if (minor) {
                minor = ":" + minor;
                this[minor] = (this[minor] || 0) + delta;
                this[major + minor] = (this[major + minor] || 0) + delta;
            }
        },
        clear: function clear() {
            for (let key in this)
                if (typeof this[key] !== "number")
                    delete this[key];
        }
    },

    getTarget: function getTarget(url) {
        let uri = Services.io.newURI(url, null, null);
        if (uri.schemeIs("resource"))
            return resourceProto.resolveURI(uri);

        let chan = Services.io.newChannelFromURI(uri);
        try { chan.cancel(Cr.NS_BINDING_ABORTED); } catch (e) {}
        return chan.name;
    },

    _atexit: [],

    atexit: function atexit(arg, self) {
        if (typeof arg !== "string")
            this._atexit.push(arguments);
        else
            for each (let [fn, self] in this._atexit)
                try {
                    fn.call(self, arg);
                }
                catch (e) {
                    reportError(e);
                }
    },

    _load: function _load(name, target) {
        let urls = [name];
        if (name.indexOf(":") === -1)
            urls = this.config["module-paths"].map(path => path + name + ".jsm");

        for each (let url in urls)
            try {
                var uri = this.getTarget(url);
                if (uri in this.globals)
                    return this.modules[name] = this.globals[uri];

                this.globals[uri] = this.modules[name];
                bootstrap_jsm.loadSubScript(url, this.modules[name], "UTF-8");
                return;
            }
            catch (e) {
                debug("Loading " + name + ": " + e);
                delete this.globals[uri];

                if (typeof e != "string")
                    throw e;
            }

        throw Error("No such module: " + name);
    },

    load: function load(name, target) {
        if (!this.modules.hasOwnProperty(name)) {
            this.modules[name] = this.modules.base ? bootstrap.create(this.modules.base)
                                                   : bootstrap.import({ JSMLoader: this, module: global.module });

            let currentModule = this.currentModule;
            this.currentModule = this.modules[name];

            try {
                this._load(name, this.modules[name]);
            }
            catch (e) {
                delete this.modules[name];
                reportError(e);
                throw e;
            }
            finally {
                this.currentModule = currentModule;
            }
        }

        let module = this.modules[name];
        if (target)
            for each (let symbol in module.EXPORTED_SYMBOLS)
                try {
                    Object.defineProperty(target, symbol, {
                        configurable: true,
                        enumerable: true,
                        writable: true,
                        value: module[symbol]
                    });
                }
                catch (e) {
                    target[symbol] = module[symbol];
                }

        return module;
    },

    // Cuts down on stupid, fscking url mangling.
    get loadSubScript() bootstrap_jsm.loadSubScript,

    cleanup: function cleanup() {
        for (let factory of this.factories.splice(0))
            manager.unregisterFactory(factory.classID, factory);
    },

    Factory: function Factory(class_) ({
        __proto__: class_.prototype,

        createInstance: function (outer, iid) {
            try {
                if (outer != null)
                    throw Cr.NS_ERROR_NO_AGGREGATION;
                if (!class_.instance)
                    class_.instance = new class_();
                return class_.instance.QueryInterface(iid);
            }
            catch (e) {
                Cu.reportError(e);
                throw e;
            }
        }
    }),

    registerFactory: function registerFactory(factory) {
        manager.registerFactory(factory.classID,
                                String(factory.classID),
                                factory.contractID,
                                factory);
        this.factories.push(factory);
    }
};

function init() {
    debug("bootstrap: init");

    let manifest = JSON.parse(httpGet(getURI("config.json"))
                                .responseText);

    if (!manifest.categories)
        manifest.categories = [];

    for (let [classID, { contract, path, categories }] of Iterator(manifest.components || {})) {
        components[classID] = new FactoryProxy(getURI(path).spec, classID, contract);
        if (categories)
            for (let [category, id] in Iterator(categories))
                manifest.categories.push([category, id, contract]);
    }

    for (let [category, id, value] of manifest.categories)
        categoryManager.addCategoryEntry(category, id, value,
                                         false, true);

    for (let [pkg, path] in Iterator(manifest.resources || {})) {
        moduleName = moduleName || pkg;
        resourceProto.setSubstitution(pkg, getURI(path));
    }

    JSMLoader.config = manifest;

    bootstrap_jsm = module(BOOTSTRAP);
    if (!JSMLoader.SANDBOX)
        bootstrap = bootstrap_jsm;
    else {
        bootstrap = Cu.Sandbox(Cc["@mozilla.org/systemprincipal;1"].createInstance(),
                               { sandboxName: BOOTSTRAP });
        Services.scriptloader.loadSubScript(BOOTSTRAP, bootstrap);
    }
    bootstrap.require = JSMLoader.load("base").require;

    let pref = "extensions.dactyl.cacheFlushCheck";
    let val  = addon.version;
    if (!Services.prefs.prefHasUserValue(pref) || Services.prefs.getCharPref(pref) != val) {
        var cacheFlush = true;
        Services.prefs.setCharPref(pref, val);
    }

    Services.obs.notifyObservers(null, "dactyl-rehash", null);

    JSMLoader.bootstrap = global;

    JSMLoader.load("config", global);
    JSMLoader.load("main", global);

    JSMLoader.cacheFlush = cacheFlush;
    JSMLoader.load("base", global);

    if (!(BOOTSTRAP_CONTRACT in Cc)) {
        // Use Sandbox to prevent closures over this scope
        let sandbox = Cu.Sandbox(Cc["@mozilla.org/systemprincipal;1"].createInstance());
        let factory = Cu.evalInSandbox("({ createInstance: function () this })", sandbox);

        factory.classID         = Components.ID("{f541c8b0-fe26-4621-a30b-e77d21721fb5}");
        factory.contractID      = BOOTSTRAP_CONTRACT;
        factory.QueryInterface  = XPCOMUtils.generateQI([Ci.nsIFactory]);
        factory.wrappedJSObject = factory;

        manager.registerFactory(factory.classID, String(factory.classID),
                                BOOTSTRAP_CONTRACT, factory);
    }

    Cc[BOOTSTRAP_CONTRACT].getService().wrappedJSObject.loader = !Cu.unload && JSMLoader;

    for each (let component in components)
        component.register();

    updateVersion();

    if (addon !== addonData)
        require("main", global);
}

/**
 * Performs necessary migrations after a version change.
 */
function updateVersion() {
    function isDev(ver) /^hg|pre$/.test(ver);
    try {
        if (typeof require === "undefined" || addon === addonData)
            return;

        JSMLoader.load("prefs", global);
        config.lastVersion = localPrefs.get("lastVersion", null);

        localPrefs.set("lastVersion", addon.version);

        // We're switching from a nightly version to a stable or
        // semi-stable version or vice versa.
        //
        // Disable automatic updates when switching to nightlies,
        // restore the default action when switching to stable.
        if (!config.lastVersion || isDev(config.lastVersion) != isDev(addon.version))
            addon.applyBackgroundUpdates =
                AddonManager[isDev(addon.version) ? "AUTOUPDATE_DISABLE"
                                                  : "AUTOUPDATE_DEFAULT"];
    }
    catch (e) {
        reportError(e);
    }
}

function startup(data, reason) {
    debug("bootstrap: startup " + reasonToString(reason));
    basePath = data.installPath;

    if (!initialized) {
        initialized = true;

        debug("bootstrap: init " + data.id);

        addonData = data;
        addon = data;
        name = data.id.replace(/@.*/, "");
        AddonManager.getAddonByID(addon.id, function (a) {
            addon = a;

            updateVersion();
            if (typeof require !== "undefined")
                require("main", global);
        });

        if (basePath.isDirectory())
            getURI = function getURI(path) {
                let uri = Services.io.newFileURI(basePath);
                uri.path += path;
                return Services.io.newFileURI(uri.QueryInterface(Ci.nsIFileURL).file);
            };
        else
            getURI = function getURI(path)
                Services.io.newURI("jar:" + Services.io.newFileURI(basePath).spec.replace(/!/g, "%21") + "!" +
                                   "/" + path, null, null);

        try {
            init();
        }
        catch (e) {
            reportError(e);
        }
    }
}

/**
 * An XPCOM class factory proxy. Loads the JavaScript module at *url*
 * when an instance is to be created and calls its NSGetFactory method
 * to obtain the actual factory.
 *
 * @param {string} url The URL of the module housing the real factory.
 * @param {string} classID The CID of the class this factory represents.
 */
function FactoryProxy(url, classID, contractID) {
    this.url = url;
    this.classID = Components.ID(classID);
    this.contractID = contractID;
}
FactoryProxy.prototype = {
    QueryInterface: XPCOMUtils.generateQI(Ci.nsIFactory),
    register: function () {
        debug("bootstrap: register: " + this.classID + " " + this.contractID);

        JSMLoader.registerFactory(this);
    },
    get module() {
        debug("bootstrap: create module: " + this.contractID);

        Object.defineProperty(this, "module", { value: {}, enumerable: true });
        JSMLoader.load(this.url, this.module);
        return this.module;
    },
    createInstance: function (iids) {
        return let (factory = this.module.NSGetFactory(this.classID))
            factory.createInstance.apply(factory, arguments);
    }
}

var timer;
function shutdown(data, reason) {
    let strReason = reasonToString(reason);
    debug("bootstrap: shutdown " + strReason);

    if (reason != APP_SHUTDOWN) {
        if (~[ADDON_UPGRADE, ADDON_DOWNGRADE, ADDON_UNINSTALL].indexOf(reason))
            Services.obs.notifyObservers(null, "dactyl-purge", null);

        Services.obs.notifyObservers(null, "dactyl-cleanup", strReason);
        Services.obs.notifyObservers(null, "dactyl-cleanup-modules", reasonToString(reason));

        JSMLoader.atexit(strReason);
        JSMLoader.cleanup(strReason);

        for each (let [category, entry] in JSMLoader.config.categories)
            categoryManager.deleteCategoryEntry(category, entry, false);
        for (let resource in JSMLoader.config.resources)
            resourceProto.setSubstitution(resource, null);

        timer = Timer(() => {
            bootstrap_jsm.require = null;
            if (JSMLoader.SANDBOX)
                Cu.nukeSandbox(bootstrap);
            else
                Cu.unload(BOOTSTRAP);
            bootstrap = null;
            bootstrap_jsm = null;
        }, 5000, Ci.nsITimer.TYPE_ONE_SHOT);
    }
}

function uninstall(data, reason) {
    debug("bootstrap: uninstall " + reasonToString(reason));
    if (reason == ADDON_UNINSTALL) {
        Services.prefs.deleteBranch("extensions.dactyl.");

        if (BOOTSTRAP_CONTRACT in Cc) {
            let service = Cc[BOOTSTRAP_CONTRACT].getService().wrappedJSObject;
            manager.unregisterFactory(service.classID, service);
        }
    }
}

function reasonToString(reason) {
    for each (let name in ["disable", "downgrade", "enable",
                           "install", "shutdown", "startup",
                           "uninstall", "upgrade"])
        if (reason == global["ADDON_" + name.toUpperCase()] ||
            reason == global["APP_" + name.toUpperCase()])
            return name;
}

function install(data, reason) { debug("bootstrap: install " + reasonToString(reason)); }

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>Add addonID to Sandbox metadata.<commit_after>// Copyright (c) 2010-2014 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
//
// See https://wiki.mozilla.org/Extension_Manager:Bootstrapped_Extensions
// for details.
"use strict";

const global = this;

var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;

function module(uri) Cu.import(uri, {});

const DEBUG = true;

__defineGetter__("BOOTSTRAP", () => "resource://" + moduleName + "/bootstrap.jsm");

var { AddonManager } = module("resource://gre/modules/AddonManager.jsm");
var { XPCOMUtils }   = module("resource://gre/modules/XPCOMUtils.jsm");
var { Services }     = module("resource://gre/modules/Services.jsm");

var Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback");

const resourceProto = Services.io.getProtocolHandler("resource")
                              .QueryInterface(Ci.nsIResProtocolHandler);
const categoryManager = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
const manager = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);

const BOOTSTRAP_CONTRACT = "@dactyl.googlecode.com/base/bootstrap";

var name = "dactyl";

function reportError(e) {
    let stack = e.stack || Error().stack;
    dump("\n" + name + ": bootstrap: " + e + "\n" + stack + "\n");
    Cu.reportError(e);
    Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
                                       .logStringMessage(stack);
}
function debug(...args) {
    if (DEBUG)
        dump(name + ": " + args.join(", ") + "\n");
}

function httpGet(uri) {
    let xmlhttp = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
    xmlhttp.overrideMimeType("text/plain");
    xmlhttp.open("GET", uri.spec || uri, false);
    xmlhttp.send(null);
    return xmlhttp;
}

let moduleName;
let initialized = false;
let addon = null;
let addonData = null;
let basePath = null;
let bootstrap;
let bootstrap_jsm;
let components = {};
let getURI = null;

let JSMLoader = {
    SANDBOX: Cu.nukeSandbox,

    get addon() addon,

    currentModule: null,

    factories: [],

    get name() name,

    get module() moduleName,

    globals: {},
    modules: {},

    times: {
        all: 0,
        add: function add(major, minor, delta) {
            this.all += delta;

            this[major] = (this[major] || 0) + delta;
            if (minor) {
                minor = ":" + minor;
                this[minor] = (this[minor] || 0) + delta;
                this[major + minor] = (this[major + minor] || 0) + delta;
            }
        },
        clear: function clear() {
            for (let key in this)
                if (typeof this[key] !== "number")
                    delete this[key];
        }
    },

    getTarget: function getTarget(url) {
        let uri = Services.io.newURI(url, null, null);
        if (uri.schemeIs("resource"))
            return resourceProto.resolveURI(uri);

        let chan = Services.io.newChannelFromURI(uri);
        try { chan.cancel(Cr.NS_BINDING_ABORTED); } catch (e) {}
        return chan.name;
    },

    _atexit: [],

    atexit: function atexit(arg, self) {
        if (typeof arg !== "string")
            this._atexit.push(arguments);
        else
            for each (let [fn, self] in this._atexit)
                try {
                    fn.call(self, arg);
                }
                catch (e) {
                    reportError(e);
                }
    },

    _load: function _load(name, target) {
        let urls = [name];
        if (name.indexOf(":") === -1)
            urls = this.config["module-paths"].map(path => path + name + ".jsm");

        for each (let url in urls)
            try {
                var uri = this.getTarget(url);
                if (uri in this.globals)
                    return this.modules[name] = this.globals[uri];

                this.globals[uri] = this.modules[name];
                bootstrap_jsm.loadSubScript(url, this.modules[name], "UTF-8");
                return;
            }
            catch (e) {
                debug("Loading " + name + ": " + e);
                delete this.globals[uri];

                if (typeof e != "string")
                    throw e;
            }

        throw Error("No such module: " + name);
    },

    load: function load(name, target) {
        if (!this.modules.hasOwnProperty(name)) {
            this.modules[name] = this.modules.base ? bootstrap.create(this.modules.base)
                                                   : bootstrap.import({ JSMLoader: this, module: global.module });

            let currentModule = this.currentModule;
            this.currentModule = this.modules[name];

            try {
                this._load(name, this.modules[name]);
            }
            catch (e) {
                delete this.modules[name];
                reportError(e);
                throw e;
            }
            finally {
                this.currentModule = currentModule;
            }
        }

        let module = this.modules[name];
        if (target)
            for each (let symbol in module.EXPORTED_SYMBOLS)
                try {
                    Object.defineProperty(target, symbol, {
                        configurable: true,
                        enumerable: true,
                        writable: true,
                        value: module[symbol]
                    });
                }
                catch (e) {
                    target[symbol] = module[symbol];
                }

        return module;
    },

    // Cuts down on stupid, fscking url mangling.
    get loadSubScript() bootstrap_jsm.loadSubScript,

    cleanup: function cleanup() {
        for (let factory of this.factories.splice(0))
            manager.unregisterFactory(factory.classID, factory);
    },

    Factory: function Factory(class_) ({
        __proto__: class_.prototype,

        createInstance: function (outer, iid) {
            try {
                if (outer != null)
                    throw Cr.NS_ERROR_NO_AGGREGATION;
                if (!class_.instance)
                    class_.instance = new class_();
                return class_.instance.QueryInterface(iid);
            }
            catch (e) {
                Cu.reportError(e);
                throw e;
            }
        }
    }),

    registerFactory: function registerFactory(factory) {
        manager.registerFactory(factory.classID,
                                String(factory.classID),
                                factory.contractID,
                                factory);
        this.factories.push(factory);
    }
};

function init() {
    debug("bootstrap: init");

    let manifest = JSON.parse(httpGet(getURI("config.json"))
                                .responseText);

    if (!manifest.categories)
        manifest.categories = [];

    for (let [classID, { contract, path, categories }] of Iterator(manifest.components || {})) {
        components[classID] = new FactoryProxy(getURI(path).spec, classID, contract);
        if (categories)
            for (let [category, id] in Iterator(categories))
                manifest.categories.push([category, id, contract]);
    }

    for (let [category, id, value] of manifest.categories)
        categoryManager.addCategoryEntry(category, id, value,
                                         false, true);

    for (let [pkg, path] in Iterator(manifest.resources || {})) {
        moduleName = moduleName || pkg;
        resourceProto.setSubstitution(pkg, getURI(path));
    }

    JSMLoader.config = manifest;

    bootstrap_jsm = module(BOOTSTRAP);
    if (!JSMLoader.SANDBOX)
        bootstrap = bootstrap_jsm;
    else {
        bootstrap = Cu.Sandbox(Cc["@mozilla.org/systemprincipal;1"].createInstance(),
                               { sandboxName: BOOTSTRAP,
                                 metadata: { addonID: addon.id } });
        Services.scriptloader.loadSubScript(BOOTSTRAP, bootstrap);
    }
    bootstrap.require = JSMLoader.load("base").require;

    let pref = "extensions.dactyl.cacheFlushCheck";
    let val  = addon.version;
    if (!Services.prefs.prefHasUserValue(pref) || Services.prefs.getCharPref(pref) != val) {
        var cacheFlush = true;
        Services.prefs.setCharPref(pref, val);
    }

    Services.obs.notifyObservers(null, "dactyl-rehash", null);

    JSMLoader.bootstrap = global;

    JSMLoader.load("config", global);
    JSMLoader.load("main", global);

    JSMLoader.cacheFlush = cacheFlush;
    JSMLoader.load("base", global);

    if (!(BOOTSTRAP_CONTRACT in Cc)) {
        // Use Sandbox to prevent closures over this scope
        let sandbox = Cu.Sandbox(Cc["@mozilla.org/systemprincipal;1"].createInstance());
        let factory = Cu.evalInSandbox("({ createInstance: function () this })", sandbox);

        factory.classID         = Components.ID("{f541c8b0-fe26-4621-a30b-e77d21721fb5}");
        factory.contractID      = BOOTSTRAP_CONTRACT;
        factory.QueryInterface  = XPCOMUtils.generateQI([Ci.nsIFactory]);
        factory.wrappedJSObject = factory;

        manager.registerFactory(factory.classID, String(factory.classID),
                                BOOTSTRAP_CONTRACT, factory);
    }

    Cc[BOOTSTRAP_CONTRACT].getService().wrappedJSObject.loader = !Cu.unload && JSMLoader;

    for each (let component in components)
        component.register();

    updateVersion();

    if (addon !== addonData)
        require("main", global);
}

/**
 * Performs necessary migrations after a version change.
 */
function updateVersion() {
    function isDev(ver) /^hg|pre$/.test(ver);
    try {
        if (typeof require === "undefined" || addon === addonData)
            return;

        JSMLoader.load("prefs", global);
        config.lastVersion = localPrefs.get("lastVersion", null);

        localPrefs.set("lastVersion", addon.version);

        // We're switching from a nightly version to a stable or
        // semi-stable version or vice versa.
        //
        // Disable automatic updates when switching to nightlies,
        // restore the default action when switching to stable.
        if (!config.lastVersion || isDev(config.lastVersion) != isDev(addon.version))
            addon.applyBackgroundUpdates =
                AddonManager[isDev(addon.version) ? "AUTOUPDATE_DISABLE"
                                                  : "AUTOUPDATE_DEFAULT"];
    }
    catch (e) {
        reportError(e);
    }
}

function startup(data, reason) {
    debug("bootstrap: startup " + reasonToString(reason));
    basePath = data.installPath;

    if (!initialized) {
        initialized = true;

        debug("bootstrap: init " + data.id);

        addonData = data;
        addon = data;
        name = data.id.replace(/@.*/, "");
        AddonManager.getAddonByID(addon.id, function (a) {
            addon = a;

            updateVersion();
            if (typeof require !== "undefined")
                require("main", global);
        });

        if (basePath.isDirectory())
            getURI = function getURI(path) {
                let uri = Services.io.newFileURI(basePath);
                uri.path += path;
                return Services.io.newFileURI(uri.QueryInterface(Ci.nsIFileURL).file);
            };
        else
            getURI = function getURI(path)
                Services.io.newURI("jar:" + Services.io.newFileURI(basePath).spec.replace(/!/g, "%21") + "!" +
                                   "/" + path, null, null);

        try {
            init();
        }
        catch (e) {
            reportError(e);
        }
    }
}

/**
 * An XPCOM class factory proxy. Loads the JavaScript module at *url*
 * when an instance is to be created and calls its NSGetFactory method
 * to obtain the actual factory.
 *
 * @param {string} url The URL of the module housing the real factory.
 * @param {string} classID The CID of the class this factory represents.
 */
function FactoryProxy(url, classID, contractID) {
    this.url = url;
    this.classID = Components.ID(classID);
    this.contractID = contractID;
}
FactoryProxy.prototype = {
    QueryInterface: XPCOMUtils.generateQI(Ci.nsIFactory),
    register: function () {
        debug("bootstrap: register: " + this.classID + " " + this.contractID);

        JSMLoader.registerFactory(this);
    },
    get module() {
        debug("bootstrap: create module: " + this.contractID);

        Object.defineProperty(this, "module", { value: {}, enumerable: true });
        JSMLoader.load(this.url, this.module);
        return this.module;
    },
    createInstance: function (iids) {
        return let (factory = this.module.NSGetFactory(this.classID))
            factory.createInstance.apply(factory, arguments);
    }
}

var timer;
function shutdown(data, reason) {
    let strReason = reasonToString(reason);
    debug("bootstrap: shutdown " + strReason);

    if (reason != APP_SHUTDOWN) {
        if (~[ADDON_UPGRADE, ADDON_DOWNGRADE, ADDON_UNINSTALL].indexOf(reason))
            Services.obs.notifyObservers(null, "dactyl-purge", null);

        Services.obs.notifyObservers(null, "dactyl-cleanup", strReason);
        Services.obs.notifyObservers(null, "dactyl-cleanup-modules", reasonToString(reason));

        JSMLoader.atexit(strReason);
        JSMLoader.cleanup(strReason);

        for each (let [category, entry] in JSMLoader.config.categories)
            categoryManager.deleteCategoryEntry(category, entry, false);
        for (let resource in JSMLoader.config.resources)
            resourceProto.setSubstitution(resource, null);

        timer = Timer(() => {
            bootstrap_jsm.require = null;
            if (JSMLoader.SANDBOX)
                Cu.nukeSandbox(bootstrap);
            else
                Cu.unload(BOOTSTRAP);
            bootstrap = null;
            bootstrap_jsm = null;
        }, 5000, Ci.nsITimer.TYPE_ONE_SHOT);
    }
}

function uninstall(data, reason) {
    debug("bootstrap: uninstall " + reasonToString(reason));
    if (reason == ADDON_UNINSTALL) {
        Services.prefs.deleteBranch("extensions.dactyl.");

        if (BOOTSTRAP_CONTRACT in Cc) {
            let service = Cc[BOOTSTRAP_CONTRACT].getService().wrappedJSObject;
            manager.unregisterFactory(service.classID, service);
        }
    }
}

function reasonToString(reason) {
    for each (let name in ["disable", "downgrade", "enable",
                           "install", "shutdown", "startup",
                           "uninstall", "upgrade"])
        if (reason == global["ADDON_" + name.toUpperCase()] ||
            reason == global["APP_" + name.toUpperCase()])
            return name;
}

function install(data, reason) { debug("bootstrap: install " + reasonToString(reason)); }

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>var settings1 = {};
//var settings2={};
var set=new traslateSettings();
var z = new translateChanges();
var clssList=[];

var patternOfDisplay = [
    'typ',
    'klasa',
    'grupa',
    'przedmiot',
    'nauczyciel',
    'sala',
    'komentarz',
    'rodzaj'
]
var btnEvents ={
            saveBtn:function(){takeValuesFromForm()},
            tommorowBtn:function(){requestForChanges('tommorow')},
            todayBtn:function(){requestForChanges('today')},
        }
function setValuesToForm(params){
    var formList=['setClass','setNotification'];
    for(var i=0;i<params.length;i++){
        var sel = document.getElementById(formList[i]);
        var opts = sel.options;
        for(var opt, j = 0; opt = opts[j]; j++) {
            if(opt.value == params[i]) {
                sel.selectedIndex = j;
                break;
            }
        }
    }
}

function changeDisplayForChanges(oneClass){
    console.log(oneClass.innerHTML);
     z.setClassName(oneClass.innerHTML);
     z.displayData();
}
function takeValuesFromForm(){
    //console.log('hi');
    var form={};
    form['setClass'] = document.getElementById('setClass').value;
    form['notification'] = document.getElementById('setNotification').value;
    var url = 'postCall';
    form['mode'] = 'saveSettings';
    //console.log(form);
    z.setClassName(form.setClass);
    z.displayData();
    sendObj(url,form,function(obj){
        //var json = JSON.parse(obj);
        console.log('saveSettings',obj);
    });
    //console.log('param from form',a,b);
}
function getClassList(form){
    var url = 'postCall';
    form['mode']='classList';
    //console.log('clsasList',form);

    sendObj(url,form,function(obj){
        //var json = obj;
        classList=obj;
       filtrEvents();
        //set.saveData(json);
        //console.log('obj',json);

    });

}
function getPicture(){
    var url = 'postCall';
    var form = {};
    form['mode']='picture';
    sendObj(url,form,function(obj){
        console.log('res picture:',obj)

        document.getElementById('personPicture').src=obj;

    })

}

function requestForChanges(type){
    //console.log('hi');
    var url = 'postCall'
    var form={};
    btnClicked(type);
    form['mode']='getChanges'
    if(type =='today'){
        form['param']='today';

    }
    if(type == 'tommorow'){
        form['param']='tommorow';
    }
    //console.log(form);

    sendObj(url,form,function(obj){
        var json = obj;
        //set.saveData(json);
        //console.log(obj,json);
        z.data=json['substitution'];
        console.log('data',z.data);
        document.getElementById('forDay').innerHTML = 'Changes for '+json['date'];
        //console.log('acctal changes',json['substitution']);
        if(z.data == 'no substitutions'){
            console.log('ji',z.data);
            z.data=[{"cancelled":[true],"note":["brak zmian"],
                    classes:[z.className]}];
            console.log(z.data);
        }
        z.displayData();
        getClassList(form);
       // console.log(obj);
    });
}

function closeInfo(){
	var infB = document.getElementById('infoBox');
	infB.style.display = 'none';
}
function sendMessage(){
	var url = 'postCall';
	var form = {};
	form['mode']='message';
	var el = document.getElementById('messageArea');
	var infB = document.getElementById('infoBox');
	var infBData = document.getElementById('infoBoxData');
	form['param']=el.value;
	//console.log(el.value);
	sendObj(url,form,function(responeText){
		infB.style.display = 'table';
		infBData.innerHTML=responeText;
	})
	//el.innerHTML='hi';

}
function onLoadFunc(){
    //console.log('hi2');
    var url='postCall';
    var form={};
    form['mode']='getSettings';
    sendObj(url,form,function(obj){
    //    console.log(JSON.parse(obj));
        settings1 = obj;
       // console.log('hi',settings1);
        set.saveData(settings1.event);
    set.addChangeClick();
    set.addClicks();
        z.setFields(settings1['fields']);
        z.setClassName(settings1.formValues[0]);
    setValuesToForm(settings1['formValues'])
    getPicture();
        //set.saveData(settings1);
    requestForChanges('today');
    });

    //console.log(settings1);
}

/* #####################jakieś śmieci#################### */
function sendObj (url,json_obj,callback){
    var http = new XMLHttpRequest();
    //var url = "get_data";
    var string_obj = JSON.stringify(json_obj);
       // console.log(string_obj);
    http.open("POST", url, true);
    http.setRequestHeader("Content-type", "application/json");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            console.log('resText',http.responseText);
            var res=JSON.parse(http.responseText);
            console.log(res);
            if(res['err'] == true){
                //console.log(res.message)
				var resMsg = res.message;
				var msg = '' + resMsg + '';
				var msgB = document.getElementById('msgBox');
				var msgBData = document.getElementById('msgBoxData');
				msgB.style.display = 'table';
				msgBData.innerHTML=msg;
            }
            //console.log('resText',res);
            callback(res.params);
        }
        else{console.log(http.status);}
    }
    http.send(string_obj);
}
function filtrEvents(){
	var allClasses = ["1a","1b","1c","1d","2a","2b","2c","2d","3a","3b","3c","3d","1ga","1gb","1gc","1gd","2ga","2gb","2gc","2gd","3ga","3gb","3gc","3gd"];
	for(var i=0; i<allClasses.length; i++){
		var el = document.getElementById(allClasses[i]);
		el.className = "className";
        el.removeEventListener('click',function(){ changeDisplayForChanges(this)},false);
	}
	for(var i=0; i<classList.length; i++){
		var el = document.getElementById(classList[i]);
		el.className = "substitution";
        el.addEventListener('click',function(){ changeDisplayForChanges(this)},false);
	}
function closeMsg(){
	var msgB = document.getElementById('msgBox');
	msgB.style.display = 'none';
}
function closeInfo(){
	var infB = document.getElementById('infoBox');
	infB.style.display = 'none';
>>>>>>> f50bfc1c5962c87c6a80c4193a53de798e0f49bf
}
function btnClicked(type){
    console.log('hello',type);
    var idList={today:'todayBtn',tommorow:'tommorowBtn'};
    for (k in idList){
        if(k==type){
            document.getElementById(idList[k]).className='btn btnClicked';
        }
        else{ document.getElementById(idList[k]).className='btn';}
    }

}
function homePosition(id){
        var el;
        for(var i=0; i<settings1.events.length;i++){
            el = document.getElementById(settings1.events[i]);
            if(settings1.events[i]==id){
                el.style.display='block';
            }
            else{
                el.style.display='none';
            }
        }
}
function traslateSettings(){
    this.formId = 'setClass';
    this.saveData = function(data){
        this.changeDisplayEvents = data['changeDisplayEvents'];
        this.btnEvents=btnEvents;
    }
    this.addChangeClick=function(){
        for(k in this.changeDisplayEvents){
            this.changeDisplayOnClick(this.changeDisplayEvents[k]);
        }
    }

    this.changeDisplayOnClick=function(key){
        console.log(key[0]);
        var key1 =key[0];
        for(var i=0;i<key1.length;i++){
        var el = document.getElementById(key1[i]);
        //console.log(el);
        el.addEventListener('click',function(){ homePosition(key[1])},false);
        }
    }
    this.addClicks=function(){
        for(k in this.btnEvents){
            var el = document.getElementById(k);
            //console.log(el);
            el.addEventListener('click',this.btnEvents[k],false);
            //console.log(this.btnEvents[k]);
        }
    }
}

function translateChanges(){
    //this.data
    this.divId='changesContainer';
    this.parsedData="";
    this.finalTables="";
    this.setClassName=function(className){
        this.className= className;
    }
    //this.className=null;
    //fieldsToFill.call(this);
    this.setFields = function(fields){
        this.fields=fields;

    }
    //this.fields=settings1['fields'];
    this.displayData=function(){
        console.log('changes for class',this.className);
        this.finalTables="";
        this.getChange();
        this.tableTest();
    }
    this.getChange = function(){
        var string="";
        for(var j=0;j<this.data.length;j++){
            console.log('dataLength',this.data.length);
            var findParam=this.changeContainsClass(this.data[j]);
            if(findParam){
            var oneChangeObj=this.assignParams(this.data[j]);
            this.finalTables+=this.createElement(oneChangeObj);
            //console.log(string);
            //+=string;
            //this.parsedData="";
            }
            //console.log(fi//);
        }
        if(this.finalTables == ""){
            //this.addToArray('brak','zastępstw',0);
            string='nic';
            //
            this.finalTables+=string;
            this.parsedData="";
            //this.finalTables==
        }
    }
    this.changeContainsClass = function(oneChange){
    if(this.className =='all'||this.className==""){
        //console.log('null on change');
        return true;
    };
    var classId=oneChange['classes'];
        for(var i=0;i<classId.length;i++){
            if(this.className == classId[i]){
                //console.log('full on change');
                return true;
            }
        }
    return false;
}
    this.addToArray=function(keyText,keyValue,tabs){
        var text = this.createElement(keyText,keyValue,tabs);
        if(text !=""){
            this.parsedData+=text;
            //this.i++;
        }
    }
    this.tableTest=function(){
        var el = document.getElementById(this.divId);
        var text="";
        //console.log(a.innerHTML);
        el.innerHTML=this.finalTables;
    }
    this.newParams=function(key,value,ifchanges){
        if (ifchanges == true){

        }

    }
    this.assignParams = function(oneChange){
        this.i=0;
        var keyText="";
        //var x = exData;
        var keyValue=""
        var elInChange={};
        for (k in oneChange){

    //console.log('hey',k);
    //console.log('hey',this.fields);
            keyText=this.fields[k];
            if(k=='cancelled'){
                keyValue=this.getType(oneChange[k]);
                if(keyText != undefined){
                    elInChange[keyText]=keyValue;
                }
                //this.addToArray(keyText,keyValue,0);
            }
            else if(k =='changes'){
                //do nothing
            }
            else{
                keyValue=oneChange[k];
                //x[keyText] =oneChange[k];
                //console.log(keyText + ' '+keyValue);
                if(keyText != undefined){
                    elInChange[keyText]=keyValue;
                }
                //this.addToArray(keyText,keyValue,0);
            }
        }
        for(j in oneChange['changes']){
            keyText=this.fields[j];
                    //x['z'+keyText] =changesIn[l];

            keyValue=oneChange['changes'][j];
            elInChange[keyText]+=' -> '+keyValue;

        }

        return elInChange;
        //this.createElement(elInChange);
        //console.log('changes ',elInChange);
    }
    this.getType= function(value){
        if(value=='true'){
            //this.style='backBlue'
            return 'anulowanie';
        }
        else{
            //this.style='backRed'
            return 'zastępstwo';
        }
    }
    this.createElement=function(obj){
        if(obj=={}){return "";}
        console.log('onj',obj);
        //if(key==undefined||value==""){return '';};
        //var tabString=this.createTabs(tabs);
        //console.log('tabs',tabs);
        var allLi=""
        for(var i=0;i<patternOfDisplay.length;i++){

           if(obj[patternOfDisplay[i]] == undefined ||obj[patternOfDisplay[i]] == ""){
               //do nothing
           }
            else{
                allLi+=this.createLi(patternOfDisplay[i],obj[patternOfDisplay[i]]);
            }
        }
        var string = '
'+allLi+'
';
        return string;
    }
    this.createLi=function(name,text){
    return '
'+name+' '+text+'
';
    }

}<commit_msg>Fixed mistakes in sendForm.js<commit_after>var settings1 = {};
//var settings2={};
var set=new traslateSettings();
var z = new translateChanges();
var clssList=[];

var patternOfDisplay = [
    'typ',
    'klasa',
    'grupa',
    'przedmiot',
    'nauczyciel',
    'sala',
    'komentarz',
    'rodzaj'
]
var btnEvents ={
            saveBtn:function(){takeValuesFromForm()},
            tommorowBtn:function(){requestForChanges('tommorow')},
            todayBtn:function(){requestForChanges('today')},
        }
function setValuesToForm(params){
    var formList=['setClass','setNotification'];
    for(var i=0;i<params.length;i++){
        var sel = document.getElementById(formList[i]);
        var opts = sel.options;
        for(var opt, j = 0; opt = opts[j]; j++) {
            if(opt.value == params[i]) {
                sel.selectedIndex = j;
                break;
            }
        }
    }
}

function changeDisplayForChanges(oneClass){
    console.log(oneClass.innerHTML);
     z.setClassName(oneClass.innerHTML);
     z.displayData();
}
function takeValuesFromForm(){
    //console.log('hi');
    var form={};
    form['setClass'] = document.getElementById('setClass').value;
    form['notification'] = document.getElementById('setNotification').value;
    var url = 'postCall';
    form['mode'] = 'saveSettings';
    //console.log(form);
    z.setClassName(form.setClass);
    z.displayData();
    sendObj(url,form,function(obj){
        //var json = JSON.parse(obj);
        console.log('saveSettings',obj);
    });
    //console.log('param from form',a,b);
}
function getClassList(form){
    var url = 'postCall';
    form['mode']='classList';
    //console.log('clsasList',form);

    sendObj(url,form,function(obj){
        //var json = obj;
        classList=obj;
       filtrEvents();
        //set.saveData(json);
        //console.log('obj',json);

    });

}
function getPicture(){
    var url = 'postCall';
    var form = {};
    form['mode']='picture';
    sendObj(url,form,function(obj){
        console.log('res picture:',obj)

        document.getElementById('personPicture').src=obj;

    })

}

function requestForChanges(type){
    //console.log('hi');
    var url = 'postCall'
    var form={};
    btnClicked(type);
    form['mode']='getChanges'
    if(type =='today'){
        form['param']='today';

    }
    if(type == 'tommorow'){
        form['param']='tommorow';
    }
    //console.log(form);

    sendObj(url,form,function(obj){
        var json = obj;
        //set.saveData(json);
        //console.log(obj,json);
        z.data=json['substitution'];
        console.log('data',z.data);
        document.getElementById('forDay').innerHTML = 'Changes for '+json['date'];
        //console.log('acctal changes',json['substitution']);
        if(z.data == 'no substitutions'){
            console.log('ji',z.data);
            z.data=[{"cancelled":[true],"note":["brak zmian"],
                    classes:[z.className]}];
            console.log(z.data);
        }
        z.displayData();
        getClassList(form);
       // console.log(obj);
    });
}

function closeInfo(){
	var infB = document.getElementById('infoBox');
	infB.style.display = 'none';
}
function sendMessage(){
	var url = 'postCall';
	var form = {};
	form['mode']='message';
	var el = document.getElementById('messageArea');
	var infB = document.getElementById('infoBox');
	var infBData = document.getElementById('infoBoxData');
	form['param']=el.value;
	//console.log(el.value);
	sendObj(url,form,function(responeText){
		infB.style.display = 'table';
		infBData.innerHTML=responeText;
	})
	//el.innerHTML='hi';

}
function onLoadFunc(){
    //console.log('hi2');
    var url='postCall';
    var form={};
    form['mode']='getSettings';
    sendObj(url,form,function(obj){
    //    console.log(JSON.parse(obj));
        settings1 = obj;
       // console.log('hi',settings1);
        set.saveData(settings1.event);
    set.addChangeClick();
    set.addClicks();
        z.setFields(settings1['fields']);
        z.setClassName(settings1.formValues[0]);
    setValuesToForm(settings1['formValues'])
    getPicture();
        //set.saveData(settings1);
    requestForChanges('today');
    });

    //console.log(settings1);
}

/* #####################jakieś śmieci#################### */
function sendObj (url,json_obj,callback){
    var http = new XMLHttpRequest();
    //var url = "get_data";
    var string_obj = JSON.stringify(json_obj);
       // console.log(string_obj);
    http.open("POST", url, true);
    http.setRequestHeader("Content-type", "application/json");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            console.log('resText',http.responseText);
            var res=JSON.parse(http.responseText);
            console.log(res);
            if(res['err'] == true){
                //console.log(res.message)
				var resMsg = res.message;
				var msg = '' + resMsg + '';
				var msgB = document.getElementById('msgBox');
				var msgBData = document.getElementById('msgBoxData');
				msgB.style.display = 'table';
				msgBData.innerHTML=msg;
            }
            //console.log('resText',res);
            callback(res.params);
        }
        else{console.log(http.status);}
    }
    http.send(string_obj);
}
function filtrEvents(){
	var allClasses = ["1a","1b","1c","1d","2a","2b","2c","2d","3a","3b","3c","3d","1ga","1gb","1gc","1gd","2ga","2gb","2gc","2gd","3ga","3gb","3gc","3gd"];
	for(var i=0; i<allClasses.length; i++){
		var el = document.getElementById(allClasses[i]);
		el.className = "className";
        el.removeEventListener('click',function(){ changeDisplayForChanges(this)},false);
	}
	for(var i=0; i<classList.length; i++){
		var el = document.getElementById(classList[i]);
		el.className = "substitution";
        el.addEventListener('click',function(){ changeDisplayForChanges(this)},false);
	}
}
function closeMsg(){
	var msgB = document.getElementById('msgBox');
	msgB.style.display = 'none';
}
function closeInfo(){
	var infB = document.getElementById('infoBox');
	infB.style.display = 'none';
}
function btnClicked(type){
    console.log('hello',type);
    var idList={today:'todayBtn',tommorow:'tommorowBtn'};
    for (k in idList){
        if(k==type){
            document.getElementById(idList[k]).className='btn btnClicked';
        }
        else{ document.getElementById(idList[k]).className='btn';}
    }

}
function homePosition(id){
        var el;
        for(var i=0; i<settings1.events.length;i++){
            el = document.getElementById(settings1.events[i]);
            if(settings1.events[i]==id){
                el.style.display='block';
            }
            else{
                el.style.display='none';
            }
        }
}
function traslateSettings(){
    this.formId = 'setClass';
    this.saveData = function(data){
        this.changeDisplayEvents = data['changeDisplayEvents'];
        this.btnEvents=btnEvents;
    }
    this.addChangeClick=function(){
        for(k in this.changeDisplayEvents){
            this.changeDisplayOnClick(this.changeDisplayEvents[k]);
        }
    }

    this.changeDisplayOnClick=function(key){
        console.log(key[0]);
        var key1 =key[0];
        for(var i=0;i<key1.length;i++){
        var el = document.getElementById(key1[i]);
        //console.log(el);
        el.addEventListener('click',function(){ homePosition(key[1])},false);
        }
    }
    this.addClicks=function(){
        for(k in this.btnEvents){
            var el = document.getElementById(k);
            //console.log(el);
            el.addEventListener('click',this.btnEvents[k],false);
            //console.log(this.btnEvents[k]);
        }
    }
}

function translateChanges(){
    //this.data
    this.divId='changesContainer';
    this.parsedData="";
    this.finalTables="";
    this.setClassName=function(className){
        this.className= className;
    }
    //this.className=null;
    //fieldsToFill.call(this);
    this.setFields = function(fields){
        this.fields=fields;

    }
    //this.fields=settings1['fields'];
    this.displayData=function(){
        console.log('changes for class',this.className);
        this.finalTables="";
        this.getChange();
        this.tableTest();
    }
    this.getChange = function(){
        var string="";
        for(var j=0;j<this.data.length;j++){
            console.log('dataLength',this.data.length);
            var findParam=this.changeContainsClass(this.data[j]);
            if(findParam){
            var oneChangeObj=this.assignParams(this.data[j]);
            this.finalTables+=this.createElement(oneChangeObj);
            //console.log(string);
            //+=string;
            //this.parsedData="";
            }
            //console.log(fi//);
        }
        if(this.finalTables == ""){
            //this.addToArray('brak','zastępstw',0);
            string='nic';
            //
            this.finalTables+=string;
            this.parsedData="";
            //this.finalTables==
        }
    }
    this.changeContainsClass = function(oneChange){
    if(this.className =='all'||this.className==""){
        //console.log('null on change');
        return true;
    };
    var classId=oneChange['classes'];
        for(var i=0;i<classId.length;i++){
            if(this.className == classId[i]){
                //console.log('full on change');
                return true;
            }
        }
    return false;
}
    this.addToArray=function(keyText,keyValue,tabs){
        var text = this.createElement(keyText,keyValue,tabs);
        if(text !=""){
            this.parsedData+=text;
            //this.i++;
        }
    }
    this.tableTest=function(){
        var el = document.getElementById(this.divId);
        var text="";
        //console.log(a.innerHTML);
        el.innerHTML=this.finalTables;
    }
    this.newParams=function(key,value,ifchanges){
        if (ifchanges == true){

        }

    }
    this.assignParams = function(oneChange){
        this.i=0;
        var keyText="";
        //var x = exData;
        var keyValue=""
        var elInChange={};
        for (k in oneChange){

    //console.log('hey',k);
    //console.log('hey',this.fields);
            keyText=this.fields[k];
            if(k=='cancelled'){
                keyValue=this.getType(oneChange[k]);
                if(keyText != undefined){
                    elInChange[keyText]=keyValue;
                }
                //this.addToArray(keyText,keyValue,0);
            }
            else if(k =='changes'){
                //do nothing
            }
            else{
                keyValue=oneChange[k];
                //x[keyText] =oneChange[k];
                //console.log(keyText + ' '+keyValue);
                if(keyText != undefined){
                    elInChange[keyText]=keyValue;
                }
                //this.addToArray(keyText,keyValue,0);
            }
        }
        for(j in oneChange['changes']){
            keyText=this.fields[j];
                    //x['z'+keyText] =changesIn[l];

            keyValue=oneChange['changes'][j];
            elInChange[keyText]+=' -> '+keyValue;

        }

        return elInChange;
        //this.createElement(elInChange);
        //console.log('changes ',elInChange);
    }
    this.getType= function(value){
        if(value=='true'){
            //this.style='backBlue'
            return 'anulowanie';
        }
        else{
            //this.style='backRed'
            return 'zastępstwo';
        }
    }
    this.createElement=function(obj){
        if(obj=={}){return "";}
        console.log('onj',obj);
        //if(key==undefined||value==""){return '';};
        //var tabString=this.createTabs(tabs);
        //console.log('tabs',tabs);
        var allLi=""
        for(var i=0;i<patternOfDisplay.length;i++){

           if(obj[patternOfDisplay[i]] == undefined ||obj[patternOfDisplay[i]] == ""){
               //do nothing
           }
            else{
                allLi+=this.createLi(patternOfDisplay[i],obj[patternOfDisplay[i]]);
            }
        }
        var string = '
'+allLi+'
';
        return string;
    }
    this.createLi=function(name,text){
    return '
'+name+' '+text+'
';
    }

}<|endoftext|>


<commit_before>import Ember from 'ember';

export function fieldType(content, fieldName) {
  if (!content) { return; }
  let meta;

  try {
    meta = content.constructor.metaForProperty(fieldName);
  } catch (err) {
    return;
  }

  // meta.options.fieldType is our convention for annotating
  // models. meta.type is the name of the transform that ember-data
  // is using, which we keep as a fallback.
  let type = meta.options && meta.options.fieldType;

  if (!type && meta.type) {
    // lift the default ember-data transform names into our core
    // types
    type = `@cardstack/core-types::${meta.type}`;
  }

  if (type) {
    type = stripNamespace(type);
  }
  return type;
}

function stripNamespace(type) {
  // Right now the actual field editor components get flattened down
  // out of their namespaces, so we throw away everything but the
  // last bit of their names here. This problem is easier to solve
  // once I can integrate a module-unification resolver, so I'm
  // leaving it like this for now.
  let parts = type.split(/[/:]/g);
  return parts[parts.length - 1];
}

export default Ember.Helper.helper(fieldType);
<commit_msg>Fix field editors for names that have dashes<commit_after>import { camelize } from '@ember/string';
import Ember from 'ember';

export function fieldType(content, fieldName) {
  if (!content) { return; }
  let meta;

  fieldName = camelize(fieldName);

  try {
    meta = content.constructor.metaForProperty(fieldName);
  } catch (err) {
    return;
  }

  // meta.options.fieldType is our convention for annotating
  // models. meta.type is the name of the transform that ember-data
  // is using, which we keep as a fallback.
  let type = meta.options && meta.options.fieldType;

  if (!type && meta.type) {
    // lift the default ember-data transform names into our core
    // types
    type = `@cardstack/core-types::${meta.type}`;
  }

  if (type) {
    type = stripNamespace(type);
  }
  return type;
}

function stripNamespace(type) {
  // Right now the actual field editor components get flattened down
  // out of their namespaces, so we throw away everything but the
  // last bit of their names here. This problem is easier to solve
  // once I can integrate a module-unification resolver, so I'm
  // leaving it like this for now.
  let parts = type.split(/[/:]/g);
  return parts[parts.length - 1];
}

export default Ember.Helper.helper(fieldType);
<|endoftext|>