<commit_before>
function PassesStore() {
	if ( ! ( this instanceof PassesStore ) ) {
		return new PassesStore();
	}

	this.socket = false;
	this.tles = [];
	this.lastModified = false;
	this.passes = [];
	this.location = {
		longitude: 0,
		latitude: 0,
		altitude: 0,
		bearing: 180
	};
	this.favoriteIDs = [];
	this.notes = [
		{
			id: 1002,
			text: 'Downlink (tone) at about 237 MHz'
		},
		{
			id: 7530,
			text: 'TLM Beacon: Downlink 145.9775 MHz CW; Uplink: 432.1250 – 432.1750 MHz SSB/CW; Downlink 145.9750 – 145.9250 MHz SSB/CW',
		},
		{
			id: 24278,
			text: 'Downlink 435.8000 – 435.9000 MHz SSB/CW'
		},
		{
			id: 25544,
			text: 'Packet Downlink 145.825 MHz'
		},
		{
			id: 26931,
			text: 'Uplink and Downlink: 145.825 MHz (FM FSK, AX.25, 1k2 and 9k6) (sun only)'
		},
		{
			id: 27607,
			text: 'Uplink: 145.850 MHz (67.0 Hz PL Tone) SO-50 also has a 10 minute timer that must be armed before use. Transmit a 2 second carrier with a PL tone of 74.4 to arm the timer.; Downlink: 436.800 MHz'
		},
		{
			id: 27844,
			text: 'Downlinks on CW Beacon 436.8375, packet 437.470'
		},
		{
			id: 32789,
			text: 'Downlink: 145.870 MHz, 1200 Baud, BPSK, AX.25, 100mW operational in Sun'
		},
		{
			id: 36122,
			text: 'Downlink 435.7900 MHz CW Beacon; 435.6750 MHz FM Voice repeater; 435.7650 – 435.7150 MHz SSB/CW Linear transponder (inverted); 435.6750 MHz 1k2 AFSK FM'
		},
		{
			id: 39444,
			text: '145.935 MHz BPSK Telemetry; Transponder (eclipse only): 435.150 – 435.130 MHz Uplink; – 145.950 – 145.970 MHz Downlink'
		},
		{
			id: 39770,
			text: '437.525 MHz FM 1k2 AFSK AX.25, CW, SSTV Downlink'
		},
		{
			id: 40897,
			text: 'Downlink: 145.980 MHz GFSK modulation at 9600 bps and AX.25 every 10 seconds, 437.365 MHz CW/MSK at 1200 bps and CSP'
		},
		{
			id: 40903,
			text: 'Downlink: Digital Telemetry 145.640, CW Beacon 145.660, Linear Transponder 145.665 ‐ 145.685'
		},
		{
			id: 40911,
			text: 'Downlink: Digital Telemetry 145.705, CW Beacon 145.725, Linear Transponder 145.730 ‐ 145.750'
		},
		{
			id: 40906,
			text: 'Downlink: Digital Telemetry 145.770, CW Beacon 145.790, Linear Transponder 145.795 ‐ 145.815'
		},
		{
			id: 40907,
			text: 'Downlink: Digital Telemetry 145.835, CW Beacon 145.855, Linear Transponder 145.860 ‐ 145.880'
		},
		{
			id: 40909,
			text: 'Downlink: Digital Telemetry 145.890, CW Beacon 145.910, Linear Transponder 145.915 ‐ 145.935'
		},
		{
			id: 40910,
			text: 'Uplink: Linear Transponder 435.330 - 435.350 MHz; Downlink: Digital Telemetry 145.955, CW Beacon 145.975, Linear Transponder 145.980 ‐ 146.000'
		},
		{
			id: 40967,
			text: 'Uplink: 435.180 MHz w/ 67 Hz tone; Downlink: 145.980 MHz'
		}
	];
}

PassesStore.prototype.findPassesOfFavorites = function() {

	if ( 0 == this.tles.length ) {
		return;
	}

	this.passes = [];

	var now = new Date();
	var nowTime = now.getTime() - 30 * 60 * 1000; // start a half hour ago
	var then = new Date();
	var thenTime = then.getTime();

	this.favoriteIDs.forEach( function( favoriteID ) {

		var favoriteTLE = _.findWhere( this.tles, { id: favoriteID } );

		var inPass = false;
		var position;

		var startTime, startAz, maxElTime, maxElAz, endTime, endAz;

		var maxEl = -1.0;
		var passPositions = [];

		// Only do any of this if we have TLEs
		if ( favoriteTLE ) {

			// Find all passes for this satellite for the next 1440 minutes (24 hours)
			for ( var minutes = 0; minutes < 1440; minutes++ ) {

				thenTime = nowTime + minutes * 60000;
				then.setTime( thenTime );

				position = this.findPositionOfSatellite( favoriteID, then );

				if ( null !== position.elevation ) {
					if ( position.elevation >= 0.0 ) {
						passPositions.push( {
							time: thenTime,
							azimuth: position.azimuth,
							elevation: position.elevation
						} );
					}

					if ( ! inPass && position.elevation >= 0.0 ) { // the pass has begun
						inPass = true;
						startTime = thenTime;
						startAz = position.azimuth;
					} else if ( inPass && position.elevation < 0.0 ) { // the pass has ended
						inPass = false;

						// save the record if Elevation got to at least 15 degrees
						if ( maxEl >= 15.0 ) {
							this.passes.push( {
								id : favoriteID,
								startTime: startTime,
								startAz: startAz,
								maxEl: maxEl,
								maxElAz: maxElAz,
								maxElTime: maxElTime,
								endTime: thenTime,
								endAz: position.azimuth,
								positions: passPositions
							} );
						}

						// Reset for next pass
						maxEl = -1.0;
						passPositions = [];
					}

					if ( inPass && position.elevation > maxEl ) {
						maxEl = position.elevation;
						maxElAz = position.azimuth;
						maxElTime = thenTime;
					}
				}
			}
		}
	}.bind( this ) );

	// Now, refine the found passes to second (not minute) resolution
	this.passes.forEach( function ( pass, index ) {
		inPass = false;
		thenTime = pass.startTime - 60 * 1000;
		maxEl = -1.0;

		do {
			then.setTime( thenTime );
			position = this.findPositionOfSatellite( pass.id, then );

			if ( ! inPass && position.elevation >= 0.0 ) {
				inPass = true;
				startTime = thenTime;
				startAz = position.azimuth;
			} else if ( inPass && position.elevation < 0.0 ) {
				inPass = false;
				endTime = thenTime;
				endAz = position.azimuth;
			}

			if ( inPass && position.elevation > maxEl ) {
				maxEl = position.elevation;
				maxElAz = position.azimuth;
				maxElTime = thenTime;
			}

			thenTime += 1000; // increment by one second
		} while ( thenTime < pass.endTime + 60 * 1000 );

		// update the record with the precision times
		pass.startTime = startTime;
		pass.startAz = startAz;
		pass.maxEl = maxEl;
		pass.maxElAz = maxElAz;
		pass.maxElTime = maxElTime;
		pass.endTime = endTime;
		pass.endAz = endAz;
		this.passes[ index ] = pass;
	}.bind( this ) );

	// Lastly, sort the passes in chronological order
	this.passes = this.passes.sort( function( a, b ) {
		if ( a.startTime < b.startTime ) {
			return -1;
		}
		if ( a.startTime > b.startTime ) {
			return 1;
		}
		return 0;
	} );

};

PassesStore.prototype.findPositionOfSatellite = function( satelliteID, dateTime ) {

	var azimuth = null;
	var elevation = null;
	var satelliteTLE = _.findWhere( this.tles, { id: satelliteID } );

	if ( satelliteTLE ) {
		var satrec = satellite.twoline2satrec( satelliteTLE.tleLine1, satelliteTLE.tleLine2 );

		var positionAndVelocity = satellite.propagate(
			satrec,
			dateTime.getUTCFullYear(),
			dateTime.getUTCMonth() + 1, // Note, this function requires months in range 1-12.
			dateTime.getUTCDate(),
			dateTime.getUTCHours(),
			dateTime.getUTCMinutes(),
			dateTime.getUTCSeconds()
		);

		var positionEci = positionAndVelocity.position;

		var deg2rad = Math.PI / 180.;
		var rad2deg = 1. / deg2rad;

		var observerGd = {
			longitude: this.location.longitude * deg2rad,
			latitude: this.location.latitude * deg2rad,
			height: 0.001 * this.location.altitude // m -> km. above WGS 84 ellipsoid?
		};

		var gmst = satellite.gstimeFromDate(
			dateTime.getUTCFullYear(),
			dateTime.getUTCMonth() + 1, // Note, this function requires months in range 1-12.
			dateTime.getUTCDate(),
			dateTime.getUTCHours(),
			dateTime.getUTCMinutes(),
			dateTime.getUTCSeconds()
		);

		var positionEcf = satellite.eciToEcf( positionEci, gmst ),
			lookAngles  = satellite.ecfToLookAngles( observerGd, positionEcf );

		azimuth   = Math.floor( 10.0 * lookAngles.azimuth * rad2deg ) / 10.0;
		elevation = Math.floor( 10.0 * lookAngles.elevation * rad2deg ) / 10.0;
		rangeSat  = Math.floor( lookAngles.rangeSat );
	}

	return { azimuth: azimuth, elevation: elevation, rangeSat: rangeSat };
};

PassesStore.prototype.loadFavorites = function() {
	// Default, just the space station and FOX-1A
	this.favoriteIDs = [ 25544, 40967 ];

	if ( "undefined" !== typeof localStorage ) {
		var localStorageFavorites = localStorage.getItem( "favorites" );
		if ( null !== localStorageFavorites ) {
			localStorageFavorites = localStorageFavorites.split( "," );
			this.favoriteIDs = [];
			localStorageFavorites.map( function( favorite ) {
				this.favoriteIDs.push( parseInt( favorite, 10 ) );
			}.bind( this ) );
			console.log( "loaded favorites from localStorage:", this.favoriteIDs );
		}
	}
};

PassesStore.prototype.setFavorites = function( favorites ) {
	this.favoriteIDs = favorites;

	if ( "undefined" !== typeof localStorage ) {
		// the browser will store arrays as a comma delimeted string
		localStorage.setItem( "favorites", favorites );
	}
};

PassesStore.prototype.getFavorites = function() {
	return this.favoriteIDs;
}

// TODO - add event emitter (e.g. when favorites changes)

PassesStore.prototype.init = function() {

	// Load favorites
	this.loadFavorites();

	// Connect our socket
	this.socket = io.connect();

	this.socket.on( 'location', ( function( data ) {
		this.location = data;
		this.findPassesOfFavorites();
	} ).bind( this ) );

	// listener, whenever the server emits 'tle-data', this updates the chat body
	this.socket.on( 'tle-data', ( function( data ) {
		this.tles = data.tle;
		this.lastModified = new Date( data.lastModified );
		this.findPassesOfFavorites();
	} ).bind( this ) );

};

