<commit_before>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	/*$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});*/
	/*$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});*/
	/*$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});*/
	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').click(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		var next = $(this).next();
		next.addClass('on');
		if(!(next.find('.content').hasClass('jscrollpane'))){
			next.find('.content').addClass('jscrollpane').jScrollPane();
		}
	});
	if($('#content .container').hasClass('peticion')){
		$('.wrap_peticion.on .content').addClass('jscrollpane').jScrollPane();
	}

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	if($('.container').hasClass('perfil')){
		var cct = $('span.CCT').html();
		var escuelas = $.cookie('escuelas') && $.cookie('escuelas').split('-') || [];
		if(escuelas.indexOf(cct)==-1){
			escuelas.push(cct);
			escuelas.sort();
			$.cookie('escuelas',escuelas.join('-'));
			$('a[href="'+cct+'"]').parent().parent().addClass('on');
		}
		/*if(!($.cookie('escuelas')) || $.cookie('escuelas').split('-').indexOf(cct)==-1){
			$('a[href="'+cct+'"]').trigger('click');
			if(!$('a[href="'+cct+'"]').size()){
				toggle_escuela(cct);
			}
		}*/

	}

	if($('.container').hasClass('comparar')){
		$('#general-search').submit(function(e){
			e.preventDefault();
			var url='';
			$(this).find('[name]').each(function(i,val){
				url +='&'+$(val).attr('name')+'='+$(val).val();
			});
			window.location = $(this).attr('action')+url;
		});
	}

	if($('.container').hasClass('resultados')){
		$(window).unload(add_escuelas_cookie);
	}

	$('#compara-main-button').click(function(e){
		e.preventDefault();
		add_escuelas_cookie();
		$(window).off();
		location.href = '/compara/escuelas/' + $.cookie('escuelas');
	});

	$('#content .comparar.resultados table tr.on .compara-escuela').click(function(e){
		e.preventDefault();
		var cct = $(this).attr('href'),
		url=document.URL.replace(new RegExp('-*'+cct),''),
		escuelas = $.cookie('escuelas') && $.cookie('escuelas').split('-') || [];
		escuelas.splice(escuelas.indexOf(cct),1);
		$.cookie('escuelas',escuelas.join('-'));
		if(document.URL != url)
			location.href = url;

	});

	$('.perfil .sort').click(function(e){
		e.preventDefault();
		var comments = $('.comment').remove(),
		temp = $(this).attr('href');
		$('.perfil .sort.on').removeClass('on');
		$(this).addClass('on');
		if($(this).hasClass('recientes')){
			comments.sort(function(a,b){
				var t1 = new Date($(a).find('.timestamp').html()),
				t2 = new Date($(b).find('.timestamp').html());
				if(temp=='top')
					return t1>t2?-1:1;
				else
					return t1>t2?1:-1;
			})
		}else{
			comments.sort(function(a,b){
				var l1 = parseFloat($(a).find('.likes').html()),
				l2 = parseFloat($(b).find('.likes').html());
				if(temp=='top')
					return l1>l2?-1:1;
				else
					return l1>l2?1:-1;

			})
		}
		$(this).attr('href',$(this).attr('href')=='top'?'bottom':'top');
		$('[name="calificaciones"]').parent().append(comments);
	});

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			item.nombre = item.nombre[0].toLocaleUpperCase() + item.nombre.substr(1);
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
/*function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}*/
function toggle_escuela(cct){
	var escuelas = $.cookie('escuelas') && $.cookie('escuelas').split('-') || [],
	index;
	if((index = escuelas.indexOf(cct)) != -1){
		escuelas.splice(index,1);
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
	}
	//$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-') || '');
	/*
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		//escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			if(document.URL != url)
				location.href = url;
		}
	}
	*/
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}

function add_escuelas_cookie(){
	var selector_table = $('.resultados.container table'),
	on = selector_table.find('tr.on'),
	cookie = $.cookie('escuelas'),
	escuelas = cookie && cookie.split('-') || [];
	for(var i=0;i<on.length;i++){
		var val = $(on[i]),
		cct = val.find('.compara-escuela').attr('href');
		if(escuelas.indexOf(cct)==-1)
			escuelas.push(cct);
	}
	escuelas.sort();
	if(escuelas.length){
		$.cookie('escuelas',escuelas.join('-'));
	}
}
<commit_msg>test de agregar quitar a la cookie en califica<commit_after>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	/*$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});*/
	/*$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});*/
	/*$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});*/
	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').click(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		var next = $(this).next();
		next.addClass('on');
		if(!(next.find('.content').hasClass('jscrollpane'))){
			next.find('.content').addClass('jscrollpane').jScrollPane();
		}
	});
	if($('#content .container').hasClass('peticion')){
		$('.wrap_peticion.on .content').addClass('jscrollpane').jScrollPane();
	}

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	if($('.container').hasClass('perfil')){
		var cct = $('span.CCT').html();
		var escuelas = $.cookie('escuelas') && $.cookie('escuelas').split('-') || [];
		if(escuelas.indexOf(cct)==-1){
			escuelas.push(cct);
			escuelas.sort();
			$.cookie('escuelas',escuelas.join('-'));
			$('a[href="'+cct+'"]').parent().parent().addClass('on');
		}
		/*if(!($.cookie('escuelas')) || $.cookie('escuelas').split('-').indexOf(cct)==-1){
			$('a[href="'+cct+'"]').trigger('click');
			if(!$('a[href="'+cct+'"]').size()){
				toggle_escuela(cct);
			}
		}*/

	}

	if($('.container').hasClass('comparar')){
		$('#general-search').submit(function(e){
			e.preventDefault();
			var url='';
			$(this).find('[name]').each(function(i,val){
				url +='&'+$(val).attr('name')+'='+$(val).val();
			});
			window.location = $(this).attr('action')+url;
		});
	}

	if($('.container').hasClass('resultados') || $('.container').hasClass('califica_select')){
		$(window).unload(add_escuelas_cookie);
	}

	$('#compara-main-button').click(function(e){
		e.preventDefault();
		add_escuelas_cookie();
		$(window).off();
		location.href = '/compara/escuelas/' + $.cookie('escuelas');
	});

	$('#content .comparar.resultados table tr.on .compara-escuela').click(function(e){
		e.preventDefault();
		var cct = $(this).attr('href'),
		url=document.URL.replace(new RegExp('-*'+cct),''),
		escuelas = $.cookie('escuelas') && $.cookie('escuelas').split('-') || [];
		escuelas.splice(escuelas.indexOf(cct),1);
		$.cookie('escuelas',escuelas.join('-'));
		if(document.URL != url)
			location.href = url;

	});

	$('.perfil .sort').click(function(e){
		e.preventDefault();
		var comments = $('.comment').remove(),
		temp = $(this).attr('href');
		$('.perfil .sort.on').removeClass('on');
		$(this).addClass('on');
		if($(this).hasClass('recientes')){
			comments.sort(function(a,b){
				var t1 = new Date($(a).find('.timestamp').html()),
				t2 = new Date($(b).find('.timestamp').html());
				if(temp=='top')
					return t1>t2?-1:1;
				else
					return t1>t2?1:-1;
			})
		}else{
			comments.sort(function(a,b){
				var l1 = parseFloat($(a).find('.likes').html()),
				l2 = parseFloat($(b).find('.likes').html());
				if(temp=='top')
					return l1>l2?-1:1;
				else
					return l1>l2?1:-1;

			})
		}
		$(this).attr('href',$(this).attr('href')=='top'?'bottom':'top');
		$('[name="calificaciones"]').parent().append(comments);
	});

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			item.nombre = item.nombre[0].toLocaleUpperCase() + item.nombre.substr(1);
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
/*function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}*/
function toggle_escuela(cct){
	var escuelas = $.cookie('escuelas') && $.cookie('escuelas').split('-') || [],
	index;
	if((index = escuelas.indexOf(cct)) != -1){
		escuelas.splice(index,1);
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
	}
	//$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-') || '');
	/*
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		//escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			if(document.URL != url)
				location.href = url;
		}
	}
	*/
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}

function add_escuelas_cookie(){
	//var selector_table = $('.resultados.container table'),
	var selector_table = $('.resultados table'),
	on = selector_table.find('tr.on'),
	cookie = $.cookie('escuelas'),
	escuelas = cookie && cookie.split('-') || [];
	for(var i=0;i<on.length;i++){
		var val = $(on[i]),
		cct = val.find('.compara-escuela').attr('href');
		if(escuelas.indexOf(cct)==-1)
			escuelas.push(cct);
	}
	escuelas.sort();
	if(escuelas.length){
		$.cookie('escuelas',escuelas.join('-'));
	}
}
<|endoftext|>


<commit_before>/*
 * app/src/Buttons.js
 *
 *
 * Copyright (C) 2015  Pierre Marchand <pierremarc07@gmail.com>
 *
 * License in LICENSE file at the root of the repository.
 *
 */

 var featureButtons = {
     'set name': ['get name | edit | set name'],
     'set image': ['media pick | set params.image'],
     'set color': ['get color | edit | set style.strokeStyle'],
     'set text': ['get text | edit | set params.text'],
     'go to feature' : ['gg | region set']
 };

var layerButtons = {
    'add text': [
        'draw | close | create | cc',
        'edit | set text'
    ],
    'add line': ['draw | create'],
    'add zone': ['draw | close | create'],
    'add image': [
        'draw | close | create | cc',
        'media pick | set params.image'
    ],
    'import data': ['import'],
    'list features': ['lf']
};

var groupButtons = {
    'add layer': ['ic'],
    'list layers' : ['ll'],
    'set map extent': ['region get | set extent']
};

var userButtons = {
    'add map': ['ic'],
    'list maps': ['lg'],
    'upload media': ['media upload'],
    'browse medias': ['media list'],
    'logout' : ['logout']

};

var shellButtons = {
    'help' : ['help'],
    'login' : ['login'],
    'register' : ['register'],
    'get context infos': ['get']
};

module.exports = exports = {
    'feature': featureButtons,
    'layer': layerButtons,
    'group': groupButtons,
    'user' : userButtons,
    'shell' : shellButtons,
};
<commit_msg>debug add text done<commit_after>/*
 * app/src/Buttons.js
 *
 *
 * Copyright (C) 2015  Pierre Marchand <pierremarc07@gmail.com>
 *
 * License in LICENSE file at the root of the repository.
 *
 */

 var featureButtons = {
     'set name': ['get name | edit | set name'],
     'set image': ['media pick | set params.image'],
     'set color': ['get color | edit | set style.strokeStyle'],
     'set text': ['get text | edit | set params.text'],
     'go to feature' : ['gg | region set']
 };

