<commit_before>/**
 * @author Eberhard Graether / http://egraether.com/
 */
// comment out lines 365-366 and 391-392 to restore click events

THREE.TrackballControls = function ( object, domElement ) {

	var _this = this;
	var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM: 4, TOUCH_PAN: 5 };

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	this.enabled = true;

	this.screen = { left: 0, top: 0, width: 0, height: 0 };

	this.rotateSpeed = 1.0;
	this.zoomSpeed = 1.2;
	this.panSpeed = 0.3;

	this.noRotate = false;
	this.noZoom = false;
	this.noPan = false;
	this.noRoll = false;

	this.staticMoving = false;
	this.dynamicDampingFactor = 0.2;

	this.minDistance = 0;
	this.maxDistance = Infinity;

	this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];

	// internals

	this.target = new THREE.Vector3();

	var lastPosition = new THREE.Vector3();

	var _state = STATE.NONE,
	_prevState = STATE.NONE,

	_eye = new THREE.Vector3(),

	_rotateStart = new THREE.Vector3(),
	_rotateEnd = new THREE.Vector3(),

	_zoomStart = new THREE.Vector2(),
	_zoomEnd = new THREE.Vector2(),

	_touchZoomDistanceStart = 0,
	_touchZoomDistanceEnd = 0,

	_panStart = new THREE.Vector2(),
	_panEnd = new THREE.Vector2();

	// for reset

	this.target0 = this.target.clone();
	this.position0 = this.object.position.clone();
	this.up0 = this.object.up.clone();

	// events

	var changeEvent = { type: 'change' };

	// methods

	this.handleResize = function () {

		if ( this.domElement === document ) {

			this.screen.left = 0;
			this.screen.top = 0;
			this.screen.width = window.innerWidth;
			this.screen.height = window.innerHeight;

		} else {

			this.screen = this.domElement.getBoundingClientRect();

		}

	};

	this.handleEvent = function ( event ) {

		if ( typeof this[ event.type ] == 'function' ) {

			this[ event.type ]( event );

		}

	};

	this.getMouseOnScreen = function ( clientX, clientY ) {

		return new THREE.Vector2(
			( clientX - _this.screen.left ) / _this.screen.width,
			( clientY - _this.screen.top ) / _this.screen.height
		);

	};

	this.getMouseProjectionOnBall = function ( clientX, clientY ) {

		var mouseOnBall = new THREE.Vector3(
			( clientX - _this.screen.width * 0.5 - _this.screen.left ) / (_this.screen.width*.5),
			( _this.screen.height * 0.5 + _this.screen.top - clientY ) / (_this.screen.height*.5),
			0.0
		);

		var length = mouseOnBall.length();

		if ( _this.noRoll ) {

			if ( length < Math.SQRT1_2 ) {

				mouseOnBall.z = Math.sqrt( 1.0 - length*length );

			} else {

				mouseOnBall.z = .5 / length;

			}

		} else if ( length > 1.0 ) {

			mouseOnBall.normalize();

		} else {

			mouseOnBall.z = Math.sqrt( 1.0 - length * length );

		}

		_eye.copy( _this.object.position ).sub( _this.target );

		var projection = _this.object.up.clone().setLength( mouseOnBall.y );
		projection.add( _this.object.up.clone().cross( _eye ).setLength( mouseOnBall.x ) );
		projection.add( _eye.setLength( mouseOnBall.z ) );

		return projection;

	};

	this.rotateCamera = function () {

		var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );

		if ( angle ) {

			var axis = ( new THREE.Vector3() ).crossVectors( _rotateStart, _rotateEnd ).normalize(),
				quaternion = new THREE.Quaternion();

			angle *= _this.rotateSpeed;

			quaternion.setFromAxisAngle( axis, -angle );

			_eye.applyQuaternion( quaternion );
			_this.object.up.applyQuaternion( quaternion );

			_rotateEnd.applyQuaternion( quaternion );

			if ( _this.staticMoving ) {

				_rotateStart.copy( _rotateEnd );

			} else {

				quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
				_rotateStart.applyQuaternion( quaternion );

			}

		}

	};

	this.zoomCamera = function () {

		if ( _state === STATE.TOUCH_ZOOM ) {

			var factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
			_touchZoomDistanceStart = _touchZoomDistanceEnd;
			_eye.multiplyScalar( factor );

		} else {

			var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;

			if ( factor !== 1.0 && factor > 0.0 ) {

				_eye.multiplyScalar( factor );

				if ( _this.staticMoving ) {

					_zoomStart.copy( _zoomEnd );

				} else {

					_zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;

				}

			}

		}

	};

	this.panCamera = function () {

		var mouseChange = _panEnd.clone().sub( _panStart );

		if ( mouseChange.lengthSq() ) {

			mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );

			var pan = _eye.clone().cross( _this.object.up ).setLength( mouseChange.x );
			pan.add( _this.object.up.clone().setLength( mouseChange.y ) );

			_this.object.position.add( pan );
			_this.target.add( pan );

			if ( _this.staticMoving ) {

				_panStart = _panEnd;

			} else {

				_panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );

			}

		}

	};

	this.checkDistances = function () {

		if ( !_this.noZoom || !_this.noPan ) {

			if ( _eye.lengthSq() > _this.maxDistance * _this.maxDistance ) {

				_this.object.position.addVectors( _this.target, _eye.setLength( _this.maxDistance ) );

			}

			if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {

				_this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) );

			}

		}

	};

	this.update = function () {

		_eye.subVectors( _this.object.position, _this.target );

		if ( !_this.noRotate ) {

			_this.rotateCamera();

		}

		if ( !_this.noZoom ) {

			_this.zoomCamera();

		}

		if ( !_this.noPan ) {

			_this.panCamera();

		}

		_this.object.position.addVectors( _this.target, _eye );

		_this.checkDistances();

		_this.object.lookAt( _this.target );

		if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {

			_this.dispatchEvent( changeEvent );

			lastPosition.copy( _this.object.position );

		}

	};

	this.reset = function () {

		_state = STATE.NONE;
		_prevState = STATE.NONE;

		_this.target.copy( _this.target0 );
		_this.object.position.copy( _this.position0 );
		_this.object.up.copy( _this.up0 );

		_eye.subVectors( _this.object.position, _this.target );

		_this.object.lookAt( _this.target );

		_this.dispatchEvent( changeEvent );

		lastPosition.copy( _this.object.position );

	};

	// listeners

	function keydown( event ) {

		if ( _this.enabled === false ) return;

		window.removeEventListener( 'keydown', keydown );

		_prevState = _state;

		if ( _state !== STATE.NONE ) {

			return;

		} else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {

			_state = STATE.ROTATE;

		} else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {

			_state = STATE.ZOOM;

		} else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {

			_state = STATE.PAN;

		}

	}

	function keyup( event ) {

		if ( _this.enabled === false ) return;

		_state = _prevState;

		window.addEventListener( 'keydown', keydown, false );

	}

	function mousedown( event ) {

		if ( _this.enabled === false ) return;

		// event.preventDefault();
		// event.stopPropagation();

		if ( _state === STATE.NONE ) {

			_state = event.button;

		}

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateStart = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
			_rotateEnd.copy(_rotateStart)

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomStart = _this.getMouseOnScreen( event.clientX, event.clientY );
			_zoomEnd.copy(_zoomStart);

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panStart = _this.getMouseOnScreen( event.clientX, event.clientY );
			_panEnd.copy(_panStart)

		}

		// document.addEventListener( 'mousemove', mousemove, false );
		// document.addEventListener( 'mouseup', mouseup, false );

	}

	function mousemove( event ) {

		if ( _this.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		}

	}

	function mouseup( event ) {

		if ( _this.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		_state = STATE.NONE;

		document.removeEventListener( 'mousemove', mousemove );
		document.removeEventListener( 'mouseup', mouseup );

	}

	function mousewheel( event ) {

		if ( _this.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		var delta = 0;

		if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

			delta = event.wheelDelta / 40;

		} else if ( event.detail ) { // Firefox

			delta = - event.detail / 3;

		}

		_zoomStart.y += delta * 0.01;

	}

	function touchstart( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_state = STATE.TOUCH_ROTATE;
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_state = STATE.TOUCH_ZOOM;
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
				break;

			case 3:
				_state = STATE.TOUCH_PAN;
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchmove( event ) {

		if ( _this.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		switch ( event.touches.length ) {

			case 1:
				_rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy )
				break;

			case 3:
				_panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchend( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
				break;

			case 3:
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

		}

		_state = STATE.NONE;

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	this.domElement.addEventListener( 'mousedown', mousedown, false );

	this.domElement.addEventListener( 'mousewheel', mousewheel, false );
	this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox

	this.domElement.addEventListener( 'touchstart', touchstart, false );
	this.domElement.addEventListener( 'touchend', touchend, false );
	this.domElement.addEventListener( 'touchmove', touchmove, false );

	window.addEventListener( 'keydown', keydown, false );
	window.addEventListener( 'keyup', keyup, false );

	this.handleResize();

};

THREE.TrackballControls.prototype = Object.create( THREE.EventDispatcher.prototype );
<commit_msg>commented out various lines to enable camera movement as well as clickable events on DOM elements<commit_after>/**
 * @author Eberhard Graether / http://egraether.com/
 */
// comment out lines 365-366 and 391-392 to restore click events

THREE.TrackballControls = function ( object, domElement ) {

	var _this = this;
	var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM: 4, TOUCH_PAN: 5 };

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	this.enabled = true;

	this.screen = { left: 0, top: 0, width: 0, height: 0 };

	this.rotateSpeed = 1.0;
	this.zoomSpeed = 1.2;
	this.panSpeed = 0.3;

	this.noRotate = false;
	this.noZoom = false;
	this.noPan = false;
	this.noRoll = false;

	this.staticMoving = false;
	this.dynamicDampingFactor = 0.2;

	this.minDistance = 0;
	this.maxDistance = Infinity;

	this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];

	// internals

	this.target = new THREE.Vector3();

	var lastPosition = new THREE.Vector3();

	var _state = STATE.NONE,
	_prevState = STATE.NONE,

	_eye = new THREE.Vector3(),

	_rotateStart = new THREE.Vector3(),
	_rotateEnd = new THREE.Vector3(),

	_zoomStart = new THREE.Vector2(),
	_zoomEnd = new THREE.Vector2(),

	_touchZoomDistanceStart = 0,
	_touchZoomDistanceEnd = 0,

	_panStart = new THREE.Vector2(),
	_panEnd = new THREE.Vector2();

	// for reset

	this.target0 = this.target.clone();
	this.position0 = this.object.position.clone();
	this.up0 = this.object.up.clone();

	// events

	var changeEvent = { type: 'change' };

	// methods

	this.handleResize = function () {

		if ( this.domElement === document ) {

			this.screen.left = 0;
			this.screen.top = 0;
			this.screen.width = window.innerWidth;
			this.screen.height = window.innerHeight;

		} else {

			this.screen = this.domElement.getBoundingClientRect();

		}

	};

	this.handleEvent = function ( event ) {

		if ( typeof this[ event.type ] == 'function' ) {

			this[ event.type ]( event );

		}

	};

	this.getMouseOnScreen = function ( clientX, clientY ) {

		return new THREE.Vector2(
			( clientX - _this.screen.left ) / _this.screen.width,
			( clientY - _this.screen.top ) / _this.screen.height
		);

	};

	this.getMouseProjectionOnBall = function ( clientX, clientY ) {

		var mouseOnBall = new THREE.Vector3(
			( clientX - _this.screen.width * 0.5 - _this.screen.left ) / (_this.screen.width*.5),
			( _this.screen.height * 0.5 + _this.screen.top - clientY ) / (_this.screen.height*.5),
			0.0
		);

		var length = mouseOnBall.length();

		if ( _this.noRoll ) {

			if ( length < Math.SQRT1_2 ) {

				mouseOnBall.z = Math.sqrt( 1.0 - length*length );

			} else {

				mouseOnBall.z = .5 / length;

			}

		} else if ( length > 1.0 ) {

			mouseOnBall.normalize();

		} else {

			mouseOnBall.z = Math.sqrt( 1.0 - length * length );

		}

		_eye.copy( _this.object.position ).sub( _this.target );

		var projection = _this.object.up.clone().setLength( mouseOnBall.y );
		projection.add( _this.object.up.clone().cross( _eye ).setLength( mouseOnBall.x ) );
		projection.add( _eye.setLength( mouseOnBall.z ) );

		return projection;

	};

	this.rotateCamera = function () {

		var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );

		if ( angle ) {

			var axis = ( new THREE.Vector3() ).crossVectors( _rotateStart, _rotateEnd ).normalize(),
				quaternion = new THREE.Quaternion();

			angle *= _this.rotateSpeed;

			quaternion.setFromAxisAngle( axis, -angle );

			_eye.applyQuaternion( quaternion );
			_this.object.up.applyQuaternion( quaternion );

			_rotateEnd.applyQuaternion( quaternion );

			if ( _this.staticMoving ) {

				_rotateStart.copy( _rotateEnd );

			} else {

				quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
				_rotateStart.applyQuaternion( quaternion );

			}

		}

	};

	this.zoomCamera = function () {

		if ( _state === STATE.TOUCH_ZOOM ) {

			var factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
			_touchZoomDistanceStart = _touchZoomDistanceEnd;
			_eye.multiplyScalar( factor );

		} else {

			var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;

			if ( factor !== 1.0 && factor > 0.0 ) {

				_eye.multiplyScalar( factor );

				if ( _this.staticMoving ) {

					_zoomStart.copy( _zoomEnd );

				} else {

					_zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;

				}

			}

		}

	};

	this.panCamera = function () {

		var mouseChange = _panEnd.clone().sub( _panStart );

		if ( mouseChange.lengthSq() ) {

			mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );

			var pan = _eye.clone().cross( _this.object.up ).setLength( mouseChange.x );
			pan.add( _this.object.up.clone().setLength( mouseChange.y ) );

			_this.object.position.add( pan );
			_this.target.add( pan );

			if ( _this.staticMoving ) {

				_panStart = _panEnd;

			} else {

				_panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );

			}

		}

	};

	this.checkDistances = function () {

		if ( !_this.noZoom || !_this.noPan ) {

			if ( _eye.lengthSq() > _this.maxDistance * _this.maxDistance ) {

				_this.object.position.addVectors( _this.target, _eye.setLength( _this.maxDistance ) );

			}

			if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {

				_this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) );

			}

		}

	};

	this.update = function () {

		_eye.subVectors( _this.object.position, _this.target );

		if ( !_this.noRotate ) {

			_this.rotateCamera();

		}

		if ( !_this.noZoom ) {

			_this.zoomCamera();

		}

		if ( !_this.noPan ) {

			_this.panCamera();

		}

		_this.object.position.addVectors( _this.target, _eye );

		_this.checkDistances();

		_this.object.lookAt( _this.target );

		if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {

			_this.dispatchEvent( changeEvent );

			lastPosition.copy( _this.object.position );

		}

	};

	this.reset = function () {

		_state = STATE.NONE;
		_prevState = STATE.NONE;

		_this.target.copy( _this.target0 );
		_this.object.position.copy( _this.position0 );
		_this.object.up.copy( _this.up0 );

		_eye.subVectors( _this.object.position, _this.target );

		_this.object.lookAt( _this.target );

		_this.dispatchEvent( changeEvent );

		lastPosition.copy( _this.object.position );

	};

	// listeners

	function keydown( event ) {

		if ( _this.enabled === false ) return;

		window.removeEventListener( 'keydown', keydown );

		_prevState = _state;

		if ( _state !== STATE.NONE ) {

			return;

		} else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {

			_state = STATE.ROTATE;

		} else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {

			_state = STATE.ZOOM;

		} else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {

			_state = STATE.PAN;

		}

	}

	function keyup( event ) {

		if ( _this.enabled === false ) return;

		_state = _prevState;

		window.addEventListener( 'keydown', keydown, false );

	}

	function mousedown( event ) {

		if ( _this.enabled === false ) return;

		// event.preventDefault();
		// event.stopPropagation();

		if ( _state === STATE.NONE ) {

			_state = event.button;

		}

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateStart = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
			_rotateEnd.copy(_rotateStart)

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomStart = _this.getMouseOnScreen( event.clientX, event.clientY );
			_zoomEnd.copy(_zoomStart);

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panStart = _this.getMouseOnScreen( event.clientX, event.clientY );
			_panEnd.copy(_panStart)

		}

		document.addEventListener( 'mousemove', mousemove, false );
		document.addEventListener( 'mouseup', mouseup, false );

	}

	function mousemove( event ) {

		if ( _this.enabled === false ) return;

		// event.preventDefault();
		// event.stopPropagation();

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		}

	}

	function mouseup( event ) {

		if ( _this.enabled === false ) return;

		// event.preventDefault();
		// event.stopPropagation();

		_state = STATE.NONE;

		document.removeEventListener( 'mousemove', mousemove );
		document.removeEventListener( 'mouseup', mouseup );

	}

	function mousewheel( event ) {

		if ( _this.enabled === false ) return;

		// event.preventDefault();
		// event.stopPropagation();

		var delta = 0;

		if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

			delta = event.wheelDelta / 40;

		} else if ( event.detail ) { // Firefox

			delta = - event.detail / 3;

		}

		_zoomStart.y += delta * 0.01;

	}

	function touchstart( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_state = STATE.TOUCH_ROTATE;
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_state = STATE.TOUCH_ZOOM;
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
				break;

			case 3:
				_state = STATE.TOUCH_PAN;
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchmove( event ) {

		if ( _this.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		switch ( event.touches.length ) {

			case 1:
				_rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy )
				break;

			case 3:
				_panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchend( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
				break;

			case 3:
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

		}

		_state = STATE.NONE;

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	this.domElement.addEventListener( 'mousedown', mousedown, false );

	this.domElement.addEventListener( 'mousewheel', mousewheel, false );
	this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox

	this.domElement.addEventListener( 'touchstart', touchstart, false );
	this.domElement.addEventListener( 'touchend', touchend, false );
	this.domElement.addEventListener( 'touchmove', touchmove, false );

	window.addEventListener( 'keydown', keydown, false );
	window.addEventListener( 'keyup', keyup, false );

	this.handleResize();

};

THREE.TrackballControls.prototype = Object.create( THREE.EventDispatcher.prototype );
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Mixin.create({

    fetched: false,

    queryParams: {
        q: {
            replace: true
        }
    },

    model: function() {
        return [];
    },

    setupController: function(controller, model) {
        this._super(controller, model);

        if (!this.get('fetched'))
            controller.filter();

        this.set('fetched', true);
    }

});
<commit_msg>Always trigger list reload when route is activated.<commit_after>import Ember from 'ember';

export default Ember.Mixin.create({

    queryParams: {
        q: {
            replace: true
        }
    },

    model: function() {
        return [];
    },

    setupController: function(controller, model) {
        this._super(controller, model);
        controller.filter();
    }

});
<|endoftext|>


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

cs.map_ = {};
cs.eventSource_ = new ol.source.Vector({});

cs.clusterSource_ = new ol.source.Cluster({
    distance: 30,
    source: cs.eventSource_
});

cs.sideBar_ = {};

cs.config_ = {};

cs.init = function (map) {
    cs.map_ = map;

    cs.popup_ = new ol.Overlay({
        element: document.getElementById('popup'),
        positioning: 'bottom-center',
        stopEvent: false
    });

    map.addOverlay(cs.popup_);

    this.getConfig();

    this.initEvents();
};

cs.getAllEvents = function()  {
    var data = {};

    var doneHandler_ = function(res) {
        cs.eventSource_.clear();
        cs.events2features(res);
    };

    gsc.cs.eventListFilter(data)
        .done(doneHandler_)
        .fail(cs.error);
};

cs.error = function(error) {
    alert(error)
};

cs.event2feature = function(event){
    var coors = new ol.geom.Point( [event.location.lat, event.location.lon])
        .transform('EPSG:4326', 'EPSG:3857');

    var feature = new ol.Feature({
        geometry: coors,
        name: 'event'
    });

    if (event.status == 'created') {
        feature.setStyle(cs.icon.ok);
    } else {
        feature.setStyle(cs.icon.ko);
    }
    feature.setId(event.id);
    feature.setProperties(event);
    return feature;
};

cs.events2features = function(events){
    events.forEach(function(event){
        cs.eventSource_.addFeature(cs.event2feature(event));
    });
    this.source2map();
    cs.datagrid.updateData();
};

cs.source2map = function() {
    cs.layer_ =  new ol.layer.Vector({
        //source: cs.eventSource_
        source: cs.clusterSource_,
        style: cs.style
    });
    cs.map_.addLayer(cs.layer_);
    cs.fit2features();
};

cs.fit2features = function() {
    var extent = cs.eventSource_.getExtent();
    cs.map_.getView().fit(extent,cs.map_.getSize(),{'padding' : [10, 10, 10, 400], 'maxZoom': 15});
};

cs.initSideBar = function() {
    cs.sideBar_ = $('#sidebar').sidebar();
};

cs.initEvents = function() {

    // http://openlayers.org/en/v3.8.1/examples/icon.html?q=style+icon
    var closePop = function(e) {
        $('#popup').popover('destroy');
        return
    };

    var singleClick = function(evt){
        cs.map_.forEachFeatureAtPixel(evt.pixel, function (feature,layer) {
            cs.clickFeatures(feature,layer,evt)
        });
    };

    //this.map_.on('pointermove', closePop);

    this.map_.getView().on('change:center', closePop);

    this.map_.on('singleclick', singleClick);
};

cs.icon = {};

cs.icon.ko  = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        // imgSize: [20,20],
        scale: 0.08,
        opacity: 1,
        src: 'images/icons/fire.svg'
    }))
});