module.exports = PassesStore;
<commit_msg>Add some notes for some more satellites<commit_after>
function PassesStore() {
	if ( ! ( this instanceof PassesStore ) ) {
		return new PassesStore();
	}

	this.socket = false;
	this.tles = [];
	this.lastModified = false;
	this.passes = [];
	this.location = {
		longitude: 0,
		latitude: 0,
		altitude: 0,
		bearing: 180
	};
	this.favoriteIDs = [];
	this.notes = [
		{
			id: 1002,
			text: 'Downlink (tone) at about 237 MHz'
		},
		{
			id: 7530,
			text: 'TLM Beacon: Downlink 145.9775 MHz CW; Uplink: 432.1250 – 432.1750 MHz SSB/CW; Downlink 145.9750 – 145.9250 MHz SSB/CW',
		},
		{
			id: 24278,
			text: 'Downlink 435.8000 – 435.9000 MHz SSB/CW'
		},
		{
			id: 25544,
			text: 'Packet Downlink 145.825 MHz'
		},
		{
			id: 26931,
			text: 'Uplink and Downlink: 145.825 MHz (FM FSK, AX.25, 1k2 and 9k6) (sun only)'
		},
		{
			id: 27607,
			text: 'Uplink: 145.850 MHz (67.0 Hz PL Tone) SO-50 also has a 10 minute timer that must be armed before use. Transmit a 2 second carrier with a PL tone of 74.4 to arm the timer.; Downlink: 436.800 MHz'
		},
		{
			id: 27844,
			text: 'Downlinks on CW Beacon 436.8375, packet 437.470'
		},
		{
			id: 28895,
			text: 'Downlink: 437.345 MHz FM FSK AX.25 1k2, 437.465 MHz CW'
		},
		{
			id: 32785,
			text: 'Downlink: 437.475 MHz, FM FSK 9k6 / AFSK 1k2 (AX.25)'
		},
		{
			id: 32789,
			text: 'Downlink: 145.870 MHz, 1200 Baud, BPSK, AX.25, 100mW operational in Sun'
		},
		{
			id: 36122,
			text: 'Downlink 435.7900 MHz CW Beacon; 435.6750 MHz FM Voice repeater; 435.7650 – 435.7150 MHz SSB/CW Linear transponder (inverted); 435.6750 MHz 1k2 AFSK FM'
		},
		{
			id: 39430,
			text: 'Downlink 437.250 MHz, 1k2/2k4/4k8/9k6 GMSK'
		},
		{
			id: 39444,
			text: '145.935 MHz BPSK Telemetry; Transponder (eclipse only): 435.150 – 435.130 MHz Uplink; – 145.950 – 145.970 MHz Downlink'
		},
		{
			id: 39770,
			text: '437.525 MHz FM 1k2 AFSK AX.25, CW, SSTV Downlink'
		},
		{
			id: 40021,
			text: 'Uplink: 435.220 MHz; Downlink: 145.980 MHz APRS/Beacon'
		},
		{
			id: 40897,
			text: 'Downlink: 145.980 MHz GFSK modulation at 9600 bps and AX.25 every 10 seconds, 437.365 MHz CW/MSK at 1200 bps and CSP'
		},
		{
			id: 40903,
			text: 'Downlink: Digital Telemetry 145.640, CW Beacon 145.660, Linear Transponder 145.665 ‐ 145.685'
		},
		{
			id: 40911,
			text: 'Downlink: Digital Telemetry 145.705, CW Beacon 145.725, Linear Transponder 145.730 ‐ 145.750'
		},
		{
			id: 40906,
			text: 'Downlink: Digital Telemetry 145.770, CW Beacon 145.790, Linear Transponder 145.795 ‐ 145.815'
		},
		{
			id: 40907,
			text: 'Downlink: Digital Telemetry 145.835, CW Beacon 145.855, Linear Transponder 145.860 ‐ 145.880'
		},
		{
			id: 40909,
			text: 'Downlink: Digital Telemetry 145.890, CW Beacon 145.910, Linear Transponder 145.915 ‐ 145.935'
		},
		{
			id: 40910,
			text: 'Uplink: Linear Transponder 435.330 - 435.350 MHz; Downlink: Digital Telemetry 145.955, CW Beacon 145.975, Linear Transponder 145.980 ‐ 146.000'
		},
		{
			id: 40967,
			text: 'Uplink: 435.170 MHz w/ 67 Hz tone; Downlink: 145.980 MHz'
		}
	];
}

PassesStore.prototype.findPassesOfFavorites = function() {

	if ( 0 == this.tles.length ) {
		return;
	}

	this.passes = [];

	var now = new Date();
	var nowTime = now.getTime() - 30 * 60 * 1000; // start a half hour ago
	var then = new Date();
	var thenTime = then.getTime();

	this.favoriteIDs.forEach( function( favoriteID ) {

		var favoriteTLE = _.findWhere( this.tles, { id: favoriteID } );

		var inPass = false;
		var position;

		var startTime, startAz, maxElTime, maxElAz, endTime, endAz;

		var maxEl = -1.0;
		var passPositions = [];

		// Only do any of this if we have TLEs
		if ( favoriteTLE ) {

			// Find all passes for this satellite for the next 1440 minutes (24 hours)
			for ( var minutes = 0; minutes < 1440; minutes++ ) {

				thenTime = nowTime + minutes * 60000;
				then.setTime( thenTime );

				position = this.findPositionOfSatellite( favoriteID, then );

				if ( null !== position.elevation ) {
					if ( position.elevation >= 0.0 ) {
						passPositions.push( {
							time: thenTime,
							azimuth: position.azimuth,
							elevation: position.elevation
						} );
					}

					if ( ! inPass && position.elevation >= 0.0 ) { // the pass has begun
						inPass = true;
						startTime = thenTime;
						startAz = position.azimuth;
					} else if ( inPass && position.elevation < 0.0 ) { // the pass has ended
						inPass = false;

						// save the record if Elevation got to at least 15 degrees
						if ( maxEl >= 15.0 ) {
							this.passes.push( {
								id : favoriteID,
								startTime: startTime,
								startAz: startAz,
								maxEl: maxEl,
								maxElAz: maxElAz,
								maxElTime: maxElTime,
								endTime: thenTime,
								endAz: position.azimuth,
								positions: passPositions
							} );
						}

						// Reset for next pass
						maxEl = -1.0;
						passPositions = [];
					}

					if ( inPass && position.elevation > maxEl ) {
						maxEl = position.elevation;
						maxElAz = position.azimuth;
						maxElTime = thenTime;
					}
				}
			}
		}
	}.bind( this ) );

	// Now, refine the found passes to second (not minute) resolution
	this.passes.forEach( function ( pass, index ) {
		inPass = false;
		thenTime = pass.startTime - 60 * 1000;
		maxEl = -1.0;

		do {
			then.setTime( thenTime );
			position = this.findPositionOfSatellite( pass.id, then );

			if ( ! inPass && position.elevation >= 0.0 ) {
				inPass = true;
				startTime = thenTime;
				startAz = position.azimuth;
			} else if ( inPass && position.elevation < 0.0 ) {
				inPass = false;
				endTime = thenTime;
				endAz = position.azimuth;
			}

			if ( inPass && position.elevation > maxEl ) {
				maxEl = position.elevation;
				maxElAz = position.azimuth;
				maxElTime = thenTime;
			}

			thenTime += 1000; // increment by one second
		} while ( thenTime < pass.endTime + 60 * 1000 );

		// update the record with the precision times
		pass.startTime = startTime;
		pass.startAz = startAz;
		pass.maxEl = maxEl;
		pass.maxElAz = maxElAz;
		pass.maxElTime = maxElTime;
		pass.endTime = endTime;
		pass.endAz = endAz;
		this.passes[ index ] = pass;
	}.bind( this ) );

	// Lastly, sort the passes in chronological order
	this.passes = this.passes.sort( function( a, b ) {
		if ( a.startTime < b.startTime ) {
			return -1;
		}
		if ( a.startTime > b.startTime ) {
			return 1;
		}
		return 0;
	} );

};

PassesStore.prototype.findPositionOfSatellite = function( satelliteID, dateTime ) {

	var azimuth = null;
	var elevation = null;
	var satelliteTLE = _.findWhere( this.tles, { id: satelliteID } );

	if ( satelliteTLE ) {
		var satrec = satellite.twoline2satrec( satelliteTLE.tleLine1, satelliteTLE.tleLine2 );

		var positionAndVelocity = satellite.propagate(
			satrec,
			dateTime.getUTCFullYear(),
			dateTime.getUTCMonth() + 1, // Note, this function requires months in range 1-12.
			dateTime.getUTCDate(),
			dateTime.getUTCHours(),
			dateTime.getUTCMinutes(),
			dateTime.getUTCSeconds()
		);

		var positionEci = positionAndVelocity.position;

		var deg2rad = Math.PI / 180.;
		var rad2deg = 1. / deg2rad;

		var observerGd = {
			longitude: this.location.longitude * deg2rad,
			latitude: this.location.latitude * deg2rad,
			height: 0.001 * this.location.altitude // m -> km. above WGS 84 ellipsoid?
		};

		var gmst = satellite.gstimeFromDate(
			dateTime.getUTCFullYear(),
			dateTime.getUTCMonth() + 1, // Note, this function requires months in range 1-12.
			dateTime.getUTCDate(),
			dateTime.getUTCHours(),
			dateTime.getUTCMinutes(),
			dateTime.getUTCSeconds()
		);

		var positionEcf = satellite.eciToEcf( positionEci, gmst ),
			lookAngles  = satellite.ecfToLookAngles( observerGd, positionEcf );

		azimuth   = Math.floor( 10.0 * lookAngles.azimuth * rad2deg ) / 10.0;
		elevation = Math.floor( 10.0 * lookAngles.elevation * rad2deg ) / 10.0;
		rangeSat  = Math.floor( lookAngles.rangeSat );
	}

	return { azimuth: azimuth, elevation: elevation, rangeSat: rangeSat };
};

PassesStore.prototype.loadFavorites = function() {
	// Default, just the space station and FOX-1A
	this.favoriteIDs = [ 25544, 40967 ];

	if ( "undefined" !== typeof localStorage ) {
		var localStorageFavorites = localStorage.getItem( "favorites" );
		if ( null !== localStorageFavorites ) {
			localStorageFavorites = localStorageFavorites.split( "," );
			this.favoriteIDs = [];
			localStorageFavorites.map( function( favorite ) {
				this.favoriteIDs.push( parseInt( favorite, 10 ) );
			}.bind( this ) );
			console.log( "loaded favorites from localStorage:", this.favoriteIDs );
		}
	}
};

PassesStore.prototype.setFavorites = function( favorites ) {
	this.favoriteIDs = favorites;

	if ( "undefined" !== typeof localStorage ) {
		// the browser will store arrays as a comma delimeted string
		localStorage.setItem( "favorites", favorites );
	}
};

PassesStore.prototype.getFavorites = function() {
	return this.favoriteIDs;
}

// TODO - add event emitter (e.g. when favorites changes)

PassesStore.prototype.init = function() {

	// Load favorites
	this.loadFavorites();

	// Connect our socket
	this.socket = io.connect();

	this.socket.on( 'location', ( function( data ) {
		this.location = data;
		this.findPassesOfFavorites();
	} ).bind( this ) );

	// listener, whenever the server emits 'tle-data', this updates the chat body
	this.socket.on( 'tle-data', ( function( data ) {
		this.tles = data.tle;
		this.lastModified = new Date( data.lastModified );
		this.findPassesOfFavorites();
	} ).bind( this ) );

};

