<commit_before>function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  loadUQFavicon();

  modifyUserAreaTile();

  //show notification bar if user is not logged in
  loadSigninNotification();

  // add a event on fadein, this is to solve session timeout issue,
  // when session timeout, primo will trigger an ajax call via function ssoByAjax then update the user login status
  var _old = $.fn.fadeIn;

  $.fn.fadeIn = function(){
    var self = this;
    _old.apply(this,arguments).promise().done(function(){
      self.trigger('fadeIn');
    });
  };

  $('#exlidSignOut').on('fadeIn',function(){
    modifyUserAreaTile();
    if ($('#alert-container')) {
      $('#alert-container').fadeOut(500);
    }
  });

  //first element of the original document
  var firstElement = document.body.children[0];

  // insert alerts after body-tag
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after alerts
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  window.addEventListener('WebComponentsReady', function () {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
    header.showAppsButton = true;
  });

  displayPublicationDates();
}

function displayPublicationDates() {
  // Use the Primo supplied function to preload the start and end dates in the Publication Date facet
  // function found in http://search.library.uq.edu.au/primo_library/libweb/wro/primo_library_web.js
  onTBChange('start');
  onTBChange('end');
}

function loadUQFavicon() {
  var link = document.createElement('link');
  link.type = 'image/x-icon';
  link.rel = 'shortcut icon';
  link.href = '//assets.library.uq.edu.au/master/reusable-components/resources/favicon.ico';
  document.getElementsByTagName('head')[0].appendChild(link);
  link.rel = 'icon'; //for IE
  document.getElementsByTagName('head')[0].appendChild(link);
}

