<commit_before>angular.module('sislegisapp').controller('ElaboracaoNormativaController',
		function($scope, $http, $routeParams, $sce, $location, $locale, $parse, toaster, locationParser, ElaboracaoNormativaResource,
				EquipeResource, FileUploader, TagResource, ComentarioResource, AreaConsultadaResource,
				OrigemElaboracaoNormativaResource, UsuarioResource, ElaboracaoNormativaConsultaResource,
				StatusSidofResource, OrgaoResource) {

			var self = this;
			$scope.disabled = false;
			$scope.showAbaSEI = false;
		    $scope.$location = $location;
			$scope.elaboracaoNormativa = $scope.elaboracaoNormativa || {};
			$scope.equipes = EquipeResource.queryAll();

			$scope.onlyNumbers = /^\d+$/;

			$scope.elaboracaoNormativaConsulta = new ElaboracaoNormativaConsultaResource();

		    $scope.loadTags = function(query) {
		    	return TagResource.buscarPorSufixo({sufixo: query}).$promise;
		    };

			$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta = [];

			$scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown = $scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown || [];

			$scope.elaboracaoNormativa.listaComentario = $scope.elaboracaoNormativa.listaComentario || [];

		    $scope.tipos = ElaboracaoNormativaResource.tipos();

		    $scope.subTipos = ElaboracaoNormativaResource.subTipos();

		    $scope.identificacoes = ElaboracaoNormativaResource.identificacoes();

		    $scope.listaStatusSidof = StatusSidofResource.queryAll();

		    $scope.situacoes = ElaboracaoNormativaResource.situacoes();

		    $scope.orgaos = OrgaoResource.orgaosDropdownSelect();

		    // inicio config upload
			$scope.distribuicaoUploader = new FileUploader( {
			    url: 'http://localhost:8080/sislegis/rest/upload',
			    onSuccessItem : function(item, response, status, headers) {
			    	console.log(response);
			    	$scope.elaboracaoNormativa.elaboracaoNormativaConsulta.arquivo = response;
			    	$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.push($scope.elaboracaoNormativa.elaboracaoNormativaConsulta);
			    	$scope.elaboracaoNormativa.elaboracaoNormativaConsulta = null;
			    }
			});

			$scope.manifestacaoUploader = new FileUploader( {
			    url: 'http://localhost:8080/sislegis/rest/upload',
			    autoUpload : 'true',
			    //removeAfterUpload : 'true',
			    onSuccessItem : function(item, response, status, headers) {
			    	console.log(response);
			    	// o response contem o caminho relativo do arquivo
			    	$scope.elaboracaoNormativa.arquivoManifestacao = response;
			    },
			});
			// fim config upload

		    $scope.selectParecerista = function(){
		    	$scope.elaboracaoNormativa.pareceristas = UsuarioResource.findByIdEquipe({idEquipe : $scope.elaboracaoNormativa.equipe.id});

		    };

		    $scope.linkSei = function() {
		    	if(!checkEmpty($scope.elaboracaoNormativa.nup)
		    			&&!checkEmpty($scope.elaboracaoNormativa.linkSei)){
		    		$scope.showAbaSEI = true;
		    		return $sce.trustAsResourceUrl($scope.elaboracaoNormativa.linkSei);
		    	}
				return $sce.trustAsResourceUrl("");
			};

		    $scope.adicionarElaboracaoNormativaConsulta = function(){
		    	//TODO: Verificar erro quando não é adicionado nenhum arquivo
		    	//$scope.distribuicaoUploader.uploadItem(0);
		    	//$scope.elaboracaoNormativa.elaboracaoNormativaConsulta.elaboracaoNormativa = $scope.elaboracaoNormativa;
		    	$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.push($scope.elaboracaoNormativaConsulta);
		    	$scope.elaboracaoNormativaConsulta = new ElaboracaoNormativaConsultaResource();
		    }

		    $scope.adicionarComentario = function(comentario){
		    	$scope.elaboracaoNormativa.listaComentario.push(comentario);
		    	$scope.comentario =null;
		    }

		    $scope.excluirComentario = function(comentario){
				var index = $scope.elaboracaoNormativa.listaComentario.indexOf(comentario);
				$scope.elaboracaoNormativa.listaComentario.splice(index, 1);
		    }

		    $scope.normas = ElaboracaoNormativaResource.normas();

			$scope.salvar = function() {

		        var successCallback = function(data,responseHeaders){
		            var id = isEditMode()?data.id:locationParser(responseHeaders);
		            $location.path('/ElaboracaoNormativa/edit/' + id);
		            $scope.displayError = false;

		        	$scope.selected = "dadosPreliminares";
		        	toaster.pop('success', 'Elaboração Normativa salvo com sucesso');
		        };
		        var errorCallback = function() {
		        	toaster.pop('error', 'Falha na inclusão');
		        };

		        if (isEditMode()) {
		        	//$scope.elaboracaoNormativa.$update(successCallback, errorCallback);
		        	ElaboracaoNormativaResource.update($scope.elaboracaoNormativa, successCallback, errorCallback);
		        } else {
		        	ElaboracaoNormativaResource.save($scope.elaboracaoNormativa, successCallback, errorCallback);
		        }

			};

			$scope.get = function() {
		        var successCallback = function(data){
		            self.original = data;
		            $scope.elaboracaoNormativa = new ElaboracaoNormativaResource(self.original);
					$scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown = $scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown || [];
					$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta = $scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta || [];
					$scope.elaboracaoNormativa.listaComentario = $scope.elaboracaoNormativa.listaComentario || [];
		        };
		        var errorCallback = function() {
		            $location.path("/ElaboracaoNormativa");
		        };
		        ElaboracaoNormativaResource.get({ElaboracaoNormativaId:$routeParams.ElaboracaoNormativaId}, successCallback, errorCallback);
			};

		    $scope.cancel = function() {
		        $location.path("/Equipes");
		    };

		    function isEditMode() {
			    if ($location.path().indexOf("edit") > -1) {
			    	return true;
				}
			    return false;
		    }

		    if (isEditMode()) {
		    	$scope.get();
		    }

		    $scope.excluirElaboracaoNormativa = function(elaboracaoNormativaConsulta){
				var index = $scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.indexOf(elaboracaoNormativaConsulta);
				$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.splice(index, 1);
		    }

			$scope.getCoAutor = function(val) {
			    return $http.get('http://localhost:8080/sislegis/rest/orgaos/find', {
			      params: {
			        nome: val
			      }
			    }).then(function(response){
			      return response.data.map(function(item){
			        return item;
			      });
			    });
			  };

			$scope.getOrigemElaboracaoNormativas = function(val) {
			    return $http.get('http://localhost:8080/sislegis/rest/orgaos/find', {
			      params: {
			        nome: val
			      }
			    }).then(function(response){
			        if (val) {
			        	var item = new OrgaoResource();
			        	item.nome = val;
			        	response.data.unshift(item);
			        }
		    		return response.data.map(function(item){
		    			return item;
		    		});
			    },function(error){
			      console.log('Erro ao buscar dados getOrigemElaboracaoNormativas');
			    });
			  };

			$scope.getAreaConsultadas = function(val) {
			    return $http.get('http://localhost:8080/sislegis/rest/areaconsultadas/find', {
			      params: {
			        descricao: val
			      }
			    }).then(function(response){
			        if (val) {
			        	var item = new AreaConsultadaResource();
			        	item.descricao = val;
			        	response.data.unshift(item);
			        }
			      return response.data.map(function(item){
			        return item;
			      });
			    });
			  };

		    $scope.onSelectAreaConsultadas = function (item) {
		    	if(!item.id){
			    	item.$save(function(success){
			    		toaster.pop('success', 'Registro inserido com sucesso.');
			    	});
		    	}
		    };

		    // CALENDARIO
		    $scope.setCalendar = function() {
				$scope.openCalendar = function($event, id) {
					$event.preventDefault();
					$event.stopPropagation();
					var opened = 'opened_'+id;
					var model = $parse(opened);
					model.assign($scope, true);
					$scope.apply;

				};

				$scope.dateOptions = {
					formatYear : 'yy',
					startingDay : 1
				};

		    }

		    $scope.setCalendar();

		    $scope.format = 'dd/MM/yyyy';

		    //Aba default
		    $scope.selected = "dadosPreliminares";

		    $scope.mostraSubTipo = function(){
		    	var retorno = false;
		    	if($scope.elaboracaoNormativa.tipo!==undefined){
		    		if(angular.equals($scope.elaboracaoNormativa.tipo, 'EXPOSICAOMOTIVOS')){
		    			retorno = true;
		    		}
		    	}
		    	return retorno;
		    }

		    $scope.validaCampos = function(campo){
		    	return checkEmpty(campo);
		    }

		    $scope.validaCamposNormaGerada = function(campoElaboracaoNormativaNorma, campo){
		    	return (!checkEmpty(campoElaboracaoNormativaNorma) && checkEmpty(campo));
		    }

		    $scope.validaForm = function(){
		    	if($scope.elaboracaoNormativa.tipo!==undefined){
		    		if(angular.equals($scope.elaboracaoNormativa.tipo, 'EXPOSICAOMOTIVOS')
		    				&& checkEmpty($scope.elaboracaoNormativa.subTipo)){
		    			return true;
		    		}
		    		if(!checkEmpty($scope.elaboracaoNormativa.elaboracaoNormativaNorma)){
			    		if(checkEmpty($scope.elaboracaoNormativa.normaGeradaNumero)
			    				||checkEmpty($scope.elaboracaoNormativa.normaGeradaAno)){
			    			return true;
			    		}
		    		}
		    		if(checkEmpty($scope.elaboracaoNormativa.tipo)
		    				||checkEmpty($scope.elaboracaoNormativa.ementa)
		    				||checkEmpty($scope.elaboracaoNormativa.identificacao)
		    				||checkEmpty($scope.elaboracaoNormativa.ano)
		    				||checkEmpty($scope.elaboracaoNormativa.nup)
		    				||checkEmpty($scope.elaboracaoNormativa.origem)){
		    			return true;
		    		}
		    	}else{
		    		return true;
		    	}
		    	return false;
		    }

		    function checkEmpty(str){
		    	if(!str || !/[^\s]+/.test(str)){
		    		return true;
		    	}
		        return false;
		    }

		});<commit_msg>Desafio 5 - editais 12 e 13<commit_after>angular.module('sislegisapp').controller('ElaboracaoNormativaController',
		function($scope, $http, $routeParams, $sce, $location, $locale, $parse, toaster, locationParser, ElaboracaoNormativaResource,
				EquipeResource, FileUploader, TagResource, ComentarioResource, AreaConsultadaResource,
				OrigemElaboracaoNormativaResource, UsuarioResource, ElaboracaoNormativaConsultaResource,
				StatusSidofResource, OrgaoResource) {

			// Constantes para pegar dinamicamente o host
			// TODO criar o host de forma global para que possa ser usado em qualquer controller
			var host = location.protocol.concat("//").concat(window.location.hostname);
			var urlUpload = host.concat('/sislegis/rest/upload');
			var urlFindOrgaos = host.concat('/sislegis/rest/orgaos/find');
			var urlFindAreasConsultadas = host.concat('/sislegis/rest/areaconsultadas/find');

			var self = this;
			$scope.disabled = false;
			$scope.showAbaSEI = false;
		    $scope.$location = $location;
			$scope.elaboracaoNormativa = $scope.elaboracaoNormativa || {};
			$scope.equipes = EquipeResource.queryAll();

			$scope.onlyNumbers = /^\d+$/;

			$scope.elaboracaoNormativaConsulta = new ElaboracaoNormativaConsultaResource();

		    $scope.loadTags = function(query) {
		    	return TagResource.buscarPorSufixo({sufixo: query}).$promise;
		    };

			$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta = [];

			$scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown = $scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown || [];

			$scope.elaboracaoNormativa.listaComentario = $scope.elaboracaoNormativa.listaComentario || [];

		    $scope.tipos = ElaboracaoNormativaResource.tipos();

		    $scope.subTipos = ElaboracaoNormativaResource.subTipos();

		    $scope.identificacoes = ElaboracaoNormativaResource.identificacoes();

		    $scope.listaStatusSidof = StatusSidofResource.queryAll();

		    $scope.situacoes = ElaboracaoNormativaResource.situacoes();

		    $scope.orgaos = OrgaoResource.orgaosDropdownSelect();

		    // inicio config upload
			$scope.distribuicaoUploader = new FileUploader( {
				url: urlUpload,
			    onSuccessItem : function(item, response, status, headers) {
			    	console.log(response);
			    	$scope.elaboracaoNormativa.elaboracaoNormativaConsulta.arquivo = response;
			    	$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.push($scope.elaboracaoNormativa.elaboracaoNormativaConsulta);
			    	$scope.elaboracaoNormativa.elaboracaoNormativaConsulta = null;
			    }
			});

			$scope.manifestacaoUploader = new FileUploader( {
			    url: urlUpload,
			    autoUpload : 'true',
			    //removeAfterUpload : 'true',
			    onSuccessItem : function(item, response, status, headers) {
			    	console.log(response);
			    	// o response contem o caminho relativo do arquivo
			    	$scope.elaboracaoNormativa.arquivoManifestacao = response;
			    },
			});
			// fim config upload

		    $scope.selectParecerista = function(){
		    	$scope.elaboracaoNormativa.pareceristas = UsuarioResource.findByIdEquipe({idEquipe : $scope.elaboracaoNormativa.equipe.id});

		    };

		    $scope.linkSei = function() {
		    	if(!checkEmpty($scope.elaboracaoNormativa.nup)
		    			&&!checkEmpty($scope.elaboracaoNormativa.linkSei)){
		    		$scope.showAbaSEI = true;
		    		return $sce.trustAsResourceUrl($scope.elaboracaoNormativa.linkSei);
		    	}
				return $sce.trustAsResourceUrl("");
			};

		    $scope.adicionarElaboracaoNormativaConsulta = function(){
		    	//TODO: Verificar erro quando não é adicionado nenhum arquivo
		    	//$scope.distribuicaoUploader.uploadItem(0);
		    	//$scope.elaboracaoNormativa.elaboracaoNormativaConsulta.elaboracaoNormativa = $scope.elaboracaoNormativa;
		    	$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.push($scope.elaboracaoNormativaConsulta);
		    	$scope.elaboracaoNormativaConsulta = new ElaboracaoNormativaConsultaResource();
		    }

		    $scope.adicionarComentario = function(comentario){
		    	$scope.elaboracaoNormativa.listaComentario.push(comentario);
		    	$scope.comentario =null;
		    }

		    $scope.excluirComentario = function(comentario){
				var index = $scope.elaboracaoNormativa.listaComentario.indexOf(comentario);
				$scope.elaboracaoNormativa.listaComentario.splice(index, 1);
		    }

		    $scope.normas = ElaboracaoNormativaResource.normas();

			$scope.salvar = function() {

		        var successCallback = function(data,responseHeaders){
		            var id = isEditMode()?data.id:locationParser(responseHeaders);
		            $location.path('/ElaboracaoNormativa/edit/' + id);
		            $scope.displayError = false;

		        	$scope.selected = "dadosPreliminares";
		        	toaster.pop('success', 'Elaboração Normativa salvo com sucesso');
		        };
		        var errorCallback = function() {
		        	toaster.pop('error', 'Falha na inclusão');
		        };

		        if (isEditMode()) {
		        	//$scope.elaboracaoNormativa.$update(successCallback, errorCallback);
		        	ElaboracaoNormativaResource.update($scope.elaboracaoNormativa, successCallback, errorCallback);
		        } else {
		        	ElaboracaoNormativaResource.save($scope.elaboracaoNormativa, successCallback, errorCallback);
		        }

			};

			$scope.get = function() {
		        var successCallback = function(data){
		            self.original = data;
		            $scope.elaboracaoNormativa = new ElaboracaoNormativaResource(self.original);
					$scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown = $scope.elaboracaoNormativa.listaCoAutoresSelecionadosDropdown || [];
					$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta = $scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta || [];
					$scope.elaboracaoNormativa.listaComentario = $scope.elaboracaoNormativa.listaComentario || [];
		        };
		        var errorCallback = function() {
		            $location.path("/ElaboracaoNormativa");
		        };
		        ElaboracaoNormativaResource.get({ElaboracaoNormativaId:$routeParams.ElaboracaoNormativaId}, successCallback, errorCallback);
			};

		    $scope.cancel = function() {
		        $location.path("/Equipes");
		    };

		    function isEditMode() {
			    if ($location.path().indexOf("edit") > -1) {
			    	return true;
				}
			    return false;
		    }

		    if (isEditMode()) {
		    	$scope.get();
		    }

		    $scope.excluirElaboracaoNormativa = function(elaboracaoNormativaConsulta){
				var index = $scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.indexOf(elaboracaoNormativaConsulta);
				$scope.elaboracaoNormativa.listaElaboracaoNormativaConsulta.splice(index, 1);
		    }

			$scope.getCoAutor = function(val) {
			    return $http.get(urlFindOrgaos, {
			      params: {
			        nome: val
			      }
			    }).then(function(response){
			      return response.data.map(function(item){
			        return item;
			      });
			    });
			  };

			$scope.getOrigemElaboracaoNormativas = function(val) {
			    return $http.get(urlFindOrgaos, {
			      params: {
			        nome: val
			      }
			    }).then(function(response){
			        if (val) {
			        	var item = new OrgaoResource();
			        	item.nome = val;
			        	response.data.unshift(item);
			        }
		    		return response.data.map(function(item){
		    			return item;
		    		});
			    },function(error){
			      console.log('Erro ao buscar dados getOrigemElaboracaoNormativas');
			    });
			  };

			$scope.getAreaConsultadas = function(val) {
			    return $http.get(urlFindAreasConsultadas, {
			      params: {
			        descricao: val
			      }
			    }).then(function(response){
			        if (val) {
			        	var item = new AreaConsultadaResource();
			        	item.descricao = val;
			        	response.data.unshift(item);
			        }
			      return response.data.map(function(item){
			        return item;
			      });
			    });
			  };

		    $scope.onSelectAreaConsultadas = function (item) {
		    	if(!item.id){
			    	item.$save(function(success){
			    		toaster.pop('success', 'Registro inserido com sucesso.');
			    	});
		    	}
		    };

		    // CALENDARIO
		    $scope.setCalendar = function() {
				$scope.openCalendar = function($event, id) {
					$event.preventDefault();
					$event.stopPropagation();
					var opened = 'opened_'+id;
					var model = $parse(opened);
					model.assign($scope, true);
					$scope.apply;

				};

				$scope.dateOptions = {
					formatYear : 'yy',
					startingDay : 1
				};

		    }

		    $scope.setCalendar();

		    $scope.format = 'dd/MM/yyyy';

		    //Aba default
		    $scope.selected = "dadosPreliminares";

		    $scope.mostraSubTipo = function(){
		    	var retorno = false;
		    	if($scope.elaboracaoNormativa.tipo!==undefined){
		    		if(angular.equals($scope.elaboracaoNormativa.tipo, 'EXPOSICAOMOTIVOS')){
		    			retorno = true;
		    		}
		    	}
		    	return retorno;
		    }

		    $scope.validaCampos = function(campo){
		    	return checkEmpty(campo);
		    }

		    $scope.validaCamposNormaGerada = function(campoElaboracaoNormativaNorma, campo){
		    	return (!checkEmpty(campoElaboracaoNormativaNorma) && checkEmpty(campo));
		    }

		    $scope.validaForm = function(){
		    	if($scope.elaboracaoNormativa.tipo!==undefined){
		    		if(angular.equals($scope.elaboracaoNormativa.tipo, 'EXPOSICAOMOTIVOS')
		    				&& checkEmpty($scope.elaboracaoNormativa.subTipo)){
		    			return true;
		    		}
		    		if(!checkEmpty($scope.elaboracaoNormativa.elaboracaoNormativaNorma)){
			    		if(checkEmpty($scope.elaboracaoNormativa.normaGeradaNumero)
			    				||checkEmpty($scope.elaboracaoNormativa.normaGeradaAno)){
			    			return true;
			    		}
		    		}
		    		if(checkEmpty($scope.elaboracaoNormativa.tipo)
		    				||checkEmpty($scope.elaboracaoNormativa.ementa)
		    				||checkEmpty($scope.elaboracaoNormativa.identificacao)
		    				||checkEmpty($scope.elaboracaoNormativa.ano)
		    				||checkEmpty($scope.elaboracaoNormativa.nup)
		    				||checkEmpty($scope.elaboracaoNormativa.origem)){
		    			return true;
		    		}
		    	}else{
		    		return true;
		    	}
		    	return false;
		    }

		    function checkEmpty(str){
		    	if(!str || !/[^\s]+/.test(str)){
		    		return true;
		    	}
		        return false;
		    }

		});<|endoftext|>


