<commit_before>'use strict';

var sampleRate;
var l1 = 'File type = \"ooTextFile\"';
var l2 = 'Object class = \"TextGrid\"';

var localID = 0;

/**
 * parse a textgrid string to the specified json format
 *
 * @param string TextGrid file string to be parsed
 * @returns a label java script object
 */
function toJSO(string, myFile, myName) {

	// remove all empty lines from string
	string = string.replace(/([ \t]*\r?\n)+/g, '\n');
	// remove all blanks
	string = string.replace(/[ \t]+/g, '');
	var lines = string.split('\n');

	var tT, tN, eT, lab;
	var inHeader = true;

	//meta info for labelJSO
	var labelJSO = {
		name: myName,
		annotates: myFile,
		sampleRate: sampleRate,
		levels: [],
		links: []
	};

	if (lines[0].replace(/\s+/g, '') === l1.replace(/\s+/g, '') && lines[1].replace(/\s+/g, '') === l2.replace(/\s+/g, '')) {
		for (var i = 2; i < lines.length; i++) {
			var cL = lines[i];
			if (cL === 'item[]:') {
				inHeader = false;
				continue;
			}
			if (inHeader) {
				continue;
			}

			if (cL.indexOf('item[') === 0) {
				// get level name
				tN = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				// get level type
				if (lines[i + 1].split(/=/)[1] === '\"IntervalTier\"') {
					tT = 'SEGMENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else if (lines[i + 1].split(/=/)[1] === '\"TextTier\"') {
					tT = 'EVENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else {
					tT = 'ITEM';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						items: []
					});
				}

			}
			if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'SEGMENT' && (cL.indexOf('intervals') === 0) && (cL.indexOf('intervals:') !== 0)) {
				// parse seg levels event
				var eSt = Math.floor(lines[i + 1].split(/=/)[1] * sampleRate) + 1;
				var eEt = Math.floor(lines[i + 2].split(/=/)[1] * sampleRate);
				lab = lines[i + 3].split(/=/)[1].replace(/"/g, '');

				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					sampleStart: eSt,
					sampleDur: eEt - eSt + 1,
					labels: labs
				});

				++localID;

			} else if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'EVENT' && cL.indexOf('points') === 0 && cL.indexOf('points:') !== 0) {
				// parse point level event
				eT = lines[i + 1].split(/=/)[1] * sampleRate;
				lab = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					samplePoint: Math.round(eT),
					labels: labs
				});

				++localID;
			}

		}
		// console.log(JSON.stringify(labelJSO, undefined, 2));
		testForGapsInLabelJSO(labelJSO);
		return labelJSO;

	} else {
		// alert('bad header in TextGrid file!!! The header has to be: ', l1, '\n', l2);
		return ({
			'status': {
				'type': 'ERROR',
				'message': 'bad header in TextGrid file!!! The header has to be: ' + l1 + '\n' + l2
			}
		});
	}

};

/**
 * converts the internal levels format returned from levelHandler.getLevels
 * to a string containing a TextGrid file
 */
function toTextGrid() {

	var l1 = 'File type = \"ooTextFile\"';
	var l2 = 'Object class = \"TextGrid\"';
	var tG = '';
	var nl = '\n';
	var t = '\t';

	// writing header infos
	tG = tG + l1 + nl + l2 + nl + nl;
	tG = tG + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
	tG = tG + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
	tG = tG + 'levels? <exists>' + nl;
	tG = tG + 'size = ' + $('#HandleLevelsCtrl').scope().getLevelLength() + nl;
	tG = tG + 'item []:' + nl;
	var levelNr = 0;
	$('#HandleLevelsCtrl level').each(function () {
		var curLevel = $('#HandleLevelsCtrl').scope().getLevel($(this).attr('id'));
		//write level items
		levelNr = levelNr + 1;
		tG = tG + t + 'item [' + levelNr + ']:' + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'class = "IntervalLevel"' + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'class = "TextLevel"' + nl;
		}
		tG = tG + t + t + 'name = "' + curLevel.LevelName + '"' + nl;
		tG = tG + t + t + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
		tG = tG + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'intervals: size = ' + curLevel.items.length + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'points: size = ' + curLevel.items.length + nl;
		}
		for (var j = 0; j < curLevel.items.length; j++) {
			var evtNr = j + 1;
			if (curLevel.type === 'SEGMENT') {
				tG = tG + t + t + t + 'intervals [' + evtNr + ']:' + nl;
				if (curLevel.items[j].sampleStart !== 0) {
					tG = tG + t + t + t + t + 'xmin = ' + ((curLevel.items[j].sampleStart) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmin = ' + 0 + nl;
				}
				if (j < curLevel.items.length - 1) {
					tG = tG + t + t + t + t + 'xmax = ' + ((curLevel.items[j].sampleStart + curLevel.items[j].sampleDur + 1) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
				}

				tG = tG + t + t + t + t + 'text = "' + curLevel.items[j].label + '"' + nl;
			} else if (curLevel.type === 'EVENT') {
				tG = tG + t + t + t + 'points[' + evtNr + ']:' + nl;
				tG = tG + t + t + t + t + 'time = ' + curLevel.items[j].sampleStart / Soundhandlerservice.wavJSO.SampleRate + nl;
				tG = tG + t + t + t + t + 'mark = "' + curLevel.items[j].label + '"' + nl;
			}
		}
	});
	return (tG);
};

/**
 *
 */
function findTimeOfMinSample() {
	return 0.000000; // maybe needed at some point...
};

/**
 *
 */
function findTimeOfMaxSample() {
	return viewState.curViewPort.bufferLength / Soundhandlerservice.wavJSO.SampleRate;
};

/**
 * test to see if all the segments in seg levels
 * are "snapped" -> sampleStart+dur+1 = sampleStart of next Segment
 */
function testForGapsInLabelJSO(labelJSO) {
	var counter = 0;
	for (var i = 0; i < labelJSO.levels.length; i++) {
		if (labelJSO.levels[i].type === 'SEGMENT') {
			for (var j = 0; j < labelJSO.levels[i].items.length - 1; j++) {
				if (labelJSO.levels[i].items[j].sampleStart + labelJSO.levels[i].items[j].sampleDur + 1 !== labelJSO.levels[i].items[j + 1].sampleStart) {
					counter = counter + 1;
				}
			}
		}
	}
	// console.log('TextGridParser had: ', counter, 'alignment issues found in parsed TextGrid');
};

/**
 * add event listener to webworker
 */
self.addEventListener('message', function (e) {
	var data = e.data;
	switch (data.cmd) {
	case 'parseTG':
		sampleRate = data.sampleRate;
		var retVal = toJSO(data.textGrid, data.annotates, data.name)
		if (retVal.type === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		// self.postMessage('yo mumma smells');
		break;
	default:
		self.postMessage({
			'status': {
				'type': 'ERROR',
				'message': 'Unknown command sent to textGridParserWorker'
			}
		});

		break;
	}
})<commit_msg>checking correct field...<commit_after>'use strict';

var sampleRate;
var l1 = 'File type = \"ooTextFile\"';
var l2 = 'Object class = \"TextGrid\"';

var localID = 0;

/**
 * parse a textgrid string to the specified json format
 *
 * @param string TextGrid file string to be parsed
 * @returns a label java script object
 */
function toJSO(string, myFile, myName) {

	// remove all empty lines from string
	string = string.replace(/([ \t]*\r?\n)+/g, '\n');
	// remove all blanks
	string = string.replace(/[ \t]+/g, '');
	var lines = string.split('\n');

	var tT, tN, eT, lab;
	var inHeader = true;

	//meta info for labelJSO
	var labelJSO = {
		name: myName,
		annotates: myFile,
		sampleRate: sampleRate,
		levels: [],
		links: []
	};

	if (lines[0].replace(/\s+/g, '') === l1.replace(/\s+/g, '') && lines[1].replace(/\s+/g, '') === l2.replace(/\s+/g, '')) {
		for (var i = 2; i < lines.length; i++) {
			var cL = lines[i];
			if (cL === 'item[]:') {
				inHeader = false;
				continue;
			}
			if (inHeader) {
				continue;
			}

			if (cL.indexOf('item[') === 0) {
				// get level name
				tN = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				// get level type
				if (lines[i + 1].split(/=/)[1] === '\"IntervalTier\"') {
					tT = 'SEGMENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else if (lines[i + 1].split(/=/)[1] === '\"TextTier\"') {
					tT = 'EVENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else {
					tT = 'ITEM';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						items: []
					});
				}

			}
			if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'SEGMENT' && (cL.indexOf('intervals') === 0) && (cL.indexOf('intervals:') !== 0)) {
				// parse seg levels event
				var eSt = Math.floor(lines[i + 1].split(/=/)[1] * sampleRate) + 1;
				var eEt = Math.floor(lines[i + 2].split(/=/)[1] * sampleRate);
				lab = lines[i + 3].split(/=/)[1].replace(/"/g, '');

				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					sampleStart: eSt,
					sampleDur: eEt - eSt + 1,
					labels: labs
				});

				++localID;

			} else if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'EVENT' && cL.indexOf('points') === 0 && cL.indexOf('points:') !== 0) {
				// parse point level event
				eT = lines[i + 1].split(/=/)[1] * sampleRate;
				lab = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					samplePoint: Math.round(eT),
					labels: labs
				});

				++localID;
			}

		}
		// console.log(JSON.stringify(labelJSO, undefined, 2));
		testForGapsInLabelJSO(labelJSO);
		return labelJSO;

	} else {
		// alert('bad header in TextGrid file!!! The header has to be: ', l1, '\n', l2);
		return ({
			'status': {
				'type': 'ERROR',
				'message': 'bad header in TextGrid file!!! The header has to be: ' + l1 + '\n' + l2
			}
		});
	}

};

/**
 * converts the internal levels format returned from levelHandler.getLevels
 * to a string containing a TextGrid file
 */
