<commit_before>/** This function is called automatically when the page is fully loaded. */
$( function () {
    // For Sensor category tabs at bottom (Headliner, All Meterological, etc.)
    $( '#btn-tabs a' ).click( function (e) {
	e.preventDefault();
	$( this ).tab( 'show' );
    });

    /* Change the start time to match the current-time-btn specified
       on the graph page (explorer/index.html) */
    var currentBtn = getCurrentTimeBtn();
    show_button_as_active( currentBtn );
    changeStartTime( $( currentBtn ).attr( "graph-days" ));

    /** Set up initial graphs

	Note: These names need to match sensor names found in the
	database.  There have been bugs in the past where the database
	names have changed and this code has fallen behind
     */
    var initial_sensors = ['wu_ti_temp_c', 'wu_ti_pressure_mb', 'wu_ti_wind_kph'];
    initial_sensors.forEach( function( sensorid ) {
	    // console.log('setting up initial graph for'+ sensorid);
	    make_chart_and_manipulate_buttons( sensorid );
	});

    /** Register the callback that handles clicks on the buttons that
	request new charts */
    $( '.graph-btn' ).click( function(){
	console.log('graph-btn clicked');
	var sensorid;
	sensorid = $( this ).attr( 'data-sensorid' );
	/* Make EVERYTING that is named sensorid (buttons and charts)
	   say 'loading...' */
	$( '.' + sensorid ).button( 'loading' );

	// console.log( 'button clicked: ' + sensorid )
	if ($( "#" + sensorid ).length !== 0) {
	    // If there is a div for this chart already, remove the chart
	    // console.log( 'about to remove: ' + sensorid );
	    remove_chart_and_manipulate_buttons( sensorid );
	} else {
	    // Otherwise, make the chart
	    make_chart_and_manipulate_buttons( sensorid );
	}

    });

    /**
       Save a custom date, updating user feed back and existing charts
     */
    $('#save-date').click(function(){
	var newstart = $('#starttimepicker').datepicker('getDate');
	var newend = $('#endtimepicker').datepicker('getDate');
	if (newstart > newend) {
	    var swaptime = newstart;
	    newstart = newend;
	    newend = swaptime;
	}
	//	console.log('custom date start is ' + newstart + " and end is " + newend);
	update_dates(newstart, newend);
	update_existing_charts();
	show_button_as_inactive(getCurrentTimeBtn());
	setCurrentTimeBtn("#custom-btn");
	show_button_as_active("#custom-btn");
    });

    /**
      Change the date range to be from 'graph-days' ago till now
      Update all the currently displayed graphs
    */
    $(".time-btn").click(function() {
	    var change = $(this).attr('graph-days');
	    var currentBtn = getCurrentTimeBtn();
	    show_button_as_inactive(currentBtn);
	    currentBtn = "#" + $(this).attr('id');
	    show_button_as_active(currentBtn);
	    setCurrentTimeBtn(currentBtn);
	    // console.log('days to graph: ' + change);
	    changeStartTime(change);
	    update_existing_charts();
    });

    /**
       Calculate the statistics for the current view of the data for a chart
     */
    $(".stats-btn").click(function() {
	});

    $("#clear").click(function(){
	$('div#charts > div').each(function() {
		var s_id = $(this).attr('data-sensorid');
		remove_chart_and_manipulate_buttons( s_id );
	});
    });

    $("#unzoom").click(function(){
	    // Unzoom all the charts
	    //	console.log('starting unzoom')
	    // We don't use startUTC and EndUTC here because we want to force to window settings.
	    var startEndDates = getDataTimes();
	    console.log("NEW DATE: unzoom: " + startEndDates.starttime + " to " +
			startEndDates.endtime);
	    var startDate = makeDate(startEndDates.starttime);
	    var endDate = makeDate(startEndDates.endtime);
	    var endUTC = endDate.getTime();
	    var startUTC = startDate.getTime();

	$('div#charts > div').each(function() {
		var s_id = $(this).attr('data-sensorid');
	    //	    console.log('going to unzoom the following: ' + s_id);
		var chartIndex = $("#"+s_id+"-chart").data('highchartsChart');
	    //	    console.log('chartindex is' + chartIndex);
	    if (typeof chartIndex === 'number') {    //error messages will have undefined chartIndex
		var thisChart = Highcharts.charts[chartIndex];
		thisChart.xAxis[0].setExtremes(startUTC, endUTC, true);
		return false; // once we set one the sync zoom will set the rest
	    }
	    });
	});
    });

/** This function updates the existing charts on our page with new time
    selectors, which have already been stored in data-start-time and
    data-end-time */
function update_existing_charts() {
    var dataTime = getDataTimes();
    console.log("NEW DATE: update_existing_charts: " + dataTime.starttime + " to " +
		dataTime.endtime);
    var endDate = makeDate(dataTime.endtime);
    var startDate = makeDate(dataTime.starttime);
    // Time zone offset is in minutes, we want 60 * 1000 for ms
    var endUTC = endDate.getTime();
    var startUTC = startDate.getTime();
    console.log("Update UTC from " + startUTC + " to " + endUTC);

    $('div#charts > div').each(function() {
	    var s_id = $(this).attr('data-sensorid');
	    var chartIndex = $("#"+s_id+"-chart").data('highchartsChart');
	    //	    console.log('chartIndex is' + chartIndex +"for " + s_id);
	    var thisChart = Highcharts.charts[chartIndex];
	    if (typeof chartIndex === 'number') {    //error messages will have undefined chartIndex
		thisChart.showLoading();
		$('.'+s_id).button('loading');

		$.getJSON('/explorer/get_data_ajax/',{'sensorid': s_id, 'starttime': dataTime.starttime, 'endtime': dataTime.endtime})
		    .done(function(data) {
			    var chartIndex = $("#"+data.sensor_id+"-chart").data('highchartsChart');
			    var thisChart = Highcharts.charts[chartIndex];
			    thisChart.series[0].setData(data.data_array1,false);
			    thisChart.xAxis[0].setExtremes(startUTC, endUTC, true);
			    thisChart.hideLoading();

			    $('.'+data.sensor_id).button('reset');  // Reset the loading on the button
		    })
		    .fail(function(jqxhr, textStatus, error) {
			var err = textStatus + ", " + error;
			//			console.log( "Request Failed: " + err );
		    });
		//need an else here to try again to draw the graph if it had an error in the original time.
	    };
	});
}

/**
   Change data-end-time to now
   Change data-start-time to this number of days before now
*/
function changeStartTime(days) {
    var today = new Date();
    // getTimezoneOffset is in minutes, we want milliseconds for Javascript
    // back up the current time
    var starttime = today.getTime();
    starttime -= days * 24 * 3600 * 1000;
    var startday = new Date(starttime);
    update_dates(startday, today);
}

/**
   Make a Date object from a date in our database format
   2014-01-18 16:28-05:00.

   If we just use new Date, the code only works on Chrome, not Firefox or IE
*/
function makeDate( dateString ){
    var dateTime = dateString.split(/ /);
    var dateParts = dateTime[0].split(/-/);
    var timeAndZone = dateTime[1].split(/[-+]/);
    var timeParts = timeAndZone[0].split(/:/);
    var d = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1]);
    return d;
}
/**
   Print the given Date in the format the database will expect
 */
function printDate( d ) {
    var rtn = "";
    var t;
    rtn += d.getFullYear();
    t = d.getMonth() + 1;
    rtn += ((t < 10) ? "-0" : "-") + t;
    t = d.getDate();
    rtn += ((t < 10) ? "-0" : "-") + t + " ";
    t = d.getHours();
    rtn += ((t < 10) ? "0" : "") + t + ":";
    t = d.getMinutes();
    rtn += ((t < 10) ? "0" : "") + t;
    // Mark the time zone
    t = d.getTimezoneOffset();
    var tzHr = t/60;
    var tzMin = t % 60;
    /* Why yes, this Timezone adjustment looks like it is backwards.
       This is the number you need to add to local time to match GMT,
       where the +- in the date tells you how far behind GMT your
       local time is
    */
    rtn += ((t > 0) ? "-" : "+") + ((tzHr < 10) ? "0" : "") + tzHr;
    rtn += ":" + ((tzMin < 10) ? "0" : "") + tzMin;
    return rtn;
}

/**
   Print a date in a format people like
*/
function prettyDate( d ) {
    var rtn = "";
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    rtn += d.getDate() + "-";
    rtn += months[d.getMonth()] + "-";
    rtn += d.getFullYear();
    return rtn;
}

/**
   Make the sensorid button display a loading message till the chart is
   displayed
 */
function make_chart_and_manipulate_buttons( sensorid ) {
    $( '.'+sensorid ).button( 'loading' );
    show_button_as_active('.'+sensorid);
    var dataTimes = getDataTimes();
    $.when( ajax_make_chart( sensorid, dataTimes.starttime, dataTimes.endtime ))
	.done( function() {
		$( '.'+sensorid ).button( 'reset' );
	    });
}

/**
   Delete charts and play with the buttons to keep users from clicking
   too often and to make sure they get colored right
 */
function remove_chart_and_manipulate_buttons( sensorid ) {
    // Remove the graph
    $( "#" + sensorid + "-chart" ).remove();
    $( "#" + sensorid ).remove();
    show_button_as_inactive('.'+sensorid);
    //Arbitrarily make the loading show up for half a second to discourage double clicking.
    setTimeout( function () {
	    $( '.'+sensorid ).button( 'reset' );
	}, 500);
}

/**
   Store the new start and end dates for graph data in the various
   places that need to know it
*/
function update_dates(startday, endday) {
    // save these dates as an attribute of our graph page
    setDataTimes( printDate( startday ), printDate( endday ));
    // Show the User the dates
    $("#startdate").html( prettyDate( startday ));
    $("#enddate").html( prettyDate( endday ));
    // Update the custom date picker
    $("#endtimepicker").datepicker( 'setDate', endday );
    $("#starttimepicker").datepicker( 'setDate', startday );
}

/**
   Show this button as selected
 */
function show_button_as_active(button_id) {
    $(button_id).addClass( 'btn-primary' );
    $(button_id).removeClass( 'btn-default' );
}

/**
   Show this button as not selected
*/
function show_button_as_inactive(button_id) {
    $(button_id).addClass( 'btn-default');
    $(button_id).removeClass( 'btn-primary');
}

/**
   Get the data time
*/
function getDataTimes(){
    var startTime = $( "#timeselection" ).attr( "data-start-time" );
    var endTime =  $( "#timeselection" ).attr( "data-end-time" );
    return {starttime: startTime, endtime: endTime};
}

/**
   Set the data time as a string with time zone on it
*/
function setDataTimes(starttime, endtime){
    $("#timeselection").attr("data-start-time", starttime);
    $("#timeselection").attr("data-end-time", endtime);
}