<commit_before>function getCurrentSection(hrefString, appContext) {
    var arr = hrefString.split('/');

    for(var i = 0; i < arr.length; i++) {
        if (arr[i].length > 0 && ('/' + arr[i].toLowerCase()) != appContext.toLowerCase()) {
            return arr[i].toLowerCase();
        }
    }
    return null;
}

function setActiveMenu(appContext) {
    if(document.location.href) {
        currentLocation = document.location.href;
    } else {
        currentLocation = document.location;
    }

    if (document.getElementById('leftnav') != null && currentLocation != null) {
        menuItems = document.getElementById('leftnav').getElementsByTagName('ul')[0].getElementsByTagName('a');
        for(var i = 0; i < menuItems.length; i++) {
            if(menuItems[i].href == currentLocation) {
                menuItems[i].className = 'selected';
                return;
            }
        }
        if (document.location.pathname != null && getCurrentSection(document.location.pathname, appContext) != null) {
            currentSection = getCurrentSection(document.location.pathname, appContext);
            for(var i = 1; i < menuItems.length; i++) {
                if(getCurrentSection(menuItems[i].pathname, appContext) == currentSection) {
                    menuItems[i].className = 'selected';
                    return;
                }
            }
        }
    }
}

function setSelectedTab() {
    tabMenuItems = document.getElementById('tabbed').getElementsByTagName('li');
    for(var i = 0; i < tabMenuItems.length; i++) {
        tabLink = tabMenuItems[i].getElementsByTagName('a')[0];
        if(tabLink.className == 'current') {
            tabMenuItems[i].className = 'active';
        } else {
            tabMenuItems[i].className = '';
        }
        tabLink.blur();
    }
}

