<commit_before>/*jslint nomen: true */
/*globals define: true */

define(function (require) {
  'use strict';

  var settings = require('settings');
  var _ = require('lib/underscore');
  var $ = require('jquery');
  var L = require('lib/leaflet');

  var api = {};

  api.getSurveyFromSlug = function() {
    var slug = window.location.hash.slice(1);

    var url = settings.api.baseurl +  '/slugs/' + slug;
    console.log("I'm using this URL to get ");
    console.log(url);

    // TODO: Display a nice error if the survey wans't found.
    $.getJSON(url, function(data) {
      settings.surveyId = data.survey;

      // Actually get the survey metadata
      var surveyUrl = api.getSurveyURL();
      $.getJSON(surveyUrl, function(survey){
        settings.survey = survey.survey;
        console.log(settings.survey);
      });

    });
  };

  /*
   * Generates the URL to retrieve results for a given parcel
   */
  api.getSurveyURL = function() {
    return settings.api.baseurl + '/surveys/' + settings.surveyId;
  };

  api.getParcelDataURL = function(parcel_id) {
    return settings.api.baseurl + '/surveys/' + settings.surveyId + '/parcels/' + parcel_id + '/responses';
  };

  // Deprecated
  // api.getGeoPointInfoURL = function(lat, lng) {
  //   return settings.api.geo + '/parcels/parcel?lat=' + lat + '&lng=' + lng;
  // };

  api.getGeoBoundsObjectsURL = function(southwest, northeast) {
    return settings.api.geo + '/parcels?bbox=' + southwest.lng + ',' + southwest.lat + ',' + northeast.lng + ',' + northeast.lat;
  };

  api.getForm = function(callback) {
    console.log('Getting form data');
    var url = api.getSurveyURL() + '/forms';

    console.log(url);

    $.getJSON(url, function(data){

      // Get only the mobile forms
      var mobileForms = _.filter(data.forms, function(form) {
        if (_.has(form, 'type')) {
          if (form.type === 'mobile'){
            return true;
          }
        }
        return false;
      });
      settings.formData = mobileForms[0];

      console.log('Mobile forms');
      console.log(mobileForms);

      // Endpoint should give the most recent form first.
      callback();
    });
  };

  // Deal with the formatting of the geodata API.
  // In the future, this will be more genericized.
  // parcel_id => object_id
  // address => object_location
  api.parseObjectData = function(data) {
    return {
      parcelId: data.parcelId,
      address: data.address,
      polygon: data.polygon,
      centroid: data.centroid
    };
  };

  // Take an address string.
  // Add 'Detroit' to the end.
  // Return the first result as a lat-lng for convenience.
  // Or Null if Bing is being a jerk / we're dumb.
  api.codeAddress = function(address, callback) {
    console.log('Coding an address');
    console.log(address);

    // TODO: Append a locale to the address to make searching easier.
    // Can we get the locale from the geolocation feature?
    var addressWithLocale = address;
    var geocodeEndpoint = 'http://dev.virtualearth.net/REST/v1/Locations/' + addressWithLocale + '?o=json&key=' + settings.bing_key + '&jsonp=?';

    $.getJSON(geocodeEndpoint, function(data){
      if(data.resourceSets.length > 0){
        var point = data.resourceSets[0].resources[0].point;
        var latlng = new L.LatLng(point.coordinates[0], point.coordinates[1]);
        callback(latlng);
      }
    });
  };

  // Get responses to the survey recorded in the given bounds
  //
  // @param {Object} bounds A leaflet map bounds object
  // @param {Function} callback Expects a list of features & attributes
  api.getResponsesInBounds = function(bounds, callback) {
    var southwest = bounds.getSouthWest();
    var northeast = bounds.getNorthEast();

    // Given the bounds, generate a URL to ge the responses from the API.
    var serializedBounds = southwest.lat + ',' + southwest.lng + ',' + northeast.lat + ',' + northeast.lng;
    var url = api.getSurveyURL() + '/responses/in/' + serializedBounds;

    // Give the callback the responses.
    $.getJSON(url, function(data){
      if(data.responses) {
        callback(data.responses);
      }
    });
  };

  // Add a 100% buffer to a bounds object.
  // Makes parcels render faster when the map is moved
  var addBuffer = function(bounds) {
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();

    var lngDiff = ne.lng - sw.lng;
    var latDiff = ne.lat - sw.lat;

    var lngMod = lngDiff / 2;
    var latMod = latDiff / 2;

    var newSW = new L.LatLng(sw.lat - latMod, sw.lng - lngMod);
    var newNE = new L.LatLng(ne.lat + latMod, ne.lng + lngMod);

    return new L.LatLngBounds(newSW, newNE);
  };

  // Query the GeoAPI for features in the given bounds
  //
  // @param {Object} bounds A leaflet map bounds object
  // @param {Object} options Not currently used; here for consistency
  // @param {Function} callback Expects a list of features & attributes
  api.getObjectsInBounds = function(bounds, options, callback) {
    var bufferedBounds = addBuffer(bounds);
    var southwest = bufferedBounds.getSouthWest();
    var northeast = bufferedBounds.getNorthEast();

    // Given the bounds, generate a URL to ge the responses from the API.
    var url = api.getGeoBoundsObjectsURL(southwest, northeast);

    // Give the callback the responses.
    $.getJSON(url, function(data){
      if(data) {
        callback(data);
      }
    });
  };

  // ESRI stuff

  // Generate a query URL
  // A sample URL might look like this:
  //  http://ags.wingis.org/ArcGIS/rest/services/1_Parcels/MapServer/1/query?
  //  geometryType=esriGeometryEnvelope
  //  &geometry=-89.097769,42.271545,-89.092362,42.274038
  //  &f=json&outFields=*&inSR=4326
  //
  // @param {Object} bounds A bounds object from Leaflet
  // @param {Object} options Options for the query. Must include:
  //    endpoint: the URL of the needed Arc Server collection
  //    name: an array of keys that, when concatenated, name each location
  //      (eg, 'house number' + 'street name')
  //    id: the primary ID for each location (eg, parcel ID)
  api.generateArcQueryURL = function(bounds, options) {
    var url = options.endpoint;

    // Set the requested fields
    var outFields = _.reduce(options.name, function(memo, field){ return memo + ',' + field; }, options.id);
    url += 'query?' + 'outFields=' + outFields;

    // Add the geometry query
    // Given the bounds, generate a URL to ge the responses from the API.
    var southwest = bounds.getSouthWest();
    var northeast = bounds.getNorthEast();
    var serializedBounds = southwest.lng + ',' + southwest.lat + ',' + northeast.lng + ',' + northeast.lat;

    url += '&geometryType=esriGeometryEnvelope';
    url += '&geometry=' + serializedBounds;

    // We want JSON back
    url += '&f=json';

    // Make sure the server know's we're sending EPSG 4326
    // And that we want to get the same back
    url += '&inSR=4326';
    url += '&outSR=4326';

    // And finally, set a callback:
    url += '&callback=?';

    console.log(url);
    return url;
  };

  // Generate a human readable name for a feature.
  // Concatenates attributes together.
  //
  // @param {Object} attributes A set of attributes from an ArcServer feature
  // @param {Object} options A set of options with attribute "name", a list of
  //    1+ string keys
  api.generateNameFromAttributes = function(attributes, options) {
    var address = _.reduce(options.name, function(memo, key) {
      if(attributes[key]) {
        memo = memo + ' ' + attributes[key];
      }
      return memo;
    }, "");
    return address;
  };

  // Generate GeoJSON from ESRI's JSON data format
  //
  // @param {Array} geometry A list of features from a geoserver
  api.generateGeoJSONFromESRIGeometry = function(geometry) {
    var multiPolygon = {
      type: 'MultiPolygon',
      coordinates: []
    };

    _.each(geometry.rings, function(ring) {
      multiPolygon.coordinates.push([ring]);
    });

    return multiPolygon;
  };

  // Given a map boundary, get the objects in the bounds from the given
  //  ESRI server.
  //
  // @param {Object} bounds, a leaflet bounds object
  // @param {Function} callback With one parameter, results, a list of result
  //    objects as defined in map.js
  api.getObjectsInBoundsFromESRI = function(bounds, options, callback) {
    var processedResults;
    var url;

    // Give the callback the responses.
    url = api.generateArcQueryURL(bounds, options);
    $.getJSON(url, function(data){
      if(data) {
        processedResults = _.reduce(data.features, function(memo, feature) {
          var attributes = feature.attributes;

          var processedFeature = {};
          processedFeature.parcelId = attributes[options.id];
          processedFeature.address = api.generateNameFromAttributes(attributes, options);
          processedFeature.geometry = api.generateGeoJSONFromESRIGeometry(feature.geometry);
          memo.push(processedFeature);

          return memo;
        }, []);

        callback(processedResults);
      }
    });

  };

  return api;
});
<commit_msg>Move comment with demo settings<commit_after>/*jslint nomen: true */
/*globals define: true */