/**
   Get the HTML ID of the current time selection button.
   The id is named in explorer/index.html
 */
function getCurrentTimeBtn() {
    return $("#timeselection").attr("current-time-btn");
}
/**
   Store the HTML ID of the current time selection button
*/
function setCurrentTimeBtn(btnId) {
    $("#timeselection").attr("current-time-btn", btnId);
}
<commit_msg>more comments is more better<commit_after>/** This function is called automatically when the page is fully loaded. */
$( function () {
    // For Sensor category tabs at bottom (Headliner, All Meterological, etc.)
    $( '#btn-tabs a' ).click( function (e) {
	e.preventDefault();
	$( this ).tab( 'show' );
    });

    /* Change the start time to match the current-time-btn specified
       on the graph page (explorer/index.html) */
    var currentBtn = getCurrentTimeBtn();
    show_button_as_active( currentBtn );
    changeStartTime( $( currentBtn ).attr( "graph-days" ));

    /** Set up initial graphs

	Note: These names need to match sensor names found in the
	database.  There have been bugs in the past where the database
	names have changed and this code has fallen behind
     */
    var initial_sensors = ['wu_ti_temp_c', 'wu_ti_pressure_mb', 'wu_ti_wind_kph'];
    initial_sensors.forEach( function( sensorid ) {
	    // console.log('setting up initial graph for'+ sensorid);
	    make_chart_and_manipulate_buttons( sensorid );
	});

    /** Register the callback that handles clicks on the buttons that
	request new charts */
    $( '.graph-btn' ).click( function(){
	console.log('graph-btn clicked');
	var sensorid;
	sensorid = $( this ).attr( 'data-sensorid' );
	/* Make EVERYTING that is named sensorid (buttons and charts)
	   say 'loading...' */
	$( '.' + sensorid ).button( 'loading' );

	// console.log( 'button clicked: ' + sensorid )
	if ($( "#" + sensorid ).length !== 0) {
	    // If there is a div for this chart already, remove the chart
	    // console.log( 'about to remove: ' + sensorid );
	    remove_chart_and_manipulate_buttons( sensorid );
	} else {
	    // Otherwise, make the chart
	    make_chart_and_manipulate_buttons( sensorid );
	}

    });

    /**
       Save a custom date, updating user feed back and existing charts
     */
    $('#save-date').click(function(){
	var newstart = $('#starttimepicker').datepicker('getDate');
	var newend = $('#endtimepicker').datepicker('getDate');
	if (newstart > newend) {
	    var swaptime = newstart;
	    newstart = newend;
	    newend = swaptime;
	}
	//	console.log('custom date start is ' + newstart + " and end is " + newend);
	update_dates(newstart, newend);
	update_existing_charts();
	show_button_as_inactive(getCurrentTimeBtn());
	setCurrentTimeBtn("#custom-btn");
	show_button_as_active("#custom-btn");
    });

    /**
      Change the date range to be from 'graph-days' ago till now
      Update all the currently displayed graphs
    */
    $(".time-btn").click(function() {
	    var change = $(this).attr('graph-days');
	    var currentBtn = getCurrentTimeBtn();
	    show_button_as_inactive(currentBtn);
	    currentBtn = "#" + $(this).attr('id');
	    show_button_as_active(currentBtn);
	    setCurrentTimeBtn(currentBtn);
	    // console.log('days to graph: ' + change);
	    changeStartTime(change);
	    update_existing_charts();
    });

    /**
       Erase all the charts, and un-select all their buttons
     */
    $("#clear").click(function(){
	$('div#charts > div').each(function() {
		var s_id = $(this).attr('data-sensorid');
		remove_chart_and_manipulate_buttons( s_id );
	});
    });

    /**
       Go back to using the Data-time as the axis limits of all the charts
     */
    $("#unzoom").click(function(){
	    // Unzoom all the charts
	    //	console.log('starting unzoom')
	    // We don't use startUTC and EndUTC here because we want to force to window settings.
	    var startEndDates = getDataTimes();
	    console.log("NEW DATE: unzoom: " + startEndDates.starttime + " to " +
			startEndDates.endtime);
	    var startDate = makeDate(startEndDates.starttime);
	    var endDate = makeDate(startEndDates.endtime);
	    var endUTC = endDate.getTime();
	    var startUTC = startDate.getTime();

	$('div#charts > div').each(function() {
		var s_id = $(this).attr('data-sensorid');
	    //	    console.log('going to unzoom the following: ' + s_id);
		var chartIndex = $("#"+s_id+"-chart").data('highchartsChart');
	    //	    console.log('chartindex is' + chartIndex);
	    if (typeof chartIndex === 'number') {    //error messages will have undefined chartIndex
		var thisChart = Highcharts.charts[chartIndex];
		thisChart.xAxis[0].setExtremes(startUTC, endUTC, true);
		return false; // once we set one the sync zoom will set the rest
	    }
	    });
	});
    });

/** This function updates the existing charts on our page with new time
    selectors, which have already been stored in data-start-time and
    data-end-time */
function update_existing_charts() {
    var dataTime = getDataTimes();
    console.log("NEW DATE: update_existing_charts: " + dataTime.starttime + " to " +
		dataTime.endtime);
    var endDate = makeDate(dataTime.endtime);
    var startDate = makeDate(dataTime.starttime);
    // Time zone offset is in minutes, we want 60 * 1000 for ms
    var endUTC = endDate.getTime();
    var startUTC = startDate.getTime();
    console.log("Update UTC from " + startUTC + " to " + endUTC);

    $('div#charts > div').each(function() {
	    var s_id = $(this).attr('data-sensorid');
	    var chartIndex = $("#"+s_id+"-chart").data('highchartsChart');
	    //	    console.log('chartIndex is' + chartIndex +"for " + s_id);
	    var thisChart = Highcharts.charts[chartIndex];
	    if (typeof chartIndex === 'number') {    //error messages will have undefined chartIndex
		thisChart.showLoading();
		$('.'+s_id).button('loading');

		$.getJSON('/explorer/get_data_ajax/',{'sensorid': s_id, 'starttime': dataTime.starttime, 'endtime': dataTime.endtime})
		    .done(function(data) {
			    var chartIndex = $("#"+data.sensor_id+"-chart").data('highchartsChart');
			    var thisChart = Highcharts.charts[chartIndex];
			    thisChart.series[0].setData(data.data_array1,false);
			    thisChart.xAxis[0].setExtremes(startUTC, endUTC, true);
			    thisChart.hideLoading();

			    $('.'+data.sensor_id).button('reset');  // Reset the loading on the button
		    })
		    .fail(function(jqxhr, textStatus, error) {
			var err = textStatus + ", " + error;
			//			console.log( "Request Failed: " + err );
		    });
		//need an else here to try again to draw the graph if it had an error in the original time.
	    };
	});
}

/**
   Change data-end-time to now
   Change data-start-time to this number of days before now
*/
function changeStartTime(days) {
    var today = new Date();
    // getTimezoneOffset is in minutes, we want milliseconds for Javascript
    // back up the current time
    var starttime = today.getTime();
    starttime -= days * 24 * 3600 * 1000;
    var startday = new Date(starttime);
    update_dates(startday, today);
}

/**
   Make a Date object from a date in our database format
   2014-01-18 16:28-05:00.

   If we just use new Date, the code only works on Chrome, not Firefox or IE
*/
function makeDate( dateString ){
    var dateTime = dateString.split(/ /);
    var dateParts = dateTime[0].split(/-/);
    var timeAndZone = dateTime[1].split(/[-+]/);
    var timeParts = timeAndZone[0].split(/:/);
    var d = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1]);
    return d;
}
/**
   Print the given Date in the format the database will expect
 */
function printDate( d ) {
    var rtn = "";
    var t;
    rtn += d.getFullYear();
    t = d.getMonth() + 1;
    rtn += ((t < 10) ? "-0" : "-") + t;
    t = d.getDate();
    rtn += ((t < 10) ? "-0" : "-") + t + " ";
    t = d.getHours();
    rtn += ((t < 10) ? "0" : "") + t + ":";
    t = d.getMinutes();
    rtn += ((t < 10) ? "0" : "") + t;
    // Mark the time zone
    t = d.getTimezoneOffset();
    var tzHr = t/60;
    var tzMin = t % 60;
    /* Why yes, this Timezone adjustment looks like it is backwards.
       This is the number you need to add to local time to match GMT,
       where the +- in the date tells you how far behind GMT your
       local time is
    */
    rtn += ((t > 0) ? "-" : "+") + ((tzHr < 10) ? "0" : "") + tzHr;
    rtn += ":" + ((tzMin < 10) ? "0" : "") + tzMin;
    return rtn;
}

/**
   Print a date in a format people like
*/
function prettyDate( d ) {
    var rtn = "";
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    rtn += d.getDate() + "-";
    rtn += months[d.getMonth()] + "-";
    rtn += d.getFullYear();
    return rtn;
}

/**
   Make the sensorid button display a loading message till the chart is
   displayed
 */
function make_chart_and_manipulate_buttons( sensorid ) {
    $( '.'+sensorid ).button( 'loading' );
    show_button_as_active('.'+sensorid);
    var dataTimes = getDataTimes();
    $.when( ajax_make_chart( sensorid, dataTimes.starttime, dataTimes.endtime ))
	.done( function() {
		$( '.'+sensorid ).button( 'reset' );
	    });
}

/**
   Delete charts and play with the buttons to keep users from clicking
   too often and to make sure they get colored right
 */
function remove_chart_and_manipulate_buttons( sensorid ) {
    // Remove the graph
    $( "#" + sensorid + "-chart" ).remove();
    $( "#" + sensorid ).remove();
    show_button_as_inactive('.'+sensorid);
    //Arbitrarily make the loading show up for half a second to discourage double clicking.
    setTimeout( function () {
	    $( '.'+sensorid ).button( 'reset' );
	}, 500);
}

/**
   Store the new start and end dates for graph data in the various
   places that need to know it
*/
function update_dates(startday, endday) {
    // save these dates as an attribute of our graph page
    setDataTimes( printDate( startday ), printDate( endday ));
    // Show the User the dates
    $("#startdate").html( prettyDate( startday ));
    $("#enddate").html( prettyDate( endday ));
    // Update the custom date picker
    $("#endtimepicker").datepicker( 'setDate', endday );
    $("#starttimepicker").datepicker( 'setDate', startday );
}

/**
   Show this button as selected
 */
function show_button_as_active(button_id) {
    $(button_id).addClass( 'btn-primary' );
    $(button_id).removeClass( 'btn-default' );
}

/**
   Show this button as not selected
*/
function show_button_as_inactive(button_id) {
    $(button_id).addClass( 'btn-default');
    $(button_id).removeClass( 'btn-primary');
}

/**
   Get the data time
*/
function getDataTimes(){
    var startTime = $( "#timeselection" ).attr( "data-start-time" );
    var endTime =  $( "#timeselection" ).attr( "data-end-time" );
    return {starttime: startTime, endtime: endTime};
}