function showSubmittingText() {
    if (document.getElementById('submittingText') != null) {
        document.getElementById('submittingText').style.display = 'block';
        document.getElementById('theForm').style.display = 'none';
    }
}

function showLoadingText() {
    if (document.getElementById('loadingText') != null) {
        document.getElementById('loadingText').style.display = 'block';
        document.getElementById('theForm').style.display = 'none';
    }
}

function submitForm(actionUrl, formId) {
    document.getElementById(formId).action = actionUrl;
    document.getElementById(formId).submit();
}

var ProtExpress = {
    submitAjaxForm: function(formId, divId, options) {
        var formData = Form.serialize(formId);
        options = options || {};
        if (options.extraArgs) {
            formData = formData + '&' + Hash.toQueryString(options.extraArgs);
        }
        var url = options.url || $(formId).action;
        new Ajax.Updater(divId, url, {parameters: formData, evalScripts: true, insertion: options.insertion} );
    },
    submitAjaxFormToUrl: function(formId, divId, url) {
        var formData = Form.serialize(formId);
        var options = {};
        new Ajax.Updater(divId, url, {parameters: formData, evalScripts: true, insertion: options.insertion} );
    },
  submitDivAsForm: function(url, divId) {
      var div = document.getElementById(divId);
      var fields = div.getElementsByTagName("input");
      var params="";
      for (var i=0; i<fields.length; i++) {
          params += fields[i].name + "=" + escape(fields[i].value) + "&";
      }
      var aj = new Ajax.Updater(div, url, {
          asynchronous: true,
          method: 'post',
          evalScripts: true,
          parameters: params
      });
      return false;
  },
    loadDiv: function(url, divId, showLoadingIcon) {
    var div = document.getElementById(divId);
    if (showLoadingIcon) {
      div.innerHTML = '
 Loading...
';
    }
    var aj = new Ajax.Updater(div, url, {
      asynchronous: true,
      method: 'get',
      evalScripts: true
    });
    return false;
  },
  submitDivOnReturn: function (e, addId) {
    var characterCode;
    if(e && e.which){
      e = e;
      characterCode = e.which;
    } else {
      e = event;
      characterCode = e.keyCode;
    }
    if(characterCode == 13){
      var add = document.getElementById(addId);
      add.onclick();
      return false
    }
    else{
      return true
    }
  },
  setFocusToFirstControl: function () {
    for (var f=0; f < document.forms.length; f++) {
      for(var i=0; i < document.forms[f].length; i++) {
        var elt = document.forms[f][i];
        if (elt.type != "hidden" && elt.disabled != true && elt.id != 'enableEnterSubmit') {
          try {
            elt.focus();
            return;
          } catch(er) {
          }
        }
      }
    }
  },
  textFieldCounter: function(elementId, labelId, maxLength, counterMessage) {
    var element = document.getElementById(elementId);
    var labelElement = document.getElementById(labelId);
    if (element.value.length > maxLength) {
        element.value = element.value.substring(0, maxLength);
    } else {
        var remainingChars = maxLength - element.value.length;
        labelElement.innerHTML = remainingChars + " " + counterMessage;
    }
  },
  showDiv: function(divId) {
    var divElement = document.getElementById(divId);
    divElement.style.display = "block";
  },
  hideDiv: function(divId) {
    var divElement = document.getElementById(divId);
    divElement.style.display = "none";
  },
  setHelpTopic: function(helpTopicId) {
    var pageHelpTopicElement = document.getElementById("pageHelpTopic");
    pageHelpTopicElement.value = helpTopicId;
  },
  showHelp: function(showNav) {
    var pageHelpTopicElement = document.getElementById("pageHelpTopic");
    var helpTopic = "welcome_help";
    if ((pageHelpTopicElement != null) && (pageHelpTopicElement.value != null) && (pageHelpTopicElement.value != "")) {
        helpTopic = pageHelpTopicElement.value;
    }
    var helpUrl = contextPath + "/help/index.html?";
    if (showNav) {
        helpUrl += "single=false&";
    }
    else {
        helpUrl += "single=true&";
    }

    helpUrl += "topic=" + helpTopic;
    window.open(helpUrl, "Help", "titlebar,status,scrollbars,resizable,alwaysRaised,dependent,width=800,height=500");
  }
}

<commit_msg>Updated to display the context sensitive help topics. <commit_after>function getCurrentSection(hrefString, appContext) {
    var arr = hrefString.split('/');

    for(var i = 0; i < arr.length; i++) {
        if (arr[i].length > 0 && ('/' + arr[i].toLowerCase()) != appContext.toLowerCase()) {
            return arr[i].toLowerCase();
        }
    }
    return null;
}

function setActiveMenu(appContext) {
    if(document.location.href) {
        currentLocation = document.location.href;
    } else {
        currentLocation = document.location;
    }

    if (document.getElementById('leftnav') != null && currentLocation != null) {
        menuItems = document.getElementById('leftnav').getElementsByTagName('ul')[0].getElementsByTagName('a');
        for(var i = 0; i < menuItems.length; i++) {
            if(menuItems[i].href == currentLocation) {
                menuItems[i].className = 'selected';
                return;
            }
        }
        if (document.location.pathname != null && getCurrentSection(document.location.pathname, appContext) != null) {
            currentSection = getCurrentSection(document.location.pathname, appContext);
            for(var i = 1; i < menuItems.length; i++) {
                if(getCurrentSection(menuItems[i].pathname, appContext) == currentSection) {
                    menuItems[i].className = 'selected';
                    return;
                }
            }
        }
    }
}

function setSelectedTab() {
    tabMenuItems = document.getElementById('tabbed').getElementsByTagName('li');
    for(var i = 0; i < tabMenuItems.length; i++) {
        tabLink = tabMenuItems[i].getElementsByTagName('a')[0];
        if(tabLink.className == 'current') {
            tabMenuItems[i].className = 'active';
        } else {
            tabMenuItems[i].className = '';
        }
        tabLink.blur();
    }
}

function showSubmittingText() {
    if (document.getElementById('submittingText') != null) {
        document.getElementById('submittingText').style.display = 'block';
        document.getElementById('theForm').style.display = 'none';
    }
}

function showLoadingText() {
    if (document.getElementById('loadingText') != null) {
        document.getElementById('loadingText').style.display = 'block';
        document.getElementById('theForm').style.display = 'none';
    }
}

function submitForm(actionUrl, formId) {
    document.getElementById(formId).action = actionUrl;
    document.getElementById(formId).submit();
}