module.exports = PassesStore;
<|endoftext|>


<commit_before>'use strict';

describe('bbc.navigation', function () {
    var navigationMockTop = [
        { title: 'TEST', route: '/test', app: 'unitTest' }
    ];
/*    var navigationMockSub = [
        { title: 'TEST-SUB', route: '/test-sub', app: 'unitTest' }
    ];
    var navigationMockList = [
        { title: 'TEST', route: '/test', app: 'unitTest', level: 0 },
        { title: 'TEST-SUB', route: '/test-sub', app: 'unitTest', level: 1 }
    ];*/

    describe('navigationList type="top"', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        //beforeEach(module('bbc.navigation.directives'));
        beforeEach(module('pascalprecht.translate'));

        var $navigation, $scope, location, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector, $location) {
                compile = $compile;
                $navigation = $injector.get('$bbcNavigation');
                location = $location;
                $navigation.getRoute = function() {
                    return('/test');
                };
                $navigation.getTopList = function(callback) {
                    callback(null, navigationMockTop);
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="top"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be correct initialized', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList).toBeDefined();
            expect(elementScope.navList.length).toBe(1);
        });

        it('should attach menus to the scope', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList.length).toBeGreaterThan(0);
            expect(elementScope.navList[0].title).toBe('TEST');
            expect(elementScope.navList[0].route).toBe('/test');
            expect(elementScope.navList[0].app).toBe('unitTest');
        });

        it('should active the correct location', function () {
            var elementScope = element.isolateScope();

            location.path('/test/path');
            expect(elementScope.isActive('/test')).toBe(true);
            expect(elementScope.isActive('/test/path')).toBe(true);
            expect(elementScope.isActive('/test/foo')).toBe(false);
        });

        it('should not have a class nav-stacked', function() {
            expect(element.hasClass('nav-stacked')).toBe(false);
        });

        it('should not add a class by orientation', function() {
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(false);
        });

        it('should add a class by orientation', function() {
            element = angular.element('<bbc-navigation type="top" orientation="vertical"></bbc-navigation>');
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(true);
        });
    });

/*    describe('navigationList type="sub"', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('bbc.navigation.directives'));
        beforeEach(module('pascalprecht.translate'));

        var $navigation, $scope, location, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector, $location) {
                compile = $compile;
                $navigation = $injector.get('$bbcNavigation');
                location = $location;
                $navigation.getRoute = function() {
                    return('/test-sub');
                };
                $navigation.getSubList = function(callback) {
                    callback(null, navigationMockSub);
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="sub"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be correct initialized', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList).toBeDefined();
            expect(elementScope.navList.length).toBe(1);
        });

        it('should attach menus to the scope', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList.length).toBeGreaterThan(0);
            expect(elementScope.navList[0].title).toBe('TEST-SUB');
            expect(elementScope.navList[0].route).toBe('/test-sub');
            expect(elementScope.navList[0].app).toBe('unitTest');
        });

        it('should active the correct location', function () {
            var elementScope = element.isolateScope();

            location.path('/test-sub/path');
            expect(elementScope.isActive('/test-sub')).toBe(true);
            expect(elementScope.isActive('/test-sub/path')).toBe(true);
            expect(elementScope.isActive('/test-sub/foo')).toBe(false);
        });

        it('should have a class nav-stacked', function() {
            expect(element.hasClass('nav-stacked')).toBe(true);
        });

        it('should remove a class by orientation', function() {
            element = angular.element('<bbc-navigation type="sub" orientation="horizontal"></bbc-navigation>');
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(false);
        });
    });

    describe('navigationList type="list"', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('bbc.navigation.directives'));
        beforeEach(module('pascalprecht.translate'));

        var $navigation, $scope, location, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector, $location) {
                compile = $compile;
                $navigation = $injector.get('$bbcNavigation');
                location = $location;
                $navigation.getRoute = function() {
                    return('/test');
                };
                $navigation.getList = function(callback) {
                    callback(null, navigationMockList);
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="list"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be correct initialized', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList).toBeDefined();
            expect(elementScope.navList.length).toBe(2);
        });

        it('should attach menus to the scope', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList.length).toBeGreaterThan(0);

            expect(elementScope.navList[0].title).toBe('TEST');
            expect(elementScope.navList[0].route).toBe('/test');
            expect(elementScope.navList[0].app).toBe('unitTest');
            expect(elementScope.navList[0].level).toBe(0);

            expect(elementScope.navList[1].title).toBe('TEST-SUB');
            expect(elementScope.navList[1].route).toBe('/test-sub');
            expect(elementScope.navList[1].app).toBe('unitTest');
            expect(elementScope.navList[1].level).toBe(1);
        });

        it('should active the correct location', function () {
            var elementScope = element.isolateScope();

            location.path('/test/path');
            expect(elementScope.isActive('/test')).toBe(true);
            expect(elementScope.isActive('/test/path')).toBe(true);
            expect(elementScope.isActive('/test/foo')).toBe(false);
        });

        it('should have a class nav-stacked', function() {
            expect(element.hasClass('nav-stacked')).toBe(true);
        });

        it('should remove a class by orientation', function() {
            element = angular.element('<bbc-navigation type="list" orientation="horizontal"></bbc-navigation>');
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(false);
        });
    });

    describe('navigationList with error', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('bbc.navigation.directives'));
        beforeEach(module('pascalprecht.translate'));

        var $scope, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector) {
                compile = $compile;
                var $navigation = $injector.get('$bbcNavigation');
                $navigation.getTopList = function(callback) {
                    callback('error');
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="top"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be attach a empty menuTopList', function () {
            var elementScope = element.isolateScope();
            expect(elementScope.navList.length).toBe(0);
        });

        it('should throw an error with missing type', function() {
            element = angular.element('<bbc-navigation></bbc-navigation>');
            expect(function () {
                compile(element)($scope);
            }).toThrow(new Error('Type must be top, sub or list.'));
        });
    });*/
});
<commit_msg>chore(navigation): complete tests for navigation directives<commit_after>'use strict';

describe('bbc.navigation', function () {
    var navigationMockTop = [
        { title: 'TEST', route: '/test', app: 'unitTest' }
    ];
    var navigationMockSub = [
        { title: 'TEST-SUB', route: '/test-sub', app: 'unitTest' }
    ];
    var navigationMockList = [
        { title: 'TEST', route: '/test', app: 'unitTest', level: 0 },
        { title: 'TEST-SUB', route: '/test-sub', app: 'unitTest', level: 1 }
    ];

    describe('navigationList type="top"', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('pascalprecht.translate'));

        var $navigation, $scope, location, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector, $location) {
                compile = $compile;
                $navigation = $injector.get('$bbcNavigation');
                location = $location;
                $navigation.getRoute = function() {
                    return('/test');
                };
                $navigation.getTopList = function(callback) {
                    callback(null, navigationMockTop);
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="top"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be correct initialized', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList).toBeDefined();
            expect(elementScope.navList.length).toBe(1);
        });

        it('should attach menus to the scope', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList.length).toBeGreaterThan(0);
            expect(elementScope.navList[0].title).toBe('TEST');
            expect(elementScope.navList[0].route).toBe('/test');
            expect(elementScope.navList[0].app).toBe('unitTest');
        });

        it('should active the correct location', function () {
            var elementScope = element.isolateScope();

            location.path('/test/path');
            expect(elementScope.isActive('/test')).toBe(true);
            expect(elementScope.isActive('/test/path')).toBe(true);
            expect(elementScope.isActive('/test/foo')).toBe(false);
        });

        it('should not have a class nav-stacked', function() {
            expect(element.hasClass('nav-stacked')).toBe(false);
        });

        it('should not add a class by orientation', function() {
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(false);
        });

        it('should add a class by orientation', function() {
            element = angular.element('<bbc-navigation type="top" orientation="vertical"></bbc-navigation>');
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(true);
        });
    });

    describe('navigationList type="sub"', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('pascalprecht.translate'));

        var $navigation, $scope, location, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector, $location) {
                compile = $compile;
                $navigation = $injector.get('$bbcNavigation');
                location = $location;
                $navigation.getRoute = function() {
                    return('/test-sub');
                };
                $navigation.getSubList = function(callback) {
                    callback(null, navigationMockSub);
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="sub"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be correct initialized', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList).toBeDefined();
            expect(elementScope.navList.length).toBe(1);
        });

        it('should attach menus to the scope', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList.length).toBeGreaterThan(0);
            expect(elementScope.navList[0].title).toBe('TEST-SUB');
            expect(elementScope.navList[0].route).toBe('/test-sub');
            expect(elementScope.navList[0].app).toBe('unitTest');
        });

        it('should active the correct location', function () {
            var elementScope = element.isolateScope();

            location.path('/test-sub/path');
            expect(elementScope.isActive('/test-sub')).toBe(true);
            expect(elementScope.isActive('/test-sub/path')).toBe(true);
            expect(elementScope.isActive('/test-sub/foo')).toBe(false);
        });

        it('should have a class nav-stacked', function() {
            expect(element.hasClass('nav-stacked')).toBe(true);
        });

        it('should remove a class by orientation', function() {
            element = angular.element('<bbc-navigation type="sub" orientation="horizontal"></bbc-navigation>');
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(false);
        });
    });

    describe('navigationList type="list"', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('pascalprecht.translate'));

        var $navigation, $scope, location, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector, $location) {
                compile = $compile;
                $navigation = $injector.get('$bbcNavigation');
                location = $location;
                $navigation.getRoute = function() {
                    return('/test');
                };
                $navigation.getList = function(callback) {
                    callback(null, navigationMockList);
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="list"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be correct initialized', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList).toBeDefined();
            expect(elementScope.navList.length).toBe(2);
        });

        it('should attach menus to the scope', function () {
            var elementScope = element.isolateScope();

            expect(elementScope.navList.length).toBeGreaterThan(0);

            expect(elementScope.navList[0].title).toBe('TEST');
            expect(elementScope.navList[0].route).toBe('/test');
            expect(elementScope.navList[0].app).toBe('unitTest');
            expect(elementScope.navList[0].level).toBe(0);

            expect(elementScope.navList[1].title).toBe('TEST-SUB');
            expect(elementScope.navList[1].route).toBe('/test-sub');
            expect(elementScope.navList[1].app).toBe('unitTest');
            expect(elementScope.navList[1].level).toBe(1);
        });

        it('should active the correct location', function () {
            var elementScope = element.isolateScope();

            location.path('/test/path');
            expect(elementScope.isActive('/test')).toBe(true);
            expect(elementScope.isActive('/test/path')).toBe(true);
            expect(elementScope.isActive('/test/foo')).toBe(false);
        });

        it('should have a class nav-stacked', function() {
            expect(element.hasClass('nav-stacked')).toBe(true);
        });

        it('should remove a class by orientation', function() {
            element = angular.element('<bbc-navigation type="list" orientation="horizontal"></bbc-navigation>');
            compile(element)($scope);
            expect(element.hasClass('nav-stacked')).toBe(false);
        });
    });

    describe('navigationList with error', function() {
        beforeEach(module('bbc.transport'));
        beforeEach(module('bbc.navigation'));
        beforeEach(module('pascalprecht.translate'));

        var $scope, element, compile;

        beforeEach(function (done) {
            inject(function ($compile, $rootScope, $injector) {
                compile = $compile;
                var $navigation = $injector.get('$bbcNavigation');
                $navigation.getTopList = function(callback) {
                    callback('error');
                };

                $scope = $rootScope.$new();
                element = angular.element('<bbc-navigation type="top"></bbc-navigation>');
                compile(element)($scope);
                done();
            });
        });

        it('should be attach a empty menuTopList', function () {
            var elementScope = element.isolateScope();
            expect(elementScope.navList.length).toBe(0);
        });

        it('should throw an error with missing type', function() {
            element = angular.element('<bbc-navigation></bbc-navigation>');
            expect(function () {
                compile(element)($scope);
            }).toThrow(new Error('Type must be top, sub or list.'));
        });
    });
});
<|endoftext|>


