<commit_before>
angular.module('os.biospecimen.extensions.util', [])
  .factory('ExtensionsUtil', function($modal, Form, Alerts, ApiUrls) {
    var filesUrl = ApiUrls.getBaseUrl() + 'form-files';

    function getFileDownloadUrl(formId, recordId, ctrlName) {
      var params = '?formId=' + formId +
                   '&recordId=' + recordId +
                   '&ctrlName=' + ctrlName +
                   '&_reqTime=' + new Date().getTime();

      return filesUrl + params;
    }

    function deleteRecord(record, onDeletion) {
      var modalInstance = $modal.open({
        templateUrl: 'modules/biospecimen/extensions/delete-record.html',
        controller: function($scope, $modalInstance) {
          $scope.record= record;

          $scope.yes = function() {
            Form.deleteRecord(record.formId, record.recordId).then(
              function(result) {
                $modalInstance.close();
                Alerts.success('extensions.record_deleted');
              },

              function() {
                $modalInstance.dismiss('cancel');
              }
            );
          }

          $scope.no = function() {
            $modalInstance.dismiss('cancel');
          }
        }
      });

      modalInstance.result.then(
        function() {
          if (typeof onDeletion == 'function') {
            onDeletion(record);
          }
        }
      );
    };

    function createExtensionFieldMap(entity) {
      var extensionDetail = entity.extensionDetail;
      if (!extensionDetail) {
        return;
      }

      extensionDetail.attrsMap = {
        id: extensionDetail.id,
        containerId: extensionDetail.formId
      };

      angular.forEach(extensionDetail.attrs, function(attr) {
        if (attr.type == 'datePicker') {
          if (!isNaN(attr.value) && !isNaN(parseInt(attr.value))) {
            attr.value = parseInt(attr.value);
          } else {
            attr.value = new Date(attr.value);
          }
        }

        extensionDetail.attrsMap[attr.name] = attr.type != 'subForm' ? attr.value : getSubformFieldMap(attr);
      });
    }

    function getSubformFieldMap(sf) {
      var attrsMap = [];
      angular.forEach(sf.value, function(attrs, idx) {
        attrsMap[idx] = {};
        angular.forEach(attrs, function(attr) {
          attrsMap[idx][attr.name] = attr.value;
        });
      })

      return attrsMap;
    }

    function getExtnOpts(entity, extnCtxt, disableFields) {
      if (!extnCtxt) {
        return undefined;
      }

      createExtensionFieldMap(entity);

      return {
        formId: extnCtxt.formId,
        recordId: !!entity.extensionDetail ? entity.extensionDetail.id : undefined,
        formCtxtId: parseInt(extnCtxt.formCtxtId),
        objectId: entity.id,
        formData: !!entity.extensionDetail ? (entity.extensionDetail.attrsMap || {}): {},
        showActionBtns: false,
        showPanel: false,
        labelAlignment: 'horizontal',
        disableFields: disableFields || []
      };
    }

    function sortForms(inputForms, orderSpec) {
      if (!orderSpec || orderSpec.length == 0) {
        return inputForms;
      }

      var formsByType = {};
      angular.forEach(inputForms,
        function(form) {
          if (!formsByType[form.entityType]) {
            formsByType[form.entityType] = [];
          }

          formsByType[form.entityType].push(form);
        }
      );

      var result = [];
      angular.forEach(orderSpec,
        function(typeForms) {
          Array.prototype.push.apply(result, sortForms0(formsByType[typeForms.type], typeForms.forms));
          delete formsByType[typeForms.type];
        }
      );

      angular.forEach(inputForms,
        function(form) {
          if (formsByType[form.entityType]) {
            result.push(form);
          }
        }
      );

      return result;
    }

    function sortForms0(inputForms, orderSpec) {
      var formsById = {};
      angular.forEach(inputForms,
        function(form) {
          formsById[form.formId] = form;
        }
      );

      var result = [];
      angular.forEach(orderSpec,
        function(spec) {
          var form = formsById[spec.id];
          if (form) {
            result.push(form);
            inputForms.splice(inputForms.indexOf(form), 1);
          }
        }
      );

      Array.prototype.push.apply(result, inputForms);
      return result;
    }

    function linkFormRecords(inputForms, records) {
      var recsMap = {};
      angular.forEach(records,
        function(rec) {
          if (!recsMap[rec.fcId]) {
            recsMap[rec.fcId] = [];
          }
          recsMap[rec.fcId].push(rec);
        }
      );

      angular.forEach(inputForms,
        function(form) {
          form.records = recsMap[form.formCtxtId] || [];
        }
      );
    }

    return {
      getFileDownloadUrl: getFileDownloadUrl,

      deleteRecord: deleteRecord,

      createExtensionFieldMap: createExtensionFieldMap,

      getExtnOpts: getExtnOpts,

      sortForms: sortForms,

      linkFormRecords: linkFormRecords
    }

  });
<commit_msg>OPSMN-4086: Do not attempt to create a date object of null value (i.e. not specified date field).<commit_after>
angular.module('os.biospecimen.extensions.util', [])
  .factory('ExtensionsUtil', function($modal, Form, Alerts, ApiUrls) {
    var filesUrl = ApiUrls.getBaseUrl() + 'form-files';

    function getFileDownloadUrl(formId, recordId, ctrlName) {
      var params = '?formId=' + formId +
                   '&recordId=' + recordId +
                   '&ctrlName=' + ctrlName +
                   '&_reqTime=' + new Date().getTime();

      return filesUrl + params;
    }

    function deleteRecord(record, onDeletion) {
      var modalInstance = $modal.open({
        templateUrl: 'modules/biospecimen/extensions/delete-record.html',
        controller: function($scope, $modalInstance) {
          $scope.record= record;

          $scope.yes = function() {
            Form.deleteRecord(record.formId, record.recordId).then(
              function(result) {
                $modalInstance.close();
                Alerts.success('extensions.record_deleted');
              },

              function() {
                $modalInstance.dismiss('cancel');
              }
            );
          }

          $scope.no = function() {
            $modalInstance.dismiss('cancel');
          }
        }
      });

      modalInstance.result.then(
        function() {
          if (typeof onDeletion == 'function') {
            onDeletion(record);
          }
        }
      );
    };

    function createExtensionFieldMap(entity) {
      var extensionDetail = entity.extensionDetail;
      if (!extensionDetail) {
        return;
      }

      extensionDetail.attrsMap = {
        id: extensionDetail.id,
        containerId: extensionDetail.formId
      };

      angular.forEach(extensionDetail.attrs, function(attr) {
        if (attr.type == 'datePicker') {
          if (!isNaN(attr.value) && !isNaN(parseInt(attr.value))) {
            attr.value = parseInt(attr.value);
          } else if (!!attr.value || attr.value == 0) {
            attr.value = new Date(attr.value);
          }
        }

        extensionDetail.attrsMap[attr.name] = attr.type != 'subForm' ? attr.value : getSubformFieldMap(attr);
      });
    }

    function getSubformFieldMap(sf) {
      var attrsMap = [];
      angular.forEach(sf.value, function(attrs, idx) {
        attrsMap[idx] = {};
        angular.forEach(attrs, function(attr) {
          attrsMap[idx][attr.name] = attr.value;
        });
      })

      return attrsMap;
    }

    function getExtnOpts(entity, extnCtxt, disableFields) {
      if (!extnCtxt) {
        return undefined;
      }

      createExtensionFieldMap(entity);

      return {
        formId: extnCtxt.formId,
        recordId: !!entity.extensionDetail ? entity.extensionDetail.id : undefined,
        formCtxtId: parseInt(extnCtxt.formCtxtId),
        objectId: entity.id,
        formData: !!entity.extensionDetail ? (entity.extensionDetail.attrsMap || {}): {},
        showActionBtns: false,
        showPanel: false,
        labelAlignment: 'horizontal',
        disableFields: disableFields || []
      };
    }

    function sortForms(inputForms, orderSpec) {
      if (!orderSpec || orderSpec.length == 0) {
        return inputForms;
      }

      var formsByType = {};
      angular.forEach(inputForms,
        function(form) {
          if (!formsByType[form.entityType]) {
            formsByType[form.entityType] = [];
          }

          formsByType[form.entityType].push(form);
        }
      );

      var result = [];
      angular.forEach(orderSpec,
        function(typeForms) {
          Array.prototype.push.apply(result, sortForms0(formsByType[typeForms.type], typeForms.forms));
          delete formsByType[typeForms.type];
        }
      );

      angular.forEach(inputForms,
        function(form) {
          if (formsByType[form.entityType]) {
            result.push(form);
          }
        }
      );

      return result;
    }

    function sortForms0(inputForms, orderSpec) {
      var formsById = {};
      angular.forEach(inputForms,
        function(form) {
          formsById[form.formId] = form;
        }
      );

      var result = [];
      angular.forEach(orderSpec,
        function(spec) {
          var form = formsById[spec.id];
          if (form) {
            result.push(form);
            inputForms.splice(inputForms.indexOf(form), 1);
          }
        }
      );

      Array.prototype.push.apply(result, inputForms);
      return result;
    }

    function linkFormRecords(inputForms, records) {
      var recsMap = {};
      angular.forEach(records,
        function(rec) {
          if (!recsMap[rec.fcId]) {
            recsMap[rec.fcId] = [];
          }
          recsMap[rec.fcId].push(rec);
        }
      );

      angular.forEach(inputForms,
        function(form) {
          form.records = recsMap[form.formCtxtId] || [];
        }
      );
    }

    return {
      getFileDownloadUrl: getFileDownloadUrl,

      deleteRecord: deleteRecord,

      createExtensionFieldMap: createExtensionFieldMap,

      getExtnOpts: getExtnOpts,

      sortForms: sortForms,

      linkFormRecords: linkFormRecords
    }

  });
<|endoftext|>


<commit_before>// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.login')