/* Call primo defined method isUserLoggedIn() to check users login status, show the notification if the user is not logged in */
function loadSigninNotification() {
  if (isUserLoggedIn())
    return;
  if ($('#signInPrompt').length > 0) /* prevents a double sign-in on some pages */
    return;
  if ($('body').hasClass('MyAccount')) /* don't repeat sign-in prompt on E-Shelf page */
    return;

  /* get the login address from the signin link already generated by primo */
  var signInLink = $('#exlidSignIn a').attr('href');

  //put the notification bar in the feedback area which is sitting right after search bar
  var container = $('#exlidHeaderSystemFeedback');
  container.prepend('

Log in to access full text, more search results and more services. Refresh this page if you are logged in but still see this message.
');
}

function modifyUserAreaTile() {
  var userAreaRibbon = $('#exlidUserAreaTile #exlidUserAreaRibbon');

  if (userAreaRibbon) {

    var myAccount = userAreaRibbon.find('#exlidMyAccount'),
        myShelf = userAreaRibbon.find('#exlidMyShelf'),
        hiddenClass = 'EXLHidden';

    // move signin and signout button next to the user name
    userAreaRibbon.find('.EXLLastItem').insertAfter(userAreaRibbon.find('#exlidUserName'));

    if (isUserLoggedIn()){
      // undo not logged in changes
      if (myAccount.hasClass(hiddenClass)) {
        myAccount.removeClass(hiddenClass);
        myShelf.remove('span');
      }

      // add saved searches and alerts link
      var savedSearches = $('
Saved searches & alerts
');
      myShelf.after(savedSearches);

    } else {
      if ($('#exlidSavedSearches')){
        $('#exlidSavedSearches').remove();
      }
      // hide my account link
      myAccount.addClass(hiddenClass);

      // insert a login reminder after myself
      myShelf.append(' - temporary if not logged in');
    }
  }

}

ready(loadReusableComponents);

// load google analytics
(function (i, s, o, g, r, a, m) {
  i.GoogleAnalyticsObject = r;
  i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments);
      };

  i[r].l = 1 * new Date();
  a = s.createElement(o);
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-4365437-14', 'auto');
ga('send', 'pageview');
<commit_msg>hide login reminder when login status changes<commit_after>function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  loadUQFavicon();

  modifyUserAreaTile();

  //show notification bar if user is not logged in
  loadSigninNotification();

  listenToLoginStatusChanges();

  //first element of the original document
  var firstElement = document.body.children[0];

  // insert alerts after body-tag
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after alerts
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  window.addEventListener('WebComponentsReady', function () {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
    header.showAppsButton = true;
  });

  displayPublicationDates();
}

function displayPublicationDates() {
  // Use the Primo supplied function to preload the start and end dates in the Publication Date facet
  // function found in http://search.library.uq.edu.au/primo_library/libweb/wro/primo_library_web.js
  onTBChange('start');
  onTBChange('end');
}

function loadUQFavicon() {
  var link = document.createElement('link');
  link.type = 'image/x-icon';
  link.rel = 'shortcut icon';
  link.href = '//assets.library.uq.edu.au/master/reusable-components/resources/favicon.ico';
  document.getElementsByTagName('head')[0].appendChild(link);
  link.rel = 'icon'; //for IE
  document.getElementsByTagName('head')[0].appendChild(link);
}

/* Call primo defined method isUserLoggedIn() to check users login status, show the notification if the user is not logged in */
function loadSigninNotification() {
  if (isUserLoggedIn())
    return;
  if ($('#signInPrompt').length > 0) /* prevents a double sign-in on some pages */
    return;
  if ($('body').hasClass('MyAccount')) /* don't repeat sign-in prompt on E-Shelf page */
    return;

  /* get the login address from the signin link already generated by primo */
  var signInLink = $('#exlidSignIn a').attr('href');

  //put the notification bar in the feedback area which is sitting right after search bar
  var container = $('#exlidHeaderSystemFeedback');
  container.prepend('

Log in to access full text, more search results and more services. Refresh this page if you are logged in but still see this message.
');
}

function modifyUserAreaTile() {
  var userAreaRibbon = $('#exlidUserAreaTile #exlidUserAreaRibbon');

  if (userAreaRibbon) {

    var myAccount = userAreaRibbon.find('#exlidMyAccount'),
        myShelf = userAreaRibbon.find('#exlidMyShelf'),
        hiddenClass = 'EXLHidden';

    // move signin and signout button next to the user name
    userAreaRibbon.find('.EXLLastItem').insertAfter(userAreaRibbon.find('#exlidUserName'));

    if (isUserLoggedIn()){
      // undo not logged in changes
      if (myAccount.hasClass(hiddenClass)) {
        myAccount.removeClass(hiddenClass);
        myShelf.children('span').remove();
      }

      // add saved searches and alerts link
      var savedSearches = $('
Saved searches & alerts
');
      myShelf.after(savedSearches);

    } else {
      if ($('#exlidSavedSearches')){
        $('#exlidSavedSearches').remove();
      }
      // hide my account link
      myAccount.addClass(hiddenClass);

      // insert a login reminder after myself
      myShelf.append(' - temporary if not logged in');
    }
  }

}

// add a event on fadein, this is to solve session timeout issue,
// when session timeout, primo will trigger an ajax call via function ssoByAjax then update the user login status
function listenToLoginStatusChanges() {
  var _old = $.fn.fadeIn;

  $.fn.fadeIn = function(){
    var self = this;
    _old.apply(this,arguments).promise().done(function(){
      self.trigger('fadeIn');
    });
  };

  $('#exlidSignOut').on('fadeIn',function(){
    modifyUserAreaTile();
    if ($('#alert-container')) { // remove the login reminder
      $('#alert-container').fadeOut(500);
    }
  });
}

ready(loadReusableComponents);

// load google analytics
(function (i, s, o, g, r, a, m) {
  i.GoogleAnalyticsObject = r;
  i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments);
      };

  i[r].l = 1 * new Date();
  a = s.createElement(o);
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-4365437-14', 'auto');
ga('send', 'pageview');
<|endoftext|>


<commit_before>var argv = require('yargs').argv;
var assign = require('lodash.assign');
var autoprefixer = require('gulp-autoprefixer');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var concat = require('gulp-concat');
var connect = require('gulp-connect');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var minifycss = require('gulp-minify-css');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var reactify = require('reactify');
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');
var watchify = require('watchify');
var replace = require('gulp-replace-path');
var manifest = require('gulp-manifest');
var jsBundleFile = 'js/app.js';

opts = assign({}, watchify.args, {
  entries: jsBundleFile,
  extensions: 'jsx',
  debug: !argv.production
});

var bundler = browserify(opts);

bundler.transform(reactify);

gulp.task('browserify', function () {
  return bundler.bundle().pipe(source(jsBundleFile)).pipe(buffer()).pipe(gulpif(!argv.production, sourcemaps.init({
    loadMaps: true
  }))).pipe(gulpif(argv.production, uglify())).pipe(gulpif(!argv.production, sourcemaps.write('./'))).pipe(gulp.dest('./dist/assets/')).pipe(connect.reload());
});

gulp.task('browserify:watchify', function () {
  var watcher;
  watcher = watchify(bundler);
  return watcher.on('error', gutil.log.bind(gutil, 'Browserify Error')).on('update', function () {
    var updateStart;
    updateStart = Date.now();
    console.log('Browserify started');
    watcher.bundle().pipe(source(jsBundleFile)).pipe(buffer()).pipe(sourcemaps.init({
      loadMaps: true
    })).pipe(sourcemaps.write('./')).pipe(gulp.dest('./dist/assets/')).pipe(connect.reload());
    return console.log('Browserify ended', (Date.now() - updateStart) + 'ms');
  }).bundle().pipe(source(jsBundleFile)).pipe(gulp.dest('./dist/assets/'));
});

gulp.task('sass', function () {
  return gulp.src(['./styles/styles.scss']).pipe(gulpif(!argv.production, sourcemaps.init({
    loadMaps: true
  }))).pipe(sass().on('error', gutil.log)).pipe(autoprefixer()).pipe(gulpif(argv.production, minifycss())).pipe(gulpif(!argv.production, sourcemaps.write('./'))).pipe(gulp.dest('./dist/assets/css/')).pipe(connect.reload());
});

gulp.task('html', function () {
  return gulp.src(['./index.html']).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('push', function () {
  return gulp.src(['./push/*']).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('watch', ['server'], function () {
  gulp.watch(['./styles/**/*.scss'], ['sass']);
  return gulp.watch(['./index.html'], ['html']);
});

gulp.task('assets', function () {
  gulp.src(['./assets/**/*']).pipe(gulp.dest('./dist/assets/'));
  return gulp.src(['./bower_components/actor/*.js', './bower_components/actor/*.txt', './bower_components/actor/*.txt']).pipe(gulp.dest('./dist/actor/'));
});

gulp.task('usemin', function () {
  return gulp.src(['./index.html']).pipe(usemin({
    js: [
      sourcemaps.init({
        loadMaps: true
      }), 'concat', uglify(), sourcemaps.write('./')
    ],
    css: [autoprefixer(), minifycss()]
  })).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('manifest:prod', ['assets', 'browserify', 'sass', 'html', 'usemin', 'push'], function () {
  return gulp.src(['./dist/**/*']).pipe(manifest({
    hash: true,
    network: ['http://*', 'https://*', '*'],
    filename: 'app.appcache',
    exclude: 'app.appcache'
  })).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('server', function () {
  return connect.server({
    port: 3000,
    root: ['./dist/', './'],
    livereload: true
  });
});

gulp.task('build', ['assets', 'browserify', 'sass', 'html', 'usemin', 'push', 'manifest:prod']);

gulp.task('build:dev', ['assets', 'browserify:watchify', 'sass', 'html', 'push']);

gulp.task('build:gwt', ['assets', 'browserify', 'sass', 'usemin', 'push']);

gulp.task('dev', ['build:dev', 'server', 'watch']);

gulp.task('default', ['build']);

<commit_msg>chore(web): use strict for gulpfile.js<commit_after>'use strict';

var argv = require('yargs').argv;
var assign = require('lodash.assign');
var autoprefixer = require('gulp-autoprefixer');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var concat = require('gulp-concat');
var connect = require('gulp-connect');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var minifycss = require('gulp-minify-css');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var reactify = require('reactify');
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');
var watchify = require('watchify');
var replace = require('gulp-replace-path');
var manifest = require('gulp-manifest');
var jsBundleFile = 'js/app.js';

var opts = assign({}, watchify.args, {
  entries: jsBundleFile,
  extensions: 'jsx',
  debug: !argv.production
});

var bundler = browserify(opts);

bundler.transform(reactify);

gulp.task('browserify', function () {
  return bundler.bundle().pipe(source(jsBundleFile)).pipe(buffer()).pipe(gulpif(!argv.production, sourcemaps.init({
    loadMaps: true
  }))).pipe(gulpif(argv.production, uglify())).pipe(gulpif(!argv.production, sourcemaps.write('./'))).pipe(gulp.dest('./dist/assets/')).pipe(connect.reload());
});

gulp.task('browserify:watchify', function () {
  var watcher;
  watcher = watchify(bundler);
  return watcher.on('error', gutil.log.bind(gutil, 'Browserify Error')).on('update', function () {
    var updateStart;
    updateStart = Date.now();
    console.log('Browserify started');
    watcher.bundle().pipe(source(jsBundleFile)).pipe(buffer()).pipe(sourcemaps.init({
      loadMaps: true
    })).pipe(sourcemaps.write('./')).pipe(gulp.dest('./dist/assets/')).pipe(connect.reload());
    return console.log('Browserify ended', (Date.now() - updateStart) + 'ms');
  }).bundle().pipe(source(jsBundleFile)).pipe(gulp.dest('./dist/assets/'));
});

gulp.task('sass', function () {
  return gulp.src(['./styles/styles.scss']).pipe(gulpif(!argv.production, sourcemaps.init({
    loadMaps: true
  }))).pipe(sass().on('error', gutil.log)).pipe(autoprefixer()).pipe(gulpif(argv.production, minifycss())).pipe(gulpif(!argv.production, sourcemaps.write('./'))).pipe(gulp.dest('./dist/assets/css/')).pipe(connect.reload());
});

gulp.task('html', function () {
  return gulp.src(['./index.html']).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('push', function () {
  return gulp.src(['./push/*']).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('watch', ['server'], function () {
  gulp.watch(['./styles/**/*.scss'], ['sass']);
  return gulp.watch(['./index.html'], ['html']);
});

gulp.task('assets', function () {
  gulp.src(['./assets/**/*']).pipe(gulp.dest('./dist/assets/'));
  return gulp.src(['./bower_components/actor/*.js', './bower_components/actor/*.txt', './bower_components/actor/*.txt']).pipe(gulp.dest('./dist/actor/'));
});

gulp.task('usemin', function () {
  return gulp.src(['./index.html']).pipe(usemin({
    js: [
      sourcemaps.init({
        loadMaps: true
      }), 'concat', uglify(), sourcemaps.write('./')
    ],
    css: [autoprefixer(), minifycss()]
  })).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('manifest:prod', ['assets', 'browserify', 'sass', 'html', 'usemin', 'push'], function () {
  return gulp.src(['./dist/**/*']).pipe(manifest({
    hash: true,
    network: ['http://*', 'https://*', '*'],
    filename: 'app.appcache',
    exclude: 'app.appcache'
  })).pipe(gulp.dest('./dist/')).pipe(connect.reload());
});

gulp.task('server', function () {
  return connect.server({
    port: 3000,
    root: ['./dist/', './'],
    livereload: true
  });
});

gulp.task('build', ['assets', 'browserify', 'sass', 'html', 'usemin', 'push', 'manifest:prod']);

gulp.task('build:dev', ['assets', 'browserify:watchify', 'sass', 'html', 'push']);

gulp.task('build:gwt', ['assets', 'browserify', 'sass', 'usemin', 'push']);

gulp.task('dev', ['build:dev', 'server', 'watch']);

gulp.task('default', ['build']);

<|endoftext|>


<commit_before>defineSuite([
        'Core/Cartesian3',
        'Renderer/ComputeEngine',
        'Renderer/Pass',
        'Scene/OctahedralProjectedCubeMap',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/pollToPromise'
    ], function(
        Cartesian3,
        ComputeEngine,
        Pass,
        OctahedralProjectedCubeMap,
        createContext,
        createFrameState,
        pollToPromise) {
    'use strict';

    var context;
    var computeEngine;

    var environmentMapUrl = './Data/EnvironmentMap/kiara_6_afternoon_2k_ibl.ktx';
    var fsOctahedralMap =
        'uniform sampler2D projectedMap;' +
        'uniform vec2 textureSize;' +
        'uniform vec3 direction;' +
        'uniform float lod;' +
        'uniform float maxLod;' +
        'void main() {' +
        '   vec3 color = czm_sampleOctahedralProjection(projectedMap, textureSize, direction, lod, maxLod);' +
        '   gl_FragColor = vec4(color, 1.0);' +
        '}';

    var fsCubeMap =
        'uniform samplerCube cubeMap;' +
        'uniform vec3 direction;' +
        'void main() {' +
        '   vec4 rgbm = textureCube(cubeMap, direction);' +
        '   float m = rgbm.a * 16.0;' +
        '   vec3 r = rgbm.rgb * m;' +
        '   gl_FragColor = vec4(r * r, 1.0);' +
        '}';

    beforeAll(function() {
        context = createContext();
        computeEngine = new ComputeEngine(context);
    });

    afterAll(function() {
        context.destroyForSpecs();
        computeEngine.destroy();
    });

    afterEach(function() {

    });

    function executeCommands(frameState) {
        var length = frameState.commandList.length;
        for (var i = 0; i < length; ++i) {
            var command = frameState.commandList[i];
            if (command.pass === Pass.COMPUTE) {
                command.execute(computeEngine);
            } else {
                command.execute(context);
            }
        }
        frameState.commandList.length = 0;
    }

    function sampleOctahedralMap(octahedralMap, direction, lod, callback) {
        expect({
            context : context,
            fragmentShader : fsOctahedralMap,
            uniformMap : {
                projectedMap : function() {
                    return octahedralMap.texture;
                },
                textureSize : function() {
                    return octahedralMap.texture.dimensions;
                },
                direction : function() {
                    return direction;
                },
                lod : function() {
                    return lod;
                },
                maxLod : function() {
                    return octahedralMap.maximumMipmapLevel;
                }
            }
        }).contextToRenderAndCall(callback);
    }

    function sampleCubeMap(cubeMap, direction, callback) {
        expect({
            context : context,
            fragmentShader : fsCubeMap,
            uniformMap : {
                cubeMap : function() {
                    return cubeMap;
                },
                direction : function() {
                    return direction;
                }
            }
        }).contextToRenderAndCall(callback);
    }

    function expectCubeMapAndOctahedralMapEqual(octahedralMap, direction, lod) {
        return sampleCubeMap(octahedralMap._cubeMaps[lod], direction, function(cubeMapColor) {
            var directionFlipY = direction.clone();
            directionFlipY.y *= -1;

            sampleOctahedralMap(octahedralMap, directionFlipY, lod, function(octahedralMapColor) {
                return expect(cubeMapColor).toEqualEpsilon(octahedralMapColor, 5);
            });
        });
    }

    it('creates a packed texture with the right dimensions', function() {
        var octahedralMap = new OctahedralProjectedCubeMap(environmentMapUrl);
        var frameState = createFrameState(context);

        return pollToPromise(function() {
            octahedralMap.update(frameState);
            return octahedralMap.ready;
        }).then(function() {
            expect(octahedralMap.texture.width).toEqual(770);
            expect(octahedralMap.texture.height).toEqual(512);
            expect(octahedralMap.maximumMipmapLevel).toEqual(5);
        });
    });

    it('correctly projects the given cube map and all mip levels', function() {
        var octahedralMap = new OctahedralProjectedCubeMap(environmentMapUrl);
        var frameState = createFrameState(context);

        return pollToPromise(function() {
            // We manually call update and execute the commands
            // because calling scene.renderForSpecs does not
            // actually execute these commands, and we need
            // to get the output of the texture.
            octahedralMap.update(frameState);
            executeCommands(frameState);

            return octahedralMap.ready;
        }).then(function() {
            var directions = {
                positiveX : new Cartesian3(1, 0, 0),
                negativeX : new Cartesian3(-1, 0, 0),
                positiveY : new Cartesian3(0, 1, 0),
                negativeY : new Cartesian3(0, -1, 0),
                positiveZ : new Cartesian3(0, 0, 1),
                negativeZ : new Cartesian3(0, 0, -1)
            };

            for (var mipLevel = 0; mipLevel < octahedralMap.maximumMipmapLevel; mipLevel++) {
               for (var key in directions) {
                    if (directions.hasOwnProperty(key)) {
                        var direction = directions[key];

                        expectCubeMapAndOctahedralMapEqual(octahedralMap, direction, mipLevel);
                    }
                }
            }
        });
    });
}, 'WebGL');
<commit_msg>Fix spec name<commit_after>defineSuite([
        'Scene/OctahedralProjectedCubeMap',
        'Core/Cartesian3',
        'Renderer/ComputeEngine',
        'Renderer/Pass',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/pollToPromise'
    ], function(
        OctahedralProjectedCubeMap,
        Cartesian3,
        ComputeEngine,
        Pass,
        createContext,
        createFrameState,
        pollToPromise) {
    'use strict';

    var context;
    var computeEngine;

    var environmentMapUrl = './Data/EnvironmentMap/kiara_6_afternoon_2k_ibl.ktx';
    var fsOctahedralMap =
        'uniform sampler2D projectedMap;' +
        'uniform vec2 textureSize;' +
        'uniform vec3 direction;' +
        'uniform float lod;' +
        'uniform float maxLod;' +
        'void main() {' +
        '   vec3 color = czm_sampleOctahedralProjection(projectedMap, textureSize, direction, lod, maxLod);' +
        '   gl_FragColor = vec4(color, 1.0);' +
        '}';

    var fsCubeMap =
        'uniform samplerCube cubeMap;' +
        'uniform vec3 direction;' +
        'void main() {' +
        '   vec4 rgbm = textureCube(cubeMap, direction);' +
        '   float m = rgbm.a * 16.0;' +
        '   vec3 r = rgbm.rgb * m;' +
        '   gl_FragColor = vec4(r * r, 1.0);' +
        '}';

    beforeAll(function() {
        context = createContext();
        computeEngine = new ComputeEngine(context);
    });

    afterAll(function() {
        context.destroyForSpecs();
        computeEngine.destroy();
    });

    afterEach(function() {

    });

    function executeCommands(frameState) {
        var length = frameState.commandList.length;
        for (var i = 0; i < length; ++i) {
            var command = frameState.commandList[i];
            if (command.pass === Pass.COMPUTE) {
                command.execute(computeEngine);
            } else {
                command.execute(context);
            }
        }
        frameState.commandList.length = 0;
    }

    function sampleOctahedralMap(octahedralMap, direction, lod, callback) {
        expect({
            context : context,
            fragmentShader : fsOctahedralMap,
            uniformMap : {
                projectedMap : function() {
                    return octahedralMap.texture;
                },
                textureSize : function() {
                    return octahedralMap.texture.dimensions;
                },
                direction : function() {
                    return direction;
                },
                lod : function() {
                    return lod;
                },
                maxLod : function() {
                    return octahedralMap.maximumMipmapLevel;
                }
            }
        }).contextToRenderAndCall(callback);
    }

    function sampleCubeMap(cubeMap, direction, callback) {
        expect({
            context : context,
            fragmentShader : fsCubeMap,
            uniformMap : {
                cubeMap : function() {
                    return cubeMap;
                },
                direction : function() {
                    return direction;
                }
            }
        }).contextToRenderAndCall(callback);
    }

    function expectCubeMapAndOctahedralMapEqual(octahedralMap, direction, lod) {
        return sampleCubeMap(octahedralMap._cubeMaps[lod], direction, function(cubeMapColor) {
            var directionFlipY = direction.clone();
            directionFlipY.y *= -1;

            sampleOctahedralMap(octahedralMap, directionFlipY, lod, function(octahedralMapColor) {
                return expect(cubeMapColor).toEqualEpsilon(octahedralMapColor, 5);
            });
        });
    }

    it('creates a packed texture with the right dimensions', function() {
        var octahedralMap = new OctahedralProjectedCubeMap(environmentMapUrl);
        var frameState = createFrameState(context);

        return pollToPromise(function() {
            octahedralMap.update(frameState);
            return octahedralMap.ready;
        }).then(function() {
            expect(octahedralMap.texture.width).toEqual(770);
            expect(octahedralMap.texture.height).toEqual(512);
            expect(octahedralMap.maximumMipmapLevel).toEqual(5);
        });
    });

    it('correctly projects the given cube map and all mip levels', function() {
        var octahedralMap = new OctahedralProjectedCubeMap(environmentMapUrl);
        var frameState = createFrameState(context);

        return pollToPromise(function() {
            // We manually call update and execute the commands
            // because calling scene.renderForSpecs does not
            // actually execute these commands, and we need
            // to get the output of the texture.
            octahedralMap.update(frameState);
            executeCommands(frameState);

            return octahedralMap.ready;
        }).then(function() {
            var directions = {
                positiveX : new Cartesian3(1, 0, 0),
                negativeX : new Cartesian3(-1, 0, 0),
                positiveY : new Cartesian3(0, 1, 0),
                negativeY : new Cartesian3(0, -1, 0),
                positiveZ : new Cartesian3(0, 0, 1),
                negativeZ : new Cartesian3(0, 0, -1)
            };

            for (var mipLevel = 0; mipLevel < octahedralMap.maximumMipmapLevel; mipLevel++) {
               for (var key in directions) {
                    if (directions.hasOwnProperty(key)) {
                        var direction = directions[key];

                        expectCubeMapAndOctahedralMapEqual(octahedralMap, direction, mipLevel);
                    }
                }
            }
        });
    });
}, 'WebGL');
<|endoftext|>


<commit_before>import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const styles = {margin:12}

class FormInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      address:null,
      name:null,
      accounts:[],
      detail:{}
    };

    this.props.getAccounts(accounts => {
      this.setState({
        address:accounts[0],
        accounts:accounts
      })
    })
    this.props.getDetail(detail => {
      this.setState({
        detail:detail
      })
    })
    this.props.eventEmitter.on('change', detail => {
      console.log('DETAIL', detail)
      this.setState({detail:detail});
    });
  }

  handleAction(actionName) {
    this.setState({
      name: null,
    });
    this.props.action(actionName, this.state.address.trim(), this.state.name)
  }

  handleSelect(event,index,value){
    this.setState({
      address: value,
    });
  }

  isOwner(){
    return this.state.accounts.includes(this.state.detail.owner);
  }

  showRegister(){
    return this.state.detail.canRegister
  }

  showPayback(){
    return this.state.detail.canPayback
  }

  showCancel(){
    return this.state.detail.canCancel
  }

  showClear(){
    return this.state.detail.ended
  }

  handleName(e) {
    this.setState({
      name: e.target.value,
    });
  }

  render() {
    let adminButtons, registerButton;
    if(this.isOwner()){
      adminButtons =
        <RaisedButton secondary={this.showPayback()} disabled={!this.showPayback()}
          label="Payback" style={styles}
          onClick={this.handleAction.bind(this, 'payback')}
        />
        <RaisedButton secondary={this.showCancel()} disabled={!this.showCancel()}
          label="Cancel" style={styles}
          onClick={this.handleAction.bind(this, 'cancel')}
        />
        <RaisedButton secondary={this.showClear()} disabled={!this.showClear()}
          label="Clear" style={styles}
          onClick={this.handleAction.bind(this, 'clear')}
        />

    }

    var availableSpots = this.state.detail.limitOfParticipants - this.state.detail.registered;
    if(this.props.read_only){
      registerButton = Connect via Mist/Metamask to be able to register.
    }else if(this.state.accounts.length > 0){
      if(this.state.detail.ended){
        registerButton = This even is over
      }else if (availableSpots <= 0){
        registerButton = No more spots left
      }else{
        registerButton = <RaisedButton secondary={this.showRegister()} disabled={!this.showRegister()}
          label="Register" style={styles}
          onClick={this.handleAction.bind(this, 'register')}
        />
      }
    }else{
      registerButton = No account is set
    }

    return (
      <Paper zDepth={1}>
        <form>
          <TextField
            hintText="@twitter_handle"
            floatingLabelText="Twitter handle"
            floatingLabelFixed={true}
            value={this.state.name}
            onChange={this.handleName.bind(this)}
            style={{margin:'0 5px'}}
          />
          <SelectField
            value={this.state.address}
            onChange={this.handleSelect.bind(this)}
            floatingLabelText="Account address"
            floatingLabelFixed={true}
            style={{width:'25em', verticalAlign:'top', margin:'0 5px'}}
            >
            {
              this.state.accounts.map(account => {
                return (<MenuItem value={account} primaryText={account} />)
              })
            }
          </SelectField>

          {registerButton}
          {adminButtons}
        </form>
      </Paper>
    );
  }
}

export default FormInput;
<commit_msg>Add final warning<commit_after>import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const styles = {margin:12}

class FormInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      address:null,
      name:null,
      accounts:[],
      detail:{}
    };

    this.props.getAccounts(accounts => {
      this.setState({
        address:accounts[0],
        accounts:accounts
      })
    })
    this.props.getDetail(detail => {
      this.setState({
        detail:detail
      })
    })
    this.props.eventEmitter.on('change', detail => {
      console.log('DETAIL', detail)
      this.setState({detail:detail});
    });
  }

  handleAction(actionName) {
    this.setState({
      name: null,
    });
    this.props.action(actionName, this.state.address.trim(), this.state.name)
  }

  handleSelect(event,index,value){
    this.setState({
      address: value,
    });
  }

  isOwner(){
    return this.state.accounts.includes(this.state.detail.owner);
  }

  showRegister(){
    return this.state.detail.canRegister
  }

  showPayback(){
    return this.state.detail.canPayback
  }

  showCancel(){
    return this.state.detail.canCancel
  }

  showClear(){
    return this.state.detail.ended
  }

  handleName(e) {
    this.setState({
      name: e.target.value,
    });
  }

  render() {
    let adminButtons, registerButton, warningText;
    if(this.isOwner()){
      adminButtons =
        <RaisedButton secondary={this.showPayback()} disabled={!this.showPayback()}
          label="Payback" style={styles}
          onClick={this.handleAction.bind(this, 'payback')}
        />
        <RaisedButton secondary={this.showCancel()} disabled={!this.showCancel()}
          label="Cancel" style={styles}
          onClick={this.handleAction.bind(this, 'cancel')}
        />
        <RaisedButton secondary={this.showClear()} disabled={!this.showClear()}
          label="Clear" style={styles}
          onClick={this.handleAction.bind(this, 'clear')}
        />

    }

    var availableSpots = this.state.detail.limitOfParticipants - this.state.detail.registered;
    if(this.props.read_only){
      registerButton = Connect via Mist/Metamask to be able to register.
    }else if(this.state.accounts.length > 0){
      if(this.state.detail.ended){
        registerButton = This even is over
      }else if (availableSpots <= 0){
        registerButton = No more spots left
      }else{
        registerButton = <RaisedButton secondary={this.showRegister()} disabled={!this.showRegister()}
          label="Register" style={styles}
          onClick={this.handleAction.bind(this, 'register')}
        />
        warningText =
Please be aware that you cannot cancel once regiesterd. Please read FAQ section at ABOUT page on top right corner for more detail about this service.

      }
    }else{
      registerButton = No account is set
    }

    return (
      <Paper zDepth={1}>
        <form>
          <TextField
            hintText="@twitter_handle"
            floatingLabelText="Twitter handle"
            floatingLabelFixed={true}
            value={this.state.name}
            onChange={this.handleName.bind(this)}
            style={{margin:'0 5px'}}
          />
          <SelectField
            value={this.state.address}
            onChange={this.handleSelect.bind(this)}
            floatingLabelText="Account address"
            floatingLabelFixed={true}
            style={{width:'25em', verticalAlign:'top', margin:'0 5px'}}
            >
            {
              this.state.accounts.map(account => {
                return (<MenuItem value={account} primaryText={account} />)
              })
            }
          </SelectField>
          {registerButton}
          {adminButtons}
        </form>
        {warningText}
      </Paper>
    );
  }
}

export default FormInput;
<|endoftext|>


<commit_before>import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const styles = {margin:12}

class FormInput extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      address:props.accounts[0],
      name:null
    };
  }

  handleAction(actionName) {
    this.setState({
      name: null,
    });
    this.props.action(actionName, this.state.address.trim(), this.state.name)
  }

  handleSelect(event,index,value){
    this.setState({
      address: value,
    });
  }

  handleName(e) {
    this.setState({
      name: e.target.value,
    });
  }

  render() {
    return (
      <Paper zDepth={1}>
        <form>

          <SelectField
            value={this.state.address}
            onChange={this.handleSelect.bind(this)}
            floatingLabelText="Account address"
            floatingLabelFixed={true}
            style={{width:'25em'}}
            >
            {
              this.props.accounts.map(account => {
                return (<MenuItem value={account} primaryText={account} />)
              })
            }
          </SelectField>
          <TextField
            hintText="@twitter_handle"
            floatingLabelText="Twitter handle"
            floatingLabelFixed={true}
            value={this.state.name}
            onChange={this.handleName.bind(this)}
          />
          <RaisedButton secondary={true}
            label="Register" style={styles}
            onClick={this.handleAction.bind(this, 'register')}
          />
          <RaisedButton secondary={true}
            label="Attend" style={styles}
            onClick={this.handleAction.bind(this, 'attend')}
          />
          <RaisedButton secondary={true}
            label="Payback" style={styles}
            onClick={this.handleAction.bind(this, 'payback')}
          />
        <RaisedButton secondary={true}
            label="Reset" style={styles}
            onClick={this.handleAction.bind(this, 'reset')}
          />
        </form>
      </Paper>
    );
  }
}

export default FormInput;
<commit_msg>Align form<commit_after>import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const styles = {margin:12}

class FormInput extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      address:props.accounts[0],
      name:null
    };
  }

  handleAction(actionName) {
    this.setState({
      name: null,
    });
    this.props.action(actionName, this.state.address.trim(), this.state.name)
  }

  handleSelect(event,index,value){
    this.setState({
      address: value,
    });
  }

  handleName(e) {
    this.setState({
      name: e.target.value,
    });
  }

  render() {
    return (
      <Paper zDepth={1}>
        <form>
          <TextField
            hintText="@twitter_handle"
            floatingLabelText="Twitter handle"
            floatingLabelFixed={true}
            value={this.state.name}
            onChange={this.handleName.bind(this)}
            style={{margin:'0 5px'}}
          />
          <SelectField
            value={this.state.address}
            onChange={this.handleSelect.bind(this)}
            floatingLabelText="Account address"
            floatingLabelFixed={true}
            style={{width:'25em', verticalAlign:'top', margin:'0 5px'}}
            >
            {
              this.props.accounts.map(account => {
                return (<MenuItem value={account} primaryText={account} />)
              })
            }
          </SelectField>

          <RaisedButton secondary={true}
            label="Register" style={styles}
            onClick={this.handleAction.bind(this, 'register')}
          />
          <RaisedButton secondary={true}
            label="Attend" style={styles}
            onClick={this.handleAction.bind(this, 'attend')}
          />
          <RaisedButton secondary={true}
            label="Payback" style={styles}
            onClick={this.handleAction.bind(this, 'payback')}
          />
        <RaisedButton secondary={true}
            label="Reset" style={styles}
            onClick={this.handleAction.bind(this, 'reset')}
          />
        </form>
      </Paper>
    );
  }
}

export default FormInput;
<|endoftext|>


<commit_before>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

define(['require', 'module', 'jquery', 'underscore', 'backbone', 'URIjs'],
    function (require, module, $, _, Backbone, URI) {

    // Description: This model provides an interface for navigating an EPUB's package document
    var PackageDocument = function(packageDocumentURL, resourceFetcher, metadata, spine, manifest) {

        var _page_prog_dir;

        this.manifest = manifest;

        this.getSharedJsPackageData = function () {

            var packageDocRoot = packageDocumentURL.substr(0, packageDocumentURL.lastIndexOf("/"));
            return {
                rootUrl : packageDocRoot,
                rendition_layout : metadata.rendition_layout,
                rendition_orientation : metadata.rendition_orientation,
                rendition_flow : metadata.rendition_flow,
                media_overlay : metadata.media_overlay,
                spine : {
                    direction : this.getPageProgressionDirection(),
                    items : spine
                }
            };
        };

        /**
         * Get spine item data in readium-shared-js accepted format.
         * @param spineIndex the index of the item within the spine
         * @returns Spine item data in readium-shared-js accepted format.
         */
        this.getSpineItem = function(spineIndex) {
            var spineItem = spine[spineIndex];
            return spineItem;
        };

        this.setPageProgressionDirection = function(page_prog_dir) {
            _page_prog_dir = page_prog_dir;
        };

        this.getPageProgressionDirection = function() {
            if (_page_prog_dir === "rtl") {
                return "rtl";
            }
            else if (_page_prog_dir === "default") {
                return "default";
            }
            else {
                return "ltr";
            }
        };

        this.spineLength = function() {
            return spine.length;
        };

        this.getMetadata = function() {
            return metadata;
        };

        this.getToc = function() {
            var item = getTocItem();
            if (item) {
                return item.href;
            }
            return null;
        };

        this.getTocText = function(callback) {
            var toc = this.getToc();

            resourceFetcher.relativeToPackageFetchFileContents(toc, 'text', function (tocDocumentText) {
                callback(tocDocumentText)
            }, function (err) {
                console.error('ERROR fetching TOC from [' + toc + ']:');
                console.error(err);
                callback(undefined);
            });
        };

        this.getTocDom = function(callback) {

            this.getTocText(function (tocText) {
                if (typeof tocText === 'string') {
                    var tocDom = (new DOMParser()).parseFromString(tocText, "text/xml");
                    callback(tocDom);
                } else {
                    callback(undefined);
                }
            });
        };

        // Unused?
        this.generateTocListDOM = function(callback) {
            var that = this;
            this.getTocDom(function (tocDom) {
                if (tocDom) {
                    if (tocIsNcx()) {
                        var $ncxOrderedList;
                        $ncxOrderedList = getNcxOrderedList($("navMap", tocDom));
                        callback($ncxOrderedList[0]);
                    } else {
                        var packageDocumentAbsoluteURL = new URI(packageDocumentURL).absoluteTo(document.URL);
                        var tocDocumentAbsoluteURL = new URI(that.getToc()).absoluteTo(packageDocumentAbsoluteURL);
                        // add a BASE tag to change the TOC document's baseURI.
                        var oldBaseTag = $(tocDom).remove('base');
                        var newBaseTag = $('<base></base>');
                        $(newBaseTag).attr('href', tocDocumentAbsoluteURL);
                        $(tocDom).find('head').append(newBaseTag);
                        // TODO: fix TOC hrefs both for exploded in zipped EPUBs
                        callback(tocDom);
                    }
                } else {
                    callback(undefined);
                }
            });
        };

        function tocIsNcx() {

            var tocItem = getTocItem();
            var contentDocURI = tocItem.href;
            var fileExtension = contentDocURI.substr(contentDocURI.lastIndexOf('.') + 1);

            return fileExtension.trim().toLowerCase() === "ncx";
        }

        // ----------------------- PRIVATE HELPERS -------------------------------- //

        function getNcxOrderedList($navMapDOM) {

            var $ol = $("

");
            $.each($navMapDOM.children("navPoint"), function (index, navPoint) {
                addNavPointElements($(navPoint), $ol);
            });
            return $ol;
        }

        // Description: Constructs an html representation of NCX navPoints, based on an object of navPoint information
        // Rationale: This is a recursive method, as NCX navPoint elements can nest 0 or more of themselves as children
        function addNavPointElements($navPointDOM, $ol) {

            // Add the current navPoint element to the TOC html
            var navText = $navPointDOM.children("navLabel").text().trim();
            var navHref = $navPointDOM.children("content").attr("src");
            var $navPointLi = $('

').append(
                $('', { href: navHref, text: navText })
            );

            // Append nav point info
            $ol.append($navPointLi);

            // Append ordered list of nav points
            if ($navPointDOM.children("navPoint").length > 0 ) {

                var $newLi = $("

");
                var $newOl = $("

");
                $.each($navPointDOM.children("navPoint"), function (navIndex, navPoint) {
                    $newOl.append(addNavPointElements($(navPoint), $newOl));
                });

                $newLi.append($newOl);
                $ol.append($newLi);
            }
        }

        function getTocItem(){

            var item = manifest.getNavItem();
            if (item) {
                return item;
            }

            var spine_id = metadata.ncx;
            if (spine_id && spine_id.length > 0) {
                return manifest.getManifestItemByIdref(spine_id);
            }

            return null;
        }

    };

    return PackageDocument;
});
<commit_msg>Propagate the package-global rendition_spread property<commit_after>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

define(['require', 'module', 'jquery', 'underscore', 'backbone', 'URIjs'],
    function (require, module, $, _, Backbone, URI) {

    // Description: This model provides an interface for navigating an EPUB's package document
    var PackageDocument = function(packageDocumentURL, resourceFetcher, metadata, spine, manifest) {

        var _page_prog_dir;

        this.manifest = manifest;

        this.getSharedJsPackageData = function () {

            var packageDocRoot = packageDocumentURL.substr(0, packageDocumentURL.lastIndexOf("/"));
            return {
                rootUrl : packageDocRoot,
                rendition_layout : metadata.rendition_layout,
                rendition_orientation : metadata.rendition_orientation,
                rendition_flow : metadata.rendition_flow,
                rendition_spread : metadata.rendition_spread,
                media_overlay : metadata.media_overlay,
                spine : {
                    direction : this.getPageProgressionDirection(),
                    items : spine
                }
            };
        };

        /**
         * Get spine item data in readium-shared-js accepted format.
         * @param spineIndex the index of the item within the spine
         * @returns Spine item data in readium-shared-js accepted format.
         */
        this.getSpineItem = function(spineIndex) {
            var spineItem = spine[spineIndex];
            return spineItem;
        };

        this.setPageProgressionDirection = function(page_prog_dir) {
            _page_prog_dir = page_prog_dir;
        };

        this.getPageProgressionDirection = function() {
            if (_page_prog_dir === "rtl") {
                return "rtl";
            }
            else if (_page_prog_dir === "default") {
                return "default";
            }
            else {
                return "ltr";
            }
        };

        this.spineLength = function() {
            return spine.length;
        };

        this.getMetadata = function() {
            return metadata;
        };

        this.getToc = function() {
            var item = getTocItem();
            if (item) {
                return item.href;
            }
            return null;
        };

        this.getTocText = function(callback) {
            var toc = this.getToc();

            resourceFetcher.relativeToPackageFetchFileContents(toc, 'text', function (tocDocumentText) {
                callback(tocDocumentText)
            }, function (err) {
                console.error('ERROR fetching TOC from [' + toc + ']:');
                console.error(err);
                callback(undefined);
            });
        };

        this.getTocDom = function(callback) {

            this.getTocText(function (tocText) {
                if (typeof tocText === 'string') {
                    var tocDom = (new DOMParser()).parseFromString(tocText, "text/xml");
                    callback(tocDom);
                } else {
                    callback(undefined);
                }
            });
        };

        // Unused?
        this.generateTocListDOM = function(callback) {
            var that = this;
            this.getTocDom(function (tocDom) {
                if (tocDom) {
                    if (tocIsNcx()) {
                        var $ncxOrderedList;
                        $ncxOrderedList = getNcxOrderedList($("navMap", tocDom));
                        callback($ncxOrderedList[0]);
                    } else {
                        var packageDocumentAbsoluteURL = new URI(packageDocumentURL).absoluteTo(document.URL);
                        var tocDocumentAbsoluteURL = new URI(that.getToc()).absoluteTo(packageDocumentAbsoluteURL);
                        // add a BASE tag to change the TOC document's baseURI.
                        var oldBaseTag = $(tocDom).remove('base');
                        var newBaseTag = $('<base></base>');
                        $(newBaseTag).attr('href', tocDocumentAbsoluteURL);
                        $(tocDom).find('head').append(newBaseTag);
                        // TODO: fix TOC hrefs both for exploded in zipped EPUBs
                        callback(tocDom);
                    }
                } else {
                    callback(undefined);
                }
            });
        };

        function tocIsNcx() {

            var tocItem = getTocItem();
            var contentDocURI = tocItem.href;
            var fileExtension = contentDocURI.substr(contentDocURI.lastIndexOf('.') + 1);

            return fileExtension.trim().toLowerCase() === "ncx";
        }

        // ----------------------- PRIVATE HELPERS -------------------------------- //

        function getNcxOrderedList($navMapDOM) {

            var $ol = $("

");
            $.each($navMapDOM.children("navPoint"), function (index, navPoint) {
                addNavPointElements($(navPoint), $ol);
            });
            return $ol;
        }

        // Description: Constructs an html representation of NCX navPoints, based on an object of navPoint information
        // Rationale: This is a recursive method, as NCX navPoint elements can nest 0 or more of themselves as children
        function addNavPointElements($navPointDOM, $ol) {

            // Add the current navPoint element to the TOC html
            var navText = $navPointDOM.children("navLabel").text().trim();
            var navHref = $navPointDOM.children("content").attr("src");
            var $navPointLi = $('

').append(
                $('', { href: navHref, text: navText })
            );

            // Append nav point info
            $ol.append($navPointLi);

            // Append ordered list of nav points
            if ($navPointDOM.children("navPoint").length > 0 ) {

                var $newLi = $("

");
                var $newOl = $("

");
                $.each($navPointDOM.children("navPoint"), function (navIndex, navPoint) {
                    $newOl.append(addNavPointElements($(navPoint), $newOl));
                });

                $newLi.append($newOl);
                $ol.append($newLi);
            }
        }

        function getTocItem(){

            var item = manifest.getNavItem();
            if (item) {
                return item;
            }

            var spine_id = metadata.ncx;
            if (spine_id && spine_id.length > 0) {
                return manifest.getManifestItemByIdref(spine_id);
            }

            return null;
        }

    };

    return PackageDocument;
});
<|endoftext|>


<commit_before>/**
 * Library to render a series of hexagons from arbitrary data
 * Requires jQuery and D3
 */
define([ 'jquery','honest/d3.min'],
    function($, d3)
    {
        // NOTE this could be encapsulated further (into a Class) but all use cases
        // not yet clear. It doesn't make any functional difference.
        return {

            /**
             * Calculate all the vital information about a Hexagon
             * @param {Number} _width Width of hexagon
             * @param {Number} _aspect How much to scale the sides
             * @param {Object} _offset Offset from origin {x,y}
             * @returns {Object} Hexagon definition
             */
            calculateHexagon: function(_width, _aspect, _offset)
            {
                var _offset = _offset || {x:0,y:0};
                // Side length
                var _side = (_width * Math.sqrt(3) / 4) * _aspect;
                // Gap betwwen rows
                var _gap = (_width / 4) * _aspect;
                // Height of hexagon
                var _height = _side + ((_width / 2) * _aspect);
                // Hexagon lines for D3 line generator
                var _hexagon = [{x : _width / 2, y : 0},
                                {x : 0,          y : _gap},
                                {x : 0,          y : _gap + _side},
                                {x : _width / 2, y : _height},
                                {x : _width,     y : _gap + _side},
                                {x : _width,     y : _gap},
                                {x : _width / 2, y : 0}];
                for(var i = 0; i < 7; i++)
                {
                    _hexagon[i].x += _offset.x;
                    _hexagon[i].y += _offset.y;
                }
                return {side:_side, gap:_gap, height:_height, hexagon:_hexagon};
            },

            /**
             * Calculate all the vital information about the hexagons we are plotting
             * @param {String} where Selector string
             * @param {Number} _pad Width between hexagons
             * @param {Number} _width Width of hexagon
             * @param {Number} _aspect How much to scale the sides
             * @param {Array} items Items to render
             * @param {Boolean} equalRows - do we have the same number of hexagons in each row?
             * @returns {Object} Hexagons definition
             */
            calculateHexagons : function(where, _pad, _width, _aspect, items, equalRows)
            {
                if (where.length == 0)
                    return;

                // Internal page width function
                var pageWidth = function()
                {
                    return where.width();
                };

                // Work our hexagon variables
                var _hexagon = this.calculateHexagon(_width, _aspect);
                // Side length
                var _side = _hexagon.side;
                // Gap betwwen rows
                var _gap = _hexagon.gap;
                // Height of hexagon
                var _height = _hexagon.height;
                // Hexagon lines for D3 line generator
                var hexagon = _hexagon.hexagon;

                if(equalRows)
                {
                    // Maximum number of columns
                    var _maxCols = Math.ceil(pageWidth() / (_width + _pad)) - 1;
                    // Minimum number of columns
                    var _minCols = _maxCols;
                }
                else
                {
                    // Maximum number of columns
                    _maxCols = Math.floor(pageWidth() / (_width + _pad));
                    // Minimum number of columns
                    _minCols = _maxCols === 1 ? 1 : _maxCols - 1;
                }
                var _rows = 0, _count = 0;
                var _wrapHeight = 0;
                // Determine total height and number of rows
                while(_count < items)
                {
                    _rows++;
                    _count += (_count % 2 === 0) ? _maxCols : _minCols;
                }

                // Centre hexagons horizontally
                if(!equalRows)
                {
                    var centre = (_maxCols === 1) ? (pageWidth() + (_pad * 2) - (_width * 1.5)) / 2 : (pageWidth() +(_pad * 2) - (_width * _maxCols)) / 2;
                    if(centre < 0)
                    {
                        centre = 0;
                    }
                }
                else
                {
                    centre = 0;
                }

               // Return all Hexagon info
               return {
                   pad: _pad,
                   width: _width,
                   aspect: _aspect,
                   side: _side,
                   gap: _gap,
                   height: _height,
                   wrapHeight: _wrapHeight + 2,
                   wrapWidth: pageWidth(),
                   min: _minCols,
                   max: _maxCols,
                   rows: _rows,
                   hexagon: hexagon,
                   centre: centre
               };
            },

            /**
             * Given a Hexagon 'hex/ set all items in the correct position
             * @param {Object from calculateHexagons} hex Hexagon info
             * @param {Array} items Items to render
             */
            setPositions : function(hex, items)
            {
                hex.wrapHeight = 0;
               // Update positions into questions
                var row = 0, col = 0, x = hex.centre, y = 0, full_row = false;
                for(var i = 0, len = items.length; i < len; i++)
                {
                    full_row = false;
                    items[i].x = x;
                    items[i].y = y;
                    // Increment
                    col++; x += hex.width + hex.pad;
                    // New row?
                    if(col >= (row % 2 === 0 ? hex.max : hex.min))
                    {
                        row++;
                        // Update X & Y
                        y += hex.height + hex.pad - hex.gap;
                        // X depends on even or odd
                        x = (row % 2 === 0 ? hex.centre : hex.centre + ((hex.width + hex.pad) / 2));
                        // Are we the last hexagon on a new row with minWidth > 1?
                        if(i === len - 2 && hex.min > 1)
                        {
                            x = (( hex.wrapWidth / 2) - ( hex.width / 2)) + (hex.pad * (1 + Math.floor(hex.max / 2)));
                        }
                        col = 0;
                        full_row = true;
                    }
                    hex.wrapHeight = y;
                }
                hex.wrapHeight += full_row ? hex.gap : hex.height;
            },

            /**
             * Draw hexagons
             * @param {String} where Selector string
             * @param {Object} hex Hexagon definintion
             * @param {Array} items Items to render
             * @param {String} divClass Class to assign to wrapper DIV
             * @param {function} divItems Allow caller to render specific DIV contents, should
             * return what it was passed.
             * @param {function} pathAttrs Allow caller to set specific attribtues on rendered Hexagon,
             * should return what it was passed.
             * @param {function} svgItems Allow caller to add to SVG, e.g. patterns, should return
             * what it was passed.
             */
            drawHexagons : function(where, hex, items, divClass, divItems, pathAttrs, svgItems)
            {
                // Clear target
                where.empty();

                // Create D3 enter for each item
                var plot = d3.select(where[0]).selectAll("div")
                        .data(items).enter();

                // Create div for each item and position
                var obj = {};
                obj[divClass] = true;
                var plotdiv = plot.append("div")
                            .classed(obj)
                            .style('top', function(d) { return d.y+'px'; })
                            .style('left', function(d) { return d.x+'px'; })
                            .style('position', 'absolute')
                            .style('z-index', '1')
                            .style('width', hex.width + 'px')
                            .style('height', hex.height + 'px');

               // Call user supplied function to add other items
               plotdiv = divItems(plotdiv);

               // Basic D3 Line function
               var lineFunction = d3.svg.line()
                                 .x(function(d) { return d.x; })
                                 .y(function(d) { return d.y; })
                                 .interpolate("linear");

               // Create and position SVG canvas for each Hexagon
               var hexplot = plot.append('div')
                            .style('top', function(d) { return d.y+'px'; })
                            .style('left', function(d) { return d.x+'px'; })
                            .style('position', 'absolute')
                            .style('z-index', '0')
                            .style('width', hex.width + 'px')
                            .style('height', (Math.ceil(hex.height)) + 'px')
                            .append('svg');

               // Call user supplied function to add specific items to SVG
               hexplot = svgItems(hexplot);
               hexplot.attr("viewBox", "0 0 " + hex.width + " " + (Math.ceil(hex.height)));

               // Plot Hexagon
               var hexPath = hexplot.append("path")
                                .attr("d", lineFunction(hex.hexagon));

               // Call user supplied function to add specific attributes to the Hexagon
               hexPath = pathAttrs(hexPath);
            },

            /**
             * Calculate and position all hexagons for the supplied items
             * @param {String} where Selector string
             * @param {Number} _pad Width between hexagons
             * @param {Number} _width Width of hexagon
             * @param {Number} _aspect How much to scale the sides
             * @param {Array} items Items to render
             * @param {Boolean} equalRows - do we have the same number of hexagons in each row?
             * @returns {Object} Hexagon definition
             */
            calculateAndPositionHexagons : function(where, _pad, _width, _aspect, items, equalRows)
            {
                // Calculate
                var hex = this.calculateHexagons(where, _pad, _width, _aspect, items.length, equalRows);
                this.setPositions(hex, items);
                // Position and wrapper height
                where.height(hex.wrapHeight);
                // Return Hexagon info
                return hex;
            }
        };
    }
);
<commit_msg>Fix resize bug that causes the browser to hang<commit_after>/**
 * Library to render a series of hexagons from arbitrary data
 * Requires jQuery and D3
 */
define([ 'jquery','honest/d3.min'],
    function($, d3)
    {
        // NOTE this could be encapsulated further (into a Class) but all use cases
        // not yet clear. It doesn't make any functional difference.
        return {

            /**
             * Calculate all the vital information about a Hexagon
             * @param {Number} _width Width of hexagon
             * @param {Number} _aspect How much to scale the sides
             * @param {Object} _offset Offset from origin {x,y}
             * @returns {Object} Hexagon definition
             */
            calculateHexagon: function(_width, _aspect, _offset)
            {
                var _offset = _offset || {x:0,y:0};
                // Side length
                var _side = (_width * Math.sqrt(3) / 4) * _aspect;
                // Gap betwwen rows
                var _gap = (_width / 4) * _aspect;
                // Height of hexagon
                var _height = _side + ((_width / 2) * _aspect);
                // Hexagon lines for D3 line generator
                var _hexagon = [{x : _width / 2, y : 0},
                                {x : 0,          y : _gap},
                                {x : 0,          y : _gap + _side},
                                {x : _width / 2, y : _height},
                                {x : _width,     y : _gap + _side},
                                {x : _width,     y : _gap},
                                {x : _width / 2, y : 0}];
                for(var i = 0; i < 7; i++)
                {
                    _hexagon[i].x += _offset.x;
                    _hexagon[i].y += _offset.y;
                }
                return {side:_side, gap:_gap, height:_height, hexagon:_hexagon};
            },

            /**
             * Calculate all the vital information about the hexagons we are plotting
             * @param {String} where Selector string
             * @param {Number} _pad Width between hexagons
             * @param {Number} _width Width of hexagon
             * @param {Number} _aspect How much to scale the sides
             * @param {Array} items Items to render
             * @param {Boolean} equalRows - do we have the same number of hexagons in each row?
             * @returns {Object} Hexagons definition
             */
            calculateHexagons : function(where, _pad, _width, _aspect, items, equalRows)
            {
                if (where.length == 0)
                    return;

                // Internal page width function
                var pageWidth = function()
                {
                    return where.width();
                };

                // Work our hexagon variables
                var _hexagon = this.calculateHexagon(_width, _aspect);
                // Side length
                var _side = _hexagon.side;
                // Gap betwwen rows
                var _gap = _hexagon.gap;
                // Height of hexagon
                var _height = _hexagon.height;
                // Hexagon lines for D3 line generator
                var hexagon = _hexagon.hexagon;

                if(equalRows)
                {
                    // Maximum number of columns
                    var _maxCols = Math.ceil(pageWidth() / (_width + _pad)) - 1;
                    // Minimum number of columns
                    var _minCols = _maxCols;
                }
                else
                {
                    // Maximum number of columns
                    _maxCols = Math.max(1, Math.floor(pageWidth() / (_width + _pad))); // Ensure _maxCols is at least 1
                    // Minimum number of columns
                    _minCols = _maxCols === 1 ? 1 : _maxCols - 1;
                }
                var _rows = 0, _count = 0;
                var _wrapHeight = 0;
                // Determine total height and number of rows
                while(_count < items)
                {
                    _rows++;
                    _count += (_count % 2 === 0) ? _maxCols : _minCols;
                }

                // Centre hexagons horizontally
                if(!equalRows)
                {
                    var centre = (_maxCols === 1) ? (pageWidth() + (_pad * 2) - (_width * 1.5)) / 2 : (pageWidth() +(_pad * 2) - (_width * _maxCols)) / 2;
                    if(centre < 0)
                    {
                        centre = 0;
                    }
                }
                else
                {
                    centre = 0;
                }

               // Return all Hexagon info
               return {
                   pad: _pad,
                   width: _width,
                   aspect: _aspect,
                   side: _side,
                   gap: _gap,
                   height: _height,
                   wrapHeight: _wrapHeight + 2,
                   wrapWidth: pageWidth(),
                   min: _minCols,
                   max: _maxCols,
                   rows: _rows,
                   hexagon: hexagon,
                   centre: centre
               };
            },

            /**
             * Given a Hexagon 'hex/ set all items in the correct position
             * @param {Object from calculateHexagons} hex Hexagon info
             * @param {Array} items Items to render
             */
            setPositions : function(hex, items)
            {
                hex.wrapHeight = 0;
               // Update positions into questions
                var row = 0, col = 0, x = hex.centre, y = 0, full_row = false;
                for(var i = 0, len = items.length; i < len; i++)
                {
                    full_row = false;
                    items[i].x = x;
                    items[i].y = y;
                    // Increment
                    col++; x += hex.width + hex.pad;
                    // New row?
                    if(col >= (row % 2 === 0 ? hex.max : hex.min))
                    {
                        row++;
                        // Update X & Y
                        y += hex.height + hex.pad - hex.gap;
                        // X depends on even or odd
                        x = (row % 2 === 0 ? hex.centre : hex.centre + ((hex.width + hex.pad) / 2));
                        // Are we the last hexagon on a new row with minWidth > 1?
                        if(i === len - 2 && hex.min > 1)
                        {
                            x = (( hex.wrapWidth / 2) - ( hex.width / 2)) + (hex.pad * (1 + Math.floor(hex.max / 2)));
                        }
                        col = 0;
                        full_row = true;
                    }
                    hex.wrapHeight = y;
                }
                hex.wrapHeight += full_row ? hex.gap : hex.height;
            },

            /**
             * Draw hexagons
             * @param {String} where Selector string
             * @param {Object} hex Hexagon definintion
             * @param {Array} items Items to render
             * @param {String} divClass Class to assign to wrapper DIV
             * @param {function} divItems Allow caller to render specific DIV contents, should
             * return what it was passed.
             * @param {function} pathAttrs Allow caller to set specific attribtues on rendered Hexagon,
             * should return what it was passed.
             * @param {function} svgItems Allow caller to add to SVG, e.g. patterns, should return
             * what it was passed.
             */
            drawHexagons : function(where, hex, items, divClass, divItems, pathAttrs, svgItems)
            {
                // Clear target
                where.empty();

                // Create D3 enter for each item
                var plot = d3.select(where[0]).selectAll("div")
                        .data(items).enter();

                // Create div for each item and position
                var obj = {};
                obj[divClass] = true;
                var plotdiv = plot.append("div")
                            .classed(obj)
                            .style('top', function(d) { return d.y+'px'; })
                            .style('left', function(d) { return d.x+'px'; })
                            .style('position', 'absolute')
                            .style('z-index', '1')
                            .style('width', hex.width + 'px')
                            .style('height', hex.height + 'px');

               // Call user supplied function to add other items
               plotdiv = divItems(plotdiv);

               // Basic D3 Line function
               var lineFunction = d3.svg.line()
                                 .x(function(d) { return d.x; })
                                 .y(function(d) { return d.y; })
                                 .interpolate("linear");

               // Create and position SVG canvas for each Hexagon
               var hexplot = plot.append('div')
                            .style('top', function(d) { return d.y+'px'; })
                            .style('left', function(d) { return d.x+'px'; })
                            .style('position', 'absolute')
                            .style('z-index', '0')
                            .style('width', hex.width + 'px')
                            .style('height', (Math.ceil(hex.height)) + 'px')
                            .append('svg');

               // Call user supplied function to add specific items to SVG
               hexplot = svgItems(hexplot);
               hexplot.attr("viewBox", "0 0 " + hex.width + " " + (Math.ceil(hex.height)));

               // Plot Hexagon
               var hexPath = hexplot.append("path")
                                .attr("d", lineFunction(hex.hexagon));

               // Call user supplied function to add specific attributes to the Hexagon
               hexPath = pathAttrs(hexPath);
            },

            /**
             * Calculate and position all hexagons for the supplied items
             * @param {String} where Selector string
             * @param {Number} _pad Width between hexagons
             * @param {Number} _width Width of hexagon
             * @param {Number} _aspect How much to scale the sides
             * @param {Array} items Items to render
             * @param {Boolean} equalRows - do we have the same number of hexagons in each row?
             * @returns {Object} Hexagon definition
             */
            calculateAndPositionHexagons : function(where, _pad, _width, _aspect, items, equalRows)
            {
                // Calculate
                var hex = this.calculateHexagons(where, _pad, _width, _aspect, items.length, equalRows);
                this.setPositions(hex, items);
                // Position and wrapper height
                where.height(hex.wrapHeight);
                // Return Hexagon info
                return hex;
            }
        };
    }
);
<|endoftext|>


<commit_before>'use strict';

import React         from 'react/addons';
import {Link}        from 'react-router';
import DocumentTitle from 'react-document-title';

var AuthenticatedRouteMixin = require('../mixins/AuthenticatedRouteMixin');

var Profile = React.createClass({

    mixins: [AuthenticatedRouteMixin],

    render() {
        return (
            <DocumentTitle title="Profile">

Profile

            </DocumentTitle>
        );
    }
});

export default Profile;
<commit_msg>profile<commit_after>'use strict';

import React         from 'react/addons';
import {Link}        from 'react-router';
import DocumentTitle from 'react-document-title';

var AuthenticatedRouteMixin = require('../mixins/AuthenticatedRouteMixin');

var Profile = React.createClass({

    mixins: [AuthenticatedRouteMixin],

    render() {
        return (
            <DocumentTitle title="Profile">

Profile

Name {localStorage.getItem('email')}

Email {localStorage.getItem('email')}

            </DocumentTitle>
        );
    }
});

export default Profile;
<|endoftext|>