<commit_before>//component/icon.js

var Icon = React.createClass({
  render: function() {
    var className = 'icon ' + this.props.icon;
    return
  }
});

//component/link.js

var Link = React.createClass({
  render: function() {
    console.log(this.props);
    var href = this.props.href ? this.props.href : 'javascript:;',
        icon = this.props.icon ? <Icon icon={this.props.icon} />  : '',
        className = (this.props.button ? 'button-block button-' + this.props.button : 'button-text') +
                    (this.props.fadeIn ? ' fade-in-link' : '');
    return (

        {this.props.icon ? icon : '' }
        {this.props.label}

    );
  }
});

//component/splash.js
var splashStyle = {
  color: 'white',
  backgroundImage: 'url(' + lbry.imagePath('lbry-bg.png') + ')',
  backgroundSize: 'cover',
  minHeight: '100vh',
  minWidth: '100vw',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center'
}, splashMessageStyle = {
  marginTop: '24px'
};

var SplashScreen = React.createClass({
  propTypes: {
    message: React.PropTypes.string,
  },
  render: function() {
    var imgSrc = lbry.imagePath('lbry-white-485x160.png');
    return (

             {this.props.message}

    );
  }
});

//component/credit-amount.js
var creditAmountStyle = {
  color: '#216C2A',
  fontWeight: 'bold',
  fontSize: '0.8em'
}, estimateStyle = {
  marginLeft : '5px',
  color: '#aaa',
}, menuStyle = {
  position: 'relative',
  top: '3px',
  marginLeft: '2px'
}, menuItemStyle = {
  marginLeft: '3px'
};

var CreditAmount = React.createClass({
  propTypes: {
    amount: React.PropTypes.number,
  },
  render: function() {
    var formattedAmount = lbry.formatCredits(this.props.amount);
    return (

          {formattedAmount}
          { this.props.isEstimate ? (est) : null }

          <Link href='#' icon="icon-gear" fadeIn={true} style={menuItemStyle} />

    );
  }
});

//component/header.js
var logoStyle = {
  padding: '48px 12px',
  textAlign: 'center',
  maxHeight: '80px',
},
    balanceStyle = {
  float: 'right',
  marginTop: '3px'
},
    imgStyle = { //@TODO: remove this, img should be properly scaled once size is settled
  height: '80px'
};

var Header = React.createClass({
  getInitialState: function() {
    return {
      balance: 0
    };
  },
  componentDidMount: function() {
    lbry.getBalance(function(balance) {
      this.setState({
        balance: balance
      });
    }.bind(this));
  },
  render: function() {
    return (

          <CreditAmount amount={this.state.balance}/>

    );
  }
});

//component/discover.js

var searchInputStyle = {
  width: '400px',
  display: 'block',
  marginBottom: '48px',
  marginLeft: 'auto',
  marginRight: 'auto'
},
    fetchResultsStyle = {
  color: '#888',
  textAlign: 'center',
  fontSize: '1.2em'
};

var SearchActive = React.createClass({
  render: function() {
    return (

        Looking up the Dewey Decimals

    );
  }
});

var searchNoResultsStyle = {
  textAlign: 'center'
}, searchNoResultsMessageStyle = {
  fontStyle: 'italic',
  marginRight: '5px'
};

var SearchNoResults = React.createClass({
  render: function() {
    return (

          No one has checked anything in for {this.props.query} yet.
          <Link label="Be the first" href="javascript:alert('aww I do nothing')" />

    );
  }
});

var SearchResults = React.createClass({
  render: function() {
    var rows = [];
    console.log('results');
    console.log('made it here');
    this.props.results.forEach(function(result) {
      rows.push(
        <SearchResultRow name={result.name} title={result.stream_name} imgUrl={result.thumbnail}
                          description={result.description} cost_est={result.cost_est} />
      );
    });
    console.log(this.props.results);
    console.log(rows);
    console.log('done');
    return (

{rows}

    );
  }
});

var searchRowImgStyle = {
  maxHeight: '100px',
  display: 'block',
  marginLeft: 'auto',
  marginRight: 'auto',
  float: 'left'
},
    searchRowCostStyle = {
  float: 'right',
  marginLeft: '20px',
  marginTop: '5px',
  display: 'inline-block'
},
    searchRowNameStyle = {
  fontSize: '0.9em',
  color: '#666',
  marginBottom: '24px',
  clear: 'both'
},
    searchRowDescriptionStyle = {
  color : '#444',
  marginBottom: '24px',
  fontSize: '0.9em'
};

var SearchResultRow = React.createClass({
  render: function() {
    var uri = 'lbry://' + this.props.name;
    return (

            <CreditAmount amount={this.props.cost_est} isEstimate={true}/>

{this.props.title}

{uri}

{this.props.description}

            <Link href={uri} label="Watch" icon="icon-play" button="primary" />
            <Link href={uri} label="Download" icon="icon-download" button="alt" />

    );
  }
});

var discoverMainStyle = {
  color: '#333'
};

var Discover = React.createClass({
  userTypingTimer: null,

  getInitialState: function() {
    return {
      results: [],
      searching: false,
      query: ''
    };
  },

  search: function() {
    if (this.state.query)
    {
      console.log('search');
      lbry.search(this.state.query, this.searchCallback.bind(this, this.state.query));
    }
    else
    {
      this.setState({
        searching: false,
        results: []
      });
    }
  },

  searchCallback: function(originalQuery, results) {
    if (this.state.searching) //could have canceled while results were pending, in which case nothing to do
    {
      this.setState({
        results: results,
        searching: this.state.query != originalQuery, //multiple searches can be out, we're only done if we receive one we actually care about
      });
    }
  },

  onQueryChange: function(event) {
    if (this.userTypingTimer)
    {
      clearTimeout(this.userTypingTimer);
    }

    //@TODO: Switch to React.js timing
    this.userTypingTimer = setTimeout(this.search, 800); // 800ms delay, tweak for faster/slower

    this.setState({
      searching: event.target.value.length > 0,
      query: event.target.value
    });
  },

  render: function() {
    console.log(this.state);
    return (

<input type="search" style={searchInputStyle} onChange={this.onQueryChange}
          placeholder="Find movies, music, games, and more"/>

        { this.state.searching ? <SearchActive /> : null }
        { !this.state.searching && this.state.results.length ? <SearchResults results={this.state.results} /> : null }
        { !this.state.searching && !this.state.results.length && this.state.query ? <SearchNoResults query={this.state.query} /> : null }

    );
  }
});

//component/home.js

var homeStyles = {
    width: '800px',
    marginLeft: 'auto',
    marginRight: 'auto',
};

var Home = React.createClass({
  render: function() {
    return (

        <Discover />

    );
  }
});

//main.js
var init = function() {
  var canvas = document.getElementById('canvas');

  ReactDOM.render(
    <SplashScreen message="Connecting"/>,
    canvas
  );

  lbry.connect(function() {
    ReactDOM.render(<Home/>, canvas);
  })
};

init();

<commit_msg>Move top bar into its own component<commit_after>//component/icon.js

var Icon = React.createClass({
  render: function() {
    var className = 'icon ' + this.props.icon;
    return
  }
});

//component/link.js

var Link = React.createClass({
  render: function() {
    console.log(this.props);
    var href = this.props.href ? this.props.href : 'javascript:;',
        icon = this.props.icon ? <Icon icon={this.props.icon} />  : '',
        className = (this.props.button ? 'button-block button-' + this.props.button : 'button-text') +
                    (this.props.fadeIn ? ' fade-in-link' : '');
    return (

        {this.props.icon ? icon : '' }
        {this.props.label}

    );
  }
});

//component/splash.js
var splashStyle = {
  color: 'white',
  backgroundImage: 'url(' + lbry.imagePath('lbry-bg.png') + ')',
  backgroundSize: 'cover',
  minHeight: '100vh',
  minWidth: '100vw',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center'
}, splashMessageStyle = {
  marginTop: '24px'
};

var SplashScreen = React.createClass({
  propTypes: {
    message: React.PropTypes.string,
  },
  render: function() {
    var imgSrc = lbry.imagePath('lbry-white-485x160.png');
    return (

             {this.props.message}

    );
  }
});

//component/credit-amount.js
var creditAmountStyle = {
  color: '#216C2A',
  fontWeight: 'bold',
  fontSize: '0.8em'
}, estimateStyle = {
  marginLeft : '5px',
  color: '#aaa',
};

var CreditAmount = React.createClass({
  propTypes: {
    amount: React.PropTypes.number,
  },
  render: function() {
    var formattedAmount = lbry.formatCredits(this.props.amount);
    return (

        {formattedAmount}
        { this.props.isEstimate ? (est) : null }

    );
  }
});

//component/header.js
var logoStyle = {
  padding: '48px 12px',
  textAlign: 'center',
  maxHeight: '80px',
},
    balanceStyle = {
//  float: 'right',
  marginTop: '3px'
},
    imgStyle = { //@TODO: remove this, img should be properly scaled once size is settled
  height: '80px'
};

var Header = React.createClass({
  render: function() {
    return (

        <TopBar />

    );
  }
});

var topBarStyle = {
  'float': 'right'
};

var menuStyle = {
  position: 'relative',
  top: '3px',
  marginLeft: '2px'
}, menuItemStyle = {
  marginLeft: '3px'
};

var TopBar = React.createClass({
  getInitialState: function() {
    return {
      balance: 0
    };
  },
  componentDidMount: function() {
    lbry.getBalance(function(balance) {
      this.setState({
        balance: balance
      });
    }.bind(this));
  },

  render: function() {
    return (

        <CreditAmount amount={this.state.balance}/>

        <Link href='#' icon="icon-gear" fadeIn={true} style={menuItemStyle} />

    );
  }
});

//component/discover.js

var searchInputStyle = {
  width: '400px',
  display: 'block',
  marginBottom: '48px',
  marginLeft: 'auto',
  marginRight: 'auto'
},
    fetchResultsStyle = {
  color: '#888',
  textAlign: 'center',
  fontSize: '1.2em'
};

var SearchActive = React.createClass({
  render: function() {
    return (

        Looking up the Dewey Decimals

    );
  }
});

var searchNoResultsStyle = {
  textAlign: 'center'
}, searchNoResultsMessageStyle = {
  fontStyle: 'italic',
  marginRight: '5px'
};

var SearchNoResults = React.createClass({
  render: function() {
    return (

          No one has checked anything in for {this.props.query} yet.
          <Link label="Be the first" href="javascript:alert('aww I do nothing')" />

    );
  }
});

var SearchResults = React.createClass({
  render: function() {
    var rows = [];
    console.log('results');
    console.log('made it here');
    this.props.results.forEach(function(result) {
      rows.push(
        <SearchResultRow name={result.name} title={result.stream_name} imgUrl={result.thumbnail}
                          description={result.description} cost_est={result.cost_est} />
      );
    });
    console.log(this.props.results);
    console.log(rows);
    console.log('done');
    return (

{rows}

    );
  }
});

var searchRowImgStyle = {
  maxHeight: '100px',
  display: 'block',
  marginLeft: 'auto',
  marginRight: 'auto',
  float: 'left'
},
    searchRowCostStyle = {
  float: 'right',
  marginLeft: '20px',
  marginTop: '5px',
  display: 'inline-block'
},
    searchRowNameStyle = {
  fontSize: '0.9em',
  color: '#666',
  marginBottom: '24px',
  clear: 'both'
},
    searchRowDescriptionStyle = {
  color : '#444',
  marginBottom: '24px',
  fontSize: '0.9em'
};