/**
 * Controller to handle the list of sites.
 *
 * @module mm.core.login
 * @ngdoc controller
 * @name mmLoginSitesCtrl
 */
.controller('mmLoginSitesCtrl', function($scope, $state, $mmSitesManager, $log, $translate, $mmUtil, $ionicHistory, $mmText) {

    $log = $log.getInstance('mmLoginSitesCtrl');

    $mmSitesManager.getSites().then(function(sites) {
        $scope.sites = sites;
        $scope.data = {
            hasSites: sites.length > 0,
            showDetele: false
        };
    });

    $scope.toggleDelete = function() {
        $scope.data.showDelete = !$scope.data.showDelete;
    };

    $scope.onItemDelete = function(e, index) {
        // Prevent login() from being triggered. No idea why I cannot replicate this
        // problem on http://codepen.io/ionic/pen/JsHjf.
        e.stopPropagation();

        var site = $scope.sites[index],
            sitename = site.sitename;

        $mmText.formatText(sitename).then(function(sitename) {
            $mmUtil.showConfirm($translate('mm.login.confirmdeletesite', {sitename: sitename})).then(function() {
                $mmSitesManager.deleteSite(site.id).then(function() {
                    $scope.sites.splice(index, 1);
                    $mmSitesManager.hasNoSites().then(function() {
                        $ionicHistory.nextViewOptions({disableBack: true});
                        $state.go('mm_login.site');
                    });
                }, function(error) {
                    $log.error('Delete site failed');
                    $mmUtil.showErrorModal('mm.login.errordeletesite', true);
                });
            });
        });
    };

    $scope.login = function(siteid) {
        var modal = $mmUtil.showModalLoading();

        $mmSitesManager.loadSite(siteid).then(function() {
            $ionicHistory.nextViewOptions({disableBack: true});
            $state.go('site.mm_courses');
        }, function(error) {
            $log.error('Error loading site '+siteid);
            error = error || 'Error loading site.';
            $mmUtil.showErrorModal(error);
        }).finally(function() {
            modal.dismiss();
        });
    };

    $scope.add = function() {
        $state.go('mm_login.site');
    };

});
<commit_msg>MOBILE-1272 sites: Fix misspel in sites controller<commit_after>// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.login')

/**
 * Controller to handle the list of sites.
 *
 * @module mm.core.login
 * @ngdoc controller
 * @name mmLoginSitesCtrl
 */
.controller('mmLoginSitesCtrl', function($scope, $state, $mmSitesManager, $log, $translate, $mmUtil, $ionicHistory, $mmText) {

    $log = $log.getInstance('mmLoginSitesCtrl');

    $mmSitesManager.getSites().then(function(sites) {
        $scope.sites = sites;
        $scope.data = {
            hasSites: sites.length > 0,
            showDelete: false
        };
    });

    $scope.toggleDelete = function() {
        $scope.data.showDelete = !$scope.data.showDelete;
    };

    $scope.onItemDelete = function(e, index) {
        // Prevent login() from being triggered. No idea why I cannot replicate this
        // problem on http://codepen.io/ionic/pen/JsHjf.
        e.stopPropagation();

        var site = $scope.sites[index],
            sitename = site.sitename;

        $mmText.formatText(sitename).then(function(sitename) {
            $mmUtil.showConfirm($translate('mm.login.confirmdeletesite', {sitename: sitename})).then(function() {
                $mmSitesManager.deleteSite(site.id).then(function() {
                    $scope.sites.splice(index, 1);
                    $mmSitesManager.hasNoSites().then(function() {
                        $ionicHistory.nextViewOptions({disableBack: true});
                        $state.go('mm_login.site');
                    });
                }, function(error) {
                    $log.error('Delete site failed');
                    $mmUtil.showErrorModal('mm.login.errordeletesite', true);
                });
            });
        });
    };

    $scope.login = function(siteid) {
        var modal = $mmUtil.showModalLoading();

        $mmSitesManager.loadSite(siteid).then(function() {
            $ionicHistory.nextViewOptions({disableBack: true});
            $state.go('site.mm_courses');
        }, function(error) {
            $log.error('Error loading site '+siteid);
            error = error || 'Error loading site.';
            $mmUtil.showErrorModal(error);
        }).finally(function() {
            modal.dismiss();
        });
    };

    $scope.add = function() {
        $state.go('mm_login.site');
    };

});
<|endoftext|>


<commit_before>//__BEGIN_LICENSE__
// Copyright (c) 2015, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The xGDS platform is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//__END_LICENSE__

var xgds_image = xgds_image || {};