function toTextGrid() {

	var l1 = 'File type = \"ooTextFile\"';
	var l2 = 'Object class = \"TextGrid\"';
	var tG = '';
	var nl = '\n';
	var t = '\t';

	// writing header infos
	tG = tG + l1 + nl + l2 + nl + nl;
	tG = tG + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
	tG = tG + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
	tG = tG + 'levels? <exists>' + nl;
	tG = tG + 'size = ' + $('#HandleLevelsCtrl').scope().getLevelLength() + nl;
	tG = tG + 'item []:' + nl;
	var levelNr = 0;
	$('#HandleLevelsCtrl level').each(function () {
		var curLevel = $('#HandleLevelsCtrl').scope().getLevel($(this).attr('id'));
		//write level items
		levelNr = levelNr + 1;
		tG = tG + t + 'item [' + levelNr + ']:' + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'class = "IntervalLevel"' + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'class = "TextLevel"' + nl;
		}
		tG = tG + t + t + 'name = "' + curLevel.LevelName + '"' + nl;
		tG = tG + t + t + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
		tG = tG + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'intervals: size = ' + curLevel.items.length + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'points: size = ' + curLevel.items.length + nl;
		}
		for (var j = 0; j < curLevel.items.length; j++) {
			var evtNr = j + 1;
			if (curLevel.type === 'SEGMENT') {
				tG = tG + t + t + t + 'intervals [' + evtNr + ']:' + nl;
				if (curLevel.items[j].sampleStart !== 0) {
					tG = tG + t + t + t + t + 'xmin = ' + ((curLevel.items[j].sampleStart) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmin = ' + 0 + nl;
				}
				if (j < curLevel.items.length - 1) {
					tG = tG + t + t + t + t + 'xmax = ' + ((curLevel.items[j].sampleStart + curLevel.items[j].sampleDur + 1) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
				}

				tG = tG + t + t + t + t + 'text = "' + curLevel.items[j].label + '"' + nl;
			} else if (curLevel.type === 'EVENT') {
				tG = tG + t + t + t + 'points[' + evtNr + ']:' + nl;
				tG = tG + t + t + t + t + 'time = ' + curLevel.items[j].sampleStart / Soundhandlerservice.wavJSO.SampleRate + nl;
				tG = tG + t + t + t + t + 'mark = "' + curLevel.items[j].label + '"' + nl;
			}
		}
	});
	return (tG);
};

/**
 *
 */
function findTimeOfMinSample() {
	return 0.000000; // maybe needed at some point...
};

/**
 *
 */
function findTimeOfMaxSample() {
	return viewState.curViewPort.bufferLength / Soundhandlerservice.wavJSO.SampleRate;
};

/**
 * test to see if all the segments in seg levels
 * are "snapped" -> sampleStart+dur+1 = sampleStart of next Segment
 */
function testForGapsInLabelJSO(labelJSO) {
	var counter = 0;
	for (var i = 0; i < labelJSO.levels.length; i++) {
		if (labelJSO.levels[i].type === 'SEGMENT') {
			for (var j = 0; j < labelJSO.levels[i].items.length - 1; j++) {
				if (labelJSO.levels[i].items[j].sampleStart + labelJSO.levels[i].items[j].sampleDur + 1 !== labelJSO.levels[i].items[j + 1].sampleStart) {
					counter = counter + 1;
				}
			}
		}
	}
	// console.log('TextGridParser had: ', counter, 'alignment issues found in parsed TextGrid');
};

/**
 * add event listener to webworker
 */
self.addEventListener('message', function (e) {
	var data = e.data;
	switch (data.cmd) {
	case 'parseTG':
		sampleRate = data.sampleRate;
		var retVal = toJSO(data.textGrid, data.annotates, data.name)
		if (retVal.status.type === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		// self.postMessage('yo mumma smells');
		break;
	default:
		self.postMessage({
			'status': {
				'type': 'ERROR',
				'message': 'Unknown command sent to textGridParserWorker'
			}
		});

		break;
	}
})<|endoftext|>


<commit_before>$(function () {
  var light_style = [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];

  var map;
  var infowindow;
  var loadDataLayer = function(data, z_index, click_content_fn) {
    var markers = [];
    var clickable = false;
    if (click_content_fn !== null) {
      clickable = true;
    }

    var showInfoWindow = function() {
      var content = click_content_fn(this.data);
      infowindow.close();
      infowindow.setContent(content);
      infowindow.open(map, this);
    };

    for (var i in data) {
      var rec = data[i];
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(rec.latitude, rec.longitude),
        zIndex: z_index,
        clickable: clickable
      });

      marker.data = rec;

      if (clickable) {
        marker.addListener('click', showInfoWindow);
      }

      markers.push(marker);
    }

    var len = markers.length;
    var setMap = function(m, filterFn) {
      for (var i = 0; i < len; i++) {
        if (filterFn) {
          if (filterFn(markers[i].data)) {
            markers[i].setMap(m);
          } else {
            markers[i].setMap(null);
          }
        } else {
          markers[i].setMap(m);
        }
      }
    };

    return {
      show: function() {
        setMap(map);
      },
      hide: function() {
        setMap(null);
      },
      filter: function(fn) {
        setMap(map, fn);
      }
    };
  };

  var initMap = function() {
    var mapCanvas = document.getElementById('map');
    var mapOptions = {
      center: new google.maps.LatLng(35.16899709632771, -89.85338676720858),
      zoom: 6,
      panControl: false,
      streetViewControl: false,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.RIGHT_TOP,
        mapTypeIds: [
          google.maps.MapTypeId.ROADMAP,
          google.maps.MapTypeId.HYBRID,
          'style_light'
        ]
      }
    };
    map = new google.maps.Map(mapCanvas, mapOptions);
    var style = new google.maps.StyledMapType(light_style, {name:"Light"});
    map.mapTypes.set('style_light', style);
    map.setMapTypeId('style_light');

    var input = /** @type {!HTMLInputElement} */(document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({map: map});
    infowindow = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
    autocomplete.addListener('place_changed', function() {
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        geocoder.geocode({
          address: input.value
        }, function(result) {
          if (result.length > 0) {
            search_result(result[0]);
          } else {
            alert("No results found.");
          }
        });
      } else {
        search_result(place);
      }
    });

    var search_result = function(result) {
      if (result.geometry.viewport) {
        map.fitBounds(result.geometry.viewport);
      } else {
        map.setCenter(result.geometry.location);
        map.setZoom(17);
      }
      marker.setPosition(result.geometry.location);
      marker.setVisible(true);
    };

    var memtech = loadDataLayer(locations, 999, function(data) {
      return "" + data.name + "
" +
             "" + data.origin + "
";
             "" + data.slack_handle || "??" + " on MTF Slack
";
    });
    memtech.show();

    /* uncomment if you want to show heatmap
    var heatmap_data = jQuery.map(locations, function(record) {
      return new google.maps.LatLng(record.latitude, record.longitude);
    });
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatmap_data
    });
    heatmap.setMap(map);
    */

  };
  google.maps.event.addDomListener(window, 'load', initMap);
});
<commit_msg>Whoops i need to read more js<commit_after>$(function () {
  var light_style = [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];

  var map;
  var infowindow;
  var loadDataLayer = function(data, z_index, click_content_fn) {
    var markers = [];
    var clickable = false;
    if (click_content_fn !== null) {
      clickable = true;
    }

    var showInfoWindow = function() {
      var content = click_content_fn(this.data);
      infowindow.close();
      infowindow.setContent(content);
      infowindow.open(map, this);
    };

    for (var i in data) {
      var rec = data[i];
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(rec.latitude, rec.longitude),
        zIndex: z_index,
        clickable: clickable
      });

      marker.data = rec;

      if (clickable) {
        marker.addListener('click', showInfoWindow);
      }

      markers.push(marker);
    }

    var len = markers.length;
    var setMap = function(m, filterFn) {
      for (var i = 0; i < len; i++) {
        if (filterFn) {
          if (filterFn(markers[i].data)) {
            markers[i].setMap(m);
          } else {
            markers[i].setMap(null);
          }
        } else {
          markers[i].setMap(m);
        }
      }
    };

    return {
      show: function() {
        setMap(map);
      },
      hide: function() {
        setMap(null);
      },
      filter: function(fn) {
        setMap(map, fn);
      }
    };
  };

  var initMap = function() {
    var mapCanvas = document.getElementById('map');
    var mapOptions = {
      center: new google.maps.LatLng(35.16899709632771, -89.85338676720858),
      zoom: 6,
      panControl: false,
      streetViewControl: false,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.RIGHT_TOP,
        mapTypeIds: [
          google.maps.MapTypeId.ROADMAP,
          google.maps.MapTypeId.HYBRID,
          'style_light'
        ]
      }
    };
    map = new google.maps.Map(mapCanvas, mapOptions);
    var style = new google.maps.StyledMapType(light_style, {name:"Light"});
    map.mapTypes.set('style_light', style);
    map.setMapTypeId('style_light');

    var input = /** @type {!HTMLInputElement} */(document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({map: map});
    infowindow = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
    autocomplete.addListener('place_changed', function() {
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        geocoder.geocode({
          address: input.value
        }, function(result) {
          if (result.length > 0) {
            search_result(result[0]);
          } else {
            alert("No results found.");
          }
        });
      } else {
        search_result(place);
      }
    });

    var search_result = function(result) {
      if (result.geometry.viewport) {
        map.fitBounds(result.geometry.viewport);
      } else {
        map.setCenter(result.geometry.location);
        map.setZoom(17);
      }
      marker.setPosition(result.geometry.location);
      marker.setVisible(true);
    };

    var memtech = loadDataLayer(locations, 999, function(data) {
      return "" + data.name + "
" +
             "" + data.origin + "
" +
             "" + data.slack_handle || "??" + " on MTF Slack
";
    });
    memtech.show();

    /* uncomment if you want to show heatmap
    var heatmap_data = jQuery.map(locations, function(record) {
      return new google.maps.LatLng(record.latitude, record.longitude);
    });
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatmap_data
    });
    heatmap.setMap(map);
    */

  };
  google.maps.event.addDomListener(window, 'load', initMap);
});
<|endoftext|>


<commit_before>'use strict';

var sampleRate;
var l1 = 'File type = \"ooTextFile\"';
var l2 = 'Object class = \"TextGrid\"';

var localID = 0;

/**
 * parse a textgrid string to the specified json format
 *
 * @param string TextGrid file string to be parsed
 * @returns a label java script object
 */
