<commit_before>/*   Copyright (c) 2010, Diaspora Inc.  This file is
 *   licensed under the Affero General Public License version 3 or later.  See
 *   the COPYRIGHT file.
 */

$(document).ready(function(){
  var selectedGUIDS = [],
      requests = 0;

  $("#aspect_nav li").each(function(){
    var button = $(this),
        guid = button.attr('data-guid');

    if(guid && location.href.search("a_ids..="+guid+"(&|$)") != -1){
      button.addClass('selected');
      selectedGUIDS.push(guid);
    }
  });

  $("a.hard_aspect_link").live("click", function(e){
    e.preventDefault();
    requests++;

    var guid = $(this).attr('data-guid');

    // select correct aspect in filter list & deselect others
    $("#aspect_nav li").each(function(){
      var $this = $(this);
      if( $this.attr('data-guid') == guid){
        $this.addClass('selected');
      } else {
        $this.removeClass('selected');
      }
    });

    // loading animation
    $("#aspect_stream_container").fadeTo(100, 0.4);
    $("#aspect_contact_pictures").fadeTo(100, 0.4);

    performAjax( $(this).attr('href'));
  });

  $("#aspect_nav a.aspect_selector").click(function(e){
    e.preventDefault();

    requests++;

    // loading animation
    $("#aspect_stream_container").fadeTo(100, 0.4);
    $("#aspect_contact_pictures").fadeTo(100, 0.4);

    // filtering //////////////////////
    var $this = $(this),
        listElement = $this.parent(),
        guid = listElement.attr('data-guid'),
        homeListElement = $("#aspect_nav a.home_selector").parent();

    if( listElement.hasClass('selected') ){
      // remove filter
      var idx = selectedGUIDS.indexOf( guid );
      if( idx != -1 ){
        selectedGUIDS.splice(idx,1);
      }
      listElement.removeClass('selected');

      if(selectedGUIDS.length == 0){
        homeListElement.addClass('selected');
      }

    } else {
      // append filter
      if(selectedGUIDS.indexOf( guid == 1)){
        selectedGUIDS.push( guid );
      }
      listElement.addClass('selected');

      homeListElement.removeClass('selected');
    }

     performAjax(generateURL());
  });

  function generateURL(){
    var baseURL = location.href.split("?")[0];

    // generate new url
    baseURL = baseURL.replace('#','');
    baseURL += '?';
    for(i=0; i < selectedGUIDS.length; i++){
      baseURL += 'a_ids[]='+ selectedGUIDS[i] +'&';
    }

    if(!$("#publisher").hasClass("closed")) {
      // open publisher
      baseURL += "op=true";
    } else {
      // slice last '&'
      baseURL = baseURL.slice(0,baseURL.length-1);
    }
    return baseURL;
  }

  function performAjax(newURL) {
    var post = $("#publisher textarea").val(),
        photos = {};

    //pass photos
    $('#photodropzone img').each(function(){
      var img = $(this);
      guid = img.attr('data-id');
      url = img.attr('src');
      photos[guid] = url;
    });

    // set url
    history.pushState(null, document.title, newURL);

    $.ajax({
      url : newURL,
      dataType : 'script',
      success  : function(data){
        requests--;
        // fill in publisher
        // (not cached because this element changes)

        var textarea = $("#publisher textarea");
        var photozone = $('#photodropzone')

        if( textarea.val() == "" ) {
          textarea.val(post);
          textarea.focus();
        }

        var photos_html = "";
        for(var key in photos){
          $("#publisher textarea").addClass("with_attachments");
          photos_html = photos_html + "
 " + ("") +  "
";
        };

        $('html, body').animate({scrollTop:0}, 'fast');

        // reinit listeners on stream
        photozone.html(photos_html);
        Stream.initialize();

        // fade contents back in
        if(requests == 0){
          $("#aspect_stream_container").fadeTo(100, 1);
          $("#aspect_contact_pictures").fadeTo(100, 1);
        }
      }
    });
  }

});
<commit_msg>some browers (Firefox for example) have no pushState, so disable it for those for now<commit_after>/*   Copyright (c) 2010, Diaspora Inc.  This file is
 *   licensed under the Affero General Public License version 3 or later.  See
 *   the COPYRIGHT file.
 */

$(document).ready(function(){
  var selectedGUIDS = [],
      requests = 0;

  $("#aspect_nav li").each(function(){
    var button = $(this),
        guid = button.attr('data-guid');

    if(guid && location.href.search("a_ids..="+guid+"(&|$)") != -1){
      button.addClass('selected');
      selectedGUIDS.push(guid);
    }
  });

  $("a.hard_aspect_link").live("click", function(e){
    e.preventDefault();
    requests++;

    var guid = $(this).attr('data-guid');

    // select correct aspect in filter list & deselect others
    $("#aspect_nav li").each(function(){
      var $this = $(this);
      if( $this.attr('data-guid') == guid){
        $this.addClass('selected');
      } else {
        $this.removeClass('selected');
      }
    });

    // loading animation
    $("#aspect_stream_container").fadeTo(100, 0.4);
    $("#aspect_contact_pictures").fadeTo(100, 0.4);

    performAjax( $(this).attr('href'));
  });

  $("#aspect_nav a.aspect_selector").click(function(e){
    e.preventDefault();

    requests++;

    // loading animation
    $("#aspect_stream_container").fadeTo(100, 0.4);
    $("#aspect_contact_pictures").fadeTo(100, 0.4);

    // filtering //////////////////////
    var $this = $(this),
        listElement = $this.parent(),
        guid = listElement.attr('data-guid'),
        homeListElement = $("#aspect_nav a.home_selector").parent();

    if( listElement.hasClass('selected') ){
      // remove filter
      var idx = selectedGUIDS.indexOf( guid );
      if( idx != -1 ){
        selectedGUIDS.splice(idx,1);
      }
      listElement.removeClass('selected');

      if(selectedGUIDS.length == 0){
        homeListElement.addClass('selected');
      }

    } else {
      // append filter
      if(selectedGUIDS.indexOf( guid == 1)){
        selectedGUIDS.push( guid );
      }
      listElement.addClass('selected');

      homeListElement.removeClass('selected');
    }

     performAjax(generateURL());
  });

  function generateURL(){
    var baseURL = location.href.split("?")[0];

    // generate new url
    baseURL = baseURL.replace('#','');
    baseURL += '?';
    for(i=0; i < selectedGUIDS.length; i++){
      baseURL += 'a_ids[]='+ selectedGUIDS[i] +'&';
    }

    if(!$("#publisher").hasClass("closed")) {
      // open publisher
      baseURL += "op=true";
    } else {
      // slice last '&'
      baseURL = baseURL.slice(0,baseURL.length-1);
    }
    return baseURL;
  }

  function performAjax(newURL) {
    var post = $("#publisher textarea").val(),
        photos = {};

    //pass photos
    $('#photodropzone img').each(function(){
      var img = $(this);
      guid = img.attr('data-id');
      url = img.attr('src');
      photos[guid] = url;
    });

    // set url
    // some browsers (Firefox for example) don't support pushState
    if (typeof(history.pushState) == 'function') {
      history.pushState(null, document.title, newURL);
    }

    $.ajax({
      url : newURL,
      dataType : 'script',
      success  : function(data){
        requests--;
        // fill in publisher
        // (not cached because this element changes)

        var textarea = $("#publisher textarea");
        var photozone = $('#photodropzone')

        if( textarea.val() == "" ) {
          textarea.val(post);
          textarea.focus();
        }

        var photos_html = "";
        for(var key in photos){
          $("#publisher textarea").addClass("with_attachments");
          photos_html = photos_html + "
 " + ("") +  "
";
        };

        $('html, body').animate({scrollTop:0}, 'fast');

        // reinit listeners on stream
        photozone.html(photos_html);
        Stream.initialize();

        // fade contents back in
        if(requests == 0){
          $("#aspect_stream_container").fadeTo(100, 1);
          $("#aspect_contact_pictures").fadeTo(100, 1);
        }
      }
    });
  }

});
<|endoftext|>


<commit_before>var requirejs = require( 'requirejs' ),
	path = require( 'path' ),
	fs = require( 'fs' );

module.exports = function( grunt ) {
	var config = grunt.config.get( 'global' ),
		outputFile = path.join( config.dirs.output, config.names.root ),
		helpers = config.helpers;

	grunt.config.set( 'js', {
		require: {
			baseUrl: 'js',
			name: 'jquery.mobile',
			exclude:[
				'jquery',
				'../external/requirejs/order',
				'../external/requirejs/depend',
				'../external/requirejs/text',
				'../external/requirejs/text!../version.txt'
			],
			out: 'outputFile.compiled.js',
			pragmasOnSave: { jqmBuildExclude: true },
			wrap: { startFile: 'build/wrap.start', endFile: 'build/wrap.end' },
			findNestedDependencies: true,
			skipModuleInsertion: true,
			optimize: 'none'
		}
	});

	grunt.registerTask( 'js_without_deps', 'compile and minify the js', function() {
		var done = this.async(), require = grunt.config.get( 'js' ).require;

		helpers.asyncConfig(function( config ) {
			// pull the includes together using require js
			requirejs.optimize( require );

			// dump the versioned header into the normal js file
			grunt.file.write( config.ver.header, outputFile + '.js' );

			// add the compiled js to the normal js file, replace the version tag
			// with the contents from version.txt
			helpers.appendFrom( require.out, outputFile + '.js', function( fileContents ) {
				return fileContents.replace( /__version__/, '"' + config.ver.official + '"' );
			});

			// add the min header into the minified file
			var max, min;
			max = grunt.file.read( outputFile + ".js" );
			min = grunt.helper( 'uglify', max, {});

			grunt.file.write( outputFile + ".min.js" , config.ver.min );
			helpers.append( min, outputFile + ".min.js" );

			grunt.log.writeln();
			grunt.helper( 'min_max_info', min, max);
			// TODO add minification of js file

			// remove the requirejs compile output
			fs.unlink( require.out );
			done();
		});
	});

	// NOTE custom dasks don't accept dependencies so we alias
	grunt.registerTask( 'js', 'init js_without_deps' );
};
<commit_msg>quick correction to js<commit_after>var requirejs = require( 'requirejs' ),
	path = require( 'path' ),
	fs = require( 'fs' );