var SearchResultRow = React.createClass({
  render: function() {
    var uri = 'lbry://' + this.props.name;
    return (

            <CreditAmount amount={this.props.cost_est} isEstimate={true}/>

{this.props.title}

{uri}

{this.props.description}

            <Link href={uri} label="Watch" icon="icon-play" button="primary" />
            <Link href={uri} label="Download" icon="icon-download" button="alt" />

    );
  }
});

var discoverMainStyle = {
  color: '#333'
};

var Discover = React.createClass({
  userTypingTimer: null,

  getInitialState: function() {
    return {
      results: [],
      searching: false,
      query: ''
    };
  },

  search: function() {
    if (this.state.query)
    {
      console.log('search');
      lbry.search(this.state.query, this.searchCallback.bind(this, this.state.query));
    }
    else
    {
      this.setState({
        searching: false,
        results: []
      });
    }
  },

  searchCallback: function(originalQuery, results) {
    if (this.state.searching) //could have canceled while results were pending, in which case nothing to do
    {
      this.setState({
        results: results,
        searching: this.state.query != originalQuery, //multiple searches can be out, we're only done if we receive one we actually care about
      });
    }
  },

  onQueryChange: function(event) {
    if (this.userTypingTimer)
    {
      clearTimeout(this.userTypingTimer);
    }

    //@TODO: Switch to React.js timing
    this.userTypingTimer = setTimeout(this.search, 800); // 800ms delay, tweak for faster/slower

    this.setState({
      searching: event.target.value.length > 0,
      query: event.target.value
    });
  },

  render: function() {
    console.log(this.state);
    return (

<input type="search" style={searchInputStyle} onChange={this.onQueryChange}
          placeholder="Find movies, music, games, and more"/>

        { this.state.searching ? <SearchActive /> : null }
        { !this.state.searching && this.state.results.length ? <SearchResults results={this.state.results} /> : null }
        { !this.state.searching && !this.state.results.length && this.state.query ? <SearchNoResults query={this.state.query} /> : null }

    );
  }
});

//component/home.js

var homeStyles = {
    width: '800px',
    marginLeft: 'auto',
    marginRight: 'auto',
};

var Home = React.createClass({
  render: function() {
    return (

        <Discover />

    );
  }
});

//main.js
var init = function() {
  var canvas = document.getElementById('canvas');

  ReactDOM.render(
    <SplashScreen message="Connecting"/>,
    canvas
  );

  lbry.connect(function() {
    ReactDOM.render(<Home/>, canvas);
  })
};

init();

<|endoftext|>


<commit_before>var map;

var markerimage = {
  url: 'img/map/marker.png',
  size: new google.maps.Size(31,50),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(16,50),
  scaledSize: new google.maps.Size(31, 50)
};

function initMap() {

  var uluru = {lat: 37.544935, lng:  127.039454};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 17,
    center: uluru
  });
  var marker = new google.maps.Marker({
    position: uluru,
    map: map,
    icon: markerimage
  });
}

$(document).ready(function() {

  initMap();
});
<commit_msg>disabled mouse scroll<commit_after>var map;

var markerimage = {
  url: 'img/map/marker.png',
  size: new google.maps.Size(31,50),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(16,50),
  scaledSize: new google.maps.Size(31, 50)
};

function initMap() {

  var seoulforest = {lat: 37.544935, lng:  127.039454};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 17,
    center: seoulforest,
    scrollwheel: false,
  });
  var marker = new google.maps.Marker({
    position: seoulforest,
    map: map,
    icon: markerimage
  });
}

$(document).ready(function() {

  initMap();
});
<|endoftext|>


<commit_before>var wikiUrl = "https://orga.sha2017.org/";
var wikiApi = wikiUrl + "api.php";
var map, base_layers, overlay_layers;

var popupsEnabled = { enabled: true };

function isMobile() {
	try {
		document.createEvent("TouchEvent");
		return true;
	}
	catch (e) {
		return false;
	}
}

$(function () {
	$.getJSON('config.json', createMap);
});

function createMap(config) {

	base_layers = new ol.layer.Group({
		title: 'Base Layers',
		layers: [
			new ol.layer.Tile({title: "Blank", type: 'base'}),
			new ol.layer.Tile({title: "OSM", type: 'base', source: new ol.source.OSM()}),
		]
	});

	overlay_layers = new ol.layer.Group({
		title: 'Overlays', layers: []
	});

	measurement_layers = new ol.layer.Group({
		layers: []
	});

	map = new ol.Map({
		layers: [base_layers, overlay_layers, measurement_layers],
		target: 'map',
		controls: ol.control.defaults({
			attributionOptions: ({
				collapsible: false
			})
		}).extend([new ol.control.ScaleLine()]),
		view: new ol.View({
			center: (new ol.geom.Point([5.52579, 52.28488])).transform('EPSG:4326', 'EPSG:3857').getCoordinates(),
			zoom: 17,
			minZoom: config.zoom_range[0],
			maxZoom: config.zoom_range[1]
		})
	});

	initMeasurements(map, measurement_layers, popupsEnabled);

	var layerSwitcher = new ol.control.LayerSwitcher();
	map.addControl(layerSwitcher);

	$.getJSON('vector_layers.json', addVectorLayers);

	config.layers.forEach(function (layer) {
		var layerTile = new ol.layer.Tile({
			title: layer.name,
			visible: layer.visible,
			source: new ol.source.XYZ({
				url: 'tiles/' + layer.path + '/{z}/{x}/{y}.png'
			}),
			minZoom: config.zoom_range[0],
			maxZoom: config.zoom_range[1]

		});
		overlay_layers.getLayers().push(layerTile);
	});

	// The <canvas> element doesn't seem to get sized correctly
	// on page load, which causes vector element hover to break.
	// Update the size after a small delay.
	setTimeout(function () {
		map.updateSize();
	}, 50);
}

function generateStyle(style, props, resolution) {
	var data = {};
	if ("line-color" in style) {
		data['stroke'] = new ol.style.Stroke({
			color: style['line-color'],
			width: style['line-width']
		});
	}

	if ("polygon-fill" in style) {
		data['fill'] = new ol.style.Fill({
			color: style['polygon-fill']
		});
	}

	if ("z-index" in style) {
		data['zIndex'] = style['z-index'];
	}

	if ("text-color" in style && "text" in props) {
		data['text'] = new ol.style.Text({
			text: props['text'],
			textAlign: 'center',
			scale: props['text_size'] / 5 / resolution,
			rotation: props['text_rotation'] !== undefined ? (-props['text_rotation'] / 180.0 * Math.PI) : 0,
			rotateWithView: true,
			/*
			 stroke: new ol.style.Stroke({
			 color: [230, 230, 230, 0.9],
			 width: 4 * resolution,
			 }),
			 */
		});
	}

	return new ol.style.Style(data);
}

function addVectorLayers(layer_data) {
	$.each(layer_data.layers, function (index, layer) {
		var vectorSource = new ol.source.Vector({
			url: 'vector/' + layer.source,
			format: new ol.format.GeoJSON()
		});

		var vectorLayer = new ol.layer.Vector({
			title: layer.name,
			source: vectorSource,
			visible: layer.visible,
			style: function(feature, resolution) {
				var props = feature.getProperties();
				return generateStyle(layer_data.styles[layer.name][props['layer']], props, resolution);
			},
			updateWhileAnimating: !isMobile(),
			updateWhileInteracting: !isMobile()
		});
		vectorLayer.setZIndex(layer['z-index']);
		overlay_layers.getLayers().push(vectorLayer);
	});

	addPopupActions(map, layer_data);
}