function toJSO(string, myFile, myName) {

	// remove all empty lines from string
	string = string.replace(/([ \t]*\r?\n)+/g, '\n');
	// remove all blanks
	string = string.replace(/[ \t]+/g, '');
	var lines = string.split('\n');

	var tT, tN, eT, lab;
	var inHeader = true;

	//meta info for labelJSO
	var labelJSO = {
		name: myName,
		annotates: myFile,
		sampleRate: sampleRate,
		levels: [],
		links: []
	};

	if (lines[0].replace(/\s+/g, '') === l1.replace(/\s+/g, '') && lines[1].replace(/\s+/g, '') === l2.replace(/\s+/g, '')) {
		for (var i = 2; i < lines.length; i++) {
			var cL = lines[i];
			if (cL === 'item[]:') {
				inHeader = false;
				continue;
			}
			if (inHeader) {
				continue;
			}

			if (cL.indexOf('item[') === 0) {
				// get level name
				tN = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				// get level type
				if (lines[i + 1].split(/=/)[1] === '\"IntervalTier\"') {
					tT = 'SEGMENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else if (lines[i + 1].split(/=/)[1] === '\"TextTier\"') {
					tT = 'EVENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else {
					tT = 'ITEM';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						items: []
					});
				}

			}
			if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'SEGMENT' && (cL.indexOf('intervals') === 0) && (cL.indexOf('intervals:') !== 0)) {
				// parse seg levels event
				var eSt = Math.floor(lines[i + 1].split(/=/)[1] * sampleRate) + 1;
				var eEt = Math.floor(lines[i + 2].split(/=/)[1] * sampleRate);
				lab = lines[i + 3].split(/=/)[1].replace(/"/g, '');

				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					sampleStart: eSt,
					sampleDur: eEt - eSt + 1,
					labels: labs
				});

				++localID;

			} else if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'EVENT' && cL.indexOf('points') === 0 && cL.indexOf('points:') !== 0) {
				// parse point level event
				eT = lines[i + 1].split(/=/)[1] * sampleRate;
				lab = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					samplePoint: Math.round(eT),
					labels: labs
				});

				++localID;
			}

		}
		// console.log(JSON.stringify(labelJSO, undefined, 2));
		testForGapsInLabelJSO(labelJSO);
		return labelJSO;

	} else {
		alert('bad header in TextGrid file!!! The header has to be: ', l1, '\n', l2);
		return ({
			'status': {
				'type': 'ERROR',
				'message': 'bad header in TextGrid file!!! The header has to be: ' + l1 + '\n' + l2
			}
		});
	}

};

/**
 * converts the internal levels format returned from levelHandler.getLevels
 * to a string containing a TextGrid file
 */
function toTextGrid() {

	var l1 = 'File type = \"ooTextFile\"';
	var l2 = 'Object class = \"TextGrid\"';
	var tG = '';
	var nl = '\n';
	var t = '\t';

	// writing header infos
	tG = tG + l1 + nl + l2 + nl + nl;
	tG = tG + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
	tG = tG + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
	tG = tG + 'levels? <exists>' + nl;
	tG = tG + 'size = ' + $('#HandleLevelsCtrl').scope().getLevelLength() + nl;
	tG = tG + 'item []:' + nl;
	var levelNr = 0;
	$('#HandleLevelsCtrl level').each(function () {
		var curLevel = $('#HandleLevelsCtrl').scope().getLevel($(this).attr('id'));
		//write level items
		levelNr = levelNr + 1;
		tG = tG + t + 'item [' + levelNr + ']:' + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'class = "IntervalLevel"' + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'class = "TextLevel"' + nl;
		}
		tG = tG + t + t + 'name = "' + curLevel.LevelName + '"' + nl;
		tG = tG + t + t + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
		tG = tG + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'intervals: size = ' + curLevel.items.length + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'points: size = ' + curLevel.items.length + nl;
		}
		for (var j = 0; j < curLevel.items.length; j++) {
			var evtNr = j + 1;
			if (curLevel.type === 'SEGMENT') {
				tG = tG + t + t + t + 'intervals [' + evtNr + ']:' + nl;
				if (curLevel.items[j].sampleStart !== 0) {
					tG = tG + t + t + t + t + 'xmin = ' + ((curLevel.items[j].sampleStart) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmin = ' + 0 + nl;
				}
				if (j < curLevel.items.length - 1) {
					tG = tG + t + t + t + t + 'xmax = ' + ((curLevel.items[j].sampleStart + curLevel.items[j].sampleDur + 1) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
				}

				tG = tG + t + t + t + t + 'text = "' + curLevel.items[j].label + '"' + nl;
			} else if (curLevel.type === 'EVENT') {
				tG = tG + t + t + t + 'points[' + evtNr + ']:' + nl;
				tG = tG + t + t + t + t + 'time = ' + curLevel.items[j].sampleStart / Soundhandlerservice.wavJSO.SampleRate + nl;
				tG = tG + t + t + t + t + 'mark = "' + curLevel.items[j].label + '"' + nl;
			}
		}
	});
	return (tG);
};

/**
 *
 */
function findTimeOfMinSample() {
	return 0.000000; // maybe needed at some point...
};

/**
 *
 */
function findTimeOfMaxSample() {
	return viewState.curViewPort.bufferLength / Soundhandlerservice.wavJSO.SampleRate;
};

/**
 * test to see if all the segments in seg levels
 * are "snapped" -> sampleStart+dur+1 = sampleStart of next Segment
 */
function testForGapsInLabelJSO(labelJSO) {
	var counter = 0;
	for (var i = 0; i < labelJSO.levels.length; i++) {
		if (labelJSO.levels[i].type === 'SEGMENT') {
			for (var j = 0; j < labelJSO.levels[i].items.length - 1; j++) {
				if (labelJSO.levels[i].items[j].sampleStart + labelJSO.levels[i].items[j].sampleDur + 1 !== labelJSO.levels[i].items[j + 1].sampleStart) {
					counter = counter + 1;
				}
			}
		}
	}
	// console.log('TextGridParser had: ', counter, 'alignment issues found in parsed TextGrid');
};

/**
 * add event listener to webworker
 */
self.addEventListener('message', function (e) {
	var data = e.data;
	switch (data.cmd) {
	case 'parseTG':
		sampleRate = data.sampleRate;
		var retVal = toJSO(data.textGrid, data.annotates, data.name)
		if (retVal.type === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		// self.postMessage('yo mumma smells');
		break;
	default:
		self.postMessage({
			'status': {
				'type': 'ERROR',
				'message': 'Unknown command sent to textGridParserWorker'
			}
		});

		break;
	}
})<commit_msg>no more alert()<commit_after>'use strict';

var sampleRate;
var l1 = 'File type = \"ooTextFile\"';
var l2 = 'Object class = \"TextGrid\"';

var localID = 0;

/**
 * parse a textgrid string to the specified json format
 *
 * @param string TextGrid file string to be parsed
 * @returns a label java script object
 */
function toJSO(string, myFile, myName) {

	// remove all empty lines from string
	string = string.replace(/([ \t]*\r?\n)+/g, '\n');
	// remove all blanks
	string = string.replace(/[ \t]+/g, '');
	var lines = string.split('\n');

	var tT, tN, eT, lab;
	var inHeader = true;

	//meta info for labelJSO
	var labelJSO = {
		name: myName,
		annotates: myFile,
		sampleRate: sampleRate,
		levels: [],
		links: []
	};

	if (lines[0].replace(/\s+/g, '') === l1.replace(/\s+/g, '') && lines[1].replace(/\s+/g, '') === l2.replace(/\s+/g, '')) {
		for (var i = 2; i < lines.length; i++) {
			var cL = lines[i];
			if (cL === 'item[]:') {
				inHeader = false;
				continue;
			}
			if (inHeader) {
				continue;
			}

			if (cL.indexOf('item[') === 0) {
				// get level name
				tN = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				// get level type
				if (lines[i + 1].split(/=/)[1] === '\"IntervalTier\"') {
					tT = 'SEGMENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else if (lines[i + 1].split(/=/)[1] === '\"TextTier\"') {
					tT = 'EVENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						sampleRate: sampleRate,
						items: []
					});
				} else {
					tT = 'ITEM';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						items: []
					});
				}

			}
			if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'SEGMENT' && (cL.indexOf('intervals') === 0) && (cL.indexOf('intervals:') !== 0)) {
				// parse seg levels event
				var eSt = Math.floor(lines[i + 1].split(/=/)[1] * sampleRate) + 1;
				var eEt = Math.floor(lines[i + 2].split(/=/)[1] * sampleRate);
				lab = lines[i + 3].split(/=/)[1].replace(/"/g, '');

				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					sampleStart: eSt,
					sampleDur: eEt - eSt + 1,
					labels: labs
				});

				++localID;

			} else if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'EVENT' && cL.indexOf('points') === 0 && cL.indexOf('points:') !== 0) {
				// parse point level event
				eT = lines[i + 1].split(/=/)[1] * sampleRate;
				lab = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					samplePoint: Math.round(eT),
					labels: labs
				});

				++localID;
			}

		}
		// console.log(JSON.stringify(labelJSO, undefined, 2));
		testForGapsInLabelJSO(labelJSO);
		return labelJSO;

	} else {
		// alert('bad header in TextGrid file!!! The header has to be: ', l1, '\n', l2);
		return ({
			'status': {
				'type': 'ERROR',
				'message': 'bad header in TextGrid file!!! The header has to be: ' + l1 + '\n' + l2
			}
		});
	}

};

/**
 * converts the internal levels format returned from levelHandler.getLevels
 * to a string containing a TextGrid file
 */
function toTextGrid() {

	var l1 = 'File type = \"ooTextFile\"';
	var l2 = 'Object class = \"TextGrid\"';
	var tG = '';
	var nl = '\n';
	var t = '\t';

	// writing header infos
	tG = tG + l1 + nl + l2 + nl + nl;
	tG = tG + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
	tG = tG + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
	tG = tG + 'levels? <exists>' + nl;
	tG = tG + 'size = ' + $('#HandleLevelsCtrl').scope().getLevelLength() + nl;
	tG = tG + 'item []:' + nl;
	var levelNr = 0;
	$('#HandleLevelsCtrl level').each(function () {
		var curLevel = $('#HandleLevelsCtrl').scope().getLevel($(this).attr('id'));
		//write level items
		levelNr = levelNr + 1;
		tG = tG + t + 'item [' + levelNr + ']:' + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'class = "IntervalLevel"' + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'class = "TextLevel"' + nl;
		}
		tG = tG + t + t + 'name = "' + curLevel.LevelName + '"' + nl;
		tG = tG + t + t + 'xmin = ' + sServObj.findTimeOfMinSample() + nl;
		tG = tG + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'intervals: size = ' + curLevel.items.length + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'points: size = ' + curLevel.items.length + nl;
		}
		for (var j = 0; j < curLevel.items.length; j++) {
			var evtNr = j + 1;
			if (curLevel.type === 'SEGMENT') {
				tG = tG + t + t + t + 'intervals [' + evtNr + ']:' + nl;
				if (curLevel.items[j].sampleStart !== 0) {
					tG = tG + t + t + t + t + 'xmin = ' + ((curLevel.items[j].sampleStart) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmin = ' + 0 + nl;
				}
				if (j < curLevel.items.length - 1) {
					tG = tG + t + t + t + t + 'xmax = ' + ((curLevel.items[j].sampleStart + curLevel.items[j].sampleDur + 1) / Soundhandlerservice.wavJSO.SampleRate + ((1 / Soundhandlerservice.wavJSO.SampleRate) / 2)) + nl;
				} else {
					tG = tG + t + t + t + t + 'xmax = ' + sServObj.findTimeOfMaxSample() + nl;
				}

				tG = tG + t + t + t + t + 'text = "' + curLevel.items[j].label + '"' + nl;
			} else if (curLevel.type === 'EVENT') {
				tG = tG + t + t + t + 'points[' + evtNr + ']:' + nl;
				tG = tG + t + t + t + t + 'time = ' + curLevel.items[j].sampleStart / Soundhandlerservice.wavJSO.SampleRate + nl;
				tG = tG + t + t + t + t + 'mark = "' + curLevel.items[j].label + '"' + nl;
			}
		}
	});
	return (tG);
};