<commit_before>tabris.registerWidget("DateTime", {
  _type: "rwt.widgets.DateTime",
  _properties: {year: true, month: true, day: true}
});

var message;

var page = tabris.create("Page", {
  title: "Oceanic Flight 815 Booking",
  topLevel: true
});

var firstNameLabel = tabris.create("Label", {
  layoutData: {left: 10, top: 18, width: 120},
  alignment: "left",
  text: "First Name:"
}).appendTo(page);

var firstNameInput = tabris.create("Text", {
  layoutData: {left: [firstNameLabel, 10], right: 10, baseline: firstNameLabel},
  message: "First Name"
}).appendTo(page);

var lastNameLabel = tabris.create("Label", {
  layoutData: {left: 10, top: [firstNameLabel, 18], width: 120},
  alignment: "left",
  text: "Last Name:"
}).appendTo(page);

var lastNameInput = tabris.create("Text", {
  layoutData: {left: [lastNameLabel, 10], right: 10, baseline: lastNameLabel},
  message: "Last Name"
}).appendTo(page);

var passphraseLabel = tabris.create("Label", {
  layoutData: {left: 10, top: [lastNameLabel, 18], width: 120},
  alignment: "left",
  text: "Passphrase:"
}).appendTo(page);

tabris.create("Text", {
  type: "password",
  layoutData: {left: [passphraseLabel, 10], right: 10, baseline: passphraseLabel},
  message: "Passphrase"
}).appendTo(page);

var countryLabel = tabris.create("Label", {
  layoutData: {left: 10, top: [passphraseLabel, 18], width: 120},
  alignment: "left",
  text: "Country:"
}).appendTo(page);

tabris.create("Combo", {
  layoutData: {left: [countryLabel, 10], right: 10, baseline: countryLabel},
  items: ["Germany", "Canada", "USA", "Bulgaria"],
  selectionIndex: 0
}).appendTo(page);

var classLabel = tabris.create("Label", {
  layoutData: {left: 10, top: [countryLabel, 18], width: 120},
  alignment: "left",
  text: "Class:"
}).appendTo(page);

tabris.create("Combo", {
  layoutData: {left: [classLabel, 10], right: 10, baseline: classLabel},
  items: ["Business", "Economy", "Economy Plus"],
  selectionIndex: 0
}).appendTo(page);

var dateLabel = tabris.create("Label", {
  layoutData: {left: 10, top: [classLabel, 18], width: 120},
  alignment: "left",
  text: "Date:"
}).appendTo(page);

var current = new Date();
var dateField = tabris.create("DateTime", {
  style: ["DATE"],
  layoutData: {left: [dateLabel, 10], right: 10, baseline: dateLabel},
  year: current.getFullYear(),
  month: current.getMonth(),
  day: current.getDate()
}).appendTo(page);

var luggageLabel = tabris.create("Label", {
  layoutData: {left: 10, top: [dateLabel, 18], width: 120},
  alignment: "left",
  text: "Luggage:"
}).appendTo(page);

var luggageWeight = tabris.create("Label", {
  layoutData: {right: 10, baseline: luggageLabel, width: 50},
  alignment: "left",
  text: "0 Kg"
}).appendTo(page);

var luggage = tabris.create("Slider", {
  layoutData: {left: [luggageLabel, 10], right: [luggageWeight, 10], top: [dateLabel, 18]}
}).on("change:selection", function() {
  luggageWeight.set("text", this.get("selection") + " Kg");
}).appendTo(page);

var checkbox = tabris.create("CheckBox", {
  layoutData: {left: [dateLabel, 10], right: 10, top: [luggage, 10]},
  text: "Vegetarian"
}).appendTo(page);

var button = tabris.create("Button", {
  layoutData: {left: 10, right: 10, top: [checkbox, 18]},
  text: "Place Reservation",
  background: "#8b0000",
  foreground: "white"
}).on("selection", function() {
  populateMessage();
}).appendTo(page);

function populateMessage() {
  if (message) {
    message.dispose();
  }
  message = tabris.create("Label", {
    layoutData: {left: 10, right: 10, top: [button, 10]},
    alignment: "left",
    text: "Flight booked for: " + createName() + "\n" + "Departure: " + createDepartureDate()
  }).appendTo(page);
}

function createName() {
  return [firstNameInput.get("text"), lastNameInput.get("text")].join(" ");
}

function createDepartureDate() {
  return [dateField.get("year"), (dateField.get("month") + 1), dateField.get("day")].join("/");
}

page.open();
<commit_msg>Replace deprecated types in input example<commit_after>tabris.registerWidget("DateTime", {
  _type: "rwt.widgets.DateTime",
  _properties: {year: true, month: true, day: true}
});

var message;

var page = tabris.create("Page", {
  title: "Oceanic Flight 815 Booking",
  topLevel: true
});

var firstNameTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: 18, width: 120},
  alignment: "left",
  text: "First Name:"
}).appendTo(page);

var firstNameInput = tabris.create("TextInput", {
  layoutData: {left: [firstNameTextView, 10], right: 10, baseline: firstNameTextView},
  message: "First Name"
}).appendTo(page);

var lastNameTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: [firstNameTextView, 18], width: 120},
  alignment: "left",
  text: "Last Name:"
}).appendTo(page);

var lastNameInput = tabris.create("TextInput", {
  layoutData: {left: [lastNameTextView, 10], right: 10, baseline: lastNameTextView},
  message: "Last Name"
}).appendTo(page);

var passphraseTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: [lastNameTextView, 18], width: 120},
  alignment: "left",
  text: "Passphrase:"
}).appendTo(page);

tabris.create("TextInput", {
  type: "password",
  layoutData: {left: [passphraseTextView, 10], right: 10, baseline: passphraseTextView},
  message: "Passphrase"
}).appendTo(page);

var countryTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: [passphraseTextView, 18], width: 120},
  alignment: "left",
  text: "Country:"
}).appendTo(page);

tabris.create("Combo", {
  layoutData: {left: [countryTextView, 10], right: 10, baseline: countryTextView},
  items: ["Germany", "Canada", "USA", "Bulgaria"],
  selectionIndex: 0
}).appendTo(page);

var classTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: [countryTextView, 18], width: 120},
  alignment: "left",
  text: "Class:"
}).appendTo(page);

tabris.create("Combo", {
  layoutData: {left: [classTextView, 10], right: 10, baseline: classTextView},
  items: ["Business", "Economy", "Economy Plus"],
  selectionIndex: 0
}).appendTo(page);

var dateTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: [classTextView, 18], width: 120},
  alignment: "left",
  text: "Date:"
}).appendTo(page);

var current = new Date();
var dateField = tabris.create("DateTime", {
  style: ["DATE"],
  layoutData: {left: [dateTextView, 10], right: 10, baseline: dateTextView},
  year: current.getFullYear(),
  month: current.getMonth(),
  day: current.getDate()
}).appendTo(page);

var luggageTextView = tabris.create("TextView", {
  layoutData: {left: 10, top: [dateTextView, 18], width: 120},
  alignment: "left",
  text: "Luggage:"
}).appendTo(page);

var luggageWeight = tabris.create("TextView", {
  layoutData: {right: 10, baseline: luggageTextView, width: 50},
  alignment: "left",
  text: "0 Kg"
}).appendTo(page);

var luggage = tabris.create("Slider", {
  layoutData: {left: [luggageTextView, 10], right: [luggageWeight, 10], top: [dateTextView, 18]}
}).on("change:selection", function() {
  luggageWeight.set("text", this.get("selection") + " Kg");
}).appendTo(page);

var checkbox = tabris.create("CheckBox", {
  layoutData: {left: [dateTextView, 10], right: 10, top: [luggage, 10]},
  text: "Vegetarian"
}).appendTo(page);

var button = tabris.create("Button", {
  layoutData: {left: 10, right: 10, top: [checkbox, 18]},
  text: "Place Reservation",
  background: "#8b0000",
  foreground: "white"
}).on("selection", function() {
  populateMessage();
}).appendTo(page);

function populateMessage() {
  if (message) {
    message.dispose();
  }
  message = tabris.create("TextView", {
    layoutData: {left: 10, right: 10, top: [button, 10]},
    alignment: "left",
    text: "Flight booked for: " + createName() + "\n" + "Departure: " + createDepartureDate()
  }).appendTo(page);
}

function createName() {
  return [firstNameInput.get("text"), lastNameInput.get("text")].join(" ");
}

function createDepartureDate() {
  return [dateField.get("year"), (dateField.get("month") + 1), dateField.get("day")].join("/");
}

page.open();
<|endoftext|>


<commit_before>/*global define */
/*global $uibModal */
/*golbal $uibModalInstance */

