<commit_before>/* global Marionette, $ */

/**
 *
 * @copyright Copyright (c) 2018, Daniel Calviño Sánchez (danxuliu@gmail.com)
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function(OCA, Marionette, $) {

	'use strict';

	OCA.SpreedMe = OCA.SpreedMe || {};
	OCA.SpreedMe.Views = OCA.SpreedMe.Views || {};

	var roomsChannel = Backbone.Radio.channel('rooms');
	var localMediaChannel = Backbone.Radio.channel('localMedia');

	/**
	 * View for the main empty content message.
	 *
	 * This view does not render its own elements; an existing element must be
	 * provided when the view is created. In the main UI of Talk that element
	 * comes from the templates rendered by the server, which ensures that even
	 * if the UI takes a while to load the user will not see just an empty
	 * screen (which would happen if the view itself rendered the elements).
	 */
	var EmptyContentView  = Marionette.View.extend({

		template: false,

		ui: {
			'icon': '#emptycontent-icon',
			'message': 'h2',
			'messageAdditional': '.emptycontent-additional',
			'shareRoomInput': '.share-room-input',
			'shareRoomClipboardButton': '.shareRoomClipboard',
		},

		/**
		 * @param {string} options.el selector for the existing empty content
		 *                 element.
		 */
		initialize: function(/*options*/) {
			// Force render to create the UI bindings to the existing elements.
			this.render();

			this.listenTo(roomsChannel, 'leaveCurrentRoom', this.setEmptyContentMessageWhenConversationEnded);

			this.listenTo(localMediaChannel, 'webRtcNotSupported', function() {
				this._disableUpdatesOnActiveRoomChanges();

				this.setEmptyContentMessageWhenWebRtcIsNotSupported();
			});
			this.listenTo(localMediaChannel, 'waitingForPermissions', function() {
				this._disableUpdatesOnActiveRoomChanges();

				this.setEmptyContentMessageWhenWaitingForMediaPermissions();
			});
			this.listenTo(localMediaChannel, 'startLocalMedia', function() {
				this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall();

				this._enableUpdatesOnActiveRoomChanges();
			});
			this.listenTo(localMediaChannel, 'startWithoutLocalMedia', function() {
				this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall();

				this._enableUpdatesOnActiveRoomChanges();
			});
		},

		setActiveRoom: function(activeRoom) {
			this.stopListening(this._activeRoom, 'destroy', this.setInitialEmptyContentMessage);
			this._disableUpdatesOnActiveRoomChanges();

			this._activeRoom = activeRoom;

			if (!this._activeRoom.isCurrentParticipantInLobby()) {
				this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall();
			} else {
				this.setEmptyContentMessageWhenWaitingInLobby();
			}

			this.listenTo(this._activeRoom, 'destroy', function() {
				this.stopListening(this._activeRoom, 'destroy', this.setInitialEmptyContentMessage);
				this._disableUpdatesOnActiveRoomChanges();

				this._activeRoom = null;

				// 'leaveCurrentRoom' is sometimes triggered before the
				// 'destroy' event, so when the room is destroyed the initial
				// message overwrites the conversation ended message.
				this.setInitialEmptyContentMessage();
			});
			this._enableUpdatesOnActiveRoomChanges();
		},

		_disableUpdatesOnActiveRoomChanges: function() {
			this.stopListening(this._activeRoom, 'change:participants', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.stopListening(this._activeRoom, 'change:numGuests', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.stopListening(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.stopListening(this._activeRoom, 'change:type', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);

			this.stopListening(this._activeRoom, 'change:lobbyState', this.setEmptyContentMessageWhenWaitingInLobby);
			this.stopListening(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingInLobby);
		},

		_enableUpdatesOnActiveRoomChanges: function() {
			this.listenTo(this._activeRoom, 'change:participants', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.listenTo(this._activeRoom, 'change:numGuests', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.listenTo(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.listenTo(this._activeRoom, 'change:type', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);

			this.listenTo(this._activeRoom, 'change:lobbyState', this.setEmptyContentMessageWhenWaitingInLobby);
			this.listenTo(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingInLobby);
		},

		/**
		 *
		 * @param {string|Object} icon
		 * @param {string} icon.userId
		 * @param {string} icon.displayName
		 * @param {string} message
		 * @param {string} [messageAdditional]
		 * @param {string} [url]
		 */
		setEmptyContentMessage: function(icon, message, messageAdditional, url) {
			//Remove previous icon and avatar from emptycontent
			this.getUI('icon').removeAttr('class').attr('class', '');
			this.getUI('icon').html('');

			if (url) {
				this.getUI('shareRoomInput').removeClass('hidden').val(url);
				this.getUI('shareRoomClipboardButton').removeClass('hidden');
			} else {
				this.getUI('shareRoomInput').addClass('hidden');
				this.getUI('shareRoomClipboardButton').addClass('hidden');
			}

			if (typeof icon === 'string') {
				this.getUI('icon').addClass(icon);
			} else {
				var $avatar = $('<div>');
				$avatar.addClass('avatar room-avatar');
				if (icon.userId !== icon.displayName) {
					$avatar.avatar(icon.userId, 128, undefined, false, undefined, icon.displayName);
				} else {
					$avatar.avatar(icon.userId, 128);
				}
				this.getUI('icon').append($avatar);
			}

			this.getUI('message').html(message);
			this.getUI('messageAdditional').text(messageAdditional ? messageAdditional : '');
		},

		setInitialEmptyContentMessage: function() {
			this.setEmptyContentMessage(
				'icon-talk',
				t('spreed', 'Join a conversation or start a new one'),
				t('spreed', 'Say hi to your friends and colleagues!')
			);
		},

		setEmptyContentMessageWhenWaitingInLobby: function() {
			if (!this._activeRoom.isCurrentParticipantInLobby()) {
				return;
			}

			var icon = '';

			if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_PUBLIC) {
				icon = 'icon-public';
			} else {
				icon = 'icon-contacts-dark';
			}

			this.setEmptyContentMessage(
				icon,
				this._activeRoom.get('name'),
				t('spreed', 'Waiting for the conversation to be opened')
			);
		},

		setEmptyContentMessageWhenWaitingForOthersToJoinTheCall: function() {
			if (this._activeRoom.isCurrentParticipantInLobby()) {
				return;
			}

			var icon = '';
			var message = '';
			var messageAdditional = '';
			var url = '';

			var isGuest = (OC.getCurrentUser().uid === null);

			var participants = this._activeRoom.get('participants');
			var numberOfParticipants = Object.keys(participants).length;

			if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_PUBLIC) {
				icon = 'icon-public';
			} else {
				icon = 'icon-contacts-dark';
			}

			if (numberOfParticipants === 1 && this._activeRoom.get('numGuests') === 0) {
				message = t('spreed', 'No other people in this call');
			} else if ((!isGuest && numberOfParticipants === 2 && this._activeRoom.get('numGuests') === 0) ||
						(isGuest && numberOfParticipants === 1 && this._activeRoom.get('numGuests') === 1)) {
				var participantId = '',
					participantName = '';

				_.each(participants, function(data, userId) {
					if (OC.getCurrentUser().uid !== userId) {
						participantId = userId;
						participantName = data.name;
					}
				});

				icon = { userId: participantId, displayName: participantName};

				message = t('spreed', 'Waiting for {participantName} to join the call …', {participantName: participantName});
			} else {
				message = t('spreed', 'Waiting for others to join the call …');
			}

			var canModerate = this._activeRoom.get('participantType') === OCA.SpreedMe.app.OWNER ||
								this._activeRoom.get('participantType') === OCA.SpreedMe.app.MODERATOR;

			if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_GROUP && canModerate) {
				messageAdditional = t('spreed', 'You can invite others in the participant tab of the sidebar');
			} else if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_PUBLIC) {
				messageAdditional = t('spreed', 'Share this link to invite others!');

				canModerate = canModerate ||
								this._activeRoom.get('participantType') === OCA.SpreedMe.app.GUEST_MODERATOR;
				if (canModerate) {
					messageAdditional = t('spreed', 'You can invite others in the participant tab of the sidebar or share this link to invite others!');
				}

				url = window.location.protocol + '//' + window.location.host + OC.generateUrl('/call/' + this._activeRoom.get('token'));
			}

			if (this._activeRoom.get('objectType') === 'share:password' || this._activeRoom.get('objectType') === 'file') {
				messageAdditional = '';
				url = '';
			}

			this.setEmptyContentMessage(icon, message, messageAdditional, url);
		},

		setEmptyContentMessageWhenWebRtcIsNotSupported: function() {
			this.setEmptyContentMessage(
				'icon-video-off',
				t('spreed', 'WebRTC is not supported in your browser :-/'),
				t('spreed', 'Please use a different browser like Firefox or Chrome')
			);
		},

		setEmptyContentMessageWhenWaitingForMediaPermissions: function() {
			this.setEmptyContentMessage(
				'icon-video-off',
				t('spreed', 'Waiting for camera and microphone permissions'),
				t('spreed', 'Please, give your browser access to use your camera and microphone in order to use this app.')
			);
		},

		setEmptyContentMessageWhenConversationEnded: function() {
			// 'leaveCurrentRoom' is sometimes triggered after the 'destroy'
			// event, so do not overwrite the initial message with the
			// conversation ended message.
			if (!this._activeRoom) {
				return;
			}

			this.setEmptyContentMessage(
				'icon-video-off',
				t('spreed', 'This conversation has ended')
			);
		},

	});

	OCA.SpreedMe.Views.EmptyContentView = EmptyContentView;

})(OCA, Marionette, $);
<commit_msg>Show the start time in the lobby message of the empty content view<commit_after>/* global Marionette, $ */

