<commit_before>'use strict';

angular.module('mage').directive('formDirective', function (FormService, ObservationService, UserService, FeatureAttachment, appConstants, mageLib, FeatureState) {
    return {
      templateUrl: 'js/app/partials/form/form.html',
      restrict: 'E',
      transclude: true,
      scope: {
        form: '=',
        formObservation: '=',
        formPreview: '='
      },
      controller: function($scope) {
        var uploadId = 0;

        $scope.getToken = mageLib.getToken;
        $scope.amAdmin = UserService.amAdmin;
        $scope.attachmentUploads = {};

        $scope.save = function() {
          $scope.form.getObservation().$save({}, function(observation) {
            $scope.formObservation = observation;
            if (_.some(_.values($scope.attachmentUploads), function(v) {return v;})) {
              $scope.observationSaved = true;
            } else {
              $scope.form = null;
              $scope.attachmentUploads = {};
            }

            // delete any attachments that are marked for delete
            var markedForDelete = _.filter($scope.formObservation.attachments, function(a){ return a.markedForDelete; });
            _.each(markedForDelete, function(attachment) {
              var data = {id: attachment.id, layerId: appConstants.featureLayer.id, featureId: $scope.formObservation.id};
              FeatureAttachment.delete(data, function(success) {
                $scope.$emit('attachmentDeleted', attachment);
              });
            });

            $scope.$emit('newObservationSaved', observation);
          });
        }

        $scope.cancelEdit = function() {
          $scope.form = null;
          $scope.attachmentUploads = [];
          _.each($scope.formObservation.attachments, function(attachment) {
            delete attachment.markedForDelete;
          });
        }

        $scope.deleteObservation = function() {
            console.log("delte it now");
            var observation = $scope.form.getObservation();

            console.log('making call to archive observation');
            FeatureState.save(
              {layerId: observation.layerId, featureId: observation.id},
              {name: 'archive'},
              function(state) {
                $scope.form = null;
                // $scope.deletedFeature = $scope.activeFeature;
                observation.state = state;
                $scope.$emit('observationDeleted', observation);
            });
        }

        $scope.addAttachment = function() {
          uploadId++;
          $scope.attachmentUploads[uploadId] = false;
        }

        $scope.removeFileUpload = function(id) {
          delete $scope.attachmentUploads[id];
        }

        $scope.$on('uploadComplete', function(e, url, response, id) {
          $scope.$emit('newAttachmentSaved', response, $scope.formObservation.id);

          delete $scope.attachmentUploads[id];
          if (_.keys($scope.attachmentUploads).length == 0) {
            $scope.form = null;
            $scope.observationSaved = false;
            $scope.attachmentUploads = {};
          }
        });

        $scope.$on('uploadFile', function(e, id) {
          $scope.attachmentUploads[id] = true;
        });
      }
    };
  });
<commit_msg>Fixed bug with not being able to delete attachments<commit_after>'use strict';

angular.module('mage').directive('formDirective', function (FormService, ObservationService, UserService, FeatureAttachment, appConstants, mageLib, FeatureState) {
    return {
      templateUrl: 'js/app/partials/form/form.html',
      restrict: 'E',
      transclude: true,
      scope: {
        form: '=',
        formObservation: '=',
        formPreview: '='
      },
      controller: function($scope) {
        var uploadId = 0;

        $scope.getToken = mageLib.getToken;
        $scope.amAdmin = UserService.amAdmin;
        $scope.attachmentUploads = {};

        $scope.save = function() {
          $scope.form.getObservation().$save({}, function(observation) {
            if (_.some(_.values($scope.attachmentUploads), function(v) {return v;})) {
              $scope.observationSaved = true;
            } else {
              $scope.form = null;
              $scope.attachmentUploads = {};
            }

            // delete any attachments that are marked for delete
            var markedForDelete = _.filter($scope.formObservation.attachments, function(a){ return a.markedForDelete; });
            _.each(markedForDelete, function(attachment) {
              var data = {id: attachment.id, layerId: appConstants.featureLayer.id, featureId: $scope.formObservation.id};
              FeatureAttachment.delete(data, function(success) {
                $scope.$emit('attachmentDeleted', attachment);
              });
            });

            $scope.formObservation = observation;
            $scope.$emit('newObservationSaved', observation);
          });
        }

        $scope.cancelEdit = function() {
          $scope.form = null;
          $scope.attachmentUploads = [];
          _.each($scope.formObservation.attachments, function(attachment) {
            delete attachment.markedForDelete;
          });
        }

        $scope.deleteObservation = function() {
            console.log("delte it now");
            var observation = $scope.form.getObservation();

            console.log('making call to archive observation');
            FeatureState.save(
              {layerId: observation.layerId, featureId: observation.id},
              {name: 'archive'},
              function(state) {
                $scope.form = null;
                // $scope.deletedFeature = $scope.activeFeature;
                observation.state = state;
                $scope.$emit('observationDeleted', observation);
            });
        }

        $scope.addAttachment = function() {
          uploadId++;
          $scope.attachmentUploads[uploadId] = false;
        }

        $scope.removeFileUpload = function(id) {
          delete $scope.attachmentUploads[id];
        }

        $scope.$on('uploadComplete', function(e, url, response, id) {
          $scope.$emit('newAttachmentSaved', response, $scope.formObservation.id);

          delete $scope.attachmentUploads[id];
          if (_.keys($scope.attachmentUploads).length == 0) {
            $scope.form = null;
            $scope.observationSaved = false;
            $scope.attachmentUploads = {};
          }
        });

        $scope.$on('uploadFile', function(e, id) {
          $scope.attachmentUploads[id] = true;
        });
      }
    };
  });
<|endoftext|>


<commit_before>describe('Unit : youtubePlugin content services', function () {
    var Buildfire;
    beforeEach(module('youtubePluginContent'));

    beforeEach(inject(function (_Buildfire_) {
        Buildfire = _Buildfire_;
    }));

    describe('Provider : Buildfire', function () {
        it('Buildfire should exist and be an object', function () {
            expect(typeof Buildfire).toEqual('object');
        });
    });
});
<commit_msg>Appended test cases for content/app.services.js<commit_after>describe('Unit : youtubePlugin content services', function () {
    describe('Unit: Buildfire Provider', function () {
        var Buildfire;
        beforeEach(module('youtubePluginContent'));

        beforeEach(inject(function (_Buildfire_) {
            Buildfire = _Buildfire_;
        }));

        it('Buildfire should exist and be an object', function () {
            expect(typeof Buildfire).toEqual('object');
        });
    });
    describe('Unit : DataStore Factory', function () {
        var DataStore, Buildfire, STATUS_MESSAGES, STATUS_CODE, q;
        beforeEach(module('youtubePluginContent'));
        beforeEach(inject(function (_DataStore_, _STATUS_CODE_, _STATUS_MESSAGES_) {
            DataStore = _DataStore_;
            STATUS_CODE = _STATUS_CODE_;
            STATUS_MESSAGES = _STATUS_MESSAGES_;
            Buildfire = {
                datastore: {}
            };
            Buildfire.datastore = jasmine.createSpyObj('Buildfire.datastore', ['get', 'bulkInsert', 'insert', 'search', 'update', 'save', 'delete']);
        }));

        it('DataStore should exist and be an object', function () {
            expect(typeof DataStore).toEqual('object');
        });
        it('DataStore.get should exist and be an function', function () {
            expect(typeof DataStore.get).toEqual('function');
        });
        it('DataStore.getById should exist and be an function', function () {
            expect(typeof DataStore.getById).toEqual('function');
        });
        it('DataStore.insert should exist and be an function', function () {
            expect(typeof DataStore.insert).toEqual('function');
        });
        it('DataStore.bulkInsert should exist and be an function', function () {
            expect(typeof DataStore.bulkInsert).toEqual('function');
        });
        it('DataStore.search should exist and be an function', function () {
            expect(typeof DataStore.search).toEqual('function');
        });
        it('DataStore.update should exist and be an function', function () {
            expect(typeof DataStore.update).toEqual('function');
        });
        it('DataStore.save should exist and be an function', function () {
            expect(typeof DataStore.save).toEqual('function');
        });
        it('DataStore.deleteById should exist and be an function', function () {
            expect(typeof DataStore.deleteById).toEqual('function');
        });
    });
    describe('Unit : ImageLibrary Factory', function () {
        var ImageLibrary, Buildfire, STATUS_MESSAGES, STATUS_CODE, q;
        beforeEach(module('youtubePluginContent'));

        beforeEach(inject(function (_ImageLibrary_, _STATUS_CODE_, _STATUS_MESSAGES_, _$q_) {
            ImageLibrary = _ImageLibrary_;
            STATUS_CODE = _STATUS_CODE_;
            STATUS_MESSAGES = _STATUS_MESSAGES_;
            Buildfire = {
                imageLib: {}
            };
            Buildfire.imageLib = jasmine.createSpyObj('Buildfire.imageLib', ['showDialog']);
        }));

        it('Buildfire should exist and be an object', function () {
            expect(typeof Buildfire).toEqual('object');
        });
        it('Buildfire.imageLib should exist and be an object', function () {
            expect(typeof Buildfire.imageLib).toEqual('object');
        });
        it('ImageLibrary should exist and be an object', function () {
            expect(typeof ImageLibrary).toEqual('object');
        });
        it('ImageLibrary.showDialog should exist and be an function', function () {
            expect(typeof ImageLibrary.showDialog).toEqual('function');
        });
    });
    describe('Unit : ActionItems Factory', function () {
        var ActionItems, Buildfire, STATUS_MESSAGES, STATUS_CODE, q;
        beforeEach(module('youtubePluginContent'));

        beforeEach(inject(function (_ActionItems_, _STATUS_CODE_, _STATUS_MESSAGES_, _$q_) {
            ActionItems = _ActionItems_;
            STATUS_CODE = _STATUS_CODE_;
            STATUS_MESSAGES = _STATUS_MESSAGES_;
            Buildfire = {
                actionItems: {}
            };
            Buildfire.actionItems = jasmine.createSpyObj('Buildfire.actionItems', ['showDialog']);
        }));

        it('Buildfire should exist and be an object', function () {
            expect(typeof Buildfire).toEqual('object');
        });
        it('Buildfire.actionItems should exist and be an object', function () {
            expect(typeof Buildfire.actionItems).toEqual('object');
        });
        it('Buildfire.actionItems.showDialog should exist and be an function', function () {
            expect(typeof Buildfire.actionItems.showDialog).toEqual('function');
        });
        it('ActionItems should exist and be an object', function () {
            expect(typeof ActionItems).toEqual('object');
        });
        it('ActionItems.showDialog should exist and be an function', function () {
            expect(typeof ActionItems.showDialog).toEqual('function');
        });
    });
})
;
<|endoftext|>