/**
   Set the data time as a string with time zone on it
*/
function setDataTimes(starttime, endtime){
    $("#timeselection").attr("data-start-time", starttime);
    $("#timeselection").attr("data-end-time", endtime);
}

/**
   Get the HTML ID of the current time selection button.
   The id is named in explorer/index.html
 */
function getCurrentTimeBtn() {
    return $("#timeselection").attr("current-time-btn");
}
/**
   Store the HTML ID of the current time selection button
*/
function setCurrentTimeBtn(btnId) {
    $("#timeselection").attr("current-time-btn", btnId);
}
<|endoftext|>


<commit_before>var markersArray = [];
var instaArray = [];
Meteor.startup(function(){

  clinics = new Meteor.Collection("clinics");
  users = new Meteor.Collection("user");

  Session.set('photoset', '');
  Session.set('zoomed', '');
  getTwitter();

  var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|iemobile|BlackBerry)/);
  console.log(isMobile);

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  }
  else {
      alert('It appears that Geolocation, which is required for this web page application, is not enabled in your browser. Please use a browser which supports the Geolocation API.');
  }

  function successFunction(success) {
      var navLatLng = newLatLng(success);
      createMap(navLatLng);
      placeNavMarker(navLatLng);
      addAutocomplete();
  }

  function errorFunction(success) {
    // alert("You've disabled your geolocation... So here are some pretty pictures of the Golden Gate bridge... You can always click around on the map or use the search to see more photos");
    var latlng = new google.maps.LatLng(37.808631, -122.474470);
    createMap(latlng);
    placeNavMarker(navLatLng);
    addAutocomplete();
  }

});

//GOOGLE MAPS HELPERS

function newLatLng(success) {
   return new google.maps.LatLng(success.coords.latitude, success.coords.longitude);
}

function createMap(latLng) {
  var mapOptions = {
    streetViewControl: false,
    scrollwheel: false,
    zoom: 15,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}

function addAutocomplete() {
  var input = document.getElementById('searchTextField');
  autocomplete = new google.maps.places.Autocomplete(input);
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    placeClickMarker(place.geometry.location);
    map.setCenter(place.geometry.location);
    map.setZoom(15);
  });
}

function placeNavMarker(latLng) {
  var image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
  var blueIcon = new google.maps.Marker({
      position: latLng,
      map: map,
      icon: image
  });
}
//GENERAL HELPERS
var getTwitter = function() {
  !function(d,s,id){
    var js,fjs= d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)){
      js=d.createElement(s);js.id=id;
      js.src="https://platform.twitter.com/widgets.js";
      fjs.parentNode.insertBefore(js,fjs);
    }
  }(document,"script","twitter-wjs");
}

$('div#social').hide()
<commit_msg>moved most actions and some functions to Template.content.rendered, social div now successfully hidden. Converted some functions into local variable scope<commit_after>var markersArray = [];
var instaArray = [];
Meteor.startup(function(){

  clinics = new Meteor.Collection("clinics");
  users = new Meteor.Collection("user");

  Session.set('photoset', '');
  Session.set('zoomed', '');

});

Template.content.rendered = function(){
  getTwitter();
  var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|iemobile|BlackBerry)/);
  console.log(isMobile);

    var createMap=function (latLng) {
      var mapOptions = {
        streetViewControl: false,
        scrollwheel: false,
        zoom: 15,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    };
    var addAutocomplete=function () {
      var input = document.getElementById('searchTextField');
      autocomplete = new google.maps.places.Autocomplete(input);
      google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();
        placeClickMarker(place.geometry.location);
        map.setCenter(place.geometry.location);
        map.setZoom(15);
      });
    }
    var placeNavMarker=function (latLng) {
      var image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
      var blueIcon = new google.maps.Marker({
          position: latLng,
          map: map,
          icon: image
      });
    }
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  }
  else {
      alert('It appears that Geolocation, which is required for this web page application, is not enabled in your browser. Please use a browser which supports the Geolocation API.');
  }

  function successFunction(success) {
      var navLatLng = newLatLng(success);
      createMap(navLatLng);
      placeNavMarker(navLatLng);
      addAutocomplete();
  }

  function errorFunction(success) {
    // alert("You've disabled your geolocation... So here are some pretty pictures of the Golden Gate bridge... You can always click around on the map or use the search to see more photos");
    var latlng = new google.maps.LatLng(37.808631, -122.474470);
    createMap(latlng);
    placeNavMarker(navLatLng);
    addAutocomplete();
  }
    $('div#social').hide();
    $('div#clinic_add').hide();
}

//GOOGLE MAPS HELPERS

function newLatLng(success) {
   return new google.maps.LatLng(success.coords.latitude, success.coords.longitude);
}

//GENERAL HELPERS
var getTwitter = function() {
  !function(d,s,id){
    var js,fjs= d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)){
      js=d.createElement(s);js.id=id;
      js.src="https://platform.twitter.com/widgets.js";
      fjs.parentNode.insertBefore(js,fjs);
    }
  }(document,"script","twitter-wjs");
}

<|endoftext|>


<commit_before>var answers = require('./answers');
var stopwords = require('./stopwords');
// var storage = require('./storage');

var makeDictionary = function(d) {
	var final = {}
	for (item in d) {
		var key = item.toLowerCase();
		var val = d[item];
		final[key] = val;
	}
	return final
}

var answerDict = makeDictionary(answers);