function addPopupActions(map, layer_data) {
	// Highlight element on hover:
	var hoverAction = new ol.interaction.Select({
		condition: ol.events.condition.pointerMove,
		filter: function(feature, layer) {
			if (layer === null) {
				return false;
			}
			var style = layer_data.styles[layer.getProperties()['title']][feature.getProperties()['layer']];
			if ('selectable' in style && !style['selectable']) {
				return false;
			}
			return true;
		}
	});
	map.addInteraction(hoverAction);

	var container = $('#popup');
	var content = $('#popup-content');
	var closer = $('#popup-closer');

	var otherElementsThatHaveToBeMovedToTheLeft = $('.layer-switcher, .measurement-tool, .ol-attribution');

	closer.click(function () {
		container.css("right", "-400px");
		otherElementsThatHaveToBeMovedToTheLeft.css("right", "");
		this.blur();
		return false;
	});

	// Display popup on click
	var clickAction = new ol.interaction.Select({
		filter: function(feature, layer) {
			if (layer === null) {
				return false;
			}
			var style = layer_data.styles[layer.getProperties()['title']][feature.getProperties()['layer']];
			if ('selectable' in style && !style['selectable']) {
				return false;
			}
			return true;
		}
	});
	map.addInteraction(clickAction);
	clickAction.on('select', function (e) {
		if(!popupsEnabled.enabled) {
			return;
		}
		if (e.selected.length > 0) {
			var props = e.selected[0].getProperties();
			if(!props['layer']) {
				return;
			}
			var html = 'Layer: ' + props['layer'] + "
Handle: 0x" + props['entityhandle'] + "
";
			for (attr in props) {
				if (!['layer', 'entityhandle', 'geometry'].includes(attr) && props[attr] != null) {
					html += '' + attr + ': ' + props[attr] + '
';
				}
			}
			content.html(html);
			container.css("right", "0");
			otherElementsThatHaveToBeMovedToTheLeft.css("right", "407px");

			$.ajax({
				url: wikiApi + "?action=askargs&printouts=Summary&format=json&conditions=Handle::0x" + props['entityhandle'],
				dataType: "jsonp",
				jsonp: "callback",
				success: function (data) {
					if (Object.keys(data.query.results).length == 0) {
						html += "
This object is not yet defined in the wiki. If there is an page on the wiki representing this object, add the following snippet to that page:
";
						html += "
{{MapObject|Handle = 0x" + props['entityhandle'] + "}}
";
						content.html(html);
					} else {
						content.html("");
						$.each(data.query.results, function (index, item) {
							if ('printouts' in item) {
								$.ajax({
									url: wikiApi + "?action=parse&format=json&page=" + item.fulltext,
									dataType: "jsonp",
									jsonp: "callback",
									cache: false,
									success: function (data) {
										html = "
";
										html += "
" + item.fulltext + "
";
										html += data.parse.text["*"];
										html += "
";
										content.html(content.html() + html);
									},
									error: function (req, error1, error2) {
										html = "
Wiki-data is currently unavailable
";
										content.html(content.html() + html);
									}
								});
							}
						});
					}
				},
				error: function () {
					content.html(html + "
Wiki-data is currently unavailable
");
				}
			});
		}
		clickAction.getFeatures().clear()
	});
}
<commit_msg>Added text color support.<commit_after>var wikiUrl = "https://orga.sha2017.org/";
var wikiApi = wikiUrl + "api.php";
var map, base_layers, overlay_layers;

var popupsEnabled = { enabled: true };

function isMobile() {
	try {
		document.createEvent("TouchEvent");
		return true;
	}
	catch (e) {
		return false;
	}
}

$(function () {
	$.getJSON('config.json', createMap);
});

function createMap(config) {

	base_layers = new ol.layer.Group({
		title: 'Base Layers',
		layers: [
			new ol.layer.Tile({title: "Blank", type: 'base'}),
			new ol.layer.Tile({title: "OSM", type: 'base', source: new ol.source.OSM()}),
		]
	});

	overlay_layers = new ol.layer.Group({
		title: 'Overlays', layers: []
	});

	measurement_layers = new ol.layer.Group({
		layers: []
	});

	map = new ol.Map({
		layers: [base_layers, overlay_layers, measurement_layers],
		target: 'map',
		controls: ol.control.defaults({
			attributionOptions: ({
				collapsible: false
			})
		}).extend([new ol.control.ScaleLine()]),
		view: new ol.View({
			center: (new ol.geom.Point([5.52579, 52.28488])).transform('EPSG:4326', 'EPSG:3857').getCoordinates(),
			zoom: 17,
			minZoom: config.zoom_range[0],
			maxZoom: config.zoom_range[1]
		})
	});

	initMeasurements(map, measurement_layers, popupsEnabled);

	var layerSwitcher = new ol.control.LayerSwitcher();
	map.addControl(layerSwitcher);

	$.getJSON('vector_layers.json', addVectorLayers);

	config.layers.forEach(function (layer) {
		var layerTile = new ol.layer.Tile({
			title: layer.name,
			visible: layer.visible,
			source: new ol.source.XYZ({
				url: 'tiles/' + layer.path + '/{z}/{x}/{y}.png'
			}),
			minZoom: config.zoom_range[0],
			maxZoom: config.zoom_range[1]

		});
		overlay_layers.getLayers().push(layerTile);
	});

	// The <canvas> element doesn't seem to get sized correctly
	// on page load, which causes vector element hover to break.
	// Update the size after a small delay.
	setTimeout(function () {
		map.updateSize();
	}, 50);
}

function generateStyle(style, props, resolution) {
	var data = {};
	if ("line-color" in style) {
		data['stroke'] = new ol.style.Stroke({
			color: style['line-color'],
			width: style['line-width']
		});
	}

	if ("polygon-fill" in style) {
		data['fill'] = new ol.style.Fill({
			color: style['polygon-fill']
		});
	}

	if ("z-index" in style) {
		data['zIndex'] = style['z-index'];
	}

	if ("text-color" in style && "text" in props) {
		data['text'] = new ol.style.Text({
			text: props['text'],
			textAlign: 'center',
			scale: props['text_size'] / 5 / resolution,
			rotation: props['text_rotation'] !== undefined ? (-props['text_rotation'] / 180.0 * Math.PI) : 0,
			rotateWithView: true,
			fill: new ol.style.Fill({ color: style['text-color'] })
		});
	}

	return new ol.style.Style(data);
}

function addVectorLayers(layer_data) {
	$.each(layer_data.layers, function (index, layer) {
		var vectorSource = new ol.source.Vector({
			url: 'vector/' + layer.source,
			format: new ol.format.GeoJSON()
		});

		var vectorLayer = new ol.layer.Vector({
			title: layer.name,
			source: vectorSource,
			visible: layer.visible,
			style: function(feature, resolution) {
				var props = feature.getProperties();
				return generateStyle(layer_data.styles[layer.name][props['layer']], props, resolution);
			},
			updateWhileAnimating: !isMobile(),
			updateWhileInteracting: !isMobile()
		});
		vectorLayer.setZIndex(layer['z-index']);
		overlay_layers.getLayers().push(vectorLayer);
	});

	addPopupActions(map, layer_data);
}

function addPopupActions(map, layer_data) {
	// Highlight element on hover:
	var hoverAction = new ol.interaction.Select({
		condition: ol.events.condition.pointerMove,
		filter: function(feature, layer) {
			if (layer === null) {
				return false;
			}
			var style = layer_data.styles[layer.getProperties()['title']][feature.getProperties()['layer']];
			if ('selectable' in style && !style['selectable']) {
				return false;
			}
			if (feature.getGeometry().getType() == "Point" && 'text-selectable' in style && !style['text-selectable']) {
				return false;
			}
			return true;
		}
	});
	map.addInteraction(hoverAction);

	var container = $('#popup');
	var content = $('#popup-content');
	var closer = $('#popup-closer');

	var otherElementsThatHaveToBeMovedToTheLeft = $('.layer-switcher, .measurement-tool, .ol-attribution');

	closer.click(function () {
		container.css("right", "-400px");
		otherElementsThatHaveToBeMovedToTheLeft.css("right", "");
		this.blur();
		return false;
	});

	// Display popup on click
	var clickAction = new ol.interaction.Select({
		filter: function(feature, layer) {
			if (layer === null) {
				return false;
			}
			var style = layer_data.styles[layer.getProperties()['title']][feature.getProperties()['layer']];
			if ('selectable' in style && !style['selectable']) {
				return false;
			}
			if (feature.getGeometry().getType() == "Point" && 'text-selectable' in style && !style['text-selectable']) {
				return false;
			}
			return true;
		}
	});
	map.addInteraction(clickAction);
	clickAction.on('select', function (e) {
		if(!popupsEnabled.enabled) {
			return;
		}
		if (e.selected.length > 0) {
			var props = e.selected[0].getProperties();
			if(!props['layer']) {
				return;
			}
			var html = 'Layer: ' + props['layer'] + "
Handle: 0x" + props['entityhandle'] + "
";
			for (attr in props) {
				if (!['layer', 'entityhandle', 'geometry'].includes(attr) && props[attr] != null) {
					html += '' + attr + ': ' + props[attr] + '
';
				}
			}
			content.html(html);
			container.css("right", "0");
			otherElementsThatHaveToBeMovedToTheLeft.css("right", "407px");

			$.ajax({
				url: wikiApi + "?action=askargs&printouts=Summary&format=json&conditions=Handle::0x" + props['entityhandle'],
				dataType: "jsonp",
				jsonp: "callback",
				success: function (data) {
					if (Object.keys(data.query.results).length == 0) {
						html += "
This object is not yet defined in the wiki. If there is an page on the wiki representing this object, add the following snippet to that page:
";
						html += "
{{MapObject|Handle = 0x" + props['entityhandle'] + "}}
";
						content.html(html);
					} else {
						content.html("");
						$.each(data.query.results, function (index, item) {
							if ('printouts' in item) {
								$.ajax({
									url: wikiApi + "?action=parse&format=json&page=" + item.fulltext,
									dataType: "jsonp",
									jsonp: "callback",
									cache: false,
									success: function (data) {
										html = "
";
										html += "
" + item.fulltext + "
";
										html += data.parse.text["*"];
										html += "
";
										content.html(content.html() + html);
									},
									error: function (req, error1, error2) {
										html = "
Wiki-data is currently unavailable
";
										content.html(content.html() + html);
									}
								});
							}
						});
					}
				},
				error: function () {
					content.html(html + "
Wiki-data is currently unavailable
");
				}
			});
		}
		clickAction.getFeatures().clear()
	});
}
<|endoftext|>


<commit_before>function map(data){

    // Global varibale
    CURRMUN = "Upplands Väsby";

    var zoom = d3.behavior.zoom()
        .scaleExtent([1, 8])
        .on("zoom", move);

    var mapDiv = $("#map");

    var margin = {top: 20, right: 20, bottom: 20, left: 20},
        width = mapDiv.width() - margin.right - margin.left,
        height = mapDiv.height() - margin.top - margin.bottom;

    //initialize color scale
    color = new Map();
    color.set("Moderaterna", "#52BDEC");
    color.set("Centerpartiet", "#016A3A");
    color.set("Folkpartiet", "#0094D7");
    color.set("Kristdemokraterna", "#231977");
    color.set("Miljöpartiet", "#53A045");
    color.set("Socialdemokraterna", "#ED1B34");
    color.set("Vänsterpartiet", "#DA291C");
    color.set("Sverigedemokraterna", "#DDDD00");
    color.set("övriga partier", "gray");
    color.set("Odefinierad", "white");

    //initialize tooltip
    var tooltip = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

    var projection = d3.geo.mercator()
        .center([50, 60 ])
        .scale(600);

    var svg = d3.select("#map").append("svg")
        .attr("width", width)
        .attr("height", height)
        .call(zoom);

    var path = d3.geo.path()
        .projection(projection);

    g = svg.append("g");

    // load data and draw the map
    d3.json("data/sweden_mun.topojson", function(error, sweden) {

        var mun = topojson.feature(sweden, sweden.objects.swe_mun).features;

        draw(mun, data);

    });

    function draw(mun, electionData)
    {

        self.electionData = electionData;
        var year = document.getElementById("year").value;

        var mun = g.selectAll(".swe_mun").data(mun);
        var colorOfParty = partyColor(electionData, year);

        mun.enter().insert("path")
            .attr("class", "mun")
            .attr("d", path)
            .attr("title", function(d) {
                return d.properties.name;
            })
            .style("fill", function(d, i) {
                var index = 0;
                for(var l = 0; l < colorOfParty.length; ++l) {
                    // Compare region-name
                    if(d.properties.name == colorOfParty[l].reg) {
                        index = l;
                        break;
                    }

                };
                return color.get(colorOfParty[index].par);
            })
            .attr("stroke-width", 0.1)
            .attr("stroke", "black")

/*          // Fungerar inte, css krånglar
            //tooltip
            .on("mousemove", function(d) {
                tooltip.transition()
                .duration(200)
                .style("opacity", 0.9);
            })
            .on("mouseout", function(d) {
                tooltip.transition()
                .duration(200)
                .style("opacity", 0);
            })
*/
            .on("click", function(d) {
                var mun = currentMun(d.properties.name);
                //console.log(mun);
                donut1.drawMun(mun);
            })

            .on('mouseover', function(d) {
                d3.select(this)
                    .style('stroke-width', .5);
            })
            .on('mouseout', function(d) {
                d3.selectAll('path')
                    .style( 'stroke-width', 0.1 );
            });
    }

    this.colorByYear = function(electionYear) {

        //var year = document.getElementById("year").value;
        //console.log(electionYear);
        year = electionYear;

        donut1.drawMun(CURRMUN, electionYear);

        var colorOfParty = partyColor(electionData, year);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);
            point.style("fill-opacity", 1 )

            point.style("fill", function(d) {

            var index = NaN;
            for(var l = 0; l < colorOfParty.length; ++l) {
                // Compare region-name
                if(d.properties.name == colorOfParty[l].reg) {
                    index = l;
                    break;
                }
            };
            //console.log(index)
            if(!isNaN(index)) {
                return color.get(colorOfParty[index].par);
            } else {
                return color.get("Odefinierad");
            }

            });

        });
    }

    this.colorByParty = function(electionYear, party) {

        year = electionYear;
        //party = party;
        //var party = $('#party label.active input').val()

        //var year = document.getElementById("year").value;

        // TEMP
        if(!party) { var party = CURRMUN };

        var nested_data = d3.nest()
            .key(function(d) { return d.parti; })
            .sortValues(function(a, b) { return b[year] - a[year]; })
            .entries(electionData);

        nested_data = nested_data.filter(function(d) {
            return d.key == party;
        })

        var len = nested_data[0].values.length;

        var max, min;
        max = parseFloat(nested_data[0].values[0][year]);
        min = parseFloat(nested_data[0].values[len-1][year]);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);

            point.style("fill", function(d) {
                for(var i = 0; i < len; ++i) {

                    var region = nested_data[0].values[i];

                    if(d.properties.name == region.region) {

                        return !(isNaN(region[year])) ? color.get(party) : "white";

                    }
                };
            })

            point.style("fill-opacity", function(d) {

            var opac = 0;
            for(var i = 0; i < len; ++i) {

                var region = nested_data[0].values[i];
                // Compare region-name
                if(d.properties.name == region.region) {

                    opac = (parseFloat(region[year]) - min)/(max - min);
                    break;
                }
            };

            return opac;
            });
        });

    }

    function currentMun(mun) {

        if(mun) {
            CURRMUN = mun;
            return CURRMUN;
        } else {
            return CURRMUN;
        }

    }

    function partyColor(electionData, year) {

        var nested_data = d3.nest()
            .key(function(d) { return d.region; })
            .sortValues(function(a, b) { return b[year] - a[year]; })
            .entries(electionData);

        var colorOfParty = [];

        nested_data.forEach(function(d, i) {
            colorOfParty.push({reg: d.values[0].region, par: d.values[0].parti });
        });
        return colorOfParty;
    }

    //zoom and panning method
    function move() {

        var t = d3.event.translate;
        var s = d3.event.scale;

        zoom.translate(t);
        g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");

    }

    // Sends the name of the mun to other .js-files
    this.selectMun = function (mun) {

        //console.log(mun);

    }
}<commit_msg>Fixed a bug causing the donut chart not working properly<commit_after>function map(data){

    // Global varibale
    CURRMUN = "Upplands Väsby";

    var zoom = d3.behavior.zoom()
        .scaleExtent([1, 8])
        .on("zoom", move);

    var mapDiv = $("#map");

    var margin = {top: 20, right: 20, bottom: 20, left: 20},
        width = mapDiv.width() - margin.right - margin.left,
        height = mapDiv.height() - margin.top - margin.bottom;

    //initialize color scale
    color = new Map();
    color.set("Moderaterna", "#52BDEC");
    color.set("Centerpartiet", "#016A3A");
    color.set("Folkpartiet", "#0094D7");
    color.set("Kristdemokraterna", "#231977");
    color.set("Miljöpartiet", "#53A045");
    color.set("Socialdemokraterna", "#ED1B34");
    color.set("Vänsterpartiet", "#DA291C");
    color.set("Sverigedemokraterna", "#DDDD00");
    color.set("övriga partier", "gray");
    color.set("Odefinierad", "white");

    //initialize tooltip
    var tooltip = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

    var projection = d3.geo.mercator()
        .center([50, 60 ])
        .scale(600);

    var svg = d3.select("#map").append("svg")
        .attr("width", width)
        .attr("height", height)
        .call(zoom);

    var path = d3.geo.path()
        .projection(projection);

    g = svg.append("g");

    // load data and draw the map
    d3.json("data/sweden_mun.topojson", function(error, sweden) {

        var mun = topojson.feature(sweden, sweden.objects.swe_mun).features;

        draw(mun, data);

    });

    function draw(mun, electionData)
    {

        self.electionData = electionData;
        var year = document.getElementById("year").value;

        var mun = g.selectAll(".swe_mun").data(mun);
        var colorOfParty = partyColor(electionData, year);

        mun.enter().insert("path")
            .attr("class", "mun")
            .attr("d", path)
            .attr("title", function(d) {
                return d.properties.name;
            })
            .style("fill", function(d, i) {
                var index = 0;
                for(var l = 0; l < colorOfParty.length; ++l) {
                    // Compare region-name
                    if(d.properties.name == colorOfParty[l].reg) {
                        index = l;
                        break;
                    }

                };
                return color.get(colorOfParty[index].par);
            })
            .attr("stroke-width", 0.1)
            .attr("stroke", "black")

/*          // Fungerar inte, css krånglar
            //tooltip
            .on("mousemove", function(d) {
                tooltip.transition()
                .duration(200)
                .style("opacity", 0.9);
            })
            .on("mouseout", function(d) {
                tooltip.transition()
                .duration(200)
                .style("opacity", 0);
            })
*/
            .on("click", function(d) {

                selectedMun(d.properties.name);
            })

            .on('mouseover', function(d) {
                d3.select(this)
                    .style('stroke-width', .5);
            })
            .on('mouseout', function(d) {
                d3.selectAll('path')
                    .style( 'stroke-width', 0.1 );
            });
    }

    this.colorByYear = function(electionYear) {

        //var year = document.getElementById("year").value;
        //console.log(electionYear);
        year = electionYear;

        donut1.drawMun(CURRMUN, electionYear);

        var colorOfParty = partyColor(electionData, year);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);
            point.style("fill-opacity", 1 )

            point.style("fill", function(d) {

            var index = NaN;
            for(var l = 0; l < colorOfParty.length; ++l) {
                // Compare region-name
                if(d.properties.name == colorOfParty[l].reg) {
                    index = l;
                    break;
                }
            };
            //console.log(index)
            if(!isNaN(index)) {
                return color.get(colorOfParty[index].par);
            } else {
                return color.get("Odefinierad");
            }

            });

        });
    }

    this.colorByParty = function(electionYear, party) {

        year = electionYear;
        //party = party;
        //var party = $('#party label.active input').val()

        //var year = document.getElementById("year").value;

        // TEMP
        if(!party) { var party = CURRMUN };

        var nested_data = d3.nest()
            .key(function(d) { return d.parti; })
            .sortValues(function(a, b) { return b[year] - a[year]; })
            .entries(electionData);

        nested_data = nested_data.filter(function(d) {
            return d.key == party;
        })

        var len = nested_data[0].values.length;

        var max, min;
        max = parseFloat(nested_data[0].values[0][year]);
        min = parseFloat(nested_data[0].values[len-1][year]);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);

            point.style("fill", function(d) {
                for(var i = 0; i < len; ++i) {

                    var region = nested_data[0].values[i];

                    if(d.properties.name == region.region) {

                        return !(isNaN(region[year])) ? color.get(party) : "white";

                    }
                };
            })

            point.style("fill-opacity", function(d) {

            var opac = 0;
            for(var i = 0; i < len; ++i) {

                var region = nested_data[0].values[i];
                // Compare region-name
                if(d.properties.name == region.region) {

                    opac = (parseFloat(region[year]) - min)/(max - min);
                    break;
                }
            };

            return opac;
            });
        });

    }

    function currentMun(mun) {

        if(mun) {
            CURRMUN = mun;
            return CURRMUN;
        } else {
            return CURRMUN;
        }

    }

    function partyColor(electionData, year) {

        var nested_data = d3.nest()
            .key(function(d) { return d.region; })
            .sortValues(function(a, b) { return b[year] - a[year]; })
            .entries(electionData);

        var colorOfParty = [];

        nested_data.forEach(function(d, i) {
            colorOfParty.push({reg: d.values[0].region, par: d.values[0].parti });
        });
        return colorOfParty;
    }

    //zoom and panning method
    function move() {

        var t = d3.event.translate;
        var s = d3.event.scale;

        zoom.translate(t);
        g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");

    }

    // Sends the name of the mun to other .js-files
    function selectedMun(mun) {

        var electionYear = $('#year').slider('getValue');

        donut1.drawMun(mun, electionYear);

    }
}<|endoftext|>