var ProtExpress = {
    submitAjaxForm: function(formId, divId, options) {
        var formData = Form.serialize(formId);
        options = options || {};
        if (options.extraArgs) {
            formData = formData + '&' + Hash.toQueryString(options.extraArgs);
        }
        var url = options.url || $(formId).action;
        new Ajax.Updater(divId, url, {parameters: formData, evalScripts: true, insertion: options.insertion} );
    },
    submitAjaxFormToUrl: function(formId, divId, url) {
        var formData = Form.serialize(formId);
        var options = {};
        new Ajax.Updater(divId, url, {parameters: formData, evalScripts: true, insertion: options.insertion} );
    },
  submitDivAsForm: function(url, divId) {
      var div = document.getElementById(divId);
      var fields = div.getElementsByTagName("input");
      var params="";
      for (var i=0; i<fields.length; i++) {
          params += fields[i].name + "=" + escape(fields[i].value) + "&";
      }
      var aj = new Ajax.Updater(div, url, {
          asynchronous: true,
          method: 'post',
          evalScripts: true,
          parameters: params
      });
      return false;
  },
    loadDiv: function(url, divId, showLoadingIcon) {
    var div = document.getElementById(divId);
    if (showLoadingIcon) {
      div.innerHTML = '
 Loading...
';
    }
    var aj = new Ajax.Updater(div, url, {
      asynchronous: true,
      method: 'get',
      evalScripts: true
    });
    return false;
  },
  submitDivOnReturn: function (e, addId) {
    var characterCode;
    if(e && e.which){
      e = e;
      characterCode = e.which;
    } else {
      e = event;
      characterCode = e.keyCode;
    }
    if(characterCode == 13){
      var add = document.getElementById(addId);
      add.onclick();
      return false
    }
    else{
      return true
    }
  },
  setFocusToFirstControl: function () {
    for (var f=0; f < document.forms.length; f++) {
      for(var i=0; i < document.forms[f].length; i++) {
        var elt = document.forms[f][i];
        if (elt.type != "hidden" && elt.disabled != true && elt.id != 'enableEnterSubmit') {
          try {
            elt.focus();
            return;
          } catch(er) {
          }
        }
      }
    }
  },
  textFieldCounter: function(elementId, labelId, maxLength, counterMessage) {
    var element = document.getElementById(elementId);
    var labelElement = document.getElementById(labelId);
    if (element.value.length > maxLength) {
        element.value = element.value.substring(0, maxLength);
    } else {
        var remainingChars = maxLength - element.value.length;
        labelElement.innerHTML = remainingChars + " " + counterMessage;
    }
  },
  showDiv: function(divId) {
    var divElement = document.getElementById(divId);
    divElement.style.display = "block";
  },
  hideDiv: function(divId) {
    var divElement = document.getElementById(divId);
    divElement.style.display = "none";
  },
  setHelpTopic: function(helpTopicId) {
    var pageHelpTopicElement = document.getElementById("pageHelpTopic");
    pageHelpTopicElement.value = helpTopicId;
  },
  showHelp: function(showNav) {
    var pageHelpTopicElement = document.getElementById("pageHelpTopic");
    var helpTopic = "welcome_help";
    var helpContext = "protExpress_Online_Help";

    if ((pageHelpTopicElement != null) && (pageHelpTopicElement.value != null) && (pageHelpTopicElement.value != "")) {
        helpTopic = pageHelpTopicElement.value;
    }
    var helpUrl = contextPath + "/help/index.html?context=" + helpContext + "&";
    if (showNav) {
        helpUrl += "single=false&";
    }
    else {
        helpUrl += "single=true&";
    }

    helpUrl += "topic=" + helpTopic;
    window.open(helpUrl, "Help", "titlebar,status,scrollbars,resizable,alwaysRaised,dependent,width=800,height=500");
  }
}

<|endoftext|>


<commit_before>const _ = {};
module.exports = _;

// 常用的函数
_.ø = function (){};
_.identity = x => x;
_.toString = ({}).toString;

// 类型判断
_.isType = type => val => _.toString.call(val) === '[object ' + type + ']';

_.isFunc = _.isType('Function');
_.isArray = _.isType('Array');
_.isNumber = _.isType('Number');
_.isString = _.isType('String');
_.isBoolean = _.isType('Boolean');<commit_msg>add:isBoolean, isNull, isUndefined<commit_after>const _ = {};
module.exports = _;

// 常用的函数
_.ø = function (){};
_.identity = x => x;
_.toString = ({}).toString;

// 类型判断
_.isType = type => val => _.toString.call(val) === '[object ' + type + ']';

_.isFunc = _.isType('Function');
_.isArray = _.isType('Array');
_.isNumber = _.isType('Number');
_.isString = _.isType('String');
_.isBoolean = _.isType('Boolean');
_.isNull = _.isType('Null');
_.isUndefined = _.isType('Undefined');<|endoftext|>


<commit_before>/** @flow */
import cn from 'classnames'
import Immutable from 'immutable'
import React, { Component, PropTypes } from 'react'
import { ContentBox, ContentBoxHeader, ContentBoxParagraph } from '../demo/ContentBox'
import WindowScroller from './WindowScroller'
import List from '../List'
import AutoSizer from '../AutoSizer'
import shallowCompare from 'react-addons-shallow-compare'
import styles from './WindowScroller.example.css'

export default class WindowScrollerExample extends Component {
  static contextTypes = {
    list: PropTypes.instanceOf(Immutable.List).isRequired,
    customElement: PropTypes.any,
    isScrollingCustomElement: PropTypes.bool.isRequired,
    setScrollingCustomElement: PropTypes.func
  }

  constructor (props) {
    super(props)

    this.state = {
      showHeaderText: true
    }

    this._hideHeader = this._hideHeader.bind(this)
    this._rowRenderer = this._rowRenderer.bind(this)
    this.onChangeCustomElementCheckbox = this.onChangeCustomElementCheckbox.bind(this)
  }

  onChangeCustomElementCheckbox (event) {
    this.context.setScrollingCustomElement(event.target.checked)
  }

  render () {
    const { list, isScrollingCustomElement, customElement } = this.context
    const { showHeaderText } = this.state

    return (
      <ContentBox>
        <ContentBoxHeader
          text='WindowScroller'
          sourceLink='https://github.com/bvaughn/react-virtualized/blob/master/source/WindowScroller/WindowScroller.example.js'
          docsLink='https://github.com/bvaughn/react-virtualized/blob/master/docs/WindowScroller.md'
        />

        {showHeaderText && (
          <ContentBoxParagraph>
            This component decorates List, Table, or any other component
            and manages the window scroll to scroll through the list
          </ContentBoxParagraph>
        )}

        {showHeaderText && (
          <ContentBoxParagraph>
            <button onClick={this._hideHeader}>
              Hide header text
            </button>
          </ContentBoxParagraph>
        )}

        <ContentBoxParagraph>

            <input
              aria-label='Use custom element for scrolling'
              className={styles.checkbox}
              type='checkbox'
              value={isScrollingCustomElement}
              onChange={this.onChangeCustomElementCheckbox}
            />
            Use custom element for scrolling

        </ContentBoxParagraph>

          <WindowScroller scrollElement={isScrollingCustomElement ? customElement : null}>
            {({ height, isScrolling, scrollTop }) => (
              <AutoSizer disableHeight>
                {({ width }) => (
                  <List
                    autoHeight
                    className={styles.List}
                    height={height}
                    overscanRowCount={2}
                    rowCount={list.size}
                    rowHeight={30}
                    rowRenderer={({ index, isVisible, key, style }) => this._rowRenderer({ index, isScrolling, isVisible, key, style })}
                    scrollTop={scrollTop}
                    width={width}
                  />
                )}
              </AutoSizer>
            )}
          </WindowScroller>

      </ContentBox>
    )
  }

  shouldComponentUpdate (nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }

  _hideHeader () {
    const { showHeaderText } = this.state

    this.setState({
      showHeaderText: !showHeaderText
    }, () => {
      this._windowScroller.updatePosition()
    })
  }

  _rowRenderer ({ index, isScrolling, isVisible, key, style }) {
    const { list } = this.context
    const row = list.get(index)
    const className = cn(styles.row, {
      [styles.rowScrolling]: isScrolling,
      isVisible: isVisible
    })

    return (

        {row.name}

    )
  }
}
<commit_msg>Fix checkbox bug/typo<commit_after>/** @flow */
import cn from 'classnames'
import Immutable from 'immutable'
import React, { Component, PropTypes } from 'react'
import { ContentBox, ContentBoxHeader, ContentBoxParagraph } from '../demo/ContentBox'
import WindowScroller from './WindowScroller'
import List from '../List'
import AutoSizer from '../AutoSizer'
import shallowCompare from 'react-addons-shallow-compare'
import styles from './WindowScroller.example.css'

export default class WindowScrollerExample extends Component {
  static contextTypes = {
    list: PropTypes.instanceOf(Immutable.List).isRequired,
    customElement: PropTypes.any,
    isScrollingCustomElement: PropTypes.bool.isRequired,
    setScrollingCustomElement: PropTypes.func
  }

  constructor (props) {
    super(props)

    this.state = {
      showHeaderText: true
    }

    this._hideHeader = this._hideHeader.bind(this)
    this._rowRenderer = this._rowRenderer.bind(this)
    this.onChangeCustomElementCheckbox = this.onChangeCustomElementCheckbox.bind(this)
  }

  onChangeCustomElementCheckbox (event) {
    this.context.setScrollingCustomElement(event.target.checked)
  }

  render () {
    const { list, isScrollingCustomElement, customElement } = this.context
    const { showHeaderText } = this.state

    return (
      <ContentBox>
        <ContentBoxHeader
          text='WindowScroller'
          sourceLink='https://github.com/bvaughn/react-virtualized/blob/master/source/WindowScroller/WindowScroller.example.js'
          docsLink='https://github.com/bvaughn/react-virtualized/blob/master/docs/WindowScroller.md'
        />

        {showHeaderText && (
          <ContentBoxParagraph>
            This component decorates List, Table, or any other component
            and manages the window scroll to scroll through the list
          </ContentBoxParagraph>
        )}

        {showHeaderText && (
          <ContentBoxParagraph>
            <button onClick={this._hideHeader}>
              Hide header text
            </button>
          </ContentBoxParagraph>
        )}

        <ContentBoxParagraph>

            <input
              aria-label='Use custom element for scrolling'
              className={styles.checkbox}
              type='checkbox'
              checked={isScrollingCustomElement}
              onChange={this.onChangeCustomElementCheckbox}
            />
            Use custom element for scrolling

        </ContentBoxParagraph>

          <WindowScroller scrollElement={isScrollingCustomElement ? customElement : null}>
            {({ height, isScrolling, scrollTop }) => (
              <AutoSizer disableHeight>
                {({ width }) => (
                  <List
                    autoHeight
                    className={styles.List}
                    height={height}
                    overscanRowCount={2}
                    rowCount={list.size}
                    rowHeight={30}
                    rowRenderer={({ index, isVisible, key, style }) => this._rowRenderer({ index, isScrolling, isVisible, key, style })}
                    scrollTop={scrollTop}
                    width={width}
                  />
                )}
              </AutoSizer>
            )}
          </WindowScroller>

      </ContentBox>
    )
  }

  shouldComponentUpdate (nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }

  _hideHeader () {
    const { showHeaderText } = this.state

    this.setState({
      showHeaderText: !showHeaderText
    }, () => {
      this._windowScroller.updatePosition()
    })
  }