var removePunc = function(text) {
	return text.replace(/[.,\/#!?$%\^&\*;:{}=\-_`~()]/g,"");
}

var hasWords = function(text, wordList) {
	var arr = text.split(" ");
	for (i in wordList) {
		var word = wordList[i];
		if (arr.indexOf(word) !== -1) {
			return true;
		}
	}
	return false;
}

var cleanText = function(text) {
	text = text.toLowerCase();
	text = removePunc(text);
	return text;
}

var countDict = function(arr) {
	var dict = {};
	for (i in arr) {
		var val = arr[i];
		if (!(val in dict)) {
			dict[val] = 0;
		}
		dict[val] += 1;
	}
	return dict;
}

var checkFave = function(text) {
	return hasWords(text, ["you"]) && hasWords(text, ["best", "fav", "fave", "favorite", "awesome", "smart"]);
};

var checkThanks = function(text) {
	return hasWords(text, ["thank", "thanks"]);
};

var checkParting = function(text) {
	return hasWords(text, ["goodbye", "bye", "byebye"]);
};

var checkGreetings = function(text) {
	return hasWords(text, ["hi", "hello", "hey"]);
};

var checkAgreement = function(text) {
	return hasWords(text, ["yes", "yep", "okay"]);
};

var stringDistance = function(str1, str2) {

	str1 = removePunc(str1);
	str2 = removePunc(str2);
	var arr1 = str1.split(" ");
	var arr2 = str2.split(" ");
	var matches = 0;
	var dict1 = countDict(arr1);
	var dict2 = countDict(arr2);

	for (key in dict1) {
		if (key in dict2) {
			matches += Math.min(dict1[key], dict2[key]);
		}
	}
	matches = matches/(arr1.length+arr2.length);
	return matches;
}

var getCloserString = function(closestStr, newStr, text) {
	closestStr = closestStr.toLowerCase();
	newStr = newStr.toLowerCase();

	var closestScore = stringDistance(closestStr, text);
	var newScore = stringDistance(newStr, text);
	if (newScore > closestScore) {
		return newStr;
	}
	return closestStr;
}

var getClosestString = function(questions, text) {
	var closestQuestion = '';
	for (i in questions) {
		var question = questions[i];
		closestQuestion = getCloserString(closestQuestion, question, text);
	}
	return closestQuestion;
}

var getQuestionPreComment = function() {
	var commentArray = [
		"",
		"",
		"Good question!",
		"Great question!",
		"Very good question!",
		"Smart question!",
		"Hmm... Let me see.",
		"Okay, let's see.."
	];
	var comment = commentArray[Math.floor(Math.random() * commentArray.length)];
	return comment;
}

var getQuestionPostComment = function() {
	var commentArray = [
		"",
		"",
		"",
		"Make sense?",
		"\nAnything else you want to know?",
		"\nAny questions?",
		"That's pretty much it!",
		"I hope that makes sense!",
		"I hope that helps!"
	];
	var comment = commentArray[Math.floor(Math.random() * commentArray.length)];
	return comment;
}

var searchAnswers = function (userId, text) {
	var questions = Object.keys(answerDict);
	var closestQuestion = getClosestString(questions, stopwords.removeStopWords(text).join(' '));
	if (closestQuestion === '') {
		closestQuestion = getClosestString(questions, text);
		if (closestQuestion === '') {
			return '🙊\nI\'m sorry, I didn\'t understand that.\nCould you ask in another way?';
		}
		return '🙊\nI\'m sorry, I didn\'t quite understand that.\nDid you mean:\n"' + closestQuestion +'"';
	}
	console.log("RESPONSE:");
	console.log(closestQuestion);
	console.log(answerDict[closestQuestion]);

	var responseArr = [
		'"'+closestQuestion+'"\n\n🐵',
		getQuestionPreComment(),
		answerDict[closestQuestion],
		getQuestionPostComment()
	];

	return responseArr.join(" ");
}

var respond = function (userId, text) {
	text = cleanText(text);
	if (checkGreetings(text)) {
		return "🐵 I'm Madeliene!\nGreat to meet you!\n\nWhat are you interested in?\n1. I want to learn about sex\n2. I want to get hygiene products\n3. I want to find resources near me"
	}
	if (checkFave(text)) {
		return "🙉 Aww golly gee! Thanks! 😀"
	}
	if (checkThanks(text)) {
		return "🙈 You're welcome! Happy to help! 😀"
	}
	if (checkAgreement(text)) {
		return "🙉 That's great to hear!"
	}
	if (checkPartings(text)) {
		return "🐒 See you later! Come by any time you have questions!"
	}
	return searchAnswers(userId, text);
}

module.exports = {
	'respond': respond
}
<commit_msg>Fixed goodbye text<commit_after>var answers = require('./answers');
var stopwords = require('./stopwords');
// var storage = require('./storage');

var makeDictionary = function(d) {
	var final = {}
	for (item in d) {
		var key = item.toLowerCase();
		var val = d[item];
		final[key] = val;
	}
	return final
}

var answerDict = makeDictionary(answers);

var removePunc = function(text) {
	return text.replace(/[.,\/#!?$%\^&\*;:{}=\-_`~()]/g,"");
}

var hasWords = function(text, wordList) {
	var arr = text.split(" ");
	for (i in wordList) {
		var word = wordList[i];
		if (arr.indexOf(word) !== -1) {
			return true;
		}
	}
	return false;
}

var cleanText = function(text) {
	text = text.toLowerCase();
	text = removePunc(text);
	return text;
}

var countDict = function(arr) {
	var dict = {};
	for (i in arr) {
		var val = arr[i];
		if (!(val in dict)) {
			dict[val] = 0;
		}
		dict[val] += 1;
	}
	return dict;
}

var checkFave = function(text) {
	return hasWords(text, ["you"]) && hasWords(text, ["best", "fav", "fave", "favorite", "awesome", "smart"]);
};

var checkThanks = function(text) {
	return hasWords(text, ["thank", "thanks"]);
};

var checkParting = function(text) {
	return hasWords(text, ["goodbye", "bye", "byebye"]);
};

var checkGreetings = function(text) {
	return hasWords(text, ["hi", "hello", "hey"]);
};

var checkAgreement = function(text) {
	return hasWords(text, ["yes", "yep", "okay"]);
};

var stringDistance = function(str1, str2) {

	str1 = removePunc(str1);
	str2 = removePunc(str2);
	var arr1 = str1.split(" ");
	var arr2 = str2.split(" ");
	var matches = 0;
	var dict1 = countDict(arr1);
	var dict2 = countDict(arr2);

	for (key in dict1) {
		if (key in dict2) {
			matches += Math.min(dict1[key], dict2[key]);
		}
	}
	matches = matches/(arr1.length+arr2.length);
	return matches;
}

var getCloserString = function(closestStr, newStr, text) {
	closestStr = closestStr.toLowerCase();
	newStr = newStr.toLowerCase();

	var closestScore = stringDistance(closestStr, text);
	var newScore = stringDistance(newStr, text);
	if (newScore > closestScore) {
		return newStr;
	}
	return closestStr;
}

var getClosestString = function(questions, text) {
	var closestQuestion = '';
	for (i in questions) {
		var question = questions[i];
		closestQuestion = getCloserString(closestQuestion, question, text);
	}
	return closestQuestion;
}

var getQuestionPreComment = function() {
	var commentArray = [
		"",
		"",
		"Good question!",
		"Great question!",
		"Very good question!",
		"Smart question!",
		"Hmm... Let me see.",
		"Okay, let's see.."
	];
	var comment = commentArray[Math.floor(Math.random() * commentArray.length)];
	return comment;
}

var getQuestionPostComment = function() {
	var commentArray = [
		"",
		"",
		"",
		"Make sense?",
		"\nAnything else you want to know?",
		"\nAny questions?",
		"That's pretty much it!",
		"I hope that makes sense!",
		"I hope that helps!"
	];
	var comment = commentArray[Math.floor(Math.random() * commentArray.length)];
	return comment;
}

var searchAnswers = function (userId, text) {
	var questions = Object.keys(answerDict);
	var closestQuestion = getClosestString(questions, stopwords.removeStopWords(text).join(' '));
	if (closestQuestion === '') {
		closestQuestion = getClosestString(questions, text);
		if (closestQuestion === '') {
			return '🙊\nI\'m sorry, I didn\'t understand that.\nCould you ask in another way?';
		}
		return '🙊\nI\'m sorry, I didn\'t quite understand that.\nDid you mean:\n"' + closestQuestion +'"';
	}
	console.log("RESPONSE:");
	console.log(closestQuestion);
	console.log(answerDict[closestQuestion]);

	var responseArr = [
		'"'+closestQuestion+'"\n\n🐵',
		getQuestionPreComment(),
		answerDict[closestQuestion],
		getQuestionPostComment()
	];

	return responseArr.join(" ");
}

var respond = function (userId, text) {
	text = cleanText(text);
	if (checkGreetings(text)) {
		return "🐵 I'm Madeliene!\nGreat to meet you!\n\nWhat are you interested in?\n1. I want to learn about sex\n2. I want to get hygiene products\n3. I want to find resources near me"
	}
	if (checkFave(text)) {
		return "🙉 Aww golly gee! Thanks! 😀"
	}
	if (checkThanks(text)) {
		return "🙈 You're welcome! Happy to help! 😀"
	}
	if (checkAgreement(text)) {
		return "🙉 That's great to hear!"
	}
	if (checkParting(text)) {
		return "🐒 See you later!\nCome by any time you have questions!"
	}
	return searchAnswers(userId, text);
}

module.exports = {
	'respond': respond
}
<|endoftext|>


<commit_before>import * as t from "../../types";

/**
 * [Please add a description.]
 */

export function ImportSpecifier(node, print) {
  print.plain(node.imported);
  if (node.local && node.local.name !== node.imported.name) {
    this.push(" as ");
    print.plain(node.local);
  }
}

/**
 * [Please add a description.]
 */

export function ImportDefaultSpecifier(node, print) {
  print.plain(node.local);
}

/**
 * [Please add a description.]
 */

export function ExportDefaultSpecifier(node, print) {
  print.plain(node.exported);
}

/**
 * [Please add a description.]
 */

export function ExportSpecifier(node, print) {
  print.plain(node.local);
  if (node.exported && node.local.name !== node.exported.name) {
    this.push(" as ");
    print.plain(node.exported);
  }
}

/**
 * [Please add a description.]
 */

export function ExportNamespaceSpecifier(node, print) {
  this.push("* as ");
  print.plain(node.exported);
}

/**
 * [Please add a description.]
 */

export function ExportAllDeclaration(node, print) {
  this.push("export *");
  if (node.exported) {
    this.push(" as ");
    print.plain(node.exported);
  }
  this.push(" from ");
  print.plain(node.source);
  this.semicolon();
}

/**
 * [Please add a description.]
 */

export function ExportNamedDeclaration(node, print) {
  this.push("export ");
  ExportDeclaration.call(this, node, print);
}

/**
 * [Please add a description.]
 */

export function ExportDefaultDeclaration(node, print) {
  this.push("export default ");
  ExportDeclaration.call(this, node, print);
}

/**
 * [Please add a description.]
 */

function ExportDeclaration(node, print) {
  var specifiers = node.specifiers;

  if (node.declaration) {
    var declar = node.declaration;
    print.plain(declar);
    if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
  } else {
    var first = specifiers[0];
    var hasSpecial = false;
    if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
      hasSpecial = true;
      print.plain(specifiers.shift());
      if (specifiers.length) {
        this.push(", ");
      }
    }

    if (specifiers.length || (!specifiers.length && !hasSpecial)) {
      this.push("{");
      if (specifiers.length) {
        this.space();
        print.join(specifiers, { separator: ", " });
        this.space();
      }
      this.push("}");
    }

    if (node.source) {
      this.push(" from ");
      print.plain(node.source);
    }
  }

  this.ensureSemicolon();
}

/**
 * [Please add a description.]
 */

export function ImportDeclaration(node, print) {
  this.push("import ");

  if (node.importKind === "type" || node.importKind === "typeof") {
    this.push(node.importKind + " ");
  }

  var specfiers = node.specifiers;
  if (specfiers && specfiers.length) {
    var first = node.specifiers[0];
    if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
      print.plain(node.specifiers.shift());
      if (node.specifiers.length) {
        this.push(", ");
      }
    }

    if (node.specifiers.length) {
      this.push("{");
      this.space();
      print.join(node.specifiers, { separator: ", " });
      this.space();
      this.push("}");
    }

    this.push(" from ");
  }

  print.plain(node.source);
  this.semicolon();
}

/**
 * [Please add a description.]
 */

export function ImportNamespaceSpecifier(node, print) {
  this.push("* as ");
  print.plain(node.local);
}
<commit_msg>Add descriptions to generation/generators/modules<commit_after>import * as t from "../../types";

/**
 * Prints ImportSpecifier, prints imported and local.
 */

export function ImportSpecifier(node, print) {
  print.plain(node.imported);
  if (node.local && node.local.name !== node.imported.name) {
    this.push(" as ");
    print.plain(node.local);
  }
}

/**
 * Prints ImportDefaultSpecifier, prints local.
 */

export function ImportDefaultSpecifier(node, print) {
  print.plain(node.local);
}

/**
 * Prints ExportDefaultSpecifier, prints exported.
 */

export function ExportDefaultSpecifier(node, print) {
  print.plain(node.exported);
}

/**
 * Prints ExportSpecifier, prints local and exported.
 */

export function ExportSpecifier(node, print) {
  print.plain(node.local);
  if (node.exported && node.local.name !== node.exported.name) {
    this.push(" as ");
    print.plain(node.exported);
  }
}

/**
 * Prints ExportNamespaceSpecifier, prints exported.
 */

export function ExportNamespaceSpecifier(node, print) {
  this.push("* as ");
  print.plain(node.exported);
}

/**
 * Prints ExportAllDeclaration, prints exported and source.
 */

export function ExportAllDeclaration(node, print) {
  this.push("export *");
  if (node.exported) {
    this.push(" as ");
    print.plain(node.exported);
  }
  this.push(" from ");
  print.plain(node.source);
  this.semicolon();
}

/**
 * Prints ExportNamedDeclaration, delegates to ExportDeclaration.
 */

export function ExportNamedDeclaration(node, print) {
  this.push("export ");
  ExportDeclaration.call(this, node, print);
}

/**
 * Prints ExportDefaultDeclaration, delegates to ExportDeclaration.
 */

export function ExportDefaultDeclaration(node, print) {
  this.push("export default ");
  ExportDeclaration.call(this, node, print);
}

/**
 * Prints ExportDeclaration, prints specifiers, declration, and source.
 */

function ExportDeclaration(node, print) {
  var specifiers = node.specifiers;

  if (node.declaration) {
    var declar = node.declaration;
    print.plain(declar);
    if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
  } else {
    var first = specifiers[0];
    var hasSpecial = false;
    if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
      hasSpecial = true;
      print.plain(specifiers.shift());
      if (specifiers.length) {
        this.push(", ");
      }
    }

    if (specifiers.length || (!specifiers.length && !hasSpecial)) {
      this.push("{");
      if (specifiers.length) {
        this.space();
        print.join(specifiers, { separator: ", " });
        this.space();
      }
      this.push("}");
    }

    if (node.source) {
      this.push(" from ");
      print.plain(node.source);
    }
  }

  this.ensureSemicolon();
}

/**
 * Prints ImportDeclaration, prints specifiers and source, handles isType.
 */

export function ImportDeclaration(node, print) {
  this.push("import ");

  if (node.importKind === "type" || node.importKind === "typeof") {
    this.push(node.importKind + " ");
  }

  var specfiers = node.specifiers;
  if (specfiers && specfiers.length) {
    var first = node.specifiers[0];
    if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
      print.plain(node.specifiers.shift());
      if (node.specifiers.length) {
        this.push(", ");
      }
    }

    if (node.specifiers.length) {
      this.push("{");
      this.space();
      print.join(node.specifiers, { separator: ", " });
      this.space();
      this.push("}");
    }

    this.push(" from ");
  }

  print.plain(node.source);
  this.semicolon();
}

/**
 * Prints ImportNamespaceSpecifier, prints local.
 */