define(function (require) {
  'use strict';

  var settings = require('settings');
  var _ = require('lib/underscore');
  var $ = require('jquery');
  var L = require('lib/leaflet');

  var api = {};

  api.getSurveyFromSlug = function() {
    var slug = window.location.hash.slice(1);

    var url = settings.api.baseurl +  '/slugs/' + slug;
    console.log("I'm using this URL to get ");
    console.log(url);

    // TODO: Display a nice error if the survey wans't found.
    $.getJSON(url, function(data) {
      settings.surveyId = data.survey;

      // Actually get the survey metadata
      var surveyUrl = api.getSurveyURL();
      $.getJSON(surveyUrl, function(survey){
        settings.survey = survey.survey;
        console.log(settings.survey);
      });

    });
  };

  /*
   * Generates the URL to retrieve results for a given parcel
   */
  api.getSurveyURL = function() {
    return settings.api.baseurl + '/surveys/' + settings.surveyId;
  };

  api.getParcelDataURL = function(parcel_id) {
    return settings.api.baseurl + '/surveys/' + settings.surveyId + '/parcels/' + parcel_id + '/responses';
  };

  // Deprecated
  // api.getGeoPointInfoURL = function(lat, lng) {
  //   return settings.api.geo + '/parcels/parcel?lat=' + lat + '&lng=' + lng;
  // };

  api.getGeoBoundsObjectsURL = function(southwest, northeast) {
    return settings.api.geo + '/parcels?bbox=' + southwest.lng + ',' + southwest.lat + ',' + northeast.lng + ',' + northeast.lat;
  };

  api.getForm = function(callback) {
    console.log('Getting form data');
    var url = api.getSurveyURL() + '/forms';

    console.log(url);

    $.getJSON(url, function(data){

      // Get only the mobile forms
      var mobileForms = _.filter(data.forms, function(form) {
        if (_.has(form, 'type')) {
          if (form.type === 'mobile'){
            return true;
          }
        }
        return false;
      });
      settings.formData = mobileForms[0];

      console.log('Mobile forms');
      console.log(mobileForms);

      // Endpoint should give the most recent form first.
      callback();
    });
  };

  // Deal with the formatting of the geodata API.
  // In the future, this will be more genericized.
  // parcel_id => object_id
  // address => object_location
  api.parseObjectData = function(data) {
    return {
      parcelId: data.parcelId,
      address: data.address,
      polygon: data.polygon,
      centroid: data.centroid
    };
  };

  // Take an address string.
  // Add 'Detroit' to the end.
  // Return the first result as a lat-lng for convenience.
  // Or Null if Bing is being a jerk / we're dumb.
  api.codeAddress = function(address, callback) {
    console.log('Coding an address');
    console.log(address);

    // TODO: Append a locale to the address to make searching easier.
    // Can we get the locale from the geolocation feature?
    var addressWithLocale = address;
    var geocodeEndpoint = 'http://dev.virtualearth.net/REST/v1/Locations/' + addressWithLocale + '?o=json&key=' + settings.bing_key + '&jsonp=?';

    $.getJSON(geocodeEndpoint, function(data){
      if(data.resourceSets.length > 0){
        var point = data.resourceSets[0].resources[0].point;
        var latlng = new L.LatLng(point.coordinates[0], point.coordinates[1]);
        callback(latlng);
      }
    });
  };

  // Get responses to the survey recorded in the given bounds
  //
  // @param {Object} bounds A leaflet map bounds object
  // @param {Function} callback Expects a list of features & attributes
  api.getResponsesInBounds = function(bounds, callback) {
    var southwest = bounds.getSouthWest();
    var northeast = bounds.getNorthEast();

    // Given the bounds, generate a URL to ge the responses from the API.
    var serializedBounds = southwest.lat + ',' + southwest.lng + ',' + northeast.lat + ',' + northeast.lng;
    var url = api.getSurveyURL() + '/responses/in/' + serializedBounds;

    // Give the callback the responses.
    $.getJSON(url, function(data){
      if(data.responses) {
        callback(data.responses);
      }
    });
  };

  // Add a 100% buffer to a bounds object.
  // Makes parcels render faster when the map is moved
  var addBuffer = function(bounds) {
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();

    var lngDiff = ne.lng - sw.lng;
    var latDiff = ne.lat - sw.lat;

    var lngMod = lngDiff / 2;
    var latMod = latDiff / 2;

    var newSW = new L.LatLng(sw.lat - latMod, sw.lng - lngMod);
    var newNE = new L.LatLng(ne.lat + latMod, ne.lng + lngMod);

    return new L.LatLngBounds(newSW, newNE);
  };

  // Query the GeoAPI for features in the given bounds
  //
  // @param {Object} bounds A leaflet map bounds object
  // @param {Object} options Not currently used; here for consistency
  // @param {Function} callback Expects a list of features & attributes
  api.getObjectsInBounds = function(bounds, options, callback) {
    var bufferedBounds = addBuffer(bounds);
    var southwest = bufferedBounds.getSouthWest();
    var northeast = bufferedBounds.getNorthEast();

    // Given the bounds, generate a URL to ge the responses from the API.
    var url = api.getGeoBoundsObjectsURL(southwest, northeast);

    // Give the callback the responses.
    $.getJSON(url, function(data){
      if(data) {
        callback(data);
      }
    });
  };

  // ESRI stuff

  // Generate a query URL
  // A sample URL might look like this:
  //  http://ags.wingis.org/ArcGIS/rest/services/1_Parcels/MapServer/1/query?
  //  geometryType=esriGeometryEnvelope
  //  &geometry=-89.097769,42.271545,-89.092362,42.274038
  //  &f=json&outFields=*&inSR=4326
  //
  // Sample options might looks like this:
  // {
  //   "type": "ArcGIS Server",
  //   "endpoint": "http://ags.wingis.org/ArcGIS/rest/services/1_Parcels/MapServer/1/",
  //   "name": ["LOPHouseNumber", "LOPPrefixDirectional", "LOPStreetName"],
  //   "id": "PrimaryPIN"
  // }
  //
  // @param {Object} bounds A bounds object from Leaflet
  // @param {Object} options Options for the query. Must include:
  //    endpoint: the URL of the needed Arc Server collection
  //    name: an array of keys that, when concatenated, name each location
  //      (eg, 'house number' + 'street name')
  //    id: the primary ID for each location (eg, parcel ID)
  api.generateArcQueryURL = function(bounds, options) {
    var url = options.endpoint;

    // Set the requested fields
    var outFields = _.reduce(options.name, function(memo, field){ return memo + ',' + field; }, options.id);
    url += 'query?' + 'outFields=' + outFields;

    // Add the geometry query
    // Given the bounds, generate a URL to ge the responses from the API.
    var southwest = bounds.getSouthWest();
    var northeast = bounds.getNorthEast();
    var serializedBounds = southwest.lng + ',' + southwest.lat + ',' + northeast.lng + ',' + northeast.lat;

    url += '&geometryType=esriGeometryEnvelope';
    url += '&geometry=' + serializedBounds;

    // We want JSON back
    url += '&f=json';

    // Make sure the server know's we're sending EPSG 4326
    // And that we want to get the same back
    url += '&inSR=4326';
    url += '&outSR=4326';

    // And finally, set a callback:
    url += '&callback=?';

    console.log(url);
    return url;
  };

  // Generate a human readable name for a feature.
  // Concatenates attributes together.
  //
  // @param {Object} attributes A set of attributes from an ArcServer feature
  // @param {Object} options A set of options with attribute "name", a list of
  //    1+ string keys
  api.generateNameFromAttributes = function(attributes, options) {
    var address = _.reduce(options.name, function(memo, key) {
      if(attributes[key]) {
        memo = memo + ' ' + attributes[key];
      }
      return memo;
    }, "");
    return address;
  };

  // Generate GeoJSON from ESRI's JSON data format
  //
  // @param {Array} geometry A list of features from a geoserver
  api.generateGeoJSONFromESRIGeometry = function(geometry) {
    var multiPolygon = {
      type: 'MultiPolygon',
      coordinates: []
    };

    _.each(geometry.rings, function(ring) {
      multiPolygon.coordinates.push([ring]);
    });

    return multiPolygon;
  };

  // Given a map boundary, get the objects in the bounds from the given
  //  ESRI server.
  //
  // @param {Object} bounds, a leaflet bounds object
  // @param {Function} callback With one parameter, results, a list of result
  //    objects as defined in map.js
  api.getObjectsInBoundsFromESRI = function(bounds, options, callback) {
    var processedResults;
    var url;

    // Give the callback the responses.
    url = api.generateArcQueryURL(bounds, options);
    $.getJSON(url, function(data){
      if(data) {
        processedResults = _.reduce(data.features, function(memo, feature) {
          var attributes = feature.attributes;

          var processedFeature = {};
          processedFeature.parcelId = attributes[options.id];
          processedFeature.address = api.generateNameFromAttributes(attributes, options);
          processedFeature.geometry = api.generateGeoJSONFromESRIGeometry(feature.geometry);
          memo.push(processedFeature);

          return memo;
        }, []);

        callback(processedResults);
      }
    });

  };

  return api;
});
<|endoftext|>


<commit_before>//TODO:
	//THE ARRAY OF OBJECTS IS ALL FUCKED
	// MUST DEBUG $.EACH
	// NEED A BETTER METHOD

// API DATA Global Variables
var jsonReportLatest,
		sol,
		solarLongitue,
		updatedOn,
		sol,
		minTemp,
		maxTemp,
		minTempF,
		maxTempF,
		pressure,
		season,
		sunrise,
		sunset,
		condition;

var temperatureArchive = []; // graph uses this dataset

(function ($) {

	'use strict';

	// DOM NODE CACHING
	var maxTempContainer = $('.temp-max > span');
	var minTempContainer = $('.temp-min > span');
	var updateInfo = $('.update-info');

	// load latest data on load
	$('document').ready(getLatestMarsWeather);

	function getLatestMarsWeather() {

		var latestReportUrl = 'http://marsweather.ingenology.com/v1/latest/?format=jsonp';

		function outputData(data) {

			jsonReportLatest = data.report;
			updatedOn = data.report.terrestrial_date;
			sol = data.report.sol;
			minTemp = data.report.min_temp; // in celsius
			maxTemp = data.report.max_temp; // in celsius
			minTempF = data.report.min_temp_fahrenheit;
			maxTempF = data.report.max_temp_fahrenheit;
			condition = data.report.atmo_opacity; // always sunny, apparently...

			/*
			*		DOM INJECTION
			*/

			//update
			updateInfo.text("Curiosity Sent Last Update on  " + updatedOn);

			// temp module
			maxTempContainer.text(maxTempF).append('°');
			minTempContainer.text(minTempF).append('°');

		}

		/* GET JSONP FROM API
		============================*/
		$.ajax({

    	url: latestReportUrl,

    	// The name of the callback parameter, as specified by the YQL service
    	jsonp: "callback",

    	// Tell jQuery we're expecting JSONP
    	dataType: "jsonp",

    	// Work with the response
    	success: outputData
});

}

	/*================================
			Get Archive Mars data
	================================*/

	function loadArchive( pageNum ) {

		// if a page number is given, query that report
		if(pageNum)
			var archiveUrl = "http://marsweather.ingenology.com/v1/archive/?page=" + pageNum + "&format=jsonp";
		// otherwise request the latest 10 reports
		else
			var archiveUrl = "http://marsweather.ingenology.com/v1/archive/?format=jsonp";

		console.log(archiveUrl);

		// on success fill the last 10 temperature data reports into an array
		function getDataSet (data) {

			$.each(data.results, function(index, value){

				var graphPointsMinTemp = {
					date: value.terrestrial_date,
					min_temp: value.min_temp,
					min_temp_fahrenheit: value.min_temp_fahrenheit
				};

//				var graphPointsMaxTemp = {
//					date: value.terrestrial_date,
//					max_temp: value.max_temp,
//					max_temp_fahrenheit: value.max_temp_fahrenheit
//				};

				//push objects to array
				//temperatureArchive.push(graphPointsMaxTemp);
				temperatureArchive.push(graphPointsMinTemp);

			});

		}// end fillDataSet

		/* GET JSONP FROM API
		============================*/
		$.ajax({

    	url: archiveUrl,

    	// The name of the callback parameter, as specified by the YQL service
    	jsonp: "callback",

    	// Tell jQuery we're expecting JSONP
    	dataType: "jsonp",

    	// Work with the response
    	success: getDataSet,

			// chart the response once we obtain the data
			complete: drawChart
		}); // end AJAX

	} // end load archive;

	loadArchive();	// execute for debugging

	/* Temperature UI TOGGLE
	===============================**/

	// Temp Unit Toggling
	$('.unit-toggle').on('click', function(e) {

		var unitSymbol = $('.unit-symbol');
		var unit = this.dataset.unit;
		var button = $(this);

			if(unit === 'celsius') {

				// load celsius data
				maxTempContainer.text(maxTemp).append('°');
				minTempContainer.text(minTemp).append('°');

				// change unit in heading
				unitSymbol.text('( C )').append('°');

				// add active class and remove the other button's
				button.addClass('unit-active').siblings('button').removeClass('unit-active');

			} else {
				//load fahrenheit data
				maxTempContainer.text(maxTempF).append('°');
				minTempContainer.text(minTempF).append('°');

				// change unit in heading
				unitSymbol.text('( F )').append('°');

				// add active class and remove the other button's
				button.addClass('unit-active').siblings('button').removeClass('unit-active');

			}

	});

})(jQuery); // end module