  _rowRenderer ({ index, isScrolling, isVisible, key, style }) {
    const { list } = this.context
    const row = list.get(index)
    const className = cn(styles.row, {
      [styles.rowScrolling]: isScrolling,
      isVisible: isVisible
    })

    return (

        {row.name}

    )
  }
}
<|endoftext|>


<commit_before>/**
 * @copyright Copyright (c) 2019 Marco Ambrosini <marcoambrosini@pm.me>
 *
 * @author Marco Ambrosini <marcoambrosini@pm.me>
 *
 * @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/>.
 *
 */
import Vue from 'vue'

const state = {
	/**
	 * Map of conversation token to message list
	 */
	messages: {},
	/**
	 * Map of conversation token to first known message id
	 */
	firstKnown: {},
	/**
	 * Map of conversation token to last known message id
	 */
	lastKnown: {},
}

const getters = {
	/**
	 * Gets the messages array
	 * @param {object} state the state object.
	 * @returns {array} the messages array (if there are messages in the store)
	 */
	messagesList: (state) => (token) => {
		if (state.messages[token]) {
			return Object.values(state.messages[token])
		}
		return []
	},
	/**
	 * Gets the messages object
	 * @param {object} state the state object.
	 * @param {string} token the conversation token.
	 * @returns {object} the messages object (if there are messages in the store)
	 */
	messages: (state) => (token) => {
		if (state.messages[token]) {
			return state.messages[token]
		}
		return {}
	},
	/**
	 * Gets a single message object
	 * @param {object} state the state object.
	 * @param {string} token the conversation token.
	 * @param {string} id the message id.
	 * @returns {object} the message object (if the message is found in the store)
	 */
	message: (state) => (token, id) => {
		if (state.messages[token][id]) {
			return state.messages[token][id]
		}
		return {}
	},

	getTemporaryReferences: (state) => (token, referenceId) => {
		if (!state.messages[token]) {
			return []
		}

		return Object.values(state.messages[token]).filter(message => {
			return message.referenceId === referenceId
				&& ('' + message.id).startsWith('temp-')
		})
	},

	getFirstKnownMessageId: (state) => (token) => {
		if (state.firstKnown[token]) {
			return state.firstKnown[token]
		}
		return null
	},

	getLastKnownMessageId: (state) => (token) => {
		if (state.lastKnown[token]) {
			return state.lastKnown[token]
		}
		return null
	},
}

const mutations = {
	/**
	 * Adds a message to the store.
	 * @param {object} state current store state;
	 * @param {object} message the message;
	 */
	addMessage(state, message) {
		if (!state.messages[message.token]) {
			Vue.set(state.messages, message.token, {})
		}
		if (state.messages[message.token][message.id]) {
			Vue.set(state.messages[message.token], message.id,
				Object.assign(state.messages[message.token][message.id], message)
			)
		} else {
			Vue.set(state.messages[message.token], message.id, message)
		}
	},
	/**
	 * Deletes a message from the store.
	 * @param {object} state current store state;
	 * @param {object} message the message;
	 */
	deleteMessage(state, message) {
		Vue.delete(state.messages[message.token], message.id)
	},

	/**
	 * Adds a temporary message to the store.
	 * @param {object} state current store state;
	 * @param {object} message the temporary message;
	 */
	addTemporaryMessage(state, message) {
		Vue.set(state.messages[message.token], message.id, message)
	},

	/**
	 * Adds a temporary message to the store.
	 * @param {object} state current store state;
	 * @param {object} message the temporary message;
	 * @param {string} reason the reason the temporary message failed;
	 */
	markTemporaryMessageAsFailed(state, { message, reason }) {
		if (state.messages[message.token][message.id]) {
			Vue.set(state.messages[message.token][message.id], 'sendingFailure', reason)
		}
	},

	/**
	 * @param {object} state current store state;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the first known chat message
	 */
	setFirstKnownMessageId(state, { token, id }) {
		Vue.set(state.firstKnown, token, id)
	},

	/**
	 * @param {object} state current store state;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the last known chat message
	 */
	setLastKnownMessageId(state, { token, id }) {
		Vue.set(state.lastKnown, token, id)
	},

	/**
	 * Deletes the messages entry from the store for the given conversation token.
	 *
	 * @param {object} state current store state
	 * @param {string} token Token of the conversation
	 */
	deleteMessages(state, token) {
		if (state.firstKnown[token]) {
			Vue.delete(state.firstKnown, token)
		}
		if (state.lastKnown[token]) {
			Vue.delete(state.lastKnown, token)
		}
		if (state.messages[token]) {
			Vue.delete(state.messages, token)
		}
	},
}

const actions = {

	/**
	 * Adds message to the store.
	 *
	 * If the message has a parent message object,
	 * first it adds the parent to the store.
	 *
	 * @param {object} context default store context;
	 * @param {object} message the message;
	 */
	processMessage(context, message) {
		if (message.parent) {
			context.commit('addMessage', message.parent)
			message.parent = message.parent.id
		}

		if (message.referenceId) {
			const tempMessages = context.getters.getTemporaryReferences(message.token, message.referenceId)
			tempMessages.forEach(tempMessage => {
				context.commit('deleteMessage', tempMessage)
			})
		}

		context.commit('addMessage', message)
	},

	/**
	 * Delete a message
	 *
	 * @param {object} context default store context;
	 * @param {string} message the message to be deleted;
	 */
	deleteMessage(context, message) {
		context.commit('deleteMessage', message)
	},

	/**
	 * Add a temporary message generated in the client to
	 * the store, these messages are deleted once the full
	 * message object is received from the server.
	 *
	 * @param {object} context default store context;
	 * @param {object} message the temporary message;
	 */
	addTemporaryMessage(context, message) {
		context.commit('addTemporaryMessage', message)
		// Update conversations list order
		context.dispatch('updateConversationLastActive', message.token)
	},

	/**
	 * Mark a temporary message as failed to allow retrying it again
	 *
	 * @param {object} context default store context;
	 * @param {object} message the temporary message;
	 * @param {string} reason the reason the temporary message failed;
	 */
	markTemporaryMessageAsFailed(context, { message, reason }) {
		context.commit('markTemporaryMessageAsFailed', { message, reason })
	},

	/**
	 * @param {object} context default store context;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the first known chat message
	 */
	setFirstKnownMessageId(context, { token, id }) {
		context.commit('setFirstKnownMessageId', { token, id })
	},

	/**
	 * @param {object} context default store context;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the last known chat message
	 */
	setLastKnownMessageId(context, { token, id }) {
		context.commit('setLastKnownMessageId', { token, id })
	},

	/**
	 * Deletes the messages of a conversation
	 *
	 * @param {object} context default store context;
	 * @param {object} token the token of the conversation to be deleted;
	 */
	deleteMessages(context, token) {
		context.commit('deleteMessages', token)
	},
}

export default { state, mutations, getters, actions }
<commit_msg>Allow to post in completely empty chats<commit_after>/**
 * @copyright Copyright (c) 2019 Marco Ambrosini <marcoambrosini@pm.me>
 *
 * @author Marco Ambrosini <marcoambrosini@pm.me>
 *
 * @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/>.
 *
 */
import Vue from 'vue'

const state = {
	/**
	 * Map of conversation token to message list
	 */
	messages: {},
	/**
	 * Map of conversation token to first known message id
	 */
	firstKnown: {},
	/**
	 * Map of conversation token to last known message id
	 */
	lastKnown: {},
}

const getters = {
	/**
	 * Gets the messages array
	 * @param {object} state the state object.
	 * @returns {array} the messages array (if there are messages in the store)
	 */
	messagesList: (state) => (token) => {
		if (state.messages[token]) {
			return Object.values(state.messages[token])
		}
		return []
	},
	/**
	 * Gets the messages object
	 * @param {object} state the state object.
	 * @param {string} token the conversation token.
	 * @returns {object} the messages object (if there are messages in the store)
	 */
	messages: (state) => (token) => {
		if (state.messages[token]) {
			return state.messages[token]
		}
		return {}
	},
	/**
	 * Gets a single message object
	 * @param {object} state the state object.
	 * @param {string} token the conversation token.
	 * @param {string} id the message id.
	 * @returns {object} the message object (if the message is found in the store)
	 */
	message: (state) => (token, id) => {
		if (state.messages[token][id]) {
			return state.messages[token][id]
		}
		return {}
	},

	getTemporaryReferences: (state) => (token, referenceId) => {
		if (!state.messages[token]) {
			return []
		}

		return Object.values(state.messages[token]).filter(message => {
			return message.referenceId === referenceId
				&& ('' + message.id).startsWith('temp-')
		})
	},

	getFirstKnownMessageId: (state) => (token) => {
		if (state.firstKnown[token]) {
			return state.firstKnown[token]
		}
		return null
	},

	getLastKnownMessageId: (state) => (token) => {
		if (state.lastKnown[token]) {
			return state.lastKnown[token]
		}
		return null
	},
}

const mutations = {
	/**
	 * Adds a message to the store.
	 * @param {object} state current store state;
	 * @param {object} message the message;
	 */
	addMessage(state, message) {
		if (!state.messages[message.token]) {
			Vue.set(state.messages, message.token, {})
		}
		if (state.messages[message.token][message.id]) {
			Vue.set(state.messages[message.token], message.id,
				Object.assign(state.messages[message.token][message.id], message)
			)
		} else {
			Vue.set(state.messages[message.token], message.id, message)
		}
	},
	/**
	 * Deletes a message from the store.
	 * @param {object} state current store state;
	 * @param {object} message the message;
	 */
	deleteMessage(state, message) {
		if (state.messages[message.token][message.id]) {
			Vue.delete(state.messages[message.token], message.id)
		}
	},

	/**
	 * Adds a temporary message to the store.
	 * @param {object} state current store state;
	 * @param {object} message the temporary message;
	 */
	addTemporaryMessage(state, message) {
		if (!state.messages[message.token]) {
			Vue.set(state.messages, message.token, {})
		}
		Vue.set(state.messages[message.token], message.id, message)
	},

	/**
	 * Adds a temporary message to the store.
	 * @param {object} state current store state;
	 * @param {object} message the temporary message;
	 * @param {string} reason the reason the temporary message failed;
	 */
	markTemporaryMessageAsFailed(state, { message, reason }) {
		if (state.messages[message.token][message.id]) {
			Vue.set(state.messages[message.token][message.id], 'sendingFailure', reason)
		}
	},

	/**
	 * @param {object} state current store state;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the first known chat message
	 */
	setFirstKnownMessageId(state, { token, id }) {
		Vue.set(state.firstKnown, token, id)
	},

	/**
	 * @param {object} state current store state;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the last known chat message
	 */
	setLastKnownMessageId(state, { token, id }) {
		Vue.set(state.lastKnown, token, id)
	},

	/**
	 * Deletes the messages entry from the store for the given conversation token.
	 *
	 * @param {object} state current store state
	 * @param {string} token Token of the conversation
	 */
	deleteMessages(state, token) {
		if (state.firstKnown[token]) {
			Vue.delete(state.firstKnown, token)
		}
		if (state.lastKnown[token]) {
			Vue.delete(state.lastKnown, token)
		}
		if (state.messages[token]) {
			Vue.delete(state.messages, token)
		}
	},
}