export function ImportNamespaceSpecifier(node, print) {
  this.push("* as ");
  print.plain(node.local);
}
<|endoftext|>


<commit_before>import filePaths from './utils/filePaths';
import dialog from 'dialog';
import yargs from 'yargs';
import path from 'path';
import app from 'app';

import CrashReporter from 'crash-reporter';
import AutoUpdater from './components/auto-updater';
import SquirrelEvents from './components/squirrel-events';
import Application from './application';

import manifest from '../../package.json';

// Handle uncaught exceptions
process.on('uncaughtException', function(ex) {
  console.error('uncaught exception', ex);
  const isProdRelease = manifest.distrib != 'unset';
  if (isProdRelease) {
    dialog.showErrorBox('JavaScript error in the main process', ex.stack);
  }
});

(function() {
  // Define the CLI arguments and parse them
  const argv = yargs
    .usage('Usage: $0 [options]')
    .option('os-startup', {
      type: 'boolean',
      description: 'Flag to indicate the app is being ran by the OS on startup.'
    })
    .option('portable', {
      type: 'boolean',
      description: 'Run in portable mode.'
    })
    .option('version', {
      type: 'boolean',
      description: 'Print the app version.',
      alias: 'v'
    })
    .option('squirrel-install', {
      type: 'string',
      description: 'Squirrel.Windows flag, called when the app is installed.'
    })
    .option('squirrel-uninstall', {
      type: 'string',
      description: 'Squirrel.Windows flag, called after the app is updated.'
    })
    .option('squirrel-updated', {
      type: 'string',
      description: 'Squirrel.Windows flag, called when the app is uninstalled.'
    })
    .option('squirrel-obsolete', {
      type: 'string',
      description: 'Squirrel.Windows flag, called before updating to a new version.'
    })
    .option('squirrel-firstrun', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called only once after installation.'
    })
    .help('help', 'Print this help message.').alias('help', 'h')
    .epilog('Created with <3 by Alexandru Rosianu – http://www.aluxian.com/')
    .argv;

  // Check for Squirrel.Windows CLI args
  if (process.platform == 'win32' && SquirrelEvents.check(argv)) {
    return;
  }

  // Print the version and exit
  if (argv.version) {
    console.log(`${app.getName()} ${app.getVersion()}`);
    console.log(`Electron ${process.versions.electron}`);
    console.log(`Chromium ${process.versions.chrome}`);
    return app.quit();
  }

  // Enforce single instance
  const isDuplicateInstance = app.makeSingleInstance(() => {
    if (global.application) {
      const mainWindow = global.application.mainWindowManager.window;
      if (mainWindow) {
        if (mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        mainWindow.focus();
      }
    }
    return true;
  });

  if (isDuplicateInstance) {
    log('another instance of the app is already running');
    return app.quit();
  }

  // Change the userData path if in portable mode
  if (argv.portable || manifest.portable) {
    log('running in portable mode');
    const userDataPath = path.join(filePaths.getAppDir(), 'data');
    log('set userData path', userDataPath);
    app.setPath('userData', userDataPath);
  }

  // Enable the crash reporter and auto updater
  if (!process.mas) {
    app.on('will-finish-launching', function() {
      log('will finish launching');

      // Crash reporter
      const reporterOptions = {
        productName: manifest.productName,
        companyName: manifest.win.companyName,
        submitURL: manifest.crashReporter.url,
        autoSubmit: true
      };
      log('starting crash reporter', JSON.stringify(reporterOptions));
      CrashReporter.start(reporterOptions);

      // Auto updater
      log('starting auto updater');
      app.setAppUserModelId(manifest.win.userModelId);
      const feedUrl = manifest.updater.squirrelUrl[process.platform]
        .replace(/%CURRENT_VERSION%/g, manifest.version);
      AutoUpdater.setFeedURL(feedUrl);
    });
  } else {
    log('mas release');
  }

  // Create the main app object and init
  app.on('ready', function() {
    log('ready, launching app');
    global.manifest = manifest;
    global.application = new Application(manifest, argv);
    global.application.init();
  });
})();
<commit_msg>Only handle known uncaught exceptions<commit_after>import filePaths from './utils/filePaths';
import dialog from 'dialog';
import yargs from 'yargs';
import path from 'path';
import app from 'app';

import CrashReporter from 'crash-reporter';
import AutoUpdater from './components/auto-updater';
import SquirrelEvents from './components/squirrel-events';
import Application from './application';

import manifest from '../../package.json';

// Handle uncaught exceptions
process.on('uncaughtException', function(ex) {
  const isSignatureEx = ex.message == 'Could not get code signature for running application';
  const isDevRelease = manifest.distrib == 'unset';
  if (isDevRelease && isSignatureEx) {
    console.error('uncaught exception', ex.message);
  } else {
    dialog.showErrorBox('JavaScript error in the main process', ex.stack);
  }
});

(function() {
  // Define the CLI arguments and parse them
  const argv = yargs
    .usage('Usage: $0 [options]')
    .option('os-startup', {
      type: 'boolean',
      description: 'Flag to indicate the app is being ran by the OS on startup.'
    })
    .option('portable', {
      type: 'boolean',
      description: 'Run in portable mode.'
    })
    .option('version', {
      type: 'boolean',
      description: 'Print the app version.',
      alias: 'v'
    })
    .option('squirrel-install', {
      type: 'string',
      description: 'Squirrel.Windows flag, called when the app is installed.'
    })
    .option('squirrel-uninstall', {
      type: 'string',
      description: 'Squirrel.Windows flag, called after the app is updated.'
    })
    .option('squirrel-updated', {
      type: 'string',
      description: 'Squirrel.Windows flag, called when the app is uninstalled.'
    })
    .option('squirrel-obsolete', {
      type: 'string',
      description: 'Squirrel.Windows flag, called before updating to a new version.'
    })
    .option('squirrel-firstrun', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called only once after installation.'
    })
    .help('help', 'Print this help message.').alias('help', 'h')
    .epilog('Created with <3 by Alexandru Rosianu – http://www.aluxian.com/')
    .argv;

  // Check for Squirrel.Windows CLI args
  if (process.platform == 'win32' && SquirrelEvents.check(argv)) {
    return;
  }

  // Print the version and exit
  if (argv.version) {
    console.log(`${app.getName()} ${app.getVersion()}`);
    console.log(`Electron ${process.versions.electron}`);
    console.log(`Chromium ${process.versions.chrome}`);
    return app.quit();
  }

  // Enforce single instance
  const isDuplicateInstance = app.makeSingleInstance(() => {
    if (global.application) {
      const mainWindow = global.application.mainWindowManager.window;
      if (mainWindow) {
        if (mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        mainWindow.focus();
      }
    }
    return true;
  });

  if (isDuplicateInstance) {
    log('another instance of the app is already running');
    return app.quit();
  }

  // Change the userData path if in portable mode
  if (argv.portable || manifest.portable) {
    log('running in portable mode');
    const userDataPath = path.join(filePaths.getAppDir(), 'data');
    log('set userData path', userDataPath);
    app.setPath('userData', userDataPath);
  }

  // Enable the crash reporter and auto updater
  if (!process.mas) {
    app.on('will-finish-launching', function() {
      log('will finish launching');

      // Crash reporter
      const reporterOptions = {
        productName: manifest.productName,
        companyName: manifest.win.companyName,
        submitURL: manifest.crashReporter.url,
        autoSubmit: true
      };
      log('starting crash reporter', JSON.stringify(reporterOptions));
      CrashReporter.start(reporterOptions);

      // Auto updater
      log('starting auto updater');
      app.setAppUserModelId(manifest.win.userModelId);
      const feedUrl = manifest.updater.squirrelUrl[process.platform]
        .replace(/%CURRENT_VERSION%/g, manifest.version);
      AutoUpdater.setFeedURL(feedUrl);
    });
  } else {
    log('mas release');
  }

  // Create the main app object and init
  app.on('ready', function() {
    log('ready, launching app');
    global.manifest = manifest;
    global.application = new Application(manifest, argv);
    global.application.init();
  });
})();
<|endoftext|>


<commit_before>//
//  Copyright (C) Microsoft. All rights reserved.
//  Licensed under the MIT license. See LICENSE.txt file in the project root
//  for full license information.
//

'use strict';

var fs = require('fs');
var nativeInstaller = require('../../ios/nativeInstaller');
var path = require('path');

function loadIsTestEnvironment() {
  var utFlagFilePath = 'platforms/ios/unittests';

  try {
    var utFlag = fs.lstatSync(utFlagFilePath);

    try {
      console.log('Removing UT flag');

      fs.unlinkSync(utFlagFilePath);
    } catch (error) {
      console.log(error);
      console.log('Failed to remove the UT flag file, continuing anyway');
    }

    return utFlag.isFile();
  } catch (error) {
    console.log(error);
    console.log('Not a test environment, continue normally.');
  }

  return false;
}

module.exports = function (context) {

  var isTestEnvironment = loadIsTestEnvironment();

  // Need a promise so that
  // the install waits for us to complete our project modifications
  // before the plugin gets installed.
  var Q = context.requireCordovaModule('q');
  var deferred = new Q.defer();

  // Only bother if we're on macOS
  if (process.platform !== 'darwin') {
    deferred.resolve();
    return deferred.promise;
  }

  var platforms = context.opts.cordova.platforms;

  // We can bail out if the iOS platform isn't present.
  if (platforms.indexOf('ios') === -1) {
    deferred.resolve();
    return deferred.promise;
  }

  // We need to build ThaliCore.framework before embedding it into the project

  var thaliCoreProjectFolder = path.join(
    context.opts.plugin.dir, 'lib', 'ios', 'Carthage', 'Checkouts', 'thali-ios');
  var thaliCoreOutputFolder = path.join(
    context.opts.plugin.dir, 'lib', 'ios');
  var testingInfrastructureDir = path.join(
    context.opts.plugin.dir, 'src', 'ios', 'Testing');

  // We need to embded frameworks to the project here.
  // They need to be embedded binaries and cordova does not yet support that.
  // We will use node-xcode directy to add them since that library has
  // been upgraded to support embedded binaries.

  // Cordova libs to get the project path and project name
  // so we can locate the xcode project file.
  var cordovaUtil =
      context.requireCordovaModule('cordova-lib/src/cordova/util');
  var ConfigParser = context.requireCordovaModule('cordova-lib').configparser;
  var projectRoot = cordovaUtil.isCordova();
  var xml = cordovaUtil.projectConfig(projectRoot);
  var cfg = new ConfigParser(xml);

  var projectPath = path.join(
    projectRoot, 'platforms', 'ios', cfg.name() + '.xcodeproj');

  return nativeInstaller.addFramework(projectPath, thaliCoreProjectFolder,
    thaliCoreOutputFolder, isTestEnvironment, testingInfrastructureDir);
};
<commit_msg>Revert "Update thaliCoreProjectFolder in after_plugin_install.js hook."<commit_after>//
//  Copyright (C) Microsoft. All rights reserved.
//  Licensed under the MIT license. See LICENSE.txt file in the project root
//  for full license information.
//