$.extend(xgds_image,{
	hookDelete: function() {
		// Add a click handler for the delete row
//		$('#delete_images').click( function() {
//		    var selectedRows = getSelectedRows( theDataTable );
//		    // get a list containing just the id's of selected images
//		    var selectedImageIdsList = jQuery.map(selectedRows, function(element) { return jQuery(element).attr('pk'); });
//		    var selectedImageIdsJson = {"pk": selectedImageIdsList};
//			//delete selected images from db
//		    var url = deleteImagesUrl;
//		    $.ajax({
//				url: url,
//				type: "POST",
//				data: selectedImageIdsJson, // serializes the form's elements.
//				success: function(data) {
//					console.log("images successfully deleted");
//				},
//				error: function(request, status, error) {
//					console.log("error! ", error);
//				}
//			})
//
//			// delete selected rows from datatable.
//		    for (var i = 0; i < selectedRows.length; i++) {
//		        theDataTable.fnDeleteRow(selectedRows[i]);
//		    }
//		    // re-render the map icons with only the non-deleted images.
//		    showOnMap(theDataTable.fnGetData());
//		} );
	},
	activateButtons: function(el) {
		// Hook up edit info and add note buttons
		el.find("#edit_info_button").click(function(event) {
		    event.preventDefault();
		    el.find("#image_overview").hide();
		    el.find("#more_info_view").show();
		});
		el.find("#cancel_edit").click(function(event) {
		    event.preventDefault();
		    el.find("#more_info_view").hide();
		    el.find("#image_overview").show();
		});
		el.find(".add_note_button").click(function(event) {
		    event.preventDefault();
		    el.find("#notes_input").show();
		});
	},
	onImageNextOrPrev: function(el){
		el.find('.next-button').click(function(event) {
			// set the img src
			var index = xgds_image.getCurrentImageAndIndex(el);
			if (index != null) {
			    index = index + 1;
			    if (index == imageSetsArray.length){
			    	index = 0;
			    }
			    clearTableSelection(theDataTable);
			    xgds_image.updateImageView(el, null, index, false, false);
			}
		});
		el.find(".prev-button").click(function(event) {
			var index = xgds_image.getCurrentImageAndIndex(el);
			if (index != null) {
			    index = index - 1;
			    if (index < 0){
				index = imageSetsArray.length - 1;
			    }
			    clearTableSelection(theDataTable);
			    xgds_image.updateImageView(el, null, index, false, false);
			}
		});
	},
	setChangedPosition: function(value, el){
		$(el).find('#id_changed_position').attr('value', value);
	},
	hookEditingPosition: function(el){
		// Set the changed_position to true if the user edits any of the position fields.
		$(el).find("#id_latitude").change(function() {setChangedPosition(1, el)});
		$(el).find("#id_longitude").change(function() {setChangedPosition(1, el)});
		$(el).find("#id_altitude").change(function() {setChangedPosition(1, el)});
		$(el).find("#id_heading").change(function() {setChangedPosition(1, el)});
	},
	onUpdateImageInfo: function(el) {
		// Saves image info to the db when user updates it and submits.
		$(el).find("#updateInfoSubmit").on('click', function(event) {
			event.preventDefault(); 	// avoid to execute the actual submit of the form.
			var url = updateImageUrl; // the script where you handle the form input.
			var postData = $("#more-info-form").serialize();
			$.ajax({
				url: url,
				type: "POST",
				data: postData, // serializes the form's elements.
				success: function(data)
				{
				    xgds_image.setSaveStatusMessage($('#message'), 'Saved','');
				    xgds_image.updateImageView(el, data[0], undefined, true, true);
				    el.find("#more_info_view").hide();
				    el.find("#image_overview").show();
				},
				error: function(request, status, error) {
				    xgds_image.setSaveStatusMessage($('#message'), status, error);
				}
			});
			return false;
		});
	},
	getCurrentImageAndIndex: function(el){
		// Helper that finds index in imageSetsArray
		// of the currently displayed image in the imageView.
		var currentImageName = el.attr('pk');
		var currentImageIndex = null;
		for (var i=0; i< imageSetsArray.length; i++) {
			if (imageSetsArray[i]['name'] == currentImageName) {
				currentImageIndex = i;
				break;
			}
		}
		return currentImageIndex;
	},
	stopTiles: function() {
		if (!_.isUndefined(this.viewer)){
			this.viewer._cancelPendingImages();
		}
	},
	updateImageView: function(el, imageJson, index, keepingImage, keepingNotes) {
		if (imageJson == null){
			if (index != null) {
				imageJson = imageSetsArray[index];
			} else {
				return;
			}
		}

		if (!keepingNotes){
			var tbl = el.find('table.notes_list');
			xgds_notes.initializeNotesReference(el, imageJson['app_label'], imageJson['model_type'], imageJson['pk'], imageJson['acquisition_time'], imageJson['acquisition_timezone']);
			xgds_notes.getNotesForObject(imageJson['app_label'], imageJson['model_type'], imageJson['pk'], 'notes_content', tbl);
		}

		var newContent = this.compiledTemplate(imageJson);
		$(el).html(newContent);

		if (!keepingImage){
			this.setupImageViewer(imageJson);
	    }
	},
	constructImageView: function(imageJson) {
		var modelMap = app.options.searchModels['Photo'];
		var url = '/xgds_core/handlebar_string/' + modelMap.viewHandlebars;
		$.when($.get(url, function(handlebarSource, status){
			app.showDetailView(handlebarSource, imageJson, modelMap, 'Photo');
		}));
	},
	loadImageInViewer: function(imageJson){
		this.setupImageViewer(imageJson);
	},
	hideImageNextPrev: function() {
		$('.prev-button').hide();
		$('.next-button').hide();
		$('#new-window-btn').hide();
	},
	saveRotationDegrees: function(imageJson, degrees) {
		// save rotation degrees to the database
		imageJson['rotation_degrees'] = degrees;
		var postData = imageJson;
		var url = app.options.searchModels.Photo.saveRotationUrl;
		// get rotation degrees from db, compare to degrees.
		// this gets called when user switches the view to another image.
		// call ajax to save the rotation degrees.
		$.ajax({
			url: url,
			type: "POST",
			data: postData, // serializes the form's elements.
			success: function(data) {
			},
			error: function(request, status, error) {
				//console.log("error! ", error)
			}
		});
	},
	setOpenseadragonRotation: function(osd_viewer, imagePK){
		var getData = {'imagePK': imagePK };
		var url = app.options.searchModels.Photo.getRotationUrl;
		$.ajax({
			url: url,
			type: "POST",
			data: getData, // serializes the form's elements.
			success: function(data) {
				osd_viewer.viewport.setRotation(data['rotation_degrees'])
			},
			error: function(request, status, error) {
				console.log("error! ", error);
			}
		});
	},
	removeViewer: function() {
		if (!_.isUndefined(this.viewer)){
			this.viewer._cancelPendingImages();
			this.viewer.destroy();
			this.viewer = undefined;
		}
	},
	showRawImage: function(imageJson){
		var rawImage = imageJson.raw_image_url;
		this.removeViewer();
		try {
			$(".openseadragon-container").hide();
		} catch (err){
			// pass
		}
		$('#display-image').prepend('<img id="raw-image" src="' + rawImage + '" />');
	},
	setupImageViewer: function(imageJson){
		if (this.viewer != undefined){
			//TODO this should really be appropriate but somehow updateContents is being triggered many times
//			if (this.viewer.imageJson.pk == imageJson.pk){
//				return;
//			}
			this.removeViewer();
			//TODO WILLIAM put in some clearAnnotations
		}
		// try removing the raw image
		try {
			$("#raw-image").remove();  // or destroy();
		} catch (err) {
			//pass
		}

		var tiledImage = imageJson.deepzoom_file_url;

		if (imageJson.create_deepzoom || _.isEmpty(tiledImage)){
			// tiles are not ready yet, let's make sure:
			$.ajax({
				  dataType: "json",
				  url: '/xgds_image/checkTiles/' + imageJson.pk,
				  success: function(data) {
					  imageJson.create_deepzoom = data.create_deepzoom;
					  imageJson.deepzoom_file_url = data.deepzoom_file_url;
					  tiledImage = data.deepzoom_file_url;
				  },
				  error: function(){
					  // use the old state
				  },
				  async: false
				});
			if (imageJson.create_deepzoom || _.isEmpty(tiledImage)){
				this.showRawImage(imageJson);
				return;
			}
		}

		// build tile sources for openseadragon image viewer
		var prefixUrl = '/static/openseadragon/built-openseadragon/openseadragon/images/';
		try {
			var displayImage = $('#display-image');
			if (displayImage.length == 0){
				throw ('Cound not find display-image div');
			} else {
				displayImage = displayImage[0];
			}
			this.viewer = OpenSeadragon({
				element: displayImage,
//				id: "display-image",
				prefixUrl: prefixUrl,
				tileSources: tiledImage,
			    showRotationControl: true,
			    imageJson: imageJson,
			 	gestureSettingsMouse:   {
 	            	clickToZoom: false
 		        }
			});
			this.viewer['viewer_initialized'] = true;
			this.setOpenseadragonRotation(this.viewer, imageJson['pk']);

			// Add handlers for full-screen event and rotation event.
			this.viewer.addHandler('full-screen', function (viewer) {
				// grab the canvas from the viewer and reset the size.
				var element = viewer.eventSource.element; // #display-image
				var osd_canvas = $(element).find('.openseadragon-canvas'); // somehow change the style -- test with funky values.
				osd_canvas.width("100%");
				osd_canvas.height("100%");
			});

			var failDict = {imageJson: imageJson};
			this.viewer.addHandler('open-failed', function(inputDict) {
				// If the tiles are not there or not ready, then open the raw image
				xgds_image.showRawImage(inputDict.userData.imageJson);
			}, failDict);

			this.viewer.addHandler('tile-load-failed', function(inputDict) {
				// If the tiles are not there or not ready, then open the raw image
				// do not expect the data here
				xgds_image.showRawImage(inputDict.userData.imageJson);
			}, failDict);

			// add a handler for rotation that saves the rotation degrees to the database.
			var context = this;
			this.viewer.addHandler('rotate', function(viewer) {
				if (context.viewer['viewer_initialized'] != true) {
					var element = viewer.eventSource.element;
					var degrees = viewer.degrees;
					var userData = viewer.userData;
					// save the rotation to the db.
					context.saveRotationDegrees(imageJson, degrees);
				} else { // viewer is initialized.
					// set the initialized flag to false
					context.viewer['viewer_initialized'] = false
				}

			});
			xgds_image_annotation.initialize(imageJson, this.viewer);
		} catch (err) {
			console.log(err);
		}
	},
	resizeImageViewer: function(element) {
		// when viewDiv resize,
		// element is the view-div
		var element = $(element);

		var newWidth = element.width();
		var newHeight = element.height();

		var wrapper = element.find('.image-wrapper');
		wrapper.width(newWidth);
		wrapper.height(newHeight);

		var osd_viewer = wrapper.find('#display-image');
		osd_viewer.width(newWidth);
		osd_viewer.height(newHeight);

		var osd_canvas = osd_viewer.find('.openseadragon-canvas');
		osd_canvas.width(newWidth);
		osd_canvas.height(newHeight);
	},
	setSaveStatusMessage: function(handler, status, msg){
		if (status == 'success') {
			handler.attr('class', 'success-message');
		} else {
			handler.attr('class', 'error-message');
		}
		handler.html(msg);
		setTimeout(function() { // messages fades out.
			handler.fadeOut().empty();
		}, 5000);
	}
});
<commit_msg>Commted out code that checks if image is tiled--instead, always showRawImage()<commit_after>//__BEGIN_LICENSE__
// Copyright (c) 2015, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The xGDS platform is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//__END_LICENSE__

var xgds_image = xgds_image || {};