(function () {
    "use strict";
    var isFirstViewing = true;

    console.log('MasherCtrl setup');
    define(['angular', 'lib/AgoNewWindowConfig', 'controllers/WebSiteDescriptionCtrl', 'lib/utils'], function (angular,  AgoNewWindowConfig, WebSiteDescriptionCtrl, utils) {
        console.log('MasherCtrl define');
        var selfMethods = {},
            descriptions = {
            'leaflet': 'A selection of coffee shops that were retrieved from a query to a geographic information lookup service, using open source maps and data, displayed on a Leaflet Map.  Alternatively, this could be the web site for a single organization where one of the web site pages contains a Leaflet map of its multiple locations.',
            'google' : 'A selection of restaurants that were retrieved from a query to a geographic information lookup service, such as Google, displayed on a Google Map using an Open Street Map base layer.  Alternatively, this could be the web site for a single organization where one of the web site pages contains a Google map of its multiple locations.',
            'arcgis' : 'A typical Web Map from the ArcGIS Online user contributed database.  The intially displayed map is chosen to provide a working environment for this demo.'
        };

        function MasherCtrl($scope, $location, $window, $route, $templateCache, $uibModal) {  //$route, $routeParams, $window) {
            console.debug('MasherCtrl - initialize collapsed bool');

            var startupView = AgoNewWindowConfig.getStartupView();
            $scope.ExpandSum = startupView.summary === true ? "Collapse" : "Expand";
            $scope.MasterSiteVis = startupView.website ? "inline" : 'none';
            $scope.isCollapsed = !startupView.summary;
            $scope.showPopupBlockerDialog = false;
            $scope.data = {
                'blockedUrl': 'place holder',
                'completeUrl': 'completeslashdoturl',
                'nextWindowName': 'InitialWindowName',
                'popupDimensions': 'popdimensions',
                selfdict : {
                    mapType : "",
                    imgSrc : "",
                    description : ""
                }
            };

            $scope.catchClick = function () {
                // alert("Caught in MasherCtrl");
                $scope.showPopupBlockerDialog = true;
                $('#PopupBlockerDialog').modal311('show');
            };

            $scope.ok = function () {
                $scope.showPopupBlockerDialog = false;
                window.open($scope.data.completeUrl, $scope.data.nextWindowName,
                    $scope.data.popupDimensions);
            };

            $scope.cancel = function () {
                $scope.showPopupBlockerDialog = false;
            };
            $scope.expBtnHeight = 1.4;  //utils.getButtonHeight(1.2); //'ExpandSumImgId');

            $scope.currentTab = null;
            console.log("init with isCollapsed = " + $scope.isCollapsed);
            $scope.showDescriptionDialog = false;

            $scope.$on('$viewContentLoaded', function () {
                if (isFirstViewing === false) {
                    if (startupView.summary === true) {
                        $scope.summmaryCollapser();
                    }
                } else {
                    isFirstViewing = false;
                }
            });

            $scope.summmaryCollapser = function () {
                // $scope.MasterSiteVis = $scope.ExpandSum === "Expand" ? "inline" : "none";
                $scope.ExpandSum = $scope.ExpandSum === "Expand" ? "Collapse" : "Expand";

                console.log("MasherCtrl isCollapsed before broadcast " + $scope.isCollapsed);
                $scope.$broadcast('CollapseSummaryEvent', {'mastersitevis' : $scope.MasterSiteVis});
                $scope.isCollapsed = !$scope.isCollapsed;
                console.log("MasherCtrl isCollapsed after broadcast " + $scope.isCollapsed);
            };
            selfMethods.summmaryCollapser = $scope.summmaryCollapser;

            console.debug(selfMethods);

            $scope.windowResized = function () {
                $scope.$broadcast('windowResized');
            };
            selfMethods.windowResized = $scope.windowResized;

            $scope.showMeTheMapClicked = function () {
                // var currentPageTemplate;
                console.log("currentTab - url reset to " + $scope.currentTab.url);
                console.debug($location);

                $location.path($scope.currentTab.url, true);
                $location.replace();
                $route.reload();

                // $scope.$apply(function() {
                //     $location.path($scope.currentTab.url, true);
                //     $location.replace();
                // });
                // $window.location = $scope.currentTab.url;
                // $scope.$apply();
                // $window.location.href = $scope.currentTab.url;
                // $window.location.reload();
                // $scope.summmaryCollapser();

                // currentPageTemplate = $route.current.loadedTemplateUrl;
                // console.log("currentPageTemplate : " + currentPageTemplate);
                // $templateCache.remove(currentPageTemplate);
                // $route.reload();
                // $location.path($scope.currentTab.url, true).replace();
            };

            $scope.describeTheWebsiteClicked = function () {
                console.log("Describe the website for currentTab " + $scope.currentTab.title);
//                var hostElement = $document.find('mashbox').eq(0);
                // $scope.$broadcast('ShowWebSiteDescriptionModalEvent');

                $scope.data.selfdict.mapType = $scope.currentTab.maptype; //.slice(1);
                $scope.data.selfdict.imgSrc = $scope.currentTab.imgSrc;
                $scope.data.selfdict.description = descriptions[$scope.currentTab.maptype];

                var tmplt = ' \

 \

 \
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> \

This sample Web Site powered by   {{data.mapType}} is showing us :
 \

 \

 \

 \
                            {{data.description}} \

 \

 \
                            Clicking on a location icon pops up available, relevant information at that address. \

 \

 \

 \
                        <button type="button" class="btn btn-primary" ng-click="accept()">Accept</button> \
                        <button type="button" class="btn btn-primary" ng-click="cancel()">Cancel</button> \

 \

 \
                ',

                    modalInstance = $uibModal.open({
                        template : tmplt,
                        controller : 'WebSiteDescriptionCtrl',
                        size : 'sm',
                        backdrop : 'false',
//                        appendTo : hostElement,
                        resolve : {
                            data: function () {
                                return $scope.data.selfdict;
                            }
                        }
                    });

                modalInstance.result.then(function (selectedItem) {
                    $scope.selected = selectedItem;
                }, function () {
                    console.log('Modal dismissed at: ' + new Date());
                });

            };

            $scope.$on('WebSiteDescriptionEvent', function () {
                console.log("WebSiteDescriptionEvent received, currentTab - url reset to " + $scope.currentTab.url);
                console.debug($location);
                var showElem = document.getElementById('showMeTheMap'),
                    showElemA = angular.element(showElem),
                    showElem0 = showElemA[0];

                showElem0.click();
                // $scope.catchClick();  // for testing dialog without an actual popup block event

            });

            function handlePopupBlocked(completeUrl, nextWindowName, dimensions) {
                console.log('in function handlePopupBlocked');
                alert('in function handlePopupBlocked');
                $scope.showPopupBlockerDialog = true;
                $scope.data.completeUrl = completeUrl;
                $scope.data.nextWindowName = nextWindowName;
                $scope.data.popupDimensions = dimensions;
                $('#PopupBlockerDialog').modal311('show');
            }

            $scope.onNewMapPosition = function (pos) {
                var pos2prt = String.format('onNewMapPosition handler - framework {0}, referrer {1}, at x {2}, y {3}, zoom {4}',
                    pos.maphost, pos.referrerId, pos.lon, pos.lat, pos.zoom),

                    baseUrl = AgoNewWindowConfig.getbaseurl(),
                    completeUrl = baseUrl + pos.maphost + pos.search,
                    nextWindowName = AgoNewWindowConfig.getNextWindowName(),
                    wnd = null;
                console.log(pos2prt);
                console.log("search url :");
                console.log(pos.search);
                console.log('completeUrl');
                console.debug(completeUrl);
                console.log("userId = " + AgoNewWindowConfig.getUserId() + " referrerId = " + AgoNewWindowConfig.getReferrerId() + " pos.referrerId = " + pos.referrerId);
                console.log("is Initial User ? " + AgoNewWindowConfig.getInitialUserStatus());
                console.log("Open new window with name " + nextWindowName);
                $scope.data.blockedUrl = completeUrl;

                // if (pos.referrerId !== AgoNewWindowConfig.getUserId()) {
                if (pos.referrerName !== AgoNewWindowConfig.getUserName()) {
                    completeUrl += "&userName=" + AgoNewWindowConfig.getUserName();
                    wnd = window.open(completeUrl, nextWindowName,
                        AgoNewWindowConfig.getSmallFormDimensions());
                    if (!wnd || wnd === 'undefined') {
                        handlePopupBlocked(completeUrl, nextWindowName,
                            AgoNewWindowConfig.getSmallFormDimensions());
                    }
                    console.log("after call to window.open with initial user status true");
                } else {
                    console.log("userId and referrerId match : do not open window");
                }

            };
            selfMethods.onNewMapPosition = $scope.onNewMapPosition;
        }

        // MasherCtrl.prototype.windowResized = function () {
        //     selfMethods.windowResized();
        // }

        function init(App) {
            console.log('MasherCtrl init');
            App.controller('MasherCtrl', ['$scope', '$location', '$window', '$route', '$templateCache', '$uibModal', MasherCtrl]);

            //calling tellAngular on resize event
            window.onresize = selfMethods.windowResized;  // MasherCtrl.prototype.windowResized;

            var $inj = angular.injector(['app']),
                evtSvc = $inj.get('StompEventHandlerService');

            evtSvc.addEvent('client-NewMapPosition', this.onNewMapPosition);

            App.directive('modalshowpopupblockdlg', function () {
                return {
                    templateUrl : '/Templates/ModalDialogPopupBlocked',

                    restrict: 'E',
                    transclude: true,
                    replace: true,
                    scope: {
                        modalVisible: "="
                    },
                    link: function postLink(scope, element, attrs) {
                        // scope.title = attrs.title;
                        //Hide or show the modal
                        scope.showModal = function (visible, elem) {
                            if (!elem) {
                                elem = element;
                            }
                            if (visible) {
                                $(elem).modal311("show");
                            } else {
                                $(elem).modal311("hide");
                            }
                        };

                        if (!attrs.modalVisible) {
                            //The attribute isn't defined, show the modal by default
                            scope.showModal(true);

                        } else {
                            scope.$watch(attrs.visible, function (value) {
                                if (value === true) {
                                    $(element).modal311('show');
                                } else {
                                    $(element).modal311('hide');
                                }
                            });
                            scope.$watch('scope.$parent.showPopupBlockerDialog', function (newValue, oldValue) {
                                console.log("scope.$watch newValue : " + newValue);
                                console.log("scope.$watch 'scope.$parent.showPopupBlockerDialog' : " + scope.$parent.showPopupBlockerDialog);
                                // scope.showModal(newValue);
                                //attrs.modalVisible = false;
                            });

                            //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                            $(element).on('hidden.bs.modal', function () {
                                scope.$apply(function () {
                                    scope.$parent[attrs.visible] = false;
                                });
                            });
                            $(element).on('hidden.bs.modal', function () {
                                scope.$apply(function () {
                                    scope.$parent[attrs.visible] = true;
                                });
                            });
                            $(element).on('loaded.bs.modal', function () {
                                alert('Modal is successfully loaded!');
                            });
                        }
                    }
                };
            });

            return MasherCtrl;
        }
        function startMapSystem() {
            var startupView = AgoNewWindowConfig.getStartupView();
            console.log("startMapSystem");
            isFirstViewing = false;

            if (startupView.summary === true) {
                selfMethods.summmaryCollapser();
            }
        }

        function onNewMapPosition(pos) {
            console.log("onNewMapPosition");

            selfMethods.onNewMapPosition(pos);
        }

        return { start: init, startMapSystem: startMapSystem, onNewMapPosition : onNewMapPosition };

    });
}());
// }()).call(this);
<commit_msg>hooks showMeTheMap to accept click<commit_after>/*global define */
/*global $uibModal */
/*golbal $uibModalInstance */