'use strict';

var fs = require('fs');
var nativeInstaller = require('../../ios/nativeInstaller');
var path = require('path');

function loadIsTestEnvironment() {
  var utFlagFilePath = 'platforms/ios/unittests';

  try {
    var utFlag = fs.lstatSync(utFlagFilePath);

    try {
      console.log('Removing UT flag');

      fs.unlinkSync(utFlagFilePath);
    } catch (error) {
      console.log(error);
      console.log('Failed to remove the UT flag file, continuing anyway');
    }

    return utFlag.isFile();
  } catch (error) {
    console.log(error);
    console.log('Not a test environment, continue normally.');
  }

  return false;
}

module.exports = function (context) {

  var isTestEnvironment = loadIsTestEnvironment();

  // Need a promise so that
  // the install waits for us to complete our project modifications
  // before the plugin gets installed.
  var Q = context.requireCordovaModule('q');
  var deferred = new Q.defer();

  // Only bother if we're on macOS
  if (process.platform !== 'darwin') {
    deferred.resolve();
    return deferred.promise;
  }

  var platforms = context.opts.cordova.platforms;

  // We can bail out if the iOS platform isn't present.
  if (platforms.indexOf('ios') === -1) {
    deferred.resolve();
    return deferred.promise;
  }

  // We need to build ThaliCore.framework before embedding it into the project

  var thaliCoreProjectFolder = path.join(
    context.opts.plugin.dir, 'lib', 'ios', 'ThaliCore');
  var thaliCoreOutputFolder = path.join(
    context.opts.plugin.dir, 'lib', 'ios');
  var testingInfrastructureDir = path.join(
    context.opts.plugin.dir, 'src', 'ios', 'Testing');

  // We need to embded frameworks to the project here.
  // They need to be embedded binaries and cordova does not yet support that.
  // We will use node-xcode directy to add them since that library has
  // been upgraded to support embedded binaries.

  // Cordova libs to get the project path and project name
  // so we can locate the xcode project file.
  var cordovaUtil =
      context.requireCordovaModule('cordova-lib/src/cordova/util');
  var ConfigParser = context.requireCordovaModule('cordova-lib').configparser;
  var projectRoot = cordovaUtil.isCordova();
  var xml = cordovaUtil.projectConfig(projectRoot);
  var cfg = new ConfigParser(xml);

  var projectPath = path.join(
    projectRoot, 'platforms', 'ios', cfg.name() + '.xcodeproj');

  return nativeInstaller.addFramework(projectPath, thaliCoreProjectFolder,
    thaliCoreOutputFolder, isTestEnvironment, testingInfrastructureDir);
};
<|endoftext|>


<commit_before>(function ($) {
    /**
     * DatetimePicker Logic.
     */
    function DatetimePicker()
    {
        var that = this;

        this.format = {
            datetime: 'YYYY-MM-DD HH:mm',
            date: 'YYYY-MM-DD'
        };
        this.magicValues = [
            {id: '%%today%%', name: 'Today', value: [moment(), moment()]},
            {id: '%%yesterday%%', name: 'Yesterday', value: [moment().subtract(1, 'days'), moment().subtract(1, 'days')]},
            {id: '%%tomorrow%%', name: 'Tomorrow', value: [moment().add(1, 'days'), moment().add(1, 'days')]}
        ];

        // initialize
        this.init();

        // Observe document for added datetime picker(s)
        dom_observer.added(document, function (nodes) {
            $(nodes).each(function () {
                $(this).find('[data-provide="datetimepicker"]').each(function () {
                    that.init();
                });
            });
        });
    }

    DatetimePicker.prototype = {

        /**
         * Initialize method
         *
         * @return {undefined}
         */
        init: function () {
            var that = this;

            $('[data-provide="datetimepicker"]').each(function () {
                var input = this;
                // hidden input for magic value logic
                var hiddenInput = $('<input>').attr({name: $(this).attr('name'), type: 'hidden'});

                if ($(this).data('magic-value')) {
                    that.magicValues.forEach(function (item) {
                        if (input.value === item.id) {
                            hiddenInput.insertAfter(input);
                            $(hiddenInput).val(item.id);
                        }
                    });
                }

                var options = $(this).data();

                // date range picker (used for datetime fields)
                $(this).daterangepicker(that.getOptions(this, options), that.getCallback(this, hiddenInput));

                $(this).on('apply.daterangepicker', function (ev, picker) {
                    $(this).val(picker.startDate.format(picker.locale.format));
                });

                $(this).on('cancel.daterangepicker', function (ev, picker) {
                    $(this).val('');
                });
            });
        },

        /**
         * DateTime picker options getter.
         *
         * @param {object} input Datetime picker input
         * @return {object}
         */
        getOptions: function (input, args) {
            var options = {
                singleDatePicker: true,
                showDropdowns: true,
                timePicker: true,
                minYear: 1900,
                maxYear: 2050,
                drops: 'up',
                autoUpdateInput: false,
                timePicker24Hour: true,
                timePickerIncrement: 5,
                locale: {
                    cancelLabel: 'Clear',
                    firstDay: 1
                }
            };

            if (args !== undefined) {
                options = Object.assign(options, args)
            }

            options.locale.format = options.timePicker ? this.format.datetime : this.format.date;

            if ($(input).data('magic-value')) {
                options.ranges = [];
                this.magicValues.forEach(function (item) {
                    // add custom ranges for magic value logic
                    options.ranges[item.name] = item.value;

                    // convert magic value to label, for example "%%today%%" becomes "Today"
                    if (input.value === item.id) {
                        $(input).val(item.name);
                    }
                });
            }

            if (! input.value && undefined !== $(input).data('default-value')) {
                options.startDate = moment().format($(input).data('default-value'));
                options.autoUpdateInput = true;
            }

            return options;
        },

        getCallback: function (input, hiddenInput) {
            var that = this;
            var result = function (start, end, label) {};

            if ($(input).data('magic-value')) {
                result = function (start, end, label) {
                    // always remove hidden input
                    hiddenInput.remove();

                    if ('Custom Range' === label) {
                        return;
                    }

                    $(input).val(label);

                    // attach hidden input on magic value selection
                    hiddenInput.insertAfter(input);
                    that.magicValues.forEach(function (item) {
                        if (label === item.name) {
                            $(hiddenInput).val(item.id);
                        }
                    });

                    $(input).val(label);
                };
            }

            return result;
        }
    };

    new DatetimePicker();

})(jQuery);
<commit_msg>Daterangepicker Magic Values (task #10535)<commit_after>(function ($) {
    /**
     * DatetimePicker Logic.
     */
    function DatetimePicker()
    {
        var that = this;

        this.format = {
            datetime: 'YYYY-MM-DD HH:mm',
            date: 'YYYY-MM-DD'
        };
        this.magicValues = [
            {id: '%%today%%', name: 'Today', value: [moment(), moment()]},
            {id: '%%yesterday%%', name: 'Yesterday', value: [moment().subtract(1, 'days'), moment().subtract(1, 'days')]},
            {id: '%%tomorrow%%', name: 'Tomorrow', value: [moment().add(1, 'days'), moment().add(1, 'days')]}
        ];

        // initialize
        this.init();

        // Observe document for added datetime picker(s)
        dom_observer.added(document, function (nodes) {
            $(nodes).each(function () {
                $(this).find('[data-provide="datetimepicker"]').each(function () {
                    that.init();
                });
            });
        });
    }

    DatetimePicker.prototype = {

        /**
         * Initialize method
         *
         * @return {undefined}
         */
        init: function () {
            var that = this;

            $('[data-provide="datetimepicker"]').each(function () {
                var input = this;
                // hidden input for magic value logic
                var hiddenInput = $('<input>').attr({name: $(this).attr('name'), type: 'hidden'});

                if ($(this).data('magic-value')) {
                    that.magicValues.forEach(function (item) {
                        if (input.value === item.id) {
                            hiddenInput.insertAfter(input);
                            $(hiddenInput).val(item.id);
                        }
                    });
                }

                var options = $(this).data();

                // date range picker (used for datetime fields)
                $(this).daterangepicker(that.getOptions(this, options), that.getCallback(this, hiddenInput));

                if ($(this).data('magic-value')) {
                    $($(this).data('daterangepicker').container).find('.ranges ul').show();
                }

                $(this).on('apply.daterangepicker', function (ev, picker) {
                    $(this).val(picker.startDate.format(picker.locale.format));
                });

                $(this).on('cancel.daterangepicker', function (ev, picker) {
                    $(this).val('');
                });
            });
        },

        /**
         * DateTime picker options getter.
         *
         * @param {object} input Datetime picker input
         * @return {object}
         */
        getOptions: function (input, args) {
            var options = {
                singleDatePicker: true,
                showDropdowns: true,
                timePicker: true,
                minYear: 1900,
                maxYear: 2050,
                drops: 'up',
                autoUpdateInput: false,
                timePicker24Hour: true,
                timePickerIncrement: 5,
                locale: {
                    cancelLabel: 'Clear',
                    firstDay: 1
                }
            };

            if (args !== undefined) {
                options = Object.assign(options, args)
            }

            options.locale.format = options.timePicker ? this.format.datetime : this.format.date;

            if ($(input).data('magic-value')) {
                options.ranges = {};
                this.magicValues.forEach(function (item) {
                    // add custom ranges for magic value logic
                    options.ranges[item.name] = item.value;

                    // convert magic value to label, for example "%%today%%" becomes "Today"
                    if (input.value === item.id) {
                        $(input).val(item.name);
                    }
                });
            }

            if (! input.value && undefined !== $(input).data('default-value')) {
                options.startDate = moment().format($(input).data('default-value'));
                options.autoUpdateInput = true;
            }

            return options;
        },

        getCallback: function (input, hiddenInput) {
            var that = this;
            var result = function (start, end, label) {};

            if ($(input).data('magic-value')) {
                result = function (start, end, label) {
                    // always remove hidden input
                    hiddenInput.remove();

                    if ('Custom Range' === label) {
                        return;
                    }

                    $(input).val(label);

                    // attach hidden input on magic value selection
                    hiddenInput.insertAfter(input);
                    that.magicValues.forEach(function (item) {
                        if (label === item.name) {
                            $(hiddenInput).val(item.id);
                        }
                    });

                    $(input).val(label);
                };
            }

            return result;
        }
    };

    new DatetimePicker();

})(jQuery);
<|endoftext|>


<commit_before>//interface for accessing react-native-fcm module

import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm';
import {Platform} from "react-native";