const actions = {

	/**
	 * Adds message to the store.
	 *
	 * If the message has a parent message object,
	 * first it adds the parent to the store.
	 *
	 * @param {object} context default store context;
	 * @param {object} message the message;
	 */
	processMessage(context, message) {
		if (message.parent) {
			context.commit('addMessage', message.parent)
			message.parent = message.parent.id
		}

		if (message.referenceId) {
			const tempMessages = context.getters.getTemporaryReferences(message.token, message.referenceId)
			tempMessages.forEach(tempMessage => {
				context.commit('deleteMessage', tempMessage)
			})
		}

		context.commit('addMessage', message)
	},

	/**
	 * Delete a message
	 *
	 * @param {object} context default store context;
	 * @param {string} message the message to be deleted;
	 */
	deleteMessage(context, message) {
		context.commit('deleteMessage', message)
	},

	/**
	 * Add a temporary message generated in the client to
	 * the store, these messages are deleted once the full
	 * message object is received from the server.
	 *
	 * @param {object} context default store context;
	 * @param {object} message the temporary message;
	 */
	addTemporaryMessage(context, message) {
		context.commit('addTemporaryMessage', message)
		// Update conversations list order
		context.dispatch('updateConversationLastActive', message.token)
	},

	/**
	 * Mark a temporary message as failed to allow retrying it again
	 *
	 * @param {object} context default store context;
	 * @param {object} message the temporary message;
	 * @param {string} reason the reason the temporary message failed;
	 */
	markTemporaryMessageAsFailed(context, { message, reason }) {
		context.commit('markTemporaryMessageAsFailed', { message, reason })
	},

	/**
	 * @param {object} context default store context;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the first known chat message
	 */
	setFirstKnownMessageId(context, { token, id }) {
		context.commit('setFirstKnownMessageId', { token, id })
	},

	/**
	 * @param {object} context default store context;
	 * @param {string} token Token of the conversation
	 * @param {string} id Id of the last known chat message
	 */
	setLastKnownMessageId(context, { token, id }) {
		context.commit('setLastKnownMessageId', { token, id })
	},

	/**
	 * Deletes the messages of a conversation
	 *
	 * @param {object} context default store context;
	 * @param {object} token the token of the conversation to be deleted;
	 */
	deleteMessages(context, token) {
		context.commit('deleteMessages', token)
	},
}

export default { state, mutations, getters, actions }
<|endoftext|>


<commit_before>function ClearNodes() {}

module.exports = ClearNodes;

ClearNodes.prototype.build = function() {
    var buf = new ArrayBuffer(1);
    var view = new DataView(buf);

    view.setUint8(0, 20, true);

    return buf;
};
<commit_msg>Integrate protocol 7<commit_after>function ClearNodes(protocolVersion) {
    this.protocolVersion = protocolVersion;
}

module.exports = ClearNodes;

ClearNodes.prototype.build = function() {
    var buf = new ArrayBuffer(1);
    var view = new DataView(buf);

    view.setUint8(0, this.protocolVersion == 5 ? 20 : 18);

    return buf;
};
<|endoftext|>


<commit_before>'use strict';

var should = require('should');
var path = require('path');
var generateApi = require('../../lib/commands/generateApi/generateApi');
var generateSkeleton = require('../../lib/commands/generateApi/generateSkeleton.js')
var fs = require('fs');
var xml2js = require('xml2js');

describe('generateApi with regex-protection', function() {
  var options = {
    source : path.join(__dirname, '/swagger_files/regex-protection.yaml'),
    destination : path.join(__dirname, '../../api_bundles'),
    apiProxy :'petStoreRegexProtection'
  };

  describe('generate', function(done) {
    it('Correct swagger file should generate proxy', function(done) {
      generateApi.generateApi(options.apiProxy, options, function(err, reply) {
        should.equal(err, null);
        done();
      })
    });
  });

  describe('Add regex-protection policy', function() {
    // it('Headers token policy should be generated', function(done) {
    //   var filePath = path.join(options.destination, options.apiProxy + "/apiproxy/policies/add-headers-token.xml");
    //   var file = fs.lstatSync(filePath);
    //   should.equal(file.isFile(), true);
    //
    //   var fileData = fs.readFileSync(filePath);
    //   var parser = new xml2js.Parser();
    //   parser.parseString(fileData, function (err, result) {
    //     result.should.have.property('AssignMessage');
    //     result.should.have.property('AssignMessage').property('Set');
    //     var headers = result.AssignMessage.Set[0].Headers[0];
    //     // Check Header name and value
    //     should.equal(headers.Header[0].$.name, 'x-token', 'x-token not found: ');
    //     should.equal(headers.Header[0]._, 'random_token', 'x-token value not correct');
    //     done();
    //   });
    // });

    // it('Headers x-api-key policy should be generated', function(done) {
    //   var filePath = path.join(options.destination, options.apiProxy + "/apiproxy/policies/add-headers-x-api-key.xml");
    //   var file = fs.lstatSync(filePath);
    //   should.equal(file.isFile(), true);
    //
    //   var fileData = fs.readFileSync(filePath);
    //   var parser = new xml2js.Parser();
    //   parser.parseString(fileData, function (err, result) {
    //     result.should.have.property('AssignMessage');
    //     result.should.have.property('AssignMessage').property('Set');
    //     var headers = result.AssignMessage.Set[0].Headers[0];
    //     // Check Header name and value
    //     should.equal(headers.Header[0].$.name, 'x-api-key', 'x-api-key not found: ');
    //     should.equal(headers.Header[0]._, 'random_api_key', 'x-api-key value not correct');
    //     done();
    //   });
    // });

    it('Proxy should contain header step in PreFlow', function(done) {
      var filePath = path.join(options.destination, options.apiProxy, '/apiproxy/proxies/default.xml');
      var fileData = fs.readFileSync(filePath);
      var parser = new xml2js.Parser();
      parser.parseString(fileData, function (err, result) {
        result.should.have.property('ProxyEndpoint');
        result.should.have.property('ProxyEndpoint').property('PreFlow');
        should.equal(result.ProxyEndpoint.PreFlow[0].Request[0].Step[0].Name[0], 'Add Regex Protection', 'Add Reqex Protection step in found in PreFlow');
        done();
      });
    });

  });
});
<commit_msg>tests...<commit_after>'use strict';

var should = require('should');
var path = require('path');
var generateApi = require('../../lib/commands/generateApi/generateApi');
var generateSkeleton = require('../../lib/commands/generateApi/generateSkeleton.js')
var fs = require('fs');
var xml2js = require('xml2js');

describe('generateApi with regex-protection', function() {
  var options = {
    source : path.join(__dirname, '/swagger_files/regex-protection.yaml'),
    destination : path.join(__dirname, '../../api_bundles'),
    apiProxy :'petStoreRegexProtection'
  };

  describe('generate', function(done) {
    it('Correct swagger file should generate proxy', function(done) {
      generateApi.generateApi(options.apiProxy, options, function(err, reply) {
        should.equal(err, null);
        done();
      })
    });
  });

  describe('Add regex-protection policy', function() {

    it('Regexp protection policy should be generated', function(done) {
      var filePath = path.join(options.destination, options.apiProxy + "/apiproxy/policies/regex-protection.xml");
      var file = fs.lstatSync(filePath);
      should.equal(file.isFile(), true);

      var fileData = fs.readFileSync(filePath);
      var parser = new xml2js.Parser();
      parser.parseString(fileData, function (err, result) {
        result.should.have.property('Javascript');
        result.should.have.property('Javascript').property('ResourceURL');
        // Check Header name and value
        should.equal(result.Javascript.ResourceURL[0], 'jsc://regex-protection.js', 'regex protection script not found');
        should.equal(result.Javascript.IncludeURL[0], 'jsc://regex.js', 'regex js script not found');
        done();
      });
    });

    it('Js files should be generated', function(done) {
      var filePath = path.join(options.destination, options.apiProxy + "/apiproxy/resources/jsc/regex-protection.js");
      var file = fs.lstatSync(filePath);
      should.equal(file.isFile(), true);
      var filePath = path.join(options.destination, options.apiProxy + "/apiproxy/resources/jsc/regex.js");
      var file = fs.lstatSync(filePath);
      should.equal(file.isFile(), true);
      done();
    });

    it('Raise fault policy should be generated', function(done) {
      var filePath = path.join(options.destination, options.apiProxy + "/apiproxy/policies/raiseFault.xml");
      var file = fs.lstatSync(filePath);
      should.equal(file.isFile(), true);

      var fileData = fs.readFileSync(filePath);
      var parser = new xml2js.Parser();
      parser.parseString(fileData, function (err, result) {
        result.should.have.property('RaiseFault');
        result.should.have.property('RaiseFault').property('FaultResponse');
        // Check Header name and value
        console.log('RaiseFault.FaultResponse[0]', result.RaiseFault.FaultResponse[0].Set[0].ReasonPhrase[0]);
        should.equal(result.RaiseFault.FaultResponse[0].Set[0].ReasonPhrase[0], 'Bad Request', 'ReasonPhrase not found');
        should.equal(result.RaiseFault.FaultResponse[0].Set[0].StatusCode[0], '501', '501 not found');
        done();
      });
    });

    it('Proxy should contain Add Regex Protection step in PreFlow', function(done) {
      var filePath = path.join(options.destination, options.apiProxy, '/apiproxy/proxies/default.xml');
      var fileData = fs.readFileSync(filePath);
      var parser = new xml2js.Parser();
      parser.parseString(fileData, function (err, result) {
        result.should.have.property('ProxyEndpoint');
        result.should.have.property('ProxyEndpoint').property('PreFlow');
        should.equal(result.ProxyEndpoint.PreFlow[0].Request[0].Step[0].Name[0], 'Add Regex Protection', 'Add Reqex Protection step in found in PreFlow');
        done();
      });
    });

    it('Proxy should contain Raise Regex Error step in PreFlow', function(done) {
      var filePath = path.join(options.destination, options.apiProxy, '/apiproxy/proxies/default.xml');
      var fileData = fs.readFileSync(filePath);
      var parser = new xml2js.Parser();
      parser.parseString(fileData, function (err, result) {
        result.should.have.property('ProxyEndpoint');
        result.should.have.property('ProxyEndpoint').property('PreFlow');
        should.equal(result.ProxyEndpoint.PreFlow[0].Request[0].Step[1].Name[0], 'Raise Regex Error', 'Raise Regex Error step in found in PreFlow');
        done();
      });
    });

  });
});
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const fileUrl = require('file-url');
const failFast = require('protractor-fail-fast');