$.extend(xgds_image,{
	hookDelete: function() {
		// Add a click handler for the delete row
//		$('#delete_images').click( function() {
//		    var selectedRows = getSelectedRows( theDataTable );
//		    // get a list containing just the id's of selected images
//		    var selectedImageIdsList = jQuery.map(selectedRows, function(element) { return jQuery(element).attr('pk'); });
//		    var selectedImageIdsJson = {"pk": selectedImageIdsList};
//			//delete selected images from db
//		    var url = deleteImagesUrl;
//		    $.ajax({
//				url: url,
//				type: "POST",
//				data: selectedImageIdsJson, // serializes the form's elements.
//				success: function(data) {
//					console.log("images successfully deleted");
//				},
//				error: function(request, status, error) {
//					console.log("error! ", error);
//				}
//			})
//
//			// delete selected rows from datatable.
//		    for (var i = 0; i < selectedRows.length; i++) {
//		        theDataTable.fnDeleteRow(selectedRows[i]);
//		    }
//		    // re-render the map icons with only the non-deleted images.
//		    showOnMap(theDataTable.fnGetData());
//		} );
	},
	activateButtons: function(el) {
		// Hook up edit info and add note buttons
		el.find("#edit_info_button").click(function(event) {
		    event.preventDefault();
		    el.find("#image_overview").hide();
		    el.find("#more_info_view").show();
		});
		el.find("#cancel_edit").click(function(event) {
		    event.preventDefault();
		    el.find("#more_info_view").hide();
		    el.find("#image_overview").show();
		});
		el.find(".add_note_button").click(function(event) {
		    event.preventDefault();
		    el.find("#notes_input").show();
		});
	},
	onImageNextOrPrev: function(el){
		el.find('.next-button').click(function(event) {
			// set the img src
			var index = xgds_image.getCurrentImageAndIndex(el);
			if (index != null) {
			    index = index + 1;
			    if (index == imageSetsArray.length){
			    	index = 0;
			    }
			    clearTableSelection(theDataTable);
			    xgds_image.updateImageView(el, null, index, false, false);
			}
		});
		el.find(".prev-button").click(function(event) {
			var index = xgds_image.getCurrentImageAndIndex(el);
			if (index != null) {
			    index = index - 1;
			    if (index < 0){
				index = imageSetsArray.length - 1;
			    }
			    clearTableSelection(theDataTable);
			    xgds_image.updateImageView(el, null, index, false, false);
			}
		});
	},
	setChangedPosition: function(value, el){
		$(el).find('#id_changed_position').attr('value', value);
	},
	hookEditingPosition: function(el){
		// Set the changed_position to true if the user edits any of the position fields.
		$(el).find("#id_latitude").change(function() {setChangedPosition(1, el)});
		$(el).find("#id_longitude").change(function() {setChangedPosition(1, el)});
		$(el).find("#id_altitude").change(function() {setChangedPosition(1, el)});
		$(el).find("#id_heading").change(function() {setChangedPosition(1, el)});
	},
	onUpdateImageInfo: function(el) {
		// Saves image info to the db when user updates it and submits.
		$(el).find("#updateInfoSubmit").on('click', function(event) {
			event.preventDefault(); 	// avoid to execute the actual submit of the form.
			var url = updateImageUrl; // the script where you handle the form input.
			var postData = $("#more-info-form").serialize();
			$.ajax({
				url: url,
				type: "POST",
				data: postData, // serializes the form's elements.
				success: function(data)
				{
				    xgds_image.setSaveStatusMessage($('#message'), 'Saved','');
				    xgds_image.updateImageView(el, data[0], undefined, true, true);
				    el.find("#more_info_view").hide();
				    el.find("#image_overview").show();
				},
				error: function(request, status, error) {
				    xgds_image.setSaveStatusMessage($('#message'), status, error);
				}
			});
			return false;
		});
	},
	getCurrentImageAndIndex: function(el){
		// Helper that finds index in imageSetsArray
		// of the currently displayed image in the imageView.
		var currentImageName = el.attr('pk');
		var currentImageIndex = null;
		for (var i=0; i< imageSetsArray.length; i++) {
			if (imageSetsArray[i]['name'] == currentImageName) {
				currentImageIndex = i;
				break;
			}
		}
		return currentImageIndex;
	},
	stopTiles: function() {
		if (!_.isUndefined(this.viewer)){
			this.viewer._cancelPendingImages();
		}
	},
	updateImageView: function(el, imageJson, index, keepingImage, keepingNotes) {
		if (imageJson == null){
			if (index != null) {
				imageJson = imageSetsArray[index];
			} else {
				return;
			}
		}

		if (!keepingNotes){
			var tbl = el.find('table.notes_list');
			xgds_notes.initializeNotesReference(el, imageJson['app_label'], imageJson['model_type'], imageJson['pk'], imageJson['acquisition_time'], imageJson['acquisition_timezone']);
			xgds_notes.getNotesForObject(imageJson['app_label'], imageJson['model_type'], imageJson['pk'], 'notes_content', tbl);
		}

		var newContent = this.compiledTemplate(imageJson);
		$(el).html(newContent);

		if (!keepingImage){
			this.setupImageViewer(imageJson);
	    }
	},
	constructImageView: function(imageJson) {
		var modelMap = app.options.searchModels['Photo'];
		var url = '/xgds_core/handlebar_string/' + modelMap.viewHandlebars;
		$.when($.get(url, function(handlebarSource, status){
			app.showDetailView(handlebarSource, imageJson, modelMap, 'Photo');
		}));
	},
	loadImageInViewer: function(imageJson){
		this.setupImageViewer(imageJson);
	},
	hideImageNextPrev: function() {
		$('.prev-button').hide();
		$('.next-button').hide();
		$('#new-window-btn').hide();
	},
	saveRotationDegrees: function(imageJson, degrees) {
		// save rotation degrees to the database
		imageJson['rotation_degrees'] = degrees;
		var postData = imageJson;
		var url = app.options.searchModels.Photo.saveRotationUrl;
		// get rotation degrees from db, compare to degrees.
		// this gets called when user switches the view to another image.
		// call ajax to save the rotation degrees.
		$.ajax({
			url: url,
			type: "POST",
			data: postData, // serializes the form's elements.
			success: function(data) {
			},
			error: function(request, status, error) {
				//console.log("error! ", error)
			}
		});
	},
	setOpenseadragonRotation: function(osd_viewer, imagePK){
		var getData = {'imagePK': imagePK };
		var url = app.options.searchModels.Photo.getRotationUrl;
		$.ajax({
			url: url,
			type: "POST",
			data: getData, // serializes the form's elements.
			success: function(data) {
				osd_viewer.viewport.setRotation(data['rotation_degrees'])
			},
			error: function(request, status, error) {
				console.log("error! ", error);
			}
		});
	},
	removeViewer: function() {
		if (!_.isUndefined(this.viewer)){
			this.viewer._cancelPendingImages();
			this.viewer.destroy();
			this.viewer = undefined;
		}
	},
	showRawImage: function(imageJson){
		var rawImage = imageJson.raw_image_url;
		this.removeViewer();
		try {
			$(".openseadragon-container").hide();
		} catch (err){
			// pass
		}
		$('#display-image').prepend('<img id="raw-image" src="' + rawImage + '" />');
	},
	setupImageViewer: function(imageJson){
		if (this.viewer != undefined){
			//TODO this should really be appropriate but somehow updateContents is being triggered many times
//			if (this.viewer.imageJson.pk == imageJson.pk){
//				return;
//			}
			this.removeViewer();
			//TODO WILLIAM put in some clearAnnotations
		}
		// try removing the raw image
		try {
			$("#raw-image").remove();  // or destroy();
		} catch (err) {
			//pass
		}

		var tiledImage = imageJson.deepzoom_file_url;

		if (imageJson.create_deepzoom || _.isEmpty(tiledImage)){
			// tiles are not ready yet, let's make sure:
			$.ajax({
				  dataType: "json",
				  url: '/xgds_image/checkTiles/' + imageJson.pk,
				  success: function(data) {
					  imageJson.create_deepzoom = data.create_deepzoom;
					  imageJson.deepzoom_file_url = data.deepzoom_file_url;
					  tiledImage = data.deepzoom_file_url;
				  },
				  error: function(){
					  // use the old state
				  },
				  async: false
				});

			/* Hardcore showRawImage (don't check if image is tiled) */
			// if (imageJson.create_deepzoom || _.isEmpty(tiledImage)){
			this.showRawImage(imageJson);
			return;
			//}
		}

		// build tile sources for openseadragon image viewer
		var prefixUrl = '/static/openseadragon/built-openseadragon/openseadragon/images/';
		try {
			var displayImage = $('#display-image');
			if (displayImage.length == 0){
				throw ('Cound not find display-image div');
			} else {
				displayImage = displayImage[0];
			}
			this.viewer = OpenSeadragon({
				element: displayImage,
//				id: "display-image",
				prefixUrl: prefixUrl,
				tileSources: tiledImage,
			    showRotationControl: true,
			    imageJson: imageJson,
			 	gestureSettingsMouse:   {
 	            	clickToZoom: false
 		        }
			});
			this.viewer['viewer_initialized'] = true;
			this.setOpenseadragonRotation(this.viewer, imageJson['pk']);

			// Add handlers for full-screen event and rotation event.
			this.viewer.addHandler('full-screen', function (viewer) {
				// grab the canvas from the viewer and reset the size.
				var element = viewer.eventSource.element; // #display-image
				var osd_canvas = $(element).find('.openseadragon-canvas'); // somehow change the style -- test with funky values.
				osd_canvas.width("100%");
				osd_canvas.height("100%");
			});

			var failDict = {imageJson: imageJson};
			this.viewer.addHandler('open-failed', function(inputDict) {
				// If the tiles are not there or not ready, then open the raw image
				xgds_image.showRawImage(inputDict.userData.imageJson);
			}, failDict);

			this.viewer.addHandler('tile-load-failed', function(inputDict) {
				// If the tiles are not there or not ready, then open the raw image
				// do not expect the data here
				xgds_image.showRawImage(inputDict.userData.imageJson);
			}, failDict);

			// add a handler for rotation that saves the rotation degrees to the database.
			var context = this;
			this.viewer.addHandler('rotate', function(viewer) {
				if (context.viewer['viewer_initialized'] != true) {
					var element = viewer.eventSource.element;
					var degrees = viewer.degrees;
					var userData = viewer.userData;
					// save the rotation to the db.
					context.saveRotationDegrees(imageJson, degrees);
				} else { // viewer is initialized.
					// set the initialized flag to false
					context.viewer['viewer_initialized'] = false
				}

			});
			xgds_image_annotation.initialize(imageJson, this.viewer);
		} catch (err) {
			console.log(err);
		}
	},
	resizeImageViewer: function(element) {
		// when viewDiv resize,
		// element is the view-div
		var element = $(element);

		var newWidth = element.width();
		var newHeight = element.height();

		var wrapper = element.find('.image-wrapper');
		wrapper.width(newWidth);
		wrapper.height(newHeight);

		var osd_viewer = wrapper.find('#display-image');
		osd_viewer.width(newWidth);
		osd_viewer.height(newHeight);

		var osd_canvas = osd_viewer.find('.openseadragon-canvas');
		osd_canvas.width(newWidth);
		osd_canvas.height(newHeight);
	},
	setSaveStatusMessage: function(handler, status, msg){
		if (status == 'success') {
			handler.attr('class', 'success-message');
		} else {
			handler.attr('class', 'error-message');
		}
		handler.html(msg);
		setTimeout(function() { // messages fades out.
			handler.fadeOut().empty();
		}, 5000);
	}
});
<|endoftext|>


<commit_before>const assert = require('assert');

const { makeS3Request } = require('../utils/makeRequest');

const authCredentials = {
    accessKey: 'accessKey1',
    secretKey: 'verySecretKey1',
};
const bucket = 'rawnodeapibucket';

describe.only('api tests', () => {
    before(() => {
        makeS3Request({
            method: 'PUT',
            authCredentials,
            bucket,
        }, err => {
            assert.ifError(err);
        });
    });

    after(() => {
        makeS3Request({
            method: 'DELETE',
            authCredentials,
            bucket,
        }, err => {
            assert.ifError(err);
        });
    });

    it('should return 405 on headBucket when bucket is empty string', done => {
        makeS3Request({
            method: 'HEAD',
            authCredentials,
            bucket: '',
        }, (err, res) => {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 405);
            return done();
        });
    });
});
<commit_msg>bf: ZENKO-2729 remove .only from raw-node tests<commit_after>const assert = require('assert');

const { makeS3Request } = require('../utils/makeRequest');

const authCredentials = {
    accessKey: 'accessKey1',
    secretKey: 'verySecretKey1',
};
const bucket = 'rawnodeapibucket';

describe('api tests', () => {
    before(() => {
        makeS3Request({
            method: 'PUT',
            authCredentials,
            bucket,
        }, err => {
            assert.ifError(err);
        });
    });

    after(() => {
        makeS3Request({
            method: 'DELETE',
            authCredentials,
            bucket,
        }, err => {
            assert.ifError(err);
        });
    });

    it('should return 405 on headBucket when bucket is empty string', done => {
        makeS3Request({
            method: 'HEAD',
            authCredentials,
            bucket: '',
        }, (err, res) => {
            assert.ifError(err);
            assert.strictEqual(res.statusCode, 405);
            return done();
        });
    });
});
<|endoftext|>