const API_KEY = 'AAAA1i1g05s:APA91bEm3cI3lCflqY74PSH3O-3RGUk4H9kGqXKB1NfhT9igNntvDSSqWDBxajEK-rsbFovPVJzTJojx4Q-SlgFs-7D2fT2dmdw_0ii_5jodpn__jahPlKE1UL-HibRkSO8_6WL88B3D';

module.exports = {
    listen: function(alertCallback, infoCallback){
        this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {

                //if alert type message
                if(!notif.local_notification){
                    //if iOS or Android alert
                    if((notif.aps && notif.aps.alert && notif.aps.alert.body) || (notif.fcm && notif.fcm.body)){
                        if(alertCallback) {
                            alertCallback(notif);
                        }
                    }
                }
                //if information type message
                if(notif.message) {
                    if(infoCallback)
                        infoCallback(notif);
                }

                //closing iOS notification, required for being able to properly continuing receiving notifications
                if (Platform.OS === 'ios') {
                    switch (notif._notificationType) {
                        case NotificationType.Remote:
                            notif.finish(RemoteNotificationResult.NewData);
                            break;
                        case NotificationType.NotificationResponse:
                            notif.finish();
                            break;
                        case NotificationType.WillPresent:
                            notif.finish(WillPresentNotificationResult.All);
                            break;
                    }
                }
            }
        );
    },
    displayLocalNotif: function(notif){ //Android Only
        FCM.presentLocalNotification({
            id: notif["google.message_id"],
            body: notif.fcm.body,
            sound: "default",
            show_in_foreground: true
        });
        alert(notif.fcm.body);
    },
    //gets array of topic keys of currently subscribed subjects
    getSubscribed: function(callback){
        FCM.getFCMToken().then((token) => {
            fetch('https://iid.googleapis.com/iid/info/'+token+'?details=true', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'key='+API_KEY
                }
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(subscribed) {
                if(subscribed.rel && subscribed.rel.topics){
                    callback(Object.keys(subscribed.rel.topics));
                }
                else{
                    callback([]);
                }
            })
            .catch(function(err){
                console.log("GET SUBS ERR", err);
            });
        });
    },
    //subscribes device to subject (FCM topic) that corresponds with topic_key parameter
    subscribe: function(topic_key){
        FCM.subscribeToTopic('/topics/'+topic_key);
    },
    //unsubscribes device from subject (FCM topic) that corresponds with topic_key parameter
    unsubscribe: function(topic_key){
        //add check here for safeguarding against removing required/forced topics?
        FCM.unsubscribeFromTopic('/topics/'+topic_key);
    }
};<commit_msg>Update fcm.js<commit_after>//interface for accessing react-native-fcm module

import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm';
import {Platform} from "react-native";

const API_KEY = 'api-key';

module.exports = {
    listen: function(alertCallback, infoCallback){
        this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {

                //if alert type message
                if(!notif.local_notification){
                    //if iOS or Android alert
                    if((notif.aps && notif.aps.alert && notif.aps.alert.body) || (notif.fcm && notif.fcm.body)){
                        if(alertCallback) {
                            alertCallback(notif);
                        }
                    }
                }
                //if information type message
                if(notif.message) {
                    if(infoCallback)
                        infoCallback(notif);
                }

                //closing iOS notification, required for being able to properly continuing receiving notifications
                if (Platform.OS === 'ios') {
                    switch (notif._notificationType) {
                        case NotificationType.Remote:
                            notif.finish(RemoteNotificationResult.NewData);
                            break;
                        case NotificationType.NotificationResponse:
                            notif.finish();
                            break;
                        case NotificationType.WillPresent:
                            notif.finish(WillPresentNotificationResult.All);
                            break;
                    }
                }
            }
        );
    },
    displayLocalNotif: function(notif){ //Android Only
        FCM.presentLocalNotification({
            id: notif["google.message_id"],
            body: notif.fcm.body,
            sound: "default",
            show_in_foreground: true
        });
        alert(notif.fcm.body);
    },
    //gets array of topic keys of currently subscribed subjects
    getSubscribed: function(callback){
        FCM.getFCMToken().then((token) => {
            fetch('https://iid.googleapis.com/iid/info/'+token+'?details=true', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'key='+API_KEY
                }
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(subscribed) {
                if(subscribed.rel && subscribed.rel.topics){
                    callback(Object.keys(subscribed.rel.topics));
                }
                else{
                    callback([]);
                }
            })
            .catch(function(err){
                console.log("GET SUBS ERR", err);
            });
        });
    },
    //subscribes device to subject (FCM topic) that corresponds with topic_key parameter
    subscribe: function(topic_key){
        FCM.subscribeToTopic('/topics/'+topic_key);
    },
    //unsubscribes device from subject (FCM topic) that corresponds with topic_key parameter
    unsubscribe: function(topic_key){
        //add check here for safeguarding against removing required/forced topics?
        FCM.unsubscribeFromTopic('/topics/'+topic_key);
    }
};
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const ManifestPlugin = require('webpack-manifest-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const isProduction = process.env.APP_ENV === 'production'
const defaultFilename = isProduction ? '[name]-[hash]' : '[name]'

const styleParser = new ExtractTextPlugin(`styles/${defaultFilename}.css`)

const config = {
    entry: {
        //        blog: ['./resources/assets/scripts/src/public/public.js'],
        'blog-admin': ['./resources/assets/src/admin/scripts/admin.js'],
    },
    output: {
        path: path.resolve(process.cwd(), 'public/vendor/blog'),
        filename: `scripts/${defaultFilename}.js`,
        publicPath: '/vendor/blog/',
    },
    module: {
        loaders: [
            {
                // Watch for changes in HTML files
                test: /\.html$/,
                loader: 'raw-loader'
            },

            {
                test: /\.jsx?$/i,
                // Don't (re)compile vendor JS files
                exclude: /(node_modules|bower_components)/,
                // 'babel-loader' is also a legal name to reference
                loader: 'babel',
                query: {
                    presets: ['es2015'],
                    plugins: ['transform-strict-mode'],
                }
            },

            {
                test: /\.vue$/,
                loader: 'vue',
            },

            {
                // Compile CSS and SASS stylesheets with sourcemaps enabled
                test: /\.s?css$/i,
                loader: styleParser.extract(['css?sourceMap!postcss!sass?sourceMap']),
            },

            {
                // Optimize images
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    `file?name=[path]${defaultFilename}.[ext]&context=./resources/`,
                    'image-webpack'
                ]
            },

            // Extract fonts from stylesheets, optimize, and copy to public assets directory
            {
                test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=application/font-woff&name=./fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=application/font-woff&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=application/octet-stream&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'file?&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=image/svg+xml&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
        ],
    },
    // Image optimization settings
    imageWebpackLoader: {
        mozjpeg: {
            quality: 82
        },
        pngquant: {
            quality: "65-90",
            speed: 4
        },
        svgo: {
            plugins: [
                {removeEmptyAttrs: true},
                {cleanupAttrs: true},
                {removeComments: true},
                {removeMetadata: true},
                {removeTitle: true},
                {removeDesc: true},
                {removeEditorsNSData: true},
                {convertStyleToAttrs: true},
                {removeUselessDefs: true},
                {removeUnknownsAndDefaults: true},
                {removeUselessStrokeAndFill: true},
                {convertPathData: true},
                {removeDimensions: true},
            ]
        }
    },
    plugins: [
        // Log start of compiling
        function () {
            this.plugin('watch-run', function (watching, callback) {
                console.log('Begin compile at ' + new Date())
                callback()
            })
        },

        // Set our environment variables
        new webpack.DefinePlugin({
            'process.env.APP_ENV': JSON.stringify(process.env.APP_ENV),
        }),

        new ManifestPlugin({
            fileName: 'rev-manifest.json'
        }),

        // Compile CSS
        styleParser,

        // Find duplicate dependencies & prevents duplicate inclusion
        new webpack.optimize.DedupePlugin(),

        // Provide global support for vendor libraries
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',

            _: 'lodash',

            tether: 'tether',
            Tether: 'tether',
            'window.Tether': 'tether',

            CodeMirror: 'codemirror'
        }),
    ],
    resolve: {
        alias: {
            'jquery': path.resolve(process.cwd(), 'node_modules/jquery/src/jquery'),
            'vue$': 'vue/dist/vue.js',
        }
    },
    node: {
        // Fixes SimpleMDE package (see https://github.com/NextStepWebs/simplemde-markdown-editor/issues/150)
        fs: 'empty'
    },
    devServer: {
        port: process.env.SERVE_PORT || 8080,
        contentBase: 'public/vendor/blog',
        publicPath: process.env.SERVE_PROXY_TARGET + '/vendor/blog',
        hot: true,
        https: true,

        proxy: {
            '*': {
                target: process.env.SERVE_PROXY_TARGET,
                changeOrigin: true,
                autoRewrite: true,
                xfwd: true,
                secure: false,
            },
        },

        watchOptions: {
            aggregateTimeout: 20,
            poll: 1000
        },
    }
}

/* Production */

// Optimize order and uglify JS in production
if (process.env.APP_ENV === 'production') {
    // Add additional plugins
    config.plugins = config.plugins.concat([
        // This plugins optimizes chunks and modules by
        // how much they are used in your app
        new webpack.optimize.OccurenceOrderPlugin(),

        // This plugin prevents Webpack from creating chunks
        // that would be too small to be worth loading separately
        new webpack.optimize.MinChunkSizePlugin({
            // ~50kb
            minChunkSize: 51200,
        }),

        new webpack.optimize.UglifyJsPlugin({
            compress: {
                // Suppress uglification warnings
                warnings: false,
            },
            mangle: true,
            screw_ie8: true,
        }),
    ])
}