const failFastActive = (process.argv.length > 4 && process.argv[4] == '--params=ff');

exports.config = {

    seleniumAddress: 'http://localhost:9515/wd/hub',
    baseUrl: fileUrl(path.resolve(__dirname, '../../..') + '/index.html'),

    specs: [
        '../syncing/*.spec.js',
        '../resources/*.spec.js',
        '../settings/*.spec.js',
        '../images/*.spec.js',
        '../list/*.spec.js',
        '../map/*.spec.js',
        '../widgets/*.spec.js',
        '../import/*.spec.js'
    ],

    allScriptsTimeout: 110000,
    getPageTimeout: 100000,
    framework: 'jasmine2',
    jasmineNodeOpts: {
        isVerbose: false,
        showColors: true,
        includeStackTrace: false,
        defaultTimeoutInterval: 400000
    },
    plugins: [{
        package: 'protractor-console-plugin',
        failOnWarning: true,
        failOnError: true,
        logWarnings: true,
        exclude: [
            "http://localhost:3001/" // pouchdb issues ignorable errors when syncing
        ]
    }],
    params: {
        appDataPath: 'test/test-temp',
        configPath: 'config/config.test.json',
        configTemplate: { 'dbs' : ['test'] }
    },
    onPrepare: function() {
        if (failFastActive) jasmine.getEnv().addReporter(failFast.init());

        var ProgressReporter = function() {

            this.specStarted = function(spec) {
                process.stdout.write("SPEC " + spec.fullName + " ")
            };

            this.specDone = function(spec) {

                console.log(spec.status.toUpperCase());

                browser.manage().logs().get('browser').then(function(browserLogs) {

                    var errLogs = browserLogs.filter(function (log) {
                        return (log.level.value_ > 900 && (log.message.
                            indexOf('Failed to load resource') === -1))});

                    if (errLogs.length > 0) {

                        console.log('--- There has been at least one browser console error (Spec '+spec.fullName+')!');

                        browserLogs.forEach(function(log){
                            if (log.level.value_ > 900) { // it's an error log
                                if (log.message.
                                    indexOf('Failed to load resource') === -1) {

                                    console.log("===> critical ERROR message: ",log.message);
                                } else {
                                    console.log("(uncritical) Error message: ",log.message);
                                }
                            } else {
                                console.log("Log message: ",log.message);
                            }
                        });
                    }

                });

            }
        };
        jasmine.getEnv().addReporter(new ProgressReporter());
    },
    afterLaunch: function() {
        if (failFastActive) failFast.clean();
    },
    /**
     * ng2 related configuration
     *
     * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
     * `rootEl`
     *
     */
    useAllAngular2AppRoots: true
};

if (failFastActive) exports.config.plugins.push({package: 'protractor-fail-fast'});<commit_msg>Adjust protractor conf<commit_after>const fs = require('fs');
const path = require('path');
const fileUrl = require('file-url');
const failFast = require('protractor-fail-fast');

const failFastActive = (process.argv.length > 4 && process.argv[4] == '--params=ff');

exports.config = {

    seleniumAddress: 'http://localhost:9515/wd/hub',
    baseUrl: fileUrl(path.resolve(__dirname, '../../..') + '/index.html'),

    specs: [
        '../syncing/*.spec.js',
        '../resources/*.spec.js',
        '../settings/*.spec.js',
        '../images/*.spec.js',
        '../map/*.spec.js',
        '../import/*.spec.js'
    ],

    allScriptsTimeout: 110000,
    getPageTimeout: 100000,
    framework: 'jasmine2',
    jasmineNodeOpts: {
        isVerbose: false,
        showColors: true,
        includeStackTrace: false,
        defaultTimeoutInterval: 400000
    },
    plugins: [{
        package: 'protractor-console-plugin',
        failOnWarning: true,
        failOnError: true,
        logWarnings: true,
        exclude: [
            "http://localhost:3001/" // pouchdb issues ignorable errors when syncing
        ]
    }],
    params: {
        appDataPath: 'test/test-temp',
        configPath: 'config/config.test.json',
        configTemplate: { 'dbs' : ['test'] }
    },
    onPrepare: function() {
        if (failFastActive) jasmine.getEnv().addReporter(failFast.init());

        var ProgressReporter = function() {

            this.specStarted = function(spec) {
                process.stdout.write("SPEC " + spec.fullName + " ")
            };

            this.specDone = function(spec) {

                console.log(spec.status.toUpperCase());

                browser.manage().logs().get('browser').then(function(browserLogs) {

                    var errLogs = browserLogs.filter(function (log) {
                        return (log.level.value_ > 900 && (log.message.
                            indexOf('Failed to load resource') === -1))});

                    if (errLogs.length > 0) {

                        console.log('--- There has been at least one browser console error (Spec '+spec.fullName+')!');

                        browserLogs.forEach(function(log){
                            if (log.level.value_ > 900) { // it's an error log
                                if (log.message.
                                    indexOf('Failed to load resource') === -1) {

                                    console.log("===> critical ERROR message: ",log.message);
                                } else {
                                    console.log("(uncritical) Error message: ",log.message);
                                }
                            } else {
                                console.log("Log message: ",log.message);
                            }
                        });
                    }

                });

            }
        };
        jasmine.getEnv().addReporter(new ProgressReporter());
    },
    afterLaunch: function() {
        if (failFastActive) failFast.clean();
    },
    /**
     * ng2 related configuration
     *
     * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
     * `rootEl`
     *
     */
    useAllAngular2AppRoots: true
};

if (failFastActive) exports.config.plugins.push({package: 'protractor-fail-fast'});<|endoftext|>


<commit_before>var locastyle = locastyle || {};

locastyle.popover = (function() {
  'use strict';

  var config = {
    container    : 'body',
    hoverEvent   : 'mouseenter.ls.popover',
    idPopover    : '#ls-popover-',
    module       : '[data-ls-module="popover"]',
    placement    : 'top',
    trigger      : 'click.ls.popover',
    popoverClass : 'ls-popover',
    uniqueId     : 0
  }

  function init() {
    if(/sm|xs/.test(locastyle.breakpointClass)){
      $(config.module).attr('data-ls-module', 'modal').removeAttr('data-trigger');
      locastyle.modal.init();
    } else{
      $(config.module).each(function  (index, elem) {
        createPopover($(elem));
      });
    }
    updateBreakpoint();
  }

  function updateBreakpoint (argument) {
    $(window).on("breakpoint-updated", function () {
      destroy();
      init();
    });
  }

  function createPopover ($elem) {
    var elementData = $elem.data(),
        width  = $elem.outerWidth(),
        height = $elem.outerHeight();
    $elem.data('uniqueId', config.uniqueId);
    elementData.position  = elementData.container ? $elem.position() : $elem.offset() ;
    elementData.container = elementData.container || config.container;
    elementData.placement = elementData.placement || config.placement;
    switch (elementData.placement) {
      case 'top':
        elementData.position.top -=  12;
        elementData.position.left +=  (width/2 + 4);
        break;
      case 'right':
        elementData.position.top +=  (height/2 -2);
        elementData.position.left += (width + 12);
        break;
      case 'bottom':
        elementData.position.top += (height + 12);
        elementData.position.left +=  (width/2 + 4);
        break;
      case 'left':
        elementData.position.top +=  (height/2 -2 );
        elementData.position.left -= 12;
    }
    elementData.uniqueId = config.uniqueId++;
    $(elementData.container).append(locastyle.templates.popover(elementData));
    var aa = $('#ls-popover-' + elementData.uniqueId );
    console.log( aa.css('width') )
    bindActions($elem, elementData);
  }

  function bindActions ($elem, elementData) {
    var trigger = elementData.trigger == 'hover' ? config.hoverEvent : config.trigger,
        $popover = $(config.idPopover + elementData.uniqueId);
    if(trigger === config.hoverEvent){
      $elem.on({
        mouseenter: function (event) {
          event.preventDefault();
          $popover.stop().show();
        },
        mouseleave: function (event) {
          event.preventDefault();
          $popover.stop().hide();
        }
      });
    } else {
      $elem.on({
        click: function (event) {
          event.preventDefault();
          event.stopPropagation();
          $popover.stop().toggle();
        }
      });
      $(document).on('click', function (event) {
        var element = event.toElement;
        if(!$(element).parents().hasClass( config.popoverClass )){
         $('.' + config.popoverClass).hide();
        }
      })
    }
  }

  function destroy() {
    $('.' + config.popoverClass).remove();
    $(config.module).each(function  (index, elem) {
      $(elem)
        .removeData('uniqueId')
        .off(config.hoverEvent)
        .off(config.trigger);
    });
  }

  return {
    init: init,
    destroyPopover: destroy
  }

}());<commit_msg>log remove<commit_after>var locastyle = locastyle || {};