<commit_before>NPC = function(game, scale, sprite) {
    this._game = game;
    var state = this._game.state.getCurrentState();

    startPosition = state.getItemPosition();

    Phaser.Sprite.call(this, this._game, startPosition[0], startPosition[1], sprite);

    this.scale.setTo(scale, scale);
}

NPC.prototype = Object.create(Phaser.Sprite.prototype);
NPC.prototype.constructor = NPC;

/**
 * Automatically called by World.update
 */
NPC.prototype.update = function() {
    // todo: update
}

NPC.prototype.spawnOrangeBox = function(player, npc) {
    // spawn 'orange box'
    var spawnPosition = player._game.state.getCurrentState().getItemPosition();

    var orangebox = player._game.add.sprite(spawnPosition[0], spawnPosition[1], 'orange_box');
    player._game.physics.enable(orangebox);
    orangebox.body.immovable = true;

    var orangegroup = new Phaser.Group(player._game, null, 'collectable_rpg', false);

    orangegroup.add(orangebox);

    player._game.add.existing(orangegroup);
}
<commit_msg>Stopped duplication of orange boxes.<commit_after>NPC = function(game, scale, sprite) {
    this._game = game;
    var state = this._game.state.getCurrentState();

    startPosition = state.getItemPosition();

    Phaser.Sprite.call(this, this._game, startPosition[0], startPosition[1], sprite);

    this.scale.setTo(scale, scale);

    this._hasOrangeBox = false;
}

NPC.prototype = Object.create(Phaser.Sprite.prototype);
NPC.prototype.constructor = NPC;

/**
 * Automatically called by World.update
 */
NPC.prototype.update = function() {
    // todo: update
}