cs.icon.ok  = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        // imgSize: [20,20],
        scale: 0.08,
        opacity: 1,
        src: 'images/icons/star.svg'
    }))
});

cs.styleCache = {};

cs.style = function(feature, resolution) {
    var style = cs.styleCache[size];
    var size = feature.get('features').length;
    if (size == 1){
        var f = feature.get('features')[0]
        if (f.get('status') == 'created') {
            return cs.icon.ko;
        } else {
            return cs.icon.ok;
        }
    }

    if (!style) {
        style = [new ol.style.Style({
            image: new ol.style.Circle({
                radius: 10,
                stroke: new ol.style.Stroke({
                    color: '#fff'
                }),
                fill: new ol.style.Fill({
                    color: '#3399CC'
                })
            }),
            text: new ol.style.Text({
                text: size.toString(),
                fill: new ol.style.Fill({
                    color: '#fff'
                })
            })
        })];
        cs.styleCache[size] = style;
    }
    return style;
};

cs.clickFeatures = function(feature,layer,evt) {
    var size = feature.get('features').length;

    if (size < 5) {

        cs.popup_.setPosition(evt.coordinate);
        var content = $('
');
        feature.get('features').forEach(function (item) {
            content.append(cs.renderFeaturePopup(item));
        });

        var popElm = $('#popup');

        popElm.popover("destroy").popover({
            'placement': 'top',
            'html': true,
            'content': content
        });

        popElm.popover('show');
    } else {
        console.log(feature.get())
        //cs.map_.getView().setZoom(cs.map_.getView().getZoom()+1);
        cs.zoom2feature(feature, cs.map_.getView().getZoom() + 1 );
    }
};

cs.renderFeaturePopup = function(feature) {

    var goTo = function(evt) {
        cs.featureDetail(feature);
    };

    var wrapper = $('
',{class:'cs-feature-popup-item-wrapper'})
        .on('click',goTo);

    $('', {class:'fa fa-info-circle cs-feature-popup-item-icon'}).appendTo(wrapper);
   // $('', {class: 'cs-feature-popup-item-name'}).html(feature.get('name')).appendTo(wrapper);
    $('', {class: 'cs-feature-popup-item-name'}).html('status: '+ feature.get('status') +', priority: '+ feature.get('priority')).appendTo(wrapper);
    $('', {class: 'cs-feature-popup-item-name', src:feature.get('media')[0].src }).appendTo(wrapper);

    return wrapper;
};

cs.zoom2feature = function(feature, maxZoom) {

    var mz = maxZoom || 15;

    var geometry = (feature.getGeometry());
    var mapSize = cs.map_.getSize();
    cs.map_.getView().fit(geometry, mapSize, {'padding' : [0, 0, 0, cs.sideBar_.width()], 'maxZoom': mz});

};

cs.getConfig = function() {
    var promiseDone = function(res) {
        cs.config_ = res;

        cs.filterform('#filterWrapper');
    };
    var promise = gsc.cs.getConfig()
        .done(promiseDone)
};

cs.evSchema = {
    'name' : 'string',
    'datetime' : 'datetime',
    'description' : 'desc',
    'id' : 'id',
    'media' : 'media',
    'priority' : 'priority',
    'user' : 'user',
    'status' : 'status',
    'location' : 'geometry',
    'geometry' : 'geometry',
    'tags' : 'tags',
    'comments' : 'comments'
};

cs.dgAttrs = ['name','location','description','datetime','media','priority','user','status','tags','comments'];

cs.fdAttrs = ['name','description','datetime','media','priority','user','status','tags','comments', 'location'];<commit_msg>fix swapped coordinates<commit_after>var cs = cs || {};

cs.map_ = {};
cs.eventSource_ = new ol.source.Vector({});

cs.clusterSource_ = new ol.source.Cluster({
    distance: 30,
    source: cs.eventSource_
});

cs.sideBar_ = {};

cs.config_ = {};

cs.init = function (map) {
    cs.map_ = map;

    cs.popup_ = new ol.Overlay({
        element: document.getElementById('popup'),
        positioning: 'bottom-center',
        stopEvent: false
    });

    map.addOverlay(cs.popup_);

    this.getConfig();

    this.initEvents();
};

cs.getAllEvents = function()  {
    var data = {};

    var doneHandler_ = function(res) {
        cs.eventSource_.clear();
        cs.events2features(res);
    };

    gsc.cs.eventListFilter(data)
        .done(doneHandler_)
        .fail(cs.error);
};

cs.error = function(error) {
    alert(error)
};

cs.event2feature = function(event){
    var coors = new ol.geom.Point( [event.location.lon, event.location.lat])
        .transform('EPSG:4326', 'EPSG:3857');

    var feature = new ol.Feature({
        geometry: coors,
        name: 'event'
    });

    if (event.status == 'created') {
        feature.setStyle(cs.icon.ok);
    } else {
        feature.setStyle(cs.icon.ko);
    }
    feature.setId(event.id);
    feature.setProperties(event);
    return feature;
};

cs.events2features = function(events){
    events.forEach(function(event){
        cs.eventSource_.addFeature(cs.event2feature(event));
    });
    this.source2map();
    cs.datagrid.updateData();
};

cs.source2map = function() {
    cs.layer_ =  new ol.layer.Vector({
        //source: cs.eventSource_
        source: cs.clusterSource_,
        style: cs.style
    });
    cs.map_.addLayer(cs.layer_);
    cs.fit2features();
};

cs.fit2features = function() {
    var extent = cs.eventSource_.getExtent();
    cs.map_.getView().fit(extent,cs.map_.getSize(),{'padding' : [10, 10, 10, 400], 'maxZoom': 15});
};

cs.initSideBar = function() {
    cs.sideBar_ = $('#sidebar').sidebar();
};

cs.initEvents = function() {

    // http://openlayers.org/en/v3.8.1/examples/icon.html?q=style+icon
    var closePop = function(e) {
        $('#popup').popover('destroy');
        return
    };

    var singleClick = function(evt){
        cs.map_.forEachFeatureAtPixel(evt.pixel, function (feature,layer) {
            cs.clickFeatures(feature,layer,evt)
        });
    };

    //this.map_.on('pointermove', closePop);

    this.map_.getView().on('change:center', closePop);

    this.map_.on('singleclick', singleClick);
};

cs.icon = {};

cs.icon.ko  = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        // imgSize: [20,20],
        scale: 0.08,
        opacity: 1,
        src: 'images/icons/fire.svg'
    }))
});