/*=======================================
*	D3.js Visualitzation Code
*=======================================*/

function drawChart() {

	var data = temperatureArchive;

	// svg element dimensions
	var margin = {top: 30, right: 20, bottom: 30, left: 50},
			width = 600 - margin.left - margin.right,
			height = 270 - margin.top - margin.bottom;

	// Parse the date / time
	var parseDate = d3.time.format("%d-%b-%y").parse;

	// Set the ranges
	var x = d3.time.scale().range([0, width]);
	var y = d3.scale.linear().range([height, 0]);

	// Define the axes
	var xAxis = d3.svg.axis().scale(x)
			.orient("bottom").ticks(5);

	var yAxis = d3.svg.axis().scale(y)
			.orient("left").ticks(5);

	// Adds the svg canvas
	var svg = d3.select("#temp-graph")
			.append("svg")
					.attr("width", width + margin.left + margin.right)
					.attr("height", height + margin.top + margin.bottom)
			.append("g")
					.attr("transform",
								"translate(" + margin.left + "," + margin.top + ")");

	// iterate over data
	data.forEach(function(d) {
					d.date = new Date(d.date);
					d.min_temp_fahrenheit = d.min_temp_fahrenheit;
					//console.log(d.date);
					console.log(d.min_temp_fahrenheit);
			});

	// Scale the range of the data
	x.domain(d3.extent(data, function(d) { return d.date; }));
	y.domain([d3.min(data, function(d) { return d.min_temp_fahrenheit; }), d3.max(data, function(d) { return d.min_temp_fahrenheit; })]);

	// Define the line
	var valueline = d3.svg.line()
			.x(function(d) { return x(d.date); })
			.y(function(d) { return y(d.min_temp_fahrenheit); });

	// Add the valueline path.
	svg.append("path")
		 .attr("class", "line")
		 .attr("d", valueline(data));

	// Add the X Axis
	svg.append("g")
		 .attr("class", "x axis")
		 .attr("transform", "translate(0," + height + ")")
		 .call(xAxis);

	// Add the Y Axis
	svg.append("g")
		 .attr("class", "y axis")
		 .call(yAxis);

}

	<commit_msg>Added latest update info with real time computations<commit_after>//TODO:
	//THE ARRAY OF OBJECTS IS ALL FUCKED
	// MUST DEBUG $.EACH
	// NEED A BETTER METHOD

// API DATA Global Variables
var jsonReportLatest,
		sol,
		solarLongitue,
		updatedOn,
		sol,
		minTemp,
		maxTemp,
		minTempF,
		maxTempF,
		pressure,
		season,
		sunrise,
		sunset,
		condition;

var temperatureArchive = []; // graph uses this dataset

(function ($) {

	'use strict';

	// DOM NODE CACHING
	var maxTempContainer = $('.temp-max > span');
	var minTempContainer = $('.temp-min > span');
	var updateInfo = $('.update-info');

	// load latest data on load
	$('document').ready(getLatestMarsWeather);

	function getLatestMarsWeather() {

		var latestReportUrl = 'http://marsweather.ingenology.com/v1/latest/?format=jsonp';

		function outputData(data) {

			jsonReportLatest = data.report;
			updatedOn = data.report.terrestrial_date;
			sol = data.report.sol;
			minTemp = data.report.min_temp; // in celsius
			maxTemp = data.report.max_temp; // in celsius
			minTempF = data.report.min_temp_fahrenheit;
			maxTempF = data.report.max_temp_fahrenheit;
			condition = data.report.atmo_opacity; // always sunny, apparently...

			/*
			*		DOM Manipulation
			*/

			//update information
			var today = new Date();
			console.log(today);
			var diff = Math.abs(today - new Date(updatedOn)); // compute last update time in miliseconds
			var days = Math.floor(diff / 86400000); // convert do days

			//if days is 0, it was sent today
			if(days === 0)
				updateInfo.text("Curiosity Sent its last Update Today");
			else
				updateInfo.text("Curiosity Sent its last Update " + days + " days ago");

			// temp module
			maxTempContainer.text(maxTempF).append('°');
			minTempContainer.text(minTempF).append('°');

		}

		/* GET JSONP FROM API
		============================*/
		$.ajax({

    	url: latestReportUrl,

    	// The name of the callback parameter, as specified by the YQL service
    	jsonp: "callback",

    	// Tell jQuery we're expecting JSONP
    	dataType: "jsonp",

    	// Work with the response
    	success: outputData
});

}

	/*================================
			Get Archive Mars data
	================================*/

	function loadArchive( pageNum ) {

		// if a page number is given, query that report
		if(pageNum)
			var archiveUrl = "http://marsweather.ingenology.com/v1/archive/?page=" + pageNum + "&format=jsonp";
		// otherwise request the latest 10 reports
		else
			var archiveUrl = "http://marsweather.ingenology.com/v1/archive/?format=jsonp";

		// on success fill the last 10 temperature data reports into an array
		function getDataSet (data) {

			$.each(data.results, function(index, value){

				var graphPointsMinTemp = {
					date: value.terrestrial_date,
					min_temp: value.min_temp,
					min_temp_fahrenheit: value.min_temp_fahrenheit
				};

//				var graphPointsMaxTemp = {
//					date: value.terrestrial_date,
//					max_temp: value.max_temp,
//					max_temp_fahrenheit: value.max_temp_fahrenheit
//				};

				//push objects to array
				temperatureArchive.push(graphPointsMinTemp);

			});

		}// end fillDataSet

		/* GET JSONP FROM API
		============================*/
		$.ajax({

    	url: archiveUrl,

    	// The name of the callback parameter, as specified by the YQL service
    	jsonp: "callback",

    	// Tell jQuery we're expecting JSONP
    	dataType: "jsonp",

    	// Work with the response
    	success: getDataSet,

			// chart the response once we obtain the data
			complete: drawChart
		}); // end AJAX

	} // end load archive;

	loadArchive();	// execute for debugging

	/* Temperature UI TOGGLE
	===============================**/

	// Temp Unit Toggling
	$('.unit-toggle').on('click', function(e) {

		var unitSymbol = $('.unit-symbol');
		var unit = this.dataset.unit;
		var button = $(this);

			if(unit === 'celsius') {

				// load celsius data
				maxTempContainer.text(maxTemp).append('°');
				minTempContainer.text(minTemp).append('°');

				// change unit in heading
				unitSymbol.text('( C )').append('°');

				// add active class and remove the other button's
				button.addClass('unit-active').siblings('button').removeClass('unit-active');

			} else {
				//load fahrenheit data
				maxTempContainer.text(maxTempF).append('°');
				minTempContainer.text(minTempF).append('°');

				// change unit in heading
				unitSymbol.text('( F )').append('°');

				// add active class and remove the other button's
				button.addClass('unit-active').siblings('button').removeClass('unit-active');

			}

	});

})(jQuery); // end module

/*=======================================
*	D3.js Visualitzation Code
*=======================================*/

function drawChart() {

	var data = temperatureArchive;

	// svg element dimensions
	var margin = {top: 30, right: 20, bottom: 30, left: 50},
			width = 600 - margin.left - margin.right,
			height = 270 - margin.top - margin.bottom;

	// Parse the date / time
	var parseDate = d3.time.format("%d-%b-%y").parse;

	// Set the ranges
	var x = d3.time.scale().range([0, width]);
	var y = d3.scale.linear().range([height, 0]);

	// Define the axes
	var xAxis = d3.svg.axis().scale(x)
			.orient("bottom").ticks(5);

	var yAxis = d3.svg.axis().scale(y)
			.orient("left").ticks(5);

	// Adds the svg canvas
	var svg = d3.select("#temp-graph")
			.append("svg")
					.attr("width", width + margin.left + margin.right)
					.attr("height", height + margin.top + margin.bottom)
			.append("g")
					.attr("transform",
								"translate(" + margin.left + "," + margin.top + ")");

	// iterate over data
	data.forEach(function(d) {
					d.date = new Date(d.date);
					d.min_temp_fahrenheit = d.min_temp_fahrenheit;
					//console.log(d.date);
					console.log(d.min_temp_fahrenheit);
			});

	// Scale the range of the data
	x.domain(d3.extent(data, function(d) { return d.date; }));
	y.domain([d3.min(data, function(d) { return d.min_temp_fahrenheit; }), d3.max(data, function(d) { return d.min_temp_fahrenheit; })]);

	// Define the line
	var valueline = d3.svg.line()
			.x(function(d) { return x(d.date); })
			.y(function(d) { return y(d.min_temp_fahrenheit); })
			.interpolate('monotone');

	// Add the valueline path.
	svg.append("path")
		 .attr("class", "line")
		 .attr("d", valueline(data));

	// Add the X Axis
	svg.append("g")
		 .attr("class", "x axis")
		 .attr("transform", "translate(0," + height + ")")
		 .call(xAxis);

	// Add the Y Axis
	svg.append("g")
		 .attr("class", "y axis")
		 .call(yAxis);

}

	<|endoftext|>