module.exports = function( grunt ) {
	var config = grunt.config.get( 'global' ),
		outputFile = path.join( config.dirs.output, config.names.root ),
		helpers = config.helpers;

	grunt.config.set( 'js', {
		require: {
			baseUrl: 'js',
			name: 'jquery.mobile',
			exclude:[
				'jquery',
				'../external/requirejs/order',
				'../external/requirejs/depend',
				'../external/requirejs/text',
				'../external/requirejs/text!../version.txt'
			],
			out: 'outputFile.compiled.js',
			pragmasOnSave: { jqmBuildExclude: true },
			wrap: { startFile: 'build/wrap.start', endFile: 'build/wrap.end' },
			findNestedDependencies: true,
			skipModuleInsertion: true,
			optimize: 'none'
		}
	});

	grunt.registerTask( 'js_without_deps', 'compile and minify the js', function() {
		var done = this.async(), require = grunt.config.get( 'js' ).require;

		helpers.asyncConfig(function( config ) {
			// pull the includes together using require js
			requirejs.optimize( require );

			// dump the versioned header into the normal js file
			helpers.write( config.ver.header, outputFile + '.js' );

			// add the compiled js to the normal js file, replace the version tag
			// with the contents from version.txt
			helpers.appendFrom( require.out, outputFile + '.js', function( fileContents ) {
				return fileContents.replace( /__version__/, '"' + config.ver.official + '"' );
			});

			// add the min header into the minified file
			var max, min;
			max = grunt.file.read( outputFile + ".js" );
			min = grunt.helper( 'uglify', max, {});

			grunt.file.write( outputFile + ".min.js" , config.ver.min );
			helpers.append( min, outputFile + ".min.js" );

			grunt.log.writeln();
			grunt.helper( 'min_max_info', min, max);
			// TODO add minification of js file

			// remove the requirejs compile output
			fs.unlink( require.out );
			done();
		});
	});

	// NOTE custom dasks don't accept dependencies so we alias
	grunt.registerTask( 'js', 'init js_without_deps' );
};
<|endoftext|>