<commit_before>Astriarch.NewGameControl = {
	GameCreator: true, //if the player created the game
	StarfieldCanvas: null,
	StarfieldCanvasContext: null,
	StarfieldCanvasSize: {w:200, h:170},
	init: function(){

		this.StarfieldCanvas = document.getElementById("newGameControlStarfieldCanvas");
		this.StarfieldCanvasContext = this.StarfieldCanvas.getContext("2d");

		$("#GameNameTextBox").val(Astriarch.LocalStorageInterface.Prefs.gameName);
		$("#GameNameTextBox").change(function(){
			var name = $("#GameNameTextBox").val();
			Astriarch.LocalStorageInterface.Prefs.gameName = name;
			Astriarch.LocalStorageInterface.savePrefs();
			Astriarch.NewGameControl.changedGameOptions();
		});

		$("#PlayerNameTextBox").val(Astriarch.LocalStorageInterface.Prefs.playerName);
		$("#PlayerNameTextBox").change(function(){
			var playerName = $( this ).val();
			Astriarch.LocalStorageInterface.Prefs.playerName = playerName;
			Astriarch.LocalStorageInterface.savePrefs();
			var payload = {playerName: playerName};
			Astriarch.server_comm.sendMessage({type:Astriarch.Shared.MESSAGE_TYPE.CHANGE_PLAYER_NAME, payload:payload});
		});

		$('select#NumberOfSystemsComboBox').selectmenu({style:'popup', width:55, change:function(e, object){Astriarch.NewGameControl.UpdateStartupOptionsBasedOnOpponentCount();Astriarch.NewGameControl.changedGameOptions();}});
		$('select#PlanetsPerSystemComboBox').selectmenu({style:'popup', width:55, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });

		$('input#DistributePlanetsEvenlyCheckBox').change(function(){
			Astriarch.NewGameControl.changedGameOptions();
		});

		$('select#TurnTimeLimitComboBox').selectmenu({style:'popup', width:120, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });

		this.buildPlayerComboBoxes();

		$("#StartGameOptionsOkButton").button();
		$("#StartGameOptionsOkButton").click(
			function() {
				if(window.tour.enabled){
					window.tour.jqElm.joyride('nextTip');
				}
				Astriarch.NewGameControl.SetupNewGame();
			}
		);

		//Display the canvas representation
		var gameOptions = this.getSelectedGameOptions();
		this.drawGameOptionsRepresentationOnCanvas(gameOptions);
	},

	buildPlayerComboBoxes: function(gameOptions){
		var closedOption = '<option value="-2">Closed</option>';
		var openOption = '<option value="-1" selected="">Open</option>';
		var humanOption = '<option value="0" disabled="disabled">Human</option>';
		var computerOptions = '<option value="1">Easy Computer</option><option value="2">Normal Computer</option><option value="3">Hard Computer</option><option value="4">Expert Computer</option>';
		$("#Player2OptionsBox").html('<select id="Player2ComboBox">' + openOption + ((gameOptions && gameOptions.opponentOptions[0].type == 0) ? humanOption : "") + computerOptions  +'</select>');
		$("#Player3OptionsBox").html('<select id="Player3ComboBox">' + closedOption + openOption + ((gameOptions && gameOptions.opponentOptions[1].type == 0) ? humanOption : "") + computerOptions  +'</select>');
		$("#Player4OptionsBox").html('<select id="Player4ComboBox">' + closedOption + openOption + ((gameOptions && gameOptions.opponentOptions[2].type == 0) ? humanOption : "") + computerOptions  +'</select>');

		//jquery ui selectmenu
		//from https://github.com/fnagel/jquery-ui
		//also here: http://jquerystyle.com/2009/08/24/jquery-ui-selectmenu
		$('select#Player2ComboBox').selectmenu({style:'popup',width:150, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });
		$('select#Player3ComboBox').selectmenu({style:'popup',width:150, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });
		$('select#Player4ComboBox').selectmenu({style:'popup',width:150, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });
	},

	UpdateStartupOptionsBasedOnOpponentCount: function() {
		var numberOfOpponents = Number($('select#NumberOfSystemsComboBox').selectmenu("value"));
		$('.Player3Panel').hide();
		$('.Player4Panel').hide();

		if (numberOfOpponents >= 3) {
			$('.Player3Panel').show();
		} else {
			$('select#Player3ComboBox').selectmenu("value","-2");
		}
		if (numberOfOpponents >= 4){
			$('.Player4Panel').show();
		} else {
			$('select#Player4ComboBox').selectmenu("value","-2");
		}
	},

	newGame: function(){
		//join the chat room for this game
		Astriarch.CommControl.joinChatRoom(Astriarch.LocalStorageInterface.Prefs.playerName, 1);
	},

	joinGame: function(message){
		Astriarch.NewGameControl.GameCreator = false;

		$("#GameNameTextBox").parent().html('');

		$('select#NumberOfSystemsComboBox').parent().html('');
		$('select#PlanetsPerSystemComboBox').parent().html('');

		$('input#DistributePlanetsEvenlyCheckBox').parent().html('');
		$('select#TurnTimeLimitComboBox').parent().html('');

		$('select#Player2ComboBox').parent().html('');
		$('select#Player3ComboBox').parent().html('');
		$('select#Player4ComboBox').parent().html('');
		$("#StartGameOptionsOkButton").remove();

		Astriarch.NewGameControl.OnGameOptionsChanged(message);

		//join the chat room for this game
		Astriarch.CommControl.joinChatRoom(Astriarch.LocalStorageInterface.Prefs.playerName, (message.payload.playerPosition + 1));
	},

	changedGameOptions: function() {
		var gameOptions = this.getSelectedGameOptions();
		var name = $("#GameNameTextBox").val();
		this.drawGameOptionsRepresentationOnCanvas(gameOptions);

		Astriarch.server_comm.sendMessage({type:Astriarch.Shared.MESSAGE_TYPE.CHANGE_GAME_OPTIONS, payload:{gameOptions: gameOptions, name:name}});

		if(window.tour.enabled && ((gameOptions.systemsToGenerate == 2 && window.tour.step == 3) || (gameOptions.opponentOptions[0].type == 1 && window.tour.step == 4))){
			window.tour.jqElm.joyride('nextTip');
		}
	},

	OnGameOptionsChanged: function(message){
		var gameOptions = message.payload.gameOptions;
		this.drawGameOptionsRepresentationOnCanvas(gameOptions);
		//refresh view with new game options
		if(!Astriarch.NewGameControl.GameCreator){
			$("#GameNameValue").text(message.payload.name);

			$("#NumberOfSystemsValue").text(gameOptions.systemsToGenerate);
			$("#PlanetsPerSystemValue").text(gameOptions.planetsPerSystem);
			$("#DistributePlanetsEvenlyValue").text("Distribute Planets Evenly: " + gameOptions.distributePlanetsEvenly);
			var turnTimeLimitMinutes = gameOptions.turnTimeLimitSeconds / 60;
			$("#TurnTimeLimitValue").text("Turn Time Limit: " + (turnTimeLimitMinutes == 0 ? "None" : (turnTimeLimitMinutes == 1 ? "1 Minute" : turnTimeLimitMinutes + " Minutes")));

			$("#Player1NamePanel").text(gameOptions.mainPlayerName);
			$("#Player2NamePanel").text(Astriarch.GameTools.OpponentOptionToFriendlyString(gameOptions.opponentOptions[0]));
			$("#Player3NamePanel").text(Astriarch.GameTools.OpponentOptionToFriendlyString(gameOptions.opponentOptions[1]));
			$("#Player4NamePanel").text(Astriarch.GameTools.OpponentOptionToFriendlyString(gameOptions.opponentOptions[2]));
		} else {
			Astriarch.NewGameControl.buildPlayerComboBoxes(gameOptions);
			//we get this message for player name changes and joins also
			for(var i = 0; i < gameOptions.opponentOptions.length; i++){
				var opponent = gameOptions.opponentOptions[i];
				if(opponent.type == 0){
					var selectId = 'select#Player' + (i + 2) + 'ComboBox';
					$(selectId).selectmenu("value","0");
					$('#Player' + (i + 2) + 'OptionsBox').hide();
					$('#Player' + (i + 2) + 'NamePanel').text(opponent.name);
					//TODO: Add Kick button for GameCreator
				}
			}
		}
		var playerSessions = [{playerName:gameOptions.mainPlayerName, playerNumber: 1, dateJoined: new Date()}];
		for(var i = 0; i < gameOptions.opponentOptions.length; i++){
			if(gameOptions.opponentOptions[i].type >= 0){
				playerSessions.push({playerName:gameOptions.opponentOptions[i].name, playerNumber: i+2, dateJoined: new Date()});
			}
		}

		Astriarch.CommControl.setPlayerSessions(playerSessions);

	},

	getSelectedGameOptions: function(){
		var opponentOptions = [];
		var playerName = $('#PlayerNameTextBox').val();
		if(playerName == null || $.trim(playerName) == "")
			playerName = "Player";

		//NOTE: difficulty Combobox values correspond to Astriarch.Player.PlayerType 'enum' values (with -1 meaning closed)
		opponentOptions.push({name: $("#Player2NamePanel").text(), type: Number($('select#Player2ComboBox').selectmenu("value"))});
		opponentOptions.push({name: $("#Player3NamePanel").text(), type: Number($('select#Player3ComboBox').selectmenu("value"))});
		opponentOptions.push({name: $("#Player4NamePanel").text(), type: Number($('select#Player4ComboBox').selectmenu("value"))});

		var systemsToGenerate = Number($('select#NumberOfSystemsComboBox').selectmenu("value"));
		//NOTE: systems to generate combobox values correspond to Astriarch.Model.PlanetsPerSystemOption 'enum' values
		var planetsPerSystem = Number($('select#PlanetsPerSystemComboBox').selectmenu("value"));

		var distributePlanetsEvenly = true;
		if(!$('#DistributePlanetsEvenlyCheckBox').attr('checked')){
			distributePlanetsEvenly = false;
		}

		var turnTimeLimitSeconds = Number($('select#TurnTimeLimitComboBox').selectmenu("value"));

		var gameOptions = {"mainPlayerName":playerName, "opponentOptions": opponentOptions, "systemsToGenerate":systemsToGenerate, "planetsPerSystem":planetsPerSystem, "distributePlanetsEvenly":distributePlanetsEvenly, "turnTimeLimitSeconds": turnTimeLimitSeconds};
		return gameOptions;
	},

	SetupNewGame: function() {

		//get selected game options
		var gameOptions = this.getSelectedGameOptions();

		var playerCount = 1;
		for(var i in gameOptions.opponentOptions){
			if(gameOptions.opponentOptions[i].type >= 0){
				playerCount++;
			}
		}

		AstriarchExtern.OnGameStart({'Players':playerCount, 'PlanetsPerSystem':gameOptions.planetsPerSystem, 'Systems':gameOptions.systemsToGenerate});
		Astriarch.server_comm.sendMessage({type:Astriarch.Shared.MESSAGE_TYPE.START_GAME, payload:gameOptions});
	},

	OnGameStartMessageResponse: function(message) {

		$('#startGameOptionsContainer').hide();

		Astriarch.GameController.ResetView(message.payload);
	},

	drawGameOptionsRepresentationOnCanvas: function(gameOptions) {
		var width = this.StarfieldCanvasSize.w;
		var halfWidth = width/2;
		var height = this.StarfieldCanvasSize.h;
		var halfHeight = height/2;
		this.StarfieldCanvasContext.clearRect(0, 0, width, height);

		for(var i = 0; i < gameOptions.systemsToGenerate; i++){

			var x = 0;
			var y = 0;
			if((gameOptions.systemsToGenerate == 2 && i == 1) || (gameOptions.systemsToGenerate == 4 && i == 3)) {
				x = halfWidth;
				y = halfHeight;
			} else if ((gameOptions.systemsToGenerate == 3 || gameOptions.systemsToGenerate == 4) && i == 1) {
				x = halfWidth;
			} else if (gameOptions.systemsToGenerate == 3 && i == 2) {
				x = width / 4;
				y = halfHeight;
			} else if (gameOptions.systemsToGenerate == 4 && i == 2) {
				y = halfHeight;
			}

			// set up gradient
			var radialGradient = this.StarfieldCanvasContext.createRadialGradient(
				x + halfWidth/2, y + halfHeight/2, 0,
				x + halfWidth/2, y + halfHeight/2, this.StarfieldCanvasSize.h/4);

			var color = Astriarch.View.Colors[0];//white
			if(i == 0 || gameOptions.opponentOptions[i - 1].type >= 0) {
				color = Astriarch.Model.PlayerColors[i];
			}

			radialGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
			radialGradient.addColorStop(0.9, color);
			radialGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');

			// draw gradient
			this.StarfieldCanvasContext.fillStyle = radialGradient;
			this.StarfieldCanvasContext.fillRect(x, y, halfWidth, halfHeight);
		}

	}
};
<commit_msg>for 1.6.3: fixed bug in drawGameOptionsRepresentationOnCanvas where computer 2 and computer 3's colors were being swapped<commit_after>Astriarch.NewGameControl = {
	GameCreator: true, //if the player created the game
	StarfieldCanvas: null,
	StarfieldCanvasContext: null,
	StarfieldCanvasSize: {w:200, h:170},
	init: function(){

		this.StarfieldCanvas = document.getElementById("newGameControlStarfieldCanvas");
		this.StarfieldCanvasContext = this.StarfieldCanvas.getContext("2d");

		$("#GameNameTextBox").val(Astriarch.LocalStorageInterface.Prefs.gameName);
		$("#GameNameTextBox").change(function(){
			var name = $("#GameNameTextBox").val();
			Astriarch.LocalStorageInterface.Prefs.gameName = name;
			Astriarch.LocalStorageInterface.savePrefs();
			Astriarch.NewGameControl.changedGameOptions();
		});

		$("#PlayerNameTextBox").val(Astriarch.LocalStorageInterface.Prefs.playerName);
		$("#PlayerNameTextBox").change(function(){
			var playerName = $( this ).val();
			Astriarch.LocalStorageInterface.Prefs.playerName = playerName;
			Astriarch.LocalStorageInterface.savePrefs();
			var payload = {playerName: playerName};
			Astriarch.server_comm.sendMessage({type:Astriarch.Shared.MESSAGE_TYPE.CHANGE_PLAYER_NAME, payload:payload});
		});

		$('select#NumberOfSystemsComboBox').selectmenu({style:'popup', width:55, change:function(e, object){Astriarch.NewGameControl.UpdateStartupOptionsBasedOnOpponentCount();Astriarch.NewGameControl.changedGameOptions();}});
		$('select#PlanetsPerSystemComboBox').selectmenu({style:'popup', width:55, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });

		$('input#DistributePlanetsEvenlyCheckBox').change(function(){
			Astriarch.NewGameControl.changedGameOptions();
		});

		$('select#TurnTimeLimitComboBox').selectmenu({style:'popup', width:120, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });

		this.buildPlayerComboBoxes();

		$("#StartGameOptionsOkButton").button();
		$("#StartGameOptionsOkButton").click(
			function() {
				if(window.tour.enabled){
					window.tour.jqElm.joyride('nextTip');
				}
				Astriarch.NewGameControl.SetupNewGame();
			}
		);

		//Display the canvas representation
		var gameOptions = this.getSelectedGameOptions();
		this.drawGameOptionsRepresentationOnCanvas(gameOptions);
	},

	buildPlayerComboBoxes: function(gameOptions){
		var closedOption = '<option value="-2">Closed</option>';
		var openOption = '<option value="-1" selected="">Open</option>';
		var humanOption = '<option value="0" disabled="disabled">Human</option>';
		var computerOptions = '<option value="1">Easy Computer</option><option value="2">Normal Computer</option><option value="3">Hard Computer</option><option value="4">Expert Computer</option>';
		$("#Player2OptionsBox").html('<select id="Player2ComboBox">' + openOption + ((gameOptions && gameOptions.opponentOptions[0].type == 0) ? humanOption : "") + computerOptions  +'</select>');
		$("#Player3OptionsBox").html('<select id="Player3ComboBox">' + closedOption + openOption + ((gameOptions && gameOptions.opponentOptions[1].type == 0) ? humanOption : "") + computerOptions  +'</select>');
		$("#Player4OptionsBox").html('<select id="Player4ComboBox">' + closedOption + openOption + ((gameOptions && gameOptions.opponentOptions[2].type == 0) ? humanOption : "") + computerOptions  +'</select>');

		//jquery ui selectmenu
		//from https://github.com/fnagel/jquery-ui
		//also here: http://jquerystyle.com/2009/08/24/jquery-ui-selectmenu
		$('select#Player2ComboBox').selectmenu({style:'popup',width:150, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });
		$('select#Player3ComboBox').selectmenu({style:'popup',width:150, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });
		$('select#Player4ComboBox').selectmenu({style:'popup',width:150, change: function(e, object){Astriarch.NewGameControl.changedGameOptions();} });
	},

	UpdateStartupOptionsBasedOnOpponentCount: function() {
		var numberOfOpponents = Number($('select#NumberOfSystemsComboBox').selectmenu("value"));
		$('.Player3Panel').hide();
		$('.Player4Panel').hide();

		if (numberOfOpponents >= 3) {
			$('.Player3Panel').show();
		} else {
			$('select#Player3ComboBox').selectmenu("value","-2");
		}
		if (numberOfOpponents >= 4){
			$('.Player4Panel').show();
		} else {
			$('select#Player4ComboBox').selectmenu("value","-2");
		}
	},

	newGame: function(){
		//join the chat room for this game
		Astriarch.CommControl.joinChatRoom(Astriarch.LocalStorageInterface.Prefs.playerName, 1);
	},

	joinGame: function(message){
		Astriarch.NewGameControl.GameCreator = false;

		$("#GameNameTextBox").parent().html('');

		$('select#NumberOfSystemsComboBox').parent().html('');
		$('select#PlanetsPerSystemComboBox').parent().html('');

		$('input#DistributePlanetsEvenlyCheckBox').parent().html('');
		$('select#TurnTimeLimitComboBox').parent().html('');

		$('select#Player2ComboBox').parent().html('');
		$('select#Player3ComboBox').parent().html('');
		$('select#Player4ComboBox').parent().html('');
		$("#StartGameOptionsOkButton").remove();

		Astriarch.NewGameControl.OnGameOptionsChanged(message);

		//join the chat room for this game
		Astriarch.CommControl.joinChatRoom(Astriarch.LocalStorageInterface.Prefs.playerName, (message.payload.playerPosition + 1));
	},

	changedGameOptions: function() {
		var gameOptions = this.getSelectedGameOptions();
		var name = $("#GameNameTextBox").val();
		this.drawGameOptionsRepresentationOnCanvas(gameOptions);

		Astriarch.server_comm.sendMessage({type:Astriarch.Shared.MESSAGE_TYPE.CHANGE_GAME_OPTIONS, payload:{gameOptions: gameOptions, name:name}});

		if(window.tour.enabled && ((gameOptions.systemsToGenerate == 2 && window.tour.step == 3) || (gameOptions.opponentOptions[0].type == 1 && window.tour.step == 4))){
			window.tour.jqElm.joyride('nextTip');
		}
	},

	OnGameOptionsChanged: function(message){
		var gameOptions = message.payload.gameOptions;
		this.drawGameOptionsRepresentationOnCanvas(gameOptions);
		//refresh view with new game options
		if(!Astriarch.NewGameControl.GameCreator){
			$("#GameNameValue").text(message.payload.name);

			$("#NumberOfSystemsValue").text(gameOptions.systemsToGenerate);
			$("#PlanetsPerSystemValue").text(gameOptions.planetsPerSystem);
			$("#DistributePlanetsEvenlyValue").text("Distribute Planets Evenly: " + gameOptions.distributePlanetsEvenly);
			var turnTimeLimitMinutes = gameOptions.turnTimeLimitSeconds / 60;
			$("#TurnTimeLimitValue").text("Turn Time Limit: " + (turnTimeLimitMinutes == 0 ? "None" : (turnTimeLimitMinutes == 1 ? "1 Minute" : turnTimeLimitMinutes + " Minutes")));

			$("#Player1NamePanel").text(gameOptions.mainPlayerName);
			$("#Player2NamePanel").text(Astriarch.GameTools.OpponentOptionToFriendlyString(gameOptions.opponentOptions[0]));
			$("#Player3NamePanel").text(Astriarch.GameTools.OpponentOptionToFriendlyString(gameOptions.opponentOptions[1]));
			$("#Player4NamePanel").text(Astriarch.GameTools.OpponentOptionToFriendlyString(gameOptions.opponentOptions[2]));
		} else {
			Astriarch.NewGameControl.buildPlayerComboBoxes(gameOptions);
			//we get this message for player name changes and joins also
			for(var i = 0; i < gameOptions.opponentOptions.length; i++){
				var opponent = gameOptions.opponentOptions[i];
				if(opponent.type == 0){
					var selectId = 'select#Player' + (i + 2) + 'ComboBox';
					$(selectId).selectmenu("value","0");
					$('#Player' + (i + 2) + 'OptionsBox').hide();
					$('#Player' + (i + 2) + 'NamePanel').text(opponent.name);
					//TODO: Add Kick button for GameCreator
				}
			}
		}
		var playerSessions = [{playerName:gameOptions.mainPlayerName, playerNumber: 1, dateJoined: new Date()}];
		for(var i = 0; i < gameOptions.opponentOptions.length; i++){
			if(gameOptions.opponentOptions[i].type >= 0){
				playerSessions.push({playerName:gameOptions.opponentOptions[i].name, playerNumber: i+2, dateJoined: new Date()});
			}
		}

		Astriarch.CommControl.setPlayerSessions(playerSessions);

	},

	getSelectedGameOptions: function(){
		var opponentOptions = [];
		var playerName = $('#PlayerNameTextBox').val();
		if(playerName == null || $.trim(playerName) == "")
			playerName = "Player";

		//NOTE: difficulty Combobox values correspond to Astriarch.Player.PlayerType 'enum' values (with -1 meaning closed)
		opponentOptions.push({name: $("#Player2NamePanel").text(), type: Number($('select#Player2ComboBox').selectmenu("value"))});
		opponentOptions.push({name: $("#Player3NamePanel").text(), type: Number($('select#Player3ComboBox').selectmenu("value"))});
		opponentOptions.push({name: $("#Player4NamePanel").text(), type: Number($('select#Player4ComboBox').selectmenu("value"))});

		var systemsToGenerate = Number($('select#NumberOfSystemsComboBox').selectmenu("value"));
		//NOTE: systems to generate combobox values correspond to Astriarch.Model.PlanetsPerSystemOption 'enum' values
		var planetsPerSystem = Number($('select#PlanetsPerSystemComboBox').selectmenu("value"));

		var distributePlanetsEvenly = true;
		if(!$('#DistributePlanetsEvenlyCheckBox').attr('checked')){
			distributePlanetsEvenly = false;
		}

		var turnTimeLimitSeconds = Number($('select#TurnTimeLimitComboBox').selectmenu("value"));

		var gameOptions = {"mainPlayerName":playerName, "opponentOptions": opponentOptions, "systemsToGenerate":systemsToGenerate, "planetsPerSystem":planetsPerSystem, "distributePlanetsEvenly":distributePlanetsEvenly, "turnTimeLimitSeconds": turnTimeLimitSeconds};
		return gameOptions;
	},

	SetupNewGame: function() {

		//get selected game options
		var gameOptions = this.getSelectedGameOptions();

		var playerCount = 1;
		for(var i in gameOptions.opponentOptions){
			if(gameOptions.opponentOptions[i].type >= 0){
				playerCount++;
			}
		}

		AstriarchExtern.OnGameStart({'Players':playerCount, 'PlanetsPerSystem':gameOptions.planetsPerSystem, 'Systems':gameOptions.systemsToGenerate});
		Astriarch.server_comm.sendMessage({type:Astriarch.Shared.MESSAGE_TYPE.START_GAME, payload:gameOptions});
	},

	OnGameStartMessageResponse: function(message) {

		$('#startGameOptionsContainer').hide();

		Astriarch.GameController.ResetView(message.payload);
	},

	drawGameOptionsRepresentationOnCanvas: function(gameOptions) {
		var width = this.StarfieldCanvasSize.w;
		var halfWidth = width/2;
		var height = this.StarfieldCanvasSize.h;
		var halfHeight = height/2;
		this.StarfieldCanvasContext.clearRect(0, 0, width, height);

		for(var i = 0; i < gameOptions.systemsToGenerate; i++){

			var x = 0;
			var y = 0;
			if((gameOptions.systemsToGenerate == 2 && i == 1) || (gameOptions.systemsToGenerate == 4 && i == 2)) {
				x = halfWidth;
				y = halfHeight;
			} else if ((gameOptions.systemsToGenerate == 3 || gameOptions.systemsToGenerate == 4) && i == 1) {
				x = halfWidth;
			} else if (gameOptions.systemsToGenerate == 3 && i == 2) {
				x = width / 4;
				y = halfHeight;
			} else if (gameOptions.systemsToGenerate == 4 && i == 3) {
				y = halfHeight;
			}

			// set up gradient
			var radialGradient = this.StarfieldCanvasContext.createRadialGradient(
				x + halfWidth/2, y + halfHeight/2, 0,
				x + halfWidth/2, y + halfHeight/2, this.StarfieldCanvasSize.h/4);

			var color = Astriarch.View.Colors[0];//white
			if(i == 0 || gameOptions.opponentOptions[i - 1].type >= 0) {
				color = Astriarch.Model.PlayerColors[i];
			}

			radialGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
			radialGradient.addColorStop(0.9, color);
			radialGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');

			// draw gradient
			this.StarfieldCanvasContext.fillStyle = radialGradient;
			this.StarfieldCanvasContext.fillRect(x, y, halfWidth, halfHeight);
		}

	}
};
<|endoftext|>


