<commit_before>/*!
 * dragtable - jquery ui widget to re-order table columns
 * version 3.0
 *
 * Copyright (c) 2010, Jesse Baird <jebaird@gmail.com>
 * 12/2/2010
 * https://github.com/jebaird/dragtable
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 *
 * Forked from https://github.com/akottr/dragtable - Andres Koetter akottr@gmail.com
 *
 *
 *
 *
 * quick down and and dirty on how this works
 * ###########################################
 * so when a column is selected we grab all of the cells in that row and clone append them to a semi copy of the parent table and the
 * "real" cells get a place holder class witch is removed when the dragstop event is triggered
 *
 * TODO:
 * add / create / edit css framework
 * add drag handles
 * click event to handle drag
 * ignore class
 *
 *
 * clean up the api - event driven like ui autocompleate
 * make it easy to have a button swap colums
 *
 */

(function($) {
  $.widget("jb.dragtable", {
  		//TODO: implement this
  		eventWidgetPrefix: 'dragtable',

		options: {
			//used to the col headers, data containted in here is used to set / get the name of the col
			dataHeader:'data-header',
			//handle
			handle:'.dragtable-drag-handle',
			//optional call back used when the col order has changed
			change: $.noop,

			//called after we create the drag display allows user to customize the look of the col in drag
			displayHelper: $.noop,

			//TODO: Faze these out
			// when a col is dragged use this to find the symantic elements, for speed
			tableElemIndex:{
				head: '0',
				body: '1',
				foot: '2'
			}
		},

		_create: function() {

			//console.log(this);
			//used start/end of drag
			this.startIndex = null;
			this.endIndex = null;
			this.currentColumnCollection = [];//the refferences to the table cells that are getting dragged

			//used on drag event to detect what direction the mouse is moving
			//init on drag start
			this.prevMouseX = 0;

			var self = this,
			o = self.options,
			el = self.element;

			//grab the ths and the handles and bind them
			el.delegate('thead th:not( :has(' + o.handle + ')), ' + o.handle, 'mousedown', function(e){
				var $handle = $(this);
				//make sure we are working with a th instead of a handle
				if($handle.hasClass(o.handle.replace('.',''))){
					$handle = $handle.closest('th');
				}

				var $dragDisplay = self.getCol( $handle.index() );
				//console.log(dragDisplay)
				self._eventHelper('displayHelper',{},{
					'draggable':$dragDisplay
				});

                //console.log( $dragDisplay, e );

				$dragDisplay
				.disableSelection()
				.css({
					position:'absolute',
                    top: e.pageY,
                    left: e.pageX
				})
                .appendTo(document.body)

                //drag the column around

                self.prevMouseX = e.pageX;

                $( document )
                .disableSelection()
                .bind('mousemove.dragtable', function( e ){
                    $dragDisplay
                    .css({
    					position:'absolute',
                        //top: e.pageY,
                        left: e.pageX,
                        zindex: 100
				    })

                    var columnPos = self._findElementPosition(self.currentColumnCollection[0]),
					half = self.currentColumnCollection[0].clientWidth / 2;
                    if(e.pageX < self.prevMouseX){
							var threshold = columnPos.x - half;
							if(e.pageX < threshold){
								//console.info('move left');
								self._swapCol(self.startIndex-1);
								self._eventHelper('change',e);

							}

						}else{
							var threshold = columnPos.x + half;
							if(e.pageX > threshold){
								//console.info('move right');
								self._swapCol(self.startIndex+1);
								self._eventHelper('change',e);

							}
						}
						//update mouse position
						self.prevMouseX = e.pageX;

                })
                .one( 'mouseup.dragtable',function(){
                    $( document )
                    .enableSelection()
                    .unbind( 'mousemove.dragtable' );
                    self._dropCol($dragDisplay);
                    self.prevMouseX = 0;
                });

				//############
			});

		},

		_setOption: function(option, value) {
			$.Widget.prototype._setOption.apply( this, arguments );

		},

		/*
		 * get the selected index cell out of table row
		 * works dam fast
		 */
		_getCells: function( elem, index ){
			var ei = this.options.tableElemIndex,

			//TODO: clean up this format
			tds = {
				'semantic':{
					'0': [],//head throws error if ei.head or ei['head']
					'1': [],//body
					'2': []//footer
				},
				'array':[]
			};

			//console.log(index);
			//check does this col exsist
			if(index <= -1 || typeof elem.rows[0].cells[index] == 'undefined'){
				return tds;
			}

			for(var i = 0, length = elem.rows.length; i < length; i++){
				var td = elem.rows[i].cells[index];

				tds.array.push(td);

				switch(td.parentNode.parentNode.nodeName){
					case 'THEAD':
					case 'thead':
						tds.semantic[ei.head].push(td);
						break;
					case 'TFOOT':
					case 'tfoot':
						tds.semantic[ei.foot].push(td);
						break;
					default:
						tds.semantic[ei.body].push(td);
						break;
				}

		 	}

		 	return tds;
		},
		/*
		 * return and array of children excluding text nodes
		 * used only on this.element
		 */
		_getChildren: function(){

			var children = this.element[0].childNodes,
			ret = [];
			for(var i = 0, length = children.length; i < length; i++){
				var e = children[i];
				if(e.nodeType == 1){
					ret.push(e);
				}
			}

			return ret;
		},

		_getElementAttributes: function(element){

        	var attrsString = '',
	        attrs = element.attributes;
	        for(var i=0, length = attrs.length; i < length; i++) {
	            attrsString += attrs[i].nodeName + '="' + attrs[i].nodeValue+'"';
	        }
	        return attrsString;
		},
		/*
		 * currently not uses
		 */
		_swapNodes: function(a, b) {
        	var aparent = a.parentNode,
        	asibling = a.nextSibling === b ? a : a.nextSibling;
        	b.parentNode.insertBefore(a, b);
        	aparent.insertBefore(b, asibling);
     	},
     	/*
     	 * faster than swap nodes
     	 * only works if a b parent are the same, works great for colums
     	 */
     	_swapCells: function(a, b) {
        	a.parentNode.insertBefore(b, a);
     	},
     	/*
     	 * use this instead of jquerys offset, in the cases were using is faster than creating a jquery collection
     	 */
		_findElementPosition: function( oElement ) {
			if( typeof( oElement.offsetParent ) != 'undefined' ) {
				for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
					posX += oElement.offsetLeft;
					posY += oElement.offsetTop;
				}
				return {'x':posX, 'y':posY };
			} else {
				return {'x':oElement.x, 'y':oElement.y };
			}
		},
		/*
		 * used to tirgger optional events
		 */
		_eventHelper: function(eventName ,eventObj, additionalData){
			this._trigger(
				eventName,
				eventObj,
				$.extend({
					column: this.currentColumnCollection,
					order: this.order()
				},additionalData)
			);
		},
		/*
		 * build copy of table and attach the selected col to it, also removes the select col out of the table
		 * @returns copy of table with the selected col
		 */
		getCol: function(index){
			//console.log('index of col '+index);
			//drag display is just simple html
			//console.profile('selectCol');

			//colHeader.addClass('ui-state-disabled')

			var $table = this.element,
			self = this,
			eIndex = self.options.tableElemIndex,
			//BUG: IE thinks that this table is disabled, dont know how that happend
			$dragDisplay = $('

')
			.addClass('dragtable-drag-col');

			//start and end are the same to start out with
			self.startIndex = self.endIndex = index;

		 	var cells = self._getCells($table[0], index);
			self.currentColumnCollection = cells.array;
			//console.log(cells);
			//################################

			//TODO: convert to for in // its faster than each
			$.each(cells.semantic,function(k,collection){
				//dont bother processing if there is nothing here

				if(collection.length == 0){
					return;
				}

                if ( k == '0' ){
                    var target = document.createElement('thead');
						$dragDisplay[0].appendChild(target);
						//
						// var target = $('

')
						// .appendTo($dragDisplay);
                }else{
                    var target = document.createElement('tbody');
						$dragDisplay[0].appendChild(target);
						// var target = $('

')
						// .appendTo($dragDisplay);

                }

				for(var i = 0,length = collection.length; i < length; i++){

					var clone = collection[i].cloneNode(true);
					collection[i].className+=' dragtable-col-placeholder';
					var tr = document.createElement('tr');
					tr.appendChild(clone);
					//console.log(tr);

					target.appendChild(tr);
					//collection[i]=;
				}
			});
    		// console.log($dragDisplay);
    		//console.profileEnd('selectCol')
            $dragDisplay  = $('

').append($dragDisplay)
    		return $dragDisplay;
		},

		/*
		 * move column left or right
		 */
		_swapCol: function( to ){

			//cant swap if same postion
			if(to == this.startIndex){
				return false;
			}

			from = this.startIndex;
			this.endIndex = to;

	        if(from < to) {
	        	//console.log('move right');
	        	for(var i = from; i < to; i++) {
	        		var row2 = this._getCells(this.element[0],i+1);
	        	//	console.log(row2)
	        		for(var j = 0, length = row2.array.length; j < length; j++){
	          			this._swapCells(this.currentColumnCollection[j],row2.array[j]);
	          		}
	          	}
	        } else {
	        	//console.log('move left');
	        	for(var i = from; i > to; i--) {
	            	var row2 = this._getCells(this.element[0],i-1);
	            	for(var j = 0, length = row2.array.length; j < length; j++){
	          			this._swapCells(row2.array[j],this.currentColumnCollection[j]);
	          		}
	        	}
	        }

	        this.startIndex = this.endIndex;
		},
		/*
		 * called when drag start is finished
		 */
		_dropCol: function($dragDisplay){
		//	console.profile('dropCol');
			var self = this;

			if($dragDisplay){
				$dragDisplay.remove();
			}
			//remove placeholder class
			for(var i = 0, length = self.currentColumnCollection.length; i < length; i++){
				var td = self.currentColumnCollection[i];

				td.className = td.className.replace(' dragtable-col-placeholder','');
			}

		},
		/*
		 * get / set the current order of the cols
		 */
		order: function(order){
			var self = this,
			elem = self.element,
			options = self.options,
			headers = elem.find('thead tr:first').children('th');

			if(order == undefined){
				//get
				var ret = [];
				headers.each(function(){
					var header = this.getAttribute(options.dataHeader);
					if(header == null){
						//the attr is missing so grab the text and use that
						header = $(this).text();
					}

					ret.push(header);

				});

				return ret;

			}else{
				//set
				//headers and order have to match up
				if(order.length != headers.length){
					//console.log('length not the same')
					return self;
				}
				for(var i = 0, length = order.length; i < length; i++){

					 var start = headers.filter('['+ options.dataHeader +'='+ order[i] +']').index();
					 if(start != -1){
					 	//console.log('start index '+start+' - swap to '+i);
					 	self.startIndex = start;

						self.currentColumnCollection = self._getCells(self.element[0], start).array;

					 	self._swapCol(i);
					 }

				}
				self._eventHelper('change',{});
				return self;
			}
		},

		destroy: function() {
			return this;
		}

	});

})(jQuery);<commit_msg>fixed style drag on x axis, now dragdisplay top is even with target element<commit_after>/*!
 * dragtable - jquery ui widget to re-order table columns
 * version 3.0
 *
 * Copyright (c) 2010, Jesse Baird <jebaird@gmail.com>
 * 12/2/2010
 * https://github.com/jebaird/dragtable
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 *
 * Forked from https://github.com/akottr/dragtable - Andres Koetter akottr@gmail.com
 *
 *
 *
 *
 * quick down and and dirty on how this works
 * ###########################################
 * so when a column is selected we grab all of the cells in that row and clone append them to a semi copy of the parent table and the
 * "real" cells get a place holder class witch is removed when the dragstop event is triggered
 *
 * TODO:
 * add / create / edit css framework
 * add drag handles
 * click event to handle drag
 * ignore class
 *
 *
 * clean up the api - event driven like ui autocompleate
 * make it easy to have a button swap colums
 *
 */

(function($) {
  $.widget("jb.dragtable", {
  		//TODO: implement this
  		eventWidgetPrefix: 'dragtable',

		options: {
			//used to the col headers, data containted in here is used to set / get the name of the col
			dataHeader:'data-header',
			//handle
			handle:'.dragtable-drag-handle',
			//optional call back used when the col order has changed
			change: $.noop,

			//called after we create the drag display allows user to customize the look of the col in drag
			displayHelper: $.noop,

			//TODO: Faze these out
			// when a col is dragged use this to find the symantic elements, for speed
			tableElemIndex:{
				head: '0',
				body: '1',
				foot: '2'
			}
		},

		_create: function() {

			//console.log(this);
			//used start/end of drag
			this.startIndex = null;
			this.endIndex = null;
			this.currentColumnCollection = [];//the refferences to the table cells that are getting dragged

			//used on drag event to detect what direction the mouse is moving
			//init on drag start
			this.prevMouseX = 0;

			var self = this,
			o = self.options,
			el = self.element;

			//grab the ths and the handles and bind them
			el.delegate('thead th:not( :has(' + o.handle + ')), ' + o.handle, 'mousedown', function(e){
				var $handle = $(this);
				//make sure we are working with a th instead of a handle
				if($handle.hasClass(o.handle.replace('.',''))){
					$handle = $handle.closest('th');
				}

				var $dragDisplay = self.getCol( $handle.index() );
				//console.log(dragDisplay)
				self._eventHelper('displayHelper',{},{
					'draggable':$dragDisplay
				});

                //console.log( el, e );

				$dragDisplay
                .focus()
				.disableSelection()
				.css({
					position:'absolute',
                    top: el[0].offsetTop,
                    left: e.pageX
				})
                .appendTo(document.body)

                //drag the column around

                self.prevMouseX = e.pageX;

                $( document )
                .disableSelection()
                .css( 'cursor', 'move')
                .bind('mousemove.dragtable', function( e ){
                    $dragDisplay
                    .css({
    					position:'absolute',
                        left: e.pageX,
                        zindex: 100
				    })

                    var columnPos = self._findElementPosition(self.currentColumnCollection[0]),
					half = self.currentColumnCollection[0].clientWidth / 2;
                    if(e.pageX < self.prevMouseX){
							var threshold = columnPos.x - half;
							if(e.pageX < threshold){
								//console.info('move left');
								self._swapCol(self.startIndex-1);
								self._eventHelper('change',e);

							}

						}else{
							var threshold = columnPos.x + half;
							if(e.pageX > threshold){
								//console.info('move right');
								self._swapCol(self.startIndex+1);
								self._eventHelper('change',e);

							}
						}
						//update mouse position
						self.prevMouseX = e.pageX;

                })
                .one( 'mouseup.dragtable',function(){
                    $( document )
                    .css({
                        cursor: 'auto'
                    })
                    .enableSelection()
                    .unbind( 'mousemove.dragtable' );
                    self._dropCol($dragDisplay);
                    self.prevMouseX = 0;
                });

				//############
			});

		},

		_setOption: function(option, value) {
			$.Widget.prototype._setOption.apply( this, arguments );

		},

		/*
		 * get the selected index cell out of table row
		 * works dam fast
		 */
		_getCells: function( elem, index ){
			var ei = this.options.tableElemIndex,

			//TODO: clean up this format
			tds = {
				'semantic':{
					'0': [],//head throws error if ei.head or ei['head']
					'1': [],//body
					'2': []//footer
				},
				'array':[]
			};

			//console.log(index);
			//check does this col exsist
			if(index <= -1 || typeof elem.rows[0].cells[index] == 'undefined'){
				return tds;
			}

			for(var i = 0, length = elem.rows.length; i < length; i++){
				var td = elem.rows[i].cells[index];

				tds.array.push(td);

				switch(td.parentNode.parentNode.nodeName){
					case 'THEAD':
					case 'thead':
						tds.semantic[ei.head].push(td);
						break;
					case 'TFOOT':
					case 'tfoot':
						tds.semantic[ei.foot].push(td);
						break;
					default:
						tds.semantic[ei.body].push(td);
						break;
				}

		 	}

		 	return tds;
		},
		/*
		 * return and array of children excluding text nodes
		 * used only on this.element
		 */
		_getChildren: function(){

			var children = this.element[0].childNodes,
			ret = [];
			for(var i = 0, length = children.length; i < length; i++){
				var e = children[i];
				if(e.nodeType == 1){
					ret.push(e);
				}
			}

			return ret;
		},

		_getElementAttributes: function(element){

        	var attrsString = '',
	        attrs = element.attributes;
	        for(var i=0, length = attrs.length; i < length; i++) {
	            attrsString += attrs[i].nodeName + '="' + attrs[i].nodeValue+'"';
	        }
	        return attrsString;
		},
		/*
		 * currently not uses
		 */
		_swapNodes: function(a, b) {
        	var aparent = a.parentNode,
        	asibling = a.nextSibling === b ? a : a.nextSibling;
        	b.parentNode.insertBefore(a, b);
        	aparent.insertBefore(b, asibling);
     	},
     	/*
     	 * faster than swap nodes
     	 * only works if a b parent are the same, works great for colums
     	 */
     	_swapCells: function(a, b) {
        	a.parentNode.insertBefore(b, a);
     	},
     	/*
     	 * use this instead of jquerys offset, in the cases were using is faster than creating a jquery collection
     	 */
		_findElementPosition: function( oElement ) {
			if( typeof( oElement.offsetParent ) != 'undefined' ) {
				for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
					posX += oElement.offsetLeft;
					posY += oElement.offsetTop;
				}
				return {'x':posX, 'y':posY };
			} else {
				return {'x':oElement.x, 'y':oElement.y };
			}
		},
		/*
		 * used to tirgger optional events
		 */
		_eventHelper: function(eventName ,eventObj, additionalData){
			this._trigger(
				eventName,
				eventObj,
				$.extend({
					column: this.currentColumnCollection,
					order: this.order()
				},additionalData)
			);
		},
		/*
		 * build copy of table and attach the selected col to it, also removes the select col out of the table
		 * @returns copy of table with the selected col
		 */
		getCol: function(index){
			//console.log('index of col '+index);
			//drag display is just simple html
			//console.profile('selectCol');

			//colHeader.addClass('ui-state-disabled')

			var $table = this.element,
			self = this,
			eIndex = self.options.tableElemIndex,
			//BUG: IE thinks that this table is disabled, dont know how that happend
			$dragDisplay = $('

')
			.addClass('dragtable-drag-col');

			//start and end are the same to start out with
			self.startIndex = self.endIndex = index;

		 	var cells = self._getCells($table[0], index);
			self.currentColumnCollection = cells.array;
			//console.log(cells);
			//################################

			//TODO: convert to for in // its faster than each
			$.each(cells.semantic,function(k,collection){
				//dont bother processing if there is nothing here

				if(collection.length == 0){
					return;
				}

                if ( k == '0' ){
                    var target = document.createElement('thead');
						$dragDisplay[0].appendChild(target);
						//
						// var target = $('

')
						// .appendTo($dragDisplay);
                }else{
                    var target = document.createElement('tbody');
						$dragDisplay[0].appendChild(target);
						// var target = $('

')
						// .appendTo($dragDisplay);

                }

				for(var i = 0,length = collection.length; i < length; i++){

					var clone = collection[i].cloneNode(true);
					collection[i].className+=' dragtable-col-placeholder';
					var tr = document.createElement('tr');
					tr.appendChild(clone);
					//console.log(tr);

					target.appendChild(tr);
					//collection[i]=;
				}
			});
    		// console.log($dragDisplay);
    		//console.profileEnd('selectCol')
            $dragDisplay  = $('

').append($dragDisplay)
    		return $dragDisplay;
		},

		/*
		 * move column left or right
		 */
		_swapCol: function( to ){

			//cant swap if same postion
			if(to == this.startIndex){
				return false;
			}

			from = this.startIndex;
			this.endIndex = to;

	        if(from < to) {
	        	//console.log('move right');
	        	for(var i = from; i < to; i++) {
	        		var row2 = this._getCells(this.element[0],i+1);
	        	//	console.log(row2)
	        		for(var j = 0, length = row2.array.length; j < length; j++){
	          			this._swapCells(this.currentColumnCollection[j],row2.array[j]);
	          		}
	          	}
	        } else {
	        	//console.log('move left');
	        	for(var i = from; i > to; i--) {
	            	var row2 = this._getCells(this.element[0],i-1);
	            	for(var j = 0, length = row2.array.length; j < length; j++){
	          			this._swapCells(row2.array[j],this.currentColumnCollection[j]);
	          		}
	        	}
	        }

	        this.startIndex = this.endIndex;
		},
		/*
		 * called when drag start is finished
		 */
		_dropCol: function($dragDisplay){
		//	console.profile('dropCol');
			var self = this;

			if($dragDisplay){
				$dragDisplay.remove();
			}
			//remove placeholder class
			for(var i = 0, length = self.currentColumnCollection.length; i < length; i++){
				var td = self.currentColumnCollection[i];

				td.className = td.className.replace(' dragtable-col-placeholder','');
			}

		},
		/*
		 * get / set the current order of the cols
		 */
		order: function(order){
			var self = this,
			elem = self.element,
			options = self.options,
			headers = elem.find('thead tr:first').children('th');

			if(order == undefined){
				//get
				var ret = [];
				headers.each(function(){
					var header = this.getAttribute(options.dataHeader);
					if(header == null){
						//the attr is missing so grab the text and use that
						header = $(this).text();
					}

					ret.push(header);

				});

				return ret;

			}else{
				//set
				//headers and order have to match up
				if(order.length != headers.length){
					//console.log('length not the same')
					return self;
				}
				for(var i = 0, length = order.length; i < length; i++){

					 var start = headers.filter('['+ options.dataHeader +'='+ order[i] +']').index();
					 if(start != -1){
					 	//console.log('start index '+start+' - swap to '+i);
					 	self.startIndex = start;

						self.currentColumnCollection = self._getCells(self.element[0], start).array;

					 	self._swapCol(i);
					 }

				}
				self._eventHelper('change',{});
				return self;
			}
		},

		destroy: function() {
			this.element.undelegate( 'thead th:not( :has(' + o.handle + ')), ' + o.handle, 'mousedown');

		}

	});

})(jQuery);<|endoftext|>


<commit_before>/**
 * Layout utility class for positioning HTMLElements in a boxed/flexed layout
 * position.
 */
Blend.defineClass('Blend.layout.utils.Box', {
    extend: 'Blend.layout.utils.Util',
    singleton: true,
    /**
     * @internal
     * Arranges given elements in to a vertical box layout. This function
     * needs a layoutContext and a list of item layout context configuration for
     * each item.
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @returns {undefined}
     */
    vflex: function (parent, children, ilctx, lctx) {
        var me = this, needtotals, nexttop = -1, margin, proccessors = {
            pack: {
                start: function (bounds) {
                    var r;
                    if (nexttop === -1) {
                        nexttop = margin; // the first item with its margins
                    }
                    r = nexttop;
                    nexttop += (bounds.height + margin);
                    bounds.top = r;
                },
                center: function (bounds) {
                    var r;
                    if (nexttop === -1) {
                        nexttop = ((lctx.bounds.height / 2) - (lctx.total_height / 2)) + margin;
                    }
                    r = nexttop;
                    nexttop += (bounds.height + margin);
                    bounds.top = r;
                },
                end: function (bounds) {
                    var r;
                    if (nexttop === -1) {
                        nexttop = (lctx.bounds.height - (lctx.total_height)) + margin;
                    }
                    r = nexttop;
                    nexttop += (bounds.height + margin);
                    bounds.top = r;
                }
            },
            align: {
                start: function (bounds) {
                    bounds.left = margin;
                },
                stretch: function (bounds) {
                    bounds.left = margin;
                    bounds.width = lctx.bounds.width - (bounds.left * 2);
                },
                center: function (bounds) {
                    bounds.left = (lctx.bounds.width / 2) - (bounds.width / 2); // no margins
                },
                end: function (bounds) {
                    bounds.left = lctx.bounds.width - (bounds.width + margin);
                }
            },
            bounds: function (el, ctx) {
                var b = Blend.Element.getBounds(el);
                if (Blend.Environment.isIE) {
                    b.height = ctx.height;
                }
                return b;
            }
        };
        lctx.pack = lctx.margin === true ? 'center' : lctx.pack;
        needtotals = (lctx.pack === 'center' || lctx.pack === 'end');
        parent = me.getEl(parent);
        children = me.getEl(children);
        me.calculateSetBounds(parent, children, ilctx, lctx, 'height', needtotals);
        margin = lctx.margin;
        me.flex(parent, children, ilctx, lctx, proccessors);
    },
    /**
     * Common processor for both vflex and hflex layout utilities
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @param {type} proccessors
     * @returns {undefined}
     */
    flex: function (parent, children, ilctx, lctx, proccessors) {
        var me = this, alignFn, packFn, ctx, a, len, el, bounds;
        len = children.length;
        for (a = 0; a !== len; a++) {
            el = children[a];
            ctx = ilctx[a];
            bounds = proccessors.bounds.apply(me, [el, ctx]);
            alignFn = proccessors.align[lctx.align];
            packFn = proccessors.pack[lctx.pack];
            packFn.apply(me, [bounds]);
            alignFn.apply(me, [bounds]);
            Blend.Style.set(el, bounds);
        }
    },
    /**
     * @internal
     * Update/Set the given layoutContext with:
     * [1] Maximum flex units of elements that are flexed
     * [2] Total width/height of fixed elements
     * @param {type} children
     * @param {type} lctx
     * @param {type} ilctx
     * @param {type} flexed_prop
     * @returns {undefined}
     */
    updateLayoutContext: function (children, lctx, ilctx, flexed_prop) {
        var me = this, maxFlex = 0, itm, total = 0, bounds;
        Blend.foreach(ilctx, function (ctx, idx) {
            itm = children[idx];
            bounds = Blend.Element.getBounds(itm);
            if (ctx.flex) {
                maxFlex++;
            } else {
                total += bounds[flexed_prop];
            }
        });
        lctx.maxFlex = maxFlex;
        lctx[flexed_prop] = total;
    },
    /**
     * @internal
     * Calculates and sets the bounds of flexed elements. This function also
     * sets the total units of widths/heights of all the elements to be used
     * later in the width/height calculations
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @param {type} flexed_prop
     * @param {type} need_all_totals
     * @returns {undefined}
     */
    calculateSetBounds: function (parent, children, ilctx, lctx, flexed_prop, need_all_totals) {
        var me = this, alltotals = 0,
                ctx, unit,
                mrg = lctx.margin, omrg = mrg, avail, totalMargin = 0;

        need_all_totals = need_all_totals || false;

        //Update the layout context to get maxFlex and total width/height that is taken
        me.updateLayoutContext(children, lctx, ilctx, flexed_prop);

        if (lctx.maxFlex !== 0) {
            //omrg is the original margin
            mrg = Blend.isNumeric(omrg) ? mrg : 0;
            totalMargin = (children.length + 1) * mrg;
            var pbounds = Blend.Element.getBounds(parent);
            avail = (pbounds[flexed_prop] - totalMargin) - lctx[flexed_prop];
        }

        Blend.foreach(children, function (itm, idx) {
            ctx = ilctx[idx];
            if (ctx.flex) {
                unit = (avail * ctx.flex) / lctx.maxFlex;
                var o = {};
                o[flexed_prop] = unit;
                Blend.Style.set(itm, o);
            }
            if (need_all_totals) {
                if (unit) {
                    alltotals += unit;
                    ctx[flexed_prop] = unit; // For F** IE that does not return the
                    unit = null;
                } else {
                    var b = Blend.Element.getBounds(itm);
                    ctx[flexed_prop] = b.height;
                    alltotals += b.height;
                }
            }
        });
        if (need_all_totals) {
            if (!Blend.isNumeric(omrg) && omrg === true) {
                /*
                 * Calculate the distributed margin value
                 */
                mrg = (lctx.bounds[flexed_prop] - alltotals) / children.length;
                lctx.margin = mrg;
            }
            totalMargin = (children.length + 1) * mrg; // +1 is for the margin before the first element
            alltotals += totalMargin;
            lctx['total_' + flexed_prop] = alltotals;
        }

    }
});<commit_msg>Implemented initial hbox layout<commit_after>/**
 * Layout utility class for positioning HTMLElements in a boxed/flexed layout
 * position.
 */
Blend.defineClass('Blend.layout.utils.Box', {
    extend: 'Blend.layout.utils.Util',
    singleton: true,
    /**
     * @internal
     * Arranges given elements in to a vertical box layout. This function
     * needs a layoutContext and a list of item layout context configuration for
     * each item.
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @returns {undefined}
     */
    hflex: function (parent, children, ilctx, lctx) {
        var me = this, needtotals, nextleft = -1, margin, proccessors = {
            pack: {
                start: function (bounds) {
                    var r;
                    if (nextleft === -1) {
                        nextleft = margin;
                    }
                    r = nextleft;
                    nextleft += (bounds.width + margin)
                    bounds.left = r;
                },
                center: function (bounds) {
                    var r;
                    if (nextleft === -1) {
                        nextleft = ((lctx.bounds.width / 2) - (lctx.width / 2)) - (margin * 2);
                    }
                    r = nextleft;
                    nextleft += (bounds.width + margin);
                    bounds.left = r;
                },
                end: function (bounds) {
                    var r;
                    if (nextleft === -1) {
                        nextleft = (lctx.bounds.width - (lctx.total_width)) + margin;
                    }
                    r = nextleft;
                    nextleft += (bounds.width + margin);
                    bounds.left = r;
                }
            },
            align: {
                start: function (bounds) {
                    bounds.top = margin;
                },
                stretch: function (bounds) {
                    bounds.top = margin;
                    bounds.height = lctx.bounds.height - (bounds.top * 2);
                },
                center: function (bounds) {
                    bounds.top = (lctx.bounds.height / 2) - (bounds.height / 2); // no margins
                },
                end: function (bounds) {
                    bounds.top = lctx.bounds.height - (bounds.height + margin);
                }
            }, bounds: function (el, ctx) {
                var b = Blend.Element.getBounds(el);
                if (Blend.Environment.isIE) {
                    b.width = ctx.width;
                }
                return b;
            }
        };
        lctx.pack = lctx.margin === true ? 'center' : lctx.pack;
        needtotals = (lctx.pack === 'center' || lctx.pack === 'end');
        parent = me.getEl(parent);
        children = me.getEl(children);
        me.calculateSetBounds(parent, children, ilctx, lctx, 'width', needtotals);
        margin = lctx.margin;
        me.flex(parent, children, ilctx, lctx, proccessors);
    },
    /**
     * @internal
     * Arranges given elements in to a vertical box layout. This function
     * needs a layoutContext and a list of item layout context configuration for
     * each item.
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @returns {undefined}
     */
    vflex: function (parent, children, ilctx, lctx) {
        var me = this, needtotals, nexttop = -1, margin, proccessors = {
            pack: {
                start: function (bounds) {
                    var r;
                    if (nexttop === -1) {
                        nexttop = margin; // the first item with its margins
                    }
                    r = nexttop;
                    nexttop += (bounds.height + margin);
                    bounds.top = r;
                },
                center: function (bounds) {
                    var r;
                    if (nexttop === -1) {
                        nexttop = ((lctx.bounds.height / 2) - (lctx.total_height / 2)) + margin;
                    }
                    r = nexttop;
                    nexttop += (bounds.height + margin);
                    bounds.top = r;
                },
                end: function (bounds) {
                    var r;
                    if (nexttop === -1) {
                        nexttop = (lctx.bounds.height - (lctx.total_height)) + margin;
                    }
                    r = nexttop;
                    nexttop += (bounds.height + margin);
                    bounds.top = r;
                }
            },
            align: {
                start: function (bounds) {
                    bounds.left = margin;
                },
                stretch: function (bounds) {
                    bounds.left = margin;
                    bounds.width = lctx.bounds.width - (bounds.left * 2);
                },
                center: function (bounds) {
                    bounds.left = (lctx.bounds.width / 2) - (bounds.width / 2); // no margins
                },
                end: function (bounds) {
                    bounds.left = lctx.bounds.width - (bounds.width + margin);
                }
            },
            bounds: function (el, ctx) {
                var b = Blend.Element.getBounds(el);
                if (Blend.Environment.isIE) {
                    b.height = ctx.height;
                }
                return b;
            }
        };
        lctx.pack = lctx.margin === true ? 'center' : lctx.pack;
        needtotals = (lctx.pack === 'center' || lctx.pack === 'end');
        parent = me.getEl(parent);
        children = me.getEl(children);
        me.calculateSetBounds(parent, children, ilctx, lctx, 'height', needtotals);
        margin = lctx.margin;
        me.flex(parent, children, ilctx, lctx, proccessors);
    },
    /**
     * Common processor for both vflex and hflex layout utilities
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @param {type} proccessors
     * @returns {undefined}
     */
    flex: function (parent, children, ilctx, lctx, proccessors) {
        var me = this, alignFn, packFn, ctx, a, len, el, bounds;
        len = children.length;
        for (a = 0; a !== len; a++) {
            el = children[a];
            ctx = ilctx[a];
            bounds = proccessors.bounds.apply(me, [el, ctx]);
            alignFn = proccessors.align[lctx.align];
            packFn = proccessors.pack[lctx.pack];
            packFn.apply(me, [bounds]);
            alignFn.apply(me, [bounds]);
            Blend.Style.set(el, bounds);
        }
    },
    /**
     * @internal
     * Update/Set the given layoutContext with:
     * [1] Maximum flex units of elements that are flexed
     * [2] Total width/height of fixed elements
     * @param {type} children
     * @param {type} lctx
     * @param {type} ilctx
     * @param {type} flexed_prop
     * @returns {undefined}
     */
    updateLayoutContext: function (children, lctx, ilctx, flexed_prop) {
        var me = this, maxFlex = 0, itm, total = 0, bounds;
        Blend.foreach(ilctx, function (ctx, idx) {
            itm = children[idx];
            bounds = Blend.Element.getBounds(itm);
            if (ctx.flex) {
                maxFlex++;
            } else {
                total += bounds[flexed_prop];
            }
        });
        lctx.maxFlex = maxFlex;
        lctx[flexed_prop] = total;
    },
    /**
     * @internal
     * Calculates and sets the bounds of flexed elements. This function also
     * sets the total units of widths/heights of all the elements to be used
     * later in the width/height calculations
     * @param {type} parent
     * @param {type} children
     * @param {type} ilctx
     * @param {type} lctx
     * @param {type} flexed_prop
     * @param {type} need_all_totals
     * @returns {undefined}
     */
    calculateSetBounds: function (parent, children, ilctx, lctx, flexed_prop, need_all_totals) {
        var me = this, alltotals = 0,
                ctx, unit,
                mrg = lctx.margin, omrg = mrg, avail, totalMargin = 0;

        need_all_totals = need_all_totals || false;

        //Update the layout context to get maxFlex and total width/height that is taken
        me.updateLayoutContext(children, lctx, ilctx, flexed_prop);

        if (lctx.maxFlex !== 0) {
            //omrg is the original margin
            mrg = Blend.isNumeric(omrg) ? mrg : 0;
            totalMargin = (children.length + 1) * mrg;
            var pbounds = Blend.Element.getBounds(parent);
            avail = (pbounds[flexed_prop] - totalMargin) - lctx[flexed_prop];
        }

        Blend.foreach(children, function (itm, idx) {
            ctx = ilctx[idx];
            if (ctx.flex) {
                unit = (avail * ctx.flex) / lctx.maxFlex;
                var o = {};
                o[flexed_prop] = unit;
                Blend.Style.set(itm, o);
            }
            if (need_all_totals) {
                if (unit) {
                    alltotals += unit;
                    ctx[flexed_prop] = unit; // For F** IE that does not return the
                    unit = null;
                } else {
                    var b = Blend.Element.getBounds(itm);
                    ctx[flexed_prop] = b[flexed_prop];
                    alltotals += b[flexed_prop];
                }
            }
        });
        if (need_all_totals) {
            if (!Blend.isNumeric(omrg) && omrg === true) {
                /*
                 * Calculate the distributed margin value
                 */
                mrg = (lctx.bounds[flexed_prop] - alltotals) / children.length;
                lctx.margin = mrg;
            }
            totalMargin = (children.length + 1) * mrg; // +1 is for the margin before the first element
            alltotals += totalMargin;
            lctx['total_' + flexed_prop] = alltotals;
        }

    }
});<|endoftext|>


<commit_before>'use strict';
var globalJson;
var globalThead;
var globalInnerKeys;
var asc = true;

function drawTable(theadArray, json, innerArrayKeys) {
  // for sorting and drawing again
  globalJson = json;
  globalThead = theadArray;
  globalInnerKeys = innerArrayKeys;

  // Create Table Heading first
  var html = '';
  html += "

";
  for (var heading in theadArray) {
    html += "" + theadArray[heading] + "	";
  }
  html += "

";
  // for  the tbody iterate over the json, and get the value of the keys in the theadArray
  for (var e in json) {
    html += "
";
    for (heading in theadArray) {

      var value = json[e][theadArray[heading]];
      // If a value is an array, then create an inner table within the td tag
      if (Array.isArray(value)) {
        html += "" + "
";
        html += "
";
        //Heading for innerTable
        for (var innerKey in innerArrayKeys) {
          html += "" + innerArrayKeys[innerKey] + "	";
        }
        html += "
";
        for (var innerArrayIndex in value) {
          html += "
";
          for (innerKey in innerArrayKeys) {
            html += "" + value[innerArrayIndex][innerArrayKeys[innerKey]] + "	";
          }
          html += "
";
        }
        html += "
	";
      } else {
        html += "" + value + "	";
      }
    }
    html += "
";
  }
  html += "

";

  $('#table-data').html(html);
}

function sortTable(element) {
  var id = element.id;
  //var asc = element.getAttribute('asc'); // switch the order, true if not set
  asc = asc ? false : true;
  sortResults(globalJson, id, asc);
  drawTable(globalThead, globalJson, globalInnerKeys);
}

/* Get Timespan from Datepicker or Timeslider, depending which of them is visible
   return : array with first element 1st datetime in ms and second 2nd datetime in ms
   */

function getTimespan() {
  var timespan = [];
  // Check which of the datepickers are visible
  if ($('#timeslider').is(":visible")) {
    timespan = dateSlider.noUiSlider.get();
  } else {
    var time1 = new Date($('#filterDateStart').datepicker('getDate').getTime());
    var time2 = new Date($('#filterDateEnd').datepicker('getDate').getTime());

    timespan[0] = (new Date(time1.getFullYear(), time1.getMonth())).getTime();
    timespan[1] = (new Date(time2.getFullYear(), time2.getMonth())).getTime();
    //alert("Datepicker: Time1:"+ timespan[0] + "Time2:" + timespan[1]);
  }

  return timespan;
}

/* Merge double Entry of Ciphersuites from different TLS Versions in the ciphers/summary response JSON
   returns summarized array
   */

function mergeDoubleEntrys(json, tlsVersion, totalHosts) {
  var summarized = [];
  for (var i = 0; i < json.length; i++) {
    var doubleEntry = false;
    // get a object from the summary
    var obj = json[i];
    // if TLS version is given
    if (tlsVersion) {
      if (obj.protocol === tlsVersion) {
        obj.percent = parseFloat(((obj.count / totalHosts) * 100).toFixed(2));
        summarized.push(obj);
      }
    } else {

      // iterate over summarized array and check for double entry
      for (var j = 0; j < summarized.length; j++) {
        // if entry found, add increase the count number of the first entry
        if (obj.cipher === summarized[j].cipher) {
          doubleEntry = true;
          summarized[j].count += obj.count;
        }
      }
      // if no double entry found, push the obj normally to the summarized arra
      if (!doubleEntry) {

        summarized.push(obj);
      }
      doubleEntry = false;

    }

  }

  return summarized;
}

// Compare function for sorting Array of JSONs
function sortResults(arr, prop, asc) {
  arr = arr.sort(function(a, b) {
    if (asc) {
      return (a[prop] > b[prop]);
    } else {
      return (b[prop] > a[prop]);
    }
  });
}

function formatDate2(date) {
  var string = date.getFullYear() + "_" + (date.getMonth() + 1);
  return string;
}

function filterResponseByTimespan(response, start, end) {
  var filtered = [];
  var date = new Date(start.getFullYear(), start.getMonth());
  var end = new Date(end.getFullYear(), end.getMonth());
  while (date.getTime() <= end.getTime()) {
    for (var i = 0; i < response.length; i++) {
      if (response[i].month === formatDate2(date) || response[i]._id === formatDate2(date)) {
        filtered.push(response[i]);
        break;
      }
    }
    // if value is 12, then the first month of the next year will be set
    date.setMonth(date.getMonth() + 1);
  }
  return filtered;
}

function getLatestElementIndex(response) {
  var latestElement = 0;
  for (var i = 0; i < response.length; i++) {
    var split = response[i].month.split('_');
    var comparedate = new Date(split[0], split[1] - 1);
    for (var j = i + 1; j < response.length; j++) {
      var split2 = response[j].month.split('_');
      if (comparedate.getTime() < new Date(split2[0], split2[1] - 1).getTime()) {
        latestElement = j;
      }
    }
  }
  return latestElement;
}

  $('#filterDateEnd').datepicker({
    format: "yyyy_mm",
    startView: 1,
    minViewMode: 1,
    autoclose: true,
    //setDate: new Date(2015,11),
    startDate: new Date(2015, 10),
    endDate: new Date(),
  });

  // default end date, this syntax is weird but it worked
  $('#filterDateEnd').datepicker('setDate', new Date(new Date().getFullYear(), new Date().getMonth()));

  $('#filterDateStart').datepicker({
    format: "yyyy_mm",
    viewMode: "months",
    minViewMode: "months",
    autoclose: true,
    startDate: new Date(2015, 10),
    endDate: new Date(),
  }).on('changeDate', function(e) {
    var month = e.date.getMonth();
    var year = e.date.getFullYear();
    var startDate = new Date(year, month);
    $('#filterDateEnd').datepicker('setStartDate', startDate);
    //$('#filterDateEnd').datepicker('setDate',  startDate);
  });

  // set default Beginn date
  $('#filterDateStart').datepicker('setDate', new Date(2015, 10));<commit_msg>add Documentation<commit_after>'use strict';
var globalJson;
var globalThead;
var globalInnerKeys;
var asc = true;

/*
 * Draws sortable Table from json object.
 * @param theadArray - Array with keys for the json object
 * @param json - json object
 * @param theadArray - Name of Table headings
 * @returns void
 */

function drawTable(theadArray, json, innerArrayKeys) {
  // Global Variables for sorting and drawing the chart again
  globalJson = json;
  globalThead = theadArray;
  globalInnerKeys = innerArrayKeys;

  // Create Table Heading first
  var html = '';
  html += "

";
  for (var heading in theadArray) {
    html += "" + theadArray[heading] + "	";
  }
  html += "

";
  // for  the tbody iterate over the json, and get the value of the keys in the theadArray
  for (var e in json) {
    html += "
";
    for (heading in theadArray) {

      var value = json[e][theadArray[heading]];
      // If a value is an array, then create an inner table within the td tag
      if (Array.isArray(value)) {
        html += "" + "
";
        html += "
";
        //Heading for innerTable
        for (var innerKey in innerArrayKeys) {
          html += "" + innerArrayKeys[innerKey] + "	";
        }
        html += "
";
        for (var innerArrayIndex in value) {
          html += "
";
          for (innerKey in innerArrayKeys) {
            html += "" + value[innerArrayIndex][innerArrayKeys[innerKey]] + "	";
          }
          html += "
";
        }
        html += "
	";
      } else {
        html += "" + value + "	";
      }
    }
    html += "
";
  }
  html += "

";

  $('#table-data').html(html);
}

/*
 * Sort alternating table by given element(table heading/key) and draws the Table again
 * @param element - the compare element
 * @returns void -
 */

function sortTable(element) {
  var id = element.id;
  //var asc = element.getAttribute('asc'); // switch the order, true if not set
  asc = asc ? false : true;
  sortResults(globalJson, id, asc);
  drawTable(globalThead, globalJson, globalInnerKeys);
}

/*
 * Get Timespan from Datepicker or Timeslider, depending which of them is visible
 * @returns array with first element 1st datetime in ms and second 2nd datetime in ms
 */

function getTimespan() {
  var timespan = [];
  // Check which of the datepickers are visible
  if ($('#timeslider').is(":visible")) {
    timespan = dateSlider.noUiSlider.get();
  } else {
    var time1 = new Date($('#filterDateStart').datepicker('getDate').getTime());
    var time2 = new Date($('#filterDateEnd').datepicker('getDate').getTime());

    timespan[0] = (new Date(time1.getFullYear(), time1.getMonth())).getTime();
    timespan[1] = (new Date(time2.getFullYear(), time2.getMonth())).getTime();
    //alert("Datepicker: Time1:"+ timespan[0] + "Time2:" + timespan[1]);
  }

  return timespan;
}

/*
 *  Merge double entries of Ciphersuites from different TLS Versions in the ciphers/summary response JSON
 * @param json - the json object to work in
 * @param tlsVersion - the TLS Version (1.2,1.1 or 1.0)
 * @param totalHosts - Number of totals hosts for calculating the percentage
 * @returns summarized array
 */

function mergeDoubleEntrys(json, tlsVersion, totalHosts) {
  var summarized = [];
  for (var i = 0; i < json.length; i++) {
    var doubleEntry = false;
    // get a object from the summary
    var obj = json[i];
    // if TLS version is given
    if (tlsVersion) {
      if (obj.protocol === tlsVersion) {
        obj.percent = parseFloat(((obj.count / totalHosts) * 100).toFixed(2));
        summarized.push(obj);
      }
    } else {

      // iterate over summarized array and check for double entry
      for (var j = 0; j < summarized.length; j++) {
        // if entry found, add increase the count number of the first entry
        if (obj.cipher === summarized[j].cipher) {
          doubleEntry = true;
          summarized[j].count += obj.count;
        }
      }
      // if no double entry found, push the obj normally to the summarized arra
      if (!doubleEntry) {

        summarized.push(obj);
      }
      doubleEntry = false;

    }

  }

  return summarized;
}

/*
 *   Compare function for sorting Array of JSONs
 * @param arr - the json object to work in
 * @param prop - the prop which is sorted by
 * @param {bool} asc - sort ascending or descending
 * @returns comparator
 */

function sortResults(arr, prop, asc) {
  arr = arr.sort(function(a, b) {
    if (asc) {
      return (a[prop] > b[prop]);
    } else {
      return (b[prop] > a[prop]);
    }
  });
}

/*
 * Date is stored in databse in specifig way (2015_12 e.g)
 * @param date - {date} the date
 * @returns formatted date
 */

function formatDate2(date) {
  var string = date.getFullYear() + "_" + (date.getMonth() + 1);
  return string;
}

/*
 * Filter response from API by given timespan.
 * @param response - the response json
 * @param start - start date
 * @param end - end date
 * @returns filtered json
 */

function filterResponseByTimespan(response, start, end) {
  var filtered = [];
  var date = new Date(start.getFullYear(), start.getMonth());
  var end = new Date(end.getFullYear(), end.getMonth());
  while (date.getTime() <= end.getTime()) {
    for (var i = 0; i < response.length; i++) {
      if (response[i].month === formatDate2(date) || response[i]._id === formatDate2(date)) {
        filtered.push(response[i]);
        break;
      }
    }
    // if value is 12, then the first month of the next year will be set
    date.setMonth(date.getMonth() + 1);
  }
  return filtered;
}

/*
 * Get the Index of the Latest Element in the response JSON.
 * @param response - the response json
 * @returns Index of latest Element in the response JSON
 */

function getLatestElementIndex(response) {
  var latestElement = 0;
  for (var i = 0; i < response.length; i++) {
    var split = response[i].month.split('_');
    var comparedate = new Date(split[0], split[1] - 1);
    for (var j = i + 1; j < response.length; j++) {
      var split2 = response[j].month.split('_');
      if (comparedate.getTime() < new Date(split2[0], split2[1] - 1).getTime()) {
        latestElement = j;
      }
    }
  }
  return latestElement;
}

// Bootstrap Datepicker - The End Time

$('#filterDateEnd').datepicker({
  format: "yyyy_mm",
  startView: 1,
  minViewMode: 1,
  autoclose: true,
  //setDate: new Date(2015,11),
  startDate: new Date(2015, 10),
  endDate: new Date(),
});

// default end date, this syntax is weird but it worked
$('#filterDateEnd').datepicker('setDate', new Date(new Date().getFullYear(), new Date().getMonth()));

// Boostrap Datepicker - Start time
$('#filterDateStart').datepicker({
  format: "yyyy_mm",
  viewMode: "months",
  minViewMode: "months",
  autoclose: true,
  startDate: new Date(2015, 10),
  endDate: new Date(),
}).on('changeDate', function(e) {
  var month = e.date.getMonth();
  var year = e.date.getFullYear();
  var startDate = new Date(year, month);
  $('#filterDateEnd').datepicker('setStartDate', startDate);
  //$('#filterDateEnd').datepicker('setDate',  startDate);
});

// set default Beginn date
$('#filterDateStart').datepicker('setDate', new Date(2015, 10));<|endoftext|>


<commit_before>(function($) {

	// options
	$.extend(mejs.MepDefaults, {
		duration: -1,
		timeAndDurationSeparator: '  |  '
	});

	// current and duration 00:00 / 00:00
	$.extend(MediaElementPlayer.prototype, {
		buildcurrent: function(player, controls, layers, media) {
			var t = this;

			$('
'+
					'' + (player.options.alwaysShowHours ? '00:' : '')
					+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ ''+
					'
')
					.appendTo(controls);

			t.currenttime = t.controls.find('.mejs-currenttime');

			media.addEventListener('timeupdate',function() {
				player.updateCurrent();
			}, false);
		},

		buildduration: function(player, controls, layers, media) {
			var t = this;

			if (controls.children().last().find('.mejs-currenttime').length > 0) {
				$(t.options.timeAndDurationSeparator +
					'' +
						(t.options.duration > 0 ?
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount,  t.options.framesPerSecond || 25) :
				   			((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
				   		) +
					'')
					.appendTo(controls.find('.mejs-time'));
			} else {

				// add class to current time
				controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');

				$('
'+
					'' +
						(t.options.duration > 0 ?
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount,  t.options.framesPerSecond || 25) :
				   			((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
				   		) +
					'' +
				'
')
				.appendTo(controls);
			}

			t.durationD = t.controls.find('.mejs-duration');

			media.addEventListener('timeupdate',function() {
				player.updateDuration();
			}, false);
		},

		updateCurrent:  function() {
			var t = this;

			if (t.currenttime) {
				t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount,  t.options.framesPerSecond || 25));
			}
		},

		updateDuration: function() {
			var t = this;

			//Toggle the long video class if the video is longer than an hour.
			t.container.toggleClass("mejs-long-video", t.media.duration > 3600);

			if (t.durationD && (t.options.duration > 0 || t.media.duration)) {
				t.durationD.html(mejs.Utility.secondsToTimeCode(t.options.duration > 0 ? t.options.duration : t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
			}
		}
	});

})(mejs.$);<commit_msg>change to separate element pipe to slash.<commit_after>(function($) {

	// options
	$.extend(mejs.MepDefaults, {
		duration: -1,
		timeAndDurationSeparator: '  /  '
	});

	// current and duration 00:00 / 00:00
	$.extend(MediaElementPlayer.prototype, {
		buildcurrent: function(player, controls, layers, media) {
			var t = this;

			$('
'+
					'' + (player.options.alwaysShowHours ? '00:' : '')
					+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ ''+
					'
')
					.appendTo(controls);

			t.currenttime = t.controls.find('.mejs-currenttime');

			media.addEventListener('timeupdate',function() {
				player.updateCurrent();
			}, false);
		},

		buildduration: function(player, controls, layers, media) {
			var t = this;

			if (controls.children().last().find('.mejs-currenttime').length > 0) {
				$(t.options.timeAndDurationSeparator +
					'' +
						(t.options.duration > 0 ?
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount,  t.options.framesPerSecond || 25) :
				   			((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
				   		) +
					'')
					.appendTo(controls.find('.mejs-time'));
			} else {

				// add class to current time
				controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');

				$('
'+
					'' +
						(t.options.duration > 0 ?
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount,  t.options.framesPerSecond || 25) :
				   			((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
				   		) +
					'' +
				'
')
				.appendTo(controls);
			}

			t.durationD = t.controls.find('.mejs-duration');

			media.addEventListener('timeupdate',function() {
				player.updateDuration();
			}, false);
		},

		updateCurrent:  function() {
			var t = this;

			if (t.currenttime) {
				t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount,  t.options.framesPerSecond || 25));
			}
		},

		updateDuration: function() {
			var t = this;

			//Toggle the long video class if the video is longer than an hour.
			t.container.toggleClass("mejs-long-video", t.media.duration > 3600);

			if (t.durationD && (t.options.duration > 0 || t.media.duration)) {
				t.durationD.html(mejs.Utility.secondsToTimeCode(t.options.duration > 0 ? t.options.duration : t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
			}
		}
	});

})(mejs.$);
<|endoftext|>


<commit_before>var util = require('../util');

var constants = require('../util/constants');
var intl = require('../intl');

var Commands = require('../commands');
var Errors = require('../util/errors');
var CommandProcessError = Errors.CommandProcessError;
var LocaleStore = require('../stores/LocaleStore');
var LocaleActions = require('../actions/LocaleActions');
var LevelStore = require('../stores/LevelStore');
var GlobalStateStore = require('../stores/GlobalStateStore');
var GlobalStateActions = require('../actions/GlobalStateActions');
var GitError = Errors.GitError;
var Warning = Errors.Warning;
var CommandResult = Errors.CommandResult;

var instantCommands = [
  [/^ls( |$)/, function() {
    throw new CommandResult({
      msg: intl.str('ls-command')
    });
  }],
  [/^cd( |$)/, function() {
    throw new CommandResult({
      msg: intl.str('cd-command')
    });
  }],
  [/^(locale|locale reset)$/, function(bits) {
    LocaleActions.changeLocale(
      LocaleStore.getDefaultLocale()
    );

    throw new CommandResult({
      msg: intl.str(
        'locale-reset-command',
        { locale: LocaleStore.getDefaultLocale() }
      )
    });
  }],
  [/^show$/, function(bits) {
    var lines = [
      intl.str('show-command'),
      '
',
      'show commands',
      'show solution',
      'show goal'
    ];

    throw new CommandResult({
      msg: lines.join('\n')
    });
  }],
  [/^alias (\w+)="(.+)"$/, function(bits) {
    const alias = bits[1];
    const expansion = bits[2];
    LevelStore.addToAliasMap(alias, expansion);
    throw new CommandResult({
      msg: 'Set alias "'+alias+'" to "'+expansion+'"',
    });
  }],
  [/^unalias (\w+)$/, function(bits) {
    const alias = bits[1];
    LevelStore.removeFromAliasMap(alias);
    throw new CommandResult({
      msg: 'Removed alias "'+alias+'"',
    });
  }],
  [/^locale (\w+)$/, function(bits) {
    LocaleActions.changeLocale(bits[1]);
    throw new CommandResult({
      msg: intl.str(
        'locale-command',
        { locale: bits[1] }
      )
    });
  }],
  [/^flip$/, function() {
    GlobalStateActions.changeFlipTreeY(
      !GlobalStateStore.getFlipTreeY()
    );
    require('../app').getEvents().trigger('refreshTree');
    throw new CommandResult({
      msg: intl.str('flip-tree-command')
    });
  }],
  [/^disableLevelInstructions$/, function() {
    GlobalStateActions.disableLevelInstructions();
    throw new CommandResult({
      msg: intl.todo('Level instructions disabled'),
    });
  }],
  [/^refresh$/, function() {
    var events = require('../app').getEvents();

    events.trigger('refreshTree');
    throw new CommandResult({
      msg: intl.str('refresh-tree-command')
    });
  }],
  [/^rollup (\d+)$/, function(bits) {
    var events = require('../app').getEvents();

    // go roll up these commands by joining them with semicolons
    events.trigger('rollupCommands', bits[1]);
    throw new CommandResult({
      msg: 'Commands combined!'
    });
  }],
  [/^echo "(.*?)"$|^echo (.*?)$/, function(bits) {
    var msg = bits[1] || bits[2];
    throw new CommandResult({
      msg: msg
    });
  }],
  [/^show +commands$/, function(bits) {
    var allCommands = getAllCommands();
    var lines = [
      intl.str('show-all-commands'),
      '
'
    ];
    Object.keys(allCommands)
      .forEach(function(command) {
        lines.push(command);
      });

    throw new CommandResult({
      msg: lines.join('\n')
    });
  }]
];

var regexMap = {
  'reset solved': /^reset solved($|\s)/,
  'help': /^help( +general)?$|^\?$/,
  'reset': /^reset( +--forSolution)?$/,
  'delay': /^delay (\d+)$/,
  'clear': /^clear($|\s)/,
  'exit level': /^exit level($|\s)/,
  'sandbox': /^sandbox($|\s)/,
  'level': /^level\s?([a-zA-Z0-9]*)/,
  'levels': /^levels($|\s)/,
  'mobileAlert': /^mobile alert($|\s)/,
  'build level': /^build +level\s?([a-zA-Z0-9]*)$/,
  'export tree': /^export +tree$/,
  'importTreeNow': /^importTreeNow($|\s)/,
  'importLevelNow': /^importLevelNow($|\s)/,
  'import tree': /^import +tree$/,
  'import level': /^import +level$/,
  'undo': /^undo($|\s)/,
  'share permalink': /^share( +permalink)?$/
};

var getAllCommands = function() {
  var toDelete = [
    'mobileAlert'
  ];

  var allCommands = Object.assign(
    {},
    require('../level').regexMap,
    regexMap
  );
  var mRegexMap = Commands.commands.getRegexMap();
  Object.keys(mRegexMap).forEach(function(vcs) {
    var map = mRegexMap[vcs];
    Object.keys(map).forEach(function(method) {
      var regex = map[method];
      allCommands[vcs + ' ' + method] = regex;
    });
  });
  toDelete.forEach(function(key) {
    delete allCommands[key];
  });

  return allCommands;
};

exports.instantCommands = instantCommands;
exports.parse = util.genParseCommand(regexMap, 'processSandboxCommand');

// optimistically parse some level and level builder commands; we do this
// so you can enter things like "level intro1; show goal" and not
// have it barf. when the
// command fires the event, it will check if there is a listener and if not throw
// an error

// note: these are getters / setters because the require kills us
exports.getOptimisticLevelParse = function() {
  return util.genParseCommand(
    require('../level').regexMap,
    'processLevelCommand'
  );
};

exports.getOptimisticLevelBuilderParse = function() {
  return util.genParseCommand(
    require('../level/builder').regexMap,
    'processLevelBuilderCommand'
  );
};
<commit_msg>Issue #845 -- show options for each command<commit_after>var util = require('../util');

var constants = require('../util/constants');
var intl = require('../intl');

var Commands = require('../commands');
var Errors = require('../util/errors');
var CommandProcessError = Errors.CommandProcessError;
var LocaleStore = require('../stores/LocaleStore');
var LocaleActions = require('../actions/LocaleActions');
var LevelStore = require('../stores/LevelStore');
var GlobalStateStore = require('../stores/GlobalStateStore');
var GlobalStateActions = require('../actions/GlobalStateActions');
var GitError = Errors.GitError;
var Warning = Errors.Warning;
var CommandResult = Errors.CommandResult;

var instantCommands = [
  [/^ls( |$)/, function() {
    throw new CommandResult({
      msg: intl.str('ls-command')
    });
  }],
  [/^cd( |$)/, function() {
    throw new CommandResult({
      msg: intl.str('cd-command')
    });
  }],
  [/^(locale|locale reset)$/, function(bits) {
    LocaleActions.changeLocale(
      LocaleStore.getDefaultLocale()
    );

    throw new CommandResult({
      msg: intl.str(
        'locale-reset-command',
        { locale: LocaleStore.getDefaultLocale() }
      )
    });
  }],
  [/^show$/, function(bits) {
    var lines = [
      intl.str('show-command'),
      '
',
      'show commands',
      'show solution',
      'show goal'
    ];

    throw new CommandResult({
      msg: lines.join('\n')
    });
  }],
  [/^alias (\w+)="(.+)"$/, function(bits) {
    const alias = bits[1];
    const expansion = bits[2];
    LevelStore.addToAliasMap(alias, expansion);
    throw new CommandResult({
      msg: 'Set alias "'+alias+'" to "'+expansion+'"',
    });
  }],
  [/^unalias (\w+)$/, function(bits) {
    const alias = bits[1];
    LevelStore.removeFromAliasMap(alias);
    throw new CommandResult({
      msg: 'Removed alias "'+alias+'"',
    });
  }],
  [/^locale (\w+)$/, function(bits) {
    LocaleActions.changeLocale(bits[1]);
    throw new CommandResult({
      msg: intl.str(
        'locale-command',
        { locale: bits[1] }
      )
    });
  }],
  [/^flip$/, function() {
    GlobalStateActions.changeFlipTreeY(
      !GlobalStateStore.getFlipTreeY()
    );
    require('../app').getEvents().trigger('refreshTree');
    throw new CommandResult({
      msg: intl.str('flip-tree-command')
    });
  }],
  [/^disableLevelInstructions$/, function() {
    GlobalStateActions.disableLevelInstructions();
    throw new CommandResult({
      msg: intl.todo('Level instructions disabled'),
    });
  }],
  [/^refresh$/, function() {
    var events = require('../app').getEvents();

    events.trigger('refreshTree');
    throw new CommandResult({
      msg: intl.str('refresh-tree-command')
    });
  }],
  [/^rollup (\d+)$/, function(bits) {
    var events = require('../app').getEvents();

    // go roll up these commands by joining them with semicolons
    events.trigger('rollupCommands', bits[1]);
    throw new CommandResult({
      msg: 'Commands combined!'
    });
  }],
  [/^echo "(.*?)"$|^echo (.*?)$/, function(bits) {
    var msg = bits[1] || bits[2];
    throw new CommandResult({
      msg: msg
    });
  }],
  [/^show +commands$/, function(bits) {
    var allCommands = getAllCommands();
    var allOptions = Commands.commands.getOptionMap();
    var commandToOptions = {};

    Object.keys(allOptions).forEach(function(vcs) {
      var vcsMap = allOptions[vcs];
      Object.keys(vcsMap).forEach(function(method) {
        var options = vcsMap[method];
        if (options) {
          commandToOptions[vcs + ' ' + method] = Object.keys(options).filter(option => option.length > 1);
        }
      });
    });

    var lines = [
      intl.str('show-all-commands'),
      '
'
    ];
    Object.keys(allCommands)
      .forEach(function(command) {
        lines.push(command);
        if (commandToOptions[command]) {
          commandToOptions[command].forEach(option => lines.push('    ' + option));
        }
      });

    throw new CommandResult({
      msg: lines.join('\n')
    });
  }]
];

var regexMap = {
  'reset solved': /^reset solved($|\s)/,
  'help': /^help( +general)?$|^\?$/,
  'reset': /^reset( +--forSolution)?$/,
  'delay': /^delay (\d+)$/,
  'clear': /^clear($|\s)/,
  'exit level': /^exit level($|\s)/,
  'sandbox': /^sandbox($|\s)/,
  'level': /^level\s?([a-zA-Z0-9]*)/,
  'levels': /^levels($|\s)/,
  'mobileAlert': /^mobile alert($|\s)/,
  'build level': /^build +level\s?([a-zA-Z0-9]*)$/,
  'export tree': /^export +tree$/,
  'importTreeNow': /^importTreeNow($|\s)/,
  'importLevelNow': /^importLevelNow($|\s)/,
  'import tree': /^import +tree$/,
  'import level': /^import +level$/,
  'undo': /^undo($|\s)/,
  'share permalink': /^share( +permalink)?$/
};

var getAllCommands = function() {
  var toDelete = [
    'mobileAlert'
  ];

  var allCommands = Object.assign(
    {},
    require('../level').regexMap,
    regexMap
  );
  var mRegexMap = Commands.commands.getRegexMap();
  Object.keys(mRegexMap).forEach(function(vcs) {
    var map = mRegexMap[vcs];
    Object.keys(map).forEach(function(method) {
      var regex = map[method];
      allCommands[vcs + ' ' + method] = regex;
    });
  });
  toDelete.forEach(function(key) {
    delete allCommands[key];
  });

  return allCommands;
};

exports.instantCommands = instantCommands;
exports.parse = util.genParseCommand(regexMap, 'processSandboxCommand');

// optimistically parse some level and level builder commands; we do this
// so you can enter things like "level intro1; show goal" and not
// have it barf. when the
// command fires the event, it will check if there is a listener and if not throw
// an error

// note: these are getters / setters because the require kills us
exports.getOptimisticLevelParse = function() {
  return util.genParseCommand(
    require('../level').regexMap,
    'processLevelCommand'
  );
};

exports.getOptimisticLevelBuilderParse = function() {
  return util.genParseCommand(
    require('../level/builder').regexMap,
    'processLevelBuilderCommand'
  );
};
<|endoftext|>


<commit_before>import React from 'react';

import BlockUser from './components.block-user';

class UserList extends React.Component {
  render() {
    return (

        <BlockUser/>
        <BlockUser/>
        <BlockUser/>
        <BlockUser/>
        <BlockUser/>

    );
  }

  // functions.
}

export default UserList;
<commit_msg>add props to user-list component<commit_after>import React from 'react';

import BlockUser from './components.block-user';

class UserList extends React.Component {
  render() {
    let users = renderUsers(this.props.users);

    return (

        {users}

    );
  }
}

UserList.propTypes = {
  users: React.PropTypes.array,
};

function renderUsers(users) {
  if (users.length > 0) {
    return users.map((user, index) => (
      <BlockUser
        id={ user.id }
        name={ user.firstName }
        description={ user.description }
        lastMessage={ user.lastMessage }
        imageSource={ user.imageSource }
        lastSeenDate={ user.lastSeenDate }
        lastMessageDate={ user.lastMessageDate }
        unreadMessagesLength={ user.unreadMessagesLength }
      />
    ));
  }

  else { return []; }
}

export default UserList;
<|endoftext|>


<commit_before>import {EventEmitter} from 'events';

import {
  DCOS_CHANGE,
  MESOS_SUMMARY_CHANGE,
  MARATHON_GROUPS_CHANGE,
  MARATHON_SERVICE_VERSION_CHANGE,
  MARATHON_SERVICE_VERSIONS_CHANGE
} from '../constants/EventTypes';
import Framework from '../structs/Framework';
import MarathonStore from './MarathonStore';
import MesosSummaryStore from './MesosSummaryStore';
import ServiceTree from '../structs/ServiceTree';
import SummaryList from '../structs/SummaryList';

const METHODS_TO_BIND = [
  'onMarathonGroupsChange',
  'onMarathonServiceVersionChange',
  'onMarathonServiceVersionsChange',
  'onMesosSummaryChange'
];

class DCOSStore extends EventEmitter {

  constructor() {
    super(...arguments);

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });

    this.data = {
      marathon: {
        serviceTree: new ServiceTree(),
        versions: new Map()
      },
      mesos: new SummaryList(),
      dataProcessed: false
    };

    this.proxyListeners = [
      {
        event: MARATHON_GROUPS_CHANGE,
        handler: this.onMarathonGroupsChange,
        store: MarathonStore
      },
      {
        event: MARATHON_SERVICE_VERSION_CHANGE,
        handler: this.onMarathonServiceVersionChange,
        store: MarathonStore
      },
      {
        event: MARATHON_SERVICE_VERSIONS_CHANGE,
        handler: this.onMarathonServiceVersionsChange,
        store: MarathonStore
      },
      {
        event: MESOS_SUMMARY_CHANGE,
        handler: this.onMesosSummaryChange,
        store: MesosSummaryStore
      }
    ];
  }

  /**
   * Fetch service version/configuration from Marathon
   * @param {string} serviceID
   * @param {string} versionID
   */
  fetchServiceVersion(serviceID, versionID) {
    MarathonStore.fetchServiceVersion(serviceID, versionID);
  }

  /**
   * Fetch service versions/configurations from Marathon
   * @param {string} serviceID
   */
  fetchServiceVersions(serviceID) {
    MarathonStore.fetchServiceVersions(serviceID);
  }

  onMarathonGroupsChange() {
    let serviceTree = MarathonStore.get('groups');
    if (!(serviceTree instanceof ServiceTree)) {
      return;
    }

    this.data.marathon.serviceTree = serviceTree;
    this.data.dataProcessed = true;
    this.emit(DCOS_CHANGE);
  }

  onMarathonServiceVersionChange({serviceID, versionID, version}) {
    let {marathon:{versions}} = this.data;
    let currentVersions = versions.get(serviceID);

    if (!currentVersions) {
      currentVersions = new Map();
      versions.set(serviceID, currentVersions);
    }

    currentVersions.set(versionID, version);

    this.emit(DCOS_CHANGE);
  }

  onMarathonServiceVersionsChange({serviceID, versions:nextVersions}) {
    let {marathon:{versions}} = this.data;
    let currentVersions = versions.get(serviceID);

    if (currentVersions) {
      nextVersions = new Map([...nextVersions, ...currentVersions]);
    }

    versions.set(serviceID, nextVersions);
    this.emit(DCOS_CHANGE);
  }

  onMesosSummaryChange() {
    let states = MesosSummaryStore.get('states');
    if (!(states instanceof SummaryList)) {
      return;
    }

    this.data.mesos = states;
    this.emit(DCOS_CHANGE);
  }

  addProxyListeners() {
    this.proxyListeners.forEach(function (item) {
      item.store.addChangeListener(item.event, item.handler);
    });
  }

  removeProxyListeners() {
    this.proxyListeners.forEach(function (item) {
      item.store.removeChangeListener(item.event, item.handler);
    });
  }

  addChangeListener(eventName, callback) {
    this.on(eventName, callback);
  }

  removeChangeListener(eventName, callback) {
    this.removeListener(eventName, callback);
  }

  /**
   * Adds the listener for the specified event
   * @param {string} eventName
   * @param {Function} callback
   * @return {DCOSStore} DCOSStore instance
   * @override
   */
  on(eventName, callback) {
    // Only add proxy listeners if not already listening
    if (this.listeners().length === 0) {
      this.addProxyListeners();
    }

    return super.on(eventName, callback);
  }

  /**
   * Remove the specified listener for the specified event
   * @param {string} eventName
   * @param {Function} callback
   * @return {DCOSStore} DCOSStore instance
   * @override
   */
  removeListener(eventName, callback) {
    super.removeListener(eventName, callback);
    // Remove proxy listeners if no one is listening
    if (this.listeners().length === 0) {
      this.removeProxyListeners();
    }

    return this;
  }

  /**
   * @type {ServiceTree}
   */
  get serviceTree() {
    let {marathon:{serviceTree, versions}, mesos} = this.data;

    // Create framework dict from Mesos data
    let frameworks = mesos.lastSuccessful().getServiceList()
      .reduceItems(function (memo, framework) {
        memo[framework.name] = framework;

        return memo;
      }, {});

    // Merge data by framework name, as  Marathon doesn't know framework ids.
    return serviceTree.mapItems(function (item) {
      if (item instanceof ServiceTree) {
        return item;
      }

      let options = {versions: versions.get(item.getId())};

      if (item instanceof Framework) {
        options = Object.assign(options, frameworks[item.getName()]);
      }

      return new item.constructor(
        Object.assign(options, item)
      );
    });

  }

  get dataProcessed() {
    return this.data.dataProcessed;
  }

  get storeID() {
    return 'dcos';
  }
}

module.exports = new DCOSStore();
<commit_msg>Integrate Chronos into DCOS store<commit_after>import {EventEmitter} from 'events';

import {
  CHRONOS_CHANGE,
  DCOS_CHANGE,
  MESOS_SUMMARY_CHANGE,
  MARATHON_GROUPS_CHANGE,
  MARATHON_SERVICE_VERSION_CHANGE,
  MARATHON_SERVICE_VERSIONS_CHANGE
} from '../constants/EventTypes';
import ChronosStore from '../stores/ChronosStore';
import Framework from '../structs/Framework';
import JobTree from '../structs/JobTree';
import MarathonStore from './MarathonStore';
import MesosSummaryStore from './MesosSummaryStore';
import ServiceTree from '../structs/ServiceTree';
import SummaryList from '../structs/SummaryList';

const METHODS_TO_BIND = [
  'onChronosChange',
  'onMarathonGroupsChange',
  'onMarathonServiceVersionChange',
  'onMarathonServiceVersionsChange',
  'onMesosSummaryChange'
];

class DCOSStore extends EventEmitter {

  constructor() {
    super(...arguments);

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });

    this.data = {
      marathon: {
        serviceTree: new ServiceTree(),
        versions: new Map()
      },
      chronos: {
        jobTree: new JobTree(),
      },
      mesos: new SummaryList(),
      dataProcessed: false
    };

    this.proxyListeners = [
      {
        event: CHRONOS_CHANGE,
        handler: this.onChronosChange,
        store: ChronosStore
      },
      {
        event: MARATHON_GROUPS_CHANGE,
        handler: this.onMarathonGroupsChange,
        store: MarathonStore
      },
      {
        event: MARATHON_SERVICE_VERSION_CHANGE,
        handler: this.onMarathonServiceVersionChange,
        store: MarathonStore
      },
      {
        event: MARATHON_SERVICE_VERSIONS_CHANGE,
        handler: this.onMarathonServiceVersionsChange,
        store: MarathonStore
      },
      {
        event: MESOS_SUMMARY_CHANGE,
        handler: this.onMesosSummaryChange,
        store: MesosSummaryStore
      }
    ];
  }

  /**
   * Fetch service version/configuration from Marathon
   * @param {string} serviceID
   * @param {string} versionID
   */
  fetchServiceVersion(serviceID, versionID) {
    MarathonStore.fetchServiceVersion(serviceID, versionID);
  }

  /**
   * Fetch service versions/configurations from Marathon
   * @param {string} serviceID
   */
  fetchServiceVersions(serviceID) {
    MarathonStore.fetchServiceVersions(serviceID);
  }

  onMarathonGroupsChange() {
    let serviceTree = MarathonStore.get('groups');
    if (!(serviceTree instanceof ServiceTree)) {
      return;
    }

    this.data.marathon.serviceTree = serviceTree;
    this.data.dataProcessed = true;
    this.emit(DCOS_CHANGE);
  }

  onMarathonServiceVersionChange({serviceID, versionID, version}) {
    let {marathon:{versions}} = this.data;
    let currentVersions = versions.get(serviceID);

    if (!currentVersions) {
      currentVersions = new Map();
      versions.set(serviceID, currentVersions);
    }

    currentVersions.set(versionID, version);

    this.emit(DCOS_CHANGE);
  }

  onMarathonServiceVersionsChange({serviceID, versions:nextVersions}) {
    let {marathon:{versions}} = this.data;
    let currentVersions = versions.get(serviceID);

    if (currentVersions) {
      nextVersions = new Map([...nextVersions, ...currentVersions]);
    }

    versions.set(serviceID, nextVersions);
    this.emit(DCOS_CHANGE);
  }

  onMesosSummaryChange() {
    let states = MesosSummaryStore.get('states');
    if (!(states instanceof SummaryList)) {
      return;
    }

    this.data.mesos = states;
    this.emit(DCOS_CHANGE);
  }

  onChronosChange() {
    this.data.chronos.jobTree = ChronosStore.jobTree;
    this.emit(DCOS_CHANGE);
  }

  addProxyListeners() {
    this.proxyListeners.forEach(function (item) {
      item.store.addChangeListener(item.event, item.handler);
    });
  }

  removeProxyListeners() {
    this.proxyListeners.forEach(function (item) {
      item.store.removeChangeListener(item.event, item.handler);
    });
  }

  addChangeListener(eventName, callback) {
    this.on(eventName, callback);
  }

  removeChangeListener(eventName, callback) {
    this.removeListener(eventName, callback);
  }

  /**
   * Adds the listener for the specified event
   * @param {string} eventName
   * @param {Function} callback
   * @return {DCOSStore} DCOSStore instance
   * @override
   */
  on(eventName, callback) {
    // Only add proxy listeners if not already listening
    if (this.listeners().length === 0) {
      this.addProxyListeners();
    }

    return super.on(eventName, callback);
  }

  /**
   * Remove the specified listener for the specified event
   * @param {string} eventName
   * @param {Function} callback
   * @return {DCOSStore} DCOSStore instance
   * @override
   */
  removeListener(eventName, callback) {
    super.removeListener(eventName, callback);
    // Remove proxy listeners if no one is listening
    if (this.listeners().length === 0) {
      this.removeProxyListeners();
    }

    return this;
  }

  /**
   * @type {JobTree}
   */
  get jobTree() {
    return this.data.chronos.jobTree;
  }

  /**
   * @type {ServiceTree}
   */
  get serviceTree() {
    let {marathon:{serviceTree, versions}, mesos} = this.data;

    // Create framework dict from Mesos data
    let frameworks = mesos.lastSuccessful().getServiceList()
      .reduceItems(function (memo, framework) {
        memo[framework.name] = framework;

        return memo;
      }, {});

    // Merge data by framework name, as  Marathon doesn't know framework ids.
    return serviceTree.mapItems(function (item) {
      if (item instanceof ServiceTree) {
        return item;
      }

      let options = {versions: versions.get(item.getId())};

      if (item instanceof Framework) {
        options = Object.assign(options, frameworks[item.getName()]);
      }

      return new item.constructor(
        Object.assign(options, item)
      );
    });

  }

  get dataProcessed() {
    return this.data.dataProcessed;
  }

  get storeID() {
    return 'dcos';
  }
}

module.exports = new DCOSStore();
<|endoftext|>


<commit_before>(function($) {
  var clickableElement = function(ele) {
    return _.any(['a', 'input', 'textarea', 'button', 'object'], function(tn) {
      return jQuery.nodeName(ele, tn);
    });
  };
  var render_from_server_paragraph = {
    // status: ['rendered', 'rendering', 'editing']
    //   rendering => rendered
    //   rendered => editing
    //   editing => rendering
    emit: function(div, item) {
      if (item.text === "") {
        div.data('status', 'rendered');
        return div.empty();
      } else {
        div.data('status', 'rendering');
        this.parents('.card_editor').card_editor('renderWiki', item.text, function(html) {
          if (div.data('status') == 'rendering') {
            div.data('status', 'rendered');
            div.find('img').remove();
            div.append(html);
          }
        });
        return div.html('');
      }
    },
    bind: function(div, item) {
      var $this = this;
      div.bind('dblclick', function(e) {
        if (clickableElement(e.target) || !$this.story_item('editable')) {
          return;
        }
        if (div.data('status') == 'rendering') {
          alert("Please wait for server rendering " + item.text + "");
        } else {
          div.data('status', 'editing');
          $this.story_item('edit');
        }
      });
    },
    edit: function(item) {
      return this.wikimate_text_editor('init');
    }
  };

  if (window.wikimate && window.wikimate.plugins) {
    $.extend(window.wikimate.plugins, {
      paragraph: render_from_server_paragraph,
      macro: $.extend({title: 'Macro'}, render_from_server_paragraph),
      body_macro: $.extend({}, render_from_server_paragraph),
      html: $.extend({}, render_from_server_paragraph)
    });
  } else {
    console.log("No window.wikimate or window.wikimate.plugins found");
  }
})(jQuery);

<commit_msg>custom rdoc editor options to remove all plugins that need popup<commit_after>(function($) {
  var clickableElement = function(ele) {
    return _.any(['a', 'input', 'textarea', 'button', 'object'], function(tn) {
      return jQuery.nodeName(ele, tn);
    });
  };
  var render_from_server_paragraph = {
    // status: ['rendered', 'rendering', 'editing']
    //   rendering => rendered
    //   rendered => editing
    //   editing => rendering
    emit: function(div, item) {
      if (item.text === "") {
        div.data('status', 'rendered');
        return div.empty();
      } else {
        div.data('status', 'rendering');
        this.parents('.card_editor').card_editor('renderWiki', item.text, function(html) {
          if (div.data('status') == 'rendering') {
            div.data('status', 'rendered');
            div.find('img').remove();
            div.append(html);
          }
        });
        return div.html('');
      }
    },
    bind: function(div, item) {
      var $this = this;
      div.bind('dblclick', function(e) {
        if (clickableElement(e.target) || !$this.story_item('editable')) {
          return;
        }
        if (div.data('status') == 'rendering') {
          alert("Please wait for server rendering " + item.text + "");
        } else {
          div.data('status', 'editing');
          $this.story_item('edit');
        }
      });
    },
    edit: function(item) {
      return this.wikimate_text_editor('init');
    }
  };

  if (window.wikimate && window.wikimate.plugins) {
    $.extend(window.wikimate.plugins, {
      paragraph: render_from_server_paragraph,
      macro: $.extend({title: 'Macro'}, render_from_server_paragraph),
      body_macro: $.extend({}, render_from_server_paragraph),
      html: $.extend({}, render_from_server_paragraph)
    });
    window.wikimate.plugins.rdoc.editor_options = {
      plugins: "advlink,advlist,autoresize,autolink,save,fullscreen,lists",
      theme_advanced_buttons1: "save,cancel,|,formatselect,bold,italic,underline,strikethrough,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,unlink,removeformat,fullscreen,|,justifyleft,justifycenter,justifyright",
      theme_advanced_buttons2: ""
    };
  } else {
    console.log("No window.wikimate or window.wikimate.plugins found");
  }
})(jQuery);

<|endoftext|>


<commit_before>/* Copyright 2015, Yahoo Inc.
   Copyrights licensed under the MIT License.
   See the accompanying LICENSE file for terms. */
// Karma configuration

module.exports = function(config) {
  var sharedConf = require('./karma.shared')(config);

  // Coverage
  sharedConf.browserify.transform.push([
    'browserify-istanbul', {
      ignore: [
        '**/src/scrollable.js',
        '**/src/scroller-events-stub.js',
        '**/__tests__/**',
        '**/vendor/**'
      ],
    }
  ]);

  sharedConf.reporters.push("coverage");
  sharedConf.files = ['./node_modules/phantomjs-polyfill/bind-polyfill.js'].concat(sharedConf.files);

  var options = {

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      'PhantomJS',
      // 'Chrome',
    ],

    // optionally, configure the reporter
    coverageReporter: {
      type : 'json',
      dir : 'coverage/'
    },

    reporters: ["spec", "coverage"],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

  };

  for(var key in options) {
    sharedConf[key] = options[key];
  }
  config.set(sharedConf);
};
<commit_msg>Add more ignores to coverage, as well as explaining exceptions<commit_after>/* Copyright 2015, Yahoo Inc.
   Copyrights licensed under the MIT License.
   See the accompanying LICENSE file for terms. */
// Karma configuration

module.exports = function(config) {
  var sharedConf = require('./karma.shared')(config);

  // Coverage
  sharedConf.browserify.transform.push([
    'browserify-istanbul', {
      ignore: [
        '**/src/scrollable.js', // just a wrapper
        '**/src/prefixed.js', // almost a vendor library, tested on original project
        '**/src/scroller-events.js', // this is better tested by integration tests
                                     // at the moment, is tested internally at Yahoo, on
                                     // products integration tests. Will bootstrap a
                                     // integration suite later for this repository.
        '**/src/scroller-events-stub.js', // just for server-side
        '**/__tests__/**',
        '**/vendor/**'
      ],
    }
  ]);

  sharedConf.reporters.push("coverage");
  sharedConf.files = ['./node_modules/phantomjs-polyfill/bind-polyfill.js'].concat(sharedConf.files);

  var options = {

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      'PhantomJS',
      // 'Chrome',
    ],

    // optionally, configure the reporter
    coverageReporter: {
      type : 'json',
      dir : 'coverage/'
    },

    reporters: ["spec", "coverage"],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

  };

  for(var key in options) {
    sharedConf[key] = options[key];
  }
  config.set(sharedConf);
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

exports.IMPORT_RE = /(\bimport\s+(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g;
exports.EXPORT_RE = /(\bexport\s+(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g;
exports.REQUIRE_RE = /(\brequire\s*?\(\s*?)(['"])([^'"]+)(\2\s*?\))/g;
<commit_msg>Add backticks into require call parse<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

exports.IMPORT_RE = /(\bimport\s+(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g;
exports.EXPORT_RE = /(\bexport\s+(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g;
exports.REQUIRE_RE = /(\brequire\s*?\(\s*?)(['"`])([^'"`]+)(\2\s*?\))/g;
<|endoftext|>


<commit_before>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 3.1.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.ModalCustomerCommentEdit = {

    init : function() {

        var modalSelector = '#customer-comment-edit-form';

        foodcoopshop.Modal.appendModalToDom(
            modalSelector,
            foodcoopshop.LocalizedJs.modalCustomer.ChangeMemberComment,
            foodcoopshop.ModalCustomerCommentEdit.getHtml()
        );

        foodcoopshop.Modal.bindSaveButton(modalSelector, function() {
            foodcoopshop.ModalCustomerCommentEdit.getSaveHandler(modalSelector);
        });

        $(modalSelector).on('hidden.bs.modal', function (e) {
            foodcoopshop.ModalCustomerCommentEdit.getCloseHandler();
        });

        $('.customer-comment-edit-button').on('click', function () {
            foodcoopshop.ModalCustomerCommentEdit.getOpenHandler($(this), modalSelector);
        });

    },

    getHtml : function() {
        return `

                <textarea class="ckeditor" name="dialogCustomerComment" id="dialogCustomerComment"></textarea>

            <input type="hidden" name="dialogCustomerId" id="dialogCustomerId" value="" />
        `;
    },

    getCloseHandler : function() {
        $('#cke_dialogCustomerComment').val('');
        $('#dialogCustomerId').val('');
    },

    getSaveHandler : function() {

        if ($('#dialogCustomerId').val() == '') {
            return false;
        }

        foodcoopshop.Helper.ajaxCall(
            '/admin/customers/editComment/',
            {
                customerId: $('#dialogCustomerId').val(),
                customerComment: CKEDITOR.instances['dialogCustomerComment'].getData()
            },
            {
                onOk: function (data) {
                    document.location.reload();
                },
                onError: function (data) {
                    console.log(data);
                }
            }
        );
    },

    getOpenHandler : function(button, modalSelector) {

        $(modalSelector).modal();

        foodcoopshop.Helper.initCkeditor('dialogCustomerComment');

        var text = button.attr('originalTitle');
        if (text == foodcoopshop.LocalizedJs.admin.AddComment) {
            text = '';
        }

        CKEDITOR.instances['dialogCustomerComment'].setData(text); // attr title is deleted after toolbar init
        $('#customer-comment-edit-form #dialogCustomerId').val(button.closest('tr').find('td:nth-child(2)').html());

    }

};<commit_msg>tooltipster fix<commit_after>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 3.1.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.ModalCustomerCommentEdit = {

    init : function() {

        var modalSelector = '#customer-comment-edit-form';

        foodcoopshop.Modal.appendModalToDom(
            modalSelector,
            foodcoopshop.LocalizedJs.modalCustomer.ChangeMemberComment,
            foodcoopshop.ModalCustomerCommentEdit.getHtml()
        );

        foodcoopshop.Modal.bindSaveButton(modalSelector, function() {
            foodcoopshop.ModalCustomerCommentEdit.getSaveHandler(modalSelector);
        });

        $(modalSelector).on('hidden.bs.modal', function (e) {
            foodcoopshop.ModalCustomerCommentEdit.getCloseHandler();
        });

        $('.customer-comment-edit-button').on('click', function () {
            foodcoopshop.ModalCustomerCommentEdit.getOpenHandler($(this), modalSelector);
        });

    },

    getHtml : function() {
        return `

                <textarea class="ckeditor" name="dialogCustomerComment" id="dialogCustomerComment"></textarea>

            <input type="hidden" name="dialogCustomerId" id="dialogCustomerId" value="" />
        `;
    },

    getCloseHandler : function() {
        $('#cke_dialogCustomerComment').val('');
        $('#dialogCustomerId').val('');
    },

    getSaveHandler : function() {

        if ($('#dialogCustomerId').val() == '') {
            return false;
        }

        foodcoopshop.Helper.ajaxCall(
            '/admin/customers/editComment/',
            {
                customerId: $('#dialogCustomerId').val(),
                customerComment: CKEDITOR.instances['dialogCustomerComment'].getData()
            },
            {
                onOk: function (data) {
                    document.location.reload();
                },
                onError: function (data) {
                    console.log(data);
                }
            }
        );
    },

    getOpenHandler : function(button, modalSelector) {

        $('.tooltipster-base ').remove(); // on mobile tooltipster is triggered on click - interferes with ckeditor

        $(modalSelector).modal();

        foodcoopshop.Helper.initCkeditor('dialogCustomerComment');

        var text = button.attr('originalTitle');
        if (text == foodcoopshop.LocalizedJs.admin.AddComment) {
            text = '';
        }

        CKEDITOR.instances['dialogCustomerComment'].setData(text);
        $('#customer-comment-edit-form #dialogCustomerId').val(button.closest('tr').find('td:nth-child(2)').html());

    }

};<|endoftext|>