<commit_before>(function($)
{
  var router = new $.mobile.Router( [
    {"#page-authorize": {handler: "pageAuthorize",
        events: "s", // do when we show the page
        argsre: true
    } },
    {"#home": {handler: "home",
  		  events: "s", // do when we show the page
  		  argsre: true
		} },

    {"#listing": {handler: "listing",
  	    events: "s", // do when we create the page
  	    argsre: true
    } },
    {"#registering-ruleset": {handler: "registeringRuleset",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#confirming-deletion": {handler: "confirmingDeletion",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#updating-url": {handler: "updatingUrl",
    		events: "s", // do when we show the page
    		argsre: true
		} },
    {"#page-picologging": {handler: "picologging",
		    events: "bs", // do when we show the page
		    argsre: true
    } },
    {"#page-installed-rulesets": {handler: "installed_rulesets",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#install-ruleset": {handler: "install_ruleset",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#confirm-uninstall-ruleset": {handler: "uninstall_ruleset",
				events: "bs", // do when we show the page
				argsre: true

    } }
    ],
      {
        pageAuthorize: function(type, match, ui, page) {
          console.log("manage fuse: authorize page");
          $.mobile.loading("hide");
        },

        home: function(type, match, ui, page) {
          console.log("home Handler");
          $.mobile.loading("hide");
        },

        listing: function(type, match, ui, page) {
          console.log("listing Handler");
          $("#manage-list" ).empty();

          Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
            console.log("attempting rough listview");
            //    var keys = rids_json.sort(sortBy("rid_index"));
            $.each(rids_json, paint_item);
            console.log("refreshing manage-list listview.");
            $('#manage-list').listview('refresh');
          });

        },

        registeringRuleset: function(type, match, ui, page) {

          console.log("registering Ruleset Handler");
          var frm = "#formRegisterNewRuleset";
            $(frm)[0].reset(); // clear the fields in the form
          $('#regester-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "registering ruleset...",
              textVisible: true
            });
            var registering_form_data = process_form(frm);
            console.log(">>>>>>>>> RID to register", registering_form_data);
            var appURL = registering_form_data.appURL;

            if(typeof appURL !== "undefined") {
              Devtools.RegisterRulesets(appURL, function(directives) {
                console.log("registered ", appURL, directives);
                $.mobile.changePage("#listing", {
                 transition: 'slide'
               });
              });
            }
          });

        },

        confirmingDeletion: function(type, match, ui, page) {
          console.log("confirming Deletion Handler");
        },

        updatingUrl: function(type, match, ui, page) {
          console.log("updating Url Handler");
          var rid = router.getParams(match[1])["rid"]; //not sure if this will still work
          console.log("RID to update URL of: ", rid);
          var frm = "#form-update-url";

          $(frm)[0].reset(); // clear the fields in the form
          $('#update-url-confirm-button').off('tap').on('tap', function(event)
          {
            $.mobile.loading("show", {
              text: "Updating URL...",
              textVisible: true
            });
            var update_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", update_form_data);
            var url = update_form_data.url;

            if(typeof url !== "undefined") {
              /*Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                  transition: 'slide' //all of this found in install_rulesets */
                Devtools.updateURL(rid, url, function(){
                  console.log("updating the function is running");
                  $.mobile.changePage("#listing", {
                    transition: 'slide'
                   });
                });

            }

          });

        },

        picologging: function(type, match, ui, page) {
          console.log("pico logging page");
          $.mobile.loading("hide");

          function populate_logpage() {
            Pico.logging.status(CloudOS.defaultECI, function(json){
              console.log("Logging status: ", json);
              if(json) {
               $("#logstatus").val("on").slider("refresh");
               $("#loglist" ).empty();
               Pico.logging.getLogs(CloudOS.defaultECI, function(logdata){
                 console.log("Retrieved logs");
                 $.each(logdata, function(i, logobj) {
                  var eid_re = RegExp("\\s+" + logobj.eid);
                  logobj.log_items = logobj.log_items.map(function(i){ return i.replace(eid_re, '');
                  });
                  $("#loglist" ).append(
                   snippets.logitem_template(logobj)
                   ).collapsibleset().collapsibleset( "refresh" );
                  $("#loglist").listview("refresh");
                 });
               });

              } else {
               $("#logstatus").val("off").slider("refresh");
              }
            });
          }

          populate_logpage();

        	    // triggers
              $("#logstatus").unbind("change").change(function(){
                var newstatus = $("#logstatus").val();
                if(newstatus === "on") {
                  Pico.logging.reset(CloudOS.defaultECI, {});
                  populate_logpage();
                } else {
                  Pico.logging.inactive(CloudOS.defaultECI, {});
                  $("#loglist" ).empty();
                }
              });
              $( "#logrefresh" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                populate_logpage();
              });
              $( "#logclear" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                Pico.logging.flush(CloudOS.defaultECI, {});
              });

          },

        installed_rulesets: function(type, match, ui, page) {
          console.log("ruleset installation page");
          $.mobile.loading("hide");

          function populate_installed_rulesets() {
            $("#installed-rulesets" ).empty();
            Devtools.showInstalledRulesets(function(ruleset_list){
             console.log("Retrieved installed rulesets");
             $.each(ruleset_list, function(k, ruleset) {
               ruleset["rid"] = k;
      			    ruleset["OK"] = k !== "a169x625.prod"; // don't allow deletion of CloudOS; this could be more robust
      			    $("#installed-rulesets" ).append(
                 snippets.installed_ruleset_template(ruleset)
                 ).collapsibleset().collapsibleset( "refresh" );
      			    $("#installed-rulesets").listview("refresh");
             });
           });
          };

          populate_installed_rulesets();

          },

        uninstall_ruleset: function(type, match, ui, page) {
           console.log("Showing uninstall ruleset page");
           $.mobile.loading("hide");
           var rid = router.getParams(match[1])["rid"];
           console.log("RID to uninstall: ", rid);
           $("#remove-ruleset" ).empty();
           $("#remove-ruleset").append(snippets.confirm_ruleset_remove({"rid": rid}));
           $("#remove-ruleset").listview().listview("refresh");
           $('#remove-ruleset-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Uninstalling ruleset...",
              textVisible: true
            });
            console.log("Uninstalling RID ", rid);
            if(typeof rid !== "undefined") {
              Devtools.uninstallRulesets(rid, function(directives) {
                console.log("uninstalled ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
           });
      	},

      	install_ruleset: function(type, match, ui, page) {
         console.log("Showing install ruleset page");
         $.mobile.loading("hide");
         var frm = "#form-install-ruleset";
      	    $(frm)[0].reset(); // clear the fields in the form
           $('#install-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Installing ruleset...",
              textVisible: true
            });
            var install_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", install_form_data);
            var rid = install_form_data.rid;

            if(typeof rid !== "undefined") {
              Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
          });
         }
        },

      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route:", type, ui, page );
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
          list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
          logitem_template: Handlebars.compile($("#logitem-template").html() || ""),
          installed_ruleset_template: Handlebars.compile($("#installed-ruleset-template").html() || ""),
	        confirm_ruleset_remove: Handlebars.compile($("#confirm-ruleset-remove-template").html() || "")
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

      function onPageLoad() {// Document.Ready
      	console.log("document ready");
        CloudOS.retrieveSession();
  	    // only put static stuff here...
  	    plant_authorize_button();

  	    $('.logout').off("tap").on("tap", function(event)
        {
  	      CloudOS.removeSession(true); // true for hard reset (log out of login server too)
  	      $.mobile.changePage('#page-authorize', {
            transition: 'slide'
  	      }); // this will go to the authorization page.
        });

        Handlebars.registerHelper('ifDivider', function(v1, options) {
         if(v1.match(/-----\*\*\*----/)) {
          return options.fn(this);
         }
          return options.inverse(this);
         });

        console.log("Choose page to show");

        try {
          var authd = CloudOS.authenticatedSession();
          if(authd) {
            console.log("Authorized");
            document.location.hash = "#home";
          } else {
            console.log("Asking for authorization");
            document.location.hash = "#page-authorize";
          }
        } catch (exception) {

        } finally {
          $.mobile.initializePage();
          $.mobile.loading("hide");
        }

      }

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
      $(document).bind("mobileinit", onMobileInit);
      $(document).ready(onPageLoad);
  })(jQuery);

  function clear_error_msg(frm) {// we dont have #error-msg ---------------
       $("#error-msg", frm).html("").hide();
  }
  function sortBy(prop){

    return function(a,b){

    //if a and b match regex /\w+\d+xd+\.\w+/
    // split on .
      // split on x
        //compare
      if( a[prop] < b[prop]){
        return 1;
      }else if( a[prop] > b[prop] ){
        return -1;
      }
      return 0;
    };
  };

  function paint_item(id, rids) {
    var status = "no status"; // place holder for description
    console.log("rid: "+ rids.rid);

    $('#manage-list').append(
      snippets.list_rulesets_template(
        {"rid": rids["rid"],
        "uri": rids["uri"]}
      )
    );
  };

  var sortByName = function (a, b) {
  	if (a.name > b.name) {
  	    return 1;
  	}
  	if (a.name < b.name) {
  	    return -1;
  	}
  	// a must be equal to b
  	return 0;
  };

    // process an array of objects from a form to be a proper object
  var process_form_results = function(raw_results) {
  	var results = {};
  	$.each(raw_results, function(i, v) {
  		var nym = v.name,
   	  val = v.value;
  		if (results[nym] && results[nym] instanceof Array) {
  		  results[nym].push(val);
  		} else if (results[nym]) {
  		  results[nym] = [results[nym], val];
  		} else {
  		  results[nym] = val;
  		}
  	});
  	return results;
  };

  var process_form = function(frm) {
	 var results = process_form_results($(frm).serializeArray());
	 return results;
  };