<commit_before>Template.signup.events({
  'submit form': function(e){
    // Prevent form from submitting.
    e.preventDefault();

    var error = false;

    (function ($) {
  $(document).ready(function() {
    // Function to update labels of text fields
    Materialize.updateTextFields = function() {
      var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';
      $(input_selector).each(function(index, element) {
        if ($(element).val().length > 0 || element.autofocus ||$(this).attr('placeholder') !== undefined || $(element)[0].validity.badInput === true) {
          $(this).siblings('label').addClass('active');
        }
        else {
          $(this).siblings('label').removeClass('active');
        }
      });
    };

    //// Grab the student's details.
    var student = {
      firstName: $('[name="firstName"]').val(),
      middleName: $('[name="middleName"]').val(),
      lastName: $('[name="lastName"]').val(),
      DOB: $('[name="DOB"]').val(),
      studentGrade: $('[name="studentGrade"]').val(),
      emailAddress: $('[name="emailAddress"]').val(),
      password: $('[name="password"]').val(),
      studentPhoneNo: $('[name="studentPhoneNo"]').val(),
      studentId: $('[name="studentId"]').val(),
      facebookAccount: $('[name="facebookAccount"]').val(),
      facebookEvsd: $('[name="facebookEvsd"]').val(),
      schoolloopEvsd: $('[name="schoolloopEvsd"]').val(),
    };
    var parent = {
        firstParent: $('[name="firstParent"]').val(),
        firstParentPhoneNo: $('[name="firstParentPhoneNo"]').val(),
        firstParentEmailAddress: $('[name="firstParentEmailAddress"]').val(),
        firstParentEmployer: $('[name="firstParentEmployer"]').val(),
        secondParent: $('[name="secondParent"]').val(),
        secondParentPhoneNo: $('[name="secondParentPhoneNo"]').val(),
        secondParentEmailAddress: $('[name="secondParentEmailAddress"]').val(),
        secondParentEmployer: $('[name="secondParentEmployer"]').val()
    };
    var misc = {
        findOut: $('[name="findOut"]').val(),
        whyjoin: $('[name="whyjoin"]').val(),
        concerns: $('[name="concerns"]').val()
    };

    // Get the values:
    var ccNum = $('[data-stripe="cardNumber"]').val(),
        cvcNum =$('[data-stripe="cvc"]').val(),
        expMonth = $('[data-stripe="expMo"]').val(),
        expYear = $('[data-stripe="expYr"]').val(),
        name = $('[data-stripe="cardholder_name"]').val(),
        address_line1 = $('[data-stripe="address_line1"]').val(),
        address_line2 = $('[data-stripe="address_line2"]').val(),
        address_city = $('[data-stripe="address_city"]').val(),
        address_state = $('[data-stripe="address_state"]').val(),
        address_zip = $('[data-stripe="address_zip"]').val(),
        address_country = $('[data-stripe="address_country"]').val();

      if ((ccNum == null || ccNum == "") && (cvcNum == null || cvcNum == "") && (expMonth == null || expMonth == "") && (expYear == null || expYear == "") && (name == null || name == "") && (address_line1 == null || address_line1 == "")
          && (address_line2 == null || address_line2 == "") && (address_city == null || address_city == "") && (address_state == null || address_state == "") && (address_zip == null || address_zip == "") && (address_country == null || address_country == "")) {

            error = true;

          var name = $('[name="firstName"]').val(),
              emailAddress = $('[name="emailAddress"]').val(),
              password = $('[name="password"]').val();

        Meteor.call('createreguser', student, parent, misc, function(err,res) {
            if (err){
              console.log('reg user error');
            } else {
              Router.go('/success');
            }

        });
      }
    // Validate the number

    if (!Stripe.card.validateCardNumber(ccNum)) {
        error = true;
        INPUTERROR.report('The credit card number appears to be invalid.');
    }

    // Validate the CVC:
    if (!Stripe.card.validateCVC(cvcNum)) {
        error = true;
        INPUTERROR.report('The CVC number appears to be invalid.');
    }

    // Validate the expiration:
    if (!Stripe.card.validateExpiry(expMonth, expYear)) {
        error = true;
        INPUTERROR.report('The expiration date appears to be invalid.');
    }
       // Take our card data and create a Stripe token from the client. This
       // ensures that our code is PCI compliant to keep the man from knocking
       // on our door.
      if (!error) {
       STRIPE.getToken( '#application-signup', {
         number: $('[data-stripe="cardNumber"]').val(),
         exp_month: $('[data-stripe="expMo"]').val(),
         exp_year: $('[data-stripe="expYr"]').val(),
         cvc: $('[data-stripe="cvc"]').val(),
         name: $('[data-stripe="cardholder_name"]').val(),
         address_line1: $('[data-stripe="address_line1"]').val(),
         address_line2: $('[data-stripe="address_line2"]').val(),
         address_city: $('[data-stripe="address_city"]').val(),
         address_state: $('[data-stripe="address_state"]').val(),
         address_zip: $('[data-stripe="address_zip"]').val(),
         address_country: $('[data-stripe="address_country"]').val()
       }, function() {

         // Grab the customer's details.
         var token = {
           token: $('[name="stripeToken"]').val()
         };

        //var submitButton = $('input[type="submit"]').button('loading');
        console.log("test");
         Meteor.call('createCustomer', student, parent, misc, token, function(err, response){

           if (err) {
             //INPUTERROR.report('There was a problem with your signup. Please try again');
             alert(error.reason);
             console.log("alert error");
             // If creation fails, make sure to "reset" our signup interface.
             //submitButton.button('reset');
             //Router.go('error')
           } else {
             console.log("no error");
            //Router.go('/');
             // Note: because we're using a Future to return a value, even if an error
             // occurs on the server, it will be passed back to the client as the
             // response argument. Here, we test to make sure we didn't receive an error
             // in our response before continuing.
             if ( response.error ) {
               alert(response.message);
               console.log("alert response message");
               Router.go('error')
               // If creation fails, make sure to "reset" our signup interface.
                //submitButton.button('reset');
             } else {
               // Our user exists, so now we can log them in! Note: because we know
               // that we created our user using the emailAddress and password values
               // above, we can simply login with these Hot dog, indeed.
               Router.go('/success');
               //console.log("login with password");
              /* Meteor.loginWithPassword(customer.emailAddress, customer.password, function(error){
                 if (error) {
                   alert(error.reason);
                   // If login fails, make sure to "reset" our signup interface.
                   //submitButton.button('reset');
                 } else {
                  // Router.go('/');
                   // If creation fails, make sure to "reset" our signup interface.
                   submitButton.button('reset');
                 }
               });*/
             }
           }
         });

       });
     } // end STRIPE.getToken();

  }
});
<commit_msg>fixed mismatched open/close braces<commit_after>Template.signup.events({
  'submit form': function(e){
    // Prevent form from submitting.
    e.preventDefault();

    var error = false;

(function ($) {
  $(document).ready(function() {
    // Function to update labels of text fields
    Materialize.updateTextFields = function() {
      var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';
      $(input_selector).each(function(index, element) {
        if ($(element).val().length > 0 || element.autofocus ||$(this).attr('placeholder') !== undefined || $(element)[0].validity.badInput === true) {
          $(this).siblings('label').addClass('active');
        }
        else {
          $(this).siblings('label').removeClass('active');
        }
      });
    };
  }
}

    //// Grab the student's details.
    var student = {
      firstName: $('[name="firstName"]').val(),
      middleName: $('[name="middleName"]').val(),
      lastName: $('[name="lastName"]').val(),
      DOB: $('[name="DOB"]').val(),
      studentGrade: $('[name="studentGrade"]').val(),
      emailAddress: $('[name="emailAddress"]').val(),
      password: $('[name="password"]').val(),
      studentPhoneNo: $('[name="studentPhoneNo"]').val(),
      studentId: $('[name="studentId"]').val(),
      facebookAccount: $('[name="facebookAccount"]').val(),
      facebookEvsd: $('[name="facebookEvsd"]').val(),
      schoolloopEvsd: $('[name="schoolloopEvsd"]').val(),
    };
    var parent = {
        firstParent: $('[name="firstParent"]').val(),
        firstParentPhoneNo: $('[name="firstParentPhoneNo"]').val(),
        firstParentEmailAddress: $('[name="firstParentEmailAddress"]').val(),
        firstParentEmployer: $('[name="firstParentEmployer"]').val(),
        secondParent: $('[name="secondParent"]').val(),
        secondParentPhoneNo: $('[name="secondParentPhoneNo"]').val(),
        secondParentEmailAddress: $('[name="secondParentEmailAddress"]').val(),
        secondParentEmployer: $('[name="secondParentEmployer"]').val()
    };
    var misc = {
        findOut: $('[name="findOut"]').val(),
        whyjoin: $('[name="whyjoin"]').val(),
        concerns: $('[name="concerns"]').val()
    };

    // Get the values:
    var ccNum = $('[data-stripe="cardNumber"]').val(),
        cvcNum =$('[data-stripe="cvc"]').val(),
        expMonth = $('[data-stripe="expMo"]').val(),
        expYear = $('[data-stripe="expYr"]').val(),
        name = $('[data-stripe="cardholder_name"]').val(),
        address_line1 = $('[data-stripe="address_line1"]').val(),
        address_line2 = $('[data-stripe="address_line2"]').val(),
        address_city = $('[data-stripe="address_city"]').val(),
        address_state = $('[data-stripe="address_state"]').val(),
        address_zip = $('[data-stripe="address_zip"]').val(),
        address_country = $('[data-stripe="address_country"]').val();

      if ((ccNum == null || ccNum == "") && (cvcNum == null || cvcNum == "") && (expMonth == null || expMonth == "") && (expYear == null || expYear == "") && (name == null || name == "") && (address_line1 == null || address_line1 == "")
          && (address_line2 == null || address_line2 == "") && (address_city == null || address_city == "") && (address_state == null || address_state == "") && (address_zip == null || address_zip == "") && (address_country == null || address_country == "")) {

            error = true;

          var name = $('[name="firstName"]').val(),
              emailAddress = $('[name="emailAddress"]').val(),
              password = $('[name="password"]').val();

        Meteor.call('createreguser', student, parent, misc, function(err,res) {
            if (err){
              console.log('reg user error');
            } else {
              Router.go('/success');
            }

        });
      }
    // Validate the number

    if (!Stripe.card.validateCardNumber(ccNum)) {
        error = true;
        INPUTERROR.report('The credit card number appears to be invalid.');
    }

    // Validate the CVC:
    if (!Stripe.card.validateCVC(cvcNum)) {
        error = true;
        INPUTERROR.report('The CVC number appears to be invalid.');
    }

    // Validate the expiration:
    if (!Stripe.card.validateExpiry(expMonth, expYear)) {
        error = true;
        INPUTERROR.report('The expiration date appears to be invalid.');
    }
       // Take our card data and create a Stripe token from the client. This
       // ensures that our code is PCI compliant to keep the man from knocking
       // on our door.
      if (!error) {
       STRIPE.getToken( '#application-signup', {
         number: $('[data-stripe="cardNumber"]').val(),
         exp_month: $('[data-stripe="expMo"]').val(),
         exp_year: $('[data-stripe="expYr"]').val(),
         cvc: $('[data-stripe="cvc"]').val(),
         name: $('[data-stripe="cardholder_name"]').val(),
         address_line1: $('[data-stripe="address_line1"]').val(),
         address_line2: $('[data-stripe="address_line2"]').val(),
         address_city: $('[data-stripe="address_city"]').val(),
         address_state: $('[data-stripe="address_state"]').val(),
         address_zip: $('[data-stripe="address_zip"]').val(),
         address_country: $('[data-stripe="address_country"]').val()
       }, function() {

         // Grab the customer's details.
         var token = {
           token: $('[name="stripeToken"]').val()
         };

        //var submitButton = $('input[type="submit"]').button('loading');
        console.log("test");
         Meteor.call('createCustomer', student, parent, misc, token, function(err, response){

           if (err) {
             //INPUTERROR.report('There was a problem with your signup. Please try again');
             alert(error.reason);
             console.log("alert error");
             // If creation fails, make sure to "reset" our signup interface.
             //submitButton.button('reset');
             //Router.go('error')
           } else {
             console.log("no error");
            //Router.go('/');
             // Note: because we're using a Future to return a value, even if an error
             // occurs on the server, it will be passed back to the client as the
             // response argument. Here, we test to make sure we didn't receive an error
             // in our response before continuing.
             if ( response.error ) {
               alert(response.message);
               console.log("alert response message");
               Router.go('error')
               // If creation fails, make sure to "reset" our signup interface.
                //submitButton.button('reset');
             } else {
               // Our user exists, so now we can log them in! Note: because we know
               // that we created our user using the emailAddress and password values
               // above, we can simply login with these Hot dog, indeed.
               Router.go('/success');
               //console.log("login with password");
              /* Meteor.loginWithPassword(customer.emailAddress, customer.password, function(error){
                 if (error) {
                   alert(error.reason);
                   // If login fails, make sure to "reset" our signup interface.
                   //submitButton.button('reset');
                 } else {
                  // Router.go('/');
                   // If creation fails, make sure to "reset" our signup interface.
                   submitButton.button('reset');
                 }
               });*/
             }
           }
         });

       });
     } // end STRIPE.getToken();

  }
});
<|endoftext|>


<commit_before>const should = require('should');
const supertest = require('supertest');
const ObjectId = require('bson-objectid');
const testUtils = require('../../utils');
const localUtils = require('./utils');
const config = require('../../../core/shared/config');
const models = require('../../../core/server/models/index');

describe('Email Preview API', function () {
    let request;

    before(async function () {
        await localUtils.startGhost();
        request = supertest.agent(config.get('url'));
        await localUtils.doAuth(request, 'users:extra', 'posts');
    });

    describe('Read', function () {
        it('can\'t retrieve for non existent post', async function () {
            const res = await request.get(localUtils.API.getApiQuery(`posts/${ObjectId().toHexString()}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(404);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.errors);
            testUtils.API.checkResponseValue(jsonResponse.errors[0], [
                'message',
                'context',
                'type',
                'details',
                'property',
                'help',
                'code',
                'id'
            ]);
        });

        it('can read post email preview with fields', async function () {
            const res = await request
                .get(localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.email_previews);

            localUtils.API.checkResponse(jsonResponse.email_previews[0], 'email_previews', null, null);
        });

        it('can read post email preview with email card and replacements', async function () {
            const post = testUtils.DataGenerator.forKnex.createPost({
                id: ObjectId().toHexString(),
                title: 'Post with email-only card',
                slug: 'email-only-card',
                mobiledoc: '{"version":"0.3.1","atoms":[],"cards":[["email",{"html":"
Hey {first_name \\"there\\"} {unknown}

Welcome to your first Ghost email!
"}],["email",{"html":"
Another email card with a similar replacement, {first_name, \\"see?\\"}
"}]],"markups":[],"sections":[[10,0],[1,"p",[[0,[],0,"This is the actual post content..."]]],[10,1],[1,"p",[]]]}',
                html: '
This is the actual post content...
',
                plaintext: 'This is the actual post content...',
                status: 'draft',
                uuid: 'd52c42ae-2755-455c-80ec-70b2ec55c904'
            });

            await models.Post.add(post, {context: {internal: true}});
            const res = await request
                .get(localUtils.API.getApiQuery(`email_previews/posts/${post.id}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.email_previews);

            jsonResponse.email_previews[0].html.should.match(/Hey there {unknown}/);
            jsonResponse.email_previews[0].html.should.match(/Welcome to your first Ghost email!/);
            jsonResponse.email_previews[0].html.should.match(/This is the actual post content\.\.\./);
            jsonResponse.email_previews[0].html.should.match(/Another email card with a similar replacement, see\?/);

            jsonResponse.email_previews[0].plaintext.should.match(/Hey there {unknown}/);
            jsonResponse.email_previews[0].plaintext.should.match(/Welcome to your first Ghost email!/);
            jsonResponse.email_previews[0].plaintext.should.match(/This is the actual post content\.\.\./);
            jsonResponse.email_previews[0].plaintext.should.match(/Another email card with a similar replacement, see\?/);
        });

        it('has custom content transformations for email compatibility', async function () {
            const post = testUtils.DataGenerator.forKnex.createPost({
                id: ObjectId().toHexString(),
                title: 'Post with email-only card',
                slug: 'email-only-card',
                mobiledoc: '{"version":"0.3.1","atoms":[],"cards":[],"markups":[["a",["href","https://ghost.org"]]],"sections":[[1,"p",[[0,[],0,"Testing "],[0,[0],1,"links"],[0,[],0," in email excerpt and apostrophes \'"]]]]}',
                html: '
This is the actual post content...
',
                plaintext: 'This is the actual post content...',
                status: 'draft',
                uuid: 'd52c42ae-2755-455c-80ec-70b2ec55c904'
            });

            await models.Post.add(post, {context: {internal: true}});

            const res = await request
                .get(localUtils.API.getApiQuery(`email_previews/posts/${post.id}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.email_previews);

            const [preview] = jsonResponse.email_previews;

            preview.html.should.containEql('Testing links in email excerpt');

            preview.html.should.match(/'/);
            preview.html.should.not.match(/'/);
        });
    });

    describe('As Owner', function () {
        it('can send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200)
                .expect((res) => {
                    res.body.should.be.empty();
                });
        });
    });

    describe('As Admin', function () {
        before(async function () {
            const user = await testUtils.createUser({
                user: testUtils.DataGenerator.forKnex.createUser({email: 'admin+1@ghost.org'}),
                role: testUtils.DataGenerator.Content.roles[0].name
            });

            request.user = user;
            await localUtils.doAuth(request);
        });

        it('can send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200)
                .expect((res) => {
                    res.body.should.be.empty();
                });
        });
    });

    describe('As Editor', function () {
        before(async function () {
            const user = await testUtils.createUser({
                user: testUtils.DataGenerator.forKnex.createUser({
                    email: 'test+editor@ghost.org'
                }),
                role: testUtils.DataGenerator.Content.roles[1].name
            });

            request.user = user;
            await localUtils.doAuth(request);
        });

        it('can send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200)
                .expect((res) => {
                    res.body.should.be.empty();
                });
        });
    });

    describe('As Author', function () {
        before(async function () {
            const user = await testUtils.createUser({
                user: testUtils.DataGenerator.forKnex.createUser({
                    email: 'test+author@ghost.org'
                }),
                role: testUtils.DataGenerator.Content.roles[2].name
            });

            request.user = user;
            await localUtils.doAuth(request);
        });

        it('cannot send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(403)
                .expect((res) => {
                    res.body.should.be.an.Object().with.property('errors');
                });
        });
    });
});
<commit_msg>Fixed erroneously passing test<commit_after>const should = require('should');
const supertest = require('supertest');
const ObjectId = require('bson-objectid');
const testUtils = require('../../utils');
const localUtils = require('./utils');
const config = require('../../../core/shared/config');
const models = require('../../../core/server/models/index');

describe('Email Preview API', function () {
    let request;

    before(async function () {
        await localUtils.startGhost();
        request = supertest.agent(config.get('url'));
        await localUtils.doAuth(request, 'users:extra', 'posts');
    });

    describe('Read', function () {
        it('can\'t retrieve for non existent post', async function () {
            const res = await request.get(localUtils.API.getApiQuery(`email_previews/posts/${ObjectId().toHexString()}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(404);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.errors);
            testUtils.API.checkResponseValue(jsonResponse.errors[0], [
                'message',
                'context',
                'type',
                'details',
                'property',
                'help',
                'code',
                'id'
            ]);
        });

        it('can read post email preview with fields', async function () {
            const res = await request
                .get(localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.email_previews);

            localUtils.API.checkResponse(jsonResponse.email_previews[0], 'email_previews', null, null);
        });

        it('can read post email preview with email card and replacements', async function () {
            const post = testUtils.DataGenerator.forKnex.createPost({
                id: ObjectId().toHexString(),
                title: 'Post with email-only card',
                slug: 'email-only-card',
                mobiledoc: '{"version":"0.3.1","atoms":[],"cards":[["email",{"html":"
Hey {first_name \\"there\\"} {unknown}

Welcome to your first Ghost email!
"}],["email",{"html":"
Another email card with a similar replacement, {first_name, \\"see?\\"}
"}]],"markups":[],"sections":[[10,0],[1,"p",[[0,[],0,"This is the actual post content..."]]],[10,1],[1,"p",[]]]}',
                html: '
This is the actual post content...
',
                plaintext: 'This is the actual post content...',
                status: 'draft',
                uuid: 'd52c42ae-2755-455c-80ec-70b2ec55c904'
            });

            await models.Post.add(post, {context: {internal: true}});
            const res = await request
                .get(localUtils.API.getApiQuery(`email_previews/posts/${post.id}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.email_previews);

            jsonResponse.email_previews[0].html.should.match(/Hey there {unknown}/);
            jsonResponse.email_previews[0].html.should.match(/Welcome to your first Ghost email!/);
            jsonResponse.email_previews[0].html.should.match(/This is the actual post content\.\.\./);
            jsonResponse.email_previews[0].html.should.match(/Another email card with a similar replacement, see\?/);

            jsonResponse.email_previews[0].plaintext.should.match(/Hey there {unknown}/);
            jsonResponse.email_previews[0].plaintext.should.match(/Welcome to your first Ghost email!/);
            jsonResponse.email_previews[0].plaintext.should.match(/This is the actual post content\.\.\./);
            jsonResponse.email_previews[0].plaintext.should.match(/Another email card with a similar replacement, see\?/);
        });

        it('has custom content transformations for email compatibility', async function () {
            const post = testUtils.DataGenerator.forKnex.createPost({
                id: ObjectId().toHexString(),
                title: 'Post with email-only card',
                slug: 'email-only-card',
                mobiledoc: '{"version":"0.3.1","atoms":[],"cards":[],"markups":[["a",["href","https://ghost.org"]]],"sections":[[1,"p",[[0,[],0,"Testing "],[0,[0],1,"links"],[0,[],0," in email excerpt and apostrophes \'"]]]]}',
                html: '
This is the actual post content...
',
                plaintext: 'This is the actual post content...',
                status: 'draft',
                uuid: 'd52c42ae-2755-455c-80ec-70b2ec55c904'
            });

            await models.Post.add(post, {context: {internal: true}});

            const res = await request
                .get(localUtils.API.getApiQuery(`email_previews/posts/${post.id}/`))
                .set('Origin', config.get('url'))
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200);

            should.not.exist(res.headers['x-cache-invalidate']);
            const jsonResponse = res.body;
            should.exist(jsonResponse);
            should.exist(jsonResponse.email_previews);

            const [preview] = jsonResponse.email_previews;

            preview.html.should.containEql('Testing links in email excerpt');

            preview.html.should.match(/'/);
            preview.html.should.not.match(/'/);
        });
    });

    describe('As Owner', function () {
        it('can send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200)
                .expect((res) => {
                    res.body.should.be.empty();
                });
        });
    });

    describe('As Admin', function () {
        before(async function () {
            const user = await testUtils.createUser({
                user: testUtils.DataGenerator.forKnex.createUser({email: 'admin+1@ghost.org'}),
                role: testUtils.DataGenerator.Content.roles[0].name
            });

            request.user = user;
            await localUtils.doAuth(request);
        });

        it('can send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200)
                .expect((res) => {
                    res.body.should.be.empty();
                });
        });
    });

    describe('As Editor', function () {
        before(async function () {
            const user = await testUtils.createUser({
                user: testUtils.DataGenerator.forKnex.createUser({
                    email: 'test+editor@ghost.org'
                }),
                role: testUtils.DataGenerator.Content.roles[1].name
            });

            request.user = user;
            await localUtils.doAuth(request);
        });

        it('can send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(200)
                .expect((res) => {
                    res.body.should.be.empty();
                });
        });
    });

    describe('As Author', function () {
        before(async function () {
            const user = await testUtils.createUser({
                user: testUtils.DataGenerator.forKnex.createUser({
                    email: 'test+author@ghost.org'
                }),
                role: testUtils.DataGenerator.Content.roles[2].name
            });

            request.user = user;
            await localUtils.doAuth(request);
        });

        it('cannot send test email', async function () {
            const url = localUtils.API.getApiQuery(`email_previews/posts/${testUtils.DataGenerator.Content.posts[0].id}/`);
            await request
                .post(url)
                .set('Origin', config.get('url'))
                .send({
                    emails: ['test@ghost.org']
                })
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect('Cache-Control', testUtils.cacheRules.private)
                .expect(403)
                .expect((res) => {
                    res.body.should.be.an.Object().with.property('errors');
                });
        });
    });
});
<|endoftext|>


<commit_before>describe('Dataset list controller', function () {
    'use strict';

    var createController, scope;
    var datasets = [
        {id: 'ec4834d9bc2af8', name: 'Customers (50 lines)'},
        {id: 'ab45f893d8e923', name: 'Us states'},
        {id: 'cf98d83dcb9437', name: 'Customers (1K lines)'}
    ];
    var refreshedDatasets = [
        {id: 'ec4834d9bc2af8', name: 'Customers (50 lines)'},
        {id: 'ab45f893d8e923', name: 'Us states'}
    ];

    beforeEach(module('data-prep.dataset-list'));

    beforeEach(inject(function ($rootScope, $controller, $q, DatasetService, PlaygroundService, MessageService) {
        var datasetsValues = [datasets, refreshedDatasets];
        scope = $rootScope.$new();

        createController = function () {
            var ctrl = $controller('DatasetListCtrl', {
                $scope: scope
            });
            return ctrl;
        };

        spyOn(DatasetService, 'processCertification').and.returnValue($q.when(true));
        spyOn(DatasetService, 'getDatasets').and.callFake(function () {
            return $q.when(datasetsValues.shift());
        });

        spyOn(PlaygroundService, 'initPlayground').and.returnValue($q.when(true));
        spyOn(PlaygroundService, 'show').and.callThrough();
        spyOn(MessageService, 'error').and.returnValue(null);
    }));

    afterEach(inject(function($stateParams) {
        $stateParams.datasetid = null;
    }));

    it('should get dataset on creation', inject(function (DatasetService) {
        //when
        createController();
        scope.$digest();

        //then
        expect(DatasetService.getDatasets).toHaveBeenCalled();
    }));

    it('should init playground with the provided datasetId from url', inject(function ($stateParams, PlaygroundService) {
        //given
        $stateParams.datasetid = 'ab45f893d8e923';

        //when
        createController();
        scope.$digest();

        //then
        expect(PlaygroundService.initPlayground).toHaveBeenCalledWith(datasets[1]);
        expect(PlaygroundService.show).toHaveBeenCalled();
    }));

    it('should show error message when dataset id is not in users dataset', inject(function ($stateParams, PlaygroundService, MessageService) {
        //given
        $stateParams.datasetid = 'azerty';

        //when
        createController();
        scope.$digest();

        //then
        expect(PlaygroundService.initPlayground).not.toHaveBeenCalled();
        expect(PlaygroundService.show).not.toHaveBeenCalled();
        expect(MessageService.error).toHaveBeenCalledWith('PLAYGROUND_FILE_NOT_FOUND_TITLE', 'PLAYGROUND_FILE_NOT_FOUND', {type: 'dataset'});
    }));

    describe('already created', function () {
        var ctrl;

        beforeEach(inject(function ($rootScope, $q, MessageService, DatasetService) {
            ctrl = createController();
            scope.$digest();

            spyOn(DatasetService, 'delete').and.returnValue($q.when(true));
            spyOn(MessageService, 'success').and.callThrough();
        }));

        it('should delete dataset and show toast', inject(function ($q, MessageService, DatasetService, TalendConfirmService) {
            //given
            var dataset = datasets[0];
            spyOn(TalendConfirmService, 'confirm').and.returnValue($q.when(true));

            //when
            ctrl.delete(dataset);
            scope.$digest();

            //then
            expect(TalendConfirmService.confirm).toHaveBeenCalledWith({disableEnter: true}, [ 'DELETE_PERMANENTLY', 'NO_UNDONE_CONFIRM' ], {type: 'dataset', name: 'Customers (50 lines)' });
            expect(DatasetService.delete).toHaveBeenCalledWith(dataset);
            expect(MessageService.success).toHaveBeenCalledWith('REMOVE_SUCCESS_TITLE', 'REMOVE_SUCCESS', {type: 'dataset', name: 'Customers (50 lines)'});
        }));

        it('should init and show playground', inject(function ($rootScope, PlaygroundService) {
            //given
            var dataset = {name: 'Customers (50 lines)', id: 'aA2bc348e933bc2'};

            //when
            ctrl.open(dataset);
            $rootScope.$apply();

            //then
            expect(PlaygroundService.initPlayground).toHaveBeenCalledWith(dataset);
            expect(PlaygroundService.show).toHaveBeenCalled();
        }));

        it('should bind datasets getter to DatasetService.datasetsList()', inject(function (DatasetService) {
            //given
            spyOn(DatasetService, 'datasetsList').and.returnValue(refreshedDatasets);

            //then
            expect(ctrl.datasets).toBe(refreshedDatasets);
        }));

        it('should process certification on dataset', inject(function (DatasetService) {
            //when
            ctrl.processCertification(datasets[0]);

            //then
            expect(DatasetService.processCertification).toHaveBeenCalledWith(datasets[0])
        }));
    });
});
<commit_msg>TDP-140 : jshint warnings<commit_after>describe('Dataset list controller', function () {
    'use strict';

    var createController, scope;
    var datasets = [
        {id: 'ec4834d9bc2af8', name: 'Customers (50 lines)'},
        {id: 'ab45f893d8e923', name: 'Us states'},
        {id: 'cf98d83dcb9437', name: 'Customers (1K lines)'}
    ];
    var refreshedDatasets = [
        {id: 'ec4834d9bc2af8', name: 'Customers (50 lines)'},
        {id: 'ab45f893d8e923', name: 'Us states'}
    ];

    beforeEach(module('data-prep.dataset-list'));

    beforeEach(inject(function ($rootScope, $controller, $q, DatasetService, PlaygroundService, MessageService) {
        var datasetsValues = [datasets, refreshedDatasets];
        scope = $rootScope.$new();

        createController = function () {
            var ctrl = $controller('DatasetListCtrl', {
                $scope: scope
            });
            return ctrl;
        };

        spyOn(DatasetService, 'processCertification').and.returnValue($q.when(true));
        spyOn(DatasetService, 'getDatasets').and.callFake(function () {
            return $q.when(datasetsValues.shift());
        });

        spyOn(PlaygroundService, 'initPlayground').and.returnValue($q.when(true));
        spyOn(PlaygroundService, 'show').and.callThrough();
        spyOn(MessageService, 'error').and.returnValue(null);
    }));

    afterEach(inject(function($stateParams) {
        $stateParams.datasetid = null;
    }));

    it('should get dataset on creation', inject(function (DatasetService) {
        //when
        createController();
        scope.$digest();

        //then
        expect(DatasetService.getDatasets).toHaveBeenCalled();
    }));

    it('should init playground with the provided datasetId from url', inject(function ($stateParams, PlaygroundService) {
        //given
        $stateParams.datasetid = 'ab45f893d8e923';

        //when
        createController();
        scope.$digest();

        //then
        expect(PlaygroundService.initPlayground).toHaveBeenCalledWith(datasets[1]);
        expect(PlaygroundService.show).toHaveBeenCalled();
    }));

    it('should show error message when dataset id is not in users dataset', inject(function ($stateParams, PlaygroundService, MessageService) {
        //given
        $stateParams.datasetid = 'azerty';

        //when
        createController();
        scope.$digest();

        //then
        expect(PlaygroundService.initPlayground).not.toHaveBeenCalled();
        expect(PlaygroundService.show).not.toHaveBeenCalled();
        expect(MessageService.error).toHaveBeenCalledWith('PLAYGROUND_FILE_NOT_FOUND_TITLE', 'PLAYGROUND_FILE_NOT_FOUND', {type: 'dataset'});
    }));

    describe('already created', function () {
        var ctrl;

        beforeEach(inject(function ($rootScope, $q, MessageService, DatasetService) {
            ctrl = createController();
            scope.$digest();

            spyOn(DatasetService, 'delete').and.returnValue($q.when(true));
            spyOn(MessageService, 'success').and.callThrough();
        }));

        it('should delete dataset and show toast', inject(function ($q, MessageService, DatasetService, TalendConfirmService) {
            //given
            var dataset = datasets[0];
            spyOn(TalendConfirmService, 'confirm').and.returnValue($q.when(true));

            //when
            ctrl.delete(dataset);
            scope.$digest();

            //then
            expect(TalendConfirmService.confirm).toHaveBeenCalledWith({disableEnter: true}, [ 'DELETE_PERMANENTLY', 'NO_UNDONE_CONFIRM' ], {type: 'dataset', name: 'Customers (50 lines)' });
            expect(DatasetService.delete).toHaveBeenCalledWith(dataset);
            expect(MessageService.success).toHaveBeenCalledWith('REMOVE_SUCCESS_TITLE', 'REMOVE_SUCCESS', {type: 'dataset', name: 'Customers (50 lines)'});
        }));

        it('should init and show playground', inject(function ($rootScope, PlaygroundService) {
            //given
            var dataset = {name: 'Customers (50 lines)', id: 'aA2bc348e933bc2'};

            //when
            ctrl.open(dataset);
            $rootScope.$apply();

            //then
            expect(PlaygroundService.initPlayground).toHaveBeenCalledWith(dataset);
            expect(PlaygroundService.show).toHaveBeenCalled();
        }));

        it('should bind datasets getter to DatasetService.datasetsList()', inject(function (DatasetService) {
            //given
            spyOn(DatasetService, 'datasetsList').and.returnValue(refreshedDatasets);

            //then
            expect(ctrl.datasets).toBe(refreshedDatasets);
        }));

        it('should process certification on dataset', inject(function (DatasetService) {
            //when
            ctrl.processCertification(datasets[0]);

            //then
            expect(DatasetService.processCertification).toHaveBeenCalledWith(datasets[0]);
        }));
    });
});
<|endoftext|>


<commit_before>	document.getElementById("logo").style.display = "none";
	document.getElementById("top-right").style.display = "none";
	document.getElementById("language_dropdown").style.display = "none";
	document.getElementsByTagName("footer")[0].style.display = "none";
	document.getElementById("page").style.display = "none";
	document.getElementById("fixed-risk-warning").style.display = "none";
	document.getElementById("bot").style.display = "none";

	var output = [];
	var ReqCurrencies = [];

	ReqCurrencies[1] = 'AUD';
	ReqCurrencies[2] = 'BRL';
	ReqCurrencies[3] = 'CAD';
	ReqCurrencies[4] = 'CHF';
	ReqCurrencies[5] = 'CLP';
	ReqCurrencies[6] = 'CNY';
	ReqCurrencies[7] = 'COP';
	ReqCurrencies[8] = 'CZK';
	ReqCurrencies[9] = 'DKK';
	ReqCurrencies[10] = 'EUR';
	ReqCurrencies[11] = 'GBP';
	ReqCurrencies[12] = 'HKD';
	ReqCurrencies[13] = 'HUF';
	ReqCurrencies[14] = 'IDR';
	ReqCurrencies[15] = 'INR';
	ReqCurrencies[16] = 'ISK';
	ReqCurrencies[17] = 'JPY';
	ReqCurrencies[18] = 'MXN';
	ReqCurrencies[19] = 'MYR';
	ReqCurrencies[20] = 'NOK';
	ReqCurrencies[21] = 'NZD';
	ReqCurrencies[22] = 'PAB';
	ReqCurrencies[23] = 'PEN';
	ReqCurrencies[25] = 'PHP';
	ReqCurrencies[26] = 'PLN';
	ReqCurrencies[27] = 'RON';
	ReqCurrencies[28] = 'RSD';
	ReqCurrencies[29] = 'RUB';
	ReqCurrencies[30] = 'SEK';
	ReqCurrencies[31] = 'SGD';
	ReqCurrencies[32] = 'THB';
	ReqCurrencies[33] = 'TRY';
	ReqCurrencies[34] = 'USD';
	ReqCurrencies[35] = 'UYU';
	ReqCurrencies[36] = 'VEF';
	ReqCurrencies[37] = 'XAF';
	ReqCurrencies[38] = 'ZAR';
	ReqCurrencies[39] = 'EGP';
	ReqCurrencies[40] = 'TWD';

	var reqCurL = ReqCurrencies.length-2;
	alert(reqCurL);

	for (i=1;i<reqCurL;i++){

		output[i-1] = document.getElementById("menu_content").getElementsByTagName("table")[i].getElementsByTagName("tr")[2].getElementsByTagName("td")[2].getElementsByTagName("font")[0].innerHTML;

	}

	var newDIV = document.createElement('div');
	var newTAB = document.createElement('table');

	var newTR;
	var newTD;

	var newTR2;
	var newTD2;

	document.getElementById('top').appendChild(newDIV);
	newDIV.appendChild(newTAB);

	for (i=1;i<reqCurL;i++) {
		newTR2 = document.createElement('tr');
		newTD2 = document.createElement('td');
		newTD = document.createElement('td');

		newTAB.appendChild(newTR2);
		newTR2.appendChild(newTD2);
		newTD2.innerHTML = ReqCurrencies[i];
		newTR2.appendChild(newTD);
		newTD.innerHTML = output[i-1];
	}
<commit_msg>Update page2.js<commit_after>	document.getElementById("logo").style.display = "none";
	document.getElementById("top-right").style.display = "none";
	document.getElementById("language_dropdown").style.display = "none";
	document.getElementsByTagName("footer")[0].style.display = "none";
	document.getElementById("page").style.display = "none";
	document.getElementById("fixed-risk-warning").style.display = "none";
	document.getElementById("bot").style.display = "none";

	var output = [];
	var ReqCurrencies = [];

	ReqCurrencies[1] = 'AUD';
	ReqCurrencies[2] = 'BRL';
	ReqCurrencies[3] = 'CAD';
	ReqCurrencies[4] = 'CHF';
	ReqCurrencies[5] = 'CLP';
	ReqCurrencies[6] = 'CNY';
	ReqCurrencies[7] = 'COP';
	ReqCurrencies[8] = 'CZK';
	ReqCurrencies[9] = 'DKK';
	ReqCurrencies[10] = 'EGP';
	ReqCurrencies[11] = 'EUR';
	ReqCurrencies[12] = 'GBP';
	ReqCurrencies[13] = 'HKD';
	ReqCurrencies[14] = 'HUF';
	ReqCurrencies[15] = 'IDR';
	ReqCurrencies[16] = 'INR';
	ReqCurrencies[17] = 'ISK';
	ReqCurrencies[18] = 'JPY';
	ReqCurrencies[19] = 'MXN';
	ReqCurrencies[20] = 'MYR';
	ReqCurrencies[21] = 'NOK';
	ReqCurrencies[22] = 'NZD';
	ReqCurrencies[23] = 'PAB';
	ReqCurrencies[24] = 'PEN';
	ReqCurrencies[25] = 'PHP';
	ReqCurrencies[26] = 'PLN';
	ReqCurrencies[27] = 'RON';
	ReqCurrencies[28] = 'RSD';
	ReqCurrencies[29] = 'RUB';
	ReqCurrencies[30] = 'SEK';
	ReqCurrencies[31] = 'SGD';
	ReqCurrencies[32] = 'THB';
	ReqCurrencies[33] = 'TRY';
	ReqCurrencies[34] = 'TWD';
	ReqCurrencies[35] = 'USD';
	ReqCurrencies[36] = 'UYU';
	ReqCurrencies[37] = 'VEF';
	ReqCurrencies[38] = 'XAF';
	ReqCurrencies[39] = 'ZAR';

	var reqCurL = ReqCurrencies.length;

	for (i=1;i<reqCurL;i++){

		output[i-1] = document.getElementById("menu_content").getElementsByTagName("table")[i].getElementsByTagName("tr")[2].getElementsByTagName("td")[2].getElementsByTagName("font")[0].innerHTML;

	}

	var newDIV = document.createElement('div');
	var newTAB = document.createElement('table');

	var newTR;
	var newTD;

	var newTR2;
	var newTD2;

	document.getElementById('top').appendChild(newDIV);
	newDIV.appendChild(newTAB);

	for (i=1;i<reqCurL;i++) {
		newTR2 = document.createElement('tr');
		newTD2 = document.createElement('td');
		newTD = document.createElement('td');

		newTAB.appendChild(newTR2);
		newTR2.appendChild(newTD2);
		newTD2.innerHTML = ReqCurrencies[i];
		newTR2.appendChild(newTD);
		newTD.innerHTML = output[i-1];
	}
<|endoftext|>