var layerButtons = {
    'add text': [
        'draw | close | create | cc',
        'edit | set params.text'
    ],
    'add line': ['draw | create'],
    'add zone': ['draw | close | create'],
    'add image': [
        'draw | close | create | cc',
        'media pick | set params.image'
    ],
    'import data': ['import'],
    'list features': ['lf']
};

var groupButtons = {
    'add layer': ['ic'],
    'list layers' : ['ll'],
    'set map extent': ['region get | set extent']
};

var userButtons = {
    'add map': ['ic'],
    'list maps': ['lg'],
    'upload media': ['media upload'],
    'browse medias': ['media list'],
    'logout' : ['logout']

};

var shellButtons = {
    'help' : ['help'],
    'login' : ['login'],
    'register' : ['register'],
    'get context infos': ['get']
};

module.exports = exports = {
    'feature': featureButtons,
    'layer': layerButtons,
    'group': groupButtons,
    'user' : userButtons,
    'shell' : shellButtons,
};
<|endoftext|>


<commit_before>/*
 * slush-joomla
 * https://github.com/welksonramos/slush-joomla
 *
 * Copyright (c) 2015-2017, Welkson Ramos
 * Licensed under the MIT license.
 */

 'use strict';
 var gulp = require('gulp'),
 install = require('gulp-install'),
 conflict = require('gulp-conflict'),
 template = require('gulp-template'),
 inquirer = require('inquirer');

 function format(string) {
 	var username = string ? string.toLowerCase() : '';
 	return username.replace(/\s/g, '');
 }

var defaults = (function () {
var homeDir = process.env.Home || process.env.HOMEPATH || process.env.USERPROFILE,
		workingDirName = process.cwd().split('/').pop().split('\\').pop(),
		osUserName = homeDir && homeDir.split('/').pop() || 'root',
		configFile = homeDir + '/.gitconfig',
		user = {};
		if (require('fs').existsSync(configFile)) {
			user = require('iniparser').parseSync(configFile).user;
}
return {
	templateName: workingDirName,
	username: format(user.name) || osUserName,
	authorEmail: user.email || ''
};
})();

 gulp.task('default', function (done) {

 	var prompts = [
 	{ type:'input', name: 'projectName', message: 'Project name', default: defaults.templateName },
 	{ type:'input', name:'projectDescription', message:'Description' },
 	{	type:'input',	name:'projectVersion', message:'Version', default:'1.0.0' },
 	{	type:'input',	name:'creationDate', message:'Creation Date' },
 	{	type:'input', name:'authorName', message:'Author Name', default: defaults.username },
 	{	type:'input',	name:'authorEmail', message:'Author E-mail', default: defaults.authorEmail },
 	{	type:'confirm', name:'moveon', message:'Continue?' }
 	];

 	inquirer.prompt(prompts, function (answers) {
 		if (!answers.moveon) {
 			return done();
 		}

 		gulp.src(__dirname + '/templates/**')
 		.pipe(template(answers))
 		.pipe(conflict('./'))
 		.pipe(gulp.dest('./'))
 		.pipe(install())
 		.on('finish', function () {
 			done();
 		})
 		.resume();
 	});
 });
<commit_msg>refator<commit_after>/*
 * slush-joomla
 * https://github.com/welksonramos/slush-joomla
 *
 * Copyright (c) 2015-present, Welkson Ramos
 * Licensed under the MIT license.
 */

'use strict';

const gulp = require('gulp');
const install = require('gulp-install');
const conflict = require('gulp-conflict');
const template = require('gulp-template');
const inquirer = require('inquirer');

const format = (string) => {
	let username = string ? string.toLowerCase() : '';
	return username.replace(/\s/g, '');
}

const defaults = (() => {
	let homeDir = process.env.Home || process.env.HOMEPATH || process.env.USERPROFILE;
	let workingDirName = process.cwd().split('/').pop().split('\\').pop();
	let osUserName = homeDir && homeDir.split('/').pop() || 'root';
	let configFile = homeDir + '/.gitconfig';
	let user = {};

	if (require('fs').existsSync(configFile)) {
		user = require('iniparser').parseSync(configFile).user;
	}
	return {
		templateName: workingDirName,
		username: format(user.name) || osUserName,
		authorEmail: user.email || ''
	};
})();

gulp.task('default', function (done) {

	let prompts = [
		{ type: 'input', name: 'projectName', message: 'Project name', default: defaults.templateName },
		{ type: 'input', name: 'projectDescription', message: 'Description' },
		{ type: 'input', name: 'projectVersion', message: 'Version', default: '1.0.0' },
		{ type: 'input', name: 'creationDate', message: 'Creation Date' },
		{ type: 'input', name: 'authorName', message: 'Author Name', default: defaults.username },
		{ type: 'input', name: 'authorEmail', message: 'Author E-mail', default: defaults.authorEmail },
		{ type: 'confirm', name: 'moveon', message: 'Continue?' }
	];

	inquirer.prompt(prompts).then(answers => {
		if (!answers.moveon) {
			return done();
		}

		gulp.src(__dirname + '/templates/**')
			.pipe(template(answers))
			.pipe(conflict('./'))
			.pipe(gulp.dest('./'))
			.pipe(install())
			.on('finish', function () {
				done();
			})
			.resume();
	});
});
<|endoftext|>


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

/**
 * @fileoverview Functions for the edit page
 */

function make_visible(id) {
  document.getElementById(id).style.visibility = "visible";
}