/**
 *
 * @copyright Copyright (c) 2018, Daniel Calviño Sánchez (danxuliu@gmail.com)
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function(OCA, Marionette, $) {

	'use strict';

	OCA.SpreedMe = OCA.SpreedMe || {};
	OCA.SpreedMe.Views = OCA.SpreedMe.Views || {};

	var roomsChannel = Backbone.Radio.channel('rooms');
	var localMediaChannel = Backbone.Radio.channel('localMedia');

	/**
	 * View for the main empty content message.
	 *
	 * This view does not render its own elements; an existing element must be
	 * provided when the view is created. In the main UI of Talk that element
	 * comes from the templates rendered by the server, which ensures that even
	 * if the UI takes a while to load the user will not see just an empty
	 * screen (which would happen if the view itself rendered the elements).
	 */
	var EmptyContentView  = Marionette.View.extend({

		template: false,

		ui: {
			'icon': '#emptycontent-icon',
			'message': 'h2',
			'messageAdditional': '.emptycontent-additional',
			'shareRoomInput': '.share-room-input',
			'shareRoomClipboardButton': '.shareRoomClipboard',
		},

		/**
		 * @param {string} options.el selector for the existing empty content
		 *                 element.
		 */
		initialize: function(/*options*/) {
			// Force render to create the UI bindings to the existing elements.
			this.render();

			this.listenTo(roomsChannel, 'leaveCurrentRoom', this.setEmptyContentMessageWhenConversationEnded);

			this.listenTo(localMediaChannel, 'webRtcNotSupported', function() {
				this._disableUpdatesOnActiveRoomChanges();

				this.setEmptyContentMessageWhenWebRtcIsNotSupported();
			});
			this.listenTo(localMediaChannel, 'waitingForPermissions', function() {
				this._disableUpdatesOnActiveRoomChanges();

				this.setEmptyContentMessageWhenWaitingForMediaPermissions();
			});
			this.listenTo(localMediaChannel, 'startLocalMedia', function() {
				this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall();

				this._enableUpdatesOnActiveRoomChanges();
			});
			this.listenTo(localMediaChannel, 'startWithoutLocalMedia', function() {
				this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall();

				this._enableUpdatesOnActiveRoomChanges();
			});
		},

		setActiveRoom: function(activeRoom) {
			this.stopListening(this._activeRoom, 'destroy', this.setInitialEmptyContentMessage);
			this._disableUpdatesOnActiveRoomChanges();

			this._activeRoom = activeRoom;

			if (!this._activeRoom.isCurrentParticipantInLobby()) {
				this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall();
			} else {
				this.setEmptyContentMessageWhenWaitingInLobby();
			}

			this.listenTo(this._activeRoom, 'destroy', function() {
				this.stopListening(this._activeRoom, 'destroy', this.setInitialEmptyContentMessage);
				this._disableUpdatesOnActiveRoomChanges();

				this._activeRoom = null;

				// 'leaveCurrentRoom' is sometimes triggered before the
				// 'destroy' event, so when the room is destroyed the initial
				// message overwrites the conversation ended message.
				this.setInitialEmptyContentMessage();
			});
			this._enableUpdatesOnActiveRoomChanges();
		},

		_disableUpdatesOnActiveRoomChanges: function() {
			this.stopListening(this._activeRoom, 'change:participants', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.stopListening(this._activeRoom, 'change:numGuests', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.stopListening(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.stopListening(this._activeRoom, 'change:type', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);

			this.stopListening(this._activeRoom, 'change:lobbyState', this.setEmptyContentMessageWhenWaitingInLobby);
			this.stopListening(this._activeRoom, 'change:lobbyTimer', this.setEmptyContentMessageWhenWaitingInLobby);
			this.stopListening(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingInLobby);
		},

		_enableUpdatesOnActiveRoomChanges: function() {
			this.listenTo(this._activeRoom, 'change:participants', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.listenTo(this._activeRoom, 'change:numGuests', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.listenTo(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);
			this.listenTo(this._activeRoom, 'change:type', this.setEmptyContentMessageWhenWaitingForOthersToJoinTheCall);

			this.listenTo(this._activeRoom, 'change:lobbyState', this.setEmptyContentMessageWhenWaitingInLobby);
			this.listenTo(this._activeRoom, 'change:lobbyTimer', this.setEmptyContentMessageWhenWaitingInLobby);
			this.listenTo(this._activeRoom, 'change:participantType', this.setEmptyContentMessageWhenWaitingInLobby);
		},

		/**
		 *
		 * @param {string|Object} icon
		 * @param {string} icon.userId
		 * @param {string} icon.displayName
		 * @param {string} message
		 * @param {string} [messageAdditional]
		 * @param {string} [url]
		 */
		setEmptyContentMessage: function(icon, message, messageAdditional, url) {
			//Remove previous icon and avatar from emptycontent
			this.getUI('icon').removeAttr('class').attr('class', '');
			this.getUI('icon').html('');

			if (url) {
				this.getUI('shareRoomInput').removeClass('hidden').val(url);
				this.getUI('shareRoomClipboardButton').removeClass('hidden');
			} else {
				this.getUI('shareRoomInput').addClass('hidden');
				this.getUI('shareRoomClipboardButton').addClass('hidden');
			}

			if (typeof icon === 'string') {
				this.getUI('icon').addClass(icon);
			} else {
				var $avatar = $('<div>');
				$avatar.addClass('avatar room-avatar');
				if (icon.userId !== icon.displayName) {
					$avatar.avatar(icon.userId, 128, undefined, false, undefined, icon.displayName);
				} else {
					$avatar.avatar(icon.userId, 128);
				}
				this.getUI('icon').append($avatar);
			}

			this.getUI('message').html(message);
			this.getUI('messageAdditional').text(messageAdditional ? messageAdditional : '');
		},

		setInitialEmptyContentMessage: function() {
			this.setEmptyContentMessage(
				'icon-talk',
				t('spreed', 'Join a conversation or start a new one'),
				t('spreed', 'Say hi to your friends and colleagues!')
			);
		},

		setEmptyContentMessageWhenWaitingInLobby: function() {
			if (!this._activeRoom.isCurrentParticipantInLobby()) {
				return;
			}

			var icon = '';

			if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_PUBLIC) {
				icon = 'icon-public';
			} else {
				icon = 'icon-contacts-dark';
			}

			var messageAdditional = t('spreed', 'Waiting for the conversation to be opened');
			if (this._activeRoom.get('lobbyTimer')) {
				// PHP timestamp is second-based; JavaScript timestamp is
				// millisecond based.
				var startTime = OC.Util.formatDate(this._activeRoom.get('lobbyTimer') * 1000);
				messageAdditional = t('spreed', 'Waiting for the conversation to be opened. This meeting is scheduled for {startTime}', {startTime: startTime});
			}

			this.setEmptyContentMessage(
				icon,
				this._activeRoom.get('name'),
				messageAdditional
			);
		},

		setEmptyContentMessageWhenWaitingForOthersToJoinTheCall: function() {
			if (this._activeRoom.isCurrentParticipantInLobby()) {
				return;
			}

			var icon = '';
			var message = '';
			var messageAdditional = '';
			var url = '';

			var isGuest = (OC.getCurrentUser().uid === null);

			var participants = this._activeRoom.get('participants');
			var numberOfParticipants = Object.keys(participants).length;

			if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_PUBLIC) {
				icon = 'icon-public';
			} else {
				icon = 'icon-contacts-dark';
			}

			if (numberOfParticipants === 1 && this._activeRoom.get('numGuests') === 0) {
				message = t('spreed', 'No other people in this call');
			} else if ((!isGuest && numberOfParticipants === 2 && this._activeRoom.get('numGuests') === 0) ||
						(isGuest && numberOfParticipants === 1 && this._activeRoom.get('numGuests') === 1)) {
				var participantId = '',
					participantName = '';

				_.each(participants, function(data, userId) {
					if (OC.getCurrentUser().uid !== userId) {
						participantId = userId;
						participantName = data.name;
					}
				});

				icon = { userId: participantId, displayName: participantName};

				message = t('spreed', 'Waiting for {participantName} to join the call …', {participantName: participantName});
			} else {
				message = t('spreed', 'Waiting for others to join the call …');
			}

			var canModerate = this._activeRoom.get('participantType') === OCA.SpreedMe.app.OWNER ||
								this._activeRoom.get('participantType') === OCA.SpreedMe.app.MODERATOR;

			if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_GROUP && canModerate) {
				messageAdditional = t('spreed', 'You can invite others in the participant tab of the sidebar');
			} else if (this._activeRoom.get('type') === OCA.SpreedMe.app.ROOM_TYPE_PUBLIC) {
				messageAdditional = t('spreed', 'Share this link to invite others!');

				canModerate = canModerate ||
								this._activeRoom.get('participantType') === OCA.SpreedMe.app.GUEST_MODERATOR;
				if (canModerate) {
					messageAdditional = t('spreed', 'You can invite others in the participant tab of the sidebar or share this link to invite others!');
				}

				url = window.location.protocol + '//' + window.location.host + OC.generateUrl('/call/' + this._activeRoom.get('token'));
			}

			if (this._activeRoom.get('objectType') === 'share:password' || this._activeRoom.get('objectType') === 'file') {
				messageAdditional = '';
				url = '';
			}

			this.setEmptyContentMessage(icon, message, messageAdditional, url);
		},

		setEmptyContentMessageWhenWebRtcIsNotSupported: function() {
			this.setEmptyContentMessage(
				'icon-video-off',
				t('spreed', 'WebRTC is not supported in your browser :-/'),
				t('spreed', 'Please use a different browser like Firefox or Chrome')
			);
		},

		setEmptyContentMessageWhenWaitingForMediaPermissions: function() {
			this.setEmptyContentMessage(
				'icon-video-off',
				t('spreed', 'Waiting for camera and microphone permissions'),
				t('spreed', 'Please, give your browser access to use your camera and microphone in order to use this app.')
			);
		},

		setEmptyContentMessageWhenConversationEnded: function() {
			// 'leaveCurrentRoom' is sometimes triggered after the 'destroy'
			// event, so do not overwrite the initial message with the
			// conversation ended message.
			if (!this._activeRoom) {
				return;
			}

			this.setEmptyContentMessage(
				'icon-video-off',
				t('spreed', 'This conversation has ended')
			);
		},

	});

	OCA.SpreedMe.Views.EmptyContentView = EmptyContentView;

})(OCA, Marionette, $);
<|endoftext|>


<commit_before>'use strict';