(function () {
    "use strict";
    var isFirstViewing = true;

    console.log('MasherCtrl setup');
    define(['angular', 'lib/AgoNewWindowConfig', 'controllers/WebSiteDescriptionCtrl', 'lib/utils'], function (angular,  AgoNewWindowConfig, WebSiteDescriptionCtrl, utils) {
        console.log('MasherCtrl define');
        var selfMethods = {},
            descriptions = {
            'leaflet': 'A selection of coffee shops that were retrieved from a query to a geographic information lookup service, using open source maps and data, displayed on a Leaflet Map.  Alternatively, this could be the web site for a single organization where one of the web site pages contains a Leaflet map of its multiple locations.',
            'google' : 'A selection of restaurants that were retrieved from a query to a geographic information lookup service, such as Google, displayed on a Google Map using an Open Street Map base layer.  Alternatively, this could be the web site for a single organization where one of the web site pages contains a Google map of its multiple locations.',
            'arcgis' : 'A typical Web Map from the ArcGIS Online user contributed database.  The intially displayed map is chosen to provide a working environment for this demo.'
        };

        function MasherCtrl($scope, $location, $window, $route, $templateCache, $uibModal) {  //$route, $routeParams, $window) {
            console.debug('MasherCtrl - initialize collapsed bool');

            var startupView = AgoNewWindowConfig.getStartupView();
            $scope.ExpandSum = startupView.summary === true ? "Collapse" : "Expand";
            $scope.MasterSiteVis = startupView.website ? "inline" : 'none';
            $scope.isCollapsed = !startupView.summary;
            $scope.showPopupBlockerDialog = false;
            $scope.data = {
                'blockedUrl': 'place holder',
                'completeUrl': 'completeslashdoturl',
                'nextWindowName': 'InitialWindowName',
                'popupDimensions': 'popdimensions',
                selfdict : {
                    mapType : "",
                    imgSrc : "",
                    description : ""
                }
            };

            $scope.catchClick = function () {
                // alert("Caught in MasherCtrl");
                $scope.showPopupBlockerDialog = true;
                $('#PopupBlockerDialog').modal311('show');
            };

            $scope.ok = function () {
                $scope.showPopupBlockerDialog = false;
                window.open($scope.data.completeUrl, $scope.data.nextWindowName,
                    $scope.data.popupDimensions);
            };

            $scope.cancel = function () {
                $scope.showPopupBlockerDialog = false;
            };
            $scope.expBtnHeight = 1.4;  //utils.getButtonHeight(1.2); //'ExpandSumImgId');

            $scope.currentTab = null;
            console.log("init with isCollapsed = " + $scope.isCollapsed);
            $scope.showDescriptionDialog = false;

            $scope.$on('$viewContentLoaded', function () {
                if (isFirstViewing === false) {
                    if (startupView.summary === true) {
                        $scope.summmaryCollapser();
                    }
                } else {
                    isFirstViewing = false;
                }
            });

            $scope.summmaryCollapser = function () {
                // $scope.MasterSiteVis = $scope.ExpandSum === "Expand" ? "inline" : "none";
                $scope.ExpandSum = $scope.ExpandSum === "Expand" ? "Collapse" : "Expand";

                console.log("MasherCtrl isCollapsed before broadcast " + $scope.isCollapsed);
                $scope.$broadcast('CollapseSummaryEvent', {'mastersitevis' : $scope.MasterSiteVis});
                $scope.isCollapsed = !$scope.isCollapsed;
                console.log("MasherCtrl isCollapsed after broadcast " + $scope.isCollapsed);
            };
            selfMethods.summmaryCollapser = $scope.summmaryCollapser;

            console.debug(selfMethods);

            $scope.windowResized = function () {
                $scope.$broadcast('windowResized');
            };
            selfMethods.windowResized = $scope.windowResized;

            $scope.showMeTheMapClicked = function () {
                // var currentPageTemplate;
                console.log("currentTab - url reset to " + $scope.currentTab.url);
                console.debug($location);

                $location.path($scope.currentTab.url, true);
                $location.replace();
                $route.reload();

                // $scope.$apply(function() {
                //     $location.path($scope.currentTab.url, true);
                //     $location.replace();
                // });
                // $window.location = $scope.currentTab.url;
                // $scope.$apply();
                // $window.location.href = $scope.currentTab.url;
                // $window.location.reload();
                // $scope.summmaryCollapser();

                // currentPageTemplate = $route.current.loadedTemplateUrl;
                // console.log("currentPageTemplate : " + currentPageTemplate);
                // $templateCache.remove(currentPageTemplate);
                // $route.reload();
                // $location.path($scope.currentTab.url, true).replace();
            };

            $scope.describeTheWebsiteClicked = function () {
                console.log("Describe the website for currentTab " + $scope.currentTab.title);
//                var hostElement = $document.find('mashbox').eq(0);
                // $scope.$broadcast('ShowWebSiteDescriptionModalEvent');

                $scope.data.selfdict.mapType = $scope.currentTab.maptype; //.slice(1);
                $scope.data.selfdict.imgSrc = $scope.currentTab.imgSrc;
                $scope.data.selfdict.description = descriptions[$scope.currentTab.maptype];

                var tmplt = ' \

 \

 \
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> \

This sample Web Site powered by   {{data.mapType}} is showing us :
 \

 \

 \

 \
                            {{data.description}} \

 \

 \
                            Clicking on a location icon pops up available, relevant information at that address. \

 \

 \

 \
                        <button type="button" class="btn btn-primary" ng-click="accept()">Accept</button> \
                        <button type="button" class="btn btn-primary" ng-click="cancel()">Cancel</button> \

 \

 \
                ',

                    modalInstance = $uibModal.open({
                        template : tmplt,
                        controller : 'WebSiteDescriptionCtrl',
                        size : 'sm',
                        backdrop : 'false',
//                        appendTo : hostElement,
                        resolve : {
                            data: function () {
                                return $scope.data.selfdict;
                            }
                        }
                    });

                modalInstance.result.then(function (selectedItem) {
                    $scope.selected = selectedItem;
                    $scope.showMeTheMapClicked();
                }, function () {
                    console.log('Modal dismissed at: ' + new Date());
                });

            };

        // function showTheMap () {
        //     console.log("WebSiteDescriptionEvent received, currentTab - url reset to " + $scope.currentTab.url);
        //     console.debug($location);
        //     var showElem = document.getElementById('showMeTheMap'),
        //         showElemA = angular.element(showElem),
        //         showElem0 = showElemA[0];
        //
        //     showElem0.click();
        //     // $scope.catchClick();  // for testing dialog without an actual popup block event
        // }
            // $scope.$on('WebSiteDescriptionEvent', function () {
            //     console.log("WebSiteDescriptionEvent received, currentTab - url reset to " + $scope.currentTab.url);
            //     console.debug($location);
            //     var showElem = document.getElementById('showMeTheMap'),
            //         showElemA = angular.element(showElem),
            //         showElem0 = showElemA[0];
            //
            //     showElem0.click();
            //     // $scope.catchClick();  // for testing dialog without an actual popup block event
            //
            // });

            function handlePopupBlocked(completeUrl, nextWindowName, dimensions) {
                console.log('in function handlePopupBlocked');
                alert('in function handlePopupBlocked');
                $scope.showPopupBlockerDialog = true;
                $scope.data.completeUrl = completeUrl;
                $scope.data.nextWindowName = nextWindowName;
                $scope.data.popupDimensions = dimensions;
                $('#PopupBlockerDialog').modal311('show');
            }

            $scope.onNewMapPosition = function (pos) {
                var pos2prt = String.format('onNewMapPosition handler - framework {0}, referrer {1}, at x {2}, y {3}, zoom {4}',
                    pos.maphost, pos.referrerId, pos.lon, pos.lat, pos.zoom),

                    baseUrl = AgoNewWindowConfig.getbaseurl(),
                    completeUrl = baseUrl + pos.maphost + pos.search,
                    nextWindowName = AgoNewWindowConfig.getNextWindowName(),
                    wnd = null;
                console.log(pos2prt);
                console.log("search url :");
                console.log(pos.search);
                console.log('completeUrl');
                console.debug(completeUrl);
                console.log("userId = " + AgoNewWindowConfig.getUserId() + " referrerId = " + AgoNewWindowConfig.getReferrerId() + " pos.referrerId = " + pos.referrerId);
                console.log("is Initial User ? " + AgoNewWindowConfig.getInitialUserStatus());
                console.log("Open new window with name " + nextWindowName);
                $scope.data.blockedUrl = completeUrl;

                // if (pos.referrerId !== AgoNewWindowConfig.getUserId()) {
                if (pos.referrerName !== AgoNewWindowConfig.getUserName()) {
                    completeUrl += "&userName=" + AgoNewWindowConfig.getUserName();
                    wnd = window.open(completeUrl, nextWindowName,
                        AgoNewWindowConfig.getSmallFormDimensions());
                    if (!wnd || wnd === 'undefined') {
                        handlePopupBlocked(completeUrl, nextWindowName,
                            AgoNewWindowConfig.getSmallFormDimensions());
                    }
                    console.log("after call to window.open with initial user status true");
                } else {
                    console.log("userId and referrerId match : do not open window");
                }

            };
            selfMethods.onNewMapPosition = $scope.onNewMapPosition;
        }

        // MasherCtrl.prototype.windowResized = function () {
        //     selfMethods.windowResized();
        // }

        function init(App) {
            console.log('MasherCtrl init');
            App.controller('MasherCtrl', ['$scope', '$location', '$window', '$route', '$templateCache', '$uibModal', MasherCtrl]);

            //calling tellAngular on resize event
            window.onresize = selfMethods.windowResized;  // MasherCtrl.prototype.windowResized;

            var $inj = angular.injector(['app']),
                evtSvc = $inj.get('StompEventHandlerService');

            evtSvc.addEvent('client-NewMapPosition', this.onNewMapPosition);

            App.directive('modalshowpopupblockdlg', function () {
                return {
                    templateUrl : '/Templates/ModalDialogPopupBlocked',

                    restrict: 'E',
                    transclude: true,
                    replace: true,
                    scope: {
                        modalVisible: "="
                    },
                    link: function postLink(scope, element, attrs) {
                        // scope.title = attrs.title;
                        //Hide or show the modal
                        scope.showModal = function (visible, elem) {
                            if (!elem) {
                                elem = element;
                            }
                            if (visible) {
                                $(elem).modal311("show");
                            } else {
                                $(elem).modal311("hide");
                            }
                        };

                        if (!attrs.modalVisible) {
                            //The attribute isn't defined, show the modal by default
                            scope.showModal(true);

                        } else {
                            scope.$watch(attrs.visible, function (value) {
                                if (value === true) {
                                    $(element).modal311('show');
                                } else {
                                    $(element).modal311('hide');
                                }
                            });
                            scope.$watch('scope.$parent.showPopupBlockerDialog', function (newValue, oldValue) {
                                console.log("scope.$watch newValue : " + newValue);
                                console.log("scope.$watch 'scope.$parent.showPopupBlockerDialog' : " + scope.$parent.showPopupBlockerDialog);
                                // scope.showModal(newValue);
                                //attrs.modalVisible = false;
                            });

                            //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                            $(element).on('hidden.bs.modal', function () {
                                scope.$apply(function () {
                                    scope.$parent[attrs.visible] = false;
                                });
                            });
                            $(element).on('hidden.bs.modal', function () {
                                scope.$apply(function () {
                                    scope.$parent[attrs.visible] = true;
                                });
                            });
                            $(element).on('loaded.bs.modal', function () {
                                alert('Modal is successfully loaded!');
                            });
                        }
                    }
                };
            });

            return MasherCtrl;
        }
        function startMapSystem() {
            var startupView = AgoNewWindowConfig.getStartupView();
            console.log("startMapSystem");
            isFirstViewing = false;

            if (startupView.summary === true) {
                selfMethods.summmaryCollapser();
            }
        }

        function onNewMapPosition(pos) {
            console.log("onNewMapPosition");

            selfMethods.onNewMapPosition(pos);
        }

        return { start: init, startMapSystem: startMapSystem, onNewMapPosition : onNewMapPosition };

    });
}());
// }()).call(this);
<|endoftext|>