(function() {
  var button_click = '';

  /**
   * Shorthand for document.getElementById.
   * @param {string} id - ID of an element in the dom
   * @return {Element|null} - the first element in the dom with that id, or null
   */
  function $(id) {
    return document.getElementById(id);
  }

  /**
   * Sets the error state of an attribute with the given name by toggling the
   * css class an error border with id <name>_errorbox and an error message with
   * id <name>_errormsg.
   * @param {string} name - the name of the attribute
   * @param {boolean} valid - true to display the error state, false to clear it
   * @param {string} error - the error message to display if valid is false
   */
  function set_error(name, valid, error) {
    $(name + '_errorbox').className =
        valid ? 'errorbox-good' : 'errorbox-bad';
    var errormsg = $(name + '_errormsg');
    errormsg.innerHTML = valid ? '' : to_html(error);
    errormsg.className = valid ? 'hidden' : 'errormsg';
  }

  /**
   * Validates the name and affiliation fields, present the first time a user
   * makes an edit. If the fields are not present, returns true.
   */
  function validate_name_affil() {
    var nickname = $('account_nickname');
    if (!nickname) {
      return true;
    }
    var valid = validate_required_string(nickname);
    // careful to avoid short-circuiting here
    return validate_required_string($('account_affiliation')) && valid;
  }

  /**
   * Validates a string that is required, meaning that empty or whitespace
   * is considered an error.
   * @param input {Element} input - the input element to validate
   * @param opt_error {string|null} opt_error - optional error message. If
   * missing, a generic "Field is required" message is used.
   */
  function validate_required_string(input, opt_error) {
    var value = input.value ? jQuery.trim(input.value) : null;
    set_error(input.name, value, locale.ERROR_FIELD_IS_REQUIRED());
    return value ? true : false;
  }

  /**
   * Returns true if the given string is a valid number. Currently supports only
   * one number format; '-1234.5' is valid, but '1,234.5' and '3,50' are not.
   * @param {string} value - a string representing a number
   * @return {boolean} - true if the value is valid
   */
  function is_valid_number(value) {
    return jQuery.trim(value).match('^[0-9-\.]+$') ? true : false;
  }

  /**
   * Validates a numeric input field.
   * @param {Element} input - input field to validate
   * @return {boolean} - true if the value of the input is valid. If false, has
   * a side effect of displaying a "Value must be a number" error message
   */
  function validate_number(input) {
    var valid = true;
    if (input.value) {
      valid = is_valid_number(input.value);
    }
    set_error(input.name, valid, locale.ERROR_VALUE_MUST_BE_NUMBER());
    return valid;
  }

 /**
  * Validates fields representing (latitude, longitude) coordinates.
  * @param {Array.<Element>} inputs - an array of 2 elements, one with name
  * <name>.lat and the other with name <name>.lon
  * @return {boolean} - true if the pair is a valid pair of coordinates, meaning
  * both values are numbers in the valid ranges, otherwise false
  */
  function validate_geopt(inputs) {
    var valid = true;
    var name = '';
    var error = [];
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      var name_coord = input.name.split('.');
      name = name_coord[0];
      var coord = name_coord[1];
      var input_valid = is_valid_number(input.value);
      if (input_valid) {
        var value = parseFloat(jQuery.trim(input.value));
        if (coord == 'lat' && value < -90 || value > 90) {
          input_valid = false;
          error.push(locale.ERROR_LATITUDE_INVALID());
        } else if (coord == 'lon' && value < -180 || value > 180) {
          input_valid = false;
          error.push(to_html(locale.ERROR_LONGITUDE_INVALID()));
        }
      } else {
        error.push(to_html(
                     coord == 'lat' ? locale.ERROR_LATITUDE_MUST_BE_NUMBER()
                       : locale.ERROR_LONGITUDE_MUST_BE_NUMBER()));
      }
      valid = valid && input_valid;
    }

    set_error(name, valid, HTML(error.join('
')));
    return valid;
  }

  /**
   * If the save button is clicked, validate relevant inputs on the page,
   * and display error messages if fields are invalid.
   * input elements are discovered by checking for marker class names on
   * parent 'tr' elements.
   * @return {boolean} - true if the "save" button was not pressed or all
   * inputs are valid, otherwise false
   */
  function validate() {
    if (button_click !== 'save') {
      return true;
    }

    var valid_arr = [validate_name_affil()];

    var trs = document.getElementsByTagName('tr');
    for (var i = 0; i < trs.length; i++) {
      var tr = trs[i];
      var classes = tr.className.split(' ');
      if (jQuery.inArray('int', classes) != -1
          || jQuery.inArray('float', classes) != -1) {
        valid_arr.push(validate_number(tr.getElementsByTagName('input')[0]));
      } else if (jQuery.inArray('geopt', classes) != -1) {
        var inputs = tr.getElementsByTagName('input');
        valid_arr.push(validate_geopt([inputs[0], inputs[1]]));
      }
    }

    return jQuery.inArray(false, valid_arr) == -1;
  }

  /**
   * Initializes comment visibility and installs onclick handlers to make
   * comments visible if their values are updated.
   */
  function init_comment_visibility() {
    var trs = document.getElementsByTagName('tr');
    for (var i = 0; i < trs.length; i++) {
      var tr = trs[i];
      var classes = tr.className.split(' ');
      if (classes.length > 1) {
        var divs = tr.getElementsByTagName('div');
        var attribute_name = "";
        for (var div_index = 0; div_index < inputs.length; div_index++) {
          var div = divs[div_index];
          if (div.className == "comment") {
            tr.onclick = new Function(
              'make_visible("' + div.id + '");');
            var inputs = input.getElementsByTagName('input');
            if (inputs.length > 0) {
              var input = divs[0];
              if (input.value == '') {
                input.style.visibility = "hidden";
              } else {
                input.style.visibility = "visible";
              }
            }
          }
        }
      }
    }
  }

  /**
   * Handler for a click of the save button.
   */
  function save() {
    button_click = 'save';
  }

  /**
   * Handler for a click of the cancel button.
   */
  function cancel() {
    button_click = 'cancel';
  }

  /**
   * Initializes event handlers for the page.
   */
  function init() {
    $('edit').onsubmit = validate;
    $('save').onclick = save;
    $('cancel').onclick = cancel;
    init_comment_visibility();
  }

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

/**
 * @fileoverview Functions for the edit page
 */

function make_visible(id) {
  document.getElementById(id).style.visibility = "visible";
}

(function() {
  var button_click = '';

  /**
   * Shorthand for document.getElementById.
   * @param {string} id - ID of an element in the dom
   * @return {Element|null} - the first element in the dom with that id, or null
   */
  function $(id) {
    return document.getElementById(id);
  }

  /**
   * Sets the error state of an attribute with the given name by toggling the
   * css class an error border with id <name>_errorbox and an error message with
   * id <name>_errormsg.
   * @param {string} name - the name of the attribute
   * @param {boolean} valid - true to display the error state, false to clear it
   * @param {string} error - the error message to display if valid is false
   */
  function set_error(name, valid, error) {
    $(name + '_errorbox').className =
        valid ? 'errorbox-good' : 'errorbox-bad';
    var errormsg = $(name + '_errormsg');
    errormsg.innerHTML = valid ? '' : to_html(error);
    errormsg.className = valid ? 'hidden' : 'errormsg';
  }

  /**
   * Validates the name and affiliation fields, present the first time a user
   * makes an edit. If the fields are not present, returns true.
   */
  function validate_name_affil() {
    var nickname = $('account_nickname');
    if (!nickname) {
      return true;
    }
    var valid = validate_required_string(nickname);
    // careful to avoid short-circuiting here
    return validate_required_string($('account_affiliation')) && valid;
  }

  /**
   * Validates a string that is required, meaning that empty or whitespace
   * is considered an error.
   * @param input {Element} input - the input element to validate
   * @param opt_error {string|null} opt_error - optional error message. If
   * missing, a generic "Field is required" message is used.
   */
  function validate_required_string(input, opt_error) {
    var value = input.value ? jQuery.trim(input.value) : null;
    set_error(input.name, value, locale.ERROR_FIELD_IS_REQUIRED());
    return value ? true : false;
  }

  /**
   * Returns true if the given string is a valid number. Currently supports only
   * one number format; '-1234.5' is valid, but '1,234.5' and '3,50' are not.
   * @param {string} value - a string representing a number
   * @return {boolean} - true if the value is valid
   */
  function is_valid_number(value) {
    return jQuery.trim(value).match('^[0-9-\.]+$') ? true : false;
  }

  /**
   * Validates a numeric input field.
   * @param {Element} input - input field to validate
   * @return {boolean} - true if the value of the input is valid. If false, has
   * a side effect of displaying a "Value must be a number" error message
   */
  function validate_number(input) {
    var valid = true;
    if (input.value) {
      valid = is_valid_number(input.value);
    }
    set_error(input.name, valid, locale.ERROR_VALUE_MUST_BE_NUMBER());
    return valid;
  }

 /**
  * Validates fields representing (latitude, longitude) coordinates.
  * @param {Array.<Element>} inputs - an array of 2 elements, one with name
  * <name>.lat and the other with name <name>.lon
  * @return {boolean} - true if the pair is a valid pair of coordinates, meaning
  * both values are numbers in the valid ranges, otherwise false
  */
  function validate_geopt(inputs) {
    var valid = true;
    var name = '';
    var error = [];
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      var name_coord = input.name.split('.');
      name = name_coord[0];
      var coord = name_coord[1];
      var input_valid = is_valid_number(input.value);
      if (input_valid) {
        var value = parseFloat(jQuery.trim(input.value));
        if (coord == 'lat' && value < -90 || value > 90) {
          input_valid = false;
          error.push(locale.ERROR_LATITUDE_INVALID());
        } else if (coord == 'lon' && value < -180 || value > 180) {
          input_valid = false;
          error.push(to_html(locale.ERROR_LONGITUDE_INVALID()));
        }
      } else {
        error.push(to_html(
                     coord == 'lat' ? locale.ERROR_LATITUDE_MUST_BE_NUMBER()
                       : locale.ERROR_LONGITUDE_MUST_BE_NUMBER()));
      }
      valid = valid && input_valid;
    }

    set_error(name, valid, HTML(error.join('
')));
    return valid;
  }

  /**
   * If the save button is clicked, validate relevant inputs on the page,
   * and display error messages if fields are invalid.
   * Input elements are discovered by checking for marker class names on
   * parent 'tr' elements.
   * @return {boolean} - true if the "save" button was not pressed or all
   * inputs are valid, otherwise false
   */
  function validate() {
    if (button_click !== 'save') {
      return true;
    }

    var valid_arr = [validate_name_affil()];

    var trs = document.getElementsByTagName('tr');
    for (var i = 0; i < trs.length; i++) {
      var tr = trs[i];
      var classes = tr.className.split(' ');
      if (jQuery.inArray('int', classes) != -1
          || jQuery.inArray('float', classes) != -1) {
        valid_arr.push(validate_number(tr.getElementsByTagName('input')[0]));
      } else if (jQuery.inArray('geopt', classes) != -1) {
        var inputs = tr.getElementsByTagName('input');
        valid_arr.push(validate_geopt([inputs[0], inputs[1]]));
      }
    }

    return jQuery.inArray(false, valid_arr) == -1;
  }

  /**
   * Initializes comment visibility and installs onclick handlers to make
   * comments visible if their values are updated.
   */
  function init_comment_visibility() {
    var trs = document.getElementsByTagName('tr');
    for (var i = 0; i < trs.length; i++) {
      var tr = trs[i];
      var classes = tr.className.split(' ');
      if (classes.length > 1) {
        var divs = tr.getElementsByTagName('div');
        var attribute_name = "";
        for (var div_index = 0; div_index < inputs.length; div_index++) {
          var div = divs[div_index];
          if (div.className == "comment") {
            tr.onclick = new Function(
              'make_visible("' + div.id + '");');
            var inputs = input.getElementsByTagName('input');
            if (inputs.length > 0) {
              var input = divs[0];
              if (input.value == '') {
                input.style.visibility = "hidden";
              } else {
                input.style.visibility = "visible";
              }
            }
          }
        }
      }
    }
  }

  /**
   * Handler for a click of the save button.
   */
  function save() {
    button_click = 'save';
  }

  /**
   * Handler for a click of the cancel button.
   */
  function cancel() {
    button_click = 'cancel';
  }

  /**
   * Initializes event handlers for the page.
   */
  function init() {
    $('edit').onsubmit = validate;
    $('save').onclick = save;
    $('cancel').onclick = cancel;
    init_comment_visibility();
  }

  init();
})();
<|endoftext|>


<commit_before>import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';

import { loginUser, registerUser, getRooms, getOneRoom, setOneRoom, getLightStates, setOneLightState } from './api';

export function* loginSaga({ data }) {
    try {
        const { token } = yield call(loginUser, data);
        yield put({ type: 'LOGIN_SUCCESSFUL', data: token });
    }
    catch (e) {
        yield put({ type: 'LOGIN_FAILED', data: e.message });
    }
}

export function* registerSaga({ data }) {
    try {
        yield call(registerUser, data);
        yield put({ type: 'REGISTRATION_SUCCESSFUL', data: 'Registration successful' });
    }
    catch (e) {
        yield put({ type: 'REGISTRATION_FAILED', data: e.message });
    }
}

export function* getRoomsSaga({ data }) {
    try {
        const rooms = yield call(getRooms, data);
        yield put({ type: 'GET_ROOMS_SUCCESSFUL', data: rooms });
    }
    catch (e) {
        yield put({ type: 'GET_ROOMS_FAILED', data: e.message });
    }
}

export function* getOneRoomSaga({ data }) {
    try {
        const room = yield call(getOneRoom, ...data);
        yield put({ type: 'GET_ONE_ROOM_SUCCESSFUL', data: room });
    }
    catch (e) {
        yield put({ type: 'GET_ONE_ROOM_FAILED', data: e.message });
    }
}

export function* setOneRoomSaga({ data }) {
    try {
        const room = yield call(setOneRoom, ...data);
        yield put({ type: 'SET_ONE_ROOM_SUCCESSFUL', data: room });
        const lightStates = yield call(getLightStates, data[0], ...room.lightIds);
        yield put({ type: 'GET_LIGHTS_SUCCESSFUL', data: lightStates });
    }
    catch (e) {
        yield put({ type: 'SET_ONE_ROOM_FAILED', data: e.message });
    }
}

export function* getLights({ data }) {
    try {
        const lightState = yield call(getLightStates, ...data);
        yield put({ type: 'GET_LIGHTS_SUCCESSFUL', data: lightState });
    }
    catch (e) {
        yield put({ type: 'GET_LIGHTS_FAILED', data: e.message });
    }
}

export function* setLightState({ data }) {
    try {
        const lightState = yield call(setOneLightState, ...data);
        yield put({ type: 'SET_LIGHT_SUCCESSFUL', data: lightState });
    }
    catch (e) {
        yield put({ type: 'SET_LIGHT_FAILED', data: e.message });
    }
}

export default function* rootSaga() {
    yield [
        takeLatest('LOGIN_REQUESTED', loginSaga),
        takeLatest('REGISTRATION_REQUESTED', registerSaga),
        takeEvery('GET_ROOMS_REQUESTED', getRoomsSaga),
        takeEvery('GET_ONE_ROOM_REQUESTED', getOneRoomSaga),
        takeEvery('SET_ONE_ROOM_REQUESTED', setOneRoomSaga),
        takeEvery('GET_LIGHTS_REQUESTED', getLights),
        takeEvery('SET_LIGHT_REQUESTED', setLightState)
    ];
}
<commit_msg>added a delete user saga<commit_after>import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';

import {
    loginUser,
    registerUser,
    deleteAccount,
    getRooms,
    getOneRoom,
    setOneRoom,
    getLightStates,
    setOneLightState
} from './api';

export function* loginSaga({ data }) {
    try {
        const { token } = yield call(loginUser, data);
        yield put({ type: 'LOGIN_SUCCESSFUL', data: token });
    }
    catch (e) {
        yield put({ type: 'LOGIN_FAILED', data: e.message });
    }
}

export function* registerSaga({ data }) {
    try {
        yield call(registerUser, data);
        yield put({ type: 'REGISTRATION_SUCCESSFUL', data: 'Registration successful' });
    }
    catch (e) {
        yield put({ type: 'REGISTRATION_FAILED', data: e.message });
    }
}

export function* deleteSaga({ data }) {
    try {
        yield call(deleteAccount, data);
        yield put({ type: 'DELETE_ACCOUNT_SUCCESSFUL' });
    }
    catch (e) {
        yield put({ type: 'DELETE_ACCOUNT_FAILED', data: e.message });
    }
}

export function* getRoomsSaga({ data }) {
    try {
        const rooms = yield call(getRooms, data);
        yield put({ type: 'GET_ROOMS_SUCCESSFUL', data: rooms });
    }
    catch (e) {
        yield put({ type: 'GET_ROOMS_FAILED', data: e.message });
    }
}

export function* getOneRoomSaga({ data }) {
    try {
        const room = yield call(getOneRoom, ...data);
        yield put({ type: 'GET_ONE_ROOM_SUCCESSFUL', data: room });
    }
    catch (e) {
        yield put({ type: 'GET_ONE_ROOM_FAILED', data: e.message });
    }
}

export function* setOneRoomSaga({ data }) {
    try {
        const room = yield call(setOneRoom, ...data);
        yield put({ type: 'SET_ONE_ROOM_SUCCESSFUL', data: room });
        const lightStates = yield call(getLightStates, data[0], ...room.lightIds);
        yield put({ type: 'GET_LIGHTS_SUCCESSFUL', data: lightStates });
    }
    catch (e) {
        yield put({ type: 'SET_ONE_ROOM_FAILED', data: e.message });
    }
}

export function* getLights({ data }) {
    try {
        const lightState = yield call(getLightStates, ...data);
        yield put({ type: 'GET_LIGHTS_SUCCESSFUL', data: lightState });
    }
    catch (e) {
        yield put({ type: 'GET_LIGHTS_FAILED', data: e.message });
    }
}

export function* setLightState({ data }) {
    try {
        const lightState = yield call(setOneLightState, ...data);
        yield put({ type: 'SET_LIGHT_SUCCESSFUL', data: lightState });
    }
    catch (e) {
        yield put({ type: 'SET_LIGHT_FAILED', data: e.message });
    }
}

export default function* rootSaga() {
    yield [
        takeLatest('LOGIN_REQUESTED', loginSaga),
        takeLatest('REGISTRATION_REQUESTED', registerSaga),
        takeLatest('DELETE_ACCOUNT_REQUESTED', deleteSaga),
        takeEvery('GET_ROOMS_REQUESTED', getRoomsSaga),
        takeEvery('GET_ONE_ROOM_REQUESTED', getOneRoomSaga),
        takeEvery('SET_ONE_ROOM_REQUESTED', setOneRoomSaga),
        takeEvery('GET_LIGHTS_REQUESTED', getLights),
        takeEvery('SET_LIGHT_REQUESTED', setLightState)
    ];
}
<|endoftext|>


<commit_before>/* eslint-disable */
import fs from 'fs';
import _ from 'underscore';
import { readFileMap, storeFileMap } from './file';
import getSize from 'get-folder-size';
import {
  fileMapPath,
  activityPatternPath,
  statePath,
  storageDirPath,
  powerStorageSlider,
  maxStorageSlider
} from './ENV_variables';

// to be CHANGED don't real all fileMapEntries
function readFilesInfo() {
  const fileMap = JSON.parse(fs.readFileSync(fileMapPath));
  const filesInfo = [];
  for(var key in fileMap) {
    if(fileMap.hasOwnProperty(key) && key!='rnd' && key!='stmp' && key!='userID') {
        filesInfo.push({
          id: key,
          shreds: fileMap[key].shreds,
          name: fileMap[key].name,
          status: 1,
          uploadTime: fileMap[key].uploadTime,
          size: fileMap[key].size/1024, // to be CHANGED add size to fileMapEntry in file.js
        });
    }
  }
  return filesInfo;
}

function loadActivityPattern(type) { // asynchronouslly loads the Activity Pattern
  const hourlyPatterns = [];
  const averagePatterns = [];
  const hourlyLabels = [];
  const activityPatternObject = JSON.parse(fs.readFileSync(activityPatternPath));
  const patterns =
        (activityPatternObject.hasOwnProperty("Pattern"))
        ?
        activityPatternObject["Pattern"]
        :
        [];
  let sum = 0;
  for (var i=0; i<patterns.length; i++){
    sum +=parseInt(patterns[i]);
    if(i%6==0){
      hourlyPatterns.push(sum);
      sum = 0;
    }
  }
  if (type=='data'){
    return hourlyPatterns;
  } else if (type=='labels'){
    for (var i=0; i<hourlyPatterns.length; i++){
      hourlyLabels.push('');
    }
    return hourlyLabels;
  } else if (type=='average'){
    for (var i=0; i<hourlyPatterns.length; i++){
      averagePatterns.push(3);
    }
    return averagePatterns;
  }
}

function getStorageSpace(){
  const state = JSON.parse(fs.readFileSync(statePath));
  if(state.hasOwnProperty('storage')) {
    return state.storage;
  } else {
    console.error('Error reading storage field in ' + statePath);
  }
}

function getUsedSpace(){
  let usedSpace = 0;
  fs.readdirSync(storageDirPath).map((fileName)=>{
    if(fs.statSync(storageDirPath+'/'+fileName)){
      usedSpace+=fs.statSync(storageDirPath+'/'+fileName).size;
    }
  })
  return usedSpace/1024/1024;
}

function getStorageInfo(){

  const empty = getStorageSpace() - getUsedSpace();
  const used = getUsedSpace();

  return [empty,used]
}

function transform(value) {
  return Math.round((Math.exp(powerStorageSlider * value / maxStorageSlider) - 1) / (Math.exp(powerStorageSlider) - 1) * maxStorageSlider);
}

function reverse(value) {
  return (1 / powerStorageSlider) * Math.log(((Math.exp(powerStorageSlider) - 1) * value / maxStorageSlider) + 1) * maxStorageSlider;
}

function editStorage(newStorage){
  const state = JSON.parse(fs.readFileSync(statePath));
  state.storage = newStorage;
  fs.writeFileSync(statePath, JSON.stringify(state));
}

export {
  editStorage,
  reverse,
  transform,
  getStorageInfo,
  getUsedSpace,
  getStorageSpace,
  loadActivityPattern,
  readFilesInfo,
};
<commit_msg>do not read rnd, stmp, and userID as files in state.js 2<commit_after>/* eslint-disable */
import fs from 'fs';
import _ from 'underscore';
import { readFileMap, storeFileMap } from './file';
import getSize from 'get-folder-size';
import {
  fileMapPath,
  activityPatternPath,
  statePath,
  storageDirPath,
  powerStorageSlider,
  maxStorageSlider
} from './ENV_variables';

function readFilesInfo() {
  const fileMap = JSON.parse(fs.readFileSync(fileMapPath));
  const filesInfo = [];
  for(var key in fileMap) {
    if(fileMap.hasOwnProperty(key) && key!='rnd' && key!='stmp' && key!='userID') {
        filesInfo.push({
          id: key,
          shreds: fileMap[key].shreds,
          name: fileMap[key].name,
          status: 1,
          uploadTime: fileMap[key].uploadTime,
          size: fileMap[key].size/1024, // to be CHANGED add size to fileMapEntry in file.js
        });
    }
  }
  return filesInfo;
}

function loadActivityPattern(type) { // asynchronouslly loads the Activity Pattern
  const hourlyPatterns = [];
  const averagePatterns = [];
  const hourlyLabels = [];
  const activityPatternObject = JSON.parse(fs.readFileSync(activityPatternPath));
  const patterns =
        (activityPatternObject.hasOwnProperty("Pattern"))
        ?
        activityPatternObject["Pattern"]
        :
        [];
  let sum = 0;
  for (var i=0; i<patterns.length; i++){
    sum +=parseInt(patterns[i]);
    if(i%6==0){
      hourlyPatterns.push(sum);
      sum = 0;
    }
  }
  if (type=='data'){
    return hourlyPatterns;
  } else if (type=='labels'){
    for (var i=0; i<hourlyPatterns.length; i++){
      hourlyLabels.push('');
    }
    return hourlyLabels;
  } else if (type=='average'){
    for (var i=0; i<hourlyPatterns.length; i++){
      averagePatterns.push(3);
    }
    return averagePatterns;
  }
}

function getStorageSpace(){
  const state = JSON.parse(fs.readFileSync(statePath));
  if(state.hasOwnProperty('storage')) {
    return state.storage;
  } else {
    console.error('Error reading storage field in ' + statePath);
  }
}

function getUsedSpace(){
  let usedSpace = 0;
  fs.readdirSync(storageDirPath).map((fileName)=>{
    if(fs.statSync(storageDirPath+'/'+fileName)){
      usedSpace+=fs.statSync(storageDirPath+'/'+fileName).size;
    }
  })
  return usedSpace/1024/1024;
}

function getStorageInfo(){

  const empty = getStorageSpace() - getUsedSpace();
  const used = getUsedSpace();

  return [empty,used]
}

function transform(value) {
  return Math.round((Math.exp(powerStorageSlider * value / maxStorageSlider) - 1) / (Math.exp(powerStorageSlider) - 1) * maxStorageSlider);
}

function reverse(value) {
  return (1 / powerStorageSlider) * Math.log(((Math.exp(powerStorageSlider) - 1) * value / maxStorageSlider) + 1) * maxStorageSlider;
}

function editStorage(newStorage){
  const state = JSON.parse(fs.readFileSync(statePath));
  state.storage = newStorage;
  fs.writeFileSync(statePath, JSON.stringify(state));
}

export {
  editStorage,
  reverse,
  transform,
  getStorageInfo,
  getUsedSpace,
  getStorageSpace,
  loadActivityPattern,
  readFilesInfo,
};
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view1', ['ngRoute', 'ngResource', 'webStorageModule',
  'ui.grid.resizeColumns', 'ui.grid', 'underscore', 'ui.grid.selection',
  'ui.grid.edit', 'ui.grid.cellNav'])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])
.filter('prettyDate', function() {
  return function(input) {
    // convert to date object
    var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
    d.setUTCSeconds(input);
    return d.toISOString();
  };
})
.filter('asUnit', function() {
  return function(input) {
    if (!input)
    {
      return 0;
    }

    var scales = [
      {val: 1, max: Math.pow(2,10)-1, unit: 'byte'},
      {val: Math.pow(2,10), max: Math.pow(2,20)-1, unit: 'kB'},
      {val: Math.pow(2,20), max: Math.pow(2,30)-1, unit: 'MB'},
      {val: Math.pow(2,30), max: Math.pow(2,40)-1, unit: 'GB'},
      {val: Math.pow(2,40), max: Math.pow(2,50)-1, unit: 'TB'},
    ];

    var scale = scales[scales.length - 1];
    for (var i = 0; i < scales.length; i++)
    {
      if (input < scales[i].max)
      {
        scale = scales[i];
        break;
      }
    }

    // return appropriate string
    return (input/scale.val).toFixed(1) + scale.unit;;
  };
})
.controller('View1Ctrl', ['$rootScope', '$scope', '$timeout',
  'uiGridConstants', '_',
  'stateModel', 'assetsModel', 'digestsModel',
  function ($rootScope, $scope, $timeout, uiGridConstants, _,
    stateModel, assetsModel, digestsModel) {

    // transient UI state
    $scope.stateModel = stateModel;
    $scope.assetsModel = assetsModel;
    $scope.digestsModel = digestsModel;

    // cached data
    $scope.reset = function() {
      $scope.stateModel.current.transient.busy = false;
      $scope.stateModel.current.transient.cancel = false;

      $scope.duplicates = [];

      $scope.digestsModel.reset();
      $scope.assetsModel.reset();

      $scope.analysis = {
        duplicateCount: 0,
        duplicateBytes: 0,
        percentDuplicated: 0
      };
    };
    $scope.reset();

    $scope.isBusy = function()
    {
      return $scope.stateModel.current.transient.busy;
    }

    $scope.canEdit = function()
    {
      return !$scope.stateModel.current.transient.busy;
    }

    // persist current ui state
    $scope.$watch('stateModel.current.accordion[0].open', function(isOpen) {
        $scope.stateModel.save_state();
      });

    $scope.$watch('stateModel.current.accordion[1].open', function(isOpen) {
        $scope.stateModel.save_state();
      });

    $scope.resetButtonClicked = function() {
      $scope.reset();
    };

    $scope.actionButtonClicked = function() {
      if ($scope.isBusy())
      {
        // cancel
        $scope.stateModel.current.transient.cancel = true;
      }
      else
      {
        $scope.reset();

        // open the files accordion
        $scope.stateModel.current.accordion[1].open = true;

        $scope.showMsg('scanning...');

        // search for files
        $scope.refreshAssets(function() {
            $scope.stateModel.current.transient.busy = false;
            $scope.stateModel.current.transient.cancel = false;
            $scope.showMsg('scan complete');
          });
      }
    };

    // trigger an update of the assets model
    $scope.refreshAssets = function (cb) {
      var folders = $scope.stateModel.get_enabled_folders();
      if (folders.length)
      {
        $scope.stateModel.current.transient.busy = true;
        async.each(folders,
          function(folder, callback) {
            if ($scope.stateModel.current.transient.cancel)
            {
              callback('cancel');
            }
            else
            {
              assetsModel.update(folder, function(err) {
                callback(err);
              });
            }
          },
          cb);
      }
      else
      {
        cb(null);
      }
    };

    // react to assetsModel update
    $scope.$on('assets:updated', function (event, data) {
      //$scope.assets = assetsModel.data;
    });

    // react to assetsModel update
    $scope.$on('digests:updated', function (event, data) {

      // merge digest into duplicates array
      var merge = function (duplicate) {
        var index = $scope.duplicates.findIndex(function (item, i) {
          return (item.hash == duplicate.hash);
        });

        var size = $scope.digestsModel.path_size_map[duplicate.paths[0]];
        if (index >= 0)
        {
          // already exists so merge
          duplicate.paths.forEach(function(new_path) {
            var path_index = $scope.duplicates[index].paths.indexOf(new_path);
            if (path_index < 0)
            {
              // not found so insert
              $scope.duplicates[index].paths.push(new_path);
              $scope.analysis.duplicateCount += 1;
              $scope.analysis.duplicateBytes += size;
            }
          });
        }
        else
        {
          // new item
          $scope.duplicates.push(duplicate);
          $scope.analysis.duplicateCount += 1;
          $scope.analysis.duplicateBytes += size;
        }

        // update stats
        $scope.analysis.percentDuplicated = Math.round(($scope.analysis.duplicateBytes / $scope.assetsModel.totalBytes) * 100);
      };

      // update duplicates array with new information
      for (var d in $scope.digestsModel.digest_path_map)
      {
        if ($scope.stateModel.current.transient.cancel)
        {
          break;
        }

        // any duplicates?
        if ($scope.digestsModel.digest_path_map[d].length > 1)
        {
          merge({ hash: d, paths: $scope.digestsModel.digest_path_map[d]});
        }
      }
    });

    $scope.showMsg = function(msg) {
      $scope.msg = msg;
    };

    $scope.$on('error', function (event, data) {
      $scope.msg = data;
    });

    $scope.addFolder = function () {
      // insert a new row
      $scope.stateModel.current.folders.unshift({"enabled": true, "path": ''});

      // now set focus to that new cell (after the menu collapses)
      $timeout(function() {
        $scope.gridOptionsFolders.gridApi.cellNav.scrollToFocus(
          $scope.stateModel.current.folders[0],
          $scope.gridOptionsFolders.columnDefs[0]);
      }, 0);
    }

    $scope.deleteFolder = function () {
      var rowCol = $scope.gridOptionsFolders.gridApi.cellNav.getFocusedCell();
      if(rowCol !== null) {
        // delete the current row
        var index = $scope.stateModel.current.folders.indexOf(rowCol.row.entity);
        $scope.stateModel.current.folders.splice(index, 1);
      }
    }

    $scope.gridOptionsAssets = {
      enableSorting: true,
      showColumnFooter: true,
      columnDefs: [
        { name: 'date',
          cellTemplate: '
{{row.entity.date | prettyDate}}
' },
        { name: 'path', type: 'string',
          aggregationType: uiGridConstants.aggregationTypes.count
        },
        {
          name: 'size', type: 'number',
          aggregationType: uiGridConstants.aggregationTypes.sum
        }
      ],
      data: "assetsModel.data"
    };

    $scope.gridOptionsFolders = {
      enableSorting: true,
      columnDefs: [
        {
          name: 'path',
          field: 'path',
          enableCellEdit: true,
          enableCellEditOnFocus: true,
          cellEditableCondition : $scope.canEdit
        }
      ],
      data: "stateModel.current.folders",
      onRegisterApi: function(gridApi){
        //set gridApi on scope
        $scope.gridOptionsFolders.gridApi = gridApi;

        // attach the handlers
        gridApi.grid.registerDataChangeCallback(function() {
          // sync the ui state with the object state
          $scope.gridOptionsFolders.gridApi.grid.rows.forEach(
            function(row) {
              if (row.entity.enabled)
              {
                $scope.gridOptionsFolders.gridApi.selection.selectRow(row.entity);
              }
            }
          );
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(row){
          row.entity.enabled = row.isSelected;
          $scope.stateModel.save_state();
        });

        gridApi.selection.on.rowSelectionChangedBatch($scope, function(rows){
          rows.forEach(function(row) {
            row.entity.enabled = row.isSelected;
          });
          $scope.stateModel.save_state();
        });
      }
    };

    $scope.gridOptionsExt = {
      enableSorting: true,
      enableSelection: true,
      columnDefs: [
        { name: 'extension', field: 'name' }
      ],
      data: "stateModel.current.extensions",
      onRegisterApi: function(gridApi){
        $scope.gridOptionsExt.gridApi = gridApi;

        gridApi.grid.registerDataChangeCallback(function() {
          // sync the ui state with the object state
          $scope.gridOptionsExt.gridApi.grid.rows.forEach(
            function(row) {
              if (row.entity.enabled)
              {
                $scope.gridOptionsExt.gridApi.selection.selectRow(row.entity);
              }
            }
          );
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(row){
          row.entity.enabled = row.isSelected;
          $scope.stateModel.save_state();
        });

        gridApi.selection.on.rowSelectionChangedBatch($scope, function(rows){
          rows.forEach(function(row) {
            row.entity.enabled = row.isSelected;
          });
          $scope.stateModel.save_state();
        });
      }
    };

    $scope.gridOptionsDuplicates = {
      enableSorting: true,
      showColumnFooter: true,
      columnDefs: [
        { name: 'paths' }
      ],
      data: "duplicates"
    };

    // restore UI state from local storage
    stateModel.load_state();
    $scope.showMsg('Optionally adjust your search settings, then press Scan');
  }
]);
<commit_msg>Hide footer in assets table (it's duplicated in the Findings area)<commit_after>'use strict';

angular.module('myApp.view1', ['ngRoute', 'ngResource', 'webStorageModule',
  'ui.grid.resizeColumns', 'ui.grid', 'underscore', 'ui.grid.selection',
  'ui.grid.edit', 'ui.grid.cellNav'])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])
.filter('prettyDate', function() {
  return function(input) {
    // convert to date object
    var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
    d.setUTCSeconds(input);
    return d.toISOString();
  };
})
.filter('asUnit', function() {
  return function(input) {
    if (!input)
    {
      return 0;
    }

    var scales = [
      {val: 1, max: Math.pow(2,10)-1, unit: 'byte'},
      {val: Math.pow(2,10), max: Math.pow(2,20)-1, unit: 'kB'},
      {val: Math.pow(2,20), max: Math.pow(2,30)-1, unit: 'MB'},
      {val: Math.pow(2,30), max: Math.pow(2,40)-1, unit: 'GB'},
      {val: Math.pow(2,40), max: Math.pow(2,50)-1, unit: 'TB'},
    ];

    var scale = scales[scales.length - 1];
    for (var i = 0; i < scales.length; i++)
    {
      if (input < scales[i].max)
      {
        scale = scales[i];
        break;
      }
    }

    // return appropriate string
    return (input/scale.val).toFixed(1) + scale.unit;;
  };
})
.controller('View1Ctrl', ['$rootScope', '$scope', '$timeout',
  'uiGridConstants', '_',
  'stateModel', 'assetsModel', 'digestsModel',
  function ($rootScope, $scope, $timeout, uiGridConstants, _,
    stateModel, assetsModel, digestsModel) {

    // transient UI state
    $scope.stateModel = stateModel;
    $scope.assetsModel = assetsModel;
    $scope.digestsModel = digestsModel;

    // cached data
    $scope.reset = function() {
      $scope.stateModel.current.transient.busy = false;
      $scope.stateModel.current.transient.cancel = false;

      $scope.duplicates = [];

      $scope.digestsModel.reset();
      $scope.assetsModel.reset();

      $scope.analysis = {
        duplicateCount: 0,
        duplicateBytes: 0,
        percentDuplicated: 0
      };
    };
    $scope.reset();

    $scope.isBusy = function()
    {
      return $scope.stateModel.current.transient.busy;
    }

    $scope.canEdit = function()
    {
      return !$scope.stateModel.current.transient.busy;
    }

    // persist current ui state
    $scope.$watch('stateModel.current.accordion[0].open', function(isOpen) {
        $scope.stateModel.save_state();
      });

    $scope.$watch('stateModel.current.accordion[1].open', function(isOpen) {
        $scope.stateModel.save_state();
      });

    $scope.resetButtonClicked = function() {
      $scope.reset();
    };

    $scope.actionButtonClicked = function() {
      if ($scope.isBusy())
      {
        // cancel
        $scope.stateModel.current.transient.cancel = true;
      }
      else
      {
        $scope.reset();

        // open the files accordion
        $scope.stateModel.current.accordion[1].open = true;

        $scope.showMsg('scanning...');

        // search for files
        $scope.refreshAssets(function() {
            $scope.stateModel.current.transient.busy = false;
            $scope.stateModel.current.transient.cancel = false;
            $scope.showMsg('scan complete');
          });
      }
    };

    // trigger an update of the assets model
    $scope.refreshAssets = function (cb) {
      var folders = $scope.stateModel.get_enabled_folders();
      if (folders.length)
      {
        $scope.stateModel.current.transient.busy = true;
        async.each(folders,
          function(folder, callback) {
            if ($scope.stateModel.current.transient.cancel)
            {
              callback('cancel');
            }
            else
            {
              assetsModel.update(folder, function(err) {
                callback(err);
              });
            }
          },
          cb);
      }
      else
      {
        cb(null);
      }
    };

    // react to assetsModel update
    $scope.$on('assets:updated', function (event, data) {
      //$scope.assets = assetsModel.data;
    });

    // react to assetsModel update
    $scope.$on('digests:updated', function (event, data) {

      // merge digest into duplicates array
      var merge = function (duplicate) {
        var index = $scope.duplicates.findIndex(function (item, i) {
          return (item.hash == duplicate.hash);
        });

        var size = $scope.digestsModel.path_size_map[duplicate.paths[0]];
        if (index >= 0)
        {
          // already exists so merge
          duplicate.paths.forEach(function(new_path) {
            var path_index = $scope.duplicates[index].paths.indexOf(new_path);
            if (path_index < 0)
            {
              // not found so insert
              $scope.duplicates[index].paths.push(new_path);
              $scope.analysis.duplicateCount += 1;
              $scope.analysis.duplicateBytes += size;
            }
          });
        }
        else
        {
          // new item
          $scope.duplicates.push(duplicate);
          $scope.analysis.duplicateCount += 1;
          $scope.analysis.duplicateBytes += size;
        }

        // update stats
        $scope.analysis.percentDuplicated = Math.round(($scope.analysis.duplicateBytes / $scope.assetsModel.totalBytes) * 100);
      };

      // update duplicates array with new information
      for (var d in $scope.digestsModel.digest_path_map)
      {
        if ($scope.stateModel.current.transient.cancel)
        {
          break;
        }

        // any duplicates?
        if ($scope.digestsModel.digest_path_map[d].length > 1)
        {
          merge({ hash: d, paths: $scope.digestsModel.digest_path_map[d]});
        }
      }
    });

    $scope.showMsg = function(msg) {
      $scope.msg = msg;
    };

    $scope.$on('error', function (event, data) {
      $scope.msg = data;
    });

    $scope.addFolder = function () {
      // insert a new row
      $scope.stateModel.current.folders.unshift({"enabled": true, "path": ''});

      // now set focus to that new cell (after the menu collapses)
      $timeout(function() {
        $scope.gridOptionsFolders.gridApi.cellNav.scrollToFocus(
          $scope.stateModel.current.folders[0],
          $scope.gridOptionsFolders.columnDefs[0]);
      }, 0);
    }

    $scope.deleteFolder = function () {
      var rowCol = $scope.gridOptionsFolders.gridApi.cellNav.getFocusedCell();
      if(rowCol !== null) {
        // delete the current row
        var index = $scope.stateModel.current.folders.indexOf(rowCol.row.entity);
        $scope.stateModel.current.folders.splice(index, 1);
      }
    }

    $scope.gridOptionsAssets = {
      enableSorting: true,
      columnDefs: [
        { name: 'date',
          cellTemplate: '
{{row.entity.date | prettyDate}}
' },
        { name: 'path', type: 'string' },
        { name: 'size', type: 'number' }
      ],
      data: "assetsModel.data"
    };

    $scope.gridOptionsFolders = {
      enableSorting: true,
      columnDefs: [
        {
          name: 'path',
          field: 'path',
          enableCellEdit: true,
          enableCellEditOnFocus: true,
          cellEditableCondition : $scope.canEdit
        }
      ],
      data: "stateModel.current.folders",
      onRegisterApi: function(gridApi){
        //set gridApi on scope
        $scope.gridOptionsFolders.gridApi = gridApi;

        // attach the handlers
        gridApi.grid.registerDataChangeCallback(function() {
          // sync the ui state with the object state
          $scope.gridOptionsFolders.gridApi.grid.rows.forEach(
            function(row) {
              if (row.entity.enabled)
              {
                $scope.gridOptionsFolders.gridApi.selection.selectRow(row.entity);
              }
            }
          );
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(row){
          row.entity.enabled = row.isSelected;
          $scope.stateModel.save_state();
        });

        gridApi.selection.on.rowSelectionChangedBatch($scope, function(rows){
          rows.forEach(function(row) {
            row.entity.enabled = row.isSelected;
          });
          $scope.stateModel.save_state();
        });
      }
    };

    $scope.gridOptionsExt = {
      enableSorting: true,
      enableSelection: true,
      columnDefs: [
        { name: 'extension', field: 'name' }
      ],
      data: "stateModel.current.extensions",
      onRegisterApi: function(gridApi){
        $scope.gridOptionsExt.gridApi = gridApi;

        gridApi.grid.registerDataChangeCallback(function() {
          // sync the ui state with the object state
          $scope.gridOptionsExt.gridApi.grid.rows.forEach(
            function(row) {
              if (row.entity.enabled)
              {
                $scope.gridOptionsExt.gridApi.selection.selectRow(row.entity);
              }
            }
          );
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(row){
          row.entity.enabled = row.isSelected;
          $scope.stateModel.save_state();
        });

        gridApi.selection.on.rowSelectionChangedBatch($scope, function(rows){
          rows.forEach(function(row) {
            row.entity.enabled = row.isSelected;
          });
          $scope.stateModel.save_state();
        });
      }
    };

    $scope.gridOptionsDuplicates = {
      enableSorting: true,
      showColumnFooter: true,
      columnDefs: [
        { name: 'paths' }
      ],
      data: "duplicates"
    };

    // restore UI state from local storage
    stateModel.load_state();
    $scope.showMsg('Optionally adjust your search settings, then press Scan');
  }
]);
<|endoftext|>


<commit_before>//noinspection JSLint
'use strict'; // jshint ignore:line

angular.module('myApp.view1', ['ngRoute', 'dataModule', 'lvl.directives.dragdrop', 'ui.bootstrap', 'mc.resizer', 'destegabry.timeline']) // jshint ignore:line

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', ['$scope', '$filter', 'attractions', function(sc, fl, attractions) {
      var newDate;
      var curDate = new Date().getTime();
      sc.items = [];
      for (var i = 0; i < 24; i++) {
        newDate = new Date(curDate + (i*60*60*1000));
        sc.items.push(fl('date')(newDate, "short"));
      }

    sc.dropped = function(dragEl, dropEl) { // function referenced by the drop target
        //this is application logic, for the demo we just want to color the grid squares
        //the directive provides a native dom object, wrap with jqlite
        var drop = angular.element((document.getElementById(dropEl)));
        var drag = angular.element((document.getElementById(dragEl)));

        //clear the previously applied color, if it exists
        var bgClass = drop.attr('data-color');
        if (bgClass) {
            drop.removeClass(bgClass);
        }

        //add the dragged color
        bgClass = drag.attr("data-color");
        drop.addClass(bgClass);
        drop.attr('data-color', bgClass);

        //if element has been dragged from the grid, clear dragged color
        if (drag.attr("x-lvl-drop-target")) {
            drag.removeClass(bgClass);
        }
    };
        sc.attractions = attractions;

        sc.data = [];

        sc.options = {
            "width":  "100%",
            "height": "auto",
            "style": "box",
            "editable": true
        };

    sc.addAttractionToTimeline = function(attraction) {
            sc.data.push({
                'start': new Date(2010, 7, 13),
                'end': new Date(2010, 7, 14),  // end is optional
                'content': attraction.name,
                'group': ''
                // Optional: a field 'className'
                // Optional: a field 'editable'
            });
        console.log(sc.data);
    }
}]);

<commit_msg>removed console.log<commit_after>//noinspection JSLint
'use strict'; // jshint ignore:line

angular.module('myApp.view1', ['ngRoute', 'dataModule', 'lvl.directives.dragdrop', 'ui.bootstrap', 'mc.resizer', 'destegabry.timeline']) // jshint ignore:line

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', ['$scope', '$filter', 'attractions', function(sc, fl, attractions) {
      var newDate;
      var curDate = new Date().getTime();
      sc.items = [];
      for (var i = 0; i < 24; i++) {
        newDate = new Date(curDate + (i*60*60*1000));
        sc.items.push(fl('date')(newDate, "short"));
      }

    sc.dropped = function(dragEl, dropEl) { // function referenced by the drop target
        //this is application logic, for the demo we just want to color the grid squares
        //the directive provides a native dom object, wrap with jqlite
        var drop = angular.element((document.getElementById(dropEl)));
        var drag = angular.element((document.getElementById(dragEl)));

        //clear the previously applied color, if it exists
        var bgClass = drop.attr('data-color');
        if (bgClass) {
            drop.removeClass(bgClass);
        }

        //add the dragged color
        bgClass = drag.attr("data-color");
        drop.addClass(bgClass);
        drop.attr('data-color', bgClass);

        //if element has been dragged from the grid, clear dragged color
        if (drag.attr("x-lvl-drop-target")) {
            drag.removeClass(bgClass);
        }
    };
        sc.attractions = attractions;

        sc.data = [];

        sc.options = {
            "width":  "100%",
            "height": "auto",
            "style": "box",
            "editable": true
        };

    sc.addAttractionToTimeline = function(attraction) {
            sc.data.push({
                'start': new Date(2010, 7, 13),
                'end': new Date(2010, 7, 14),  // end is optional
                'content': attraction.name,
                'group': ''
                // Optional: a field 'className'
                // Optional: a field 'editable'
            });
    }
}]);

<|endoftext|>


<commit_before>'use strict';
angular
  .module('PitchEvaluator')
  .controller('View2Ctrl', function($scope, $firebaseObject, $firebaseArray) {
  	var teamsRef = new Firebase("https://pitchevaluator.firebaseio.com/teams");

	var teamList = $firebaseArray(teamsRef);
	$scope.teams = teamList;

	var curTeamName, curTeamIndex, curTeamKey, curTeamObject, curTeamRef;
	var q1, q2, q3, q4, cmt1, cmt2, cmt3, cmt4;

	$scope.onSubmit = function() {
		curTeamName = document.getElementById("team-select").value;

		q1 = $('input[name="q1radio"]:checked').val();
		q2 = $('input[name="q2radio"]:checked').val();
		q3 = $('input[name="q3radio"]:checked').val();
		q4 = $('input[name="q4radio"]:checked').val();

		cmt1 = document.getElementById("q1textarea").value;
		cmt2 = document.getElementById("q2textarea").value;
		cmt3 = document.getElementById("q3textarea").value;
		cmt4 = document.getElementById("q4textarea").value;

		for (var i = 0; i < teamList.length; i++) {
			if (teamList[i].name == curTeamName) {
				curTeamIndex = i;
				curTeamKey = teamList.$keyAt(curTeamIndex);
				curTeamObject = $firebaseObject(teamsRef.child(curTeamKey))
			//Updating a Team:
				//Create a reference to the team:
				curTeamRef = teamsRef.child(curTeamKey);

				//Utilize the "update()" function
				curTeamRef.update({ q1Val: q1,
									q1cmt: cmt1,
									q2Val: q2,
									q2cmt: cmt2,
									q3Val: q3,
									q3cmt: cmt3,
									q4Val: q4,
									q4cmt: cmt4
								 });
			}
		};

	};

  })
<commit_msg>changed syntax<commit_after>'use strict';
angular
  .module('PitchEvaluator')
  .controller('View2Ctrl', function($scope, $firebaseObject, $firebaseArray) {
  	var teamsRef = new Firebase("https://pitchevaluator.firebaseio.com/teams");

	var teamList = $firebaseArray(teamsRef);
	$scope.teams = teamList;

	var curTeamName, curTeamIndex, curTeamKey, curTeamObject, curTeamRef;
	var q1, q2, q3, q4, cmt1, cmt2, cmt3, cmt4;

	$scope.onSubmit = function() {
		curTeamName = document.getElementById("team-select").value;

		q1 = $('input[name="q1radio"]:checked').val();
		q2 = $('input[name="q2radio"]:checked').val();
		q3 = $('input[name="q3radio"]:checked').val();
		q4 = $('input[name="q4radio"]:checked').val();

		cmt1 = document.getElementById("q1textarea").value;
		cmt2 = document.getElementById("q2textarea").value;
		cmt3 = document.getElementById("q3textarea").value;
		cmt4 = document.getElementById("q4textarea").value;

		for (var i = 0; i < teamList.length; i++) {
			if (teamList[i].name == curTeamName) {
				curTeamIndex = i;
				curTeamKey = teamList.$keyAt(curTeamIndex);
				curTeamObject = $firebaseObject(teamsRef.child(curTeamKey))
			//Updating a Team:
				//Create a reference to the team:
				curTeamRef = teamsRef.child(curTeamKey);

				//Utilize the "update()" function
				curTeamRef.update({ q1Val: q1,
									q1cmt: cmt1,
									q2Val: q2,
									q2cmt: cmt2,
									q3Val: q3,
									q3cmt: cmt3,
									q4Val: q4,
									q4cmt: cmt4
								 });
			}
		}
	};

  })
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view3', ['ngRoute', 'ngResource'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
	.when('/view3', {
		redirectTo: '/plan/{D57CCB0C-9E31-44BD-9A3C-F729891B56DF}'
	})
	.when('/plan/:guid', {
		templateUrl: 'view3/view3.html',
		controller: 'View3Ctrl'
	});
}])