angular.module('employer-signup-wizard').controller('EmpWizardOneController', ['$scope', '$http','Industries', 'Countries','$rootScope','geolocation',
	function($scope, $http,Industries, Countries,$rootScope,geolocation) {
		// Controller Logic
		// ...
		$scope.company={};
		$scope.employer={};
		$scope.company.specialities = [];
		$scope.company.specialities.push({name: 'Product Development'});
		var geocoder = new google.maps.Geocoder();
		geolocation.getLocation().then(function(data){
		var lat = parseFloat(data.coords.latitude);
	  var lng = parseFloat(data.coords.longitude);
	  var latlng = new google.maps.LatLng(lat, lng);
	  geocoder.geocode({'latLng': latlng}, function(results, status) {
	    if (status == google.maps.GeocoderStatus.OK) {
	      if (results[1]) {
	      	var citycountry=results[1].formatted_address;

	       console.log(citycountry);
	      } else {
	        alert('No results found');
	      }
	    } else {
	      alert('Geocoder failed due to: ' + status);
	    }
	  });

	    });

      	$scope.industries = Industries.getIndustries();

		Countries.getCountries(function(countries){
			$scope.countries = countries;
			// $scope.countries.splice(0, 1);
			$scope.company.country = $scope.countries[0];
			$scope.getCountryCities();
		});

		// $http.get('/countries').success(function(countries) {
		// 	$scope.countries = countries;
		// 	$scope.country = $scope.countries[0].name;
		// 	$scope.getCountryCities();
		// });

		$scope.getCountryCities = function(){
				$http.get('/countries/'+ $scope.company.country.name).success(function (response){
				$scope.cities = response.cities;
				$scope.company.city = $scope.cities[0];
			});
		};

		$scope.SaveAndRedirect = function() {
			$scope.success = $scope.error = null;

			$http.post('/SaveEmpSignUpWizardOneData', {company:$scope.company, employer:$scope.employer}).success(function(response) {
				// If successful show success message and clear form

			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		//Add specialities
		$scope.addSpeciality = function() {
	      $scope.company.specialities.push({
	        name: ''
	      });
	    };
	    //Remove Speciality
	    $scope.removeSpeciality = function(index) {
	      $scope.company.specialities.splice(index, 1);
	    };

	}
]);<commit_msg>Emp wizard specialities<commit_after>'use strict';

angular.module('employer-signup-wizard').controller('EmpWizardOneController', ['$scope', '$http','Industries', 'Countries','$rootScope','geolocation',
	function($scope, $http,Industries, Countries,$rootScope,geolocation) {
		// Controller Logic
		// ...
		$scope.company={};
		$scope.employer={};
		$scope.company.specialities = [];
		$scope.company.specialities.push({name: 'Product Development'});

		var city1="";
  var country1="";
		var geocoder = new google.maps.Geocoder();
		geolocation.getLocation().then(function(data){
	var lat = parseFloat(data.coords.latitude);
  var lng = parseFloat(data.coords.longitude);

  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
      	var citycountry=results[1].formatted_address;
      var res = citycountry.split(",");
    country1=res[res.length-1];
    city1=res[res.length-2];
    city1=city1.trim();
     country1=country1.trim();

     angular.forEach($scope.countries,function(country){

          if(country1==country.name)
          {

             $scope.company.country=country;

             $scope.getCountryCities();

          }

     });

      } else {
        alert('No results found');
      }
    } else {
      alert('Geocoder failed due to: ' + status);
    }
  });

    });

      	$scope.industries = Industries.getIndustries();

		Countries.getCountries(function(countries){
			$scope.countries = countries;
			// $scope.countries.splice(0, 1);
			$scope.company.country = $scope.countries[1];
			$scope.getCountryCities();
		});

		// $http.get('/countries').success(function(countries) {
		// 	$scope.countries = countries;
		// 	$scope.country = $scope.countries[0].name;
		// 	$scope.getCountryCities();
		// });

		$scope.getCountryCities = function(){
			var foundit=false;
				$http.get('/countries/'+ $scope.company.country.name).success(function (response){
				$scope.cities = response.cities;
angular.forEach($scope.cities,function(city){
	console.log(city.name+" "+city1);
	if(city.name==city1)//fuck my life
		{
console.log(city);
			$scope.company.city=city;
			foundit=true;
		}

});if(!foundit)
				$scope.company.city = $scope.cities[0];
			});
		};

		$scope.SaveAndRedirect = function() {
			$scope.success = $scope.error = null;

			$http.post('/SaveEmpSignUpWizardOneData', {company:$scope.company, employer:$scope.employer}).success(function(response) {
				// If successful show success message and clear form

			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		//Add specialities
		$scope.addSpeciality = function() {
	      $scope.company.specialities.push({
	        name: ''
	      });
	    };
	    //Remove Speciality
	    $scope.removeSpeciality = function(index) {
	      $scope.company.specialities.splice(index, 1);
	    };

	}
]);<|endoftext|>


<commit_before>module('lively.store.Interface').requires().toRun(function() {

Object.extend(lively.store, {
    cachedStorageAccessors: {},
    get: function(spec) {
        if (this.cachedStorageAccessors[spec.id]) {
            return this.cachedStorageAccessors[spec.id];
        }
        if (!spec.type) {
            throw new Error('Storage type must be specified!');
        }
        var storageClass = lively.store[spec.type];
        if (!storageClass) {
            throw new Error('No such storage type ' + spec.type);
        }
        var storage = new storageClass(spec);
        return this.cachedStorageAccessors[spec.id] = storage;
    },

    flushCache: function() {
        this.cachedStorageAccessors = {};
    }
});

Object.subclass('lively.store.ObjectStorage',
'initializing', {
    initialize: function(spec) {
        this.stored = {}
    }
},
'accessing', {
    set: function(key, value) {
        this.stored[key] = value;
    },

    get: function(key) {
        return this.stored[key];
    }
});

Object.subclass('lively.store.FileStorage',
'initializing', {
    initialize: function(spec) {
        this.url = spec.url;
    }
},
'accessing', {
    set: function(data) {
        var webR = new WebResource(this.url);
        webR.put(data);
    },

    get: function(optCb) {
        var webR = new WebResource(this.url),
            result = webR.get().content;
        if (optCb) optCb(null, result);
        return result;
    }
});

Object.subclass('lively.store.CouchDBStorage',
'initializing', {
    initialize: function(spec) {
        var reqPath = 'couchdb/' + spec.id + '/'; // id = db name
        this.couchdbURL = URL.nodejsBase.withFilename(reqPath);
    }
},
'accessing', {
    set: function(key, value) {
        var webR = this.couchdbURL.withFilename(key).asWebResource();
        webR.put(JSON.stringify(value), 'application/json');
    },

    get: function(key, optCb) {
        var webR = this.couchdbURL.withFilename(key).asWebResource(),
            data = webR.get().content;
        try { return JSON.parse(data); } catch(e) { return {error: e}}
    },

    ensureExistance: function() {
        this.couchdbURL.asWebResource().put();
    },

    remove: function() {
        this.couchdbURL.asWebResource().del();
    }
});

Object.subclass("lively.store.ObjectRepository",
"initializing", {
    initialize: function(url) {
        this.repoURL;
    }
},
"accessing", {
    getServerInterfaceURL: function() {
        return URL.nodejsBase.withFilename("ObjectRepositoryServer/");
    }
},
"querying", {
    getRecords: function(querySpec, thenDo)  {
        // new lively.store.ObjectRepository().getRecords()
        this.getServerInterfaceURL().withQuery({getRecords: encodeURIComponent(JSON.stringify(querySpec))})
            .asWebResource().withJSONWhenDone(function(json, status) {
                 thenDo(status.isSuccess() ? null : status, json); }).beAsync().get();
        return this;
    }
});

}); // end of module
<commit_msg>Adding synchronous access of ObjectRepository<commit_after>module('lively.store.Interface').requires().toRun(function() {

Object.extend(lively.store, {
    cachedStorageAccessors: {},
    get: function(spec) {
        if (this.cachedStorageAccessors[spec.id]) {
            return this.cachedStorageAccessors[spec.id];
        }
        if (!spec.type) {
            throw new Error('Storage type must be specified!');
        }
        var storageClass = lively.store[spec.type];
        if (!storageClass) {
            throw new Error('No such storage type ' + spec.type);
        }
        var storage = new storageClass(spec);
        return this.cachedStorageAccessors[spec.id] = storage;
    },

    flushCache: function() {
        this.cachedStorageAccessors = {};
    }
});

Object.subclass('lively.store.ObjectStorage',
'initializing', {
    initialize: function(spec) {
        this.stored = {}
    }
},
'accessing', {
    set: function(key, value) {
        this.stored[key] = value;
    },

    get: function(key) {
        return this.stored[key];
    }
});

Object.subclass('lively.store.FileStorage',
'initializing', {
    initialize: function(spec) {
        this.url = spec.url;
    }
},
'accessing', {
    set: function(data) {
        var webR = new WebResource(this.url);
        webR.put(data);
    },

    get: function(optCb) {
        var webR = new WebResource(this.url),
            result = webR.get().content;
        if (optCb) optCb(null, result);
        return result;
    }
});

Object.subclass('lively.store.CouchDBStorage',
'initializing', {
    initialize: function(spec) {
        var reqPath = 'couchdb/' + spec.id + '/'; // id = db name
        this.couchdbURL = URL.nodejsBase.withFilename(reqPath);
    }
},
'accessing', {
    set: function(key, value) {
        var webR = this.couchdbURL.withFilename(key).asWebResource();
        webR.put(JSON.stringify(value), 'application/json');
    },

    get: function(key, optCb) {
        var webR = this.couchdbURL.withFilename(key).asWebResource(),
            data = webR.get().content;
        try { return JSON.parse(data); } catch(e) { return {error: e}}
    },

    ensureExistance: function() {
        this.couchdbURL.asWebResource().put();
    },

    remove: function() {
        this.couchdbURL.asWebResource().del();
    }
});

Object.subclass("lively.store.ObjectRepository",
"initializing", {

    initialize: function(url) {
        this.repoURL;
    }

},
"accessing", {

    getServerInterfaceURL: function() {
        return URL.nodejsBase.withFilename("ObjectRepositoryServer/");
    }

},
"querying", {

    getRecords: function(querySpec, thenDo)  {
        // new lively.store.ObjectRepository().getRecords()
        var res = this.getServerInterfaceURL().withQuery({getRecords: encodeURIComponent(JSON.stringify(querySpec))}).asWebResource();
        if (thenDo != null) {
            res.withJSONWhenDone(function(json, status) {
                thenDo(status.isSuccess() ? null : status, json); }).beAsync().get();
            return this;
        } else {
            var content = res.beSync().get().content;
            if (!res.status.isSuccess())
                throw new Error(content);
            var json;
            try { json = JSON.parse(content); } catch(e) { json = {error: e} }
            return json;
        }
    }

});

}); // end of module
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { dropTask, restartableTask } from 'ember-concurrency-decorators';

export default class CurriculumInventoryReportsComponent extends Component {
  @service currentUser;
  @service intl;
  @service permissionChecker;
  @service store;

  @tracked showNewCurriculumInventoryReportForm = false;
  @tracked hasMoreThanOneSchool = false;
  @tracked selectedSchool = null;
  @tracked sortedSchools = [];
  @tracked programs = [];
  @tracked selectedProgram = null;
  @tracked canCreate = false;

  @action
  async changeSelectedProgram(programId) {
    const program = this.programs.findBy('id', programId);
    const school = await program.school;
    this.args.setSchoolId(school.id);
    this.args.setProgramId(programId);
    this.showNewCurriculumInventoryReportForm = false;
  }

  @action
  changeSelectedSchool(schoolId) {
    this.args.setSchoolId(schoolId);
    this.args.setProgramId(null);
    this.showNewCurriculumInventoryReportForm = false;
  }

  @action
  toggleNewCurriculumInventoryReportForm() {
    this.showNewCurriculumInventoryReportForm = !this.showNewCurriculumInventoryReportForm;
  }

  @action
  cancel() {
    this.showNewCurriculumInventoryReportForm = false;
  }

  @action
  async saveNewCurriculumInventoryReport(newReport) {
    const savedReport = await newReport.save();
    this.newReport = savedReport;
    const program = await this.selectedProgram;
    const reports = await program.curriculumInventoryReports;
    reports.pushObject(savedReport);
    this.showNewCurriculumInventoryReportForm = false;
  }

  @restartableTask
  *load() {
    if (! this.args.schools) {
      return;
    }
    this.sortedSchools = this.args.schools.sortBy('title').toArray();
    this.hasMoreThanOneSchool = this.sortedSchools.length > 1;

    if (! this.args.schoolId) {
      const user = yield this.currentUser.model;
      this.selectedSchool =  yield user.school;
    } else {
      this.selectedSchool = this.args.schools.findBy('id', this.args.schoolId);
    }

    if (this.selectedSchool) {
      this.canCreate = yield this.permissionChecker.canCreateCurriculumInventoryReport(this.selectedSchool);
      const programs = yield this.store.query('program', { school: this.selectedSchool.id });
      this.programs = programs.sortBy('title').toArray();
    }

    if (this.args.programId) {
      this.selectedProgram = this.programs.findBy('id', this.args.programId);
    } else {
      this.selectedProgram = this.programs.length ? this.programs[0] : null;
    }
  }

  @dropTask
  *removeCurriculumInventoryReport(report) {
    const reports = yield this.selectedProgram.curriculumInventoryReports;
    reports.removeObject(report);
    yield report.destroyRecord();
  }
}
<commit_msg>load program directly from selected school.<commit_after>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { dropTask, restartableTask } from 'ember-concurrency-decorators';

export default class CurriculumInventoryReportsComponent extends Component {
  @service currentUser;
  @service intl;
  @service permissionChecker;

  @tracked showNewCurriculumInventoryReportForm = false;
  @tracked hasMoreThanOneSchool = false;
  @tracked selectedSchool = null;
  @tracked sortedSchools = [];
  @tracked programs = [];
  @tracked selectedProgram = null;
  @tracked canCreate = false;

  @action
  async changeSelectedProgram(programId) {
    const program = this.programs.findBy('id', programId);
    const school = await program.school;
    this.args.setSchoolId(school.id);
    this.args.setProgramId(programId);
    this.showNewCurriculumInventoryReportForm = false;
  }

  @action
  changeSelectedSchool(schoolId) {
    this.args.setSchoolId(schoolId);
    this.args.setProgramId(null);
    this.showNewCurriculumInventoryReportForm = false;
  }

  @action
  toggleNewCurriculumInventoryReportForm() {
    this.showNewCurriculumInventoryReportForm = !this.showNewCurriculumInventoryReportForm;
  }

  @action
  cancel() {
    this.showNewCurriculumInventoryReportForm = false;
  }

  @action
  async saveNewCurriculumInventoryReport(newReport) {
    const savedReport = await newReport.save();
    this.newReport = savedReport;
    const program = await this.selectedProgram;
    const reports = await program.curriculumInventoryReports;
    reports.pushObject(savedReport);
    this.showNewCurriculumInventoryReportForm = false;
  }

  @restartableTask
  *load() {
    if (! this.args.schools) {
      return;
    }
    this.sortedSchools = this.args.schools.sortBy('title').toArray();
    this.hasMoreThanOneSchool = this.sortedSchools.length > 1;

    if (! this.args.schoolId) {
      const user = yield this.currentUser.model;
      this.selectedSchool =  yield user.school;
    } else {
      this.selectedSchool = this.args.schools.findBy('id', this.args.schoolId);
    }

    if (this.selectedSchool) {
      this.canCreate = yield this.permissionChecker.canCreateCurriculumInventoryReport(this.selectedSchool);
      const programs = yield this.selectedSchool.programs;
      this.programs = programs.sortBy('title').toArray();
    }

    if (this.args.programId) {
      this.selectedProgram = this.programs.findBy('id', this.args.programId);
    } else {
      this.selectedProgram = this.programs.length ? this.programs[0] : null;
    }
  }

  @dropTask
  *removeCurriculumInventoryReport(report) {
    const reports = yield this.selectedProgram.curriculumInventoryReports;
    reports.removeObject(report);
    yield report.destroyRecord();
  }
}
<|endoftext|>


<commit_before>import config from '../config/config'

export const SEND_STOPREQUEST = 'SEND_STOPREQUEST'
export const RECEIVE_CONFIRM = 'RECEIVE_CONFIRM'

export let requestStoprequest = function(tripId, stopId, requestType)
{
    return {
        type: SEND_STOPREQUEST,
        sentStoprequest: false,
        tripId: tripId,
        stopId: stopId,
        requestType: requestType
    }
}

export let receiveConfirm = function()
{
    return {
        type: RECEIVE_CONFIRM,
        sentStoprequest: true
    }
}

export let sendStoprequest = function(tripId, stopId, requestType)
{
    return dispatch =>
    {
        dispatch(requestStoprequest(tripId, stopId, requestType))

        let stopRequest = JSON.stringify({
            trip_id: tripId,
            stop_id: stopId,
            requestType: requestType
        })

        return fetch(config.API_URL + '/stoprequests', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: stopRequest
        })
      .then(dispatch(receiveConfirm()))
    }
}
<commit_msg>little fix<commit_after>import config from '../config/config'

export const SEND_STOPREQUEST = 'SEND_STOPREQUEST'
export const RECEIVE_CONFIRM = 'RECEIVE_CONFIRM'

export let requestStoprequest = function(tripId, stopId, requestType)
{
    return {
        type: SEND_STOPREQUEST,
        sentStoprequest: false,
        tripId: tripId,
        stopId: stopId,
        requestType: requestType
    }
}

export let receiveConfirm = function()
{
    return {
        type: RECEIVE_CONFIRM,
        sentStoprequest: true
    }
}

export let sendStoprequest = function(tripId, stopId, requestType)
{
    return dispatch =>
    {
        dispatch(requestStoprequest(tripId, stopId, requestType))

        let stopRequest = JSON.stringify({
            trip_id: tripId,
            stop_id: stopId,
            request_type: requestType
        })

        return fetch(config.API_URL + '/stoprequests', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: stopRequest
        })
      .then(dispatch(receiveConfirm()))
    }
}
<|endoftext|>