<commit_msg>correct function call<commit_after>(function($)
{
  var router = new $.mobile.Router( [
    {"#page-authorize": {handler: "pageAuthorize",
        events: "s", // do when we show the page
        argsre: true
    } },
    {"#home": {handler: "home",
  		  events: "s", // do when we show the page
  		  argsre: true
		} },

    {"#listing": {handler: "listing",
  	    events: "s", // do when we create the page
  	    argsre: true
    } },
    {"#registering-ruleset": {handler: "registeringRuleset",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#confirming-deletion": {handler: "confirmingDeletion",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#updating-url": {handler: "updatingUrl",
    		events: "s", // do when we show the page
    		argsre: true
		} },
    {"#page-picologging": {handler: "picologging",
		    events: "bs", // do when we show the page
		    argsre: true
    } },
    {"#page-installed-rulesets": {handler: "installed_rulesets",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#install-ruleset": {handler: "install_ruleset",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#confirm-uninstall-ruleset": {handler: "uninstall_ruleset",
				events: "bs", // do when we show the page
				argsre: true

    } }
    ],
      {
        pageAuthorize: function(type, match, ui, page) {
          console.log("manage fuse: authorize page");
          $.mobile.loading("hide");
        },

        home: function(type, match, ui, page) {
          console.log("home Handler");
          $.mobile.loading("hide");
        },

        listing: function(type, match, ui, page) {
          console.log("listing Handler");
          $("#manage-list" ).empty();

          Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
            console.log("attempting rough listview");
            //    var keys = rids_json.sort(sortBy("rid_index"));
            $.each(rids_json, paint_item);
            console.log("refreshing manage-list listview.");
            $('#manage-list').listview('refresh');
          });

        },

        registeringRuleset: function(type, match, ui, page) {

          console.log("registering Ruleset Handler");
          var frm = "#formRegisterNewRuleset";
            $(frm)[0].reset(); // clear the fields in the form
          $('#regester-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "registering ruleset...",
              textVisible: true
            });
            var registering_form_data = process_form(frm);
            console.log(">>>>>>>>> RID to register", registering_form_data);
            var appURL = registering_form_data.appURL;

            if(typeof appURL !== "undefined") {
              Devtools.RegisterRuleset(appURL, function(directives) {
                console.log("registered ", appURL, directives);
                $.mobile.changePage("#listing", {
                 transition: 'slide'
               });
              });
            }
          });

        },

        confirmingDeletion: function(type, match, ui, page) {
          console.log("confirming Deletion Handler");
        },

        updatingUrl: function(type, match, ui, page) {
          console.log("updating Url Handler");
          var rid = router.getParams(match[1])["rid"]; //not sure if this will still work
          console.log("RID to update URL of: ", rid);
          var frm = "#form-update-url";

          $(frm)[0].reset(); // clear the fields in the form
          $('#update-url-confirm-button').off('tap').on('tap', function(event)
          {
            $.mobile.loading("show", {
              text: "Updating URL...",
              textVisible: true
            });
            var update_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", update_form_data);
            var url = update_form_data.url;

            if(typeof url !== "undefined") {
              /*Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                  transition: 'slide' //all of this found in install_rulesets */
                Devtools.updateURL(rid, url, function(){
                  console.log("updating the function is running");
                  $.mobile.changePage("#listing", {
                    transition: 'slide'
                   });
                });

            }

          });

        },

        picologging: function(type, match, ui, page) {
          console.log("pico logging page");
          $.mobile.loading("hide");

          function populate_logpage() {
            Pico.logging.status(CloudOS.defaultECI, function(json){
              console.log("Logging status: ", json);
              if(json) {
               $("#logstatus").val("on").slider("refresh");
               $("#loglist" ).empty();
               Pico.logging.getLogs(CloudOS.defaultECI, function(logdata){
                 console.log("Retrieved logs");
                 $.each(logdata, function(i, logobj) {
                  var eid_re = RegExp("\\s+" + logobj.eid);
                  logobj.log_items = logobj.log_items.map(function(i){ return i.replace(eid_re, '');
                  });
                  $("#loglist" ).append(
                   snippets.logitem_template(logobj)
                   ).collapsibleset().collapsibleset( "refresh" );
                  $("#loglist").listview("refresh");
                 });
               });

              } else {
               $("#logstatus").val("off").slider("refresh");
              }
            });
          }

          populate_logpage();

        	    // triggers
              $("#logstatus").unbind("change").change(function(){
                var newstatus = $("#logstatus").val();
                if(newstatus === "on") {
                  Pico.logging.reset(CloudOS.defaultECI, {});
                  populate_logpage();
                } else {
                  Pico.logging.inactive(CloudOS.defaultECI, {});
                  $("#loglist" ).empty();
                }
              });
              $( "#logrefresh" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                populate_logpage();
              });
              $( "#logclear" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                Pico.logging.flush(CloudOS.defaultECI, {});
              });

          },

        installed_rulesets: function(type, match, ui, page) {
          console.log("ruleset installation page");
          $.mobile.loading("hide");

          function populate_installed_rulesets() {
            $("#installed-rulesets" ).empty();
            Devtools.showInstalledRulesets(function(ruleset_list){
             console.log("Retrieved installed rulesets");
             $.each(ruleset_list, function(k, ruleset) {
               ruleset["rid"] = k;
      			    ruleset["OK"] = k !== "a169x625.prod"; // don't allow deletion of CloudOS; this could be more robust
      			    $("#installed-rulesets" ).append(
                 snippets.installed_ruleset_template(ruleset)
                 ).collapsibleset().collapsibleset( "refresh" );
      			    $("#installed-rulesets").listview("refresh");
             });
           });
          };

          populate_installed_rulesets();

          },

        uninstall_ruleset: function(type, match, ui, page) {
           console.log("Showing uninstall ruleset page");
           $.mobile.loading("hide");
           var rid = router.getParams(match[1])["rid"];
           console.log("RID to uninstall: ", rid);
           $("#remove-ruleset" ).empty();
           $("#remove-ruleset").append(snippets.confirm_ruleset_remove({"rid": rid}));
           $("#remove-ruleset").listview().listview("refresh");
           $('#remove-ruleset-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Uninstalling ruleset...",
              textVisible: true
            });
            console.log("Uninstalling RID ", rid);
            if(typeof rid !== "undefined") {
              Devtools.uninstallRulesets(rid, function(directives) {
                console.log("uninstalled ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
           });
      	},

      	install_ruleset: function(type, match, ui, page) {
         console.log("Showing install ruleset page");
         $.mobile.loading("hide");
         var frm = "#form-install-ruleset";
      	    $(frm)[0].reset(); // clear the fields in the form
           $('#install-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Installing ruleset...",
              textVisible: true
            });
            var install_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", install_form_data);
            var rid = install_form_data.rid;

            if(typeof rid !== "undefined") {
              Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
          });
         }
        },

      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route:", type, ui, page );
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
          list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
          logitem_template: Handlebars.compile($("#logitem-template").html() || ""),
          installed_ruleset_template: Handlebars.compile($("#installed-ruleset-template").html() || ""),
	        confirm_ruleset_remove: Handlebars.compile($("#confirm-ruleset-remove-template").html() || "")
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

      function onPageLoad() {// Document.Ready
      	console.log("document ready");
        CloudOS.retrieveSession();
  	    // only put static stuff here...
  	    plant_authorize_button();

  	    $('.logout').off("tap").on("tap", function(event)
        {
  	      CloudOS.removeSession(true); // true for hard reset (log out of login server too)
  	      $.mobile.changePage('#page-authorize', {
            transition: 'slide'
  	      }); // this will go to the authorization page.
        });

        Handlebars.registerHelper('ifDivider', function(v1, options) {
         if(v1.match(/-----\*\*\*----/)) {
          return options.fn(this);
         }
          return options.inverse(this);
         });

        console.log("Choose page to show");

        try {
          var authd = CloudOS.authenticatedSession();
          if(authd) {
            console.log("Authorized");
            document.location.hash = "#home";
          } else {
            console.log("Asking for authorization");
            document.location.hash = "#page-authorize";
          }
        } catch (exception) {

        } finally {
          $.mobile.initializePage();
          $.mobile.loading("hide");
        }

      }

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
      $(document).bind("mobileinit", onMobileInit);
      $(document).ready(onPageLoad);
  })(jQuery);

  function clear_error_msg(frm) {// we dont have #error-msg ---------------
       $("#error-msg", frm).html("").hide();
  }
  function sortBy(prop){

    return function(a,b){

    //if a and b match regex /\w+\d+xd+\.\w+/
    // split on .
      // split on x
        //compare
      if( a[prop] < b[prop]){
        return 1;
      }else if( a[prop] > b[prop] ){
        return -1;
      }
      return 0;
    };
  };

  function paint_item(id, rids) {
    var status = "no status"; // place holder for description
    console.log("rid: "+ rids.rid);

    $('#manage-list').append(
      snippets.list_rulesets_template(
        {"rid": rids["rid"],
        "uri": rids["uri"]}
      )
    );
  };

  var sortByName = function (a, b) {
  	if (a.name > b.name) {
  	    return 1;
  	}
  	if (a.name < b.name) {
  	    return -1;
  	}
  	// a must be equal to b
  	return 0;
  };

    // process an array of objects from a form to be a proper object
  var process_form_results = function(raw_results) {
  	var results = {};
  	$.each(raw_results, function(i, v) {
  		var nym = v.name,
   	  val = v.value;
  		if (results[nym] && results[nym] instanceof Array) {
  		  results[nym].push(val);
  		} else if (results[nym]) {
  		  results[nym] = [results[nym], val];
  		} else {
  		  results[nym] = val;
  		}
  	});
  	return results;
  };

  var process_form = function(frm) {
	 var results = process_form_results($(frm).serializeArray());
	 return results;
  };

<|endoftext|>


<commit_before>var app = angular.module("myApp", ["firebase"]);

app.controller("myController", function ($scope, $firebaseArray) {
    var ref = firebase.database().ref().child("messages");
    // create a synchronized array
    // click on `index.html` above to see it used in the DOM!
    $scope.messages = $firebaseArray(ref);

    $scope.addMessage = function () {
        $scope.messages.$add({
            text: $scope.newMessageText
        });
    };

    $scope.removeElement = function (message) {
        $scope.messages.$remove(message).then(function(ref) {
            ref.key === message.$id; // true
        });
    }
});<commit_msg>Prevent some bad words<commit_after>var app = angular.module("myApp", ["firebase"]);

app.controller("myController", function ($scope, $firebaseArray) {
    var ref = firebase.database().ref().child("messages");
    // create a synchronized array
    // click on `index.html` above to see it used in the DOM!
    $scope.messages = $firebaseArray(ref);

    $scope.addMessage = function () {
        if ($scope.newMessageText.includes('buceta') || $scope.newMessageText.includes('cu') || $scope.newMessageText.includes('viado') || $scope.newMessageText.includes('bolsonaro') || $scope.newMessageText.includes('lula') || $scope.newMessageText.includes('sexo')) {
            alert('Achou que eu não ia me preparar pra isso? Achou errado otário!');
        } else {
            $scope.messages.$add({
                text: $scope.newMessageText
            });
            $scope.newMessageText = "";
        }
    };

    $scope.removeElement = function (message) {
        $scope.messages.$remove(message).then(function(ref) {
            ref.key === message.$id; // true
        });
    }
});<|endoftext|>


<commit_before>var dogtalk = angular.module('dogtalk', []);

dogtalk.config(function ($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: "home.html",
    controller: "homeCtrl",
    resolve: {
      init: homeCtrl.homeInit
    }
  }).when('/settings', {
    templateUrl: "settings.html",
    controller: "settingsCtrl",
    resolve: {
      loadData: settingsCtrl.settingsInit
    }
  }).when('/log', {
    templateUrl: "log.html",
    controller: "logCtrl",
    resolve: {
      init: logCtrl.logInit
    }
  }).otherwise({
    redirectTo: "/"
  });
});