.factory('gabiObject', ['$resource', function($resource){
	return $resource( "data/:guid.json", { guid: '@uuid'} );
}])

.controller('View3Ctrl', ['$scope', '$http', '$routeParams', 'gabiObject', function($scope, $http, $routeParams, gabiObject) {

  var first = function(){
    var s = Snap("#blackboard"); // This will use an existing svg element (not a div)

    var c = s.circle( 200,200,10 );
    var r = s.rect(200,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', 'opacity': 0.3 });

    var rclone = r.clone();
    var rclone2 = r.clone();
    var rclone3 = r.clone();
    var rclone4 = r.clone();
    var rclone5 = r.clone();

    //t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
    //r=relative rotate, R=relative rotate
    //relative means it takes into account previous transforms to accumulate
    //here it doesn't make much difference, until we combine later

    rclone.transform( 't100,100');
    rclone2.transform( 'r20,200,200' );
    rclone3.transform( 'r40,200,200' );

    s.text(350,150,"rotate around 200,200");

    rclone4.transform( 't100,100r20,200,200' );
    rclone5.transform( 't100,100r40,200,200' );

    s.text(450,250,"combined translate of 100,100 and rotate around 200,200");
  }
  first();

  var second = function(){
    var s = Snap("#svgout");
    var mapSvg = Snap.load("data/map.svg", function ( loadedFragment ) {
                                                s.append( loadedFragment );
                                        } );
  }
  second();

  var applyStandardFont = function(textelem){
		textelem.attr( { "font-size": "8pt" } );
  }

  var paintCommentInst = function(ciJson){
    var s = Snap("#owPlan");

    var ci = s.rect(
      ciJson["left"],
      ciJson["top"],
      ciJson["width"],
      ciJson["height"]).attr({
        stroke: "rgb(0,0,0)",
        "stroke-width": "0.5",
        fill: "rgb(255,255,128)"
      });
    var cmt = s.text( ciJson["left"]+5, ciJson["top"] + 15, ciJson["comment"] );
    applyStandardFont( cmt );
    var g = s.g(ci, cmt);
    g.drag();
  }

  var painterFnTemplate = function(x, y){
	  return function(name, guid){
      var s = Snap("#owPlan");
      var lnk = s.el("a").attr( { "xlink:href": "#/plan/" + guid } );
      var textelem = s.text(x+5, y+15, name);
      applyStandardFont(textelem);
      lnk.append(textelem);
	  }
  }

  var resolveAndPaintProcessInst = function(piJson, painterFn){
	var guid = { guid: piJson["process-ref"] };

	var myProcess = gabiObject.get( guid ).$promise.then(
		function(responseOK){
			painterFn( responseOK["nation"] + ": " + responseOK["name"], piJson["process-ref"]);
		},
		function(responseFail){
			painterFn("?");
		}
	);
  }

  var paintProcessInst = function(piJson){
    var s = Snap("#owPlan");
    var strokeWidth = 0.75468
    var pi = s.rect(
          piJson["left"]   + strokeWidth,
          piJson["top"]    + strokeWidth,
          piJson["width"]  - strokeWidth,
          piJson["height"] - strokeWidth
      ).attr({
        stroke: "#e1e1e1",
        "stroke-width": strokeWidth,
        fill: "url(#linearGradient4156)"
      });

	var newFn = painterFnTemplate( piJson["left"], piJson["top"] );
	resolveAndPaintProcessInst( piJson, newFn );
  }

  var calcVector = function(ptStart, ptEnd){
    return {
      dirX: ptEnd.posX - ptStart.posX,
      dirY: ptEnd.posY - ptStart.posY,
      isLeftToRight: function(){ return (this.dirX>0   && this.dirY===0); },
      isRightToLeft: function(){ return (this.dirX<0   && this.dirY===0); },
      isTopToBottom: function(){ return (this.dirX===0 && this.dirY>0); },
      isBottomToTop: function(){ return (this.dirX===0 && this.dirY<0); }
    }
  }

  var paintArrowAt = function(x,y){
    var s = Snap("#owPlan");
    var arrowPath = "M" + x + " " + y + " l" + "-5 -5 l0 10 z";
    var arrow = s.path(arrowPath).attr({ fill: "rgb(0,0,255)", stroke: "rgb(0,0,255)" });
    return arrow;
  }

  var paintFlowInst = function(fiJson){
    var s = Snap("#owPlan");

    $scope.sorted = fiJson["points"].sort(function(left,right){
                                            var sortOrder = [0,2,1];
                                            return sortOrder[left.pointType] - sortOrder[right.pointType];
                                          });

    if ($scope.sorted.length > 0) {

      var pfad = [];

      for (var i = 0; i < $scope.sorted.length; i++) {
        var pt = $scope.sorted[i];
        pfad.push( pt.posX );
        pfad.push( pt.posY );
      }

      // paint flow instance line
      s.polyline(pfad).attr( { fill: "none", stroke: "rgb(0,0,255)", "stroke-width": "3" });

      var idx       = $scope.sorted.length;
      var lastPt    = $scope.sorted[idx-1];
      var butLastPt = $scope.sorted[idx-2];
      var arrowDirection = calcVector(butLastPt, lastPt);

      // paint arrow at end of line
      var arrow = paintArrowAt( lastPt.posX, lastPt.posY );

      var adon = ","+lastPt.posX+","+lastPt.posY;
      if (arrowDirection.isLeftToRight()){
      } else if (arrowDirection.isRightToLeft()) {
        arrow.transform("r180"+adon);
      } else if (arrowDirection.isTopToBottom()) {
        arrow.transform("r90"+adon);
      } else if (arrowDirection.isBottomToTop()) {
        arrow.transform("r270"+adon);
      };
    }
  }

  var fetchAndPaintVisibleQuantity = function(planJson, painterFn){
	  var guid = { guid: planJson["visibleQuantity-ref"] };
	  var visQnt = gabiObject.get( guid ).$promise.then(
		function(resonseOK){
			painterFn( resonseOK["name"] );
		},
		function(responseFail){
			painterFn( "?" );
		}
	  );
  }

  var michelangelo = function(planJson){
    var s = Snap("#owPlan");

    window.document.title = planJson["name"];
    var strPlanName = s.text( 15, 20, planJson["name"] ).attr({
        "font-size": "16pt",
        "font-style": "normal",
        "font-weight": "normal",
        "text-anchor": "start",
        "fill": "#000000",
        "font-family": "Segoe UI"
        });

    _.map( planJson["flowInstances"], paintFlowInst );
    _.map( planJson["processInstances"], paintProcessInst );
    _.map( planJson["commentInstances"], paintCommentInst );

    var paintVisibleQuantity = painterFnTemplate( 15, 20 );
    fetchAndPaintVisibleQuantity(planJson, paintVisibleQuantity);
  }

  var autsch = function(failData){
	var s = Snap("#owPlan");
	var txt = failData.status + " " + failData.statusText;
	s.text( 30, 52, txt ).attr( { "font-size": "48pt", "fill": "rgb(200,200,200)" } );
  }

  var fetch = function($scope){

	var rp = $routeParams;

	var guid = { guid: rp.guid };

	gabiObject.get( guid ).$promise.then(
		function(responseOK){
			$scope.aPlan = responseOK;
			michelangelo($scope.aPlan);
		},
		function(responseFail){
			$scope.failData = responseFail;
			autsch(responseFail);
		}
	);
  }
  fetch($scope);
}]);
<commit_msg>paint flow instances lines in their true colors<commit_after>'use strict';

angular.module('myApp.view3', ['ngRoute', 'ngResource'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
	.when('/view3', {
		redirectTo: '/plan/{D57CCB0C-9E31-44BD-9A3C-F729891B56DF}'
	})
	.when('/plan/:guid', {
		templateUrl: 'view3/view3.html',
		controller: 'View3Ctrl'
	});
}])