<commit_before>// https://stackoverflow.com/a/25359264
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null) {
        return null;
    }
    return decodeURI(results[1]) || 0;
}

// https://stackoverflow.com/a/3291856
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

// fetch ticket status from REST API
var endpoint_ticket_list = 'https://www.ebi.ac.uk/panda/jira/rest/api/2/search/?jql=project=ENSCOMPARASW+AND+issuetype=Task+AND+fixVersion+IN+("Ensembl+__RELEASE__",+"Release+__RELEASE__")+AND+component="Relco+tasks"+AND+cf[11130]=__DIVISION__+ORDER+BY+created+ASC,id+ASC&maxResults=500';
var endpoint_ticket_subtasks = 'https://www.ebi.ac.uk/panda/jira/rest/api/2/search/?jql=project=ENSCOMPARASW+AND+parent="__PARENT__"+ORDER+BY+created+ASC,id+ASC&maxResults=500';

var endpoint_ticket_query = 'https://www.ebi.ac.uk/panda/jira/rest/api/2/issue';
var url_jira_issue = 'https://www.ebi.ac.uk/panda/jira/browse/';
var release = $.urlParam("release");
var all_divisions = [ 'empty', 'Vertebrates', 'GRCh37', 'Metazoa', 'Plants', 'Protists', 'Fungi', 'Pan', 'Bacteria' ];