/**
 *
 */
function findTimeOfMinSample() {
	return 0.000000; // maybe needed at some point...
};

/**
 *
 */
function findTimeOfMaxSample() {
	return viewState.curViewPort.bufferLength / Soundhandlerservice.wavJSO.SampleRate;
};

/**
 * test to see if all the segments in seg levels
 * are "snapped" -> sampleStart+dur+1 = sampleStart of next Segment
 */
function testForGapsInLabelJSO(labelJSO) {
	var counter = 0;
	for (var i = 0; i < labelJSO.levels.length; i++) {
		if (labelJSO.levels[i].type === 'SEGMENT') {
			for (var j = 0; j < labelJSO.levels[i].items.length - 1; j++) {
				if (labelJSO.levels[i].items[j].sampleStart + labelJSO.levels[i].items[j].sampleDur + 1 !== labelJSO.levels[i].items[j + 1].sampleStart) {
					counter = counter + 1;
				}
			}
		}
	}
	// console.log('TextGridParser had: ', counter, 'alignment issues found in parsed TextGrid');
};

/**
 * add event listener to webworker
 */
self.addEventListener('message', function (e) {
	var data = e.data;
	switch (data.cmd) {
	case 'parseTG':
		sampleRate = data.sampleRate;
		var retVal = toJSO(data.textGrid, data.annotates, data.name)
		if (retVal.type === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		// self.postMessage('yo mumma smells');
		break;
	default:
		self.postMessage({
			'status': {
				'type': 'ERROR',
				'message': 'Unknown command sent to textGridParserWorker'
			}
		});

		break;
	}
})<|endoftext|>


<commit_before>var UTILS = (function () {

	return {
		/**
		 * Check if a given value is a plain Object
		 *
		 * @param  {*}       o Any value to be checked
		 * @return {Boolean}   true if it's an Object
		 */
		isObject: function (o) {
			var toString = Object.prototype.toString;
			return (toString.call(o) === toString.call({}));
		},

		/**
		 * AJAX helper function (similar to jQuery, but far from it!)
		 *
		 * @param {string} url     URL for the ajax request
		 * @param {Object} options AJAX settings
		 */
		ajax: function (url, options) {

			var xhr = new XMLHttpRequest(),
				method = 'GET',
				options = UTILS.isObject(options) ? options : {};

			// Check if "method" was supplied
			if (options.method) {
				method = options.method;
			}

			// Setup the request
			xhr.open(method.toUpperCase(), url);

			xhr.onreadystatechange = function () {
				var status;

		 		// If request finished
				if (xhr.readyState === 4) {

					status = xhr.status;

					// If response is OK or fetched from cache
					if ((status >= 200 && status < 300) || status === 304) {
						var res = xhr.responseText,
							contentType = xhr.getResponseHeader('Content-Type');

						// If server sent a content type header, handle formats
						if (contentType) {

							// Handle JSON format
							if (contentType === 'text/json' ||
								contentType === 'application/json') {

								// JSON throws an exception on invalid JSON
								try {
									res = JSON.parse(res);
								} catch (err) {
									// Trigger "fail" callback if set
									if (options.fail) {
										options.fail.call(xhr, err);
										return;
									}
								}

							// Handle XML format
							} else if (contentType === 'text/xml' ||
								contentType === 'application/xml') {
								// responseXML returns a document object
								res = xhr.responseXML;

								// if XML was invalid, trigger fail callback
								if (res === null && options.fail) {
									options.fail.call(xhr, 'Bad XML file');
									return;
								}
							}
						}

						// Trigger done callback with the proper response
						if (options.done) {
							options.done.call(xhr, res);
						}
					}

				}
			};

			// Fire the request
			xhr.send(null);
		}
	};
}());

var pageUpdate= function(data) {

}
function init () {
	 UTILS.ajax("data/config.json",{done: pageUpdate});
}

window.onLoad = init();<commit_msg>commit 2.2<commit_after>/**
 * JS Library v2
 */

var UTILS = (function () {

	return {
		/**
		 * Check if a given value is a plain Object
		 *
		 * @param  {*}       o Any value to be checked
		 * @return {Boolean}   true if it's an Object
		 */
		isObject: function (o) {
			var toString = Object.prototype.toString;
			return (toString.call(o) === toString.call({}));
		},

		/**
		 * AJAX helper function (similar to jQuery, but far from it!)
		 *
		 * @param {string} url     URL for the ajax request
		 * @param {Object} options AJAX settings
		 */
		ajax: function (url, options) {

			var xhr = new XMLHttpRequest(),
				method = 'GET',
				options = UTILS.isObject(options) ? options : {};

			// Check if "method" was supplied
			if (options.method) {
				method = options.method;
			}

			// Setup the request
			xhr.open(method.toUpperCase(), url);

			xhr.onreadystatechange = function () {
				var status;

		 		// If request finished
				if (xhr.readyState === 4) {

					status = xhr.status;

					// If response is OK or fetched from cache
					if ((status >= 200 && status < 300) || status === 304) {
						var res = xhr.responseText,
							contentType = xhr.getResponseHeader('Content-Type');

						// If server sent a content type header, handle formats
						if (contentType) {

							// Handle JSON format
							if (contentType === 'text/json' ||
								contentType === 'application/json') {

								// JSON throws an exception on invalid JSON
								try {
									res = JSON.parse(res);
								} catch (err) {
									// Trigger "fail" callback if set
									if (options.fail) {
										options.fail.call(xhr, err);
										return;
									}
								}

							// Handle XML format
							} else if (contentType === 'text/xml' ||
								contentType === 'application/xml') {
								// responseXML returns a document object
								res = xhr.responseXML;

								// if XML was invalid, trigger fail callback
								if (res === null && options.fail) {
									options.fail.call(xhr, 'Bad XML file');
									return;
								}
							}
						}

						// Trigger done callback with the proper response
						if (options.done) {
							options.done.call(xhr, res);
						}
					}

				}
			};

			// Fire the request
			xhr.send(null);
		}
	};
}());

var pageUpdate= function(data) {
	if (data.notifications !== undefined) {
        document.getElementByClass("notifications").innerHTML = "<p>" + data.notifications + "</p>";
    }
};
var updateTabs= function(data) {

};

function init () {
	 UTILS.ajax("data/config.json",{done: pageUpdate});
};
window.onLoad = init();
<|endoftext|>


<commit_before>$(document).ready(function () {
    updateDate();
    setInterval(updateDate, 15000);

    initWeather();
    updateWeather('47.6101,-122.2015', darkSkyApiKey);
    setInterval(function() {
        updateWeather('47.6101,-122.2015', darkSkyApiKey);
    }, 600000);

    loadGreeting();
    setInterval(loadGreeting, 1800000);

    showBusesForStops();
    setInterval(showBusesForStops, 60000);
});

function updateDate() {
    let date = $('#date');
    date.text(Intl.DateTimeFormat('en', { weekday: 'long', month: 'long', day: 'numeric' }).format(new Date()));
    let time = $('#time');
    time.text(Intl.DateTimeFormat('en', { hour: `numeric`, minute: `numeric`, hour12: true }).format(new Date()));
}

let general_greetings = [
    "You look amazing today.",
    "It's a beautiful day!",
    "You're cool!",
    "Today's a good day.",
    "You're the fairest of them all!"
];

function loadGreeting() {
    var current_greetings = general_greetings.slice();
    switch((new Date()).getDay()) {
        case 3:
            current_greetings.push("Happy Hump Day!");
            break;
        case 4:
            current_greetings.push("It's Friday Eve!");
            break;
        case 5:
            current_greetings.push("It's Friday!");
            break;
    }

    if ((new Date()).getDay() == 0) {
        $("#greeting").text("Happy Birthday, Charlotte! :)");
    } else {
        var index = Math.floor(Math.random() * current_greetings.length);
        $("#greeting").text(current_greetings[index]);
    }
}
<commit_msg>Removed birthday greeting<commit_after>$(document).ready(function () {
    updateDate();
    setInterval(updateDate, 15000);

    initWeather();
    updateWeather('47.6101,-122.2015', darkSkyApiKey);
    setInterval(function() {
        updateWeather('47.6101,-122.2015', darkSkyApiKey);
    }, 600000);

    loadGreeting();
    setInterval(loadGreeting, 1800000);

    showBusesForStops();
    setInterval(showBusesForStops, 60000);
});

function updateDate() {
    let date = $('#date');
    date.text(Intl.DateTimeFormat('en', { weekday: 'long', month: 'long', day: 'numeric' }).format(new Date()));
    let time = $('#time');
    time.text(Intl.DateTimeFormat('en', { hour: `numeric`, minute: `numeric`, hour12: true }).format(new Date()));
}

let general_greetings = [
    "You look amazing today.",
    "It's a beautiful day!",
    "You're cool!",
    "Today's a good day.",
    "You're the fairest of them all!"
];

function loadGreeting() {
    var current_greetings = general_greetings.slice();
    switch((new Date()).getDay()) {
        case 3:
            current_greetings.push("Happy Hump Day!");
            break;
        case 4:
            current_greetings.push("It's Friday Eve!");
            break;
        case 5:
            current_greetings.push("It's Friday!");
            break;
    }

    var index = Math.floor(Math.random() * current_greetings.length);
    $("#greeting").text(current_greetings[index]);
}
<|endoftext|>


<commit_before>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
window.fbAsyncInit = function() {
      Parse.FacebookUtils.init({ // this line replaces FB.init({
            appId      : '481383445376506',
            //appId      : '971388552927772', // Facebook App ID
            status     : true,  // check Facebook Login status
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.5' // point to the latest Facebook Graph API version
      });

  // Run code after the Facebook SDK is loaded
  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
            getUserName()
            document.getElementById("lgn-btn").style.display="none";
            document.getElementById("lgot-btn").style.display="block";
    }
    else if (response.status === 'not_authorized') {
            getUserName()
            document.getElementById("lgn-btn").style.display="none";
            document.getElementById("lgot-btn").style.display="block";
    }
});
};

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn("email", {
                  success: function(user) {
                        if (!user.existed()) {
                              //alert("User signed up and logged in through Facebook!");
                              getUserName()
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        } else {
                              //alert("User logged in through Facebook!");
                              getUserName()
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            },{scope:"email"});
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}

function getUserName() {
	if(Parse.User.current())
	{
	FB.api('/me?fields=id,first_name,last_name,email,gender,picture', function(response) {
		document.getElementById('usrname').innerHTML = '';
		//document.getElementById('usrname').innerHTML = Parse.User.current().id + response.id + "A";
		var user = Parse.User.current();
		var firstName = user.get('firstName');
		if(typeof firstName === 'undefined')
	    	{
			var usr       = Parse.Object.extend("User");
			var query     = new Parse.Query(usr);
			var uid       = Parse.User.current().id;
			var firstname = response.first_name;
			var lastname  = response.last_name;
			var gender    = response.gender;
			var email     = response.email;
			var fbid      = response.id;
			var pic       = "http://graph.facebook.com/" + response.id + "/picture";
			query.equalTo("objectId", uid);
			query.first({
				success: function(Usrobj){
				//	alert (uid+" "+firstname+" "+lastname+" "+gender+" "+email+" "+fbid+" "+pic);
					Usrobj.set("fbId", fbid);
					Usrobj.set("firstName", firstname);
					Usrobj.set("lastName", lastname);
					if(gender)
					{
						Usrobj.set("gender", gender);
					}
					if(pic)
					{
						Usrobj.set("userImg", pic);
					}
					if(email)
					{
						Usrobj.set("email", email);
					}
					Usrobj.save({
						success: function(){
							alert("Welcome To LOCAHOLIC!!!")
							//alert("success saved");
						},error: function(error){
							//alert("saving failed error " + error.message);
						}
					});
				},
				error: function(error){
					alert("query first error " +error.message);
				}

			});
		}
	});
	}
}
function lgOut(){
      //alert(Parse.User.current().id);
      Parse.User.logOut();
      FB.logout();
      window.location.href = "http://www.locaholic.co/";
}

(function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<commit_msg>Update main.js<commit_after>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
window.fbAsyncInit = function() {
      Parse.FacebookUtils.init({ // this line replaces FB.init({
            //appId      : '481383445376506',
            appId      : '971388552927772', // Facebook App ID
            status     : true,  // check Facebook Login status
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.5' // point to the latest Facebook Graph API version
      });

  // Run code after the Facebook SDK is loaded
  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
            getUserName()
            document.getElementById("lgn-btn").style.display="none";
            document.getElementById("lgot-btn").style.display="block";
    }
    else if (response.status === 'not_authorized') {
            getUserName()
            document.getElementById("lgn-btn").style.display="none";
            document.getElementById("lgot-btn").style.display="block";
    }
});
};

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn("email", {
                  success: function(user) {
                        if (!user.existed()) {
                              //alert("User signed up and logged in through Facebook!");
                              getUserName()
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        } else {
                              //alert("User logged in through Facebook!");
                              getUserName()
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            },{scope:"email"});
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}

function getUserName() {
	if(Parse.User.current())
	{
	FB.api('/me?fields=id,first_name,last_name,email,gender,picture', function(response) {
		document.getElementById('usrname').innerHTML = '';
		//document.getElementById('usrname').innerHTML = Parse.User.current().id + response.id + "A";
		var user = Parse.User.current();
		var firstName = user.get('firstName');
		if(typeof firstName === 'undefined')
	    	{
			var usr       = Parse.Object.extend("User");
			var query     = new Parse.Query(usr);
			var uid       = Parse.User.current().id;
			var firstname = response.first_name;
			var lastname  = response.last_name;
			var gender    = response.gender;
			var email     = response.email;
			var fbid      = response.id;
			var pic       = "http://graph.facebook.com/" + response.id + "/picture";
			query.equalTo("objectId", uid);
			query.first({
				success: function(Usrobj){
				//	alert (uid+" "+firstname+" "+lastname+" "+gender+" "+email+" "+fbid+" "+pic);
					Usrobj.set("fbId", fbid);
					Usrobj.set("firstName", firstname);
					Usrobj.set("lastName", lastname);
					if(gender)
					{
						Usrobj.set("gender", gender);
					}
					if(pic)
					{
						Usrobj.set("userImg", pic);
					}
					if(email)
					{
						Usrobj.set("email", email);
					}
					Usrobj.save({
						success: function(){
							alert("Welcome To LOCAHOLIC!!!")
							//alert("success saved");
						},error: function(error){
							//alert("saving failed error " + error.message);
						}
					});
				},
				error: function(error){
					alert("query first error " +error.message);
				}

			});
		}
	});
	}
}
function lgOut(){
      //alert(Parse.User.current().id);
      Parse.User.logOut();
      FB.logout();
      window.location.href = "http://www.locaholic.co/";
}

(function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<|endoftext|>


<commit_before>$(document).ready(function(){

    //Vars
    var listItem = window.location.hash;
    var logo = document.getElementById('logo');
    var projectsTitle = document.getElementById('projectsTitle');

    var projectListArray = [];

    var newProjectList;

    //AddEventListeners
    listenEvent(logo, 'click', scrollToTop);
    listenEvent(projectsTitle, 'click', scrollToTop);

    //Initialize Functions
    parseJSON();
    initCopyright();
    initGitActivity();

    //////////////////
    ////PARSE JSON
    /////////////////
    function parseJSON()
    {
        // Assign handlers immediately after making the request,
        // and remember the jqxhr object for this request

        var jqxhr = $.getJSON( "js/site.json", function(data)
        {

            $.each(data, function(key, val) {
                projectListArray = val;
            });

            buildList();
            checkForHash();

            console.log( "success" );
        })
        .done(function() { 'done' })
        .fail(function( jqxhr, textStatus, error )
        {
            var err = textStatus + ', ' + error;
            console.log( "Request Failed: " + err);
        })
        .always(function() { console.log( "complete" ); });

        // perform other work here ...

        // Set another completion function for the request above
        jqxhr.complete(function() { console.log( "second complete" ); });

        console.log("Parse JSON");
    }

    //////////////////
    ////CHECK FOR HASH
    //////////////////
    function checkForHash()
    {
        if(listItem)
        {
            var projectHash;

            for (i =0; i < projectListArray.length; i++)
            {
                projectHash = "#" + projectListArray[i].hash;

                //Check if hashtag is valid
                if(listItem === projectHash)
                {
                    console.log("Hash Found: " + listItem);
                    scrollToElement(listItem);
                }
                else { console.log("Hash invalid!"); }
            }
        }
        else
        {
            //takes care of Chrome scroll position feature when
            //user refreshes the page by hitting enter in the url field
            //scrollTo(0, 0);
            console.log("No Hash Found!");
        }
    }

    //////////////////
    ////BUILD LIST
    ////If js is enabled we want to build a dynamic list via JSON data: js/site.json.
    /////////////////
    function buildList()
    {
        var listSection = document.getElementById('listSection');

        var projectList = document.createElement('ul');
        projectList.id = 'projectList';
        listSection.appendChild(projectList);

        newProjectList = projectList;

        for(i = 0; i < projectListArray.length; i++)
        {
            buildListItem(i, projectListArray[i]);
        }

        console.log("Build List: " + projectListArray.length);
    }

    //////////////////
    ////BUILD LIST ITEM
    /////////////////
    function buildListItem(id, data)
    {
        var listItem = document.createElement('li');
        listItem.id = data.hash;
        newProjectList.appendChild(listItem);

        var title = document.createElement('h3');
        title.innerHTML = data.title;

        var image = document.createElement('img');
        image.src = data.thumb;

        var para = document.createElement('p');
        para.innerHTML = data.desc;

        var link = document.createElement('a');
        link.href = data.url;
        link.innerHTML = "GO";

        listItem.appendChild(title);
        listItem.appendChild(image);
        listItem.appendChild(para);
        listItem.appendChild(link);
    }

    //////////////////
    ////INIT COPYRIGHT
    /////////////////
    function initCopyright()
    {
       var d = new Date();
       var y = d.getFullYear();

       var currentYear = document.getElementById("copyright");
       var copyString = "Copyright © " + y;
       currentYear.innerHTML = copyString;
    }

    //////////////////
    ////INIT GIT ACTIVITY
    /////////////////
    function initGitActivity()
    {
        $('#gitActivity').FeedEk({
            FeedUrl : 'https://github.com/spektraldevelopment.atom?=' + Math.random(),
            MaxCount : 1,
            ShowDesc : false,
            ShowPubDate:false,
            DescCharacterLimit:100
        });
    }

    //////////////////
    ////SCROLL TO TOP
    /////////////////
    function scrollToTop(e)
    {
        $('html:not(:animated), body:not(:animated)').animate( { scrollTop : "0px" }, 800, "easeOutExpo");
        e.preventDefault();
        return false;
        console.log('Scroll To Top');
    }

    //////////////////
    ////SCROLL TO ELEMENT
    /////////////////
    function scrollToElement( target )
    {
        console.log('SCROLL TO ELEMENT: ' + target);

        var topoffset = 138;
        var speed = 800;

        var destination = $( target ).offset().top - topoffset;

        console.log("Destination: " + destination);

        jQuery( 'html:not(:animated), body:not(:animated)' ).animate( { scrollTop: destination}, speed, "easeOutExpo", function() {
            window.location.hash = target;
        });
        return false;
    }

    //////////////////
    ////LISTEN EVENT
    /////////////////
    function listenEvent(eventTarget, eventType, eventHandler)
    {
        if(eventTarget.addEventListener)
        {
            eventTarget.addEventListener(eventType, eventHandler, false)
        }
        else if(eventTarget.attachEvent)
        {
            eventType = "on" + eventType;
            eventTarget.attachEvent(eventType, eventHandler)
        }
        else
        {
            eventTarget["on" + eventType] = eventHandler;
        }
    }

    //Works just need to create itemArray to check all items
//    $('#item3').waypoint(function() {
//        console.log('You are looking at Item3');
//    }, { offset: 138 });

    console.log('Init Spektral Projects');
});

<commit_msg>Testing scrollToElement() on live site.<commit_after>$(document).ready(function(){

    //Vars
    var listItem = window.location.hash;
    var logo = document.getElementById('logo');
    var projectsTitle = document.getElementById('projectsTitle');

    var projectListArray = [];

    var newProjectList;

    //AddEventListeners
    listenEvent(logo, 'click', scrollToTop);
    listenEvent(projectsTitle, 'click', scrollToTop);

    //Initialize Functions
    parseJSON();
    initCopyright();
    initGitActivity();

    //////////////////
    ////PARSE JSON
    /////////////////
    function parseJSON()
    {
        // Assign handlers immediately after making the request,
        // and remember the jqxhr object for this request

        var jqxhr = $.getJSON( "js/site.json", function(data)
        {

            $.each(data, function(key, val) {
                projectListArray = val;
            });

            buildList();
            checkForHash();

            console.log( "success" );
        })
        .done(function() { 'done' })
        .fail(function( jqxhr, textStatus, error )
        {
            var err = textStatus + ', ' + error;
            console.log( "Request Failed: " + err);
        })
        .always(function() { console.log( "complete" ); });

        // perform other work here ...

        // Set another completion function for the request above
        jqxhr.complete(function() { console.log( "second complete" ); });

        console.log("Parse JSON");
    }

    //////////////////
    ////CHECK FOR HASH
    //////////////////
    function checkForHash()
    {
        if(listItem)
        {
            var projectHash;

            for (i =0; i < projectListArray.length; i++)
            {
                projectHash = "#" + projectListArray[i].hash;

                //Check if hashtag is valid
                if(listItem === projectHash)
                {
                    console.log("Hash Found: " + listItem);
                    scrollToElement(listItem);
                }
                else { console.log("Hash invalid!"); }
            }
        }
        else
        {
            //takes care of Chrome scroll position feature when
            //user refreshes the page by hitting enter in the url field
            //scrollTo(0, 0);
            console.log("No Hash Found!");
        }
    }

    //////////////////
    ////BUILD LIST
    ////If js is enabled we want to build a dynamic list via JSON data: js/site.json.
    /////////////////
    function buildList()
    {
        var listSection = document.getElementById('listSection');

        var projectList = document.createElement('ul');
        projectList.id = 'projectList';
        listSection.appendChild(projectList);

        newProjectList = projectList;

        for(i = 0; i < projectListArray.length; i++)
        {
            buildListItem(i, projectListArray[i]);
        }

        console.log("Build List: " + projectListArray.length);
    }

    //////////////////
    ////BUILD LIST ITEM
    /////////////////
    function buildListItem(id, data)
    {
        var listItem = document.createElement('li');
        listItem.id = data.hash;
        newProjectList.appendChild(listItem);

        var title = document.createElement('h3');
        title.innerHTML = data.title;

        var image = document.createElement('img');
        image.src = data.thumb;

        var para = document.createElement('p');
        para.innerHTML = data.desc;

        var link = document.createElement('a');
        link.href = data.url;
        link.innerHTML = "GO";

        listItem.appendChild(title);
        listItem.appendChild(image);
        listItem.appendChild(para);
        listItem.appendChild(link);
    }

    //////////////////
    ////INIT COPYRIGHT
    /////////////////
    function initCopyright()
    {
       var d = new Date();
       var y = d.getFullYear();

       var currentYear = document.getElementById("copyright");
       var copyString = "Copyright © " + y;
       currentYear.innerHTML = copyString;
    }

    //////////////////
    ////INIT GIT ACTIVITY
    /////////////////
    function initGitActivity()
    {
        $('#gitActivity').FeedEk({
            FeedUrl : 'https://github.com/spektraldevelopment.atom?=' + Math.random(),
            MaxCount : 1,
            ShowDesc : false,
            ShowPubDate:false,
            DescCharacterLimit:100
        });
    }

    //////////////////
    ////SCROLL TO TOP
    /////////////////
    function scrollToTop(e)
    {
        $('html:not(:animated), body:not(:animated)').animate( { scrollTop : "0px" }, 800, "easeOutExpo");
        e.preventDefault();
        return false;
        console.log('Scroll To Top');
    }

    //////////////////
    ////SCROLL TO ELEMENT
    /////////////////
    function scrollToElement( target )
    {
        console.log('SCROLL TO ELEMENT: ' + target);

        var topoffset = 138;
        var speed = 800;

        var destination = $( target ).offset().top - topoffset;

        console.log("Destination: " + destination);

        jQuery( 'html:not(:animated), body:not(:animated)' ).animate( { scrollTop: destination}, speed, "easeOutExpo", function() {
            window.location.hash = target;
        });
        target.preventDefault();
        return false;
    }

    //////////////////
    ////LISTEN EVENT
    /////////////////
    function listenEvent(eventTarget, eventType, eventHandler)
    {
        if(eventTarget.addEventListener)
        {
            eventTarget.addEventListener(eventType, eventHandler, false)
        }
        else if(eventTarget.attachEvent)
        {
            eventType = "on" + eventType;
            eventTarget.attachEvent(eventType, eventHandler)
        }
        else
        {
            eventTarget["on" + eventType] = eventHandler;
        }
    }

    //Works just need to create itemArray to check all items
//    $('#item3').waypoint(function() {
//        console.log('You are looking at Item3');
//    }, { offset: 138 });

    console.log('Init Spektral Projects');
});

<|endoftext|>


<commit_before>$(document).ready(function() {

    // Declare global variables
    var $machineModelDesc = $('.machine-model-description'), $machineImage = $('#machine-image'), $nextMachineImage = $('#machine-image').next('#machine-title'), $btnAdd = $('#btnAdd'), $btnDel = $('#btnDel'),
    // S-4 Machine attributes
    $s4Machine = $('label[for="s4"]'), s4MachineName = $s4Machine.find('.machineName').text(), s4MachineType = $s4Machine.find('.machineType').text(), s4MachinePrice = $s4Machine.find('.amount').text()
    // S-5Machine attributes
    $s5Machine = $('label[for="s5"]'), s5MachineName = $s5Machine.find('.machineName').text(), s5MachineType = $s5Machine.find('.machineType').text(), s5MachinePrice = $s5Machine.find('.amount').text()
    // S-6 Machine attributes
    $s6Machine = $('label[for="s6"]'), s6MachineName = $s6Machine.find('.machineName').text(), s6MachineType = $s6Machine.find('.machineType').text(), s6MachinePrice = $s6Machine.find('.amount').text()
    // S-7 Machine attributes
    s7Machine = $('label[for="s7"]'), s7MachineName = s7Machine.find('.machineName').text(), s7MachineType = s7Machine.find('.machineType').text(), s7MachinePrice = s7Machine.find('.amount').text();

    //  $('.field-name-machine-model input').each(function(index) {
    //      var machineID = $(this).attr('id');
    //  });

    // Create instances of the machine object and assign
    // properties
    //  machineS4 = {
    //      machineName : $('input '),
    //      machineType : "Weigh/Fill System",
    //      machinePrice : 6150
    //  };

    // Hide fallback content and delete button
    $('.large-discharge-funnel,.field-name-dimensions li,#btnDel,#step-2,#step-3,#step-4,#step-5,#hidden-accessories-page,.spout-shape-images > *').hide();
    // Remove fallback form elements
    $('.default-spout,.default-discharge-funnel,#btnQuote').remove();
    // .bottom class puts a negative z-index on the hidden
    // accessories page so that it loads underneath the rest of
    // the content. This removes that class on load.
    $('.bottom').removeClass('bottom');
    // Hide all but the first machine model description
    $machineModelDesc.not('.machine-model-description:first').hide();
    // Remove .hidden class from JS ready content
    $('.small-discharge-funnel,.large-discharge-funnel,#btnAdd,#btnDel,#btnFront,#btnSide,.cloneSpout,.step-submit,#sidebar,#btnPrint,#btnEmail,#btnClose,#btnContinue,.order-summary,#hidden-accessories-page,#machine-title,#order-summary').removeClass('hidden');
    // Check the default discharge funnel field
    $('#small-standard-discharge-funnel').prop('checked', true).addClass('active');

    // Add a waypoint to the sidebar
    var $mi_container = $('#sidebar');
    // Remove the no-sidebar class for fallback
    $('#main-content').removeClass('no-sidebar');
    // Set the .sticky class when waypoint is reached
    $mi_container.waypoint(function(direction) {
        $('#machine-image-container').toggleClass('sticky', direction === 'down');
    });

    function radioSelect() {
        var $radioInputFields = $('input[name=machine-model],input[name=weight-hopper],input[name=discharge-funnel],input.spout-type');

        $radioInputFields.click(function(e) {
            var $fieldID = $(this), inputVal = $fieldID.closest('ul.field-type-radio').find('.active').val(), objectVal = $fieldID.val();

            if (inputVal === objectVal) {
                e.preventDefault();
                //add this to prevent default click behaviour
            } else {
                var fieldValue = $fieldID.val(), $spoutContainer = $fieldID.closest('fieldset'), $grandTotalContainer = $('#cost-container .amount'), grandTotal = parseInt($grandTotalContainer.text(), 10), price = parseInt($fieldID.next('label').find(".amount").text(), 10), siblingAmounts = 0;
                radioName = $fieldID.attr("name");

                $("input[name='" + radioName + "'].active").not($fieldID).each(function() {
                    siblingAmounts += parseInt($(this).next("label").find(".amount").text(), 10);
                });
                $fieldID.toggleClass("active");
                $("input[name='" + radioName + "']").not($fieldID).removeClass("active");
                if ($fieldID.hasClass("active")) {
                    grandTotal -= siblingAmounts;
                    grandTotal += price;
                } else {
                    grandTotal -= price;
                }
                $grandTotalContainer.html(grandTotal);

                switch (fieldValue) {
                    case 'S-4':
                        $machineModelDesc.hide();
                        $s4Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s4');
                        $nextMachineImage.html(s4MachineName + " " + s4MachineType);
                        break;
                    case 'S-5':
                        $machineModelDesc.hide();
                        $s5Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s5');
                        $nextMachineImage.html(s5MachineName + " " + s5MachineType);
                        break;
                    case 'S-6':
                        $machineModelDesc.hide();
                        $s6Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s6');
                        $nextMachineImage.html(s6MachineName + " " + s6MachineType);
                        break;
                    case 'S-7':
                        $machineModelDesc.hide();
                        s7Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s7');
                        $nextMachineImage.html(s7MachineName + " " + s7MachineType);
                        break;
                    case 'small-weight-hopper':
                        $('.small-discharge-funnel').show().find('#small-standard-discharge-funnel').prop('checked', true);
                        $('.large-discharge-funnel').hide().find('input').prop('checked', false);
                        $machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('smwh std-fnl');
                        break;
                    case 'large-weight-hopper':
                        $('.large-discharge-funnel').show().find('#large-standard-discharge-funnel').prop('checked', false);
                        $('.small-discharge-funnel').hide().find('input').prop('checked', false);
                        $machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('lrgwh std-fnl');
                        break;
                    case 'small-steep-funnel':
                    case 'large-steep-funnel':
                    case 'small-standard-discharge-funnel':
                    case 'large-standard-discharge-funnel':
                        $machineImage.toggleClass('std-fnl steep-fnl');
                        break;
                    case 'flag-bag':
                        $machineImage.find('.spout').removeClass('hidden');
                        $spoutContainer.find('.field-name-dimensions li').hide();
                        $spoutContainer.find('.spout-shape-images > *').hide()
                        $spoutContainer.find('.spout-width-inches').show();
                        $spoutContainer.find('.spout-shape-images > .flat-bag-spout-shape').show();
                        $spoutContainer.find('.description p').html("Enter the width of the bag opening (W).");
                        break;
                    case '4-sided-bag':
                        $machineImage.find('.spout').removeClass('hidden');
                        $spoutContainer.find('.field-name-dimensions li').hide();
                        $spoutContainer.find('.spout-shape-images > *').hide()
                        $spoutContainer.find('.spout-width-inches,.spout-height-inches').show();
                        $spoutContainer.find('.spout-shape-images > .four-sided-bag-spout-shape').show();
                        $spoutContainer.find('.description p').html("Looking down at the top of your bag, enter the dimensions (D1) and (D2) of the bag opening.");
                        break;
                    case 'can-jar':
                        $machineImage.find('.spout').removeClass('hidden');
                        $spoutContainer.find('.field-name-dimensions li').hide();
                        $spoutContainer.find('.spout-shape-images > *').hide()
                        $spoutContainer.find('.spout-diameter-inches').show();
                        $spoutContainer.find('.spout-shape-images > .can-or-jar-spout-shape').show();
                        $spoutContainer.find('.description p').html("Enter the inside diameter of the bottle or can opening (D).");
                        break;
                }
            }
        });
    }

    radioSelect();

    $('#btnFront,#btnSide').click(function() {
        btnDirection = $(this).val();
        if (btnDirection === 'Front') {
            $machineImage.addClass('front').removeClass('side');
        } else {
            $machineImage.addClass('side').removeClass('front');
        }
    });

    $('.step-submit').click(function() {
        var $stepContainer = $(this).closest('.step-container'), nextStepContainerID = $stepContainer.next().attr('id'), prevStepContainerID = $stepContainer.prev().attr('id');
        $('#pag-navigation a').removeClass('active');

        if ($(this).is('.next')) {
            $stepContainer.hide().next().show();
            $('#pag-navigation a[href*=' + nextStepContainerID + ']').addClass('active');
        } else {
            $stepContainer.hide().prev().show();
            $('#pag-navigation a[href*=' + prevStepContainerID + ']').addClass('active');
        }
    });

    $('#pag-navigation a').click(function() {
        var stepValue = $(this).attr('href');
        $('#pag-navigation a').removeClass('active');
        $(this).addClass('active');
        $('.step-container').hide();
        $(stepValue).show();
    });

    $('#hidden-accessories-page-btn').click(function() {
        $('#hidden-accessories-page').show();
    });
    $('#btnClose,#btnContinue').click(function() {
        $(this).closest('.step-container').hide();
    });

    $btnAdd.click(function() {
        var num = $('.cloneSpout').length, newNum = new Number(num + 1),
        // the numeric ID of the new input field
        // being
        // added
        newSpoutID = 'spout-' + newNum, newSpoutTypeID = 'spout-' + newNum + "-type", newSpoutDimensionsID = 'spout-' + newNum + "-dimensions",
        // create the new element via clone(),
        // and
        // manipulate it's ID using newNum value
        newElem = $('#spout-' + num).clone().attr('id', newSpoutID),
        // manipulate the name/id values of the
        // elements
        // inside the new element
        radioFieldID = 1;
        newElem.children('legend').html('Spout ' + newNum).next().attr('id', newSpoutTypeID).find('input').attr({
            "id" : function(arr) {
                return newSpoutTypeID + "-" + arr
            },
            'name' : newSpoutTypeID
        }).prop('checked', false).next().attr('for', function(arr) {
            return newSpoutTypeID + "-" + arr
        });
        newElem.find('.description p').html("Please enter the spout type spout that you require by clicking on the image above.");
        newElem.find('.spout-shape-images > *').hide()
        newElem.children('.field-name-dimensions').attr('id', newSpoutDimensionsID).find('li').hide().find('.spout-width-inches input').attr('id', newSpoutID + "-width-inches").closest('.field-name-dimensions').find('.spout-height-inches input').attr('id', newSpoutID + "-height-inches").closest('.field-name-dimensions').find('.spout-diameter-inches input').attr('id', newSpoutID + "-diameter-inches");

        // insert the new element after the last
        // "duplicatable" input field
        $('#spout-' + num).after(newElem);

        // enable the "remove" button
        $btnDel.show().prop('disabled', false);

        // business rule: you can only add 5
        // names
        if (newNum == 3)
            $btnAdd.hide();

        radioSelect();
    });

    $btnDel.click(function() {
        var num = $('.cloneSpout').length;
        // how many "duplicatable" input fields we currently
        // have
        $('#spout-' + num).remove();
        // remove the last element

        // enable the "add" button
        if (num == 3)
            $btnAdd.show();

        // if only one element remains, disable the "remove"
        // button
        if (num - 1 == 1)
            $btnDel.hide().attr('disabled', 'disabled');
    });

});
<commit_msg>Separated the grand total calculation and the spout selection into separate functions<commit_after>$(document).ready(function() {

    // Declare global variables
    var $machineModelDesc = $('.machine-model-description'), $machineImage = $('#machine-image'), $nextMachineImage = $('#machine-image').next('#machine-title'), $btnAdd = $('#btnAdd'), $btnDel = $('#btnDel'), $grandTotalContainer = $('#cost-container .amount'), grandTotal = parseInt($grandTotalContainer.text(), 10),
    // S-4 Machine attributes
    $s4Machine = $('label[for="s4"]'), s4MachineName = $s4Machine.find('.machineName').text(), s4MachineType = $s4Machine.find('.machineType').text(), s4MachinePrice = $s4Machine.find('.amount').text()
    // S-5Machine attributes
    $s5Machine = $('label[for="s5"]'), s5MachineName = $s5Machine.find('.machineName').text(), s5MachineType = $s5Machine.find('.machineType').text(), s5MachinePrice = $s5Machine.find('.amount').text()
    // S-6 Machine attributes
    $s6Machine = $('label[for="s6"]'), s6MachineName = $s6Machine.find('.machineName').text(), s6MachineType = $s6Machine.find('.machineType').text(), s6MachinePrice = $s6Machine.find('.amount').text()
    // S-7 Machine attributes
    s7Machine = $('label[for="s7"]'), s7MachineName = s7Machine.find('.machineName').text(), s7MachineType = s7Machine.find('.machineType').text(), s7MachinePrice = s7Machine.find('.amount').text();

    //  $('.field-name-machine-model input').each(function(index) {
    //      var machineID = $(this).attr('id');
    //  });

    // Create instances of the machine object and assign
    // properties
    //  machineS4 = {
    //      machineName : $('input '),
    //      machineType : "Weigh/Fill System",
    //      machinePrice : 6150
    //  };

    // Hide fallback content, add and delete button
    $('.large-discharge-funnel,.field-name-dimensions li,#step-2,#step-3,#step-4,#step-5,#hidden-accessories-page,.spout-shape-images > *,#btnAdd,#btnDel,.btnCalculate').hide();
    // Remove fallback form elements
    $('.default-spout,.default-discharge-funnel,#btnQuote').remove();
    // .bottom class puts a negative z-index on the hidden
    // accessories page so that it loads underneath the rest of
    // the content. This removes that class on load.
    $('.bottom').removeClass('bottom');
    // Hide all but the first machine model description
    $machineModelDesc.not('.machine-model-description:first').hide();
    // Remove .hidden class from JS ready content
    $('.small-discharge-funnel,.large-discharge-funnel,#btnAdd,#btnDel,#btnFront,#btnSide,.cloneSpout,.step-submit,#sidebar,#btnPrint,#btnEmail,#btnClose,#btnContinue,.order-summary,#hidden-accessories-page,#machine-title,#order-summary').removeClass('hidden');
    // Check the default discharge funnel field
    $('#small-standard-discharge-funnel').prop('checked', true).addClass('active');

    // Add a waypoint to the sidebar
    var $mi_container = $('#sidebar');
    // Remove the no-sidebar class for fallback
    $('#main-content').removeClass('no-sidebar');
    // Set the .sticky class when waypoint is reached
    $mi_container.waypoint(function(direction) {
        $('#machine-image-container').toggleClass('sticky', direction === 'down');
    });

    function radioSelect() {
        var $radioInputFields = $('input[name=machine-model],input[name=weight-hopper],input[name=discharge-funnel]');

        $radioInputFields.click(function(e) {
            var $fieldID = $(this), inputVal = $fieldID.closest('ul.field-type-radio').find('.active').attr('id'), objectVal = $fieldID.attr('id');

            if (inputVal == objectVal) {
                e.preventDefault();
                //add this to prevent default click behaviour
            } else {

                var fieldVal = $fieldID.val(), radioName = $fieldID.attr("name");

                switch (fieldVal) {
                    case 'S-4':
                        $machineModelDesc.hide();
                        $s4Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s4');
                        $nextMachineImage.html(s4MachineName + " " + s4MachineType);
                        break;
                    case 'S-5':
                        $machineModelDesc.hide();
                        $s5Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s5');
                        $nextMachineImage.html(s5MachineName + " " + s5MachineType);
                        break;
                    case 'S-6':
                        $machineModelDesc.hide();
                        $s6Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s6');
                        $nextMachineImage.html(s6MachineName + " " + s6MachineType);
                        break;
                    case 'S-7':
                        $machineModelDesc.hide();
                        s7Machine.find('.machine-model-description').show();
                        $machineImage.removeClass('s4 s5 s6 s7').addClass('s7');
                        $nextMachineImage.html(s7MachineName + " " + s7MachineType);
                        break;
                    case 'small-weight-hopper':
                        $('.small-discharge-funnel').show().find('#small-standard-discharge-funnel').prop('checked', true);
                        $('.large-discharge-funnel').hide().find('input').prop('checked', false);
                        $machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('smwh std-fnl');
                        break;
                    case 'large-weight-hopper':
                        $('.large-discharge-funnel').show().find('#large-standard-discharge-funnel').prop('checked', false);
                        $('.small-discharge-funnel').hide().find('input').prop('checked', false);
                        $machineImage.removeClass('smwh lrgwh std-fnl steep-fnl').addClass('lrgwh std-fnl');
                        break;
                    case 'small-steep-funnel':
                    case 'large-steep-funnel':
                    case 'small-standard-discharge-funnel':
                    case 'large-standard-discharge-funnel':
                        $machineImage.toggleClass('std-fnl steep-fnl');
                        break;

                }
                calculateTotal($fieldID);
            }
        });
    }

    radioSelect();

    function spoutSelect() {
        $('input.spout-type').click(function() {
            var $fieldID = $(this), fieldVal = $fieldID.val(), $spoutContainer = $fieldID.closest('fieldset');

            $spoutContainer.find('.btnCalculate').show();
            // Toggle active class
            $spoutContainer.find('input.active').removeClass('active');
            $fieldID.addClass('active');
            // Show the spout image
            $machineImage.find('.spout').removeClass('hidden');
            // Hide all the dimensions fields and images
            $spoutContainer.find('.field-name-dimensions li').hide();
            $spoutContainer.find('.spout-shape-images > *').hide();

            switch (fieldVal) {
                case 'flag-bag':
                    $spoutContainer.find('.spout-width-inches').show();
                    $spoutContainer.find('.spout-shape-images > .flat-bag-spout-shape').show();
                    $spoutContainer.find('.description p').html("Enter the width of the bag opening (W).");
                    break;
                case '4-sided-bag':
                    $spoutContainer.find('.spout-width-inches,.spout-height-inches').show();
                    $spoutContainer.find('.spout-shape-images > .four-sided-bag-spout-shape').show();
                    $spoutContainer.find('.description p').html("Looking down at the top of your bag, enter the dimensions (D1) and (D2) of the bag opening.");
                    break;
                case 'can-jar':
                    $spoutContainer.find('.spout-diameter-inches').show();
                    $spoutContainer.find('.spout-shape-images > .can-or-jar-spout-shape').show();
                    $spoutContainer.find('.description p').html("Enter the inside diameter of the bottle or can opening (D).");
                    break;
            }

        });
    }

    spoutSelect();

    function calculateSpoutSize() {
        $('.btnCalculate').click(function() {
            var num = $('.cloneSpout').length
            if(num < 3) {
            $btnAdd.show();
            }
        });
    }

    calculateSpoutSize();

    function calculateTotal($fieldID) {
        var price = parseInt($fieldID.next('label').find(".amount").text(), 10), siblingAmounts = 0, radioName = $fieldID.attr("name");

        $("input[name='" + radioName + "'].active").not($fieldID).each(function() {
            siblingAmounts += parseInt($(this).next("label").find(".amount").text(), 10);
        });
        $fieldID.toggleClass("active");
        $("input[name='" + radioName + "']").not($fieldID).removeClass("active");
        if ($fieldID.hasClass("active")) {
            grandTotal -= siblingAmounts;
            grandTotal += price;
        } else {
            grandTotal -= price;
        }
        $grandTotalContainer.html(grandTotal);
    }

    $('#btnFront,#btnSide').click(function() {
        btnDirection = $(this).val();
        if (btnDirection === 'Front') {
            $machineImage.addClass('front').removeClass('side');
        } else {
            $machineImage.addClass('side').removeClass('front');
        }
    });

    $('.step-submit').click(function() {
        var $stepContainer = $(this).closest('.step-container'), nextStepContainerID = $stepContainer.next().attr('id'), prevStepContainerID = $stepContainer.prev().attr('id');
        $('#pag-navigation a').removeClass('active');

        if ($(this).is('.next')) {
            $stepContainer.hide().next().show();
            $('#pag-navigation a[href*=' + nextStepContainerID + ']').addClass('active');
        } else {
            $stepContainer.hide().prev().show();
            $('#pag-navigation a[href*=' + prevStepContainerID + ']').addClass('active');
        }
    });

    $('#pag-navigation a').click(function() {
        var stepValue = $(this).attr('href');
        $('#pag-navigation a').removeClass('active');
        $(this).addClass('active');
        $('.step-container').hide();
        $(stepValue).show();
    });

    $('#hidden-accessories-page-btn').click(function() {
        $('#hidden-accessories-page').show();
    });
    $('#btnClose,#btnContinue').click(function() {
        $(this).closest('.step-container').hide();
    });

    $btnAdd.click(function() {
        var num = $('.cloneSpout').length, newNum = new Number(num + 1),
        // the numeric ID of the new input field
        // being
        // added
        newSpoutID = 'spout-' + newNum, newSpoutTypeID = 'spout-' + newNum + "-type", newSpoutDimensionsID = 'spout-' + newNum + "-dimensions",
        // create the new element via clone(),
        // and
        // manipulate it's ID using newNum value
        newElem = $('#spout-' + num).clone().attr('id', newSpoutID),
        // manipulate the name/id values of the
        // elements
        // inside the new element
        radioFieldID = 1;
        newElem.children('legend').html('Spout ' + newNum).next().attr('id', newSpoutTypeID).find('input').attr({
            "id" : function(arr) {
                return newSpoutTypeID + "-" + arr
            },
            'name' : newSpoutTypeID
        }).prop('checked', false).removeClass('active').next().attr('for', function(arr) {
            return newSpoutTypeID + "-" + arr
        });
        newElem.find('.description p').html("Please enter the spout type spout that you require by clicking on the image above.");
        newElem.find('.spout-shape-images > *').hide()
        newElem.children('.field-name-dimensions').attr('id', newSpoutDimensionsID).find('li').hide().find('.spout-width-inches input').attr('id', newSpoutID + "-width-inches").closest('.field-name-dimensions').find('.spout-height-inches input').attr('id', newSpoutID + "-height-inches").closest('.field-name-dimensions').find('.spout-diameter-inches input').attr('id', newSpoutID + "-diameter-inches");
        // insert the new element after the last
        // "duplicatable" input field
        $('#spout-' + num).after(newElem);

        // enable the "remove" button
        $btnDel.show().prop('disabled', false);

        // business rule: you can only add 5
        // names
        $btnAdd.hide();

        spoutSelect();
        calculateSpoutSize();

    });

    $btnDel.click(function() {
        // Check the number of spouts
        var num = $('.cloneSpout').length;

        if ($('#spout-' + num + ' input').hasClass('active')) {
            price = parseInt($('#spout-' + num + ' input.active + label .amount').text(), 10);
            grandTotal -= price;
            $grandTotalContainer.html(grandTotal);
        }

        // Remove the last spout
        $('#spout-' + num).remove();

        // Show the "add" button
        if (num == 3) {
            $btnAdd.show();
        }
        // Disable the "remove" button
        if (num - 1 == 1) {
            $btnDel.hide().attr('disabled', 'disabled');
        }
    });

});
<|endoftext|>


<commit_before>'use strict';

requirejs.
	// http://requirejs.org/docs/api.html#config
	config({
		// enforceDefine to catch load failures in IE
		// http://requirejs.org/docs/api.html#ieloadfail
		// http://requirejs.org/docs/api.html#config-enforceDefine
		// See below for load require() | define() comment with this option
    	enforceDefine: true,

    	// http://requirejs.org/docs/api.html#pathsfallbacks
		// If the CDN location fails, load from local location

		// @TODO - work with local copies in development, and uncomment the CDN hosted when you go live
		paths: {
		'jquery': [//'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min',
					'libs/jquery.min'],
		'jquery-ui': [//'http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min',
					'libs/jquery-ui.min'],
		'backbone': [//'http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min',
					'libs/backbone'],
		'underscore': [//'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.3/underscore-min',
					'libs/underscore'],
		'hogan': 'libs/hogan'
	},
	// http://requirejs.org/docs/api.html#config-shim
	shim: {
		'jquery': {
			exports: '$'
		},
		'jquery-ui': {
			deps: ['jquery'],
			exports: '$.ui',
		},
		'underscore': {
			exports: '_'
		},
		'backbone': {
			deps: ['jquery', 'underscore'],
			exports: 'Backbone'
		},
		'hogan' : {
			exports: 'Hogan'
		}
	}
});

 // NOTE: If you do set enforceDefine: true, and you use data-main="" to load your main JS module,
 // then that main JS module must call define() instead of require() to load the code it needs.
 // The main JS module can still call require/requirejs to set config values,
 // but for loading modules it should use define().

define(['global'], function(Global) {
	Global.init();
});<commit_msg>Update some RequireJS config documentation<commit_after>'use strict';

	/**
	  * RequireJS config and shim
	  * @see http://requirejs.org/docs/api.html#config
	  *
	  * Also a good read to explain RequireJS dependency management
	  * @link http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/
      *
	  */

requirejs.
	config({
		// enforceDefine to catch load failures in IE
		// @see http://requirejs.org/docs/api.html#ieloadfail
		// @see http://requirejs.org/docs/api.html#config-enforceDefine
		// See below for load require() | define() comment with this option
    	enforceDefine: true,

    	// @see http://requirejs.org/docs/api.html#pathsfallbacks
		// If the CDN location fails, load from local location

		// @TODO - work with local copies in development, and uncomment the CDN hosted when you go live
		paths: {
		'jquery': [//'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min',
					'libs/jquery.min'],
		'jquery-ui': [//'http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min',
					'libs/jquery-ui.min'],
		'backbone': [//'http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min',
					'libs/backbone'],
		'underscore': [//'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.3/underscore-min',
					'libs/underscore'],
		'hogan': 'libs/hogan'
	},
	// @see http://requirejs.org/docs/api.html#config-shim
	shim: {
		'jquery': {
			exports: '$'
		},
		'jquery-ui': {
			deps: ['jquery'],
			exports: '$.ui',
		},
		'underscore': {
			exports: '_'
		},
		'backbone': {
			deps: ['jquery', 'underscore'],
			exports: 'Backbone'
		},
		'hogan' : {
			exports: 'Hogan'
		}
	}
});

 // DEV NOTE: If you do set enforceDefine: true, and you use data-main="" to load your main JS module,
 // then that main JS module must call define() instead of require() to load the code it needs.
 // The main JS module can still call require/requirejs to set config values,
 // but for loading modules it should use define().

define(['global'], function(Global) {
	Global.init();
});<|endoftext|>