.factory('gabiObject', ['$resource', function($resource){
	return $resource( "data/:guid.json", { guid: '@uuid'} );
}])

.controller('View3Ctrl', ['$scope', '$http', '$routeParams', 'gabiObject', function($scope, $http, $routeParams, gabiObject) {

  var first = function(){
    var s = Snap("#blackboard"); // This will use an existing svg element (not a div)

    var c = s.circle( 200,200,10 );
    var r = s.rect(200,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', 'opacity': 0.3 });

    var rclone = r.clone();
    var rclone2 = r.clone();
    var rclone3 = r.clone();
    var rclone4 = r.clone();
    var rclone5 = r.clone();

    //t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
    //r=relative rotate, R=relative rotate
    //relative means it takes into account previous transforms to accumulate
    //here it doesn't make much difference, until we combine later

    rclone.transform( 't100,100');
    rclone2.transform( 'r20,200,200' );
    rclone3.transform( 'r40,200,200' );

    s.text(350,150,"rotate around 200,200");

    rclone4.transform( 't100,100r20,200,200' );
    rclone5.transform( 't100,100r40,200,200' );

    s.text(450,250,"combined translate of 100,100 and rotate around 200,200");
  }
  first();

  var second = function(){
    var s = Snap("#svgout");
    var mapSvg = Snap.load("data/map.svg", function ( loadedFragment ) {
                                                s.append( loadedFragment );
                                        } );
  }
  second();

  var decimalToRGB = function(decimal){
    var R =  decimal % 256;
    var G = (decimal >> 8) % 256;
    var B = (decimal >> 16) % 256;
    return "rgb(" + R + "," + G + "," + B + ")" ;
  }

  var applyStandardFont = function(textelem){
		textelem.attr( { "font-size": "8pt" } );
  }

  var paintCommentInst = function(ciJson){
    var s = Snap("#owPlan");

    var ci = s.rect(
      ciJson["left"],
      ciJson["top"],
      ciJson["width"],
      ciJson["height"]).attr({
        stroke: "rgb(0,0,0)",
        "stroke-width": "0.5",
        fill: "rgb(255,255,128)"
      });
    var cmt = s.text( ciJson["left"]+5, ciJson["top"] + 15, ciJson["comment"] );
    applyStandardFont( cmt );
    var g = s.g(ci, cmt);
    g.drag();
  }

  var painterFnTemplate = function(x, y){
	  return function(name, guid){
      var s = Snap("#owPlan");
      var lnk = s.el("a").attr( { "xlink:href": "#/plan/" + guid } );
      var textelem = s.text(x+5, y+15, name);
      applyStandardFont(textelem);
      lnk.append(textelem);
	  }
  }

  var resolveAndPaintProcessInst = function(piJson, painterFn){
	var guid = { guid: piJson["process-ref"] };

	var myProcess = gabiObject.get( guid ).$promise.then(
		function(responseOK){
			painterFn( responseOK["nation"] + ": " + responseOK["name"], piJson["process-ref"]);
		},
		function(responseFail){
			painterFn("?");
		}
	);
  }

  var paintProcessInst = function(piJson){
    var s = Snap("#owPlan");
    var strokeWidth = 0.75468
    var pi = s.rect(
          piJson["left"]   + strokeWidth,
          piJson["top"]    + strokeWidth,
          piJson["width"]  - strokeWidth,
          piJson["height"] - strokeWidth
      ).attr({
        stroke: "#e1e1e1",
        "stroke-width": strokeWidth,
        fill: "url(#linearGradient4156)"
      });

	var newFn = painterFnTemplate( piJson["left"], piJson["top"] );
	resolveAndPaintProcessInst( piJson, newFn );
  }

  var calcVector = function(ptStart, ptEnd){
    return {
      dirX: ptEnd.posX - ptStart.posX,
      dirY: ptEnd.posY - ptStart.posY,
      isLeftToRight: function(){ return (this.dirX>0   && this.dirY===0); },
      isRightToLeft: function(){ return (this.dirX<0   && this.dirY===0); },
      isTopToBottom: function(){ return (this.dirX===0 && this.dirY>0); },
      isBottomToTop: function(){ return (this.dirX===0 && this.dirY<0); }
    }
  }

  var paintArrowAt = function(x,y,color){
    var s = Snap("#owPlan");
    var arrowPath = "M" + x + " " + y + " l" + "-5 -5 l0 10 z";
    var arrow = s.path(arrowPath).attr({ fill: decimalToRGB(color), stroke: decimalToRGB(color) });
    return arrow;
  }

  var paintFlowInst = function(fiJson){
    var s = Snap("#owPlan");

    $scope.sorted = fiJson["points"].sort(function(left,right){
                                            var sortOrder = [0,2,1];
                                            return sortOrder[left.pointType] - sortOrder[right.pointType];
                                          });

    if ($scope.sorted.length > 0) {

      var pfad = [];

      for (var i = 0; i < $scope.sorted.length; i++) {
        var pt = $scope.sorted[i];
        pfad.push( pt.posX );
        pfad.push( pt.posY );
      }

      // paint flow instance line
      s.polyline(pfad).attr( { fill: "none", stroke: decimalToRGB( fiJson["color"] ), "stroke-width": "3" });

      var idx       = $scope.sorted.length;
      var lastPt    = $scope.sorted[idx-1];
      var butLastPt = $scope.sorted[idx-2];
      var arrowDirection = calcVector(butLastPt, lastPt);

      // paint arrow at end of line
      var arrow = paintArrowAt( lastPt.posX, lastPt.posY, fiJson["color"] );

      var adon = ","+lastPt.posX+","+lastPt.posY;
      if (arrowDirection.isLeftToRight()){
      } else if (arrowDirection.isRightToLeft()) {
        arrow.transform("r180"+adon);
      } else if (arrowDirection.isTopToBottom()) {
        arrow.transform("r90"+adon);
      } else if (arrowDirection.isBottomToTop()) {
        arrow.transform("r270"+adon);
      };
    }
  }

  var fetchAndPaintVisibleQuantity = function(planJson, painterFn){
	  var guid = { guid: planJson["visibleQuantity-ref"] };
	  var visQnt = gabiObject.get( guid ).$promise.then(
		function(resonseOK){
			painterFn( resonseOK["name"] );
		},
		function(responseFail){
			painterFn( "?" );
		}
	  );
  }

  var michelangelo = function(planJson){
    var s = Snap("#owPlan");

    window.document.title = planJson["name"];
    var strPlanName = s.text( 15, 20, planJson["name"] ).attr({
        "font-size": "16pt",
        "font-style": "normal",
        "font-weight": "normal",
        "text-anchor": "start",
        "fill": "#000000",
        "font-family": "Segoe UI"
        });

    _.map( planJson["flowInstances"], paintFlowInst );
    _.map( planJson["processInstances"], paintProcessInst );
    _.map( planJson["commentInstances"], paintCommentInst );

    var paintVisibleQuantity = painterFnTemplate( 15, 20 );
    fetchAndPaintVisibleQuantity(planJson, paintVisibleQuantity);
  }

  var autsch = function(failData){
	var s = Snap("#owPlan");
	var txt = failData.status + " " + failData.statusText;
	s.text( 30, 52, txt ).attr( { "font-size": "48pt", "fill": "rgb(200,200,200)" } );
  }

  var fetch = function($scope){

	var rp = $routeParams;

	var guid = { guid: rp.guid };

	gabiObject.get( guid ).$promise.then(
		function(responseOK){
			$scope.aPlan = responseOK;
			michelangelo($scope.aPlan);
		},
		function(responseFail){
			$scope.failData = responseFail;
			autsch(responseFail);
		}
	);
  }
  fetch($scope);
}]);
<|endoftext|>