NPC.prototype.spawnOrangeBox = function(player, npc) {
    if (this._hasOrangeBox) {
        // we are still looking for it
        console.log("exists");
    } else {
        // spawn 'orange box'
        var spawnPosition = player._game.state.getCurrentState().getItemPosition();

        var orangebox = player._game.add.sprite(spawnPosition[0], spawnPosition[1], 'orange_box');
        player._game.physics.enable(orangebox);
        orangebox.body.immovable = true;

        var orangegroup = new Phaser.Group(player._game, null, 'orangebox', false);

        orangegroup.add(orangebox);

        player._game.add.existing(orangegroup);

        this._hasOrangeBox = true;
    }
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.8.0
(function() {

  var BubbleChart, root,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  BubbleChart = (function() {
    function BubbleChart(container, data, config) {
      this.hide_details = __bind(this.hide_details, this);
      this.show_details = __bind(this.show_details, this);
      this.move_towards_year = __bind(this.move_towards_year, this);
      this.display_by_group = __bind(this.display_by_group, this);
      this.start = __bind(this.start, this);
      this.render = __bind(this.render, this);
      this.create_nodes = __bind(this.create_nodes, this);

      var max_amount;
      this.container = container;
      this.data = data;
      this.width = config.width;
      this.height = config.height;
      this.tooltip = CustomTooltip("startup_funding_tooltip", 210);

      this.center = {
        x: this.width / 2 ,
        y: this.height / 2
      };

      this.off_screen = {
        x: this.width + 300,
        y: this.height / 2
      };

      this.layout_gravity = -0.01;
      this.damper = 0.1;
      this.vis = null;
      this.nodes = [];
      this.force = null;
      this.circles = null;
      this.selected = false;
      this.investorSelected = false;
      this.currentSelection = null;

      this.colorRange = d3.scale.linear()
        .domain(config.colorRange.domain)
        .range(config.colorRange.range)

      max_amount = d3.max(this.data, function(d) {
        return parseInt(d.amount);
      });

      this.radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([4, 60]);
      this.create_nodes();
      this.render();
    }

    BubbleChart.prototype.create_nodes = function() {
      var self = this;

      this.data.forEach(function(d) {
          var node;
          if(parseInt(d.amount) <= 0) {
            return;
          }

          node = {
            id: d.id,
            radius: self.radius_scale(parseInt(d.amount)),
            value: d.amount,
            name: d.name,
            org: d.vc_list,
            group: d.stage,
            year: d.year,
            x: Math.random() * 900,
            y: Math.random() * 800
          };

          return self.nodes.push(node);
      });

      return this.nodes.sort(function(a, b) {
        return b.value - a.value;
      });
    };

    BubbleChart.prototype.render = function() {
      var self = this;

      this.vis = d3.select(this.container).append("svg").attr("width", "100%").attr("height", this.height).attr("id", "svg_vis");

      this.vis.on("click", function() {
        //self.selected = false;
      });

      this.circles = this.vis.selectAll("circle").data(this.nodes, function(d) {
        return d.id;
      });

      this.circles.enter()
      .append("circle")
      .each(function (d) {
        var strokeColor = d3.rgb(self.colorRange(d.org.length)).darker(),
            fillColor = self.colorRange(d.org.length);

        d3.select(this).attr({
          r: 0,
          "fill": fillColor,
          "fill-opacity": 0.8,
          "stroke-width": 1,
          "stroke": strokeColor,
          "id": "bubble_" + d.id,
          "class": "bubble"

        });

      })
      .on("mouseover", function(d, i) {
        if(!self.selected) {
          showBubbleDetails(self, this, d)
        }
      })
      .on("mouseout", function(d, i) {
        if(!self.selected) {
          hideBubbleDetails(self, this, d)
        }
      })
      .on("click", function(d, i) {
        if(!self.selected) {
          self.currentSelection = this;
          self.selected = true;
          var counter = 0

          d.org.forEach(function(name){
            counter = counter + 1;
            d3.select("text#vc-title-" + counter).text(name);
            return true;
          });

          d3.selectAll(".bubble")
            .attr({
              "fill-opacity": 0.2,
            });
          d3.select(this).attr({
            "fill-opacity": 0.8,
          });

        } else {
          self.selected = false;
          d3.selectAll(".bubble").each(function(data){
            d3.select(this).attr({
              "fill-opacity": 0.8,
            });
          });

          self.hide_details(d, i, self.currentSelection);
          return self.show_details(d, i, this);
        }

      });

      // Total investment
      this.vis.append("text")
        .attr("x", 20)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "money")
        .attr("fill", "black");

      // Total investment
      this.vis.append("text")
        .attr("x", 900)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "quantity")
        .attr("fill", "black");

      return this.circles.transition().duration(2000).attr("r", function(d) {
        return d.radius;
      });

    };

    function showBubbleDetails(inst, elem, data) {
      var counter = 0

      data.org.forEach(function(name){
        counter = counter + 1;
        d3.select("text#vc-title-" + counter).text(name);
        return true;
      });

      d3.select(elem).attr("fill-opacity", 0.8);

      return inst.show_details(data, 1, elem);

    }

    function hideBubbleDetails(inst, elem, data) {
      // TODO: mark previuosly on hover elem
      d3.selectAll(".vc-lable__text")
        .each(function(data){
            d3.select(this).text("");
        });

      return inst.hide_details(data, 1, elem);
    }

    BubbleChart.prototype.charge = function(d) {
      return -Math.pow(d.radius, 2.0) / 7 ;
    };

    BubbleChart.prototype.start = function() {
      return this.force = d3.layout.force().nodes(this.nodes).size([this.width, this.height]);
    };

    BubbleChart.prototype.display_by_group = function(list) {
      var self = this;

      var dic =  {
        "seed": ["Angel Round", "Seed Round"],
        "series-a": ["Series A"],
        "series-b": ["Series B", "Series C"],
        "series-d": ["Series D", "Series E", "Series F", "Series G"],
        "private": ["Private Equity"]
      }

      var group = [];

      list.forEach(function (item) {
        group = group.concat(dic[item]);
        return group;
      });

      this.force.gravity(this.layout_gravity)
        .charge(this.charge)
        .friction(0.9)
        .on("tick", function(e) {
          return self.circles
            .each(self.move_towards_target(
                e.alpha,
                function(d) {

                  if(group.indexOf(d.group) >= 0){
                    return self.center;
                  } else {
                    return self.off_screen;
                  }

                })
            )
            .attr("cx", function(d) {
              return d.x;
            })
            .attr("cy", function(d) {
              return d.y;
            });
      });

      var sum = 0;
      var count = 0;
      this.nodes.forEach( function (d) {

        if(group.indexOf(d.group) >= 0){
          count = count + 1;
          sum = sum + parseInt(d.value);
        }
      });

      d3.select("#money").text('$' + addScale(sum));
      d3.select("#quantity").text('#' + addCommas(count));
      return this.force.start();

    };

    BubbleChart.prototype.move_towards_target = function(alpha, target) {
      var self = this;

      return function(d) {
          d.x = d.x + (target(d).x - d.x) * (self.damper + 0.02) * alpha * 1.1;
          return d.y = d.y + (target(d).y - d.y) * (self.damper + 0.02) * alpha * 1.1;
      };

    };

    BubbleChart.prototype.show_details = function(data, i, element) {

      var content1, content2;
      d3.select(element).attr("stroke", "black");
      content1 = data.name;
      content2 = data.group + ", $" + (addScale(data.value));

      d3.select("text#company-title-2").text(content2);
      return d3.select("text#company-title-1").text(content1);

    };

    BubbleChart.prototype.hide_details = function(data, i, element) {
      d3.select(element).attr("stroke", (function(_this) {
        return function(d) {
          return d3.rgb(_this.colorRange(d.org.length)).darker();
        };
      })(this));
      return this.tooltip.hideTooltip();
    };

    BubbleChart.prototype.lables_placeholder = function(json) {

      var self = this;

      // Holdes the data
      var data = json;
      var startPointY = 50;

      function drawTitle(vis, x, y, text) {

        // Title
        vis.append("text")
          .attr("x", x)
          .attr("y",y)
          .text(text)
          .attr("class","title system-font")
          .attr("fill", "black");
      }

      function companySelector(element) {
        var content = element.textContent;
        var counter = 1;
        if(!self.investorSelected) {
          self.investorSelected = true;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                counter = counter + 1;
                d3.select(this).attr({
                  "fill-opacity": 1,
                  fill: self.fill_color(d.org.length)
                });
                self.show_details(data, counter, this);
              }
            });
        } else {

          self.investorSelected = false;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                d3.select(this).attr({
                  "fill-opacity": 0.2,
                  fill: self.fill_color(d.org.length)
                });

              }
            });
        }
      }

      function generatelablesContainer(vis, data, css, itemId, x, y, clickExecutor) {

        var lablesContainer = vis
                        .selectAll("g." + css)
                        .data(data, function(d) {
                          return d.id;
                        })
                        .enter().append("g")
                        .attr("class",css);

        var currentY = y + 10,
            counter = 0;

        /*lablesContainer.append("title")
            .text(function(d) { return d.name; });*/

        lablesContainer.append("text")
            .attr("x", x)
            .each(function (d){
                counter = counter + 1;
                title_class_pos = "odd";
                if( counter % 2  == 0) {
                  title_class_pos = "even";
                }
                var tempY = currentY;
                currentY= currentY + 32;

                d3.select(this).attr({
                    y: currentY,
                    "class":  css + "__text" + " " + title_class_pos,
                    id: itemId + counter
                }).text("");
            })
            .on("click", function(d, i){

              if(clickExecutor !== 'undefined') {
                clickExecutor(this);
              }
            });
      }

      drawTitle(this.vis, 20, startPointY, "INVESTORS:");
      drawTitle(this.vis, 795, startPointY, "COMPANY:");
      generatelablesContainer(this.vis, data, "vc-lable","vc-title-", 25, startPointY);
      generatelablesContainer(this.vis, [{ id: 1, id:2 }], "company-lable","company-title-", 800, startPointY);

    }

    return BubbleChart;

  })();

  root = typeof exports !== "undefined" && exports !== null ? exports : this;

  $(function() {
    var chart, render_vis, render_lbl;
    var active_groups = ["seed", "series-a", "series-b", "series-d", "private"];
    var inactive_groups = [];
    chart = null;

    render_vis = function (data) {
      config = {
        width: 1040,
        height: 600,
        colorRange: {
          domain: [1, 3, 5, 8],
          //range: ["#143642", "#558C8C", "#F7941D", "#A8201A"]
          range: ["#6CD4FF", "#143642", "#A8201A"]
        }
      };
      chart = new BubbleChart("#viz", data, config);

      chart.start();
      return chart.display_by_group(active_groups);
    };

    render_lable = function(json) {
      return chart.lables_placeholder(json);
    }
    root.display_group = (function(_this) {
      return function(list) {
        return chart.display_by_group(list);
      };
    })(this);

    root.toggle_view = (function(_this) {
      return function(view_type) {
        var active_pos = active_groups.indexOf(view_type)

        if (active_pos >= 0) {
          inactive_groups.push(view_type);
          active_groups.splice(active_pos, 1);
        } else {
          inactive_groups.splice(inactive_groups.indexOf(view_type), 1);
          active_groups.push(view_type);
        }

        return root.display_group(active_groups);

      };
    })(this);

    // Render visualisation
    //var v = d3.csv("data/test.csv", render_vis);
    var v = d3.json("data/funding.json", function(data) {

      render_vis(data);
      // Render label
      d3.json("data/labels.json", render_lable);

    });

    return v;
  });

}).call(this);
<commit_msg>fixed company array size<commit_after>// Generated by CoffeeScript 1.8.0
(function() {

  var BubbleChart, root,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  BubbleChart = (function() {
    function BubbleChart(container, data, config) {
      this.hide_details = __bind(this.hide_details, this);
      this.show_details = __bind(this.show_details, this);
      this.move_towards_year = __bind(this.move_towards_year, this);
      this.display_by_group = __bind(this.display_by_group, this);
      this.start = __bind(this.start, this);
      this.render = __bind(this.render, this);
      this.create_nodes = __bind(this.create_nodes, this);

      var max_amount;
      this.container = container;
      this.data = data;
      this.width = config.width;
      this.height = config.height;
      this.tooltip = CustomTooltip("startup_funding_tooltip", 210);

      this.center = {
        x: this.width / 2 ,
        y: this.height / 2
      };

      this.off_screen = {
        x: this.width + 300,
        y: this.height / 2
      };

      this.layout_gravity = -0.01;
      this.damper = 0.1;
      this.vis = null;
      this.nodes = [];
      this.force = null;
      this.circles = null;
      this.selected = false;
      this.investorSelected = false;
      this.currentSelection = null;

      this.colorRange = d3.scale.linear()
        .domain(config.colorRange.domain)
        .range(config.colorRange.range)

      max_amount = d3.max(this.data, function(d) {
        return parseInt(d.amount);
      });

      this.radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([4, 60]);
      this.create_nodes();
      this.render();
    }

    BubbleChart.prototype.create_nodes = function() {
      var self = this;

      this.data.forEach(function(d) {
          var node;
          if(parseInt(d.amount) <= 0) {
            return;
          }

          node = {
            id: d.id,
            radius: self.radius_scale(parseInt(d.amount)),
            value: d.amount,
            name: d.name,
            org: d.vc_list,
            group: d.stage,
            year: d.year,
            x: Math.random() * 900,
            y: Math.random() * 800
          };

          return self.nodes.push(node);
      });

      return this.nodes.sort(function(a, b) {
        return b.value - a.value;
      });
    };

    BubbleChart.prototype.render = function() {
      var self = this;

      this.vis = d3.select(this.container).append("svg").attr("width", "100%").attr("height", this.height).attr("id", "svg_vis");

      this.vis.on("click", function() {
        //self.selected = false;
      });

      this.circles = this.vis.selectAll("circle").data(this.nodes, function(d) {
        return d.id;
      });

      this.circles.enter()
      .append("circle")
      .each(function (d) {
        var strokeColor = d3.rgb(self.colorRange(d.org.length)).darker(),
            fillColor = self.colorRange(d.org.length);

        d3.select(this).attr({
          r: 0,
          "fill": fillColor,
          "fill-opacity": 0.8,
          "stroke-width": 1,
          "stroke": strokeColor,
          "id": "bubble_" + d.id,
          "class": "bubble"

        });

      })
      .on("mouseover", function(d, i) {
        if(!self.selected) {
          showBubbleDetails(self, this, d)
        }
      })
      .on("mouseout", function(d, i) {
        if(!self.selected) {
          hideBubbleDetails(self, this, d)
        }
      })
      .on("click", function(d, i) {
        if(!self.selected) {
          self.currentSelection = this;
          self.selected = true;
          var counter = 0

          d.org.forEach(function(name){
            counter = counter + 1;
            d3.select("text#vc-title-" + counter).text(name);
            return true;
          });

          d3.selectAll(".bubble")
            .attr({
              "fill-opacity": 0.2,
            });
          d3.select(this).attr({
            "fill-opacity": 0.8,
          });

        } else {
          self.selected = false;
          d3.selectAll(".bubble").each(function(data){
            d3.select(this).attr({
              "fill-opacity": 0.8,
            });
          });

          self.hide_details(d, i, self.currentSelection);
          return self.show_details(d, i, this);
        }

      });

      // Total investment
      this.vis.append("text")
        .attr("x", 20)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "money")
        .attr("fill", "black");

      // Total investment
      this.vis.append("text")
        .attr("x", 900)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "quantity")
        .attr("fill", "black");

      return this.circles.transition().duration(2000).attr("r", function(d) {
        return d.radius;
      });

    };

    function showBubbleDetails(inst, elem, data) {
      var counter = 0

      data.org.forEach(function(name){
        counter = counter + 1;
        d3.select("text#vc-title-" + counter).text(name);
        return true;
      });

      d3.select(elem).attr("fill-opacity", 0.8);

      return inst.show_details(data, 1, elem);

    }

    function hideBubbleDetails(inst, elem, data) {
      // TODO: mark previuosly on hover elem
      d3.selectAll(".vc-lable__text")
        .each(function(data){
            d3.select(this).text("");
        });

      return inst.hide_details(data, 1, elem);
    }

    BubbleChart.prototype.charge = function(d) {
      return -Math.pow(d.radius, 2.0) / 7 ;
    };

    BubbleChart.prototype.start = function() {
      return this.force = d3.layout.force().nodes(this.nodes).size([this.width, this.height]);
    };

    BubbleChart.prototype.display_by_group = function(list) {
      var self = this;

      var dic =  {
        "seed": ["Angel Round", "Seed Round"],
        "series-a": ["Series A"],
        "series-b": ["Series B", "Series C"],
        "series-d": ["Series D", "Series E", "Series F", "Series G"],
        "private": ["Private Equity"]
      }

      var group = [];

      list.forEach(function (item) {
        group = group.concat(dic[item]);
        return group;
      });

      this.force.gravity(this.layout_gravity)
        .charge(this.charge)
        .friction(0.9)
        .on("tick", function(e) {
          return self.circles
            .each(self.move_towards_target(
                e.alpha,
                function(d) {

                  if(group.indexOf(d.group) >= 0){
                    return self.center;
                  } else {
                    return self.off_screen;
                  }

                })
            )
            .attr("cx", function(d) {
              return d.x;
            })
            .attr("cy", function(d) {
              return d.y;
            });
      });

      var sum = 0;
      var count = 0;
      this.nodes.forEach( function (d) {

        if(group.indexOf(d.group) >= 0){
          count = count + 1;
          sum = sum + parseInt(d.value);
        }
      });

      d3.select("#money").text('$' + addScale(sum));
      d3.select("#quantity").text('#' + addCommas(count));
      return this.force.start();

    };

    BubbleChart.prototype.move_towards_target = function(alpha, target) {
      var self = this;

      return function(d) {
          d.x = d.x + (target(d).x - d.x) * (self.damper + 0.02) * alpha * 1.1;
          return d.y = d.y + (target(d).y - d.y) * (self.damper + 0.02) * alpha * 1.1;
      };

    };

    BubbleChart.prototype.show_details = function(data, i, element) {

      var content1, content2;
      d3.select(element).attr("stroke", "black");
      content1 = data.name;
      content2 = data.group + ", $" + (addScale(data.value));

      d3.select("text#company-title-2").text(content2);
      return d3.select("text#company-title-1").text(content1);

    };

    BubbleChart.prototype.hide_details = function(data, i, element) {
      d3.select(element).attr("stroke", (function(_this) {
        return function(d) {
          return d3.rgb(_this.colorRange(d.org.length)).darker();
        };
      })(this));
      return this.tooltip.hideTooltip();
    };

    BubbleChart.prototype.lables_placeholder = function(json) {

      var self = this;

      // Holdes the data
      var data = json;
      var startPointY = 50;

      function drawTitle(vis, x, y, text) {

        // Title
        vis.append("text")
          .attr("x", x)
          .attr("y",y)
          .text(text)
          .attr("class","title system-font")
          .attr("fill", "black");
      }

      function companySelector(element) {
        var content = element.textContent;
        var counter = 1;
        if(!self.investorSelected) {
          self.investorSelected = true;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                counter = counter + 1;
                d3.select(this).attr({
                  "fill-opacity": 1,
                  fill: self.fill_color(d.org.length)
                });
                self.show_details(data, counter, this);
              }
            });
        } else {

          self.investorSelected = false;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                d3.select(this).attr({
                  "fill-opacity": 0.2,
                  fill: self.fill_color(d.org.length)
                });

              }
            });
        }
      }

      function generatelablesContainer(vis, data, css, itemId, x, y, clickExecutor) {

        var lablesContainer = vis
                        .selectAll("g." + css)
                        .data(data, function(d) {
                          return d.id;
                        })
                        .enter().append("g")
                        .attr("class",css);

        var currentY = y + 10,
            counter = 0;

        /*lablesContainer.append("title")
            .text(function(d) { return d.name; });*/

        lablesContainer.append("text")
            .attr("x", x)
            .each(function (d){
                counter = counter + 1;
                title_class_pos = "odd";
                if( counter % 2  == 0) {
                  title_class_pos = "even";
                }
                var tempY = currentY;
                currentY= currentY + 32;

                d3.select(this).attr({
                    y: currentY,
                    "class":  css + "__text" + " " + title_class_pos,
                    id: itemId + counter
                }).text("");
            })
            .on("click", function(d, i){

              if(clickExecutor !== 'undefined') {
                clickExecutor(this);
              }
            });
      }

      drawTitle(this.vis, 20, startPointY, "INVESTORS:");
      drawTitle(this.vis, 795, startPointY, "COMPANY:");
      generatelablesContainer(this.vis, data, "vc-lable","vc-title-", 25, startPointY);
      generatelablesContainer(this.vis, [{ id: 1},{ id:2 }], "company-lable","company-title-", 800, startPointY);

    }

    return BubbleChart;

  })();

  root = typeof exports !== "undefined" && exports !== null ? exports : this;

  $(function() {
    var chart, render_vis, render_lbl;
    var active_groups = ["seed", "series-a", "series-b", "series-d", "private"];
    var inactive_groups = [];
    chart = null;

    render_vis = function (data) {
      config = {
        width: 1040,
        height: 600,
        colorRange: {
          domain: [1, 3, 5, 8],
          //range: ["#143642", "#558C8C", "#F7941D", "#A8201A"]
          range: ["#6CD4FF", "#143642", "#A8201A"]
        }
      };
      chart = new BubbleChart("#viz", data, config);

      chart.start();
      return chart.display_by_group(active_groups);
    };

    render_lable = function(json) {
      return chart.lables_placeholder(json);
    }
    root.display_group = (function(_this) {
      return function(list) {
        return chart.display_by_group(list);
      };
    })(this);

    root.toggle_view = (function(_this) {
      return function(view_type) {
        var active_pos = active_groups.indexOf(view_type)

        if (active_pos >= 0) {
          inactive_groups.push(view_type);
          active_groups.splice(active_pos, 1);
        } else {
          inactive_groups.splice(inactive_groups.indexOf(view_type), 1);
          active_groups.push(view_type);
        }

        return root.display_group(active_groups);

      };
    })(this);

    // Render visualisation
    //var v = d3.csv("data/test.csv", render_vis);
    var v = d3.json("data/funding.json", function(data) {

      render_vis(data);
      // Render label
      d3.json("data/labels.json", render_lable);

    });

    return v;
  });

}).call(this);
<|endoftext|>