cs.icon.ok  = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        // imgSize: [20,20],
        scale: 0.08,
        opacity: 1,
        src: 'images/icons/star.svg'
    }))
});

cs.styleCache = {};

cs.style = function(feature, resolution) {
    var style = cs.styleCache[size];
    var size = feature.get('features').length;
    if (size == 1){
        var f = feature.get('features')[0];
        if (f.get('status') == 'created') {
            return cs.icon.ko;
        } else {
            return cs.icon.ok;
        }
    }

    if (!style) {
        style = [new ol.style.Style({
            image: new ol.style.Circle({
                radius: 10,
                stroke: new ol.style.Stroke({
                    color: '#fff'
                }),
                fill: new ol.style.Fill({
                    color: '#3399CC'
                })
            }),
            text: new ol.style.Text({
                text: size.toString(),
                fill: new ol.style.Fill({
                    color: '#fff'
                })
            })
        })];
        cs.styleCache[size] = style;
    }
    return style;
};

cs.clickFeatures = function(feature,layer,evt) {
    var size = feature.get('features').length;

    if (size < 5) {

        cs.popup_.setPosition(evt.coordinate);
        var content = $('
');
        feature.get('features').forEach(function (item) {
            content.append(cs.renderFeaturePopup(item));
        });

        var popElm = $('#popup');

        popElm.popover("destroy").popover({
            'placement': 'top',
            'html': true,
            'content': content
        });

        popElm.popover('show');
    } else {
        console.log(feature.get())
        //cs.map_.getView().setZoom(cs.map_.getView().getZoom()+1);
        cs.zoom2feature(feature, cs.map_.getView().getZoom() + 1 );
    }
};

cs.renderFeaturePopup = function(feature) {

    var goTo = function(evt) {
        cs.featureDetail(feature);
    };

    var wrapper = $('
',{class:'cs-feature-popup-item-wrapper'})
        .on('click',goTo);

    $('', {class:'fa fa-info-circle cs-feature-popup-item-icon'}).appendTo(wrapper);
   // $('', {class: 'cs-feature-popup-item-name'}).html(feature.get('name')).appendTo(wrapper);
    $('', {class: 'cs-feature-popup-item-name'}).html('status: '+ feature.get('status') +', priority: '+ feature.get('priority')).appendTo(wrapper);
    $('', {class: 'cs-feature-popup-item-name', src:feature.get('media')[0].src }).appendTo(wrapper);

    return wrapper;
};

cs.zoom2feature = function(feature, maxZoom) {

    var mz = maxZoom || 15;

    var geometry = (feature.getGeometry());
    var mapSize = cs.map_.getSize();
    cs.map_.getView().fit(geometry, mapSize, {'padding' : [0, 0, 0, cs.sideBar_.width()], 'maxZoom': mz});

};

cs.getConfig = function() {
    var promiseDone = function(res) {
        cs.config_ = res;

        cs.filterform('#filterWrapper');
    };
    var promise = gsc.cs.getConfig()
        .done(promiseDone)
};

cs.evSchema = {
    'name' : 'string',
    'datetime' : 'datetime',
    'description' : 'desc',
    'id' : 'id',
    'media' : 'media',
    'priority' : 'priority',
    'user' : 'user',
    'status' : 'status',
    'location' : 'geometry',
    'geometry' : 'geometry',
    'tags' : 'tags',
    'comments' : 'comments'
};

cs.dgAttrs = ['name','location','description','datetime','media','priority','user','status','tags','comments'];

cs.fdAttrs = ['name','description','datetime','media','priority','user','status','tags','comments', 'location'];<|endoftext|>


<commit_before>var COL_INPUT           = '[data="cols-input"]',
    PREFIX_INPUT        = '[data="prefix-input"]',
    TAB                 = '[data-action="tab"]',
    MQ_ADD              = '[data="add-mq"]',
    MQ_REMOVE           = '[data="remove-mq"]'
    MQ_ADD_DEFAULT      = '[data="add-default-mq"]'
    MQ_TABLE            = '#media-query-table',
    MQ_LIST             = '#media-query-table tbody',
    MQ_KEY              = '.mq-key',
    MQ_VAL              = '.mq-value',
    MQ_ROW              = '[data-row="media-query"]';

var events = {};
events[TAB]           = {click: 'handleTabClick'};
events[COL_INPUT]     = {blur: 'inputCols'};
events[PREFIX_INPUT]  = {blur: 'inputPrefix'};
events[MQ_KEY]        = {focus: 'storeMediaQueryId',
                            blur: 'addMediaQueryById'};
events[MQ_VAL]        = {focus: 'storeMediaQueryValue',
                            blur: 'addMediaQueryByValue'};
events[MQ_ADD]        = {click: 'renderNewMediaQuery'};
events[MQ_REMOVE]     = {click: 'removeRenderedMediaQuery'};
events[MQ_ADD_DEFAULT] = {click: 'generateDefaultMediaQuery'};

YUI.add('grid-input-view', function (Y, NAME, imports, exports) {

    'use strict';

    //importing stuff in from other modules. Is this the right way?
    var MqModel = imports['mq-model'].MqModel;

    exports = Y.Base.create('grid-input-view', Y.GridTabView, [], {
        events: events,

        initializer: function (cfg) {
            var model = this.get('model');
            model.after('destroy', this.destroy, this);
            this.set('template', cfg.template);
        },

        render: function () {
            //We are just going to manipulate the input values inside render(). No need to re-render all the DOM elements.
            var container = this.get('container'),
                model = this.get('model'),
                mq = model.get('mediaQueries'),
                list = container.one(MQ_LIST);

            if (model.get('cols')) {
                container.one(COL_INPUT).set('value', Y.Escape.html(model.get('cols')));
            }

            if (model.get('prefix')) {
                container.one(PREFIX_INPUT).set('value', Y.Escape.html(model.get('prefix')));
            }

            list.empty();
            mq.each(function (m) {
                this._renderNewMediaQuery(m.get('id'), m.get('mq'));
            }, this);
        },

        //This will create a new <tr> and populate it with media query values, if they exist.
        _renderNewMediaQuery: function (key, mq) {
            var container = this.get('container'),
                template = this.get('template'),
                table = container.one(MQ_TABLE),
                html;

            html = template({id: key || '', mq: mq || ''});

            if (table.hasAttribute('hidden')) {
                table.removeAttribute('hidden');
            }
            container.one(MQ_LIST).append(html);
        },

        //This will just pass through to _renderNewMediaQuery() to create an empty row.
        renderNewMediaQuery: function () {
            this._renderNewMediaQuery();

            var container = this.get('container'),
                numMediaQueries = container.one(MQ_TABLE).all(MQ_ROW).size();

            if (numMediaQueries > app.start.limits.mediaQueries.max ||
                numMediaQueries < app.start.limits.mediaQueries.min) {

                container.one(MQ_ADD).setAttribute('disabled', true);
            }
        },

        removeRenderedMediaQuery: function (e) {
            var container = this.get('container'),
                list = container.one(MQ_LIST),
                table = container.one(MQ_TABLE),
                mq = this.get('model').get('mediaQueries'),
                key = e.target.ancestor(MQ_ROW, MQ_LIST)
                        .one(MQ_KEY).get('value');

            e.target.ancestor(MQ_ROW, MQ_LIST).remove();
            container.one(MQ_ADD).removeAttribute('disabled');
            if (!list.hasChildNodes()) {
                table.setAttribute('hidden');
            }

            //we only want to update the route if the row had some contents
            if (key) {
                mq.remove(mq.getById(key));
            }

            this.get('model').set('mediaQueries', mq);
        },

        storeMediaQueryId: function (e) {
            this.mediaQueryId = e.target.get('value');
        },

        storeMediaQueryValue: function (e) {
            this.mediaQueryValue = e.target.get('value');
        },
        addMediaQueryById: function (e) {
            //check to see if this media query has a value associated with it.
            var key     = e.target.get('value'),
                oldKey  = this.mediaQueryId,
                val     = e.target.get('parentNode').next().one(MQ_VAL).get('value'),
                mq      = this.get('model').get('mediaQueries'),
                existingModel = mq.getById(oldKey),
                index   = mq.size();

            //dont want to do anything unless the key has an explicit value
            if (key && key !== oldKey) {

                //if we had an existing model, then remove that
                if (existingModel) {
                    index = mq.indexOf(existingModel);
                    mq.remove(existingModel);
                }
                //add a new media query
                mq.add({
                    id: key,
                    mq: val
                }, {index: index});

                this.get('model').set('mediaQueries', mq);
            }
        },

        addMediaQueryByValue: function (e) {
            var val = e.target.get('value'),
                oldVal = this.mediaQueryValue,
                key = e.target.get('parentNode').previous().one(MQ_KEY).get('value'),
                mq  = this.get('model').get('mediaQueries'),
                existingModel = mq.getById(key),
                model;

            //dont want to do anything unless `val` has an explicit value
            if (val && val !== oldVal) {
                model = new MqModel({id: key, mq: val});

                if (!model.isValidMediaQuery()) {
                    e.target.setAttribute('invalid', true);
                }
                else {
                    if (existingModel) {
                        //find the existing model and update it.
                        existingModel.set('mq', val);
                    }
                    //add a new model to the model list
                    else {
                        mq.add({id: key, mq: val});
                    }
                    this.get('model').set('mediaQueries', mq);
                }
            }
        },

        generateDefaultMediaQuery: function () {
            var defaults = [{
                    id: 'med',
                    mq: 'screen and (min-width: 48em)'
                },
                {
                    id: 'lrg',
                    mq: 'screen and (min-width: 60em)'
                }],
                mq = this.get('model').get('mediaQueries');

            mq.reset().add(defaults);
            this.get('model').set('mediaQueries', mq);
            this.render();
        },

        inputCols: function (e) {
            var cols = e.target.get('value');
            this.get('model').set('cols', cols);
        },

        inputPrefix: function (e) {
            var prefix = e.target.get('value');
            this.get('model').set('prefix', prefix);
        }
    });

    return exports;

}, '0.0.1', {
    es: true,
    requires: [
        'mq-model',
        'grid-tab-view',
        'event-focus'
    ]
});

<commit_msg>Clean up grid-input-view<commit_after>YUI.add('grid-input-view', function (Y, NAME, imports, exports) {

    'use strict';

    var COL_INPUT           = '[data-content="cols-input"]',
        PREFIX_INPUT        = '[data-content="prefix-input"]',
        TAB                 = '[data-action="tab"]',
        MQ_ADD              = '[data-action="add-mq"]',
        MQ_REMOVE           = '[data-action="remove-mq"]',
        MQ_ADD_DEFAULT      = '[data-action="add-default-mq"]',
        MQ_TABLE            = '#media-query-table',
        MQ_LIST             = '#media-query-table tbody',
        MQ_KEY              = '[data-content="mq-key"]',
        MQ_VAL              = '[data-content="mq-value"]',
        MQ_ROW              = '[data-row="media-query"]';

    var events = {};

    events[TAB]           = {click: 'handleTabClick'};
    events[COL_INPUT]     = {change: 'inputCols'};
    events[PREFIX_INPUT]  = {change: 'inputPrefix'};
    events[MQ_KEY]        = {change: 'addMediaQueryById'};
    events[MQ_VAL]        = {change: 'addMediaQueryByValue'};
    events[MQ_ADD]        = {click: 'renderNewMediaQuery'};
    events[MQ_REMOVE]     = {click: 'removeRenderedMediaQuery'};
    events[MQ_ADD_DEFAULT] = {click: 'generateDefaultMediaQuery'};

    var MqModel = imports['mq-model'].MqModel,
        GridTabView = imports['grid-tab-view'];

    return Y.Base.create('grid-input-view', GridTabView, [], {
        events: events,

        render: function () {
            //We are just going to manipulate the input values inside render(). No need to re-render all the DOM elements.
            var container = this.get('container'),
                model = this.get('model'),
                mqs = model.get('mediaQueries'),
                list = container.one(MQ_LIST);

            if (model.get('cols')) {
                container.one(COL_INPUT).set('value', Y.Escape.html(model.get('cols')));
            }

            if (model.get('prefix')) {
                container.one(PREFIX_INPUT).set('value', Y.Escape.html(model.get('prefix')));
            }

            list.empty();
            mqs.each(function (m) {
                this._renderNewMediaQuery(m.get('id'), m.get('mq'));
            }, this);
        },

        //This will create a new <tr> and populate it with media query values, if they exist.
        _renderNewMediaQuery: function (key, mq) {
            var container = this.get('container'),
                table = container.one(MQ_TABLE),
                html;

            html = this.template({id: key || '', mq: mq || ''});

            if (table.hasAttribute('hidden')) {
                table.removeAttribute('hidden');
            }
            container.one(MQ_LIST).append(html);
        },

        //This will just pass through to _renderNewMediaQuery() to create an empty row.
        renderNewMediaQuery: function () {
            this._renderNewMediaQuery();

            var container = this.get('container'),
                numMediaQueries = container.one(MQ_TABLE).all(MQ_ROW).size();

            if (numMediaQueries > app.start.limits.mediaQueries.max ||
                numMediaQueries < app.start.limits.mediaQueries.min) {

                container.one(MQ_ADD).setAttribute('disabled', true);
            }
        },

        removeRenderedMediaQuery: function (e) {
            var container = this.get('container'),
                list = container.one(MQ_LIST),
                table = container.one(MQ_TABLE),
                mqs = this.get('model').get('mediaQueries'),
                key = e.target.ancestor(MQ_ROW, MQ_LIST)
                        .one(MQ_KEY).get('value'),
                index = this.get('container').all(MQ_ROW).indexOf(e.target.ancestor(MQ_ROW));

            e.target.ancestor(MQ_ROW, MQ_LIST).remove();
            container.one(MQ_ADD).removeAttribute('disabled');
            if (!list.hasChildNodes()) {
                table.setAttribute('hidden');
            }

            //we only want to update the route if the row had some contents
            if (key) {
                mqs.remove(mqs.item(index));
            }

            this.get('model').set('mediaQueries', mqs);
        },

        addMediaQueryById: function (e) {
            //check to see if this media query has a value associated with it.
            var key   = e.target.get('value'),
                index = this.get('container').all(MQ_ROW).indexOf(e.target.ancestor(MQ_ROW)),
                val, mqs, existingModel;

            //dont want to do anything unless the key has an explicit value
            if (key) {

                val = e.target.get('parentNode').next().one(MQ_VAL).get('value'),
                mqs = this.get('model').get('mediaQueries'),
                existingModel = mqs.item(index);

                //if we had an existing model, then remove that
                if (existingModel) {
                    existingModel.setAttrs({
                        id: key,
                        mq: val
                    });
                }

                else {
                    //add a new media query
                    mqs.add({
                        id: key,
                        mq: val
                    });

                }

                this.get('model').set('mediaQueries', mqs);
            }
        },

        addMediaQueryByValue: function (e) {
            var val = e.target.get('value'),
                index = this.get('container').all(MQ_ROW).indexOf(e.target.ancestor(MQ_ROW)),
                key, mqs, existingModel, model;

            //dont want to do anything unless `val` has an explicit value
            if (val) {
                key = e.target.get('parentNode').previous().one(MQ_KEY).get('value'),
                mqs = this.get('model').get('mediaQueries'),
                existingModel = mqs.item(index),
                model = new MqModel({id: key, mq: val});

                if (!model.isValidMediaQuery()) {
                    e.target.setAttribute('invalid', true);
                }
                else {
                    if (existingModel) {
                        //find the existing model and update it.
                        existingModel.set('mq', val);
                    }
                    //add a new model to the model list
                    else {
                        mqs.add(model);
                    }
                    this.get('model').set('mediaQueries', mqs);
                }
            }
        },

        generateDefaultMediaQuery: function () {
            var defaults = [{
                    id: 'med',
                    mq: 'screen and (min-width: 48em)'
                },
                {
                    id: 'lrg',
                    mq: 'screen and (min-width: 60em)'
                }],
                mqs = this.get('model').get('mediaQueries');

            mqs.reset().add(defaults);
            this.get('model').set('mediaQueries', mqs);
            this.render();
        },

        inputCols: function (e) {
            var cols = e.target.get('value');
            this.get('model').set('cols', cols);
        },

        inputPrefix: function (e) {
            var prefix = e.target.get('value');
            this.get('model').set('prefix', prefix);
        }
    });

}, '0.0.1', {
    es: true,
    requires: [
        'mq-model',
        'grid-tab-view'
    ]
});

<|endoftext|>


<commit_before>/* http://github.com/avih/nopromise MIT */
(function(){

var async = setTimeout,
    staticNativePromise,
    globalQ;

try {
    async = this.setImmediate || async;
    staticNativePromise = Promise.resolve();
    async = function(f) { staticNativePromise.then(f) };
    async = process.nextTick || async;
} catch (e) {}

function deq() {
    var f, tmp = globalQ.reverse();
    globalQ = 0;
    while (f = tmp.pop())
        f();
}

function internalAsync(f) {
    if (globalQ) {
        globalQ.push(f);
    } else {
        globalQ = [f];
        async(deq);
    }
}

function unpend(p, state, value) {
    if (!p._state) {
        p._state = state;
        p._output = value;

        var f, r = p._resolvers;
        if (r) {
            r.reverse();
            while (f = r.pop())
                internalAsync(f);
        }
    }
}

NoPromise.prototype = {
    resolve: function(value) {
        unpend(this, 1, value);
    },

    reject: function(reason) {
        unpend(this, 2, reason);
    },

    then: function(onFulfilled, onRejected) {
        var _self    = this,
            promise2 = new NoPromise;

        _self._state ? internalAsync(promise2Resolver)
                     : _self._resolvers ? _self._resolvers.push(promise2Resolver)
                                        : _self._resolvers = [promise2Resolver];
        return promise2;

        function promise2Resolver() {
            var isFulfilled = _self._state < 2,
                _output     = _self._output,
                handler     = isFulfilled ? onFulfilled : onRejected,
                FUNCTION    = "function";

            if (typeof handler != FUNCTION) {
                isFulfilled ? promise2.resolve(_output) : promise2.reject(_output);
            } else {
                promise2Resolution(0, 1);
            }

            function promise2Resolution(x, firstTime) {
                var then,
                    done = 0;

                try {
                    if (firstTime)
                        x = handler(_output);

                    if (x == promise2) {
                        promise2.reject(TypeError());

                    } else if ((x && typeof x == "object" || typeof x == FUNCTION)
                               && typeof (then = x.then) == FUNCTION) {
                        then.call(x, function(y) { done++ || promise2Resolution(y) },
                                     function(r) { done++ || promise2.reject(r)    });

                    } else {
                        promise2.resolve(x);
                    }

                } catch (e) {
                    done++ || promise2.reject(e);
                }
            }
        }
    }
}

function NoPromise() {
}

NoPromise.deferred = function() { var d = new NoPromise; return d.promise = d };
try {
  module.exports = NoPromise;
} catch (e) {
  this.NoPromise = NoPromise;
}

})()
<commit_msg>add some comments<commit_after>/* http://github.com/avih/nopromise MIT */
(function(){

var async = setTimeout, // Default scheduler, IE <= 9
    staticNativePromise,
    globalQ,
    FUNCTION = "function";

try {
    // Try to find the fastest asynchronous scheduler for this environment.
    async = this.setImmediate || async; // IE 10/11 will end up using this
    staticNativePromise = Promise.resolve();
    async = function(f) { staticNativePromise.then(f) }; // Firefox/Chrome/Edge
    async = process.nextTick || async; // Node.js
} catch (e) {}

// The invariant between internalAsync and dequeue is that if globalQ is thuthy,
// then a dequeue is already scheduled and will execute globalQ asynchronously,
// otherwise, globalQ needs to be created and dequeue needs to be scheduled.
// The elements (functions) of the globalQ array need to be invoked in order.
function dequeue() {
    var f, tmp = globalQ.reverse();
    globalQ = 0;
    while (f = tmp.pop())
        f();
}

// This is used throughout the implementation as the asynchronous scheduler.
// While satisfying the contract to invoke f asynchronously, it combines
// individual f's into a single group which is later iterated synchronously.
function internalAsync(f) {
    if (globalQ) {
        globalQ.push(f);
    } else {
        globalQ = [f];
        async(dequeue);
    }
}

// Fulfil/reject a promise if it's pending, else no-op.
function unpend(p, state, value) {
    if (!p._state) {
        p._state = state;
        p._output = value;

        var f, arr = p._resolvers;
        if (arr) {
            // The case where `then` is called many times for the same promise
            // is rare, so for simplicity, we're not optimizing for it, or else
            // if globalQ is empty, we can just do: globalQ = p._resolvers;
            arr.reverse();
            while (f = arr.pop())
                internalAsync(f);
        }
    }
}

// Other than the prototype methods, the object may also have:
// ._state    : 1 if fulfilled, 2 if rejected (doesn't exist otherwise).
// ._output   : value if fulfilled, reason if rejected (doesn't exist otherwise).
// ._resolvers: array of functions (closures) for/if .then calls while pending.
NoPromise.prototype = {
    resolve: function(value) {
        unpend(this, 1, value);
    },

    reject: function(reason) {
        unpend(this, 2, reason);
    },

    // Each call to `then` returns a new NoPromise object and creates a closure
    // which is used to resolve it after then's this is fulfilled/rejected.
    then: function(onFulfilled, onRejected) {
        var _self    = this,
            promise2 = new NoPromise;

        _self._state ? internalAsync(promise2Resolver)
                     : _self._resolvers ? _self._resolvers.push(promise2Resolver)
                                        : _self._resolvers = [promise2Resolver];
        return promise2;

        // Invoked asynchronously to `then` and after _self is fulfilled/rejected.
        // _self._state here is either 1 (fulfilled) or 2 (rejected).
        function promise2Resolver() {
            var _output     = _self._output,
                isFulfilled = _self._state < 2,
                handler     = isFulfilled ? onFulfilled : onRejected;

            if (typeof handler != FUNCTION) {
                isFulfilled ? promise2.resolve(_output) : promise2.reject(_output);
            } else {
                promise2Resolution(0, 1);
            }

            function promise2Resolution(x, isFirstTime) {
                var then,
                    done = 0;

                try {
                    if (isFirstTime)
                        x = handler(_output);

                    if (x == promise2) {
                        promise2.reject(TypeError());

                    } else if ((x && typeof x == "object" || typeof x == FUNCTION)
                               && typeof (then = x.then) == FUNCTION) {
                        then.call(x, function(y) { done++ || promise2Resolution(y) },
                                     function(r) { done++ || promise2.reject(r)    });

                    } else {
                        promise2.resolve(x);
                    }

                } catch (e) {
                    done++ || promise2.reject(e);
                }
            }
        }
    }
}

// Nothing to do other than having the correct prototype.
// then/resolve/reject all need a `this` object.
function NoPromise() {
}

NoPromise.deferred = function() {
    var d = new NoPromise;
    return d.promise = d;
};

try {
  module.exports = NoPromise;
} catch (e) {
  this.NoPromise = NoPromise;
}

})()
<|endoftext|>


<commit_before>jQuery(document).ready(function(){

	var currentLocArr = window.location.pathname.split("/");

	var currentLoc = currentLocArr[1];

	jQuery('.navbar-items a').each(function(index) {

		/* Get the controller name */
		var linkLocArr = this.href.split("/");

		var linkLoc = linkLocArr[3];

		if(linkLoc == currentLoc){
            jQuery(this).closest('li.menu-item').addClass("active");
		}else{
			jQuery(this).closest('li.menu-item').removeClass("active");
		}
	});
});<commit_msg>change the navbar javascript<commit_after>jQuery(document).ready(function(){

	var currentLocArr = window.location.pathname.split("/");

	var currentLoc = currentLocArr[1];

	if(currentLoc!==""){
		jQuery('.navbar-items a').each(function(index) {

			/* Get the controller name */
			var linkLocArr = this.href.split("/");

			var linkLoc = linkLocArr[3];

			if(linkLoc == currentLoc){
	            jQuery(this).closest('li.menu-item').addClass("active");
			}else{
				jQuery(this).closest('li.menu-item').removeClass("active");
			}
		});
	}
});<|endoftext|>


<commit_before>import CodeableConcept from 'ember-fhir-adapter/models/codeable-concept';

let IECodeableConcept = CodeableConcept.extend({
  hasCode: function(code){
    let matchedCodes = this.get('coding').map(function(c){
      return c.get('system') === code.system && c.get('code') === code.code;
    });
    return matchedCodes.any(function(d){return d;});
  },

  toString: function(){
    return this.get("text");
  }
});

export default IECodeableConcept;
<commit_msg>Fix toString on codeable concept<commit_after>import CodeableConcept from 'ember-fhir-adapter/models/codeable-concept';

let IECodeableConcept = CodeableConcept.extend({
  hasCode: function(code){
    let matchedCodes = this.get('coding').map(function(c){
      return c.get('system') === code.system && c.get('code') === code.code;
    });
    return matchedCodes.any(function(d){return d;});
  },

  toString: function(){
    return this.get("text")||this.get('coding.firstObject.display')||`${this.get('coding.firstObject.system')}-${this.get('coding.firstObject.code')}`;
  }
});

export default IECodeableConcept;
<|endoftext|>


<commit_before>// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

wn.ui.toolbar.Toolbar = Class.extend({
	init: function() {
		this.make();
		//this.make_modules();
		this.make_file();
		wn.ui.toolbar.recent = new wn.ui.toolbar.RecentDocs();
		wn.ui.toolbar.bookmarks = new wn.ui.toolbar.Bookmarks();
		this.make_tools();
		this.set_user_name();
		this.make_logout();
		this.make_notification();

		$('.dropdown-toggle').dropdown();

		$(document).trigger('toolbar_setup');

		// clear all custom menus on page change
		$(document).on("page-change", function() {
			$("header .navbar .custom-menu").remove();
		})
	},
	make: function() {
		$('header').append('
\

\
				<button type="button" class="navbar-toggle" data-toggle="collapse" \
					data-target=".navbar-responsive-collapse">\
					\
					\
					\
				</button>\
				\

\

\

\
					\

\

\
							\

\

\

\

\

\

\

');
	},
	make_home: function() {
		$('.navbar-brand').attr('href', "#");
	},

	make_notification: function() {
		$('.navbar .pull-right').append('
\
			0\

\

\

');

		$(document).on("notification-update", function() {
			wn.ui.toolbar.update_notifications();
		})
	},

	// make_modules: function() {
	// 	$('
\
	// 		'+wn._("Modules")+'\
	//
\
	//
\
	//
').prependTo('.navbar .nav:first');
	//
	// 	var modules_list = wn.user.get_desktop_items().sort();
	// 	var menu_list = $(".navbar .modules");
	//
	// 	var _get_list_item = function(m) {
	// 		args = {
	// 			module: m,
	// 			module_page: wn.modules[m].link,
	// 			module_label: wn._(wn.modules[m].label || m),
	// 			icon: wn.modules[m].icon
	// 		}
	//
	// 		return repl('
\
	// 			%(module_label)s
', args);
	// 	}
	//
	// 	// desktop
	// 	$('
 '
	// 		+ wn._("Desktop") + '
\
	//

').appendTo(menu_list)
	//
	// 	// add to dropdown
	// 	$.each(modules_list,function(i, m) {
	// 		if(m!='Setup') {
	// 			menu_list.append(_get_list_item(m));
	// 		}
	// 	})
	//
	// 	// setup for system manager
	// 	if(user_roles.indexOf("System Manager")!=-1) {
	// 		menu_list.append('
' + _get_list_item("Setup"));
	// 	}
	//
	// },

	make_file: function() {
		wn.ui.toolbar.new_dialog = new wn.ui.toolbar.NewDialog();
		wn.ui.toolbar.search = new wn.ui.toolbar.Search();
		wn.ui.toolbar.report = new wn.ui.toolbar.Report();
		$('.navbar .nav:first').append('
\
			'+wn._("File")+'\

\

\
					 '+wn._('New')+'...
\

\
					 '+wn._('Search')+'...
\

\
					 '+wn._('Report')+'...
\

\

');
	},

	make_tools: function() {
		$('.navbar .nav:first').append('
\
			Tools\

\

'
					+wn._('Clear Cache & Refresh')+'
\

'
					+wn._('About')+'
\

'
					+wn._('Attributions')+'
\

\

');

		if(has_common(user_roles,['Administrator','System Manager'])) {
			$('#toolbar-tools').append('
'
				+wn._('Download Backup')+'
');
		}
	},
	set_user_name: function() {
		var fn = user_fullname;
		if(fn.length > 15) fn = fn.substr(0,12) + '...';
		$('#toolbar-user-link').html(fn + '');
	},

	make_logout: function() {
		// logout
		$('#toolbar-user').append('
'
			+wn._('Logout')+'
');
	}
});

wn.ui.toolbar.update_notifications = function() {
	var total = 0;
	var doctypes = keys(wn.boot.notification_info.open_count_doctype).sort();
	var modules = keys(wn.boot.notification_info.open_count_module).sort();

	$("#navbar-notification").empty();

	$.each(modules, function(i, module) {
		var count = wn.boot.notification_info.open_count_module[module];
		if(count) {
			$(repl('
\
				\
					%(count)s \
				%(module)s
', {
					module: module,
					count: count
				}))
				.appendTo("#navbar-notification")
					.find("a")
					.attr("data-module", module)
					.css({"min-width":"200px"})
					.on("click", function() {
						wn.set_route(wn.modules[$(this).attr("data-module")].link);
					});
			total += count;
		}
	});

	if(total) {
		$('

').appendTo("#navbar-notification");
	}

	$.each(doctypes, function(i, doctype) {
		var count = wn.boot.notification_info.open_count_doctype[doctype];
		if(count) {
			$(repl('
\
				\
					%(count)s \
				 %(doctype)s
', {
					doctype: doctype,
					icon: wn.boot.doctype_icons[doctype],
					count: count
				}))
				.appendTo("#navbar-notification")
					.find("a")
					.attr("data-doctype", doctype)
					.css({"min-width":"200px"})
					.on("click", function() {
						wn.views.show_open_count_list(this);
					});
			total += count;
		}
	});

	$(".navbar-new-comments")
		.html(total)
		.toggleClass("navbar-new-comments-true", total ? true : false);

}

wn.ui.toolbar.clear_cache = function() {
	localStorage && localStorage.clear();
	$c('webnotes.sessions.clear',{},function(r,rt){
		if(!r.exc) {
			show_alert(r.message);
			location.reload();
		}
	});
	return false;
}

wn.ui.toolbar.download_backup = function() {
	msgprint(wn._("Your download is being built, this may take a few moments..."));
	$c('webnotes.utils.backups.get_backup',{},function(r,rt) {});
	return false;
}

wn.ui.toolbar.show_about = function() {
	try {
		wn.ui.misc.about();
	} catch(e) {
		console.log(e);
	}
	return false;
}
<commit_msg>[icons] added icons to forms, toolbars, moduleview, doclistview, reportview<commit_after>// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

wn.ui.toolbar.Toolbar = Class.extend({
	init: function() {
		this.make();
		//this.make_modules();
		this.make_file();
		wn.ui.toolbar.recent = new wn.ui.toolbar.RecentDocs();
		wn.ui.toolbar.bookmarks = new wn.ui.toolbar.Bookmarks();
		this.make_tools();
		this.set_user_name();
		this.make_logout();
		this.make_notification();

		$('.dropdown-toggle').dropdown();

		$(document).trigger('toolbar_setup');

		// clear all custom menus on page change
		$(document).on("page-change", function() {
			$("header .navbar .custom-menu").remove();
		})
	},
	make: function() {
		$('header').append('
\

\
				<button type="button" class="navbar-toggle" data-toggle="collapse" \
					data-target=".navbar-responsive-collapse">\
					\
					\
					\
				</button>\
				\

\

\

\
					\

\

\
							\

\

\

\

\

\

\

');
	},
	make_home: function() {
		$('.navbar-brand').attr('href', "#");
	},

	make_notification: function() {
		$('.navbar .pull-right').append('
\
			0\

\

\

');

		$(document).on("notification-update", function() {
			wn.ui.toolbar.update_notifications();
		})
	},

	// make_modules: function() {
	// 	$('
\
	// 		'+wn._("Modules")+'\
	//
\
	//
\
	//
').prependTo('.navbar .nav:first');
	//
	// 	var modules_list = wn.user.get_desktop_items().sort();
	// 	var menu_list = $(".navbar .modules");
	//
	// 	var _get_list_item = function(m) {
	// 		args = {
	// 			module: m,
	// 			module_page: wn.modules[m].link,
	// 			module_label: wn._(wn.modules[m].label || m),
	// 			icon: wn.modules[m].icon
	// 		}
	//
	// 		return repl('
\
	// 			%(module_label)s
', args);
	// 	}
	//
	// 	// desktop
	// 	$('
 '
	// 		+ wn._("Desktop") + '
\
	//

').appendTo(menu_list)
	//
	// 	// add to dropdown
	// 	$.each(modules_list,function(i, m) {
	// 		if(m!='Setup') {
	// 			menu_list.append(_get_list_item(m));
	// 		}
	// 	})
	//
	// 	// setup for system manager
	// 	if(user_roles.indexOf("System Manager")!=-1) {
	// 		menu_list.append('
' + _get_list_item("Setup"));
	// 	}
	//
	// },

	make_file: function() {
		wn.ui.toolbar.new_dialog = new wn.ui.toolbar.NewDialog();
		wn.ui.toolbar.search = new wn.ui.toolbar.Search();
		wn.ui.toolbar.report = new wn.ui.toolbar.Report();
		$('.navbar .nav:first').append('
\
			'+wn._("File")+'\

\

\
					 '+wn._('New')+'...
\

\
					 '+wn._('Search')+'...
\

\
					 '+wn._('Report')+'...
\

\

');
	},

	make_tools: function() {
		$('.navbar .nav:first').append('
\
			Tools\

\

'
					+wn._('Clear Cache & Refresh')+'
\

'
					+wn._('About')+'
\

'
					+wn._('Attributions')+'
\

\

');

		if(has_common(user_roles,['Administrator','System Manager'])) {
			$('#toolbar-tools').append('
'
				+wn._('Download Backup')+'
');
		}
	},
	set_user_name: function() {
		var fn = user_fullname;
		if(fn.length > 15) fn = fn.substr(0,12) + '...';
		$('#toolbar-user-link').html(fn + '');
	},

	make_logout: function() {
		// logout
		$('#toolbar-user').append('
'
			+wn._('Logout')+'
');
	}
});

wn.ui.toolbar.update_notifications = function() {
	var total = 0;
	var doctypes = keys(wn.boot.notification_info.open_count_doctype).sort();
	var modules = keys(wn.boot.notification_info.open_count_module).sort();

	$("#navbar-notification").empty();

	$.each(modules, function(i, module) {
		var count = wn.boot.notification_info.open_count_module[module];
		if(count) {
			$(repl('
\
				\
					%(count)s \
				 %(module)s
', {
					module: module,
					count: count,
					icon: wn.modules[module].icon
				}))
				.appendTo("#navbar-notification")
					.find("a")
					.attr("data-module", module)
					.css({"min-width":"200px"})
					.on("click", function() {
						wn.set_route(wn.modules[$(this).attr("data-module")].link);
					});
			total += count;
		}
	});

	if(total) {
		$('

').appendTo("#navbar-notification");
	}

	$.each(doctypes, function(i, doctype) {
		var count = wn.boot.notification_info.open_count_doctype[doctype];
		if(count) {
			$(repl('
\
				\
					%(count)s \
				 %(doctype)s
', {
					doctype: doctype,
					icon: wn.boot.doctype_icons[doctype],
					count: count
				}))
				.appendTo("#navbar-notification")
					.find("a")
					.attr("data-doctype", doctype)
					.css({"min-width":"200px"})
					.on("click", function() {
						wn.views.show_open_count_list(this);
					});
			total += count;
		}
	});

	$(".navbar-new-comments")
		.html(total)
		.toggleClass("navbar-new-comments-true", total ? true : false);

}

wn.ui.toolbar.clear_cache = function() {
	localStorage && localStorage.clear();
	$c('webnotes.sessions.clear',{},function(r,rt){
		if(!r.exc) {
			show_alert(r.message);
			location.reload();
		}
	});
	return false;
}

wn.ui.toolbar.download_backup = function() {
	msgprint(wn._("Your download is being built, this may take a few moments..."));
	$c('webnotes.utils.backups.get_backup',{},function(r,rt) {});
	return false;
}

wn.ui.toolbar.show_about = function() {
	try {
		wn.ui.misc.about();
	} catch(e) {
		console.log(e);
	}
	return false;
}
<|endoftext|>


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

lg.d3 = function () {
  var self = {};

  var width = window.innerWidth * 0.85 - 20,
      height = window.innerHeight,
      nodeRadius = 10;

  var color = d3.scale.category20();

  function buildsToGraph() {
    var links = [];
    var buildIndexesByNameAndNumber = {};
    var builds = lg.allBuilds;

    _.each(builds, function (build, index) {
      buildIndexesByNameAndNumber[build.code] = index;
    });
    _.each(builds, function (build) {
      var buildIndex = buildIndexesByNameAndNumber[build.code];
      _.each(build.children, function (child) {
        links.push({
          source: buildIndex,
          target: buildIndexesByNameAndNumber[child.code]
        });
      });
    });

    return {
      nodes: builds,
      links: links
    };
  }

  var svg = d3.select("#graph").insert("svg", ":first-child")
      .attr("width", width)
      .attr("height", height);

  var force = d3.layout.force()
      .gravity(0.1)
      .charge(-200)
      .linkDistance(
        function(link) {
          if (link.target.numberOfSiblings() > 6) {
            return 60;
          } else {
            return 20;
          }
        })
      .size([width, height]);

  var forceNodes = force.nodes();

  var forceLinks = force.links();

  var buildsCentroids = [
    {x: 1 * width/4, y: 1 * height/4},
    {x: 3 * width/4, y: 1 * height/4},
    {x: 3 * width/4, y: 3 * height/4},
    {x: 1 * width/4, y: 3 * height/4}];

  function restart() {
    var allLinks = svg.selectAll("line.link")
        .data(forceLinks, function (d) { return d.source + '-' + d.target; });

    var linkEnter = allLinks
        .enter().insert('svg:line', 'g.node')
        .attr('class',  'link');

    allLinks.exit().remove();

    var allNodes = svg
        .selectAll('.node')
        .data(forceNodes);

    var nodeEnter = allNodes
        .enter()
        .append('g')
        .attr('class', 'node')
        .attr('data-build-code', function (d) { return d.code; })
        .call(force.drag);

    nodeEnter.append('svg:circle')
        .attr('r', function (d) {
          return nodeRadius;
        })
        .attr('class', function (d) {
          return d.status + ' ' + (d.job.isLast ? 'last' : '');
        })
        .style('fill', function(d) {
          if (d.status == 'success') {
            if (d.isRoot()) {
              return '#00cc00';
            }
            if (d.job.isLast) {
              return '#00ff00';
            }
            return 'green';
          }
          if (d.status == 'building') {
            return 'yellow';
          }
          if (d.status == 'failure') {
            return 'red';
          }
          return '#bbb';
        });

    nodeEnter.append('text')
        .attr('class', 'nodetext')
        .attr("dx", 12)
        .attr("dy", ".35em")
        .text(function (d) {
          if (d.hasFailed()) {
            return d.displayName.replace(/^qe_selenium_/i, '');
          }
          if (d.isRoot()) {
            return d.culprits;
          }
          return '';
        });

    nodeEnter.append('title').text(function (d) { return d.displayName; });

    allNodes.exit().remove();

    function findHeadBuild(build) {
      var parentBuilds;
      parentBuilds = forceLinks.filter(function (link) {
        return link.target.code === build;
      });

      if (parentBuilds.length == 0) {
        return build;
      }

      return findHeadBuild(parentBuilds[0].source.code);
    };

    force.on("tick", function(e) {
      linkEnter
        .attr("x1", function(d) { return normalizePosition(d.source).x; })
        .attr("y1", function(d) { return normalizePosition(d.source).y; })
        .attr("x2", function(d) { return normalizePosition(d.target).x; })
        .attr("y2", function(d) { return normalizePosition(d.target).y; });

      nodeEnter.attr("transform", function(d) {
        var position = normalizePosition(d);
        return "translate(" + position.x + "," + position.y + ")";
      });

      var headNodes = forceNodes.filter(
        function(node) {
          parentBuilds = forceLinks.filter(function (link) {
            return link.target.code === node.code;
          });
          return parentBuilds.length == 0;
        });

      headNodes.sort(
        function(a, b) {
          if (a.code < b.code)
            return 1;
          if (a.code > b.code)
            return -1;
          return 0;
        });

      var k = e.alpha * 0.1;
      forceNodes.forEach(
        function(node) {
          var headBuildCode = findHeadBuild(node.code);
          var center = buildsCentroids[headNodes.reduce(
            function( cur, val, index ){
              if( val.code === headBuildCode && cur === -1 ) {
                return index;
              }
              return cur;
            }, -1 )];
          node.x += (center.x - node.x) * k;
          node.y += (center.y - node.y) * k;
        });
    });

    force.start();
  }

  function normalizePosition(d) {
    var averageTextSize = 100;
    return {
      x: Math.max(nodeRadius, Math.min(width - nodeRadius - averageTextSize, d.x)),
      y: Math.max(nodeRadius, Math.min(height - nodeRadius, d.y))
    };
  }

  self.redraw = function () {
    forceNodes.splice(0, forceNodes.length);
    forceLinks.splice(0, forceLinks.length);
    restart();

    var graph = buildsToGraph();

    _.each(graph.nodes, function (n) { forceNodes.push(n); });
    _.each(graph.links, function (l) { forceLinks.push(l); });
    restart();
  };

  return self;
};
<commit_msg>Use root build information, and build are attracted to the root center of every root build<commit_after>var lg = lg || {};

lg.d3 = function () {
  var self = {};

  var width = window.innerWidth * 0.85 - 20,
      height = window.innerHeight,
      nodeRadius = 10;

  var color = d3.scale.category20();

  function buildsToGraph() {
    var links = [];
    var buildIndexesByNameAndNumber = {};
    var builds = lg.allBuilds;

    _.each(builds, function (build, index) {
      buildIndexesByNameAndNumber[build.code] = index;
    });
    _.each(builds, function (build) {
      var buildIndex = buildIndexesByNameAndNumber[build.code];
      _.each(build.children, function (child) {
        links.push({
          source: buildIndex,
          target: buildIndexesByNameAndNumber[child.code]
        });
      });
    });

    return {
      nodes: builds,
      links: links
    };
  }

  var svg = d3.select("#graph").insert("svg", ":first-child")
      .attr("width", width)
      .attr("height", height);

  var force = d3.layout.force()
      .gravity(0.1)
      .charge(-200)
      .linkDistance(
        function(link) {
          if (link.target.numberOfSiblings() > 6) {
            return 60;
          } else {
            return 20;
          }
        })
      .size([width, height]);

  var forceNodes = force.nodes();

  var forceLinks = force.links();

  var buildsCentroids = [
    {x: 1 * width/4, y: 1 * height/4},
    {x: 3 * width/4, y: 1 * height/4},
    {x: 3 * width/4, y: 3 * height/4},
    {x: 1 * width/4, y: 3 * height/4},
    {x: 0 * width/4, y: 4 * height/4}];

  function restart() {
    var allLinks = svg.selectAll("line.link")
        .data(forceLinks, function (d) { return d.source + '-' + d.target; });

    var linkEnter = allLinks
        .enter().insert('svg:line', 'g.node')
        .attr('class',  'link');

    allLinks.exit().remove();

    var allNodes = svg
        .selectAll('.node')
        .data(forceNodes);

    var nodeEnter = allNodes
        .enter()
        .append('g')
        .attr('class', 'node')
        .attr('data-build-code', function (d) { return d.code; })
        .call(force.drag);

    nodeEnter.append('svg:circle')
        .attr('r', function (d) {
          return nodeRadius;
        })
        .attr('class', function (d) {
          return d.status + ' ' + (d.job.isLast ? 'last' : '');
        })
        .style('fill', function(d) {
          if (d.status == 'success') {
            if (d.isRoot()) {
              return '#00cc00';
            }
            if (d.job.isLast) {
              return '#00ff00';
            }
            return 'green';
          }
          if (d.status == 'building') {
            return 'yellow';
          }
          if (d.status == 'failure') {
            return 'red';
          }
          return '#bbb';
        });

    nodeEnter.append('text')
        .attr('class', 'nodetext')
        .attr("dx", 12)
        .attr("dy", ".35em")
        .text(function (d) {
          if (d.hasFailed()) {
            return d.displayName.replace(/^qe_selenium_/i, '');
          }
          if (d.isRoot()) {
            return d.culprits;
          }
          return '';
        });

    nodeEnter.append('title').text(function (d) { return d.displayName; });

    allNodes.exit().remove();

    function findHeadBuild(build) {
      var parentBuilds;
      parentBuilds = forceLinks.filter(function (link) {
        return link.target.code === build;
      });

      if (parentBuilds.length == 0) {
        return build;
      }

      return findHeadBuild(parentBuilds[0].source.code);
    };

    force.on("tick", function(e) {
      linkEnter
        .attr("x1", function(d) { return normalizePosition(d.source).x; })
        .attr("y1", function(d) { return normalizePosition(d.source).y; })
        .attr("x2", function(d) { return normalizePosition(d.target).x; })
        .attr("y2", function(d) { return normalizePosition(d.target).y; });

      nodeEnter.attr("transform", function(d) {
        var position = normalizePosition(d);
        return "translate(" + position.x + "," + position.y + ")";
      });

      var headNodes = forceNodes.filter(
        function(node) {
          return node.isRoot();
        });

      headNodes.sort(
        function(a, b) {
          if (a.code < b.code)
            return 1;
          if (a.code > b.code)
            return -1;
          return 0;
        });

      var k = e.alpha * 0.1;
      forceNodes.forEach(
        function(node) {
          node.rootBuildsCode.forEach(function(rootBuild) {
            var screenPosition = headNodes.indexOf(lg.buildsByCode[rootBuild]);
            var center = buildsCentroids[screenPosition];
            node.x += (center.x - node.x) * k;
            node.y += (center.y - node.y) * k;
          });
        });
    });

    force.start();
  }

  function normalizePosition(d) {
    var averageTextSize = 100;
    return {
      x: Math.max(nodeRadius, Math.min(width - nodeRadius - averageTextSize, d.x)),
      y: Math.max(nodeRadius, Math.min(height - nodeRadius, d.y))
    };
  }

  self.redraw = function () {
    forceNodes.splice(0, forceNodes.length);
    forceLinks.splice(0, forceLinks.length);
    restart();

    var graph = buildsToGraph();

    _.each(graph.nodes, function (n) { forceNodes.push(n); });
    _.each(graph.links, function (l) { forceLinks.push(l); });
    restart();
  };

  return self;
};
<|endoftext|>


<commit_before>'use strict';

/* Controllers */
function WanderCtrl(scope, rootScope, cookies, FB) {
	// FB.init({
	// 		appId      : js_appId,                    // App ID from the app dashboard
	// 		status     : true,                                 // Check Facebook Login status
	// 		xfbml      : true                                  // Look for social plugins on the page
	// 	});
}

function LoginCtrl(scope) {
}

function SketchCtrl(scope, cookies, FB) {
	FB.api('/me?fields=name,hometown,picture,birthday,photos.limit(1)', function(response) {
		scope.user = response;
	});

	scope.sketch = function(processing) {
		var profile_pic;
		var online;

		processing.setup = function() {
			processing.size(window.innerWidth, window.innerHeight);
		};

		processing.draw = function() {
			processing.background(255);
			processing.fill(0);
			processing.textSize(32);
			if(scope.user) {
				processing.text('Hello ' + scope.user.name, 500, 100);
				processing.text('Your hometown is ' + scope.user.hometown.name, 500, 150);
				processing.text('Your birthday is ' + scope.user.birthday, 500, 200);
				processing.text('Heres a photo of you', 500, 250);
				var photo_url = scope.user.photos.data[0].source;
				var profile_pic_url = scope.user.picture.data.url;
				if(online) {
					processing.image(online, 600, 300);
				} else {
					online = processing.loadImage(photo_url, "jpg");
				}

				if(profile_pic) {
					processing.image(profile_pic, 400, 75);
				} else {
					profile_pic = processing.loadImage(profile_pic_url, "jpg");
				}
			}
		};
	}
}

WanderCtrl.$inject = ['$scope', '$rootScope', '$cookies', 'Facebook'];
LoginCtrl.$inject = ['$scope'];
SketchCtrl.$inject = ['$scope', '$cookies', 'Facebook'];<commit_msg>Redirect when 'user' object isn't defined<commit_after>'use strict';

/* Controllers */
function WanderCtrl(scope, rootScope, cookies, FB) {
	// FB.init({
	// 		appId      : js_appId,                    // App ID from the app dashboard
	// 		status     : true,                                 // Check Facebook Login status
	// 		xfbml      : true                                  // Look for social plugins on the page
	// 	});
}

function LoginCtrl(scope) {
}

function SketchCtrl(scope, cookies, location, FB) {
	FB.api('/me?fields=name,hometown,picture,birthday,photos.limit(1)', function(response) {
		scope.user = response;
	});

	scope.sketch = function(processing) {
		var profile_pic;
		var online;

		processing.setup = function() {
			processing.size(window.innerWidth, window.innerHeight);
		};

		processing.draw = function() {
			processing.background(255);
			processing.fill(0);
			processing.textSize(32);
			if(scope.user) {
				if(!scope.user.error) {
					if(scope.user.name) processing.text('Hello ' + scope.user.name, 500, 100);
					if(scope.user.hometown) processing.text('Your hometown is ' + scope.user.hometown.name, 500, 150);
					if(scope.user.birthday) processing.text('Your birthday is ' + scope.user.birthday, 500, 200);
					if(scope.user.picture) processing.text('Heres a photo of you', 500, 250);
					var photo_url = scope.user.photos.data[0].source;
					var profile_pic_url = scope.user.picture.data.url;
					if(online) {
						processing.image(online, 600, 300);
					} else {
						online = processing.loadImage(photo_url, "jpg");
					}

					if(profile_pic) {
						processing.image(profile_pic, 400, 75);
					} else {
						profile_pic = processing.loadImage(profile_pic_url, "jpg");
					}
				} else {
					window.location.href = '/';
				}
			}
		};
	}
}

WanderCtrl.$inject = ['$scope', '$rootScope', '$cookies', 'Facebook'];
LoginCtrl.$inject = ['$scope'];
SketchCtrl.$inject = ['$scope', '$cookies', '$location', 'Facebook'];<|endoftext|>


<commit_before>'use strict';

function modInputs(numChoices, oneChoice) {
  var result = $('.choice-wrapper');
  var renderFunc = Handlebars.compile($('#choice-template').html());
  if (numChoices > result.length) {
    var toAdd = numChoices - result.length;
    for (var a = 0; a < toAdd; a++) {
      if (!oneChoice) {
        var choiceToAdd = renderFunc({choiceText: '#choice', choiceColor: '#666666', baseVal: 0});
        $('#choice-result').append(choiceToAdd);
      }
      else {
        var choiceToAdd = renderFunc({choiceText: oneChoice.choice_text, choiceColor: oneChoice.choice_color, baseVal: oneChoice.value});
        $('#choice-result').append(choiceToAdd);
      }
    }
  } else if (numChoices < result.length) {
    var toRemove = result.length - numChoices;
    for (var a = 1; a <= toRemove; a++) {
      result.eq(result.length - a).remove();
    }
  }
}

// function addPreview(choices) {
//   var result = document.querySelector('#container');
//   result.innerHTML = ' ';
//   for (var i = 0; i < parseInt(choices.value); i++) {
//     var wrapper = document.createElement('div');
//     wrapper.innerHTML = '0 Vote';
//     result.appendChild(wrapper);
//   }
// };

$('#poll-choices').on('change', function () {
  modInputs(this.value);
  // addPreview(this);
});

// $('#fillcheckboxall').on('click', function () {
//   $('.fill-color').toggle();
// });

// $('#test-button').on('click', function (e){
//   e.preventDefault();
//   $('#widget-display').toggle();
// });

// Check to see if there are existing choices in the database, and draw the page appropriately if so
function renderWidget() {
  $.get(`/choices/${userInfo.currentUser}`, function (data) {
    var userChoices = data;
    var renderFunc = Handlebars.compile($('#form-template').html());
    if (userChoices.length === 0) {
      var theForm = renderFunc({widgetText: '', textColor: '#000000', goal: 100, fillColor: '#666666'});
      $('#widget-form').prepend(theForm);
      modInputs(2, null);
    } else {
      var theForm = renderFunc({widgetText: userChoices[0].widget_text, textColor: userChoices[0].text_color, goal: userChoices[0].goal, fillColor: userChoices[0].fill_color});
      $('#widget-form').prepend(theForm);
      userChoices.forEach(modInputs(1), this);
    }
  });
};

// Save or update the database by deleting all the choices first, and then adding the new ones
$('#save-button').click(function() {
  deleteChoices();
  var widgetText = $('#widget-title').val();
  var textColor = $('#widget-color').val();
  var fillColor = $('#fill-color').val();
  var goal = $('#goal').val();
  var choicesText = $('.choice-input');
  var choicesColor = $('.choice-color');
  var choicesVal = $('.base-value');

  for (var a = 0; a < choicesText.length; a++) {
    var thisChoice = choicesText.eq(a);
    var thisColor = choicesColor.eq(a);
    var thisVal = choicesVal.eq(a);
    insertChoice(userInfo.currentUser, widgetText, textColor, fillColor, goal, thisChoice, thisColor, thisVal);
  }
});

// Clear button: Clear all fields, and delete the choices from the database
// $('#clear-button').click(function() {
//   deleteChoices();
//   modInputs(0, null);
//   modInputs(2, null);
// });
<commit_msg>Testing save<commit_after>'use strict';

function modInputs(numChoices, oneChoice) {
  var result = $('.choice-wrapper');
  var renderFunc = Handlebars.compile($('#choice-template').html());
  if (numChoices > result.length) {
    var toAdd = numChoices - result.length;
    for (var a = 0; a < toAdd; a++) {
      if (!oneChoice) {
        var choiceToAdd = renderFunc({choiceText: '#choice', choiceColor: '#666666', baseVal: 0});
        $('#choice-result').append(choiceToAdd);
      }
      else {
        var choiceToAdd = renderFunc({choiceText: oneChoice.choice_text, choiceColor: oneChoice.choice_color, baseVal: oneChoice.value});
        $('#choice-result').append(choiceToAdd);
      }
    }
  } else if (numChoices < result.length) {
    var toRemove = result.length - numChoices;
    for (var a = 1; a <= toRemove; a++) {
      result.eq(result.length - a).remove();
    }
  }
}

// function addPreview(choices) {
//   var result = document.querySelector('#container');
//   result.innerHTML = ' ';
//   for (var i = 0; i < parseInt(choices.value); i++) {
//     var wrapper = document.createElement('div');
//     wrapper.innerHTML = '0 Vote';
//     result.appendChild(wrapper);
//   }
// };

$('#poll-choices').on('change', function () {
  modInputs(this.value);
  // addPreview(this);
});

// $('#fillcheckboxall').on('click', function () {
//   $('.fill-color').toggle();
// });

// $('#test-button').on('click', function (e){
//   e.preventDefault();
//   $('#widget-display').toggle();
// });

// Check to see if there are existing choices in the database, and draw the page appropriately if so
function renderWidget() {
  $.get(`/choices/${userInfo.currentUser}`, function (data) {
    var userChoices = data;
    var renderFunc = Handlebars.compile($('#form-template').html());
    console.log(userChoices);
    if (userChoices.length === 0) {
      var theForm = renderFunc({widgetText: '', textColor: '#000000', goal: 100, fillColor: '#666666'});
      $('#widget-form').prepend(theForm);
      modInputs(2, null);
    } else {
      var theForm = renderFunc({widgetText: userChoices[0].widget_text, textColor: userChoices[0].text_color, goal: userChoices[0].goal, fillColor: userChoices[0].fill_color});
      $('#widget-form').prepend(theForm);
      userChoices.forEach(modInputs(1), this);
    }
  });
};

// Save or update the database by deleting all the choices first, and then adding the new ones
$('#save-button').click(function() {
  deleteChoices();
  var widgetText = $('#widget-title').val();
  var textColor = $('#widget-color').val();
  var fillColor = $('#fill-color').val();
  var goal = $('#goal').val();
  var choicesText = $('.choice-input');
  var choicesColor = $('.choice-color');
  var choicesVal = $('.base-value');

  for (var a = 0; a < choicesText.length; a++) {
    var thisChoice = choicesText.eq(a);
    var thisColor = choicesColor.eq(a);
    var thisVal = choicesVal.eq(a);
    insertChoice(userInfo.currentUser, widgetText, textColor, fillColor, goal, thisChoice, thisColor, thisVal);
  }
});

// Clear button: Clear all fields, and delete the choices from the database
// $('#clear-button').click(function() {
//   deleteChoices();
//   modInputs(0, null);
//   modInputs(2, null);
// });
<|endoftext|>