$('body').append('
Release ' + release + ' dashboard
');

function process_division(division) { return function(json) {
    //console.log('json: ', json);
    var n_tickets = json.issues.length;
    console.log(n_tickets);
    if (n_tickets == 0) {
        return;
    }
    if (division.toLowerCase() != "empty") {
        $('#' + division).prepend('
' + division + '
');
    }
    var table = $('

').appendTo('#' + division);
    for(var i =0; i<n_tickets; i++) {
        var ticket = json.issues[i];
        var summary = ticket.fields.summary;
        summary = summary.replace('Release ' + release, '');
        summary = summary.replace(division, '');
        table.append( '
' + summary.trim().capitalize() + '	' + ticket.key + '
' );
        var endpoint = endpoint_ticket_subtasks.replace('__PARENT__', ticket.key);
        console.log(endpoint);
        $.ajax(endpoint, {
            success: process_task(ticket.key),
            error: function(jqXHR, status, error) {
                console.log('Error: ' + (error || jqXHR.crossDomain && 'Cross-Origin Request Blocked' || 'Network issues'));
                window.alert('Having trouble contacting Jira - please check that you are logged in');
            },
            crossDomain: true,
        })
    }

} }

function process_task(task) { return function(json) {
    console.log('json: ', json);
    var n_tickets = json.issues.length;
    //$('#' + task).append('' + json.issues.length + '	');
    var n_done = 0;
    var n_in_progress = 0;
    var n_to_do = 0;
    for(var i =0; i<n_tickets; i++) {
        var ticket = json.issues[i];
        switch (ticket.fields.status.name) {
            case 'Resolved':    n_done ++; break;
            case 'Closed':      n_done ++; break;
            case 'In Progress': n_in_progress ++; break;
            default:            n_to_do ++; break;
        }
    }
    var prog = '';
    if (n_done) {
        prog += '

';
    }
    if (n_in_progress) {
        prog += '

';
    }
    if (n_to_do) {
        prog += '

';
    }
    $('#' + task).append('
' + prog + '
	');
    $('#' + task).append('' + n_done + ' done,	');
    $('#' + task).append('' + n_in_progress + ' in progress,	');
    $('#' + task).append('' + n_to_do + ' to do	');
} }

for(var j = 0; j < all_divisions.length; j++){
    var division = all_divisions[j];
    var endpoint = endpoint_ticket_list.replace(/__RELEASE__/g, release).replace('__DIVISION__', division);
    console.log(endpoint);
    $('body').append('

');
    $.ajax(endpoint, {
        success: process_division(division),
        error: function(jqXHR, status, error) {
            console.log('Error: ' + (error || jqXHR.crossDomain && 'Cross-Origin Request Blocked' || 'Network issues'));
            window.alert('Having trouble contacting Jira - please check that you are logged in');
        },
        crossDomain: true,
    })
}
<commit_msg>No need for this empty column<commit_after>// https://stackoverflow.com/a/25359264
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null) {
        return null;
    }
    return decodeURI(results[1]) || 0;
}

// https://stackoverflow.com/a/3291856
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

// fetch ticket status from REST API
var endpoint_ticket_list = 'https://www.ebi.ac.uk/panda/jira/rest/api/2/search/?jql=project=ENSCOMPARASW+AND+issuetype=Task+AND+fixVersion+IN+("Ensembl+__RELEASE__",+"Release+__RELEASE__")+AND+component="Relco+tasks"+AND+cf[11130]=__DIVISION__+ORDER+BY+created+ASC,id+ASC&maxResults=500';
var endpoint_ticket_subtasks = 'https://www.ebi.ac.uk/panda/jira/rest/api/2/search/?jql=project=ENSCOMPARASW+AND+parent="__PARENT__"+ORDER+BY+created+ASC,id+ASC&maxResults=500';

var endpoint_ticket_query = 'https://www.ebi.ac.uk/panda/jira/rest/api/2/issue';
var url_jira_issue = 'https://www.ebi.ac.uk/panda/jira/browse/';
var release = $.urlParam("release");
var all_divisions = [ 'empty', 'Vertebrates', 'GRCh37', 'Metazoa', 'Plants', 'Protists', 'Fungi', 'Pan', 'Bacteria' ];

$('body').append('
Release ' + release + ' dashboard
');

function process_division(division) { return function(json) {
    //console.log('json: ', json);
    var n_tickets = json.issues.length;
    console.log(n_tickets);
    if (n_tickets == 0) {
        return;
    }
    if (division.toLowerCase() != "empty") {
        $('#' + division).prepend('
' + division + '
');
    }
    var table = $('

').appendTo('#' + division);
    for(var i =0; i<n_tickets; i++) {
        var ticket = json.issues[i];
        var summary = ticket.fields.summary;
        summary = summary.replace('Release ' + release, '');
        summary = summary.replace(division, '');
        table.append( '
' + summary.trim().capitalize() + '	' + ticket.key + '
' );
        var endpoint = endpoint_ticket_subtasks.replace('__PARENT__', ticket.key);
        console.log(endpoint);
        $.ajax(endpoint, {
            success: process_task(ticket.key),
            error: function(jqXHR, status, error) {
                console.log('Error: ' + (error || jqXHR.crossDomain && 'Cross-Origin Request Blocked' || 'Network issues'));
                window.alert('Having trouble contacting Jira - please check that you are logged in');
            },
            crossDomain: true,
        })
    }

} }

function process_task(task) { return function(json) {
    console.log('json: ', json);
    var n_tickets = json.issues.length;
    //$('#' + task).append('' + json.issues.length + '	');
    var n_done = 0;
    var n_in_progress = 0;
    var n_to_do = 0;
    for(var i =0; i<n_tickets; i++) {
        var ticket = json.issues[i];
        switch (ticket.fields.status.name) {
            case 'Resolved':    n_done ++; break;
            case 'Closed':      n_done ++; break;
            case 'In Progress': n_in_progress ++; break;
            default:            n_to_do ++; break;
        }
    }
    var prog = '';
    if (n_done) {
        prog += '

';
    }
    if (n_in_progress) {
        prog += '

';
    }
    if (n_to_do) {
        prog += '

';
    }
    $('#' + task).append('
' + prog + '
	');
    $('#' + task).append('' + n_done + ' done,	');
    $('#' + task).append('' + n_in_progress + ' in progress,	');
    $('#' + task).append('' + n_to_do + ' to do	');
} }

for(var j = 0; j < all_divisions.length; j++){
    var division = all_divisions[j];
    var endpoint = endpoint_ticket_list.replace(/__RELEASE__/g, release).replace('__DIVISION__', division);
    console.log(endpoint);
    $('body').append('

');
    $.ajax(endpoint, {
        success: process_division(division),
        error: function(jqXHR, status, error) {
            console.log('Error: ' + (error || jqXHR.crossDomain && 'Cross-Origin Request Blocked' || 'Network issues'));
            window.alert('Having trouble contacting Jira - please check that you are logged in');
        },
        crossDomain: true,
    })
}
<|endoftext|>


<commit_before>//Reusable functions
var Alphagov = {
  daysInMsec: function(d) {
    return d * 24 * 60 * 60 * 1000;
  },
  cookie_domain: function() {
    var host_parts = document.location.host.split(':')[0].split('.').slice(-3);
    return '.' + host_parts.join('.');
  },
  read_cookie: function(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  },
  delete_cookie: function(name) {
    if (document.cookie && document.cookie !== '') {
      var date = new Date();
      date.setTime(date.getTime() - Alphagov.daysInMsec(1)); // 1 day ago
      document.cookie = name + "=; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
    }
  },
  write_cookie: function(name, value) {
    var date = new Date();
    date.setTime(date.getTime() + Alphagov.daysInMsec(4 * 30)); // 4 nominal 30-day months in the future
    document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
  }
};

function recordOutboundLink(e) {
  _gat._getTrackerByName()._trackEvent(this.href, 'Outbound Links');
  setTimeout('document.location = "' + this.href + '"', 100);
  return false;
}

var ReportAProblem = {
  handleErrorInSubmission: function (jqXHR) {
    var response = $.parseJSON(jqXHR.responseText);
    if (response.message !== '') {
      $('.report-a-problem-container').html(response.message);
    }
  },

  submit: function() {
    $('.report-a-problem-container .error-notification').remove();

    var submitButton = $(this).find('.button');
    submitButton.attr("disabled", true);
    $.ajax({
      type: "POST",
      url: "/feedback",
      dataType: "json",
      data: $('.report-a-problem-container form').serialize(),
      success: function(data) {
        $('.report-a-problem-container').html(data.message);
      },
      error: function(jqXHR) {
        if (jqXHR.status == 422) {
          submitButton.attr("disabled", false);
          $('
Please enter details of what you were doing.
').insertAfter('.report-a-problem-container p:first-child');
        } else {
          ReportAProblem.handleErrorInSubmission(jqXHR);
        }
      },
      statusCode: {
        500: ReportAProblem.handleErrorInSubmission
      }
    });
    return false;
  }
}

$(document).ready(function() {
  $('.print-link a').attr('target', '_blank');

  // header search toggle
  $('.js-header-toggle').on('click', function(e) {
    e.preventDefault();
    $($(e.target).attr('href')).toggleClass('js-visible');
    $(this).toggleClass('js-hidden');
  });

  var $searchFocus = $('.js-search-focus');
  if($searchFocus.val() !== ''){
    $searchFocus.addClass('focus');
  }
  $searchFocus.on('focus', function(e){
    $(e.target).addClass('focus');
  });
  $searchFocus.on('blur', function(e){
    if($searchFocus.val() === ''){
      $(e.target).removeClass('focus');
    }
  });

  if(window.location.hash && $(".design-principles").length != 1 && $('.section-page').length != 1) {
    contentNudge(window.location.hash);
  }

  $("nav").delegate('a', 'click', function(){
    var hash;
    var href = $(this).attr('href');
    if(href.charAt(0) === '#'){
      hash = href;
    }
    else if(href.indexOf("#") > 0){
      hash = "#" + href.split("#")[1];
    }
    if($(hash).length == 1){
      $("html, body").animate({scrollTop: $(hash).offset().top - $("#global-header").height()},10);
    }
  });

  function contentNudge(hash){
    if($(hash).length == 1){
      if($(hash).css("top") == "auto" || "0"){
        $(window).scrollTop( $(hash).offset().top - $("#global-header").height()  );
      }
    }
  }

  // toggle for reporting a problem (on all content pages)
  $('.report-a-problem-toggle a').on('click', function() {
    $('.report-a-problem-container').toggle();
      return false;
  });

  // form submission for reporting a problem
  var $forms = $('.report-a-problem-container form, .report-a-problem form');
  $forms.append('<input type="hidden" name="javascript_enabled" value="true"/>');
  $forms.append($('<input type="hidden" name="referrer">').val(document.referrer || "unknown"));

  $('.report-a-problem-container form').submit(ReportAProblem.submit);

  // hover, active and focus states for buttons in IE<8
  if ($.browser.msie && $.browser.version < 8) {
    $('.button').not('a')
      .on('click focus', function (e) {
        $(this).addClass('button-active');
      })
      .on('blur', function (e) {
        $(this).removeClass('button-active');
      });

    $('.button')
      .on('mouseover', function (e) {
        $(this).addClass('button-hover');
      })
      .on('mouseout', function (e) {
        $(this).removeClass('button-hover');
      });
  }

  // fix for printing bug in Windows Safari
  (function () {
    var windows_safari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
        $new_styles;

    if (windows_safari) {
      // set the New Transport font to Arial for printing
      $new_styles = $("");
      document.getElementsByTagName('head')[0].appendChild($new_styles[0]);
    }
  }());

  if (window.GOVUK && GOVUK.userSatisfaction){
    var currentURL = window.location.pathname;

    function stringContains(haystack, needle) {
      return haystack.indexOf(needle) > -1;
    }

    // We don't want the satisfaction survey appearing for users who
    // have completed a transaction as they may complete the survey with
    // the department's transaction in mind as opposed to the GOV.UK content.
    if (!stringContains(currentURL, "/done") &&
        !stringContains(currentURL, "/transaction-finished") &&
        !stringContains(currentURL, "/driving-transaction-finished")) {
      GOVUK.userSatisfaction.randomlyShowSurveyBar();
    }
  }
});

<commit_msg>Use str/substr instead of haystack/needle<commit_after>//Reusable functions
var Alphagov = {
  daysInMsec: function(d) {
    return d * 24 * 60 * 60 * 1000;
  },
  cookie_domain: function() {
    var host_parts = document.location.host.split(':')[0].split('.').slice(-3);
    return '.' + host_parts.join('.');
  },
  read_cookie: function(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  },
  delete_cookie: function(name) {
    if (document.cookie && document.cookie !== '') {
      var date = new Date();
      date.setTime(date.getTime() - Alphagov.daysInMsec(1)); // 1 day ago
      document.cookie = name + "=; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
    }
  },
  write_cookie: function(name, value) {
    var date = new Date();
    date.setTime(date.getTime() + Alphagov.daysInMsec(4 * 30)); // 4 nominal 30-day months in the future
    document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
  }
};

function recordOutboundLink(e) {
  _gat._getTrackerByName()._trackEvent(this.href, 'Outbound Links');
  setTimeout('document.location = "' + this.href + '"', 100);
  return false;
}

var ReportAProblem = {
  handleErrorInSubmission: function (jqXHR) {
    var response = $.parseJSON(jqXHR.responseText);
    if (response.message !== '') {
      $('.report-a-problem-container').html(response.message);
    }
  },

  submit: function() {
    $('.report-a-problem-container .error-notification').remove();

    var submitButton = $(this).find('.button');
    submitButton.attr("disabled", true);
    $.ajax({
      type: "POST",
      url: "/feedback",
      dataType: "json",
      data: $('.report-a-problem-container form').serialize(),
      success: function(data) {
        $('.report-a-problem-container').html(data.message);
      },
      error: function(jqXHR) {
        if (jqXHR.status == 422) {
          submitButton.attr("disabled", false);
          $('
Please enter details of what you were doing.
').insertAfter('.report-a-problem-container p:first-child');
        } else {
          ReportAProblem.handleErrorInSubmission(jqXHR);
        }
      },
      statusCode: {
        500: ReportAProblem.handleErrorInSubmission
      }
    });
    return false;
  }
}

$(document).ready(function() {
  $('.print-link a').attr('target', '_blank');

  // header search toggle
  $('.js-header-toggle').on('click', function(e) {
    e.preventDefault();
    $($(e.target).attr('href')).toggleClass('js-visible');
    $(this).toggleClass('js-hidden');
  });

  var $searchFocus = $('.js-search-focus');
  if($searchFocus.val() !== ''){
    $searchFocus.addClass('focus');
  }
  $searchFocus.on('focus', function(e){
    $(e.target).addClass('focus');
  });
  $searchFocus.on('blur', function(e){
    if($searchFocus.val() === ''){
      $(e.target).removeClass('focus');
    }
  });

  if(window.location.hash && $(".design-principles").length != 1 && $('.section-page').length != 1) {
    contentNudge(window.location.hash);
  }

  $("nav").delegate('a', 'click', function(){
    var hash;
    var href = $(this).attr('href');
    if(href.charAt(0) === '#'){
      hash = href;
    }
    else if(href.indexOf("#") > 0){
      hash = "#" + href.split("#")[1];
    }
    if($(hash).length == 1){
      $("html, body").animate({scrollTop: $(hash).offset().top - $("#global-header").height()},10);
    }
  });

  function contentNudge(hash){
    if($(hash).length == 1){
      if($(hash).css("top") == "auto" || "0"){
        $(window).scrollTop( $(hash).offset().top - $("#global-header").height()  );
      }
    }
  }

  // toggle for reporting a problem (on all content pages)
  $('.report-a-problem-toggle a').on('click', function() {
    $('.report-a-problem-container').toggle();
      return false;
  });

  // form submission for reporting a problem
  var $forms = $('.report-a-problem-container form, .report-a-problem form');
  $forms.append('<input type="hidden" name="javascript_enabled" value="true"/>');
  $forms.append($('<input type="hidden" name="referrer">').val(document.referrer || "unknown"));

  $('.report-a-problem-container form').submit(ReportAProblem.submit);

  // hover, active and focus states for buttons in IE<8
  if ($.browser.msie && $.browser.version < 8) {
    $('.button').not('a')
      .on('click focus', function (e) {
        $(this).addClass('button-active');
      })
      .on('blur', function (e) {
        $(this).removeClass('button-active');
      });

    $('.button')
      .on('mouseover', function (e) {
        $(this).addClass('button-hover');
      })
      .on('mouseout', function (e) {
        $(this).removeClass('button-hover');
      });
  }

  // fix for printing bug in Windows Safari
  (function () {
    var windows_safari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
        $new_styles;

    if (windows_safari) {
      // set the New Transport font to Arial for printing
      $new_styles = $("");
      document.getElementsByTagName('head')[0].appendChild($new_styles[0]);
    }
  }());

  if (window.GOVUK && GOVUK.userSatisfaction){
    var currentURL = window.location.pathname;

    function stringContains(str, substr) {
      return str.indexOf(substr) > -1;
    }

    // We don't want the satisfaction survey appearing for users who
    // have completed a transaction as they may complete the survey with
    // the department's transaction in mind as opposed to the GOV.UK content.
    if (!stringContains(currentURL, "/done") &&
        !stringContains(currentURL, "/transaction-finished") &&
        !stringContains(currentURL, "/driving-transaction-finished")) {
      GOVUK.userSatisfaction.randomlyShowSurveyBar();
    }
  }
});

<|endoftext|>


<commit_before>$(function() {
    function NavbarTempViewModel(parameters) {
        var self = this;

        self.temperatureModel = parameters[0];
        self.global_settings = parameters[1];
        self.socTemp = ko.observable("");
        self.custCmd = ko.observable("");
        /*
         * raspi and awinner should be combined into something like hasSoc in the python
         * source, there's no need for this part to know or care what the sbc is made of
         *
         */
        self.isSupported = ko.observable();
        //hassoc should be taken care of in the python source before it gets this far
        self.hasSoc = ko.pureComputed(function() {
            return self.isSupported;
        });

        self.onBeforeBinding = function () {
            self.settings = self.global_settings.settings.plugins.navbartemp;
        };

        self.formatBarTemperature = function(toolName, actual, target) {
            if(self.settings.useShortNames == true) {
                var name = toolName.charAt(0);
                if(name == 'T'){
                name = 'E';
                }
                if(toolName.split(" ")[1]) {
                    name += toolName.split(" ")[1];
                }
            } else {
                var name = toolName;
            }
            var output = name + ": " + _.sprintf("%.1f°C", actual);

            if (target) {
                var sign = (target >= actual) ? " \u21D7 " : " \u21D8 ";
                output += sign + _.sprintf("%.1f°C", target);
            }
            return output;
        };

        self.onDataUpdaterPluginMessage = function(plugin, data) {
            if (plugin != "navbartemp") {
                return;
            }

            if (data.soctemp) {
                self.socTemp(_.sprintf("SoC: %.1f°C", data.soctemp));
            }
            if (data.cmd_name) {
                self.custCmd( _.sprintf(" %s: ", data.cmd_name) + _.sprintf("%s",data.cmd_result));
            }
        };

        self.onSettingsHidden = function () {
            if(self.settings.displayRaspiTemp() == false) {
                self.socTemp("");
            }
        };

    }

    OCTOPRINT_VIEWMODELS.push({
        construct: NavbarTempViewModel,
        dependencies: ["temperatureViewModel", "settingsViewModel"],
        elements: ["#navbar_plugin_navbartemp", "#settings_plugin_navbartemp"]
    });
});
<commit_msg>Fixed call of useShortNames<commit_after>$(function() {
    function NavbarTempViewModel(parameters) {
        var self = this;

        self.temperatureModel = parameters[0];
        self.global_settings = parameters[1];
        self.socTemp = ko.observable("");
        self.custCmd = ko.observable("");
        /*
         * raspi and awinner should be combined into something like hasSoc in the python
         * source, there's no need for this part to know or care what the sbc is made of
         *
         */
        self.isSupported = ko.observable();
        //hassoc should be taken care of in the python source before it gets this far
        self.hasSoc = ko.pureComputed(function() {
            return self.isSupported;
        });

        self.onBeforeBinding = function () {
            self.settings = self.global_settings.settings.plugins.navbartemp;
        };

        self.formatBarTemperature = function(toolName, actual, target) {
            if(self.settings.useShortNames() == true) {
                var name = toolName.charAt(0);
                if(name == 'T'){
                name = 'E';
                }
                if(toolName.split(" ")[1]) {
                    name += toolName.split(" ")[1];
                }
            } else {
                var name = toolName;
            }
            var output = name + ": " + _.sprintf("%.1f°C", actual);

            if (target) {
                var sign = (target >= actual) ? " \u21D7 " : " \u21D8 ";
                output += sign + _.sprintf("%.1f°C", target);
            }
            return output;
        };

        self.onDataUpdaterPluginMessage = function(plugin, data) {
            if (plugin != "navbartemp") {
                return;
            }

            if (data.soctemp) {
                self.socTemp(_.sprintf("SoC: %.1f°C", data.soctemp));
            }
            if (data.cmd_name) {
                self.custCmd( _.sprintf(" %s: ", data.cmd_name) + _.sprintf("%s",data.cmd_result));
            }
        };

        self.onSettingsHidden = function () {
            if(self.settings.displayRaspiTemp() == false) {
                self.socTemp("");
            }
        };

    }

    OCTOPRINT_VIEWMODELS.push({
        construct: NavbarTempViewModel,
        dependencies: ["temperatureViewModel", "settingsViewModel"],
        elements: ["#navbar_plugin_navbartemp", "#settings_plugin_navbartemp"]
    });
});
<|endoftext|>


<commit_before>var JSHint = require('jshint').JSHINT;
var CSSLint = require('csslint');
var cssparse = require('css');
var acorn = require('acorn');
var domify = require('domify');
var JscsStringChecker = require('jscs/lib/string-checker.js');
var _ = require('lodash');

var ResponseTypes = {
	LINT : 'lint',
	STYLE : 'style',
	ERROR : 'error',
	FAILURE : 'failure',
	SUCCESS : 'success'
};

var extend = function(a, b){
	var surrogate = function(){};
	surrogate.prototype = a.prototype;
	b.prototype = new surrogate();
};

var Response = function(type, message, errors){
	this.type = type;
	this.message = message || '';
	this.errors = errors;
};

var RinzaiError = function(message, line, char){
	this.message = message;
	this.line = line;
	this.char = char;
};

var Question = function(config, options){
	this.options = options;
	this.test = config.test;
	this.envUrl = config.envUrl;
	this.messages = config.messages || {};
	this.type = config.type;
};

Question.prototype.createEnvironment = function(cb){
	var self = this;
	this.envFrame = document.createElement('iframe');
	this.envFrame.style.position = 'absolute';
	this.envFrame.style.top = '-1000px';
	this.envFrame.style.left = '-1000px';
	document.body.appendChild(this.envFrame);
	var env = this.envFrame.contentWindow;
	if(this.envUrl){
		this.envFrame.src = this.envUrl;
		var onLoad = function(){
			self.envFrame.removeEventListener('load', onLoad);
			cb(env);
		};
		this.envFrame.addEventListener('load', onLoad);
	} else {
		cb(env);
	}
};

Question.prototype.destroyEnvironment = function(){
	if(this.envFrame){
		this.envFrame.parentNode.removeChild(this.envFrame);
	 	delete this.envFrame;
	}
};

Question.prototype.runTest = function(content, parsed, cb){
	var self = this;
	var env = this.createEnvironment(function(env){
		try {
			self.test(content, parsed, env);
		} catch(e) {
			self.destroyEnvironment();
			return cb(e);
		}
		self.destroyEnvironment();
		return cb();
	});
};

var HTMLQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, HTMLQuestion);

HTMLQuestion.prototype.answer = function(content, cb){
	var self = this;
	var nodes;
	try {
		nodes = domify(content);
	} catch(e) {
		return cb(new Response(
			ResponseTypes.ERROR,
			this.messages[ResponseTypes.ERROR],
			[
				new RinzaiError('HTML Parse Error', null, null)
			]
		));
	}

	this.runTest(nodes, function(testErr){
		if(testErr) {
			return cb(new Response(
				ResponseTypes.FAILURE,
				self.messages[ResponseTypes.FAILURE],
				[
					new RinzaiError(testErr.message, null, null)
				]
			));
		}

		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var JSQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, JSQuestion);

JSQuestion.prototype.answer = function(content, cb){
	var self = this;

	JSHint(content, this.options.jshint);
	if(JSHint.errors.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(JSHint.errors, function(err){
				return new RinzaiError(err.reason, err.line);
			})
		));
	}

	var checker = new JscsStringChecker();
	checker.registerDefaultRules();
	checker.configure(this.options.jscs || {});
	var styleErrors = checker.checkString(content);
	if(styleErrors.getErrorList().length){
		return cb(new Response(
			ResponseTypes.STYLE,
			this.messages[ResponseTypes.STYLE],
			_.map(styleErrors.getErrorList(), function(err){
				return new RinzaiError(err.message, err.line, err.column);
			})
		));
	}

	var ast = acorn.parse(content);
	this.runTest(content, ast, function(testErr){
		if(testErr){
			var firstStack = testErr.stack.split('\n')[1];
			if(firstStack && firstStack.indexOf('eval') > -1){
				var position = firstStack.match(/(\d+)\:(\d+)\)$/);
				return cb(new Response(
					ResponseTypes.ERROR,
					self.messages[ResponseTypes.ERROR],
					[
						new RinzaiError(testErr.message, parseInt(position[1], 10), parseInt(position[2], 10))
					]
				));
			} else {
				return cb(new Response(
					ResponseTypes.FAILURE,
					self.messages[ResponseTypes.FAILURE],
					[
						new RinzaiError(testErr.message, null, null)
					]
				));
			}
		}
		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var CSSQuestion = function(config){
	this.test = config.test;
};

extend(Question, CSSQuestion);

CSSQuestion.prototype.answer = function(content){

};

var Rinzai = function(config, options){
	this.options = options || {};
	this.questions = [];
	this.questionsById = {};
	_.forEach(config.questions, this.addQuestion, this);
};

Rinzai.prototype.addQuestion = function(q){
	var question;
	switch(q.type){
		case 'html':
			question = new HTMLQuestion(q, this.options);
			break;
		case 'javascript':
			question = new JSQuestion(q, this.options);
			break;
		case 'css':
			question = new CSSQuestion(q, this.options);
			break;
		default:
			throw new Error('Question type is unknown or undefined');
	}
	this.questions.push(question);
	this.questionsById[q.id] = question;
	return question;
};

module.exports = Rinzai;
<commit_msg>Added CSSLinting to css question<commit_after>var JSHint = require('jshint').JSHINT;
var CSSLint = require('csslint');
var cssparse = require('css');
var acorn = require('acorn');
var domify = require('domify');
var JscsStringChecker = require('jscs/lib/string-checker.js');
var _ = require('lodash');

var ResponseTypes = {
	LINT : 'lint',
	STYLE : 'style',
	ERROR : 'error',
	FAILURE : 'failure',
	SUCCESS : 'success'
};

var extend = function(a, b){
	var surrogate = function(){};
	surrogate.prototype = a.prototype;
	b.prototype = new surrogate();
};

var Response = function(type, message, errors){
	this.type = type;
	this.message = message || '';
	this.errors = errors;
};

var RinzaiError = function(message, line, char){
	this.message = message;
	this.line = line;
	this.char = char;
};

var Question = function(config, options){
	this.options = options;
	this.test = config.test;
	this.envUrl = config.envUrl;
	this.messages = config.messages || {};
	this.type = config.type;
};

Question.prototype.createEnvironment = function(cb){
	var self = this;
	this.envFrame = document.createElement('iframe');
	this.envFrame.style.position = 'absolute';
	this.envFrame.style.top = '-1000px';
	this.envFrame.style.left = '-1000px';
	document.body.appendChild(this.envFrame);
	var env = this.envFrame.contentWindow;
	if(this.envUrl){
		this.envFrame.src = this.envUrl;
		var onLoad = function(){
			self.envFrame.removeEventListener('load', onLoad);
			cb(env);
		};
		this.envFrame.addEventListener('load', onLoad);
	} else {
		cb(env);
	}
};

Question.prototype.destroyEnvironment = function(){
	if(this.envFrame){
		this.envFrame.parentNode.removeChild(this.envFrame);
	 	delete this.envFrame;
	}
};

Question.prototype.runTest = function(content, parsed, cb){
	var self = this;
	var env = this.createEnvironment(function(env){
		try {
			self.test(content, parsed, env);
		} catch(e) {
			self.destroyEnvironment();
			return cb(e);
		}
		self.destroyEnvironment();
		return cb();
	});
};

var HTMLQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, HTMLQuestion);

HTMLQuestion.prototype.answer = function(content, cb){
	var self = this;
	var nodes;
	try {
		nodes = domify(content);
	} catch(e) {
		return cb(new Response(
			ResponseTypes.ERROR,
			this.messages[ResponseTypes.ERROR],
			[
				new RinzaiError('HTML Parse Error', null, null)
			]
		));
	}

	this.runTest(content, nodes, function(testErr){
		if(testErr) {
			return cb(new Response(
				ResponseTypes.FAILURE,
				self.messages[ResponseTypes.FAILURE],
				[
					new RinzaiError(testErr.message, null, null)
				]
			));
		}

		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var JSQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, JSQuestion);

JSQuestion.prototype.answer = function(content, cb){
	var self = this;

	JSHint(content, this.options.jshint);
	if(JSHint.errors.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(JSHint.errors, function(err){
				return new RinzaiError(err.reason, err.line);
			})
		));
	}

	var checker = new JscsStringChecker();
	checker.registerDefaultRules();
	checker.configure(this.options.jscs || {});
	var styleErrors = checker.checkString(content);
	if(styleErrors.getErrorList().length){
		return cb(new Response(
			ResponseTypes.STYLE,
			this.messages[ResponseTypes.STYLE],
			_.map(styleErrors.getErrorList(), function(err){
				return new RinzaiError(err.message, err.line, err.column);
			})
		));
	}

	var ast = acorn.parse(content);
	this.runTest(content, ast, function(testErr){
		if(testErr){
			var firstStack = testErr.stack.split('\n')[1];
			if(firstStack && firstStack.indexOf('eval') > -1){
				var position = firstStack.match(/(\d+)\:(\d+)\)$/);
				return cb(new Response(
					ResponseTypes.ERROR,
					self.messages[ResponseTypes.ERROR],
					[
						new RinzaiError(testErr.message, parseInt(position[1], 10), parseInt(position[2], 10))
					]
				));
			} else {
				return cb(new Response(
					ResponseTypes.FAILURE,
					self.messages[ResponseTypes.FAILURE],
					[
						new RinzaiError(testErr.message, null, null)
					]
				));
			}
		}
		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var CSSQuestion = function(config){
	this.test = config.test;
};

extend(Question, CSSQuestion);

CSSQuestion.prototype.answer = function(content){
	var results = CSSLint(content);
	if(results.messages.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(results.messages, function(err){
				return new RinzaiError(err.message, err.line, err.col);
			})
		));
	}
};

var Rinzai = function(config, options){
	this.options = options || {};
	this.questions = [];
	this.questionsById = {};
	_.forEach(config.questions, this.addQuestion, this);
};

Rinzai.prototype.addQuestion = function(q){
	var question;
	switch(q.type){
		case 'html':
			question = new HTMLQuestion(q, this.options);
			break;
		case 'javascript':
			question = new JSQuestion(q, this.options);
			break;
		case 'css':
			question = new CSSQuestion(q, this.options);
			break;
		default:
			throw new Error('Question type is unknown or undefined');
	}
	this.questions.push(question);
	this.questionsById[q.id] = question;
	return question;
};

module.exports = Rinzai;
<|endoftext|>


<commit_before>module.exports = function(r) {
    const dbExec = require('./run');
    const db = require('./db')(r);
    const model = require('./model')(r);
    const commonQueries = require('./common-queries');
    const _ = require('lodash');

    return {
        getDatasetsForExperiment,
        getDataset,
        createDatasetForExperiment,
        addSampleToDataset,
        updateSamplesInDataset,
        allSamplesInDataset,
        modifyDataset,
        publishDataset
    };

    function* getDatasetsForExperiment(experimentId) {
        let rql = commonQueries.datasetDetailsRql(r.table('experiment2dataset').getAll(experimentId, {index: 'experiment_id'})
            .eqJoin('dataset_id', r.table('datasets')).zip(), r);
        let dataset = yield dbExec(rql);
        return {val: dataset};
    }

    function* getDataset(datasetId) {
        let rql = commonQueries.datasetDetailsRql(r.table('datasets').get(datasetId), r);
        let dataset = yield dbExec(rql);
        return {val: dataset};
    }

    function* createDatasetForExperiment(experimentId, userId, datasetArgs) {
        let dataset = new model.Dataset(datasetArgs.title, userId);
        dataset.description = datasetArgs.description;
        let created = yield db.insert('datasets', dataset);
        let e2d = new model.Experiment2Dataset(experimentId, created.id);
        yield r.table('experiment2dataset').insert(e2d);
        return yield getDataset(created.id);
    }

    function* addSampleToDataset(datasetId, sampleId) {
        let d2s = new model.Dataset2Sample(datasetId, sampleId);
        yield r.table('dataset2sample').insert(d2s);
        yield addProcessesForSampleToDataset(datasetId, sampleId);
        return yield getDataset(datasetId);
    }

    function* addProcessesForSampleToDataset(datasetId, sampleId) {
        let processes = yield r.table('process2sample').getAll(sampleId, {index: 'sample_id'});
        let uniqProcesses = uniqByKey(processes, 'process_id');
        let processesToInsert = uniqProcesses.map(p => new model.Dataset2Process(datasetId, p.process_id));
        yield r.table('dataset2process').insert(processesToInsert);
    }

    function* updateSamplesInDataset(datasetId, samplesToAdd, samplesToDelete) {
        if (samplesToAdd.length) {
            let add = samplesToAdd.map(s => new model.Dataset2Sample(datasetId, s.id));
            add = yield removeExistingSampleEntriesInDataset(add);
            if (add.length) {
                yield r.table('dataset2sample').insert(add);
                yield addProcessesForSamplesToDataset(datasetId, samplesToAdd);
            }
        }

        if (samplesToDelete.length) {
            let toDelete = samplesToDelete.map(s => [datasetId, s.id]);
            yield r.table('dataset2sample').getAll(r.args(toDelete), {index: 'dataset_sample'}).delete();
        }

        return yield getDataset(datasetId);
    }

    function uniqByKey(items, key) {
        let uniqItems = _.indexBy(items, key);
        return Object.keys(uniqItems).map(key => uniqItems[key]);
    }

    function* addProcessesForSamplesToDataset(datasetId, samples) {
        let sampleIds = samples.map(s => s.id);
        let processes = yield r.table('process2sample').getAll(r.args(sampleIds), {index: 'sample_id'});
        let uniqProcesses = uniqByKey(processes, 'process_id');
        let processesToInsert = uniqProcesses.map(p => new model.Dataset2Process(datasetId, p.process_id));
        yield r.table('dataset2process').insert(processesToInsert);
    }

    function* removeExistingSampleEntriesInDataset(samplesToAdd) {
        if (samplesToAdd.length) {
            let indexEntries = samplesToAdd.map(s => [s.dataset_id, s.sample_id]);
            let matchingEntries = yield r.table('dataset2sample').getAll(r.args(indexEntries), {index: 'dataset_sample'});
            let matchingEntriesBySampleId = _.indexBy(matchingEntries, 'sample_id');
            return samplesToAdd.filter(s => (!(s.sample_id in matchingEntriesBySampleId)));
        }

        return samplesToAdd;
    }

    function* allSamplesInDataset(datasetId, sampleIds) {
        let indexArgs = sampleIds.map(sid => [datasetId, sid]);
        let samples = yield r.table('dataset2sample').getAll(r.args(indexArgs), {index: 'dataset_sample'});
        return samples.length === sampleIds.length;
    }

    function* modifyDataset(datasetId, datasetArgs) {
        yield r.table('datasets').get(datasetId).update(datasetArgs);
        return yield getDataset(datasetId);
    }

    function* publishDataset() {
        return {error: `Not implemented`};
    }
};
<commit_msg>Don't add processes that are already in the dataset.<commit_after>module.exports = function(r) {
    const dbExec = require('./run');
    const db = require('./db')(r);
    const model = require('./model')(r);
    const commonQueries = require('./common-queries');
    const _ = require('lodash');

    return {
        getDatasetsForExperiment,
        getDataset,
        createDatasetForExperiment,
        addSampleToDataset,
        updateSamplesInDataset,
        allSamplesInDataset,
        modifyDataset,
        publishDataset
    };

    function* getDatasetsForExperiment(experimentId) {
        let rql = commonQueries.datasetDetailsRql(r.table('experiment2dataset').getAll(experimentId, {index: 'experiment_id'})
            .eqJoin('dataset_id', r.table('datasets')).zip(), r);
        let dataset = yield dbExec(rql);
        return {val: dataset};
    }

    function* getDataset(datasetId) {
        let rql = commonQueries.datasetDetailsRql(r.table('datasets').get(datasetId), r);
        let dataset = yield dbExec(rql);
        return {val: dataset};
    }

    function* createDatasetForExperiment(experimentId, userId, datasetArgs) {
        let dataset = new model.Dataset(datasetArgs.title, userId);
        dataset.description = datasetArgs.description;
        let created = yield db.insert('datasets', dataset);
        let e2d = new model.Experiment2Dataset(experimentId, created.id);
        yield r.table('experiment2dataset').insert(e2d);
        return yield getDataset(created.id);
    }

    function* addSampleToDataset(datasetId, sampleId) {
        let d2s = new model.Dataset2Sample(datasetId, sampleId);
        yield r.table('dataset2sample').insert(d2s);
        yield addProcessesForSampleToDataset(datasetId, sampleId);
        return yield getDataset(datasetId);
    }

    function* addProcessesForSampleToDataset(datasetId, sampleId) {
        let processes = yield r.table('process2sample').getAll(sampleId, {index: 'sample_id'});
        let uniqProcesses = uniqByKey(processes, 'process_id');
        let processesToInsert = uniqProcesses.map(p => new model.Dataset2Process(datasetId, p.process_id));
        processesToInsert = yield removeExistingProcessEntries(processesToInsert);
        if (processesToInsert.length) {
            yield r.table('dataset2process').insert(processesToInsert);
        }
    }

    function* removeExistingProcessEntries(processesToAdd) {
        if (processesToAdd.length) {
            let indexEntries = processesToAdd.map(p => [p.dataset_id, p.process_id]);
            let matchingEntries = yield r.table('dataset2process').getAll(r.args(indexEntries), {index: 'dataset_process'});
            let matchingEntriesByProcessId = _.indexBy(matchingEntries, 'process_id');
            return processesToAdd.filter(p => (!(p.process_id in matchingEntriesByProcessId)));
        }
        return processesToAdd;
    }

    function* updateSamplesInDataset(datasetId, samplesToAdd, samplesToDelete) {
        if (samplesToAdd.length) {
            let add = samplesToAdd.map(s => new model.Dataset2Sample(datasetId, s.id));
            add = yield removeExistingSampleEntriesInDataset(add);
            if (add.length) {
                yield r.table('dataset2sample').insert(add);
                yield addProcessesForSamplesToDataset(datasetId, samplesToAdd);
            }
        }

        if (samplesToDelete.length) {
            let toDelete = samplesToDelete.map(s => [datasetId, s.id]);
            yield r.table('dataset2sample').getAll(r.args(toDelete), {index: 'dataset_sample'}).delete();
        }

        return yield getDataset(datasetId);
    }

    function uniqByKey(items, key) {
        let uniqItems = _.indexBy(items, key);
        return Object.keys(uniqItems).map(key => uniqItems[key]);
    }

    function* addProcessesForSamplesToDataset(datasetId, samples) {
        let sampleIds = samples.map(s => s.id);
        let processes = yield r.table('process2sample').getAll(r.args(sampleIds), {index: 'sample_id'});
        let uniqProcesses = uniqByKey(processes, 'process_id');
        let processesToInsert = uniqProcesses.map(p => new model.Dataset2Process(datasetId, p.process_id));
        processesToInsert = yield removeExistingProcessEntries(processesToInsert);
        if (processesToInsert.length) {
            yield r.table('dataset2process').insert(processesToInsert);
        }
    }

    function* removeExistingSampleEntriesInDataset(samplesToAdd) {
        if (samplesToAdd.length) {
            let indexEntries = samplesToAdd.map(s => [s.dataset_id, s.sample_id]);
            let matchingEntries = yield r.table('dataset2sample').getAll(r.args(indexEntries), {index: 'dataset_sample'});
            let matchingEntriesBySampleId = _.indexBy(matchingEntries, 'sample_id');
            return samplesToAdd.filter(s => (!(s.sample_id in matchingEntriesBySampleId)));
        }

        return samplesToAdd;
    }

    function* allSamplesInDataset(datasetId, sampleIds) {
        let indexArgs = sampleIds.map(sid => [datasetId, sid]);
        let samples = yield r.table('dataset2sample').getAll(r.args(indexArgs), {index: 'dataset_sample'});
        return samples.length === sampleIds.length;
    }

    function* modifyDataset(datasetId, datasetArgs) {
        yield r.table('datasets').get(datasetId).update(datasetArgs);
        return yield getDataset(datasetId);
    }

    function* publishDataset() {
        return {error: `Not implemented`};
    }
};
<|endoftext|>


<commit_before>var Game = function(element, playerId) {
  console.log("GAME CREATED", playerId)
  this.element = $(element); // This element is game-container. We can put stuff there!
  this.init = function() {
    this.turn = 0
    this.center_deck = [];
    this.remaining_deck = [];
    this.players = [[],[],[],[]];
    this.ranks = ['1','1','1','2','2','3','3','4','4','5'];
    this.suites = ['A','B','C','D','E'];

    //Create the initial deck
    for (i = 0; i < this.ranks.length; i++) {
      for (j = 0; j < this.suites.length; j++){
        this.remaining_deck.push([this.ranks[i],this.suites[j]]);
      }
    }
    if (playerId == 0) {
      this.distributeCards(); //TODO(olivia): Make this something that naturally gets called during game start
      $('#your-turn').show();
    }

  };

  this.start = function() {
    this.init();
    this.bindEvents();
    var displayCards = this.players;
    displayCards.splice(playerId,1);

    //player can only see other players' cards
    //$('#card1').html(displayCards);
    //console.log(this.players[playerId]);
    if (playerId == 0) {
      $('#status').html('Your turn');
    } else {
      $('#status').html('Waiting for Player0 to play.');
    }

  }

  this.bindEvents = function() {
    $('#take-turn').click(function(e){
      e.preventDefault();
      $('#your-turn').hide();
      App.game.takeTurn(playerId, "play", ["5", "A"]); //TODO: Don't hard-code this.
    });

    $("#play-options input:radio").click(function(e) {
      this.turnType = e.target.value;
      switch(e.target.value) {
        case "play":
          $('#my-cards').show();
          $('#hints').hide();
          break;
        case "hint":
          $('#hints').show();
          $('#my-cards').hide();
          break;
        case "discard":
          $('#my-cards').show();
          $('#hints').hide();
          break;
        default:
          break;
      }
    });

  }

  this.distributeCards = function() {
    App.game.setup();
  };

  this.showCards = function(cards) {
    var handArr = []
    for (var hand of cards) {
      var cardStr = "["
      for (var card of hand) {
        cardStr += card[0] + card[1] + ", "
      }
      cardStr += "], "
      handArr += cardStr
    }

    $('#card1').html(handArr);
  }

  this.turnFinished = function() {
    console.log("turn before ", this.turn)
    // Later, do more with this turn
    console.log()
    this.turn = (this.turn + 1) % 2 //TODO(olivia): Later come back and don't hard code # players
    console.log("TURN: ", this.turn)
    if (this.turn == playerId) {
      $('#your-turn').show();
    }
  }

  this.start();

}
<commit_msg>Added a listener for which card is selected<commit_after>var Game = function(element, playerId) {
  console.log("GAME CREATED", playerId)
  this.element = $(element); // This element is game-container. We can put stuff there!
  this.init = function() {
    this.turn = 0
    this.center_deck = [];
    this.remaining_deck = [];
    this.players = [[],[],[],[]];
    this.ranks = ['1','1','1','2','2','3','3','4','4','5'];
    this.suites = ['A','B','C','D','E'];

    //Create the initial deck
    for (i = 0; i < this.ranks.length; i++) {
      for (j = 0; j < this.suites.length; j++){
        this.remaining_deck.push([this.ranks[i],this.suites[j]]);
      }
    }
    if (playerId == 0) {
      this.distributeCards(); //TODO(olivia): Make this something that naturally gets called during game start
      $('#your-turn').show();
    }

  };

  this.start = function() {
    this.init();
    this.bindEvents();
    var displayCards = this.players;
    displayCards.splice(playerId,1);

    //player can only see other players' cards
    //$('#card1').html(displayCards);
    //console.log(this.players[playerId]);
    if (playerId == 0) {
      $('#status').html('Your turn');
    } else {
      $('#status').html('Waiting for Player0 to play.');
    }

  }

  this.bindEvents = function() {
    $('#take-turn').click(function(e){
      e.preventDefault();
      $('#your-turn').hide();
      App.game.takeTurn(playerId, this.turnType, this.cardOption); //TODO: Don't hard-code this.
    });

    $("#play-options input:radio").click(function(e) {
      this.turnType = e.target.value;
      switch(e.target.value) {
        case "play":
          $('#my-cards').show();
          $('#hints').hide();
          break;
        case "hint":
          $('#hints').show();
          $('#my-cards').hide();
          break;
        case "discard":
          $('#my-cards').show();
          $('#hints').hide();
          break;
        default:
          break;
      }
    });

    $("#card-options input:radio").click(function(e) {
      this.cardOption = e.target.value;
    });

  }

  this.distributeCards = function() {
    App.game.setup();
  };

  this.showCards = function(cards) {
    var handArr = []
    for (var hand of cards) {
      var cardStr = "["
      for (var card of hand) {
        cardStr += card[0] + card[1] + ", "
      }
      cardStr += "], "
      handArr += cardStr
    }

    $('#card1').html(handArr);
  }

  this.turnFinished = function() {
    console.log("turn before ", this.turn)
    // Later, do more with this turn
    console.log()
    this.turn = (this.turn + 1) % 2 //TODO(olivia): Later come back and don't hard code # players
    console.log("TURN: ", this.turn)
    if (this.turn == playerId) {
      $('#your-turn').show();
    }
  }

  this.start();

}
<|endoftext|>


<commit_before>/*!
 * jQuery Mobile Widget v1.0
 * https://github.com/sebastian-meier/jquery.mobile.leaflet
 *
 * Copyright 2013, Sebastian Meier
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * This plugin requires the jQuery-, jQuery-Mobile & the Leaflet-Library
 *
 */(function($){$.widget("mobile.leaflet",$.mobile.widget,{options:{leafletAttribution:!0,config:{zoomControl:!1,zoom:11,attributionControl:!0,center:[52.52,13.41]},tileLayer:{url:"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",config:{attribution:'© OpenStreetMap contributors'}},marker:{},initSelector:".map"},_create:function(){var self=this,options=$.extend(this.options,this.element.jqmData("options")),map={element:this.element,id:this.element.attr("id"),map:undefined,marker:[],layer:[],lines:[]};self.map=map;typeof self.map.element.attr("data-zoom")!="undefined"&&(self.map.options.config.zoom=$(this).attr("data-zoom"));typeof self.map.element.attr("data-lat")!="undefined"&&typeof self.map.element.attr("data-lng")!="undefined"&&(self.map.options.config.center=[self.map.element.attr("data-lat"),self.map.element.attr("data-lng")]);self.map.map=new L.map(self.map.id,self.options.config);options.config.leafletAttribution||self.map.map.attributionControl.setPrefix("");self.map.layer.push(L.tileLayer(options.tileLayer.url,options.tileLayer.config).addTo(self.map.map));typeof self.map.element.attr("data-marker-lat")!="undefined"&&typeof self.map.element.attr("data-marker-lng")!="undefined"&&self.createMarker([self.map.element.attr("data-marker-lat"),self.map.element.attr("data-marker-lng")]);eval("typeof "+self.map.id+"_marker")!=="undefined"&&$.each(eval(self.map.id+"_marker"),function(e,t){self.createMarker(t)})},createMarker:function(e){var t,n,r=this;if(e instanceof Array){t=e[0];n=e[1]}else{if(!(e instanceof Object))return undefined;t=e.lat;n=e.lng;var i=$.extend(this.options.marker,e)}var s=L.marker(new L.LatLng(r.cleanCoordinate(t),r.cleanCoordinate(n)),i);s.addTo(r.map.map);r.map.marker.push(s);return s},cleanCoordinate:function(e){switch(typeof e){case"String":return parseFloat(e.replace(",","."));case"number":return parseFloat(e);default:return e}},clearMarker:function(){var e=this;$.each(e.map.marker,function(t,n){e.map.map.removeLayer(n)});e.map.marker=[]},clearLines:function(){var e=this;$.each(e.map.lines,function(t,n){e.map.map.removeLayer(n)});e.map.lines=[]},clearLayer:function(){var e=this;$.each(e.map.layer,function(t,n){e.map.map.removeLayer(n)});e.map.layer=[]},getMap:function(){return this.map.map},getData:function(){return this.map}})})(jQuery);<commit_msg>upaded minified see last comid<commit_after>/*!
 * jQuery Mobile Widget v1.0
 * https://github.com/sebastian-meier/jquery.mobile.leaflet
 *
 * Copyright 2013, Sebastian Meier
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * This plugin requires the jQuery-, jQuery-Mobile & the Leaflet-Library
 *
 */(function($){$.widget("mobile.leaflet",$.mobile.widget,{options:{leafletAttribution:!0,config:{zoomControl:!1,zoom:11,attributionControl:!0,center:[52.52,13.41]},tileLayer:{url:"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",config:{attribution:'© OpenStreetMap contributors'}},marker:{},initSelector:".map"},_create:function(){var self=this,options=$.extend(this.options,this.element.jqmData("options")),map={element:this.element,id:this.element.attr("id"),map:undefined,marker:[],layer:[],lines:[]};self.map=map;typeof self.map.element.attr("data-zoom")!="undefined"&&(self.options.config.zoom=$(this).attr("data-zoom"));typeof self.map.element.attr("data-lat")!="undefined"&&typeof self.map.element.attr("data-lng")!="undefined"&&(self.options.config.center=[self.map.element.attr("data-lat"),self.map.element.attr("data-lng")]);self.map.map=new L.map(self.map.id,self.options.config);options.config.leafletAttribution||self.map.map.attributionControl.setPrefix("");self.map.layer.push(L.tileLayer(options.tileLayer.url,options.tileLayer.config).addTo(self.map.map));typeof self.map.element.attr("data-marker-lat")!="undefined"&&typeof self.map.element.attr("data-marker-lng")!="undefined"&&self.createMarker([self.map.element.attr("data-marker-lat"),self.map.element.attr("data-marker-lng")]);eval("typeof "+self.map.id+"_marker")!=="undefined"&&$.each(eval(self.map.id+"_marker"),function(e,t){self.createMarker(t)})},createMarker:function(e){var t,n,r=this;if(e instanceof Array){t=e[0];n=e[1]}else{if(!(e instanceof Object))return undefined;t=e.lat;n=e.lng;var i=$.extend(this.options.marker,e)}var s=L.marker(new L.LatLng(r.cleanCoordinate(t),r.cleanCoordinate(n)),i);s.addTo(r.map.map);r.map.marker.push(s);return s},cleanCoordinate:function(e){switch(typeof e){case"String":return parseFloat(e.replace(",","."));case"number":return parseFloat(e);default:return e}},clearMarker:function(){var e=this;$.each(e.map.marker,function(t,n){e.map.map.removeLayer(n)});e.map.marker=[]},clearLines:function(){var e=this;$.each(e.map.lines,function(t,n){e.map.map.removeLayer(n)});e.map.lines=[]},clearLayer:function(){var e=this;$.each(e.map.layer,function(t,n){e.map.map.removeLayer(n)});e.map.layer=[]},getMap:function(){return this.map.map},getData:function(){return this.map}})})(jQuery);<|endoftext|>