<commit_before>/*!
 * jsUtil v0.1.3
 * https://www.tiny-threads.com
 * 2016-03-04
 *
 * Copyright 2016 Steve Koehler
 * Email : steve@tiny-threads.com
 */

if(!jsUtil)
var jsUtil={
    //specific to Storage objects
    store:{
        storage:localStorage,
        // convert val to JSON and add to the Storage object
        set:function(name,val){
            this.setup_vars();
            this.vars['jsu_'+name]=val; // keep within jsUtil to bypass future JSON conversion
            this.storage.setItem('jsu_'+name,JSON.stringify(val));
            return this;
        },

        //retrieve the property from the Storage object
        get:function(name){
            var ret;
            this.setup_vars();
            if(typeof this.vars['jsu_'+name] === 'undefined'){ // look for a jsUtil copy to bypass JSON conversion
                if(this.exists(name)){
                    ret=JSON.parse(this.storage.getItem('jsu_'+name));
                }
                else{
                    ret=null;
                }
            }
            else{
                ret=this.vars['jsu_'+name];
            }
            return ret;
        },

        //delete the property from the Storage object and jsUtil
        delete:function(name){
            this.setup_vars();
            delete this.vars['jsu_'+name];
            return delete this.storage['jsu_'+name];
        },

        //does the property exist in the Storage object; ignores the local properties
        exists:function(name){
            this.setup_vars();
            if(typeof this.storage['jsu_'+name]==='undefined'){
                return false;
            }
            else{
                return true;
            }
        },

        //completely empty all stored variables set by jsUtil
        purge:function(){
            var vars=jsUtil.objects.get_properties(this.storage);
            for(var i=0;i<vars.length;i++){ // loop through and find jsUtil properties
                if(vars[i].startsWith('jsu_')){
                    delete localStorage[vars[i]];
                }
            }
            this.vars.length=0;
        },

        // make sure the store.vars property is set to prevent unnecessary errors
        setup_vars:function(){
            if(typeof this.vars === 'undefined')this.vars={};
        }
    },

    // handle objects
    objects:{

        // get an array of the object's properties
        get_properties:function(obj){
            var keys=[];
            if(typeof obj !== 'object') return null;
            for(var key in obj){
                if(obj.hasOwnProperty(key))
                    keys.push(key);
            }
            return keys;
        }

	//merge two objects into one new object
	merge:function(obj1,obj2){
		var final_obj = {};
		for(var prop in obj1){
			final_obj[prop] = obj1[prop];
		}
		for (var prop in obj2){
			if(!final_obj.hasOwnProperty(prop)) //ignore property if it already exists
				final_obj[prop] = obj2[prop];
		}
		return final_obj;
	},

	//copied directly from https://davidwalsh.name/javascript-clone
	clone:function (obj,type){
		if(typeof type ==='undefined')
			type='shallow';
		if(type==='deep'){
			function mixin(dest, source, copyFunc) {
				var name, s, i, empty = {};
				for(name in source){
					// the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
					// inherited from Object.prototype.	 For example, if dest has a custom toString() method,
					// don't overwrite it with the toString() method that source inherited from Object.prototype
					s = source[name];
					if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){
						dest[name] = copyFunc ? copyFunc(s) : s;
					}
				}
				return dest;
			}

			if(!obj || typeof obj != "object" || Object.prototype.toString.call(obj) === "[object Function]"){
				// null, undefined, any non-object, or function
				return obj;	// anything
			}
			if(obj.nodeType && "cloneNode" in obj){
				// DOM Node
				return obj.cloneNode(true); // Node
			}
			if(obj instanceof Date){
				// Date
				return new Date(obj.getTime());	// Date
			}
			if(obj instanceof RegExp){
				// RegExp
				return new RegExp(obj);   // RegExp
			}
			var r, i, l;
			if(obj instanceof Array){
				// array
				r = [];
				for(i = 0, l = obj.length; i < l; ++i){
					if(i in obj){
						r.push(jsUtil.objects.clone(obj[i]));
					}
				}
				// we don't clone functions for performance reasons
				//		}else if(d.isFunction(obj)){
				//			// function
				//			r = function(){ return obj.apply(this, arguments); };
			}
			else{
				// generic objects
				r = obj.constructor ? new obj.constructor() : {};
			}
			return mixin(r, obj, clone);
		}
		else if(type==='shallow'){
			return JSON.parse(JSON.stringify(obj));
		}

	}
    },

    //handle arrays
    arrays:{

        //is a value in an array
        in:function(needle,haystack){
            for (key in haystack) {
                if (haystack[key] == needle) {
                    return true;
                }
            }
            return false;
        }
    },

    //handle loading files
    load:{

        //cache of loaded urls
        loaded:[],

        //load a script and store it in the cache
        scripts:function(url){
            if(!jsUtil.arrays.in(url,this.loaded)){
                var script= document.createElement("script");
                script.type = "text/javascript";
                script.src = url;
                document.getElementsByTagName('head')[0].appendChild(script);
            }
        },

        //load a stylesheet and store it in the cache
        styles:function(url,media){
            if(!jsUtil.arrays.in(url,this.loaded)){
                var style= document.createElement("link");
                style.rel = "stylesheet";
                if(media)
                    style.media=media;
                else
                    style.media='screen';
                style.href = url;
                document.getElementsByTagName('head')[0].appendChild(style);
            }
        }
    },

    unload:{
        //remove the script tag with the url and remove from the cache
        scripts:function(url){
            var scripts_ar=document.getElementsByTagName('script');

            //remove actual script tag from DOM
            for(var i=0;i<scripts_ar.length;i++){
                if(scripts_ar[i].src===url){
                    scripts_ar[i].parentNode.removeChild(scripts_ar[i]);
                }
            }

            //remove url instance from the cache
            for(var i=0;i<jsUtil.load.loaded.length;i++){
                if(jsUtil.load.loaded[i].src===url){
                    jsUtil.load.loaded.splice(i,1);
                }
            }
        },

        //remove a linked stylesheet and remove from cache
        styles:function(url,media){
            var links=document.getElementsByTagName('link');

            //remove actual stylesheet from DOM
            for(var i=0;i<links.length;i++){
                if(links[i].href===url){
                    links[i].parentNode.removeChild(links[i]);
                }
            }

            //remove url instance from the cache
            for(var i=0;i<jsUtil.load.loaded.length;i++){
                if(jsUtil.load.loaded[i].src===url){
                    jsUtil.load.loaded.splice(i,1);
                }
            }
        }
    }
}