locastyle.popover = (function() {
  'use strict';

  var config = {
    container    : 'body',
    hoverEvent   : 'mouseenter.ls.popover',
    idPopover    : '#ls-popover-',
    module       : '[data-ls-module="popover"]',
    placement    : 'top',
    trigger      : 'click.ls.popover',
    popoverClass : 'ls-popover',
    uniqueId     : 0
  }

  function init() {
    if(/sm|xs/.test(locastyle.breakpointClass)){
      $(config.module).attr('data-ls-module', 'modal').removeAttr('data-trigger');
      locastyle.modal.init();
    } else{
      $(config.module).each(function  (index, elem) {
        createPopover($(elem));
      });
    }
    updateBreakpoint();
  }

  function updateBreakpoint (argument) {
    $(window).on("breakpoint-updated", function () {
      destroy();
      init();
    });
  }

  function createPopover ($elem) {
    var elementData = $elem.data(),
        width  = $elem.outerWidth(),
        height = $elem.outerHeight();
    $elem.data('uniqueId', config.uniqueId);
    elementData.position  = elementData.container ? $elem.position() : $elem.offset() ;
    elementData.container = elementData.container || config.container;
    elementData.placement = elementData.placement || config.placement;
    switch (elementData.placement) {
      case 'top':
        elementData.position.top -=  12;
        elementData.position.left +=  (width/2 + 4);
        break;
      case 'right':
        elementData.position.top +=  (height/2 -2);
        elementData.position.left += (width + 12);
        break;
      case 'bottom':
        elementData.position.top += (height + 12);
        elementData.position.left +=  (width/2 + 4);
        break;
      case 'left':
        elementData.position.top +=  (height/2 -2 );
        elementData.position.left -= 12;
    }
    elementData.uniqueId = config.uniqueId++;
    $(elementData.container).append(locastyle.templates.popover(elementData));
    bindActions($elem, elementData);
  }

  function bindActions ($elem, elementData) {
    var trigger = elementData.trigger == 'hover' ? config.hoverEvent : config.trigger,
        $popover = $(config.idPopover + elementData.uniqueId);
    if(trigger === config.hoverEvent){
      $elem.on({
        mouseenter: function (event) {
          event.preventDefault();
          $popover.stop().show();
        },
        mouseleave: function (event) {
          event.preventDefault();
          $popover.stop().hide();
        }
      });
    } else {
      $elem.on({
        click: function (event) {
          event.preventDefault();
          event.stopPropagation();
          $popover.stop().toggle();
        }
      });
      $(document).on('click', function (event) {
        var element = event.toElement;
        if(!$(element).parents().hasClass( config.popoverClass )){
         $('.' + config.popoverClass).hide();
        }
      })
    }
  }

  function destroy() {
    $('.' + config.popoverClass).remove();
    $(config.module).each(function  (index, elem) {
      $(elem)
        .removeData('uniqueId')
        .off(config.hoverEvent)
        .off(config.trigger);
    });
  }

  return {
    init: init,
    destroyPopover: destroy
  }

}());<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var fileUtils = require('../util.js');
var path = require('path');

var UnitGenerator = module.exports = function UnitGenerator(args, options, config) {
  // By calling `NamedBase` here, we get the argument to the subgenerator call
  // as `this.name`.
  yeoman.generators.NamedBase.apply(this, arguments);
};

util.inherits(UnitGenerator, yeoman.generators.NamedBase);

UnitGenerator.prototype.info = function() {
  var cb = this.async();

  var prompts = [
    {
      type: 'list',
      name: 'testType',
      choices: [
        'protractor',
        'jasmine'
      ],
      message: 'What kind of test would you like to generate?',
      default: true
    }
  ];

  this.prompt(prompts, function(props) {
    this.testType = props.testType;
    cb();
  }.bind(this));

};

UnitGenerator.prototype.files = function files() {
  var templateName;
  switch (this.testType) {
    case 'protractor':
      templateName = 'protractorTemplate.js';
      break;
    case 'jasmine':
      break;
  }

  var testDir = 'spec';
  this.fileName = path.join(testDir, this.name + 'Spec.js')
  this.copy(templateName, this.fileName);
};

UnitGenerator.prototype.addTestToConfig = function() {
  var testString = '\'' + this.fileName + '\',';
  try {
    var fullPath = path.join('myConfig.js');
    fileUtils.rewriteFile({
      file: fullPath,
      needle: '// end-tests.',
      splicable: [
        testString
      ]
    });
  } catch (e) {
    console.log('\nUnable to find '.yellow + fullPath + '. Reference to '.yellow + testString + '.js ' + 'not added.\n'.yellow);
  }
};
<commit_msg>fix exception message<commit_after>'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var fileUtils = require('../util.js');
var path = require('path');

var UnitGenerator = module.exports = function UnitGenerator(args, options, config) {
  // By calling `NamedBase` here, we get the argument to the subgenerator call
  // as `this.name`.
  yeoman.generators.NamedBase.apply(this, arguments);
};

util.inherits(UnitGenerator, yeoman.generators.NamedBase);

UnitGenerator.prototype.info = function() {
  var cb = this.async();

  var prompts = [
    {
      type: 'list',
      name: 'testType',
      choices: [
        'protractor',
        'jasmine'
      ],
      message: 'What kind of test would you like to generate?',
      default: true
    }
  ];

  this.prompt(prompts, function(props) {
    this.testType = props.testType;
    cb();
  }.bind(this));

};

UnitGenerator.prototype.files = function files() {
  var templateName;
  switch (this.testType) {
    case 'protractor':
      templateName = 'protractorTemplate.js';
      break;
    case 'jasmine':
      break;
  }

  var testDir = 'spec';
  this.fileName = path.join(testDir, this.name + 'Spec.js')
  this.copy(templateName, this.fileName);
};

UnitGenerator.prototype.addTestToConfig = function() {
  var testString = '\'' + this.fileName + '\',';
  try {
    // Add the unit test to the protractor configuration file.
    var fullPath = path.join('myConfig.js');
    fileUtils.rewriteFile({
      file: fullPath,
      needle: '// end-tests.',
      splicable: [
        testString
      ]
    });
  } catch (e) {
    console.log('\nUnable to find ' + fullPath + '. Reference to ' + testString + ' not added.\n');
  }
};
<|endoftext|>


<commit_before>(function(){
	custom_Parsers['var'] = function(template, index, length, parent){
		var node = new Node('var', parent),
			start,
			c;

		node.stringify = stingify;
		var go_varName = 1,
			go_assign = 2,
			go_value = 3,
			go_next = 4,
			state = go_varName,
			token,
			key;
		while(true) {
			if (index < length && (c = template.charCodeAt(index)) < 33) {
				index++;
				continue;
			}

			if (state === go_varName) {
				start = index;
				index = cursor_refEnd(template, index, length);
				key = template.substring(start, index);
				state = go_assign;
				continue;
			}

			if (state === go_assign) {
				if (c !== 61 ) {
					// =
					parser_error(
						'Assignment expected'
						, template
						, index
						, c
						, 'var'
					);
					return [node, index];
				}
				state = go_value;
				index++;
				continue;
			}

			if (state === go_value) {
				start = index;
				index++;
				switch(c){
					case 123:
					case 91:
						// { [
						index = cursor_groupEnd(template, index, length, c, c + 2);
						break;
					case 39:
					case 34:
						// ' "
						index = cursor_quoteEnd(template, index, length, c === 39 ? "'" : '"')
						break;
					default:
						while (index < length) {
							c = template.charCodeAt(index);
							if (c === 44 || c === 59) {
								//, ;
								break;
							}
							index++;
						}
						index--;
						break;
				}
				index++;
				node.attr[key] = template.substring(start, index);
				state = go_next;
				continue;
			}
			if (state === go_next) {
				if (c === 44) {
					// ,
					state = go_varName;
					index++;
					continue;
				}
				break;
			}
		}
		return [node, index];
	};

	function stingify(){
		var attr = this.attr;
		var str = 'var ';
		for(var key in attr){
			if (str !== 'var ')
				str += ',';

			str += key + '=' + attr[key];
		}
		return str + ';';
	}
}());<commit_msg>rename: template -> str<commit_after>(function(){
	custom_Parsers['var'] = function(str, index, length, parent){
		var node = new Node('var', parent),
			start,
			c;

		node.stringify = stingify;
		var go_varName = 1,
			go_assign = 2,
			go_value = 3,
			go_next = 4,
			state = go_varName,
			token,
			key;
		while(true) {
			if (index < length && (c = str.charCodeAt(index)) < 33) {
				index++;
				continue;
			}

			if (state === go_varName) {
				start = index;
				index = cursor_refEnd(str, index, length);
				key = str.substring(start, index);
				state = go_assign;
				continue;
			}

			if (state === go_assign) {
				if (c !== 61 ) {
					// =
					parser_error(
						'Assignment expected'
						, str
						, index
						, c
						, 'var'
					);
					return [node, index];
				}
				state = go_value;
				index++;
				continue;
			}

			if (state === go_value) {
				start = index;
				index++;
				switch(c){
					case 123:
					case 91:
						// { [
						index = cursor_groupEnd(str, index, length, c, c + 2);
						break;
					case 39:
					case 34:
						// ' "
						index = cursor_quoteEnd(str, index, length, c === 39 ? "'" : '"')
						break;
					default:
						while (index < length) {
							c = str.charCodeAt(index);
							if (c === 44 || c === 59) {
								//, ;
								break;
							}
							index++;
						}
						index--;
						break;
				}
				index++;
				node.attr[key] = str.substring(start, index);
				state = go_next;
				continue;
			}
			if (state === go_next) {
				if (c === 44) {
					// ,
					state = go_varName;
					index++;
					continue;
				}
				break;
			}
		}
		return [node, index];
	};

	function stingify(){
		var attr = this.attr;
		var str = 'var ';
		for(var key in attr){
			if (str !== 'var ')
				str += ',';

			str += key + '=' + attr[key];
		}
		return str + ';';
	}
}());<|endoftext|>