<commit_before>// The MESSAGE event runs anytime a message is received
// Note that due to the binding of client to every event, every event
// goes `client, other, args` when this function is run.

module.exports = (client, message) => {
  // It's good practice to ignore other bots. This also makes your bot ignore itself
  // and not get into a spam loop (we call that "botception").
  if (message.author.bot) return;

  // Grab the settings for this server from the PersistentCollection
  const settings = client.settings.get(message.guild.id);

  // For ease of use in commands and functions, we'll attach the settings
  // to the message object, so `message.settings` is accessible.
  message.settings = settings;

  // Also good practice to ignore any message that does not start with our prefix,
  // which is set in the configuration file.
  if (message.content.indexOf(settings.prefix) !== 0) return;

  // Here we separate our "command" name, and our "arguments" for the command.
  // e.g. if we have the message "+say Is this the real life?" , we'll get the following:
  // command = say
  // args = ["Is", "this", "the", "real", "life?"]
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  // Get the user or member's permission level from the elevation
  const level = client.permlevel(message);

  // Check whether the command, or alias, exist in the collections defined
  // in app.js.
  const cmd = client.commands.get(command) || client.commands.get(client.aliases.get(command));
  // using this const varName = thing OR otherthign; is a pretty efficient
  // and clean way to grab one of 2 values!

  // If the command exists, **AND** the user has permission, run it.
  if (cmd && level >= cmd.conf.permLevel) {
    client.log("log", `${message.guild.name}/#${message.channel.name}:
      ${message.author.username} (${message.author.id}) ran command ${cmd.help.name}`, "CMD");
    cmd.run(client, message, args, level);
  }
  // Best Practice: **do not** reply with a message if the command does
  // not exist, or permissions lack.
};
<commit_msg>Fixed message event<commit_after>// The MESSAGE event runs anytime a message is received
// Note that due to the binding of client to every event, every event
// goes `client, other, args` when this function is run.