// Enable the configuration for external use
module.exports = config<commit_msg>Update webpack build script<commit_after>const path = require('path')
const webpack = require('webpack')
const ManifestPlugin = require('webpack-manifest-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const isProduction = process.env.APP_ENV === 'production'
const defaultFilename = isProduction ? '[name]-[hash]' : '[name]'

const styleParser = new ExtractTextPlugin(`styles/${defaultFilename}.css`)

const config = {
    devtool: 'cheap-module-eval-source-map',
    entry: {
        //        blog: ['./resources/assets/scripts/src/public/public.js'],
        'blog-admin': ['./resources/assets/src/admin/scripts/admin.js'],
    },
    output: {
        path: path.resolve(process.cwd(), 'public/vendor/blog'),
        filename: `scripts/${defaultFilename}.js`,
        publicPath: '/vendor/blog/',
    },
    module: {
        loaders: [
            {
                // Watch for changes in HTML files
                test: /\.html$/,
                loader: 'raw-loader'
            },

            {
                test: /\.jsx?$/i,
                // Don't (re)compile vendor JS files
                exclude: /(node_modules|bower_components)/,
                // 'babel-loader' is also a legal name to reference
                loader: 'babel',
                query: {
                    presets: ['es2015'],
                    plugins: ['transform-strict-mode'],
                }
            },

            {
                test: /\.vue$/,
                loader: 'vue',
            },

            {
                // Compile CSS and SASS stylesheets with sourcemaps enabled
                test: /\.s?css$/i,
                loader: styleParser.extract(['css?sourceMap!postcss!sass?sourceMap']),
            },

            {
                // Optimize images
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    `file?name=[path]${defaultFilename}.[ext]&context=./resources/`,
                    'image-webpack'
                ]
            },

            // Extract fonts from stylesheets, optimize, and copy to public assets directory
            {
                test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=application/font-woff&name=./fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=application/font-woff&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=application/octet-stream&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'file?&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url?limit=10000&mimetype=image/svg+xml&name=fonts/[name]/' + (isProduction ? '[hash]' : '[name]') + '.[ext]'
            },
        ],
    },
    // Image optimization settings
    imageWebpackLoader: {
        mozjpeg: {
            quality: 82
        },
        pngquant: {
            quality: "65-90",
            speed: 4
        },
        svgo: {
            plugins: [
                {removeEmptyAttrs: true},
                {cleanupAttrs: true},
                {removeComments: true},
                {removeMetadata: true},
                {removeTitle: true},
                {removeDesc: true},
                {removeEditorsNSData: true},
                {convertStyleToAttrs: true},
                {removeUselessDefs: true},
                {removeUnknownsAndDefaults: true},
                {removeUselessStrokeAndFill: true},
                {convertPathData: true},
                {removeDimensions: true},
            ]
        }
    },
    plugins: [
        // Log start of compiling
        function () {
            this.plugin('watch-run', function (watching, callback) {
                console.log('Begin compile at ' + new Date())
                callback()
            })
        },

        // Set our environment variables
        new webpack.DefinePlugin({
            'process.env.APP_ENV': JSON.stringify(process.env.APP_ENV),
        }),

        new ManifestPlugin({
            fileName: 'rev-manifest.json'
        }),

        // Compile CSS
        styleParser,

        // Find duplicate dependencies & prevents duplicate inclusion
        new webpack.optimize.DedupePlugin(),

        // Provide global support for vendor libraries
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',

            _: 'lodash',

            tether: 'tether',
            Tether: 'tether',
            'window.Tether': 'tether',

            CodeMirror: 'codemirror'
        }),
    ],
    resolve: {
        alias: {
            'jquery': path.resolve(process.cwd(), 'node_modules/jquery/src/jquery'),
            'vue$': 'vue/dist/vue.js',
        }
    },
    node: {
        // Fixes SimpleMDE package (see https://github.com/NextStepWebs/simplemde-markdown-editor/issues/150)
        fs: 'empty'
    },
    devServer: {
        port: process.env.SERVE_PORT || 8080,
        contentBase: 'public/vendor/blog',
        publicPath: process.env.SERVE_PROXY_TARGET + '/vendor/blog',
        hot: true,
        https: true,

        proxy: {
            '*': {
                target: process.env.SERVE_PROXY_TARGET,
                changeOrigin: true,
                autoRewrite: true,
                xfwd: true,
                secure: false,
            },
        },

        watchOptions: {
            aggregateTimeout: 20,
            poll: 1000
        },
    }
}

/* Production */

// Optimize order and uglify JS in production
if (process.env.APP_ENV === 'production') {
    // Add additional plugins
    config.plugins = config.plugins.concat([
        // This plugins optimizes chunks and modules by
        // how much they are used in your app
        new webpack.optimize.OccurenceOrderPlugin(),

        // This plugin prevents Webpack from creating chunks
        // that would be too small to be worth loading separately
        new webpack.optimize.MinChunkSizePlugin({
            // ~50kb
            minChunkSize: 51200,
        }),

        new webpack.optimize.UglifyJsPlugin({
            compress: {
                // Suppress uglification warnings
                warnings: false,
            },
            mangle: true,
            screw_ie8: true,
        }),
    ])
}

// Enable the configuration for external use
module.exports = config<|endoftext|>


<commit_before>function random_background() {
    var random_number = Math.floor(Math.random()*4)+1;
    $("#body").css('background-image', 'url("images/background'+random_number+'.jpg")');
}

function init() {
    data.load();
    favorites.load();
    filter.load();
}

function bind_talk_callbacks() {
    for(var i=0; i<data.talks().length; i++) {
        talk = data.talks()[i];

        // bind description show/hide
        $("#talk"+talk.id+" .content").toggle(function() {
            var talk_id = $(this).attr('talk_id');
            $(".description", this).show(200);
        }, function() {
            var talk_id = $(this).attr('talk_id');
            $(".description", this).hide(200);
        });

        // bind favorites/unfavorite
        $("#talk"+talk.id+" .fav").bind('click', function() {
            var talk_id = $("img", this).attr('talk_id');
            if(favorites.isFavorite(talk_id)) {
                $("img", this).attr('src', 'images/fav_off.png');
                favorites.remove(talk_id);
            } else {
                $("img", this).attr('src', 'images/fav_on.png');
                favorites.add(talk_id);
            }
        });
    }
}

function formatted_date(timestamp) {
    var date = new Date(timestamp*1000);

    // hours
    var hours = date.getHours();
    var am_pm = '';
    if(hours < 12) {
        am_pm = 'am';
    } else {
        am_pm = 'pm';
        hours -= 12;
    }

    // minutes
    var minutes = date.getMinutes();
    if(minutes < 10)
        minutes = '0'+minutes;

    // day of the week
    var day = day_of_talk(timestamp);
    return day+' '+hours+':'+minutes+am_pm;
}

function day_of_talk(timestamp) {
    var date = new Date(timestamp*1000);
    var day = date.getDay();
    switch(day) {
        case 0: day = 'Sunday'; break;
        case 1: day = 'Monday'; break;
        case 2: day = 'Tuesday'; break;
        case 3: day = 'Wednesday'; break;
        case 4: day = 'Thursday'; break;
        case 5: day = 'Friday'; break;
        case 6: day = 'Saturday'; break;
    }
    return day;
}

function favimg(id) {
    if(favorites.isFavorite(id))
        return 'fav_on.png';
    else
        return 'fav_off.png';
}

function display_talk(talk) {
    var i;
    html = '';
    html += '
';

    // favorite image
    var img_src = favimg(talk.id);
    html += '

';
    html += '
';
    // title
    html += '
'+talk.title+'
';
    // time, location
    html += '
'+formatted_date(talk.timestamp)+' | '+talk.location+'
';
    // speaker(s)
    html += '
';
    for(i=0; i<talk.speakers.length; i++) {
        var speaker = talk.speakers[i];
        html += '
'+speaker.name+'
';
        if(i < talk.speakers.length-1)
            html += ', ';
    }
    html += '
';
    // description
    html += '
'+talk.description+'
';
    // footer
    html += '
';
    html += '

';
    html += '
';
    return html;
}

function display_talks() {
    var html = '';

    if(!data.talks().length) {
        html += '
It looks like you don\'t have the schedule downloaded yet. You must open this app while connected to the internet at least once to download the schedule.
';
        html += '
Force Schedule Download Attempt
';
        $("#content").html(html);

        $("#force-download").bind('click', function() {
            data.load_force();
            display_talks();
        });
        return;
    }

    html += filter.display();

    // display all the talks for the current day
    for(var i=0; i<data.talks().length; i++) {
        var talk = data.talks()[i];
        if(filter.filter_func(talk))
            html += display_talk(talk);
    }
    $("#content").html(html);

    // bind stuff
    bind_talk_callbacks();
    filter.bind_callbacks();
}
<commit_msg>cleanup bind_talk_callbacks(), for (hopefully) performance gains<commit_after>function random_background() {
    var random_number = Math.floor(Math.random()*4)+1;
    $("#body").css('background-image', 'url("images/background'+random_number+'.jpg")');
}

function init() {
    data.load();
    favorites.load();
    filter.load();
}

function bind_talk_callbacks() {
  $(".content").click(function() {
    $(".description", this).toggle(200);
  });

  $(".fav").click(function() {
    var img = $("img", this);
    var talk_id = img.attr('talk_id');
    if(favorites.isFavorite(talk_id)) {
      img.attr('src', 'images/fav_off.png');
      favorites.remove(talk_id);
    } else {
      img.attr('src', 'images/fav_on.png');
      favorites.add(talk_id);
    }
  });
}

function formatted_date(timestamp) {
    var date = new Date(timestamp*1000);

    // hours
    var hours = date.getHours();
    var am_pm = '';
    if(hours < 12) {
        am_pm = 'am';
    } else {
        am_pm = 'pm';
        hours -= 12;
    }

    // minutes
    var minutes = date.getMinutes();
    if(minutes < 10)
        minutes = '0'+minutes;

    // day of the week
    var day = day_of_talk(timestamp);
    return day+' '+hours+':'+minutes+am_pm;
}

function day_of_talk(timestamp) {
    var date = new Date(timestamp*1000);
    var day = date.getDay();
    switch(day) {
        case 0: day = 'Sunday'; break;
        case 1: day = 'Monday'; break;
        case 2: day = 'Tuesday'; break;
        case 3: day = 'Wednesday'; break;
        case 4: day = 'Thursday'; break;
        case 5: day = 'Friday'; break;
        case 6: day = 'Saturday'; break;
    }
    return day;
}

function favimg(id) {
    if(favorites.isFavorite(id))
        return 'fav_on.png';
    else
        return 'fav_off.png';
}

function display_talk(talk) {
    var i;
    html = '';
    html += '
';

    // favorite image
    var img_src = favimg(talk.id);
    html += '

';
    html += '
';
    // title
    html += '
'+talk.title+'
';
    // time, location
    html += '
'+formatted_date(talk.timestamp)+' | '+talk.location+'
';
    // speaker(s)
    html += '
';
    for(i=0; i<talk.speakers.length; i++) {
        var speaker = talk.speakers[i];
        html += '
'+speaker.name+'
';
        if(i < talk.speakers.length-1)
            html += ', ';
    }
    html += '
';
    // description
    html += '
'+talk.description+'
';
    // footer
    html += '
';
    html += '

';
    html += '
';
    return html;
}

function display_talks() {
    var html = '';

    if(!data.talks().length) {
        html += '
It looks like you don\'t have the schedule downloaded yet. You must open this app while connected to the internet at least once to download the schedule.
';
        html += '
Force Schedule Download Attempt
';
        $("#content").html(html);

        $("#force-download").bind('click', function() {
            data.load_force();
            display_talks();
        });
        return;
    }

    html += filter.display();

    // display all the talks for the current day
    for(var i=0; i<data.talks().length; i++) {
        var talk = data.talks()[i];
        if(filter.filter_func(talk))
            html += display_talk(talk);
    }
    $("#content").html(html);

    // bind stuff
    bind_talk_callbacks();
    filter.bind_callbacks();
}
<|endoftext|>