<commit_before>(function() {

var editor;

Template.post_page.events = {
  'click input[type=submit]': function(e){
    e.preventDefault();
    var content = editor.exportFile();
    var post_id = Session.get('selected_post_id');
    var $comment = $('#comment');
    var new_comment_id=Meteor.call('comment', post_id, null, content, function(error, result){
      $("#"+result).removeClass("queued"); // does not work because new element is not yet in the DOM (probably)
    });
    $comment.val('');
  }
};

Template.post_page.show_comment_form = function(){
  return Meteor.user() !== null;
};

Template.post_page.post = function(){
  var post = Posts.findOne(Session.get('selected_post_id'));
  return post;
};

Template.post_page.body_formatted = function(){
  var converter = new Markdown.Converter();
  var html_body=converter.makeHtml(this.body);
  return html_body.autoLink();
}

Template.post_page.rendered = function(){
  t("post_page");
  editor= new EpicEditor(EpicEditorOptions).load();
}

window.newCommentTimestamp=new Date();

})();<commit_msg>do not load epiceditor if user is not logged in<commit_after>(function() {

var editor;

Template.post_page.events = {
  'click input[type=submit]': function(e){
    e.preventDefault();
    var content = editor.exportFile();
    var post_id = Session.get('selected_post_id');
    var $comment = $('#comment');
    var new_comment_id=Meteor.call('comment', post_id, null, content, function(error, result){
      $("#"+result).removeClass("queued"); // does not work because new element is not yet in the DOM (probably)
    });
    $comment.val('');
  }
};

Template.post_page.show_comment_form = function(){
  return Meteor.user() !== null;
};

Template.post_page.post = function(){
  var post = Posts.findOne(Session.get('selected_post_id'));
  return post;
};

Template.post_page.body_formatted = function(){
  var converter = new Markdown.Converter();
  var html_body=converter.makeHtml(this.body);
  return html_body.autoLink();
}

Template.post_page.rendered = function(){
  t("post_page");
  if(Meteor.user()){
    editor= new EpicEditor(EpicEditorOptions).load();
  }
}

window.newCommentTimestamp=new Date();

})();<|endoftext|>


<commit_before>import React, {Component} from 'react';
import Well from 'react-bootstrap/lib/Well';
import Alert from 'react-bootstrap/lib/Alert';
import { Draft, EditorState, ContentState, RichUtils, convertFromRaw, convertToRaw } from 'draft-js';

// eslint-disable-next-line import/no-unresolved
import Editor from 'draft-js-plugins-editor';
// eslint-disable-next-line import/no-unresolved
import createImagePlugin from 'draft-js-image-plugin';
import 'draft-js-image-plugin/lib/plugin.css'; // eslint-disable-line import/no-unresolved

import CodeUtils from 'draft-js-code';
import { stateToHTML } from 'draft-js-export-html';
import Helmet from 'react-helmet';
import cookie from 'react-cookie';
import superagent from 'superagent';
import { connect } from 'react-redux';
import { Link } from 'react-router';
require('./Community.scss');

var PrismDecorator = require('draft-js-prism');
const imagePlugin = createImagePlugin();

import { getBlogEntries } from '../../redux/actions/getBlogEntriesActions';

@connect((store) => {
  return {
    activateNewUserState: store.activateNewUser.userStatus,
    getBlogEntriesState: store.getBlogEntries.articleList,
  };
})

export default class RichEditorExample extends Component {
  state = {
    formStatus: 0,
    formMsg: ''
  }

  constructor(props) {
    super(props);
    var decorator = new PrismDecorator();
    this.state = {editorState: EditorState.createEmpty(decorator)};

    this.focus = () => this.refs.editor.focus();
    this.onChange = (editorState) => this.setState({editorState});

    this.handleKeyCommand = (command) => this._handleKeyCommand(command);
    this.onTab = (e) => this._onTab(e);
    this.handleReturn = (e) => this._handleReturn(e);
    //this.keyBindingFn = (e) => this._keyBindingFn(e);

    this.toggleBlockType = (type) => this._toggleBlockType(type);
    this.toggleInlineStyle = (style) => this._toggleInlineStyle(style);
  }

  componentDidMount() {
    superagent
    .post('/community')
    .send({ loadStatus: 1 })
    .set('Accept', 'application/json')
    .end((error, res) => {
      if (res.body.status === 1) {
        this.props.dispatch(getBlogEntries(res.body.blogArticles));
      }
    });
  }