module.exports = (client, message) => {
  // It's good practice to ignore other bots. This also makes your bot ignore itself
  // and not get into a spam loop (we call that "botception").
  if (message.author.bot) return;

  // Grab the settings for this server from the PersistentCollection
  const settings = client.settings.get(message.guild.id);

  // For ease of use in commands and functions, we'll attach the settings
  // to the message object, so `message.settings` is accessible.
  message.settings = settings;

  // Also good practice to ignore any message that does not start with our prefix,
  // which is set in the configuration file.
  if (message.content.indexOf(settings.prefix) !== 0) return;

  // Here we separate our "command" name, and our "arguments" for the command.
  // e.g. if we have the message "+say Is this the real life?" , we'll get the following:
  // command = say
  // args = ["Is", "this", "the", "real", "life?"]
  const args = message.content.slice(settings.prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  // Get the user or member's permission level from the elevation
  const level = client.permlevel(message);

  // Check whether the command, or alias, exist in the collections defined
  // in app.js.
  const cmd = client.commands.get(command) || client.commands.get(client.aliases.get(command));
  // using this const varName = thing OR otherthign; is a pretty efficient
  // and clean way to grab one of 2 values!

  // If the command exists, **AND** the user has permission, run it.
  if (cmd && level >= cmd.conf.permLevel) {
    client.log("log", `${message.guild.name}/#${message.channel.name}:
      ${message.author.username} (${message.author.id}) ran command ${cmd.help.name}`, "CMD");
    cmd.run(client, message, args, level);
  }
  // Best Practice: **do not** reply with a message if the command does
  // not exist, or permissions lack.
};
<|endoftext|>


<commit_before>var os = require("os");

module.exports = {};

switch (os.hostname()) {
    case "Tim-PC":
        module.exports = {
        	url: "localhost",
            port: "3000"
        };
        break;
    case "www":
        module.exports = {
        	url: "198.91.86.144",
            port: "3000"
        };
        break;
    default:
        module.exports = {
            url: "198.91.86.144",
            port: "3000"
        };
        //throw new Error("Unknown host");
}<commit_msg>added new host settings<commit_after>var os = require("os");

module.exports = {};

switch (os.hostname()) {
    case "Tim-PC":
        module.exports = {
        	url: "localhost",
            port: "3000"
        };
        break;
    case "bzdbbb":
        module.exports = {
        	url: "www.bzdbbb.co.uk",
            port: "80"
        };
        break;
    default:
        module.exports = {
            url: "198.91.86.144",
            port: "3000"
        };
        //throw new Error("Unknown host");
}<|endoftext|>


<commit_before>import { defineMessages } from 'react-intl';

const translations = defineMessages({
  surveys: {
    id: 'course.surveys',
    defaultMessage: 'Surveys',
  },
  title: {
    id: 'course.surveys.fields.title',
    defaultMessage: 'Title',
  },
  description: {
    id: 'course.surveys.fields.description',
    defaultMessage: 'Description',
  },
  opensAt: {
    id: 'course.surveys.fields.openAt',
    defaultMessage: 'Opens At',
  },
  expiresAt: {
    id: 'course.surveys.fields.expiresAt',
    defaultMessage: 'Expires At',
  },
  closingRemindedAt: {
    id: 'course.surveys.fields.closingRemindedAt',
    defaultMessage: 'Last Reminder Sent At',
  },
  anonymous: {
    id: 'course.surveys.fields.anonymous',
    defaultMessage: 'Anonymous',
  },
  allowResponseAfterEnd: {
    id: 'course.surveys.fields.allowResponseAfterEnd',
    defaultMessage: 'Allow Responses After Survey Expires',
  },
  allowModifyAfterSubmit: {
    id: 'course.surveys.fields.allowModifyAfterSubmit',
    defaultMessage: 'Allow Submitted Responses To Be Modified',
  },
  basePoints: {
    id: 'course.surveys.fields.basePoints',
    defaultMessage: 'Base Points',
  },
  bonusPoints: {
    id: 'course.surveys.fields.bonusPoints',
    defaultMessage: 'Bonus Points',
  },
  published: {
    id: 'course.surveys.fields.published',
    defaultMessage: 'Published',
  },
  questionText: {
    id: 'course.surveys.questionText',
    defaultMessage: 'Question Text',
  },
  questions: {
    id: 'course.surveys.questions',
    defaultMessage: 'Questions',
  },
  questionType: {
    id: 'course.surveys.questions.fields.questionType',
    defaultMessage: 'Question Type',
  },
  textResponse: {
    id: 'course.surveys.questions.fields.questionTypes.textResponse',
    defaultMessage: 'Text Response Question',
  },
  multipleChoice: {
    id: 'course.surveys.questions.fields.questionTypes.multipleChoice',
    defaultMessage: 'Mulitple Choice Question',
  },
  multipleResponse: {
    id: 'course.surveys.questions.fields.questionTypes.multipleResponse',
    defaultMessage: 'Mulitple Response Question',
  },
  maxOptions: {
    id: 'course.surveys.questions.fields.maxOptions',
    defaultMessage: 'Maximum Allowed Responses',
  },
  minOptions: {
    id: 'course.surveys.questions.fields.minOptions',
    defaultMessage: 'Minimum Allowed Responses',
  },
  updateSuccess: {
    id: 'course.surveys.updateSuccess',
    defaultMessage: 'Survey "{title}" updated.',
  },
  updateFailure: {
    id: 'course.surveys.updateFailure',
    defaultMessage: 'Failed to update survey.',
  },
  deleteSuccess: {
    id: 'course.surveys.deleteSuccess',
    defaultMessage: 'Survey "{title}" deleted.',
  },
  deleteFailure: {
    id: 'course.surveys.deleteFailure',
    defaultMessage: 'Failed to delete survey.',
  },
  results: {
    id: 'course.surveys.results',
    defaultMessage: 'Results',
  },
  responses: {
    id: 'course.surveys.responses',
    defaultMessage: 'Responses',
  },
});

export default translations;
<commit_msg>Fix typo for survey question types<commit_after>import { defineMessages } from 'react-intl';

const translations = defineMessages({
  surveys: {
    id: 'course.surveys',
    defaultMessage: 'Surveys',
  },
  title: {
    id: 'course.surveys.fields.title',
    defaultMessage: 'Title',
  },
  description: {
    id: 'course.surveys.fields.description',
    defaultMessage: 'Description',
  },
  opensAt: {
    id: 'course.surveys.fields.openAt',
    defaultMessage: 'Opens At',
  },
  expiresAt: {
    id: 'course.surveys.fields.expiresAt',
    defaultMessage: 'Expires At',
  },
  closingRemindedAt: {
    id: 'course.surveys.fields.closingRemindedAt',
    defaultMessage: 'Last Reminder Sent At',
  },
  anonymous: {
    id: 'course.surveys.fields.anonymous',
    defaultMessage: 'Anonymous',
  },
  allowResponseAfterEnd: {
    id: 'course.surveys.fields.allowResponseAfterEnd',
    defaultMessage: 'Allow Responses After Survey Expires',
  },
  allowModifyAfterSubmit: {
    id: 'course.surveys.fields.allowModifyAfterSubmit',
    defaultMessage: 'Allow Submitted Responses To Be Modified',
  },
  basePoints: {
    id: 'course.surveys.fields.basePoints',
    defaultMessage: 'Base Points',
  },
  bonusPoints: {
    id: 'course.surveys.fields.bonusPoints',
    defaultMessage: 'Bonus Points',
  },
  published: {
    id: 'course.surveys.fields.published',
    defaultMessage: 'Published',
  },
  questionText: {
    id: 'course.surveys.questionText',
    defaultMessage: 'Question Text',
  },
  questions: {
    id: 'course.surveys.questions',
    defaultMessage: 'Questions',
  },
  questionType: {
    id: 'course.surveys.questions.fields.questionType',
    defaultMessage: 'Question Type',
  },
  textResponse: {
    id: 'course.surveys.questions.fields.questionTypes.textResponse',
    defaultMessage: 'Text Response Question',
  },
  multipleChoice: {
    id: 'course.surveys.questions.fields.questionTypes.multipleChoice',
    defaultMessage: 'Multiple Choice Question',
  },
  multipleResponse: {
    id: 'course.surveys.questions.fields.questionTypes.multipleResponse',
    defaultMessage: 'Multiple Response Question',
  },
  maxOptions: {
    id: 'course.surveys.questions.fields.maxOptions',
    defaultMessage: 'Maximum Allowed Responses',
  },
  minOptions: {
    id: 'course.surveys.questions.fields.minOptions',
    defaultMessage: 'Minimum Allowed Responses',
  },
  updateSuccess: {
    id: 'course.surveys.updateSuccess',
    defaultMessage: 'Survey "{title}" updated.',
  },
  updateFailure: {
    id: 'course.surveys.updateFailure',
    defaultMessage: 'Failed to update survey.',
  },
  deleteSuccess: {
    id: 'course.surveys.deleteSuccess',
    defaultMessage: 'Survey "{title}" deleted.',
  },
  deleteFailure: {
    id: 'course.surveys.deleteFailure',
    defaultMessage: 'Failed to delete survey.',
  },
  results: {
    id: 'course.surveys.results',
    defaultMessage: 'Results',
  },
  responses: {
    id: 'course.surveys.responses',
    defaultMessage: 'Responses',
  },
});

export default translations;
<|endoftext|>


<commit_before>(function () {
    'use strict';
    angular
        .module('app.form')
        .controller('indFormController', indFormController);

    function indFormController() {
        console.log('load indFormController');
        var vm = this;

        function setIndividualForm() {
            vm.resultsShown = null;
            vm.form = {
                premium: 0,
                deductible: 0,
                copay: 0,
                expenses: 0,
                income: 0,
                SS: 0,
                gross: 0,
                you: {
                    receiveSS: 0,
                    monthlySS: 0,
                    retirement: 0,
                    age: null
                },
                spouse: {
                    receiveSS: 0,
                    monthlySS: 0,
                    retirement: 0,
                    age: null
                }
            };
            vm.other = 0;
            vm.social = 0;
            vm.medicaid = 0;
            vm.medicare = 0;
            vm.filing = 0;
            vm.results = {
                you: {
                    annualSS: 0,
                    applicableSS: 0,
                    applicableRet: 0,
                    postApplicableRet: 0,
                    SSRetirementIncome: 0,
                    calcRetirement: 0,
                    healthcareCost: 0,
                    CCCost: 0,
                    savings: 0
                },
                spouse: {
                    annualSS: 0,
                    applicableSS: 0,
                    applicableRet: 0,
                    postApplicableRet: 0,
                    SSRetirementIncome: 0,
                    calcRetirement: 0,
                    healthcareCost: 0,
                    CCCost: 0,
                    savings: 0
                },
                joint: {
                    applicableSS: 0,
                    SSRetirementIncome: 0
                }

            };
            vm.result1 = 0;
            vm.result2 = 0;
            vm.result3 = 0;
            vm.difference = 0;
            vm.resultFiling = 0;
        }

        setIndividualForm();

        var baseCalculation = function baseCalculation() {
            var results = vm.form.premium * 12 + vm.form.deductible + vm.form.copay + vm.form.expenses;
            console.log('baseCalculation return', results);
            return results;
        };

        var indDeduction = function indDeduction(a, b) {
            return (12 * a) - 9000 + b;
        };

        var jointDeduction = function jointDeduction(a, b, c) {
            console.log('Check a', a);
            console.log('check b', b);
            console.log('check c', c);
            return (12 * a) - a / (c + a) * 12000 + b;
        };

        var singleCalculation = function singleCalculation() {
            var individualDeductionFinal = indDeduction(vm.form.you.monthlySS, vm.form.you.retirement);
            console.log('individualDeductionFinal', individualDeductionFinal);
            if (vm.other && vm.social && vm.form.you.age === 'under65') {
                if (individualDeductionFinal > 20000) {
                    individualDeductionFinal = 20000;
                }
                return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - individualDeductionFinal));
            }
            else if (vm.other && vm.social && vm.form.you.age === 'over65') {
                if (individualDeductionFinal > 24000) {
                    individualDeductionFinal = 24000;
                }
                return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - individualDeductionFinal));
            }
        };
        var jointCalculation = function jointCalculation() {
            var jointDeductionFinalYou = jointDeduction(vm.form.you.monthlySS, vm.form.you.retirement, vm.form.spouse.monthlySS);
            var jointDeductionFinalSpouse = jointDeduction(vm.form.spouse.monthlySS, vm.form.spouse.retirement, vm.form.you.monthlySS);
            console.log('jointDeductionFinalYou', jointDeductionFinalYou);
            console.log('jointDeductionFinalSpouse', jointDeductionFinalSpouse);
            if (vm.other && vm.social && !vm.form.you.age) {
                jointDeductionFinalYou = 0;
                vm.resultJointYou = jointDeductionFinalYou;
            }
            else if (vm.other && vm.social && vm.form.you.age === 'under65' && jointDeductionFinalYou > 20000) {
                jointDeductionFinalYou = 20000;
                //console.log('over 20000 for you', jointDeductionFinalYou);
                vm.resultJointYou = jointDeductionFinalYou;
            }
            else if (vm.other && vm.social && vm.form.you.age === 'over65' && jointDeductionFinalYou > 24000) {
                jointDeductionFinalYou = 24000;
                //console.log('over 24000 for you', jointDeductionFinalYou);
                vm.resultJointYou = jointDeductionFinalYou;
            }

            if (vm.other && vm.social && !vm.form.spouse.age) {
                jointDeductionFinalSpouse = 0;
                vm.resultJointSpouse = jointDeductionFinalSpouse;
            }
            else if (vm.other && vm.social && vm.form.spouse.age === 'under65' && jointDeductionFinalSpouse > 20000) {
                jointDeductionFinalSpouse = 20000;
                //console.log('over 20000 for spouse', jointDeductionFinalSpouse);
                vm.resultJointSpouse = jointDeductionFinalSpouse;
            }
            else if (vm.other && vm.social && vm.form.spouse.age === 'over65' && jointDeductionFinalSpouse > 24000) {
                jointDeductionFinalSpouse = 24000;
                //console.log('over 24000 for spouse', jointDeductionFinalSpouse);
                vm.resultJointSpouse = jointDeductionFinalSpouse;
            }
            //console.log('Check you final', jointDeductionFinalYou);
            //console.log('Check spouse final', jointDeductionFinalSpouse);
            vm.resultJointFinal = (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - jointDeductionFinalYou - jointDeductionFinalSpouse));
            return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - jointDeductionFinalYou - jointDeductionFinalSpouse));
        };

        vm.calculate = function calculate() {
            console.log('Running individual calculation');
            vm.resultsShown = true;
            var sum1 = baseCalculation();
            vm.result1 = sum1.toFixed(2);
            if (!vm.result1) {
                vm.result1 = 'There has been an error calculating the result.  Please notify the webmaster';
            }

            var sum2 = 0;
            if (!vm.other && !vm.social) {
                sum2 = vm.form.income * 0.0333;
                vm.result2 = sum2.toFixed(2);
            }
            else if (vm.other && !vm.social) {
                sum2 = (vm.form.income * 0.0333) + (0.10 * vm.form.gross);
                vm.result2 = sum2.toFixed(2);
            }
            else if (vm.other && vm.social && vm.filing === 'single') {
                sum2 = singleCalculation();
                if (sum2 > 35000) {
                    sum2 = 35000.00;
                    vm.result2 = sum2.toFixed(2);
                }
                else if (sum2 < 0) {
                    sum2 = 0;
                    vm.result2 = sum2.toFixed(2);
                }
                else {
                    vm.result2 = sum2.toFixed(2);
                }
            }
            else if (vm.other && vm.social && vm.filing === 'joint') {
                sum2 = jointCalculation();
                if (sum2 < 0) {
                    sum2 = 0;
                    vm.result2 = sum2.toFixed(2);
                }
                else if (sum2 > 45000) {
                    sum2 = 45000;
                    vm.result2 = sum2.toFixed(2);
                }
                else {
                    vm.result2 = sum2.toFixed(2);
                }

            }
            if (!vm.result2) {
                vm.result2 = 'There has been an error calculating the result.  Please notify the webmaster';
            }

            var sum3 = vm.result1 - vm.result2;
            vm.difference = sum3.toFixed(2);
            if (!vm.difference) {
                vm.difference = 'There has been an error calculating the result.  Please notify the webmaster';
            }
        };

        vm.clear = function clear() {
            setIndividualForm();
        };
    }
})();<commit_msg>fix calculator max for non-payroll income<commit_after>(function () {
    'use strict';
    angular
        .module('app.form')
        .controller('indFormController', indFormController);

    function indFormController() {
        console.log('load indFormController');
        var vm = this;

        function setIndividualForm() {
            vm.resultsShown = null;
            vm.form = {
                premium: 0,
                deductible: 0,
                copay: 0,
                expenses: 0,
                income: 0,
                SS: 0,
                gross: 0,
                you: {
                    receiveSS: 0,
                    monthlySS: 0,
                    retirement: 0,
                    age: null
                },
                spouse: {
                    receiveSS: 0,
                    monthlySS: 0,
                    retirement: 0,
                    age: null
                }
            };
            vm.other = 0;
            vm.social = 0;
            vm.medicaid = 0;
            vm.medicare = 0;
            vm.filing = 0;
            vm.results = {
                you: {
                    annualSS: 0,
                    applicableSS: 0,
                    applicableRet: 0,
                    postApplicableRet: 0,
                    SSRetirementIncome: 0,
                    calcRetirement: 0,
                    healthcareCost: 0,
                    CCCost: 0,
                    savings: 0
                },
                spouse: {
                    annualSS: 0,
                    applicableSS: 0,
                    applicableRet: 0,
                    postApplicableRet: 0,
                    SSRetirementIncome: 0,
                    calcRetirement: 0,
                    healthcareCost: 0,
                    CCCost: 0,
                    savings: 0
                },
                joint: {
                    applicableSS: 0,
                    SSRetirementIncome: 0
                }

            };
            vm.result1 = 0;
            vm.result2 = 0;
            vm.result3 = 0;
            vm.difference = 0;
            vm.resultFiling = 0;
        }

        setIndividualForm();

        var baseCalculation = function baseCalculation() {
            var results = vm.form.premium * 12 + vm.form.deductible + vm.form.copay + vm.form.expenses;
            console.log('baseCalculation return', results);
            return results;
        };

        var indDeduction = function indDeduction(a, b) {
            return (12 * a) - 9000 + b;
        };

        var jointDeduction = function jointDeduction(a, b, c) {
            console.log('Check a', a);
            console.log('check b', b);
            console.log('check c', c);
            return (12 * a) - a / (c + a) * 12000 + b;
        };

        var singleCalculation = function singleCalculation() {
            var individualDeductionFinal = indDeduction(vm.form.you.monthlySS, vm.form.you.retirement);
            console.log('individualDeductionFinal', individualDeductionFinal);
            if(vm.form.gross > 350000 - vm.form.income){
                vm.form.gross =  350000 - vm.form.income;
                if (vm.other && vm.social && vm.form.you.age === 'under65') {
                    if (individualDeductionFinal > 20000) {
                        individualDeductionFinal = 20000;
                    }
                    return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - individualDeductionFinal));
                }
                else if (vm.other && vm.social && vm.form.you.age === 'over65') {
                    if (individualDeductionFinal > 24000) {
                        individualDeductionFinal = 24000;
                    }
                    return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - individualDeductionFinal));
                }
            }
            else {
                if (vm.other && vm.social && vm.form.you.age === 'under65') {
                    if (individualDeductionFinal > 20000) {
                        individualDeductionFinal = 20000;
                    }
                    return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - individualDeductionFinal));
                }
                else if (vm.other && vm.social && vm.form.you.age === 'over65') {
                    if (individualDeductionFinal > 24000) {
                        individualDeductionFinal = 24000;
                    }
                    return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - individualDeductionFinal));
                }
            }
        };
        var jointCalculation = function jointCalculation() {
            var jointDeductionFinalYou = jointDeduction(vm.form.you.monthlySS, vm.form.you.retirement, vm.form.spouse.monthlySS);
            var jointDeductionFinalSpouse = jointDeduction(vm.form.spouse.monthlySS, vm.form.spouse.retirement, vm.form.you.monthlySS);
            console.log('jointDeductionFinalYou', jointDeductionFinalYou);
            console.log('jointDeductionFinalSpouse', jointDeductionFinalSpouse);
            if (vm.other && vm.social && !vm.form.you.age) {
                jointDeductionFinalYou = 0;
                vm.resultJointYou = jointDeductionFinalYou;
            }
            else if (vm.other && vm.social && vm.form.you.age === 'under65' && jointDeductionFinalYou > 20000) {
                jointDeductionFinalYou = 20000;
                //console.log('over 20000 for you', jointDeductionFinalYou);
                vm.resultJointYou = jointDeductionFinalYou;
            }
            else if (vm.other && vm.social && vm.form.you.age === 'over65' && jointDeductionFinalYou > 24000) {
                jointDeductionFinalYou = 24000;
                //console.log('over 24000 for you', jointDeductionFinalYou);
                vm.resultJointYou = jointDeductionFinalYou;
            }

            if (vm.other && vm.social && !vm.form.spouse.age) {
                jointDeductionFinalSpouse = 0;
                vm.resultJointSpouse = jointDeductionFinalSpouse;
            }
            else if (vm.other && vm.social && vm.form.spouse.age === 'under65' && jointDeductionFinalSpouse > 20000) {
                jointDeductionFinalSpouse = 20000;
                //console.log('over 20000 for spouse', jointDeductionFinalSpouse);
                vm.resultJointSpouse = jointDeductionFinalSpouse;
            }
            else if (vm.other && vm.social && vm.form.spouse.age === 'over65' && jointDeductionFinalSpouse > 24000) {
                jointDeductionFinalSpouse = 24000;
                //console.log('over 24000 for spouse', jointDeductionFinalSpouse);
                vm.resultJointSpouse = jointDeductionFinalSpouse;
            }
            //console.log('Check you final', jointDeductionFinalYou);
            //console.log('Check spouse final', jointDeductionFinalSpouse);
            vm.resultJointFinal = (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - jointDeductionFinalYou - jointDeductionFinalSpouse));
            return (vm.form.income * 0.0333) + (0.10 * (vm.form.gross - jointDeductionFinalYou - jointDeductionFinalSpouse));
        };

        vm.calculate = function calculate() {
            console.log('Running individual calculation');
            vm.resultsShown = true;
            var sum1 = baseCalculation();
            vm.result1 = sum1.toFixed(2);
            if (!vm.result1) {
                vm.result1 = 'There has been an error calculating the result.  Please notify the webmaster';
            }

            var sum2 = 0;
            if (!vm.other && !vm.social) {
                sum2 = vm.form.income * 0.0333;
                vm.result2 = sum2.toFixed(2);
            }
            else if (vm.other && !vm.social) {
                sum2 = (vm.form.income * 0.0333) + (0.10 * vm.form.gross);
                vm.result2 = sum2.toFixed(2);
            }
            else if (vm.other && vm.social && vm.filing === 'single') {
                sum2 = singleCalculation();
                if (sum2 < 0) {
                    sum2 = 0;
                }
                vm.result2 = sum2.toFixed(2);
            }
            else if (vm.other && vm.social && vm.filing === 'joint') {
                sum2 = jointCalculation();
                if (sum2 < 0) {
                    sum2 = 0;
                }
                vm.result2 = sum2.toFixed(2);
            }
            if (!vm.result2) {
                vm.result2 = 'There has been an error calculating the result.  Please notify the webmaster';
            }

            var sum3 = vm.result1 - vm.result2;
            vm.difference = sum3.toFixed(2);
            if (!vm.difference) {
                vm.difference = 'There has been an error calculating the result.  Please notify the webmaster';
            }
        };

        vm.clear = function clear() {
            setIndividualForm();
        };
    }
})();<|endoftext|>