// load existing stylesheets and scripts into the jsUtil.load cache to allow unload to work
// set on a timeout to allow for page loading
setTimeout(function(){
	var loaded_urls_ar=document.getElementsByTagName('script');
	for(var i=0;i<loaded_urls_ar.length;i++){ //load scripts
		if(loaded_urls_ar[i].src!=='')
			jsUtil.load.loaded.push(loaded_urls_ar[i].src);
	}
	loaded_urls_ar=document.getElementsByTagName('link');
	for(var i=0;i<loaded_urls_ar.length;i++){ //load stylesheets
		if(loaded_urls_ar[i].rel==='stylesheet' && loaded_urls_ar[i].href!==''){
			jsUtil.load.loaded.push(loaded_urls_ar[i].href);
		}
	}
},300);
<commit_msg>updated comment<commit_after>/*!
 * jsUtil v0.1.3
 * https://www.tiny-threads.com
 * 2016-03-04
 *
 * Copyright 2016 Steve Koehler
 * Email : steve@tiny-threads.com
 */

if(!jsUtil)
var jsUtil={
    //specific to Storage objects
    store:{
        storage:localStorage,
        // convert val to JSON and add to the Storage object
        set:function(name,val){
            this.setup_vars();
            this.vars['jsu_'+name]=val; // keep within jsUtil to bypass future JSON conversion
            this.storage.setItem('jsu_'+name,JSON.stringify(val));
            return this;
        },

        //retrieve the property from the Storage object
        get:function(name){
            var ret;
            this.setup_vars();
            if(typeof this.vars['jsu_'+name] === 'undefined'){ // look for a jsUtil copy to bypass JSON conversion
                if(this.exists(name)){
                    ret=JSON.parse(this.storage.getItem('jsu_'+name));
                }
                else{
                    ret=null;
                }
            }
            else{
                ret=this.vars['jsu_'+name];
            }
            return ret;
        },

        //delete the property from the Storage object and jsUtil
        delete:function(name){
            this.setup_vars();
            delete this.vars['jsu_'+name];
            return delete this.storage['jsu_'+name];
        },

        //does the property exist in the Storage object; ignores the local properties
        exists:function(name){
            this.setup_vars();
            if(typeof this.storage['jsu_'+name]==='undefined'){
                return false;
            }
            else{
                return true;
            }
        },

        //completely empty all stored variables set by jsUtil
        purge:function(){
            var vars=jsUtil.objects.get_properties(this.storage);
            for(var i=0;i<vars.length;i++){ // loop through and find jsUtil properties
                if(vars[i].startsWith('jsu_')){
                    delete localStorage[vars[i]];
                }
            }
            this.vars.length=0;
        },

        // make sure the store.vars property is set to prevent unnecessary errors
        setup_vars:function(){
            if(typeof this.vars === 'undefined')this.vars={};
        }
    },

    // handle objects
    objects:{

        // get an array of the object's properties
        get_properties:function(obj){
            var keys=[];
            if(typeof obj !== 'object') return null;
            for(var key in obj){
                if(obj.hasOwnProperty(key))
                    keys.push(key);
            }
            return keys;
        }

	//merge two objects into one new object
	merge:function(obj1,obj2){
		var final_obj = {};
		for(var prop in obj1){
			final_obj[prop] = obj1[prop];
		}
		for (var prop in obj2){
			if(!final_obj.hasOwnProperty(prop)) //ignore property if it already exists
				final_obj[prop] = obj2[prop];
		}
		return final_obj;
	},

	//copied almost directly from https://davidwalsh.name/javascript-clone
	clone:function (obj,type){
		if(typeof type ==='undefined')
			type='shallow';
		if(type==='deep'){
			function mixin(dest, source, copyFunc) {
				var name, s, i, empty = {};
				for(name in source){
					// the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
					// inherited from Object.prototype.	 For example, if dest has a custom toString() method,
					// don't overwrite it with the toString() method that source inherited from Object.prototype
					s = source[name];
					if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){
						dest[name] = copyFunc ? copyFunc(s) : s;
					}
				}
				return dest;
			}

			if(!obj || typeof obj != "object" || Object.prototype.toString.call(obj) === "[object Function]"){
				// null, undefined, any non-object, or function
				return obj;	// anything
			}
			if(obj.nodeType && "cloneNode" in obj){
				// DOM Node
				return obj.cloneNode(true); // Node
			}
			if(obj instanceof Date){
				// Date
				return new Date(obj.getTime());	// Date
			}
			if(obj instanceof RegExp){
				// RegExp
				return new RegExp(obj);   // RegExp
			}
			var r, i, l;
			if(obj instanceof Array){
				// array
				r = [];
				for(i = 0, l = obj.length; i < l; ++i){
					if(i in obj){
						r.push(jsUtil.objects.clone(obj[i]));
					}
				}
				// we don't clone functions for performance reasons
				//		}else if(d.isFunction(obj)){
				//			// function
				//			r = function(){ return obj.apply(this, arguments); };
			}
			else{
				// generic objects
				r = obj.constructor ? new obj.constructor() : {};
			}
			return mixin(r, obj, clone);
		}
		else if(type==='shallow'){
			return JSON.parse(JSON.stringify(obj));
		}

	}
    },

    //handle arrays
    arrays:{

        //is a value in an array
        in:function(needle,haystack){
            for (key in haystack) {
                if (haystack[key] == needle) {
                    return true;
                }
            }
            return false;
        }
    },

    //handle loading files
    load:{

        //cache of loaded urls
        loaded:[],

        //load a script and store it in the cache
        scripts:function(url){
            if(!jsUtil.arrays.in(url,this.loaded)){
                var script= document.createElement("script");
                script.type = "text/javascript";
                script.src = url;
                document.getElementsByTagName('head')[0].appendChild(script);
            }
        },

        //load a stylesheet and store it in the cache
        styles:function(url,media){
            if(!jsUtil.arrays.in(url,this.loaded)){
                var style= document.createElement("link");
                style.rel = "stylesheet";
                if(media)
                    style.media=media;
                else
                    style.media='screen';
                style.href = url;
                document.getElementsByTagName('head')[0].appendChild(style);
            }
        }
    },

    unload:{
        //remove the script tag with the url and remove from the cache
        scripts:function(url){
            var scripts_ar=document.getElementsByTagName('script');

            //remove actual script tag from DOM
            for(var i=0;i<scripts_ar.length;i++){
                if(scripts_ar[i].src===url){
                    scripts_ar[i].parentNode.removeChild(scripts_ar[i]);
                }
            }

            //remove url instance from the cache
            for(var i=0;i<jsUtil.load.loaded.length;i++){
                if(jsUtil.load.loaded[i].src===url){
                    jsUtil.load.loaded.splice(i,1);
                }
            }
        },

        //remove a linked stylesheet and remove from cache
        styles:function(url,media){
            var links=document.getElementsByTagName('link');

            //remove actual stylesheet from DOM
            for(var i=0;i<links.length;i++){
                if(links[i].href===url){
                    links[i].parentNode.removeChild(links[i]);
                }
            }

            //remove url instance from the cache
            for(var i=0;i<jsUtil.load.loaded.length;i++){
                if(jsUtil.load.loaded[i].src===url){
                    jsUtil.load.loaded.splice(i,1);
                }
            }
        }
    }
}