<commit_before>function ModelSearcher(){

	// URL for JSON that lists categories in the form [{"name":"Agricultrure","id":4074},{"name":"Agriculture","id":2558}]
	this.listService = "";

	// URL for JSON that lists categories in a hierachy (see ModelSearch.createTreeFromArray() for details)
	this.treeService = "";

	// A script on the same subdomain. When a URL is appended to this string, the resulting URL should return the original URL's content.
	// The proxy can be bypassed by using service URLs that don't begin with "http" (and are thus on the subdomain and don't need a proxy)
	this.proxy = "";

	// The id attribute of the div which contains all of DOM elements for this
	this.divId = "";

	// The jQuery-wrapped DOM element of the div which contains all of DOM elements for this
	this.div = null;

	// The name, label, and style attributes of the hidden field in which the selected ID(s) will be entered
	this.fieldName = "searcher_id_input";
	this.fieldLabel = "";
	this.fieldStyle = "padding:3px";

	// Another method of adding objects (instead of using services)
	this.objectList = null;

	// A JS array of the object(s) which should be selected in the form [{id: '2594', name: 'animals'}]
	this.selectedObjects = null;

	// The jQuery-wrapped DOM element of the hidden input which stores the selected ID(s)
	this.hiddenIdInput = null;

	// The jQuery-wrapped DOM element of the autocomplete text field input
	this.autocompleteInput = null;

	// Whether or not a tree (and the accompanying tree link) should be used
	this.hasTree = true;

	// Whether the user can select only one category from the tree (if present) or select multiple categories
	this.singleSelectionTree = false;

	// The id attribute of the div which contains the tree popup
	this.treePopupId = null;

	// The jQuery-wrapped DOM element of the div which contains the tree popup
	this.treePopup = null;

	// The jQuery-wrapped DOM element that lists the names selected from the tree
	this.treeNames = null;

	// The jQuery-wrapped DOM element that removes the names selected from the tree
	this.treeRemove = null;

	this.treeHtml = null;
	this.treeLoaded = false;

	this.cRowSelector = '#characteristic-row';
	this.bRowID = 'bin';
	this.binItemTemplate = '{content} ';

	// See the attribute documentation above for explanations of these arguments
	this.init = function(divId, listService, treeService, options){
		var that = this;

		this.listService = listService;
		this.treeService = treeService;
		if(typeof(options.fieldName) != "undefined")			{ this.fieldName = options.fieldName; }
		if(typeof(options.fieldLabel) != "undefined")			{ this.fieldLabel = options.fieldLabel; }
		if(typeof(options.selectedObjects) != "undefined")		{ this.selectedObjects = options.selectedObjects; }
		if(typeof(options.hasTree) != "undefined")				{ this.hasTree = options.hasTree; }
		if(typeof(options.singleSelectionTree) != "undefined")	{ this.singleSelectionTree = options.singleSelectionTree; }
		if(typeof(options.proxy) != "undefined")				{ this.proxy = options.proxy; }
		this.divId = divId;
		this.div = jQuery('#'+divId);
		this.autocompleteInput = jQuery('#searcher_autocomplete');
		this.hiddenIdInput = jQuery('#searcher_id_input');

		// Request the service through a proxy if it's not local
		if(this.listService.substr(0,4) == 'http'){
			this.listService = this.proxy+this.listService;
		}
		if(this.treeService.substr(0,4) == 'http'){
			this.treeService = this.proxy+this.treeService;
		}

		jQuery.getJSON(this.listService, function(data){
			that.autocompleteInput.unautocomplete().autocomplete(data, {
				matchContains: true,
				mustMatch: true,
				max: 20,
				formatItem: that.autocompleteFormatItem,
				formatMatch: that.autocompleteFormatMatch,
				formatResult: that.autocompleteFormatItem,
				multiple: true
			});
			that.autocompleteInput.result(that.autocompleteCallback);
			that.objectList = {};
			for(var i in data){
				that.objectList[data[i].id] = data[i];
			}
		});
		if(this.selectedObjects && this.selectedObjects.length == 1){
			this.autocompleteInput.val(this.selectedObjects[0].name);
			this.hiddenIdInput.val(this.selectedObjects[0].id);
		}
		if(this.hasTree){
			this.treePopupId = this.divId+"_model_searcher_tree_popup";
			this.treeLoading = this.div.find('.tree-loading');
		}

		jQuery('.tree-remove').unbind('click'); // this and below have to be separate because live can't be chained
		jQuery('.tree-remove').live('click', function(){
			var $selection = jQuery(this).closest('.tree-names'),
				$target = $selection.siblings().length ? $selection : $selection.closest('tr');

			$selection.fadeOut( function(){
				var id = this.id.replace('bin_item_',''),
					regex = new RegExp('(^|,)' + id + '(,|$)'),
					val = that.hiddenIdInput[0].value;

				$target.remove();
				that.hiddenIdInput[0].value = val.replace(regex, ',');
				that.checkAnnotationState();
			});
			return false;
		});

		if ( document.getElementById('root_topics').value != 'All' ) jQuery('#browse_link').show().click(function(){that.activatePopup()});
	};

	this.activatePopup = function() {
		var thisModelSearcher = this;
		if(thisModelSearcher.treeLoaded){
			jQuery('#'+thisModelSearcher.treePopupId).show();
		}else{
			//thisModelSearcher.treeLoading.html(' ');
			jQuery.getJSON(thisModelSearcher.treeService, function(data){
				thisModelSearcher.treeHtml = thisModelSearcher.createTreeFromArray(data.category ? data.category.categories : data.categories);
				thisModelSearcher.loadPopup();
				thisModelSearcher.treeHtml = null;
				data = null;
				//thisModelSearcher.treeLoading.html('');
				thisModelSearcher.treeLoaded = true;
			});
		}
		return false;
	}

	this.loadPopup = function(){
		var that = thisModelSearcher;
		that.treePopup = jQuery().draggablePopup({
			id: that.treePopupId,
			header: '',
			content: '',
			footer: '',
			width: 500,
			closeWith: 'hide'
		});
		var content = '

'+
			'
Please select one or more feature types from the list below.

'+
			'For each type, click on the left box to select the type and its subcategories; '+
			'click on the right box to select only the type without its subcategories.

'+
			'<form method="get" action="">'+
			'
'+
			that.treeHtml+
			'
'+
			'
<input type="submit" value="Select" /> <input type="button" value="Cancel" onclick="jQuery(this).parents(\'.draggable-popup:first\').hide(); return false;" />'+
			'</form>'+
			'
'
			;
		that.treePopup.setContent(content);
		that.treePopup.div.checkTree({ onExpand: function( $parent ) {$parent.siblings().find('.expanded').click()}});
		that.treePopup.div
			.find('form:first').submit(function(){
				var ids = [];

				jQuery(this).find(':checkbox:checked').each(function(){
					var label_name = jQuery(this).siblings('label').attr('name');
					if(label_name.indexOf('record_') == 0){
						ids.push(label_name.substring(7));
					}
				});
				if (ids.length) that.addValue( ids );
				jQuery('#'+that.treePopupId).hide();
				return false;
			});

		// For large trees, keeping this in memory can cause performance issues, so we'll set it to null
		// and use thisModelSearcher.treePopupId when we need it.
		that.treePopup = null;
	};

	this.addValue = function( ids ) {
		var that = thisModelSearcher,
			i,
			names = [],
			ids = ids || [],
			test = document.getElementById(that.bRowID),
			$bRow = test ? $(test) : jQuery("

").insertAfter(jQuery(that.cRowSelector)).find('#' + that.bRowID);

		for(i in ids){
			if ( !document.getElementById('bin_item_' + ids[i]) ) {
				that.selectedObjects.push(that.objectList[ids[i]]);
				names.push(
					that.binItemTemplate
						.replace('{content}', that.objectList[ids[i]].name)
						.replace('{id}', ids[i])
				);
			}
		}
		that.hiddenIdInput[0].value += ',' + ids.join(',');
		$bRow.append(names.join(''));
		that.autocompleteInput.val('');
		this.checkAnnotationState();
	}

	this.checkAnnotationState = function() {
		if ( jQuery('.tree-names').length > 1 ) {
			jQuery('#media_category_association_string_value, #media_category_association_numeric_value').attr('disabled', 'disabled').closest('tr').fadeOut();
		} else {
			jQuery('.annotation').fadeIn().find('#media_category_association_string_value, #media_category_association_numeric_value').removeAttr('disabled');
		}
	}

	this.resetFields = function(){
		this.autocompleteInput.val('');
		this.hiddenIdInput.val('');
		if(this.hasTree){
			this.treeNames.html('');
			this.treeRemove.hide();
			jQuery('#'+this.treePopupId).hide();
		}
	};

	this.autocompleteFormatItem = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatMatch = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatResult = function(item, i, max){
		return item.id;
	};
	var thisModelSearcher = this;
	this.autocompleteCallback = function(event, data, formatted) {
		if(data){
			thisModelSearcher.addValue([data.id])
		}else{
			//thisModelSearcher.hiddenIdInput.val('');
		}

		//thisModelSearcher.treeNames.html('');
		// thisModelSearcher.treeRemove.hide();
		return false;
	};

	this.createTreeFromArray = function(arr){
		var html = '';
		if(arr && arr.category){
			html += '
';
			if(arr.category && arr.category[0]){
				for(var i in arr.category) {
					html += '
';
					html += '<input type="checkbox" class="toggle">'+arr.category[i].title+'';
					if(arr.category[i].categories){
						html += this.createTreeFromArray(arr.category[i].categories);
					}
					html += '
';
				}
			}else if(arr.category){
				html += '
';
				html += '<input type="checkbox" class="toggle">'+arr.category.title+'';
				if(arr.category.categories){
					html += this.createTreeFromArray(arr.category.categories);
				}
				html += '
';
			}
			html += '
';
		}
		return html;
	}

};

function reinit() {
	var el = document.getElementById('root_topics'),
		id = el.value,
		label = el.options[el.selectedIndex].text;

	if ( id == 'All' ) {
		all_searcher();
	} else {
		searcher = new ModelSearcher();
		tmb_options['hasTree'] = true;
		tmb_options['fieldLabel'] = label;
		searcher.init( tmb_div, list_url.replace('{id}', id), all_url.replace('{id}', id), tmb_options);
	}
};<commit_msg>fixing delete image url<commit_after>function ModelSearcher(){

	// URL for JSON that lists categories in the form [{"name":"Agricultrure","id":4074},{"name":"Agriculture","id":2558}]
	this.listService = "";

	// URL for JSON that lists categories in a hierachy (see ModelSearch.createTreeFromArray() for details)
	this.treeService = "";

	// A script on the same subdomain. When a URL is appended to this string, the resulting URL should return the original URL's content.
	// The proxy can be bypassed by using service URLs that don't begin with "http" (and are thus on the subdomain and don't need a proxy)
	this.proxy = "";

	// The id attribute of the div which contains all of DOM elements for this
	this.divId = "";

	// The jQuery-wrapped DOM element of the div which contains all of DOM elements for this
	this.div = null;

	// The name, label, and style attributes of the hidden field in which the selected ID(s) will be entered
	this.fieldName = "searcher_id_input";
	this.fieldLabel = "";
	this.fieldStyle = "padding:3px";

	// Another method of adding objects (instead of using services)
	this.objectList = null;

	// A JS array of the object(s) which should be selected in the form [{id: '2594', name: 'animals'}]
	this.selectedObjects = null;

	// The jQuery-wrapped DOM element of the hidden input which stores the selected ID(s)
	this.hiddenIdInput = null;

	// The jQuery-wrapped DOM element of the autocomplete text field input
	this.autocompleteInput = null;

	// Whether or not a tree (and the accompanying tree link) should be used
	this.hasTree = true;

	// Whether the user can select only one category from the tree (if present) or select multiple categories
	this.singleSelectionTree = false;

	// The id attribute of the div which contains the tree popup
	this.treePopupId = null;

	// The jQuery-wrapped DOM element of the div which contains the tree popup
	this.treePopup = null;

	// The jQuery-wrapped DOM element that lists the names selected from the tree
	this.treeNames = null;

	// The jQuery-wrapped DOM element that removes the names selected from the tree
	this.treeRemove = null;

	this.treeHtml = null;
	this.treeLoaded = false;

	this.cRowSelector = '#characteristic-row';
	this.bRowID = 'bin';
	this.binItemTemplate = '{content} ';

	// See the attribute documentation above for explanations of these arguments
	this.init = function(divId, listService, treeService, options){
		var that = this;

		this.listService = listService;
		this.treeService = treeService;
		if(typeof(options.fieldName) != "undefined")			{ this.fieldName = options.fieldName; }
		if(typeof(options.fieldLabel) != "undefined")			{ this.fieldLabel = options.fieldLabel; }
		if(typeof(options.selectedObjects) != "undefined")		{ this.selectedObjects = options.selectedObjects; }
		if(typeof(options.hasTree) != "undefined")				{ this.hasTree = options.hasTree; }
		if(typeof(options.singleSelectionTree) != "undefined")	{ this.singleSelectionTree = options.singleSelectionTree; }
		if(typeof(options.proxy) != "undefined")				{ this.proxy = options.proxy; }
		this.divId = divId;
		this.div = jQuery('#'+divId);
		this.autocompleteInput = jQuery('#searcher_autocomplete');
		this.hiddenIdInput = jQuery('#searcher_id_input');

		// Request the service through a proxy if it's not local
		if(this.listService.substr(0,4) == 'http'){
			this.listService = this.proxy+this.listService;
		}
		if(this.treeService.substr(0,4) == 'http'){
			this.treeService = this.proxy+this.treeService;
		}

		jQuery.getJSON(this.listService, function(data){
			that.autocompleteInput.unautocomplete().autocomplete(data, {
				matchContains: true,
				mustMatch: true,
				max: 20,
				formatItem: that.autocompleteFormatItem,
				formatMatch: that.autocompleteFormatMatch,
				formatResult: that.autocompleteFormatItem,
				multiple: true
			});
			that.autocompleteInput.result(that.autocompleteCallback);
			that.objectList = {};
			for(var i in data){
				that.objectList[data[i].id] = data[i];
			}
		});
		if(this.selectedObjects && this.selectedObjects.length == 1){
			this.autocompleteInput.val(this.selectedObjects[0].name);
			this.hiddenIdInput.val(this.selectedObjects[0].id);
		}
		if(this.hasTree){
			this.treePopupId = this.divId+"_model_searcher_tree_popup";
			this.treeLoading = this.div.find('.tree-loading');
		}

		jQuery('.tree-remove').unbind('click'); // this and below have to be separate because live can't be chained
		jQuery('.tree-remove').live('click', function(){
			var $selection = jQuery(this).closest('.tree-names'),
				$target = $selection.siblings().length ? $selection : $selection.closest('tr');

			$selection.fadeOut( function(){
				var id = this.id.replace('bin_item_',''),
					regex = new RegExp('(^|,)' + id + '(,|$)'),
					val = that.hiddenIdInput[0].value;

				$target.remove();
				that.hiddenIdInput[0].value = val.replace(regex, ',');
				that.checkAnnotationState();
			});
			return false;
		});

		if ( document.getElementById('root_topics').value != 'All' ) jQuery('#browse_link').show().click(function(){that.activatePopup()});
	};

	this.activatePopup = function() {
		var thisModelSearcher = this;
		if(thisModelSearcher.treeLoaded){
			jQuery('#'+thisModelSearcher.treePopupId).show();
		}else{
			//thisModelSearcher.treeLoading.html(' ');
			jQuery.getJSON(thisModelSearcher.treeService, function(data){
				thisModelSearcher.treeHtml = thisModelSearcher.createTreeFromArray(data.category ? data.category.categories : data.categories);
				thisModelSearcher.loadPopup();
				thisModelSearcher.treeHtml = null;
				data = null;
				//thisModelSearcher.treeLoading.html('');
				thisModelSearcher.treeLoaded = true;
			});
		}
		return false;
	}

	this.loadPopup = function(){
		var that = thisModelSearcher;
		that.treePopup = jQuery().draggablePopup({
			id: that.treePopupId,
			header: '',
			content: '',
			footer: '',
			width: 500,
			closeWith: 'hide'
		});
		var content = '

'+
			'
Please select one or more feature types from the list below.

'+
			'For each type, click on the left box to select the type and its subcategories; '+
			'click on the right box to select only the type without its subcategories.

'+
			'<form method="get" action="">'+
			'
'+
			that.treeHtml+
			'
'+
			'
<input type="submit" value="Select" /> <input type="button" value="Cancel" onclick="jQuery(this).parents(\'.draggable-popup:first\').hide(); return false;" />'+
			'</form>'+
			'
'
			;
		that.treePopup.setContent(content);
		that.treePopup.div.checkTree({ onExpand: function( $parent ) {$parent.siblings().find('.expanded').click()}});
		that.treePopup.div
			.find('form:first').submit(function(){
				var ids = [];

				jQuery(this).find(':checkbox:checked').each(function(){
					var label_name = jQuery(this).siblings('label').attr('name');
					if(label_name.indexOf('record_') == 0){
						ids.push(label_name.substring(7));
					}
				});
				if (ids.length) that.addValue( ids );
				jQuery('#'+that.treePopupId).hide();
				return false;
			});

		// For large trees, keeping this in memory can cause performance issues, so we'll set it to null
		// and use thisModelSearcher.treePopupId when we need it.
		that.treePopup = null;
	};

	this.addValue = function( ids ) {
		var that = thisModelSearcher,
			i,
			names = [],
			ids = ids || [],
			test = document.getElementById(that.bRowID),
			$bRow = test ? $(test) : jQuery("

").insertAfter(jQuery(that.cRowSelector)).find('#' + that.bRowID);

		for(i in ids){
			if ( !document.getElementById('bin_item_' + ids[i]) ) {
				that.selectedObjects.push(that.objectList[ids[i]]);
				names.push(
					that.binItemTemplate
						.replace('{content}', that.objectList[ids[i]].name)
						.replace('{id}', ids[i])
				);
			}
		}
		that.hiddenIdInput[0].value += ',' + ids.join(',');
		$bRow.append(names.join(''));
		that.autocompleteInput.val('');
		this.checkAnnotationState();
	}

	this.checkAnnotationState = function() {
		if ( jQuery('.tree-names').length > 1 ) {
			jQuery('#media_category_association_string_value, #media_category_association_numeric_value').attr('disabled', 'disabled').closest('tr').fadeOut();
		} else {
			jQuery('.annotation').fadeIn().find('#media_category_association_string_value, #media_category_association_numeric_value').removeAttr('disabled');
		}
	}

	this.resetFields = function(){
		this.autocompleteInput.val('');
		this.hiddenIdInput.val('');
		if(this.hasTree){
			this.treeNames.html('');
			this.treeRemove.hide();
			jQuery('#'+this.treePopupId).hide();
		}
	};

	this.autocompleteFormatItem = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatMatch = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatResult = function(item, i, max){
		return item.id;
	};
	var thisModelSearcher = this;
	this.autocompleteCallback = function(event, data, formatted) {
		if(data){
			thisModelSearcher.addValue([data.id])
		}else{
			//thisModelSearcher.hiddenIdInput.val('');
		}

		//thisModelSearcher.treeNames.html('');
		// thisModelSearcher.treeRemove.hide();
		return false;
	};

	this.createTreeFromArray = function(arr){
		var html = '';
		if(arr && arr.category){
			html += '
';
			if(arr.category && arr.category[0]){
				for(var i in arr.category) {
					html += '
';
					html += '<input type="checkbox" class="toggle">'+arr.category[i].title+'';
					if(arr.category[i].categories){
						html += this.createTreeFromArray(arr.category[i].categories);
					}
					html += '
';
				}
			}else if(arr.category){
				html += '
';
				html += '<input type="checkbox" class="toggle">'+arr.category.title+'';
				if(arr.category.categories){
					html += this.createTreeFromArray(arr.category.categories);
				}
				html += '
';
			}
			html += '
';
		}
		return html;
	}

};

function reinit() {
	var el = document.getElementById('root_topics'),
		id = el.value,
		label = el.options[el.selectedIndex].text;

	if ( id == 'All' ) {
		all_searcher();
	} else {
		searcher = new ModelSearcher();
		tmb_options['hasTree'] = true;
		tmb_options['fieldLabel'] = label;
		searcher.init( tmb_div, list_url.replace('{id}', id), all_url.replace('{id}', id), tmb_options);
	}
};<|endoftext|>


<commit_before>'use strict';

angular.module('mage.mapService', ['mage.***REMOVED***s', 'mage.lib'])
  .factory('MapService', ['appConstants', 'mageLib',
    function (appConstants, mageLib) {
      var functions = {};
      var currentMapPanel = "layers"; // options are: layers, observation, export, or none

      functions.getCurrentMapPanel = function () {
        console.log("Sending back the current map panel " + currentMapPanel);
        return currentMapPanel;
      };

      functions.setCurrentMapPanel = function (mapPanel) {
        currentMapPanel = mapPanel;
      };

      return functions;
    }]) // end of MapService<commit_msg>added in some thoughts<commit_after>'use strict';

angular.module('mage.mapService', ['mage.***REMOVED***s', 'mage.lib'])
  .factory('MapService', ['appConstants', 'mageLib',
    function (appConstants, mageLib) {
      var functions = {};
      var currentMapPanel = "layers"; // options are: layers, observation, export, or none

      functions.getCurrentMapPanel = function () {
        console.log("Sending back the current map panel " + currentMapPanel);
        return currentMapPanel;
      };

      functions.setCurrentMapPanel = function (mapPanel) {
        currentMapPanel = mapPanel;
      };

      return functions;
    }]); // end of MapService

  /* Barela idea */
  /*
angular.module('mage.mapService', ['mage.***REMOVED***s', 'mage.lib'])
  .factory('MapService', ['appConstants', 'mageLib',
    function (appConstants, mageLib) {
      var ***REMOVED*** = {
        currentMapPanel: 'layers' // options are: layers, observation, export, or none
      };
      // now in your controller you can just access MapService.currentMapPanel.  The controller
      // will be able to watch that variable fine if you attach the ***REMOVED*** to a scope variable ie
      // $scope.mapService = MapService; (after injecting that of course)
      return ***REMOVED***;
    }]);
    */<|endoftext|>


<commit_before>coinpunk.controllers.Tx = function() {};
coinpunk.controllers.Tx.prototype = new coinpunk.Controller();

coinpunk.controllers.Tx.prototype.details = function(txHash) {
  $.get('/api/tx/details', {txHashes: [txHash]}, function(resp) {
    coinpunk.router.render('view', 'tx/details', {tx: resp[0]}, function(id) {
      $('#'+id+" [rel='tooltip']").tooltip();
    });
  });
};

coinpunk.controllers.Tx.prototype.send = function() {
  var self = this;
  this.getUnspent(function(resp) {
    coinpunk.router.render('view', 'tx/send', resp, function(id) {
      self.updateExchangeRates(id, false);
      $('#'+id+" [rel='tooltip']").tooltip();
    });
  });
};

coinpunk.controllers.Tx.prototype.create = function() {
  var self = this;
  var sendButton = $('#sendButton');
  sendButton.addClass('disabled');
  var address = $('#createSendForm #address').val();
  var amount = $('#createSendForm #amount').val();
  var errors = [];
  var errorsDiv = $('#errors');

  errorsDiv.addClass('hidden');
  errorsDiv.html('');

  if(address == '')
    errors.push('You cannot have a blank sending address.');
  else {
    try {
      new Bitcoin.Address(address, coinpunk.config.network);
    } catch (e) {
      errors.push('The provided bitcoin address is not valid.');
    }
  }

  if(amount == '' || parseFloat(amount) == 0)
    errors.push('You must have a valid amount to send.');
  else if(/^[0-9]+$|^[0-9]+\.[0-9]+$|^\.[0-9]+$/.exec(amount) === null)
    errors.push('You must have a valid amount to send.');

  if(errors.length > 0) {
    this.displayErrors(errors, errorsDiv);
    sendButton.removeClass('disabled');
    return;
  }

  this.getUnspent(function(resp) {
    if(resp.amount < amount) {
      errors.push('Cannot spend more bitcoins than you currently have.');
      self.displayErrors(errors, errorsDiv);
      sendButton.removeClass('disabled');
      return;
    }

    var changeAddress = coinpunk.wallet.createNewAddress('change', true);
    var rawtx = coinpunk.wallet.createSend(amount, '0', address, changeAddress);

    self.saveWallet({override: true, address: changeAddress}, function(response) {
      $.post('/api/tx/send', {tx: rawtx}, function(resp) {
        coinpunk.database.setSuccessMessage("Sent "+amount+" BTC to "+address+".");
        coinpunk.router.route('dashboard');
      });
    });
  });
};

coinpunk.controllers.Tx.prototype.displayErrors = function(errors, errorsDiv) {
  if(errors.length > 0) {
    errorsDiv.removeClass('hidden');

    for(var i=0; i<errors.length; i++) {
      $('#errors').html($('#errors').html() + errors[i]+'
');
    }
    return;
  }
};

coinpunk.controllers.tx = new coinpunk.controllers.Tx();<commit_msg>temporary stop-gap for bug sending to self<commit_after>coinpunk.controllers.Tx = function() {};
coinpunk.controllers.Tx.prototype = new coinpunk.Controller();

coinpunk.controllers.Tx.prototype.details = function(txHash) {
  $.get('/api/tx/details', {txHashes: [txHash]}, function(resp) {
    coinpunk.router.render('view', 'tx/details', {tx: resp[0]}, function(id) {
      $('#'+id+" [rel='tooltip']").tooltip();
    });
  });
};

coinpunk.controllers.Tx.prototype.send = function() {
  var self = this;
  this.getUnspent(function(resp) {
    coinpunk.router.render('view', 'tx/send', resp, function(id) {
      self.updateExchangeRates(id, false);
      $('#'+id+" [rel='tooltip']").tooltip();
    });
  });
};

coinpunk.controllers.Tx.prototype.create = function() {
  var self = this;
  var sendButton = $('#sendButton');
  sendButton.addClass('disabled');
  var address = $('#createSendForm #address').val();
  var amount = $('#createSendForm #amount').val();
  var errors = [];
  var errorsDiv = $('#errors');

  errorsDiv.addClass('hidden');
  errorsDiv.html('');

  if(address == '')
    errors.push('You cannot have a blank sending address.');
  else {
    try {
      new Bitcoin.Address(address, coinpunk.config.network);
    } catch (e) {
      errors.push('The provided bitcoin address is not valid.');
    }
  }

  var myAddresses = coinpunk.wallet.addresses();

  for(var i=0; i<myAddresses.length;i++) {
    if(myAddresses[i].address == address)
      errors.push('You cannot send to your own bitcoin wallet.');
  }

  if(amount == '' || parseFloat(amount) == 0)
    errors.push('You must have a valid amount to send.');
  else if(/^[0-9]+$|^[0-9]+\.[0-9]+$|^\.[0-9]+$/.exec(amount) === null)
    errors.push('You must have a valid amount to send.');

  if(errors.length > 0) {
    this.displayErrors(errors, errorsDiv);
    sendButton.removeClass('disabled');
    return;
  }

  this.getUnspent(function(resp) {
    if(resp.amount < amount) {
      errors.push('Cannot spend more bitcoins than you currently have.');
      self.displayErrors(errors, errorsDiv);
      sendButton.removeClass('disabled');
      return;
    }

    var changeAddress = coinpunk.wallet.createNewAddress('change', true);
    var rawtx = coinpunk.wallet.createSend(amount, '0', address, changeAddress);

    self.saveWallet({override: true, address: changeAddress}, function(response) {
      $.post('/api/tx/send', {tx: rawtx}, function(resp) {
        coinpunk.database.setSuccessMessage("Sent "+amount+" BTC to "+address+".");
        coinpunk.router.route('dashboard');
      });
    });
  });
};

coinpunk.controllers.Tx.prototype.displayErrors = function(errors, errorsDiv) {
  if(errors.length > 0) {
    errorsDiv.removeClass('hidden');

    for(var i=0; i<errors.length; i++) {
      $('#errors').html($('#errors').html() + errors[i]+'
');
    }
    return;
  }
};

coinpunk.controllers.tx = new coinpunk.controllers.Tx();<|endoftext|>


<commit_before>var chats_cb;
var entityAdded_cb;
var ownerCall_cb;
function updatesListener() {

    function regFalsify(regObject) {
        if (!(regObject.feed || regObject.notifications))
            regObject = false;
        return regObject;
    }

    // turn off previous listener
    DB.child("users/"+userUuid+"/updates").off();

    // listen to Updates
    DB.child("users/"+userUuid+"/updates").on('value', function (entitiesUpdates) {
        // search inside entities
        entitiesUpdates.forEach(function (entityUpdates) {
            // search inside entity
            entityUpdates.forEach(function (entityUpdate) {
                var isNewSubEntityReg = {
                    feed: entityUpdate.child('feed/newSubEntity').exists(),
                    notifications: entityUpdate.child('notifications/newSubEntity').exists()
                };

                var isOwnerCallReg = {
                    feed: entityUpdate.child('feed/ownerCalls').exists(),
                    notifications: entityUpdate.child('notifications/ownerCalls').exists()
                    };

                var isChatReg = {
                    feed: entityUpdate.child('feed/chats').exists(),
                    notifications: entityUpdate.child('notifications/chats').exists()
                };

                isOwnerCallReg = regFalsify(isOwnerCallReg);
                isNewSubEntityReg = regFalsify(isNewSubEntityReg);
                isChatReg = regFalsify(isChatReg);

                // if subscribed to ownerCalls
                if (isOwnerCallReg) {
                    DB.child(entityUpdates.key + "/" + entityUpdate.key + "/ownerCalls").orderByChild('dateAdded').limitToLast(1).on('child_added',ownerCall_cb = function (ownerCall) {

                        // ==== regulation chunk ==== //
                        // will make sure we will get the latest whatever..
                        if (mostUpdatedContent == null) {
                            mostUpdatedContent = ownerCall;
                            // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                        }
                        else if (mostUpdatedContent.val().dateAdded < ownerCall.val().dateAdded - 400)
                        {
                            mostUpdatedContent = ownerCall;
                            // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                        }
                        else
                            return;
                        // ============================================================================

                            DB.child(entityUpdates.key + "/" + entityUpdate.key).once('value', function (actualContent) {
                                if(isOwnerCallReg.notifications)
                                    pushNotification(actualContent, "ownerCalls", ownerCall.val().callText);

                                if(isOwnerCallReg.feed)
                                    feedBuilder(actualContent, "ownerCalls", ownerCall.val().callText);
                            });
                    });
                }

                // check if sub-entity added, only if registered to Global or Feed. if not registered fo both - move on

                if (isNewSubEntityReg) {
                    DB.child(entityUpdates.key + "/" + entityUpdate.key + "/" + subEntity[entityUpdates.key]).orderByChild('dateAdded').limitToLast(1).on('child_added', entityAdded_cb = function (entityAddedUid) {
                        DB.child(subEntity[entityUpdates.key] + "/" + entityAddedUid.key).once('value', function (actualContent) {

                            console.log("actualContent: " + entityAddedUid.val().dateAdded);

                            // ==== regulation chunk ==== //
                            // will make sure we will get the latest whatever..
                            if (mostUpdatedContent == null) {
                                mostUpdatedContent = entityAddedUid;
                                // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                            }
                            else if (mostUpdatedContent.val().dateAdded < entityAddedUid.val().dateAdded - 400)
                            {
                                mostUpdatedContent = entityAddedUid;
                                // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                            }
                            else
                                return;
                            // ============================================================================

                            if (isNewSubEntityReg.notifications)
                                pushNotification(actualContent, subEntity[entityUpdates.key]);

                            if (isNewSubEntityReg.feed)
                                feedBuilder(actualContent, entityUpdates.key);

                        }); //.catch(function (error) { console.log(error, "no entity path") })
                    });
                }

                // chat logic

                if(isChatReg) {
                    // check if added message, get last message by date
                    DB.child("chats/" + entityUpdate.key + "/messages").orderByChild('dateAdded').limitToLast(1).on('child_added', chats_cb = function (lastMessage) {
                        // get inbox unseen messages counter
                        DB.child("users/" + userUuid + "/chatInboxes/" + entityUpdate.key).once('value', function (inboxVolume) {
                            // now we need the actual content of the entity related to current chatRoom, note that chat updates bound to groups only..
                            DB.child("/groups/" + entityUpdate.key).once('value', function (chatEntityContent) {
                                // don't bring up notificaions and nor count them if already inside subscribed chat room
                                if(!(activeEntity.entity == "chats" && activeEntity.uid == entityUpdate.key)) {
                                    // if no such group, get out

                                    if (chatEntityContent == null)
                                        return;

                                    // ==== regulation chunk ==== //
                                    // will make sure we will get the latest whatever..
                                    if (mostUpdatedContent == null) {
                                        mostUpdatedContent = lastMessage;
                                        // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                                    }
                                    else if (mostUpdatedContent.val().dateAdded < lastMessage.val().dateAdded - 400)
                                    {
                                        mostUpdatedContent = lastMessage;
                                        // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                                    }
                                    else
                                        return;
                                    // ============================================================================

                                    // create a temporary messagesSentInc to hold inboxMessages.val()
                                    var messagesSentInc;

                                    // now we need the inboxMessages to get the number of messages not seen
                                    messagesSentInc = inboxVolume.val();

                                    // increment inbox volume
                                    if (firstRun) {
                                        firstRun = false;
                                        return;
                                    }

                                    // obvious incrementation, is obvious..
                                    messagesSentInc++;

                                    //set incremented inbox volume
                                    DB.child("users/" + userUuid + "/chatInboxes/" + entityUpdate.key).set(messagesSentInc);

                                    // send notifications in jumps of 5, might want to consider further manipulations. currently unused.
                                    if (messagesSentInc % 5 ===  0) {
                                        if (isChatReg.notifications)
                                            pushNotification(chatEntityContent, "chats", messagesSentInc);
                                        if (isChatReg.feed)
                                            feedBuilder(chatEntityContent,"chats", messagesSentInc);
                                    }
                                }
                            });
                        });
                    });
                }
            });
        });
    });
}

// feed builder
function feedBuilder (entityDatum, entityType, variation) {

    switch (entityType) {
        case "chats":
            feedManager.queue.push( {
                    roomName: entityDatum.val().title,
                    chatMessagesCounter: variation,
                    date: entityDatum.val().dateAdded
            });

            break;

        case "ownerCalls":
            feedManager.queue.push( {
                roomName: entityDatum.val().title,
                callText: variation,
                date: entityDatum.val().dateAdded
            });

            break;

        default:
            feedManager.queue.push({
                title: entityDatum.val().title,
                description: entityDatum.val().description,
                date: entityDatum.val().dateAdded
            });

            // if feedVolume got to 20, also remove last feed in feedQueue
            if(Object.keys(feedManager.queue).length >= feedManager.volume + 1)
                feedManager.queue.pop();

            break;
    }

    feedManager.promise = Promise.resolve(true);

    console.dir(feedManager.queue, feedManager.promise);

}

<commit_msg>feed queue jsons expanded<commit_after>var chats_cb;
var entityAdded_cb;
var ownerCall_cb;
function updatesListener() {

    function regFalsify(regObject) {
        if (!(regObject.feed || regObject.notifications))
            regObject = false;
        return regObject;
    }

    // turn off previous listener
    DB.child("users/"+userUuid+"/updates").off();

    // listen to Updates
    DB.child("users/"+userUuid+"/updates").on('value', function (entitiesUpdates) {
        // search inside entities
        entitiesUpdates.forEach(function (entityUpdates) {
            // search inside entity
            entityUpdates.forEach(function (entityUpdate) {
                var isNewSubEntityReg = {
                    feed: entityUpdate.child('feed/newSubEntity').exists(),
                    notifications: entityUpdate.child('notifications/newSubEntity').exists()
                };

                var isOwnerCallReg = {
                    feed: entityUpdate.child('feed/ownerCalls').exists(),
                    notifications: entityUpdate.child('notifications/ownerCalls').exists()
                    };

                var isChatReg = {
                    feed: entityUpdate.child('feed/chats').exists(),
                    notifications: entityUpdate.child('notifications/chats').exists()
                };

                isOwnerCallReg = regFalsify(isOwnerCallReg);
                isNewSubEntityReg = regFalsify(isNewSubEntityReg);
                isChatReg = regFalsify(isChatReg);

                // if subscribed to ownerCalls
                if (isOwnerCallReg) {
                    DB.child(entityUpdates.key + "/" + entityUpdate.key + "/ownerCalls").orderByChild('dateAdded').limitToLast(1).on('child_added',ownerCall_cb = function (ownerCall) {

                        // ==== regulation chunk ==== //
                        // will make sure we will get the latest whatever..
                        if (mostUpdatedContent == null) {
                            mostUpdatedContent = ownerCall;
                            // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                        }
                        else if (mostUpdatedContent.val().dateAdded < ownerCall.val().dateAdded - 400)
                        {
                            mostUpdatedContent = ownerCall;
                            // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                        }
                        else
                            return;
                        // ============================================================================

                            DB.child(entityUpdates.key + "/" + entityUpdate.key).once('value', function (actualContent) {
                                if(isOwnerCallReg.notifications)
                                    pushNotification(actualContent, "ownerCalls", ownerCall.val().callText);

                                if(isOwnerCallReg.feed)
                                    feedBuilder(actualContent, entityUpdate.key, "ownerCalls", ownerCall.val().callText);
                            });
                    });
                }

                // check if sub-entity added, only if registered to Global or Feed. if not registered fo both - move on

                if (isNewSubEntityReg) {
                    DB.child(entityUpdates.key + "/" + entityUpdate.key + "/" + subEntity[entityUpdates.key]).orderByChild('dateAdded').limitToLast(1).on('child_added', entityAdded_cb = function (entityAddedUid) {
                        DB.child(subEntity[entityUpdates.key] + "/" + entityAddedUid.key).once('value', function (actualContent) {

                            console.log("actualContent: " + entityAddedUid.val().dateAdded);

                            // ==== regulation chunk ==== //
                            // will make sure we will get the latest whatever..
                            if (mostUpdatedContent == null) {
                                mostUpdatedContent = entityAddedUid;
                                // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                            }
                            else if (mostUpdatedContent.val().dateAdded < entityAddedUid.val().dateAdded - 400)
                            {
                                mostUpdatedContent = entityAddedUid;
                                // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                            }
                            else
                                return;
                            // ============================================================================

                            if (isNewSubEntityReg.notifications)
                                pushNotification(actualContent, subEntity[entityUpdates.key]);

                            if (isNewSubEntityReg.feed)
                                feedBuilder(actualContent, entityUpdate.key, entityUpdates.key);

                        }); //.catch(function (error) { console.log(error, "no entity path") })
                    });
                }

                // chat logic

                if(isChatReg) {
                    // check if added message, get last message by date
                    DB.child("chats/" + entityUpdate.key + "/messages").orderByChild('dateAdded').limitToLast(1).on('child_added', chats_cb = function (lastMessage) {
                        // get inbox unseen messages counter
                        DB.child("users/" + userUuid + "/chatInboxes/" + entityUpdate.key).once('value', function (inboxVolume) {
                            // now we need the actual content of the entity related to current chatRoom, note that chat updates bound to groups only..
                            DB.child("/groups/" + entityUpdate.key).once('value', function (chatEntityContent) {
                                // don't bring up notificaions and nor count them if already inside subscribed chat room
                                if(!(activeEntity.entity == "chats" && activeEntity.uid == entityUpdate.key)) {
                                    // if no such group, get out

                                    if (chatEntityContent == null)
                                        return;

                                    // ==== regulation chunk ==== //
                                    // will make sure we will get the latest whatever..
                                    if (mostUpdatedContent == null) {
                                        mostUpdatedContent = lastMessage;
                                        // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                                    }
                                    else if (mostUpdatedContent.val().dateAdded < lastMessage.val().dateAdded - 400)
                                    {
                                        mostUpdatedContent = lastMessage;
                                        // console.log("mostUpdatedContent: " + mostUpdatedContent.val().dateAdded);
                                    }
                                    else
                                        return;
                                    // ============================================================================

                                    // create a temporary messagesSentInc to hold inboxMessages.val()
                                    var messagesSentInc;

                                    // now we need the inboxMessages to get the number of messages not seen
                                    messagesSentInc = inboxVolume.val();

                                    // increment inbox volume
                                    if (firstRun) {
                                        firstRun = false;
                                        return;
                                    }

                                    // obvious incrementation, is obvious..
                                    messagesSentInc++;

                                    //set incremented inbox volume
                                    DB.child("users/" + userUuid + "/chatInboxes/" + entityUpdate.key).set(messagesSentInc);

                                    // send notifications in jumps of 5, might want to consider further manipulations. currently unused.
                                    if (messagesSentInc % 5 ===  0) {
                                        if (isChatReg.notifications)
                                            pushNotification(chatEntityContent, "chats", messagesSentInc);
                                        if (isChatReg.feed)
                                            feedBuilder(chatEntityContent, entityUpdate.key, "chats", messagesSentInc);
                                    }
                                }
                            });
                        });
                    });
                }
            });
        });
    });
}

// feed builder
function feedBuilder (entityDatum, entityUid, entityType, variation) {

    switch (entityType) {
        case "chats":
            feedManager.queue.push({
                roomName: entityDatum.val().title,
                chatMessagesCounter: variation,
                uid: entityUid,
                entityType: entityType,
                date: entityDatum.val().dateAdded
            });

            break;

        case "ownerCalls":
            feedManager.queue.push({
                roomName: entityDatum.val().title,
                callText: variation,
                uid: entityUid,
                entityType: entityType,
                date: entityDatum.val().dateAdded
            });

            break;

        default:
            feedManager.queue.push({
                title: entityDatum.val().title,
                description: entityDatum.val().description,
                uid: entityUid,
                entityType: entityType,
                date: entityDatum.val().dateAdded
            });

            // if feedVolume got to 20, also remove last feed in feedQueue
            if(Object.keys(feedManager.queue).length >= feedManager.volume + 1)
                feedManager.queue.pop();

            break;
    }

    feedManager.promise = Promise.resolve(true);

    console.dir(feedManager.queue, feedManager.promise);

}

<|endoftext|>


<commit_before>'use strict';

var globalTemplate = '

';
// Declare app level module which depends on filters, and services
var kdig = angular.module('KdigApp', [
//        'ui.compat',
        'KdigApp.filters',
//        'KdigApp.services',
        'KdigApp.directives',
        'KdigApp.controllers',
        'http-auth-interceptor',
        'ui.router'
            ])
            .constant('prefix', '/app_dev.php')
            .config([
                '$stateProvider',
                '$routeProvider',
                '$urlRouterProvider',
                '$locationProvider',
                '$httpProvider',
                'prefix',
                function($stateProvider, $routeProvider, $urlRouterProvider, $locationProvider, $httpProvider, prefix) {
                    fos.Router.getInstance().setBaseUrl(prefix);
                    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
                    $locationProvider.html5Mode(true).hashPrefix('!');

                    $stateProvider
                        .state('example', {
                            url: '/example',
                            template: globalTemplate,
//                            templateUrl: function(params) { return Routing.generate('index') },
                            controller: 'KdigApp.example',
//                            resolve: Resolver
                        });
                }
            ])
            ;
    /*
    config([
        '$stateProvider',
        '$routeProvider',
        '$urlRouterProvider',
        '$locationProvider',
        '$httpProvider',
        'prefix',
        function($stateProvider, $routeProvider, $urlRouterProvider, $locationProvider, $httpProvider, prefix) {

            fos.Router.getInstance().setBaseUrl(prefix);
            $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
            $locationProvider.html5Mode(true).hashPrefix('!');

            $stateProvider

                .state('home', {
                    url: '/',
                    template: globalTemplate,
                    templateUrl: function(params) { return Routing.generate('index') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us', {
                    url: '/us',
                    abstract: true,
                    template: globalTemplate,
                    templateUrl: function(params) { return Routing.generate('us') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us', {
                    url: '/home',
                    templateUrl: function(params) { return Routing.generate('us') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.show', {
                    url: '/show/:id',
                    templateUrl: function(params) { return Routing.generate('us_show', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.list', {
                    url: '/list',
                    templateUrl: function(params) { return Routing.generate('us_list') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.new', {
                    url: '/new',
                    templateUrl: function(params) { return Routing.generate('us_new', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.edit', {
                    url: '/edit/:id',
                    templateUrl: function(params) { return Routing.generate('us_edit', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.delete', {
                    url: '/delete/:id',
                    templateUrl: function(params) { return Routing.generate('us_delete', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                });
        }
    ]);*/
            /*.
    run(function($rootScope, $state) {
        $rootScope.$on('event:auth-loginRequired', function() {
            $state.transitionTo('demologin');
        });
    });
    /*
var kdigApp = angular.module('KdigApp', []).config(function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    }
);

kdigApp.controller('mainCtrl', ['$scope', function ($scope) {

}]);
kdigApp.controller('navCtrl', ['$scope', function ($scope) {

}]);
kdigApp.controller('userCtrl', ['$scope', function ($scope) {

}]);
*/<commit_msg>angular<commit_after>'use strict';

var globalTemplate = '

';
// Declare app level module which depends on filters, and services
var kdig = angular.module('KdigApp', [
        'ui.compat',
        'KdigApp.filters',
//        'KdigApp.services',
        'KdigApp.directives',
        'KdigApp.controllers',
        'http-auth-interceptor',
        'ui.router',
        'http-auth-interceptor'
            ])
            .constant('prefix', '/app_dev.php')
            .config([
                '$stateProvider',
                '$routeProvider',
                '$urlRouterProvider',
                '$locationProvider',
                '$httpProvider',
                'prefix',
                function($stateProvider, $routeProvider, $urlRouterProvider, $locationProvider, $httpProvider, prefix) {
                    fos.Router.getInstance().setBaseUrl(prefix);
                    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
                    $locationProvider.html5Mode(true).hashPrefix('!');

                    $stateProvider
                        .state('example', {
                            url: '/example',
                            template: globalTemplate,
//                            templateUrl: function(params) { return Routing.generate('index') },
                            controller: 'KdigApp.example',
//                            resolve: Resolver
                        });
                }
            ])
            ;
    /*
    config([
        '$stateProvider',
        '$routeProvider',
        '$urlRouterProvider',
        '$locationProvider',
        '$httpProvider',
        'prefix',
        function($stateProvider, $routeProvider, $urlRouterProvider, $locationProvider, $httpProvider, prefix) {

            fos.Router.getInstance().setBaseUrl(prefix);
            $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
            $locationProvider.html5Mode(true).hashPrefix('!');

            $stateProvider

                .state('home', {
                    url: '/',
                    template: globalTemplate,
                    templateUrl: function(params) { return Routing.generate('index') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us', {
                    url: '/us',
                    abstract: true,
                    template: globalTemplate,
                    templateUrl: function(params) { return Routing.generate('us') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us', {
                    url: '/home',
                    templateUrl: function(params) { return Routing.generate('us') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.show', {
                    url: '/show/:id',
                    templateUrl: function(params) { return Routing.generate('us_show', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.list', {
                    url: '/list',
                    templateUrl: function(params) { return Routing.generate('us_list') },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.new', {
                    url: '/new',
                    templateUrl: function(params) { return Routing.generate('us_new', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.edit', {
                    url: '/edit/:id',
                    templateUrl: function(params) { return Routing.generate('us_edit', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                })
                .state('us.delete', {
                    url: '/delete/:id',
                    templateUrl: function(params) { return Routing.generate('us_delete', params) },
//                    controller: LogoutCtrl,
                    resolve: Resolver
                });
        }
    ]);*/
            /*.
    run(function($rootScope, $state) {
        $rootScope.$on('event:auth-loginRequired', function() {
            $state.transitionTo('demologin');
        });
    });
    /*
var kdigApp = angular.module('KdigApp', []).config(function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    }
);

kdigApp.controller('mainCtrl', ['$scope', function ($scope) {

}]);
kdigApp.controller('navCtrl', ['$scope', function ($scope) {

}]);
kdigApp.controller('userCtrl', ['$scope', function ($scope) {

}]);
*/<|endoftext|>


<commit_before>const MachinaFFXIV = require('node-machina-ffxiv');
const isDev = require('electron-is-dev');
const path = require('path');
const { app } = require('electron');
const log = require('electron-log');
const isElevated = require('is-elevated');
const { exec } = require('child_process');

const machinaExePath = path.join(app.getAppPath(), '../../resources/MachinaWrapper/MachinaWrapper.exe');

let Machina;

function sendToRenderer(win, packet) {
  win && win.webContents && win.webContents.send('packet', packet);
}

module.exports.start = function(win, config, verbose, winpcap) {
  isElevated().then(elevated => {
    log.info('elevated', elevated);
    if (elevated) {
      exec(`netsh advfirewall firewall add rule name="FFXIVTeamcraft" dir=in action=allow program="${machinaExePath}" enable=yes`);

      const options = isDev ?
        {
          monitorType: winpcap ? 'WinPCap' : 'RawSocket',
          parseAlgorithm: 'PacketSpecific'
        } : {
          parseAlgorithm: 'PacketSpecific',
          noData: true,
          monitorType: winpcap ? 'WinPCap' : 'RawSocket',
          machinaExePath: machinaExePath,
          remoteDataPath: path.join(app.getAppPath(), '../../resources/remote-data'),
          definitionsDir: path.join(app.getAppPath(), '../../resources/app.asar.unpacked/node_modules/node-machina-ffxiv/models/default')
        };

      if (verbose) {
        options.logger = log.log;
      }

      const acceptedPackets = [
        'statusEffectList',
        'itemInfo',
        'updateInventorySlot',
        'currencyCrystalInfo',
        'marketBoardItemListingCount',
        'marketBoardItemListing',
        'marketBoardItemListingHistory',
        'marketTaxRates',
        'playerSetup',
        'playerSpawn',
        'inventoryModifyHandler',
        'npcSpawn',
        'ping',
        'playerStats',
        'updateClassInfo',
        'actorControl',
        'initZone',
        'weatherChange',
        'aetherReductionDlg',
        'desynthOrReductionResult',
        'persistentEffect',
        'effectResult',
        'eventPlay',
        'eventStart',
        'eventFinish',
        'eventUnk0',
        'updatePositionHandler'
      ];

      Machina = new MachinaFFXIV(options);
      Machina.filter(acceptedPackets);
      Machina.start(() => {
        log.info('Packet capture started');
      });
      Machina.setMaxListeners(0);
      Machina.on('any', (packet) => {
        if (verbose) {
          log.log(JSON.stringify(packet));
        }
        if (acceptedPackets.indexOf(packet.type) > -1 || acceptedPackets.indexOf(packet.superType) > -1) {
          sendToRenderer(win, packet);
        }
      });
    } else {
      throw new Error('Not enough permissions to run packet capture');
    }
  });

};

module.exports.stop = function() {
  if (Machina) {
    Machina.stop();
  }
};
<commit_msg>chore: add misses to fishing data gathering<commit_after>const MachinaFFXIV = require('node-machina-ffxiv');
const isDev = require('electron-is-dev');
const path = require('path');
const { app } = require('electron');
const log = require('electron-log');
const isElevated = require('is-elevated');
const { exec } = require('child_process');

const machinaExePath = path.join(app.getAppPath(), '../../resources/MachinaWrapper/MachinaWrapper.exe');

let Machina;

function sendToRenderer(win, packet) {
  win && win.webContents && win.webContents.send('packet', packet);
}

module.exports.start = function(win, config, verbose, winpcap) {
  isElevated().then(elevated => {
    log.info('elevated', elevated);
    if (elevated) {
      exec(`netsh advfirewall firewall add rule name="FFXIVTeamcraft" dir=in action=allow program="${machinaExePath}" enable=yes`);

      const options = isDev ?
        {
          monitorType: winpcap ? 'WinPCap' : 'RawSocket',
          parseAlgorithm: 'PacketSpecific'
        } : {
          parseAlgorithm: 'PacketSpecific',
          noData: true,
          monitorType: winpcap ? 'WinPCap' : 'RawSocket',
          machinaExePath: machinaExePath,
          remoteDataPath: path.join(app.getAppPath(), '../../resources/remote-data'),
          definitionsDir: path.join(app.getAppPath(), '../../resources/app.asar.unpacked/node_modules/node-machina-ffxiv/models/default')
        };

      if (verbose) {
        options.logger = log.log;
      }

      const acceptedPackets = [
        'statusEffectList',
        'itemInfo',
        'updateInventorySlot',
        'currencyCrystalInfo',
        'marketBoardItemListingCount',
        'marketBoardItemListing',
        'marketBoardItemListingHistory',
        'marketTaxRates',
        'playerSetup',
        'playerSpawn',
        'inventoryModifyHandler',
        'npcSpawn',
        'ping',
        'playerStats',
        'updateClassInfo',
        'actorControl',
        'initZone',
        'weatherChange',
        'aetherReductionDlg',
        'desynthOrReductionResult',
        'persistentEffect',
        'effectResult',
        'eventPlay',
        'eventStart',
        'eventFinish',
        'eventUnk0',
        'eventUnk1',
        'updatePositionHandler'
      ];

      Machina = new MachinaFFXIV(options);
      Machina.filter(acceptedPackets);
      Machina.start(() => {
        log.info('Packet capture started');
      });
      Machina.setMaxListeners(0);
      Machina.on('any', (packet) => {
        if (verbose) {
          log.log(JSON.stringify(packet));
        }
        if (acceptedPackets.indexOf(packet.type) > -1 || acceptedPackets.indexOf(packet.superType) > -1) {
          sendToRenderer(win, packet);
        }
      });
    } else {
      throw new Error('Not enough permissions to run packet capture');
    }
  });

};

module.exports.stop = function() {
  if (Machina) {
    Machina.stop();
  }
};
<|endoftext|>


<commit_before>import { moduleForComponent } from 'ember-qunit';
import { skip } from 'qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('curriculum-inventory-sequence-block-list', 'Integration | Component | curriculum inventory sequence block list', {
  integration: true
});

skip('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{curriculum-inventory-sequence-block-list}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#curriculum-inventory-sequence-block-list}}
      template block text
    {{/curriculum-inventory-sequence-block-list}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});
<commit_msg>integration test for seq block list component.<commit_after>import Ember from 'ember';
import { moduleForComponent } from 'ember-qunit';
import { test } from 'qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';
import moment from 'moment';
import tHelper from "ember-i18n/helper";

const { RSVP, Object } = Ember;
const { resolve } = RSVP;

moduleForComponent('curriculum-inventory-sequence-block-list', 'Integration | Component | curriculum inventory sequence block list', {
  integration: true,

  beforeEach: function () {
    this.container.lookup('service:i18n').set('locale', 'en');
    this.registry.register('helper:t', tHelper);
  }
});

test('it renders with top-level sequence blocks', function(assert) {
  assert.expect(25);

  let school = Object.create({ id() { return 1; }});

  let program = Object.create({
    belongsTo() {
      return school;
    }
  });

  let course = Object.create({
    id: 1,
    title: "Life Lessons",
  });

  let academicLevel1 = Object.create({ id: 1, level: '2'});
  let academicLevel2 = Object.create({ id: 2, level: '1'});

  let block1 = Object.create({
    id: 1,
    academicLevel: resolve(academicLevel1),
    title: 'Foo',
    startDate: new Date('2015-02-23'),
    endDate: new Date('2016-12-03'),
    course: resolve(course),
    orderInSequence: 0,
  });

  let block2 = Object.create({
    id: 2,
    academicLevel: resolve(academicLevel2),
    title: 'Bar',
    startDate: null,
    endDate: null,
    course: resolve(null),
    orderInSequence: 0,
  });

  let blocks = [block1, block2];

  let report = Object.create({
    academicLevels: resolve([]),
    year: '2016',
    program: resolve(program),
    linkedCourses: resolve([]),
    isFinalized: false,
    name: 'Lorem Ipsum',
    startDate: moment('2015-06-12').toDate(),
    endDate: moment('2016-04-11').toDate(),
    description: 'Lorem Ipsum',
    topLevelSequenceBlocks: resolve(blocks)
  });

  this.set('report', report);
  this.set('removeSequenceBlock', function() {});
  this.render(hbs`{{curriculum-inventory-sequence-block-list report=report remove='removeSequenceBlock'}}`);
  return wait().then(() => {
    assert.equal(this.$('.detail-title').text().trim(), `Sequence Blocks (${blocks.length})`,
      'Component title is correct, and show the correct number of blocks.'
    );
    assert.equal(this.$('.detail-actions .expand-button').length, 1, 'Add new button is visible.');

    assert.equal(this.$('thead th:eq(0)').text().trim(), 'Sequence Block', 'Table column header has correct label.');
    assert.equal(this.$('thead th:eq(1)').text().trim(), 'Level', 'Table column header has correct label.');
    assert.equal(this.$('thead th:eq(2)').text().trim(), 'Sequence #', 'Table column header has correct label.');
    assert.equal(this.$('thead th:eq(3)').text().trim(), 'Start Date', 'Table column header has correct label.');
    assert.equal(this.$('thead th:eq(4)').text().trim(), 'End Date', 'Table column header has correct label.');
    assert.equal(this.$('thead th:eq(5)').text().trim(), 'Course', 'Table column header has correct label.');
    assert.equal(this.$('thead th:eq(6)').text().trim(), 'Actions', 'Table column header has correct label.');

    assert.equal(this.$('tbody tr:eq(0) td:eq(0)').text().trim(), block2.get('title'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(1)').text().trim(), academicLevel2.get('level'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(2)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(0) td:eq(3)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(0) td:eq(4)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(0) td:eq(5)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(0) td:eq(6) .edit').length, 1, 'Edit link is visible.');
    assert.equal(this.$('tbody tr:eq(0) td:eq(6) .remove').length, 1, 'Remove link is visible.');

    assert.equal(this.$('tbody tr:eq(1) td:eq(0)').text().trim(), block1.get('title'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(1)').text().trim(), academicLevel1.get('level'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(2)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(1) td:eq(3)').text().trim(), moment(block1.get('startDate')).format('MM/DD/YY'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(4)').text().trim(), moment(block1.get('endDate')).format('MM/DD/YY'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(5)').text().trim(), course.get('title'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(6) .edit').length, 1, 'Edit link is visible.');
    assert.equal(this.$('tbody tr:eq(1) td:eq(6) .remove').length, 1, 'Remove link is visible.');

  });
});

test('it renders with nested blocks', function(assert) {
  assert.expect(18);

  let school = Object.create({ id() { return 1; }});

  let program = Object.create({
    belongsTo() {
      return school;
    }
  });

  let course = Object.create({
    id: 1,
    title: "Life Lessons",
  });

  let academicLevel1 = Object.create({ id: 1, level: '2'});
  let academicLevel2 = Object.create({ id: 2, level: '1'});

  let block1 = Object.create({
    id: 2,
    academicLevel: resolve(academicLevel1),
    title: 'Foo',
    startDate: new Date('2015-02-23'),
    endDate: new Date('2016-12-03'),
    course: resolve(course),
    orderInSequence: 1,
  });

  let block2 = Object.create({
    id: 3,
    academicLevel: resolve(academicLevel2),
    title: 'Bar',
    startDate: null,
    endDate: null,
    course: resolve(null),
    orderInSequence: 2,
  });

  let nestedBlocks = [block1, block2];

  let parentBlock = Object.create({
    id: 1,
    academicLevel: resolve(academicLevel1),
    title: 'Parent Block',
    course: resolve(null),
    isOrdered: true,
    children: resolve(nestedBlocks),
  });

  let report = Object.create({
    academicLevels: resolve([]),
    year: '2016',
    program: resolve(program),
    linkedCourses: resolve([]),
    isFinalized: false,
    name: 'Lorem Ipsum',
    startDate: moment('2015-06-12').toDate(),
    endDate: moment('2016-04-11').toDate(),
    description: 'Lorem Ipsum',
    topLevelSequenceBlocks: resolve([parentBlock]),
    sequenceBlocks: resolve([parentBlock, block1, block2])
  });

  parentBlock.set('report', resolve(report));
  block1.set('report', resolve(report));
  block1.set('parent', resolve(parentBlock));
  block2.set('report', resolve(report));
  block2.set('parent', resolve(parentBlock));

  this.set('parent', parentBlock);
  this.set('removeSequenceBlock', function() {});
  this.render(hbs`{{curriculum-inventory-sequence-block-list parent=parent remove='removeSequenceBlock'}}`);
  return wait().then(() => {
    assert.equal(this.$('.detail-title').text().trim(), `Sequence Blocks (${nestedBlocks.length})`,
      'Component title is correct, and show the correct number of nested blocks.'
    );
    assert.equal(this.$('.detail-actions .expand-button').length, 1, 'Add new button is visible.');

    assert.equal(this.$('tbody tr:eq(0) td:eq(0)').text().trim(), block1.get('title'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(1)').text().trim(), academicLevel1.get('level'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(2)').text().trim(), block1.get('orderInSequence'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(3)').text().trim(), moment(block1.get('startDate')).format('MM/DD/YY'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(4)').text().trim(), moment(block1.get('endDate')).format('MM/DD/YY'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(5)').text().trim(), course.get('title'));
    assert.equal(this.$('tbody tr:eq(0) td:eq(6) .edit').length, 1, 'Edit link is visible.');
    assert.equal(this.$('tbody tr:eq(0) td:eq(6) .remove').length, 1, 'Remove link is visible.');

    assert.equal(this.$('tbody tr:eq(1) td:eq(0)').text().trim(), block2.get('title'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(1)').text().trim(), academicLevel2.get('level'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(2)').text().trim(), block2.get('orderInSequence'));
    assert.equal(this.$('tbody tr:eq(1) td:eq(3)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(1) td:eq(4)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(1) td:eq(5)').text().trim(), 'n/a');
    assert.equal(this.$('tbody tr:eq(1) td:eq(6) .edit').length, 1, 'Edit link is visible.');
    assert.equal(this.$('tbody tr:eq(1) td:eq(6) .remove').length, 1, 'Remove link is visible.');

  });
});

test('finalized/read-only mode', function(assert){
  assert.expect(3);

  let school = Object.create({ id() { return 1; }});

  let program = Object.create({
    belongsTo() {
      return school;
    }
  });

  let block1 = Object.create({
    id: 1,
    academicLevel: resolve(Object.create({ id: 1, level: '2'})),
    title: 'Bar',
    startDate: new Date('2015-02-23'),
    endDate: new Date('2016-12-03'),
    course: resolve(null),
    orderInSequence: 0,
  });
  let report = Object.create({
    academicLevels: resolve([]),
    year: '2016',
    program: resolve(program),
    linkedCourses: resolve([]),
    isFinalized: true,
    name: 'Lorem Ipsum',
    startDate: moment('2015-06-12').toDate(),
    endDate: moment('2016-04-11').toDate(),
    description: 'Lorem Ipsum',
    topLevelSequenceBlocks: resolve([ block1 ])
  });

  this.set('report', report);
  this.set('removeSequenceBlock', function() {});
  this.render(hbs`{{curriculum-inventory-sequence-block-list report=report remove='removeSequenceBlock'}}`);
  return wait().then(() => {
    assert.equal(this.$('.detail-actions .expand-button').length, 0, 'Add new button is not visible.');
    assert.equal(this.$('tbody tr:eq(0) td:eq(6) .edit').length, 1, 'Edit link is visible.');
    assert.equal(this.$('tbody tr:eq(0) td:eq(6) .remove').length, 0, 'Remove link is not visible.');
  });
});

test('delete', function(assert){
  assert.expect(4);

  let school = Object.create({ id() { return 1; }});

  let program = Object.create({
    belongsTo() {
      return school;
    }
  });

  let block1 = Object.create({
    id: 1,
    academicLevel: resolve(Object.create({ id: 1, level: '2'})),
    title: 'Foo',
    startDate: new Date('2015-02-23'),
    endDate: new Date('2016-12-03'),
    course: resolve(null),
    orderInSequence: 0,
  });

  let report = Object.create({
    academicLevels: resolve([]),
    year: '2016',
    program: resolve(program),
    linkedCourses: resolve([]),
    isFinalized: false,
    name: 'Lorem Ipsum',
    startDate: moment('2015-06-12').toDate(),
    endDate: moment('2016-04-11').toDate(),
    description: 'Lorem Ipsum',
    topLevelSequenceBlocks: resolve([ block1 ])
  });

  this.set('report', report);
  this.on('removeSequenceBlock', function(block) {
    assert.equal(block, block1, 'Remove action was invoked, and sequence block was passed.');
    report.set('toLevelSequenceBlocks', resolve([ block1 ])); // fake deletion.
  });
  this.render(hbs`{{curriculum-inventory-sequence-block-list report=report remove='removeSequenceBlock'}}`);
  return wait().then(() => {
    this.$('tbody tr:eq(0) td:eq(6) .remove').click();
    assert.equal(this.$('tbody tr:eq(1) .confirm-message').text().trim().indexOf('Are you sure you want to delete'), 0,
      'Confirmation message is visible.');
    assert.equal(this.$('tbody tr:eq(1) .confirm-buttons .remove').length, 1,'Delete button is visible.');
    assert.equal(this.$('tbody tr:eq(1) .confirm-buttons .done').length, 1,'Cancel button is visible.');
    this.$('tbody tr:eq(1) .confirm-buttons .remove').click();
  });
});

test('cancel delete', function(assert){
  assert.expect(2);

  let school = Object.create({ id() { return 1; }});

  let program = Object.create({
    belongsTo() {
      return school;
    }
  });

  let block1 = Object.create({
    id: 1,
    academicLevel: resolve(Object.create({ id: 1, level: '2'})),
    title: 'Foo',
    startDate: new Date('2015-02-23'),
    endDate: new Date('2016-12-03'),
    course: resolve(null),
    orderInSequence: 0,
  });

  let report = Object.create({
    academicLevels: resolve([]),
    year: '2016',
    program: resolve(program),
    linkedCourses: resolve([]),
    isFinalized: false,
    name: 'Lorem Ipsum',
    startDate: moment('2015-06-12').toDate(),
    endDate: moment('2016-04-11').toDate(),
    description: 'Lorem Ipsum',
    topLevelSequenceBlocks: resolve([ block1 ])
  });

  this.set('report', report);
  this.render(hbs`{{curriculum-inventory-sequence-block-list report=report}}`);
  return wait().then(() => {
    this.$('tbody tr:eq(0) td:eq(6) .remove').click();
    assert.equal(this.$('tbody .confirm-message').length, 1,'Confirmation dialog is visible.');
    this.$('tbody tr:eq(1) .confirm-buttons .done').click();
    assert.equal(this.$('tbody .confirm-message').length, 0,'Confirmation dialog is not visible after cancelling.');
  });
});
<|endoftext|>


<commit_before>var NewVirtualNetworkWizard = function($scope, $uibModalInstance, $log, appsession, uuid4) {
	$scope.inprg = false;
	$scope.vnet = {
		'@type': 'vnet',
		id : uuid4.generate(),
		name : '',
		expectations : []
	};

	$scope.validating = false;
	$scope.valid = true;

	$scope.addVirtualNetwork = function() {
		$scope.inprg = true;
		appsession.put('/s/r/vnet', $scope.vnet).then(function() {
			$scope.inprg = false;
			$uibModalInstance.dismiss();
		});
	};

	$scope.checkVirtualNetworkName = function() {
		var name = $scope.vnet.name;
		if(name.length > 0) {
			appsession.get('s/r/vnet/byname/' + name).success(function(results) {
				if(name == $scope.vnet.name) {
					$scope.valid = results.length == 0;
				}
			});
		} else {
			$scope.valid = false;
		}
	};

	$scope.close = function() {
		$uibModalInstance.dismiss();
	};
}<commit_msg>automatic vnet name<commit_after>var NewVirtualNetworkWizard = function($scope, $uibModalInstance, $log, appsession, uuid4) {
	$scope.inprg = false;
	$scope.vnet = {
		'@type': 'vnet',
		id : uuid4.generate(),
		name : '',
		expectations : []
	};

	$scope.validating = false;
	$scope.valid = true;

	$scope.autoName = function() {
		appsession.get('s/r/vnet/autoname').then(function(name) {
			$scope.vnet.name = name;
		});
	};

	$scope.autoName();

	$scope.addVirtualNetwork = function() {
		$scope.inprg = true;
		appsession.put('/s/r/vnet', $scope.vnet).then(function() {
			$scope.inprg = false;
			$uibModalInstance.dismiss();
		});
	};

	$scope.checkVirtualNetworkName = function() {
		var name = $scope.vnet.name;
		if(name.length > 0) {
			appsession.get('s/r/vnet/byname/' + name).success(function(results) {
				if(name == $scope.vnet.name) {
					$scope.valid = results.length == 0;
				}
			});
		} else {
			$scope.valid = false;
		}
	};

	$scope.close = function() {
		$uibModalInstance.dismiss();
	};
}<|endoftext|>


<commit_before>"use strict";
import chai, {expect} from 'src/external/chai.js';
import sinon from 'src/external/sinon-3.2.1.js';
import sinonChai from 'src/external/sinon-chai.js';
chai.use(sinonChai);

describe('simple', function() {
  it('simple div1', () => {
    let div =
Hello
;

    expect(div).to.have.property('tagName', 'DIV');
    expect(div).to.have.property('innerHTML', 'Hello');
  });
});

describe('computed content', function() {
  it('supports symbols', () => {
    let div =
{Symbol('Hello')}
;

    expect(div).to.have.property('tagName', 'DIV');
    expect(div).to.have.property('innerHTML', 'Symbol(Hello)');
  });
});

describe('async support for WebComponents', function() {
  this.timeout = 30000;
  it('simple WebComponent', async done => {
    let prom = <add-knot>Hello</add-knot>;
    expect(prom).to.be.an.instanceof(Promise);

    let editor = await prom;
    expect(editor).to.have.property('tagName', 'ADD-KNOT');
    expect(editor).to.have.property('innerHTML', 'Hello');
    expect(editor.afterSubmit).to.be.a('function');

    done();
  });
  it('nested WebComponent', async done => {
    let prom =
<add-knot>Hello</add-knot>
;
    expect(prom).to.be.an.instanceof(Promise);

    let div = await prom;
    expect(div).to.have.property('tagName', 'DIV');
    let addKnot = div.querySelector('add-knot');
    expect(addKnot).to.have.property('innerHTML', 'Hello');
    expect(addKnot.afterSubmit).to.be.a('function');

    done();
  });
  xit('support CodeMirror', async done => {
    let prom = <lively-code-mirror>Hello</lively-code-mirror>;
    expect(prom).to.be.an.instanceof(Promise);

    let editor = await prom;
    expect(editor).to.have.property('tagName', 'LIVELY-CODE-MIRROR');
    expect(editor.editor.getValue()).to.equal('Hello');

    done();
  });
});
<commit_msg>this in function<commit_after>"use strict";
import chai, {expect} from 'src/external/chai.js';
import sinon from 'src/external/sinon-3.2.1.js';
import sinonChai from 'src/external/sinon-chai.js';
chai.use(sinonChai);

describe('simple', function() {
  it('simple div1', () => {
    let div =
Hello
;

    expect(div).to.have.property('tagName', 'DIV');
    expect(div).to.have.property('innerHTML', 'Hello');
  });
});

describe('computed content', function() {
  it('supports symbols', () => {
    let div =
{Symbol('Hello')}
;

    expect(div).to.have.property('tagName', 'DIV');
    expect(div).to.have.property('innerHTML', 'Symbol(Hello)');
  });
});

describe('async support for WebComponents', function() {
  it('simple WebComponent', async function(done) {
    this.timeout = 30000;
    let prom = <add-knot>Hello</add-knot>;
    expect(prom).to.be.an.instanceof(Promise);

    let editor = await prom;
    expect(editor).to.have.property('tagName', 'ADD-KNOT');
    expect(editor).to.have.property('innerHTML', 'Hello');
    expect(editor.afterSubmit).to.be.a('function');

    done();
  });
  it('nested WebComponent', async done => {
    let prom =
<add-knot>Hello</add-knot>
;
    expect(prom).to.be.an.instanceof(Promise);

    let div = await prom;
    expect(div).to.have.property('tagName', 'DIV');
    let addKnot = div.querySelector('add-knot');
    expect(addKnot).to.have.property('innerHTML', 'Hello');
    expect(addKnot.afterSubmit).to.be.a('function');

    done();
  });
  xit('support CodeMirror', async done => {
    let prom = <lively-code-mirror>Hello</lively-code-mirror>;
    expect(prom).to.be.an.instanceof(Promise);

    let editor = await prom;
    expect(editor).to.have.property('tagName', 'LIVELY-CODE-MIRROR');
    expect(editor.editor.getValue()).to.equal('Hello');

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