<commit_before>define(
  'ephox.alloy.api.GuiEvents',

  [
    'ephox.alloy.api.SystemEvents',
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.classify.Type',
    'ephox.compass.Arr',
    'ephox.fred.PlatformDetection',
    'ephox.keytar.Keys',
    'ephox.perhaps.Result',
    'ephox.sugar.api.DomEvent',
    'ephox.sugar.api.Node',
    'global!setTimeout'
  ],

  function (SystemEvents, FieldPresence, FieldSchema, ValueSchema, Type, Arr, PlatformDetection, Keys, Result, DomEvent, Node, setTimeout) {
    var isFunction = function (v) {
      return Type.isFunction(v) ? Result.value(v) : Result.error('Not a function');
    };

    var isDangerous = function (event) {
      // Will trigger the Back button in the browser
      return event.raw().which === Keys.BACKSPACE()[0] && !Arr.contains([ 'input', 'textarea' ], Node.name(event.target()));
    };

    var isFirefox = PlatformDetection.detect().browser.isFirefox();

    var settingsSchema = ValueSchema.objOf([
      // triggerEvent(eventName, event)
      FieldSchema.field('triggerEvent', 'triggerEvent', FieldPresence.strict(), ValueSchema.valueOf(isFunction)),
      FieldSchema.defaulted('stopBackspace', true)
    ]);

    var bindFocus = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'focus', handler);
      } else {
        return DomEvent.bind(container, 'focusin', handler);
      }
    };

    var bindBlur = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'blur', handler);
      } else {
        return DomEvent.bind(container, 'focusout', handler);
      }
    };

    var setup = function (container, rawSettings) {
      var settings = ValueSchema.asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);

      var onClick = DomEvent.bind(container, 'click', function (event) {
        var stopped = settings.triggerEvent('click', event);
        if (stopped) event.kill();
      });

      var onSelectStart = DomEvent.bind(container, 'selectstart', function (event) {
        var stopped = settings.triggerEvent('selectstart', event);
        if (stopped) event.kill();
      });

      var onKeydown = DomEvent.bind(container, 'keydown', function (event) {
        // Prevent default of backspace when not in input fields.
        var stopped = settings.triggerEvent('keydown', event);
        if (stopped) event.kill();
        else if (settings.stopBackspace === true && isDangerous(event)) { event.prevent(); }
      });

      var onMouseover = DomEvent.bind(container, 'mouseover', function (event) {
        var stopped = settings.triggerEvent('mouseover', event);
        if (stopped) event.kill();
      });

      // TODO: Get this working on Firefox.
      var onFocusIn = bindFocus(container, function (event) {
        // TODO: Focus vs focusin
        var stopped = settings.triggerEvent('focusin', event);
        if (stopped) event.kill();
      });

      var onFocusOut = bindBlur(container, function (event) {
        // TODO: blur vs focusout
        var stopped = settings.triggerEvent('focusout', event);
        if (stopped) event.kill();

        // Come up with a better way of doing this. Related target can be used, but not on FF.
        // It allows the active element to change before firing the blur that we will listen to
        // for things like closing popups
        setTimeout(function () {
          settings.triggerEvent(SystemEvents.postBlur(), event);
        }, 0);
      });

      var onInput = DomEvent.bind(container, 'input', function (event) {
        var stopped = settings.triggerEvent('input', event);
        if (stopped) event.kill();
      });

      var unbind = function () {
        onClick.unbind();
        onSelectStart.unbind();
        onKeydown.unbind();
        onMouseover.unbind();
        onFocusIn.unbind();
        onFocusOut.unbind();
        onInput.unbind();
      };

      return {
        unbind: unbind
      };
    };

    return {
      setup: setup
    };
  }
);<commit_msg>VAN-1: removing firefox handling so test should fail<commit_after>define(
  'ephox.alloy.api.GuiEvents',

  [
    'ephox.alloy.api.SystemEvents',
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.classify.Type',
    'ephox.compass.Arr',
    'ephox.fred.PlatformDetection',
    'ephox.keytar.Keys',
    'ephox.perhaps.Result',
    'ephox.sugar.api.DomEvent',
    'ephox.sugar.api.Node',
    'global!setTimeout'
  ],

  function (SystemEvents, FieldPresence, FieldSchema, ValueSchema, Type, Arr, PlatformDetection, Keys, Result, DomEvent, Node, setTimeout) {
    var isFunction = function (v) {
      return Type.isFunction(v) ? Result.value(v) : Result.error('Not a function');
    };

    var isDangerous = function (event) {
      // Will trigger the Back button in the browser
      return event.raw().which === Keys.BACKSPACE()[0] && !Arr.contains([ 'input', 'textarea' ], Node.name(event.target()));
    };

    var isFirefox = PlatformDetection.detect().browser.isFirefox() && false;

    var settingsSchema = ValueSchema.objOf([
      // triggerEvent(eventName, event)
      FieldSchema.field('triggerEvent', 'triggerEvent', FieldPresence.strict(), ValueSchema.valueOf(isFunction)),
      FieldSchema.defaulted('stopBackspace', true)
    ]);

    var bindFocus = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'focus', handler);
      } else {
        return DomEvent.bind(container, 'focusin', handler);
      }
    };

    var bindBlur = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'blur', handler);
      } else {
        return DomEvent.bind(container, 'focusout', handler);
      }
    };

    var setup = function (container, rawSettings) {
      var settings = ValueSchema.asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);

      var onClick = DomEvent.bind(container, 'click', function (event) {
        var stopped = settings.triggerEvent('click', event);
        if (stopped) event.kill();
      });

      var onSelectStart = DomEvent.bind(container, 'selectstart', function (event) {
        var stopped = settings.triggerEvent('selectstart', event);
        if (stopped) event.kill();
      });

      var onKeydown = DomEvent.bind(container, 'keydown', function (event) {
        // Prevent default of backspace when not in input fields.
        var stopped = settings.triggerEvent('keydown', event);
        if (stopped) event.kill();
        else if (settings.stopBackspace === true && isDangerous(event)) { event.prevent(); }
      });

      var onMouseover = DomEvent.bind(container, 'mouseover', function (event) {
        var stopped = settings.triggerEvent('mouseover', event);
        if (stopped) event.kill();
      });

      // TODO: Get this working on Firefox.
      var onFocusIn = bindFocus(container, function (event) {
        // TODO: Focus vs focusin
        var stopped = settings.triggerEvent('focusin', event);
        if (stopped) event.kill();
      });

      var onFocusOut = bindBlur(container, function (event) {
        // TODO: blur vs focusout
        var stopped = settings.triggerEvent('focusout', event);
        if (stopped) event.kill();

        // Come up with a better way of doing this. Related target can be used, but not on FF.
        // It allows the active element to change before firing the blur that we will listen to
        // for things like closing popups
        setTimeout(function () {
          settings.triggerEvent(SystemEvents.postBlur(), event);
        }, 0);
      });

      var onInput = DomEvent.bind(container, 'input', function (event) {
        var stopped = settings.triggerEvent('input', event);
        if (stopped) event.kill();
      });

      var unbind = function () {
        onClick.unbind();
        onSelectStart.unbind();
        onKeydown.unbind();
        onMouseover.unbind();
        onFocusIn.unbind();
        onFocusOut.unbind();
        onInput.unbind();
      };

      return {
        unbind: unbind
      };
    };

    return {
      setup: setup
    };
  }
);<|endoftext|>