// load existing stylesheets and scripts into the jsUtil.load cache to allow unload to work
// set on a timeout to allow for page loading
setTimeout(function(){
	var loaded_urls_ar=document.getElementsByTagName('script');
	for(var i=0;i<loaded_urls_ar.length;i++){ //load scripts
		if(loaded_urls_ar[i].src!=='')
			jsUtil.load.loaded.push(loaded_urls_ar[i].src);
	}
	loaded_urls_ar=document.getElementsByTagName('link');
	for(var i=0;i<loaded_urls_ar.length;i++){ //load stylesheets
		if(loaded_urls_ar[i].rel==='stylesheet' && loaded_urls_ar[i].href!==''){
			jsUtil.load.loaded.push(loaded_urls_ar[i].href);
		}
	}
},300);
<|endoftext|>


<commit_before>"use strict";

$(() => {
    $("a.envelope-link").on("click", function () {
        common.copy_data_attribute_value($(this), "admin-emails");
    });
});
<commit_msg>js: Convert static/js/analytics/activity.js to ES6 module.<commit_after>$(() => {
    $("a.envelope-link").on("click", function () {
        common.copy_data_attribute_value($(this), "admin-emails");
    });
});
export {};
<|endoftext|>


<commit_before>(function (angular) {
angular.module('shiverview')
.controller('faithplateAllCtrl', ['$scope', '$http', '$rootScope', function ($scope, $http, $rootScope) {
  $scope.get = function (path) {
    $http({
      url: '/faithplate/events',
      method: 'get'
    })
    .success(function (data) {
      $scope.events = data;
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.get();
}])
.controller('faithplateDetailCtrl', ['$scope', '$http', '$rootScope', '$routeParams', 'user', function ($scope, $http, $rootScope, $routeParams, user) {
  $scope.user = user.get();
  if (typeof $scope.user.then === 'function')
    $scope.user.success(function () { $scope.user = user.get(); $scope.allowBooking = true; });
  $http({
    url: '/faithplate/events',
    method: 'get',
    params: {id: $routeParams.id}
  })
  .success(function (data) {
    if (data && data.length < 1)
      $scope.event = {title: 'Event not found'};
    else {
      $scope.event = data[0];
      $scope.updateBookings();
    }
  })
  .error(function (err) {
    $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
  });
  $scope.updateBookings = function () {
    $http({
      url: '/faithplate/bookings',
      method: 'get',
      params: {id: $routeParams.id}
    })
    .success(function (data) {
      $scope.bookings = data;
      $scope.mebooked = false;
      for (var i = 0; i < $scope.bookings.length; i++) {
        if ($scope.bookings[i].user === $scope.user.name) {
          $scope.mebooked = true;
          break;
        }
      }
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.toggleBook = function () {
    var payload = {id: $routeParams.id};
    var method = 'put';
    if ($scope.mebooked)
      method = 'delete';
    $http({
      url: '/faithplate/bookings',
      method: method,
      data: payload,
      params: payload
    })
    .success(function () {
      $scope.updateBookings();
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
}])
.controller('faithplateMECtrl', ['$scope', '$http', '$rootScope', '$location', '$upload', 'user', function ($scope, $http, $rootScope, $location, $upload, user) {
  $scope.get = function (path) {
    $http({
      url: '/faithplate/events',
      method: 'get',
      params: {c: $scope.user.name}
    })
    .success(function (data) {
      $scope.events = data;
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.submit = function (e) {
    if (e) e.preventDefault();
    var method = 'put';
    if ($scope.update === true)
      method = 'post';
    $http({
      url: '/faithplate/events',
      method: method,
      data: $scope.payload
    })
    .success(function () {
      $scope.showEditor = false;
      $rootScope.$broadcast('successMessage', 'Your changes have been saved.');
      $scope.get();
    })
    .error(function (err, status) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.create = function () {
    $scope.update = false;
    $scope.showEditor = true;
    $scope.payload = {};
  };
  $scope.edit = function (index) {
    if (typeof $scope.events === 'undefined') return;
    $scope.update = true;
    $scope.payload._id = $scope.events[index]._id;
    $scope.payload.title = $scope.events[index].title;
    $scope.payload.desc = $scope.events[index].desc;
    $scope.showEditor = true;
  };
  $scope.delete = function (index) {
    if (typeof $scope.events === 'undefined') return;
    $http({
      url: '/faithplate/events',
      method: 'delete',
      params: {_id: $scope.events[index]._id}
    })
    .success(function () {
      $scope.events.splice(index, 1);
      $rootScope.$broadcast('successMessage', 'The event has been removed.');
    })
    .error(function () {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.cancel = function () {
    $scope.showEditor = false;
    $scope.imageUploaded = false;
  };
  $scope.removeImage = function () {
    delete $scope.payload.coverimg;
    $scope.imageUploaded = false;
  }
  $scope.upload = function ($files) {
    $scope.progress = 0;
    $rootScope.$broadcast('setProgress', 0);
    $upload.upload({
      url: '/users/usercontent/faithplate/img',
      file: $files[0]
    })
    .progress(function (e) {
      $rootScope.$broadcast('setProgress', parseInt(100.0 * e.loaded / e.total));
    })
    .success(function (data) {
      $rootScope.$broadcast('setProgress', 100);
      if (data.path) {
        $scope.imageUploaded = true;
        $scope.payload.coverimg = data.path;
      }
    });
  };
  $scope.openFileSelect = function () {
    var input = document.getElementById('file-input');
    var event = new MouseEvent('click', {'view': window, 'bubbles': true, 'calcelable': true});
    input.dispatchEvent(event);
  };
  $scope.user = user.get();
  if (typeof $scope.user === 'undefined')
    $location.path('/users/signin');
  else if (typeof $scope.user.then === 'function')
    $scope.user.success(function () { $scope.user = user.get(); $scope.get(); }).error(function () { $location.path('/users/signin'); });
  else
    $scope.get();
  $scope.payload = {};
}]);
})(window.angular);
<commit_msg>And a commit that I don't know the reason of...<commit_after>(function (angular) {
angular.module('shiverview')
.controller('faithplateAllCtrl', ['$scope', '$http', '$rootScope', function ($scope, $http, $rootScope) {
  $scope.get = function (path) {
    $http({
      url: '/faithplate/events',
      method: 'get'
    })
    .success(function (data) {
      $scope.events = data;
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.get();
}])
.controller('faithplateDetailCtrl', ['$scope', '$http', '$rootScope', '$routeParams', 'user', function ($scope, $http, $rootScope, $routeParams, user) {
  $scope.user = user.get();
  if (typeof $scope.user !== 'undefined')
    $scope.allowBooking = true;
  if (typeof $scope.user.then === 'function')
    $scope.user.success(function () { $scope.user = user.get(); $scope.allowBooking = true; });
  $http({
    url: '/faithplate/events',
    method: 'get',
    params: {id: $routeParams.id}
  })
  .success(function (data) {
    if (data && data.length < 1)
      $scope.event = {title: 'Event not found'};
    else {
      $scope.event = data[0];
      $scope.updateBookings();
    }
  })
  .error(function (err) {
    $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
  });
  $scope.updateBookings = function () {
    $http({
      url: '/faithplate/bookings',
      method: 'get',
      params: {id: $routeParams.id}
    })
    .success(function (data) {
      $scope.bookings = data;
      $scope.mebooked = false;
      for (var i = 0; i < $scope.bookings.length; i++) {
        if ($scope.bookings[i].user === $scope.user.name) {
          $scope.mebooked = true;
          break;
        }
      }
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.toggleBook = function () {
    var payload = {id: $routeParams.id};
    var method = 'put';
    if ($scope.mebooked)
      method = 'delete';
    $http({
      url: '/faithplate/bookings',
      method: method,
      data: payload,
      params: payload
    })
    .success(function () {
      $scope.updateBookings();
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
}])
.controller('faithplateMECtrl', ['$scope', '$http', '$rootScope', '$location', '$upload', 'user', function ($scope, $http, $rootScope, $location, $upload, user) {
  $scope.get = function (path) {
    $http({
      url: '/faithplate/events',
      method: 'get',
      params: {c: $scope.user.name}
    })
    .success(function (data) {
      $scope.events = data;
    })
    .error(function (err) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.submit = function (e) {
    if (e) e.preventDefault();
    var method = 'put';
    if ($scope.update === true)
      method = 'post';
    $http({
      url: '/faithplate/events',
      method: method,
      data: $scope.payload
    })
    .success(function () {
      $scope.showEditor = false;
      $rootScope.$broadcast('successMessage', 'Your changes have been saved.');
      $scope.get();
    })
    .error(function (err, status) {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.create = function () {
    $scope.update = false;
    $scope.showEditor = true;
    $scope.payload = {};
  };
  $scope.edit = function (index) {
    if (typeof $scope.events === 'undefined') return;
    $scope.update = true;
    $scope.payload._id = $scope.events[index]._id;
    $scope.payload.title = $scope.events[index].title;
    $scope.payload.desc = $scope.events[index].desc;
    $scope.showEditor = true;
  };
  $scope.delete = function (index) {
    if (typeof $scope.events === 'undefined') return;
    $http({
      url: '/faithplate/events',
      method: 'delete',
      params: {_id: $scope.events[index]._id}
    })
    .success(function () {
      $scope.events.splice(index, 1);
      $rootScope.$broadcast('successMessage', 'The event has been removed.');
    })
    .error(function () {
      $rootScope.$broadcast('errorMessage', 'An error has ocurred. Please try again later.');
    });
  };
  $scope.cancel = function () {
    $scope.showEditor = false;
    $scope.imageUploaded = false;
  };
  $scope.removeImage = function () {
    delete $scope.payload.coverimg;
    $scope.imageUploaded = false;
  }
  $scope.upload = function ($files) {
    $scope.progress = 0;
    $rootScope.$broadcast('setProgress', 0);
    $upload.upload({
      url: '/users/usercontent/faithplate/img',
      file: $files[0]
    })
    .progress(function (e) {
      $rootScope.$broadcast('setProgress', parseInt(100.0 * e.loaded / e.total));
    })
    .success(function (data) {
      $rootScope.$broadcast('setProgress', 100);
      if (data.path) {
        $scope.imageUploaded = true;
        $scope.payload.coverimg = data.path;
      }
    });
  };
  $scope.openFileSelect = function () {
    var input = document.getElementById('file-input');
    var event = new MouseEvent('click', {'view': window, 'bubbles': true, 'calcelable': true});
    input.dispatchEvent(event);
  };
  $scope.user = user.get();
  if (typeof $scope.user === 'undefined')
    $location.path('/users/signin');
  else if (typeof $scope.user.then === 'function')
    $scope.user.success(function () { $scope.user = user.get(); $scope.get(); }).error(function () { $location.path('/users/signin'); });
  else
    $scope.get();
  $scope.payload = {};
}]);
})(window.angular);
<|endoftext|>