dogtalk.directive("error", function ($rootScope) {
  return {
    restrict: "E",
    template: '
'+
              '{{displayError.title}}' +
              '
{{displayError.message}}
' +
              '
',
    link: function (scope) {
      $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
        console.log('directive routeChangeError: ', event, current, previous, rejection);

        scope.isError = false;
        scope.displayError = {title: '', message: ''};
        var errors = {
          1: {
            title : 'First things first',
            message: 'You must connect to your remoteStorage'
          },
          2: {
            title: 'Unable to connect to Sockethub',
            message: 'You must fill in your Sockethub connection details'
          },
          3: {
            title: 'Sockethub connection',
            message: 'Unable to connect to Sockethub please check your configuration and try again'
          },
          4: {
            title: 'Registration problem',
            message: 'We were unable to register with your Sockethub instance'
          },
          'unknown': {
            title: 'An unknown error has occurred',
            message: ''
          }
        };

        scope.isError = true;
        if ((typeof rejection !== 'object') ||
            (typeof rejection.error === 'undefined') ||
            (typeof errors[rejection.error] == 'undefined')) {
          scope.displayError = errors['unknown'];
          scope.displayError.message = String(rejection.original || rejection);
        } else {
          scope.displayError = errors[rejection.error];
        }

        if (rejection.error === 2) {
          console.log('no config found, launch modal');
          $rootScope.$broadcast('showModalSockethubSettings', {locked: true});
        }

        //console.log('error scope has flags now: ', 'remotestorage', scope.isRemoteStorageError, 'sockethub config', scope.isSockethubConfigError, 'sockethub connect', scope.isSockethubConnectionError, 'sockethub registration', scope.isSockethubRegistrationError, 'unknown', scope.isUnknownError);

      });

      $rootScope.$on("$routeChangeSuccess", function (event, current, previous) {
        if (sockethub.isConnected()) {
          scope.isSockethubConnectionError = false;
        } else {
          scope.isSockethubConnectionError = true;
        }

      });
    }
  };
});

/**
 * Function: initializeApp
 *
 * when app is loaded, we need to verify remoteStorage and Sockethub are connected
 * and provide the proper control-flow to the user if not.
 *
 */
// initialization factory
dogtalk.factory('init', ['$rootScope', '$q', '$timeout', 'sh',
function ($rootScope, $q, $timeout, sh) {
  return {
    setState: function () {
      var defer = $q.defer();
      $timeout(function() {
        if (remoteStorage.getBearerToken() === null) {
          defer.reject({error: 1, message: "remoteStorage not connected"});
        } else {
          if (sh.isConnected()) {
            console.log('already connected to sockethub');
            defer.resolve();
          } else {
            if (sh.config.exists()) {
              console.log('already have sockethub config, no need to fetch');
              sockethub.connect(defer);
            } else {
              remoteStorage.onWidget('ready', function() {
                $timeout(function() {
                  remoteStorage.sockethub.getConfig().then(function (config) {
                    console.log('initializeApp: got config: ', config);
                    if (!config) {
                      defer.reject({error: 2, message: "no sockethub config found"});
                    } else {
                      console.log('setting config and attempting connection');
                      sh.config.host = config.host;
                      sh.config.port = config.port;
                      sh.config.secret = config.secret;
                      return sh.connect().then(undefined, defer.reject);
                    }
                  }, function (error) {
                    defer.reject({error: 2, message: "couldn't get sockethub config: " + error});
                  });
                });
              });
            }
          }
        }
      }, 0);
      return defer.promise;
    }
  };
}] );

// sockethub factory
dogtalk.factory('sh', ['$rootScope', '$q',
function ($rootScope, $q) {
  var config = {
    host: '',
    port: '',
    secret: '',
    exists: function () {
      if ((config.host !== '') &&
          (config.port !== '') &&
          (config.secret !== '')) {
        return true;
      } else {
        return false;
      }
    }
  };

  function connect() {
    return sockethub.connect({
      host: 'ws://' + config.host + ':' + config.port + '/sockethub',
      confirmationTimeout: 6000,   // timeout in miliseconds to wait for confirm
      enablePings: true            // good for keepalive
    }).then(function () {  // connection to sockethub sucessful
      console.log('connected to sockethub');
      return sockethub.register({
        remoteStorage: {
          bearerToken: remoteStorage.getBearerToken(),
          scope: remoteStorage.claimedModules,
          storageInfo: remoteStorage.getStorageInfo()
        },
        secret: config.secret
      });
    }, function (err) {
      //console.log('received error on connect: '+err+' : ', o);
      throw { type: 'connect', original: err, error: 3 };
    }).then(function() {
      console.log('registered!');
    }, function(err) {
      if(typeof(err) !== 'object') {
        throw { type: 'register', original: err, error: 4 };
      } else {
        throw err;
      }
    });
  }

  return {
    config: config,
    connect: connect,
    isConnected: sockethub.isConnected
  };
}] );

dogtalk.run(function($rootScope, sh) {
    /*
        Receive emitted messages from elsewhere.
        http://jsfiddle.net/VxafF/
    */
    $rootScope.$on('showModalSockethubSettings', function(event, args) {
      backdrop_setting = true;
      if ((typeof args === 'object') && (typeof args.locked !== 'undefined')) {
        if (args.locked) {
          backdrop_setting = "static";
        }
      }
      console.log('backdrop: '+backdrop_setting);
      $("#modalSettingsSockethub").modal({
        show: true,
        keyboard: true,
        backdrop: backdrop_setting
      });
    });

    $rootScope.$on('closeModalSockethubSettings', function(event, args) {
      //console.log('closeModalSockethubSettings');
      $("#modalSettingsSockethub").modal('hide');
    });
});<commit_msg>updated the error handling some more<commit_after>var dogtalk = angular.module('dogtalk', []);

dogtalk.config(function ($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: "home.html",
    controller: "homeCtrl",
    resolve: {
      init: homeCtrl.homeInit
    }
  }).when('/settings', {
    templateUrl: "settings.html",
    controller: "settingsCtrl",
    resolve: {
      loadData: settingsCtrl.settingsInit
    }
  }).when('/log', {
    templateUrl: "log.html",
    controller: "logCtrl",
    resolve: {
      init: logCtrl.logInit
    }
  }).otherwise({
    redirectTo: "/"
  });
});

dogtalk.directive("error", function ($rootScope) {
  return {
    restrict: "E",
    template: '
'+
              '{{displayError.title}}' +
              '
{{displayError.message}}
' +
              '
',
    link: function (scope) {

      var errors = {
        'remotestorage-connect': {
          title : 'First things first',
          message: 'You must connect to your remoteStorage'
        },
        'sockethub-config': {
          title: 'Unable to connect to Sockethub',
          message: 'You must fill in your Sockethub connection details'
        },
        'sockethub-connect': {
          title: 'Sockethub connection',
          message: 'Unable to connect to Sockethub please check your configuration and try again'
        },
        'sockethub-register': {
          title: 'Registration problem',
          message: 'We were unable to register with your Sockethub instance'
        },
        'unknown': {
          title: 'An unknown error has occurred',
          message: ''
        }
      };

      $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
        console.log('directive routeChangeError: ', event, current, previous, rejection);

        scope.isError = false;
        scope.displayError = {title: '', message: ''};

        if ((typeof rejection !== 'object') ||
            (typeof rejection.error === 'undefined') ||
            (typeof errors[rejection.error] == 'undefined')) {
          scope.displayError = errors['unknown'];
          scope.displayError.message = String(rejection.message || rejection);
        } else {
          scope.displayError = errors[rejection.error];
          if (typeof rejection.message === 'string') {
            scope.displayError.message = scope.displayError.message + ': ' + rejection.message;
          }
        }
        scope.isError = true;

        if (rejection.error === 'sockethub-config') {
          console.log('no config found, launch modal');
          $rootScope.$broadcast('showModalSockethubSettings', {locked: true});
        }
      });

      $rootScope.$on("$routeChangeSuccess", function (event, current, previous) {
        if (sockethub.isConnected()) {
          scope.isError = false;
        } else {
          scope.isError = true;
          scope.displayError = errors['sockethub-connect'];
        }
      });
    }
  };
});

/**
 * Function: initializeApp
 *
 * when app is loaded, we need to verify remoteStorage and Sockethub are connected
 * and provide the proper control-flow to the user if not.
 *
 */
// initialization factory
dogtalk.factory('init', ['$rootScope', '$q', '$timeout', 'sh',
function ($rootScope, $q, $timeout, sh) {
  return {
    setState: function () {
      var defer = $q.defer();
      $timeout(function() {
        if (remoteStorage.getBearerToken() === null) {
          defer.reject({error: 'remotestorage-connect'});
        } else {
          if (sh.isConnected()) {
            console.log('already connected to sockethub');
            defer.resolve();
          } else {
            if (sh.config.exists()) {
              console.log('already have sockethub config, no need to fetch');
              sockethub.connect(defer);
            } else {
              remoteStorage.onWidget('ready', function() {
                $timeout(function() {
                  remoteStorage.sockethub.getConfig().then(function (config) {
                    console.log('initializeApp: got config: ', config);
                    if (!config) {
                      defer.reject({error: 'sockethub-config'});
                    } else {
                      console.log('setting config and attempting connection');
                      sh.config.host = config.host;
                      sh.config.port = config.port;
                      sh.config.secret = config.secret;
                      sh.connect().then(defer.resolve, defer.reject);
                    }
                  }, function (error) {
                    defer.reject({error: 'sockethub-config'});
                  });
                });
              });
            }
          }
        }
      }, 0);
      return defer.promise;
    }
  };
}] );

// sockethub factory
dogtalk.factory('sh', ['$rootScope', '$q',
function ($rootScope, $q) {
  var config = {
    host: '',
    port: '',
    secret: '',
    exists: function () {
      if ((config.host !== '') &&
          (config.port !== '') &&
          (config.secret !== '')) {
        return true;
      } else {
        return false;
      }
    }
  };

  function connect() {
    return sockethub.connect({
      host: 'ws://' + config.host + ':' + config.port + '/sockethub',
      confirmationTimeout: 6000,   // timeout in miliseconds to wait for confirm
      enablePings: true            // good for keepalive
    }).then(function () {  // connection to sockethub sucessful
      console.log('connected to sockethub');
      return sockethub.register({
        remoteStorage: {
          bearerToken: remoteStorage.getBearerToken(),
          scope: remoteStorage.claimedModules,
          storageInfo: remoteStorage.getStorageInfo()
        },
        secret: config.secret
      });
    }, function (err) { // sockethub connection failed
      console.log('received error on connect: ', err);
      throw { error: 'sockethub-connect', message: err};
    }).then(function() {
      console.log('registered!');
    }, function(err) {
      if(typeof(err) !== 'object') {
        throw {error: 'sockethub-register', message: err};
      } else {
        throw {error: 'sockethub-register'};
      }
    });
  }

  return {
    config: config,
    connect: connect,
    isConnected: sockethub.isConnected
  };
}] );