<commit_before>define(
  'ephox.polaris.api.Regexes',

  [
    'global!RegExp'
  ],

  function (RegExp) {
    var link = function () {
     /* http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the
        Modified to:
        - include port numbers
        - allow full stops in email addresses
        - allow [-.~*+=!&;:'%@?^${}(),\w] after the #
        - allow [-.~*+=!&;:'%@?^${}(),\w] after the ?
        - move allow -_.~*+=!&;:'%@?^${}() in email usernames to the first @ match (TBIO-4809)
        - enforce domains to be [A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)* so they can't end in a period (TBIO-4809)
        - removed a bunch of escaping, made every group non-capturing (during TBIO-4809)
        - colons are only valid when followed directly by // or some text and then @ (TBIO-4867)

      (?:
        (?:[A-Za-z]{3,9}:(?:\/\/))
        (?:[-.~*+=!&;:'%@?^${}(),\w]+@)?
        [A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*
        |
          (?:www\.
          |
            [-;:&=+$,.\w]+@
          )
        [A-Za-z0-9-]+
        (?:\.[A-Za-z0-9-]+)*
      )
      (?::[0-9]+)?
      (?:\/[-+~%.()\/\w]*)?
      (?:
        \?
        (?:
          [-.~*+=!&;:'%@?^${}(),\w]*
        )
      )?
      (?:
        #
        (?:
          [-.~*+=!&;:'%@?^${}(),\/\w]*
        )
      )?

      */

      return /(?:(?:[A-Za-z]{3,9}:(?:\/\/))(?:[-.~*+=!&;:'%@?^${}(),\w]+@)?[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*|(?:www\.|[-;:&=+$,.\w]+@)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)(?::[0-9]+)?(?:\/[-+~%.()\/\w]*)?(?:\?(?:[-.~*+=!&;:'%@?^${}(),\w]*))?(?:#(?:[-.~*+=!&;:'%@?^${}(),\/\w]*))?/g;
    };

    var autolink = function () {
      /*
       * Takes the link regex, and makes two additions:
       *
       * - allows punctuation at the end (so it can be used for TBIO autolink macro)
       * - wraps the link regex in a group so that match[1] returns the desired contents
       *
       * We may need to inline the link regex if this refactoring technique causes performance issues; we're assuming browsers can optimise the above regex but not this style.
       * TBIO calls this method every time space or enter is pressed.
       */
      var linksource = link().source;
      return new RegExp('(' + linksource + ')[\-_.~*+=!&;:\'%@?^${}(),]*', 'g');
    };

    var tokens = function (value, parameters) {
      return value.replace(/\{(\d+)\}/g, function (match, contents, offset, s) {
        var index = parseInt(contents, 10);
        if (parameters[index] === undefined) throw 'No value for token: ' + match + ' in translation: ' + value;
        return parameters[index];
      });
    };

    return {
      tokens: tokens,
      link: link,
      autolink: autolink
    };
  }
);<commit_msg>TBIO-4867: Apply optimisations to autolink regex<commit_after>define(
  'ephox.polaris.api.Regexes',

  [
    'global!RegExp'
  ],

  function (RegExp) {
    var link = function () {
     /* http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the
        Modified to:
        - include port numbers
        - allow full stops in email addresses
        - allow [-.~*+=!&;:'%@?^${}(),\w] after the #
        - allow [-.~*+=!&;:'%@?^${}(),\w] after the ?
        - move allow -_.~*+=!&;:'%@?^${}() in email usernames to the first @ match (TBIO-4809)
        - enforce domains to be [A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)* so they can't end in a period (TBIO-4809)
        - removed a bunch of escaping, made every group non-capturing (during TBIO-4809)
        - colons are only valid when followed directly by // or some text and then @ (TBIO-4867)

      (?:
        (?:[A-Za-z]{3,9}:(?:\/\/))
        (?:[-.~*+=!&;:'%@?^${}(),\w]+@)?
        [A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*
        |
          (?:www\.
          |
            [-;:&=+$,.\w]+@
          )
        [A-Za-z0-9-]+
        (?:\.[A-Za-z0-9-]+)*
      )
      (?::[0-9]+)?
      (?:\/[-+~%.()\/\w]*)?
      (?:
        \?
        (?:
          [-.~*+=!&;:'%@?^${}(),\w]*
        )
      )?
      (?:
        #
        (?:
          [-.~*+=!&;:'%@?^${}(),\/\w]*
        )
      )?

      */

      return /(?:(?:[A-Za-z]{3,9}:(?:\/\/))(?:[-.~*+=!&;:'%@?^${}(),\w]+@)?[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*|(?:www\.|[-;:&=+$,.\w]+@)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)(?::[0-9]+)?(?:\/[-+~%.()\/\w]*)?(?:\?(?:[-.~*+=!&;:'%@?^${}(),\w]*))?(?:#(?:[-.~*+=!&;:'%@?^${}(),\/\w]*))?/g;
    };

    var autolink = function () {
      /*
       * Takes the link regex, and makes two additions:
       *
       * - allows punctuation at the end (so it can be used for TBIO autolink macro)
       * - wraps the link regex in a group so that match[1] returns the desired contents
       *
       * We may need to inline the link regex if this refactoring technique causes performance issues; we're assuming browsers can optimise the above regex but not this style.
       * TBIO calls this method every time space or enter is pressed.
       */
      var linksource = link().source;
      return new RegExp('(' + linksource + ')[-.~*+=!&;:\'%@?^${}(),]*', 'g');
    };

    var tokens = function (value, parameters) {
      return value.replace(/\{(\d+)\}/g, function (match, contents, offset, s) {
        var index = parseInt(contents, 10);
        if (parameters[index] === undefined) throw 'No value for token: ' + match + ' in translation: ' + value;
        return parameters[index];
      });
    };

    return {
      tokens: tokens,
      link: link,
      autolink: autolink
    };
  }
);<|endoftext|>