  _handleKeyCommand(command) {
    const {editorState} = this.state;
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      this.onChange(newState);
      return true;
    }
    return false;
}

  /*_keyBindingFn(e) {
      var editorState = this.state.editorState;
      var command;

      if (CodeUtils.hasSelectionInBlock(editorState)) {
          command = CodeUtils.getKeyBinding(e);
      }
      if (command) {
          return command;
      }

      return Draft.getDefaultKeyBinding(e);
  }*/

  _handleReturn(e) {
      var editorState = this.state.editorState;

      if (!CodeUtils.hasSelectionInBlock(editorState)) {
          return;
      }
      this.onChange(
          CodeUtils.handleReturn(e, editorState)
      );
      return true;
  }

  _onTab(e) {
    /*const maxDepth = 4;
    this.onChange(RichUtils.onTab(e, this.state.editorState, maxDepth));*/
    var editorState = this.state.editorState;
    if (!CodeUtils.hasSelectionInBlock(editorState)) {
        return;
    }
    this.onChange(
        CodeUtils.handleTab(e, editorState)
    );
  }

  _toggleBlockType(blockType) {
    this.onChange(
      RichUtils.toggleBlockType(
        this.state.editorState,
        blockType
      )
    );
  }

  _toggleInlineStyle(inlineStyle) {
    this.onChange(
      RichUtils.toggleInlineStyle(
        this.state.editorState,
        inlineStyle
      )
    );
  }

  saveDataToDatabase() {
    const titelData = this.refs.titel.value;
    const markupData = stateToHTML(this.state.editorState.getCurrentContent());
    const userUuid = cookie.load('ck_uuid');
    const userAvatar = cookie.load('ck_avatar');
    const userNickname = cookie.load('ck_nickname');
    /* plus category and technologies */

    if(titelData.length > 2 && titelData.length < 60){
      if (markupData.length > 40) {

        superagent
        .post('/checkUniqueTitle')
        .send({ tryTitle: titelData })
        .set('Accept', 'application/json')
        .end((error, res) => {
          if(res.body.status === 1) {

              this.refs.titel.value = '';
              superagent
              .post('/community')
              .send({ loadStatus: 0, markupData: markupData, titelData: titelData, userUuid: userUuid, userAvatar: userAvatar, userNickname: userNickname })
              .set('Accept', 'application/json')
              .end((error, res) => {
                if (res.body.status === 1) {
                  this.props.dispatch(getBlogEntries(res.body.blogArticles));

                  /* Clear editor state */
                  const editorState = EditorState.push(this.state.editorState, ContentState.createFromText(''));
                  this.setState({ editorState });

                  this.setState({formStatus: 2});
                  this.setState({formMsg: 'Du hast erfolgreich einen Beitrag erstellt!'});
                }
              });

          } else{
            this.setState({formStatus: 1});
            this.setState({formMsg: 'Fehler: Es exisitiert bereits ein Beitrag mit dem genau gleichen Titel! Bitte verwende einen anderen Beitragstitel.'});
          }
        });

      } else{
        this.setState({formStatus: 1});
        this.setState({formMsg: 'Fehler: Ein Beitrag benötigt mindestens 40 Zeichen!'});
      }
    } else{
      this.setState({formStatus: 1});
      this.setState({formMsg: 'Fehler: Der Titel des Beitrages benötigt mindestens 3 Zeichen und darf 60 Zeichen nicht überschreiten!'});
    }
  }

  render() {
    const {formStatus, formMsg, editorState} = this.state;
    const { activateNewUserState, getBlogEntriesState } = this.props;
    const {name} = this.props.params;
    console.log(name);
    //const styles = require('./Community.scss');

    let className = 'RichEditor-editor';
    var contentState = editorState.getCurrentContent();
    if (!contentState.hasText()) {
      if (contentState.getBlockMap().first().getType() !== 'unstyled') {
        className += ' RichEditor-hidePlaceholder';
      }
    }

    let blogContentDef = '';

    getBlogEntriesState.articles.forEach(function(entry){
      blogContentDef += '

' + entry.titel + '

' + entry.markup + '
Author: ' + entry.userNickname + ' | ' + entry.timeFormatted + '
';
    });

    return (

Community

        <Helmet title="Community"/>
        {(activateNewUserState.activatedUser === true && activateNewUserState.loggedInUser === true) || (cookie.load('ck_userLoggedIn') === true && cookie.load('ck_activation') === true) ?

        {formStatus === 2 ?
          <Alert bsStyle="success">

</Alert>
        : null
        }
        {formStatus === 1 ?
          <Alert bsStyle="danger">

</Alert>
        : null
        }

Beitrag oder Projekt

          <form className="community-title-form form-inline">

              <input type="text" ref="titel" name="titel" id="titel" placeholder="Titel" className="titleStyle form-control"/>

          </form>

          <BlockStyleControls
            editorState={editorState}
            onToggle={this.toggleBlockType}
            />
          <InlineStyleControls
            editorState={editorState}
            onToggle={this.toggleInlineStyle}
            />

            <Editor
              blockStyleFn={getBlockStyle}
              customStyleMap={styleMap}
              editorState={editorState}
              handleKeyCommand={this.handleKeyCommand}
              handleReturn={this.handleReturn}
              onChange={this.onChange}
              //keyBindingFn={this.keyBindingFn}
              onTab={this.onTab}
              placeholder=""
              ref="editor"
              spellCheck={true}
              plugins={[imagePlugin]}
              />

Verwendete Technologien

        <button className="btn btn-primary" onClick={this.saveDataToDatabase.bind(this)}>Speichern</button>

        :
        <Alert bsStyle="warning">Wenn du selbst Beiträge erfassen möchtest, erstelle jetzt <Link to="/registrieren">hier</Link> deinen eigenen Account.</Alert>
        }

    );
  }
}

 const styleMap = {
   CODE: {
     backgroundColor: 'rgba(0, 0, 0, 0.05)',
     fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
     fontSize: 16,
     padding: 2,
   },
 };

 function getBlockStyle(block) {
   switch (block.getType()) {
     case 'blockquote': return 'RichEditor-blockquote';
     case 'code-block': return 'language-css';
     default: return null;
   }
 }

 class StyleButton extends Component {
   constructor() {
     super();
     this.onToggle = (e) => {
       e.preventDefault();
       this.props.onToggle(this.props.style);
     };
   }

   render() {
     let className = 'RichEditor-styleButton';
     if (this.props.active) {
       className += ' RichEditor-activeButton';
     }

     return (

         {this.props.label}

     );
   }
 }

 const BLOCK_TYPES = [
   /*{label: 'H1', style: 'header-one'},
   {label: 'H2', style: 'header-two'},
   {label: 'H3', style: 'header-four'},*/
   {label: 'Headline', style: 'header-three'},
   /*{label: 'H5', style: 'header-five'},
   {label: 'H6', style: 'header-six'},*/
   {label: 'Blockquote', style: 'blockquote'},
   {label: 'UL', style: 'unordered-list-item'},
   {label: 'OL', style: 'ordered-list-item'},
   {label: 'Code Block', style: 'code-block'},
 ];

 const BlockStyleControls = (props) => {
   const {editorState} = props;
   const selection = editorState.getSelection();
   const blockType = editorState
     .getCurrentContent()
     .getBlockForKey(selection.getStartKey())
     .getType();

   return (

       {BLOCK_TYPES.map((type) =>


<commit_before>require([
  "jquery",
  "/themes/jiaoxuebang/javascripts/jquery.jcarousel.js",
  //"/themes/jiaoxuebang/javascripts/bootstrap.js",
  "/themes/jiaoxuebang/javascripts/jquery.dataTables.js",
  "/javascripts/vendor/jqueryui/effects/slide.js"], function($){

  $(document).ready(function(){

    //$('#carousel img').css('width', '632');

    // Init data table
    $(".datatable").dataTable({
      "sDom": 'ft'
    });

    function mycarousel_initCallback(carousel)
    {
      // Disable autoscrolling if the user clicks the prev or next button.
      carousel.buttonNext.bind('click', function() {
          carousel.startAuto(0);
      });

      carousel.buttonPrev.bind('click', function() {
          carousel.startAuto(0);
      });

      // Pause autoscrolling if the user moves with the cursor over the clip.
      carousel.clip.hover(function() {
          carousel.stopAuto();
      }, function() {
          carousel.startAuto();
      });

      var list = carousel.list.find(".jcarousel-item").show();
      list.find("img").css( "width", list.width() );
    };

    $('#mycarousel').jcarousel({
        auto: 2,
        wrap: 'last',
        scroll: 1,
        visible: 2,
        initCallback: mycarousel_initCallback
    });

    $(".save_selector").click(function(){
      var $widget = $( "[data-widget='" + $(this).attr("data-widget") + "']" );
      var ids = [];
      $widget.find("[data-course-id]").hide();
      $("#config_courses_holder .course_id_checkbox:checked").each(function(){
        $widget.find("[data-course-id=" + $(this).val() + "]").show();
        ids.push( $(this).val() );
      });
      if (ids.length <= 0) {
        $widget.find(".box-body").hide();
      }else{
        $widget.find(".box-body").show();
      }
      $.ajax({
        type: "put",
        url: $(this).attr("data-url"),
        data: {"widget":{"courses": $.unique(ids).join(",") }}
      });
      $("#config_courses_holder").hide();
      return false;
    });

    $(".config_courses").click(function(){
      var $widget = $(this).parents("[data-widget]");
      var top = $widget.offset().top - 100;
      var $courses_holder = $("#config_courses_holder").css("top", top);
      var ids = [];
      $widget.find("[data-course-id]:visible").each(function(){
        ids.push( $(this).attr("data-course-id") );
      });
      $courses_holder.find(".save_selector").attr( "data-widget", $widget.attr("data-widget") ).attr( "data-url", $(this).attr("data-url") );
      $(".course_id_checkbox").each(function(){
        if ( $.inArray( $(this).val(), ids ) === -1 ) {
          $(this).removeAttr("checked");
        }else{
          $(this).attr("checked", "checked");
        }
      });
      syncCourseCheckBoxs();
      $courses_holder.hide();
      $courses_holder.show('slide', {direction: 'left'}, 500);
    });

    $("#config_courses_holder .close").click(function(){
      $("#config_courses_holder").hide('fast');
    });

    function syncCourseCheckBoxs(){
      $("#config_courses_holder .account_name_checkbox").each(function(){
        var $allBox = $("[data-account-name='" + $(this).val() + "']");
        var $checkedBox = $("[data-account-name='" + $(this).val() + "']:checked");
        if ( $allBox.length == $checkedBox.length ) {
          $(this).attr("checked", "checked");
        }else{
          $(this).removeAttr("checked");
        }
      });
    }

    $("#config_courses_holder .account_name_checkbox").click(function(){
      var $allBox = $("[data-account-name=" + $(this).val() + "]");
      if ( $(this).is(":checked") ) {
        $allBox.attr("checked", "checked");
      }else{
        $allBox.removeAttr("checked");
      }
    });
  });

});
<commit_msg>Assignments in the wiget sort by created_at desc<commit_after>require([
  "jquery",
  "/themes/jiaoxuebang/javascripts/jquery.jcarousel.js",
  //"/themes/jiaoxuebang/javascripts/bootstrap.js",
  "/themes/jiaoxuebang/javascripts/jquery.dataTables.js",
  "/javascripts/vendor/jqueryui/effects/slide.js"], function($){

  $(document).ready(function(){

    //$('#carousel img').css('width', '632');

    // Init data table
    $(".datatable").dataTable({
      "sDom": 'ft',
      "aaSorting": [[ 2, "desc" ]],
      "aoColumns": [ null, null, null, null, null ]
    });

    function mycarousel_initCallback(carousel)
    {
      // Disable autoscrolling if the user clicks the prev or next button.
      carousel.buttonNext.bind('click', function() {
          carousel.startAuto(0);
      });

      carousel.buttonPrev.bind('click', function() {
          carousel.startAuto(0);
      });

      // Pause autoscrolling if the user moves with the cursor over the clip.
      carousel.clip.hover(function() {
          carousel.stopAuto();
      }, function() {
          carousel.startAuto();
      });

      var list = carousel.list.find(".jcarousel-item").show();
      list.find("img").css( "width", list.width() );
    };

    $('#mycarousel').jcarousel({
        auto: 2,
        wrap: 'last',
        scroll: 1,
        visible: 2,
        initCallback: mycarousel_initCallback
    });

    $(".save_selector").click(function(){
      var $widget = $( "[data-widget='" + $(this).attr("data-widget") + "']" );
      var ids = [];
      $widget.find("[data-course-id]").hide();
      $("#config_courses_holder .course_id_checkbox:checked").each(function(){
        $widget.find("[data-course-id=" + $(this).val() + "]").show();
        ids.push( $(this).val() );
      });
      if (ids.length <= 0) {
        $widget.find(".box-body").hide();
      }else{
        $widget.find(".box-body").show();
      }
      $.ajax({
        type: "put",
        url: $(this).attr("data-url"),
        data: {"widget":{"courses": $.unique(ids).join(",") }}
      });
      $("#config_courses_holder").hide();
      return false;
    });

    $(".config_courses").click(function(){
      var $widget = $(this).parents("[data-widget]");
      var top = $widget.offset().top - 100;
      var $courses_holder = $("#config_courses_holder").css("top", top);
      var ids = [];
      $widget.find("[data-course-id]:visible").each(function(){
        ids.push( $(this).attr("data-course-id") );
      });
      $courses_holder.find(".save_selector").attr( "data-widget", $widget.attr("data-widget") ).attr( "data-url", $(this).attr("data-url") );
      $(".course_id_checkbox").each(function(){
        if ( $.inArray( $(this).val(), ids ) === -1 ) {
          $(this).removeAttr("checked");
        }else{
          $(this).attr("checked", "checked");
        }
      });
      syncCourseCheckBoxs();
      $courses_holder.hide();
      $courses_holder.show('slide', {direction: 'left'}, 500);
    });

    $("#config_courses_holder .close").click(function(){
      $("#config_courses_holder").hide('fast');
    });

    function syncCourseCheckBoxs(){
      $("#config_courses_holder .account_name_checkbox").each(function(){
        var $allBox = $("[data-account-name='" + $(this).val() + "']");
        var $checkedBox = $("[data-account-name='" + $(this).val() + "']:checked");
        if ( $allBox.length == $checkedBox.length ) {
          $(this).attr("checked", "checked");
        }else{
          $(this).removeAttr("checked");
        }
      });
    }

    $("#config_courses_holder .account_name_checkbox").click(function(){
      var $allBox = $("[data-account-name=" + $(this).val() + "]");
      if ( $(this).is(":checked") ) {
        $allBox.attr("checked", "checked");
      }else{
        $allBox.removeAttr("checked");
      }
    });
  });

});
<|endoftext|>


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

exports.waitUntilReady = function (elm, timeout) {
  var t = timeout === undefined ? 1000 : timeout;
  browser.wait(function () {
    return elm.isPresent();
  }, t);
  browser.wait(function () {
    return elm.isDisplayed();
  }, t);
};

browser.getCapabilities().then(function(capabilities) {
  exports.testFileUpload = function() {
    var browserName = capabilities.get('browserName').toLowerCase();
    return (['chrome', 'firefox', 'internet explorer', 'edge'].indexOf(browserName) !== -1);
  };

  exports.testFileDownload = function() {
    // The only browser that does not ask for user interaction is chrome
    var browserName = capabilities.get('browserName').toLowerCase();
    var platform = capabilities.get('platform').toLowerCase();
    return ((['firefox', 'chrome'].indexOf(browserName) !== -1) && platform === 'linux');
  };

  exports.verifyFileDownload = function() {
    if (!browser.params.verifyFileDownload) {
      return false;
    }
  };
});

exports.waitForUrl = function (url) {
  browser.wait(function() {
    return browser.getCurrentUrl().then(function(current_url) {
      return (current_url.indexOf(url) !== -1);
    });
  });
};

exports.waitForFile = function (filename, timeout) {
  var t = timeout === undefined ? 1000 : timeout;
  var fp = path.resolve(browser.params.tmpDir, filename);
  browser.wait(function() {
    try {
      var buf = fs.readFileSync(fp);
      if (buf.length > 1000) {
        return true;
      }
    } catch(err) {
      return false;
    }
  }, t);
};

exports.emulateUserRefresh = function () {
  browser.actions().sendKeys(protractor.Key.CONTROL, 'r', protractor.Key.NULL).perform();
}
<commit_msg>Add browser.waitForAngular() after page refresh<commit_after>var fs = require('fs');
var path = require('path');

exports.waitUntilReady = function (elm, timeout) {
  var t = timeout === undefined ? 1000 : timeout;
  browser.wait(function () {
    return elm.isPresent();
  }, t);
  browser.wait(function () {
    return elm.isDisplayed();
  }, t);
};

browser.getCapabilities().then(function(capabilities) {
  exports.testFileUpload = function() {
    var browserName = capabilities.get('browserName').toLowerCase();
    return (['chrome', 'firefox', 'internet explorer', 'edge'].indexOf(browserName) !== -1);
  };

  exports.testFileDownload = function() {
    // The only browser that does not ask for user interaction is chrome
    var browserName = capabilities.get('browserName').toLowerCase();
    var platform = capabilities.get('platform').toLowerCase();
    return ((['firefox', 'chrome'].indexOf(browserName) !== -1) && platform === 'linux');
  };

  exports.verifyFileDownload = function() {
    if (!browser.params.verifyFileDownload) {
      return false;
    }
  };
});

exports.waitForUrl = function (url) {
  browser.wait(function() {
    return browser.getCurrentUrl().then(function(current_url) {
      return (current_url.indexOf(url) !== -1);
    });
  });
};

exports.waitForFile = function (filename, timeout) {
  var t = timeout === undefined ? 1000 : timeout;
  var fp = path.resolve(browser.params.tmpDir, filename);
  browser.wait(function() {
    try {
      var buf = fs.readFileSync(fp);
      if (buf.length > 1000) {
        return true;
      }
    } catch(err) {
      return false;
    }
  }, t);
};

exports.emulateUserRefresh = function () {
  browser.actions().sendKeys(protractor.Key.CONTROL, 'r', protractor.Key.NULL).perform();
  browser.waitForAngular();
}
<|endoftext|>