dogtalk.run(function($rootScope, sh) {
    /*
        Receive emitted messages from elsewhere.
        http://jsfiddle.net/VxafF/
    */
    $rootScope.$on('showModalSockethubSettings', function(event, args) {
      backdrop_setting = true;
      if ((typeof args === 'object') && (typeof args.locked !== 'undefined')) {
        if (args.locked) {
          backdrop_setting = "static";
        }
      }
      console.log('backdrop: '+backdrop_setting);
      $("#modalSettingsSockethub").modal({
        show: true,
        keyboard: true,
        backdrop: backdrop_setting
      });
    });

    $rootScope.$on('closeModalSockethubSettings', function(event, args) {
      //console.log('closeModalSockethubSettings');
      $("#modalSettingsSockethub").modal('hide');
    });
});<|endoftext|>


<commit_before>$(document).foundation();

function getTriad(color) {
  $.ajax({
    url: "http://www.google.com",
    cache: false,
    success: function(html) {
      alert(html);
    },
    error: function(err) {
      console.log(err);
      alert("faff err" + err);
    }
  });
}

/**
* API Server GET Request
* @description: Gets a response and waits for the server callback
*/
function forResponse(url, callback) {
  $.ajax({
    url: url,
    cache: false,
    success: callback,
    error: function(err) {
      console.log(err);
    }
  });
}
function endpointForResponse(url, callback) {
  forResponse("http://pizzazz.xyz/api/" + url, callback);
}

//getTriad();
function setColorIndex(stringHex, index) {
  $("#color-" + index + "-block").css('background-color', stringHex);
  $("#color-" + index + "-text").text(stringHex);
};

/**
* Helper functions
* @description: Set colors given the color hex
*/
function setColorOne(stringHex) {
  setColorIndex(stringHex, "one")
};

function setColorTwo(stringHex) {
  setColorIndex(stringHex, "two")
};

function setColorThree(stringHex) {
  setColorIndex(stringHex, "three")
};

function setColorScheme(arrayScheme) {
  setColorOne(arrayScheme[0]);
  setColorTwo(arrayScheme[1]);
  setColorThree(arrayScheme[2]);
}

var hexCombinations = [
  ["#f48b52", "#b1dfd5", "#f5f6fa"],
  ["#f4858e", "#bfe2ca", "#a6daef"],
  ["#676c7f", "#ca8799", "#e1d5bf"]
];
var hexIndex = 0;
var loopHandle;

/**
* Test Loop
* @description: Cycle through colors
*/
var funcLoop = function() {
  setColorScheme(hexCombinations[hexIndex++ % hexCombinations.length]);
  loopHandle = setTimeout(funcLoop, 3500);
}
funcLoop();

/**
* NoHex
* @description: Removes hashtag
*/
function noHex(string) {
  return string.substring(1, string.length);
}

/**
* Input value
* @description: Get color value from input textbox
*/
var inputValue = "#" + $("#colorHex").val();

var theColor = inputValue ?  inputValue : "#a6daef";
$(".theColor").html("Color selected: " + theColor);

// Update values on enter keydown
$("#colorHex").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		inputValue = "#" + $("#colorHex").val();
    console.log(inputValue);
    theColor = inputValue ?  inputValue : "#a6daef";
    $(".theColor").html("Color selected: " + theColor);

    // Stop loop
    clearTimeout(loopHandle);
    endpointForResponse("triad?color=" + noHex(theColor), function(json) {
      // Set every triad to the same value
      setColorIndex([theColor], "one");
      setColorIndex([json.result[1].toString()], "two");
      setColorIndex([json.result[2].toString()], "three");
    });

    setComplementary();
    setAnalogous();
    setTriad();
    setSplit();
    setSquare();
    setMonochromatic();
    setToRGB();
    setToHSV();
	}
});

/**
* Color Combinations
* @description: Ping server, and visualize
*/
function setComplementary() {
  $(".color-complementary-a").css('background-color', theColor);
  endpointForResponse("complementary?color=" + noHex(theColor), function(json) {
    $(".color-complementary-b").css('background-color', json.result.toString());
  });
}

function setAnalogous() {
  $(".color-analogous-a").css('background-color', theColor);
  endpointForResponse("analogous?color=" + noHex(theColor), function(json) {
    $(".color-analogous-b").css('background-color', json.result[1].toString());
    $(".color-analogous-c").css('background-color', json.result[2].toString());
    $(".color-analogous-d").css('background-color', json.result[3].toString());
    $(".color-analogous-e").css('background-color', json.result[4].toString());
    $(".color-analogous-f").css('background-color', json.result[5].toString());
  });
}

function setTriad() {
  $(".color-triad-a").css('background-color', theColor);
  endpointForResponse("triad?color=" + noHex(theColor), function(json) {
    $(".color-triad-b").css('background-color', json.result[1].toString());
    $(".color-triad-c").css('background-color', json.result[2].toString());
  });
}

function setSplit() {
  $(".color-split-a").css('background-color', theColor);
  endpointForResponse("split?color=" + noHex(theColor), function(json) {
    $(".color-split-b").css('background-color', json.result[1].toString());
    $(".color-split-c").css('background-color', json.result[2].toString());
  });
}

function setSquare() {
  $(".color-rectangle-a").css('background-color', theColor);
  endpointForResponse("rectangle?color=" + noHex(theColor), function(json) {
    $(".color-rectangle-b").css('background-color', json.result[1].toString());
    $(".color-rectangle-c").css('background-color', json.result[2].toString());
    $(".color-rectangle-d").css('background-color', json.result[3].toString());
  });
}

function setMonochromatic() {
  $(".color-monochromatic-a").css('background-color', theColor);
  endpointForResponse("monochromatic?color=" + noHex(theColor), function(json) {
    $(".color-monochromatic-b").css('background-color', json.result[1].toString());
    $(".color-monochromatic-c").css('background-color', json.result[2].toString());
    $(".color-monochromatic-d").css('background-color', json.result[3].toString());
    $(".color-monochromatic-e").css('background-color', json.result[4].toString());
    $(".color-monochromatic-f").css('background-color', json.result[5].toString());
  });
}

/**
* Color Conversion
* @description: Ping server, and visualize
*/
function setToRGB() {
  $(".color-torgb-a").css('background-color', theColor);
  endpointForResponse("torgb?color=" + noHex(theColor), function(json) {
    $(".color-torgb-info").html(JSON.stringify(json.result, null, 2));
  });
}

function setToHSV() {
  $(".color-tohsv-a").css('background-color', theColor);
  endpointForResponse("tohsv?color=" + noHex(theColor), function(json) {
    $(".color-tohsv-info").html(JSON.stringify(json.result, null, 2));
  });
}

/**
* Color Palettes
* @description: Ping server, and visualize
*/

// Update values on enter keydown
var imageURL = "http://pizzazz.xyz/cutepuppy.jpg";
loadPage("frameImage", imageURL);
$("#imageURL").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		imageURL = $("#imageURL").val();
    imageURL = imageURL ? imageURL : "http://pizzazz.xyz/cutepuppy.jpg";
    loadPage("frameImage", imageURL);
    setImage();
	}
});

function setImage() {
  $(".color-image-a").css('background-color', theColor);
  endpointForResponse("image?url=" + imageURL, function(json) {
    $(".color-image-a").css('background-color', json.dominantColor.toString());
  });
}

// Update values on enter keydown
var numRandom = 5;
$("#numRandom").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		numRandom = $("#numRandom").val();
    numRandom = numRandom ? numRandom : 5;
    setRandom();
	}
});

function setRandom() {
  $(".color-random-a").css('background-color', theColor);

  endpointForResponse("random?number=" + numRandom, function(json) {

    if(numRandom >= 5) {
      $(".color-random-a").css('background-color', json.result[0].toString());
      $(".color-random-b").css('background-color', json.result[1].toString());
      $(".color-random-c").css('background-color', json.result[2].toString());
      $(".color-random-d").css('background-color', json.result[3].toString());
      $(".color-random-e").css('background-color', json.result[4].toString());
    }

    if(numRandom == 4) {
      $(".color-random-a").css('background-color', json.result[0].toString());
      $(".color-random-b").css('background-color', json.result[1].toString());
      $(".color-random-c").css('background-color', "#FFFFFF");
      $(".color-random-d").css('background-color', json.result[2].toString());
      $(".color-random-e").css('background-color', json.result[3].toString());
    }

    if(numRandom == 3) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', json.result[0].toString());
      $(".color-random-c").css('background-color', json.result[1].toString());
      $(".color-random-d").css('background-color', json.result[2].toString());
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

    if(numRandom == 2) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', json.result[0].toString());
      $(".color-random-c").css('background-color', "#FFFFFF");
      $(".color-random-d").css('background-color', json.result[1].toString());
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

    if(numRandom == 1) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', "#FFFFFF");
      $(".color-random-c").css('background-color', json.result[0].toString());
      $(".color-random-d").css('background-color', "#FFFFFF");
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

  });
}

// Update values on enter keydown
var sentimentText = "I'm so happy happy happy shalalala!";
$("#sentimentText").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		sentimentText = $("#sentimentText").val();
    sentimentText = sentimentText ? sentimentText : "I'm so happy happy happy shalalala!";
    setSentiment();
	}
});

function setSentiment() {
  $(".color-sentiment-a").css('background-color', theColor);

  endpointForResponse("sentiment?text=" + sentimentText, function(json) {
    $(".color-sentiment-a").css('background-color', json.result.toString());
  });
}

// Update values on enter keydown
var webURL = "http://nebez.github.io/floppybird/";
loadPage("frameWeb", webURL);
$("#webURL").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		webURL = $("#webURL").val();
    webURL = webURL ? webURL : "http://nebez.github.io/floppybird/";
    loadPage("frameWeb", webURL);
    setWeb();
	}
});

function setWeb() {
  $(".color-web-a").css('background-color', theColor);
  endpointForResponse("web?url=" + webURL, function(json) {
    $(".color-web-a").css('background-color', json.result[0].toString());
    $(".color-web-b").css('background-color', json.result[1].toString());
    $(".color-web-c").css('background-color', json.result[2].toString());
    $(".color-web-d").css('background-color', json.result[3].toString());
    $(".color-web-e").css('background-color', json.result[4].toString());
    $(".color-web-f").css('background-color', json.result[5].toString());
    loadPage("frameWeb", webURL);
  });
}

/**
* loadPage
* @description: Loads given url to an object specified by an id
*/
function loadPage(id, url){
  document.getElementById(id).innerHTML='<object type="text/html" data=' + url + ' height="100%" width="100%"></object>';
}

/**
* Activate Functions
*/
setComplementary();
setAnalogous();
setTriad();
setSplit();
setSquare();
setMonochromatic();
setToRGB();
setToHSV();
setImage();
setRandom();
setSentiment();
setWeb();
<commit_msg>Catch 0 numRandom<commit_after>$(document).foundation();

function getTriad(color) {
  $.ajax({
    url: "http://www.google.com",
    cache: false,
    success: function(html) {
      alert(html);
    },
    error: function(err) {
      console.log(err);
      alert("faff err" + err);
    }
  });
}

/**
* API Server GET Request
* @description: Gets a response and waits for the server callback
*/
function forResponse(url, callback) {
  $.ajax({
    url: url,
    cache: false,
    success: callback,
    error: function(err) {
      console.log(err);
    }
  });
}
function endpointForResponse(url, callback) {
  forResponse("http://pizzazz.xyz/api/" + url, callback);
}

//getTriad();
function setColorIndex(stringHex, index) {
  $("#color-" + index + "-block").css('background-color', stringHex);
  $("#color-" + index + "-text").text(stringHex);
};

/**
* Helper functions
* @description: Set colors given the color hex
*/
function setColorOne(stringHex) {
  setColorIndex(stringHex, "one")
};

function setColorTwo(stringHex) {
  setColorIndex(stringHex, "two")
};

function setColorThree(stringHex) {
  setColorIndex(stringHex, "three")
};

function setColorScheme(arrayScheme) {
  setColorOne(arrayScheme[0]);
  setColorTwo(arrayScheme[1]);
  setColorThree(arrayScheme[2]);
}

var hexCombinations = [
  ["#f48b52", "#b1dfd5", "#f5f6fa"],
  ["#f4858e", "#bfe2ca", "#a6daef"],
  ["#676c7f", "#ca8799", "#e1d5bf"]
];
var hexIndex = 0;
var loopHandle;

/**
* Test Loop
* @description: Cycle through colors
*/
var funcLoop = function() {
  setColorScheme(hexCombinations[hexIndex++ % hexCombinations.length]);
  loopHandle = setTimeout(funcLoop, 3500);
}
funcLoop();

/**
* NoHex
* @description: Removes hashtag
*/
function noHex(string) {
  return string.substring(1, string.length);
}

/**
* Input value
* @description: Get color value from input textbox
*/
var inputValue = "#" + $("#colorHex").val();

var theColor = inputValue ?  inputValue : "#a6daef";
$(".theColor").html("Color selected: " + theColor);

// Update values on enter keydown
$("#colorHex").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		inputValue = "#" + $("#colorHex").val();
    console.log(inputValue);
    theColor = inputValue ?  inputValue : "#a6daef";
    $(".theColor").html("Color selected: " + theColor);

    // Stop loop
    clearTimeout(loopHandle);
    endpointForResponse("triad?color=" + noHex(theColor), function(json) {
      // Set every triad to the same value
      setColorIndex([theColor], "one");
      setColorIndex([json.result[1].toString()], "two");
      setColorIndex([json.result[2].toString()], "three");
    });

    setComplementary();
    setAnalogous();
    setTriad();
    setSplit();
    setSquare();
    setMonochromatic();
    setToRGB();
    setToHSV();
	}
});

/**
* Color Combinations
* @description: Ping server, and visualize
*/
function setComplementary() {
  $(".color-complementary-a").css('background-color', theColor);
  endpointForResponse("complementary?color=" + noHex(theColor), function(json) {
    $(".color-complementary-b").css('background-color', json.result.toString());
  });
}

function setAnalogous() {
  $(".color-analogous-a").css('background-color', theColor);
  endpointForResponse("analogous?color=" + noHex(theColor), function(json) {
    $(".color-analogous-b").css('background-color', json.result[1].toString());
    $(".color-analogous-c").css('background-color', json.result[2].toString());
    $(".color-analogous-d").css('background-color', json.result[3].toString());
    $(".color-analogous-e").css('background-color', json.result[4].toString());
    $(".color-analogous-f").css('background-color', json.result[5].toString());
  });
}

function setTriad() {
  $(".color-triad-a").css('background-color', theColor);
  endpointForResponse("triad?color=" + noHex(theColor), function(json) {
    $(".color-triad-b").css('background-color', json.result[1].toString());
    $(".color-triad-c").css('background-color', json.result[2].toString());
  });
}

function setSplit() {
  $(".color-split-a").css('background-color', theColor);
  endpointForResponse("split?color=" + noHex(theColor), function(json) {
    $(".color-split-b").css('background-color', json.result[1].toString());
    $(".color-split-c").css('background-color', json.result[2].toString());
  });
}

function setSquare() {
  $(".color-rectangle-a").css('background-color', theColor);
  endpointForResponse("rectangle?color=" + noHex(theColor), function(json) {
    $(".color-rectangle-b").css('background-color', json.result[1].toString());
    $(".color-rectangle-c").css('background-color', json.result[2].toString());
    $(".color-rectangle-d").css('background-color', json.result[3].toString());
  });
}

function setMonochromatic() {
  $(".color-monochromatic-a").css('background-color', theColor);
  endpointForResponse("monochromatic?color=" + noHex(theColor), function(json) {
    $(".color-monochromatic-b").css('background-color', json.result[1].toString());
    $(".color-monochromatic-c").css('background-color', json.result[2].toString());
    $(".color-monochromatic-d").css('background-color', json.result[3].toString());
    $(".color-monochromatic-e").css('background-color', json.result[4].toString());
    $(".color-monochromatic-f").css('background-color', json.result[5].toString());
  });
}

/**
* Color Conversion
* @description: Ping server, and visualize
*/
function setToRGB() {
  $(".color-torgb-a").css('background-color', theColor);
  endpointForResponse("torgb?color=" + noHex(theColor), function(json) {
    $(".color-torgb-info").html(JSON.stringify(json.result, null, 2));
  });
}

function setToHSV() {
  $(".color-tohsv-a").css('background-color', theColor);
  endpointForResponse("tohsv?color=" + noHex(theColor), function(json) {
    $(".color-tohsv-info").html(JSON.stringify(json.result, null, 2));
  });
}

/**
* Color Palettes
* @description: Ping server, and visualize
*/

// Update values on enter keydown
var imageURL = "http://pizzazz.xyz/cutepuppy.jpg";
loadPage("frameImage", imageURL);
$("#imageURL").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		imageURL = $("#imageURL").val();
    imageURL = imageURL ? imageURL : "http://pizzazz.xyz/cutepuppy.jpg";
    loadPage("frameImage", imageURL);
    setImage();
	}
});

function setImage() {
  $(".color-image-a").css('background-color', theColor);
  endpointForResponse("image?url=" + imageURL, function(json) {
    $(".color-image-a").css('background-color', json.dominantColor.toString());
  });
}

// Update values on enter keydown
var numRandom = 5;
$("#numRandom").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		numRandom = $("#numRandom").val();
    numRandom = numRandom ? numRandom : 5;
    setRandom();
	}
});

function setRandom() {
  $(".color-random-a").css('background-color', theColor);

  endpointForResponse("random?number=" + numRandom, function(json) {

    if(numRandom >= 5) {
      $(".color-random-a").css('background-color', json.result[0].toString());
      $(".color-random-b").css('background-color', json.result[1].toString());
      $(".color-random-c").css('background-color', json.result[2].toString());
      $(".color-random-d").css('background-color', json.result[3].toString());
      $(".color-random-e").css('background-color', json.result[4].toString());
    }

    if(numRandom == 4) {
      $(".color-random-a").css('background-color', json.result[0].toString());
      $(".color-random-b").css('background-color', json.result[1].toString());
      $(".color-random-c").css('background-color', "#FFFFFF");
      $(".color-random-d").css('background-color', json.result[2].toString());
      $(".color-random-e").css('background-color', json.result[3].toString());
    }

    if(numRandom == 3) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', json.result[0].toString());
      $(".color-random-c").css('background-color', json.result[1].toString());
      $(".color-random-d").css('background-color', json.result[2].toString());
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

    if(numRandom == 2) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', json.result[0].toString());
      $(".color-random-c").css('background-color', "#FFFFFF");
      $(".color-random-d").css('background-color', json.result[1].toString());
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

    if(numRandom == 1) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', "#FFFFFF");
      $(".color-random-c").css('background-color', json.result[0].toString());
      $(".color-random-d").css('background-color', "#FFFFFF");
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

    if(numRandom == 0) {
      $(".color-random-a").css('background-color', "#FFFFFF");
      $(".color-random-b").css('background-color', "#FFFFFF");
      $(".color-random-c").css('background-color', "#FFFFFF");
      $(".color-random-d").css('background-color', "#FFFFFF");
      $(".color-random-e").css('background-color', "#FFFFFF");
    }

  });
}

// Update values on enter keydown
var sentimentText = "I'm so happy happy happy shalalala!";
$("#sentimentText").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		sentimentText = $("#sentimentText").val();
    sentimentText = sentimentText ? sentimentText : "I'm so happy happy happy shalalala!";
    setSentiment();
	}
});

function setSentiment() {
  $(".color-sentiment-a").css('background-color', theColor);

  endpointForResponse("sentiment?text=" + sentimentText, function(json) {
    $(".color-sentiment-a").css('background-color', json.result.toString());
  });
}

// Update values on enter keydown
var webURL = "http://nebez.github.io/floppybird/";
loadPage("frameWeb", webURL);
$("#webURL").keydown(function(event) {
	if (event.keyCode==13) {
    // Set the color from input
		webURL = $("#webURL").val();
    webURL = webURL ? webURL : "http://nebez.github.io/floppybird/";
    loadPage("frameWeb", webURL);
    setWeb();
	}
});

function setWeb() {
  $(".color-web-a").css('background-color', theColor);
  endpointForResponse("web?url=" + webURL, function(json) {
    $(".color-web-a").css('background-color', json.result[0].toString());
    $(".color-web-b").css('background-color', json.result[1].toString());
    $(".color-web-c").css('background-color', json.result[2].toString());
    $(".color-web-d").css('background-color', json.result[3].toString());
    $(".color-web-e").css('background-color', json.result[4].toString());
    $(".color-web-f").css('background-color', json.result[5].toString());
    loadPage("frameWeb", webURL);
  });
}

/**
* loadPage
* @description: Loads given url to an object specified by an id
*/
function loadPage(id, url){
  document.getElementById(id).innerHTML='<object type="text/html" data=' + url + ' height="100%" width="100%"></object>';
}

/**
* Activate Functions
*/
setComplementary();
setAnalogous();
setTriad();
setSplit();
setSquare();
setMonochromatic();
setToRGB();
setToHSV();
setImage();
setRandom();
setSentiment();
setWeb();
<|endoftext|>