<commit_before>"use strict";

var
  Map = require("es6-map"),
  Set = require("es6-set"),
  parse = require("./lib/parse"),
  resolve = require("./resolve"),
  isCore = require("resolve").isCore;

var exportCache = new Map();

function ExportMap(settings) {
  this.settings = settings

  this.hasDefault = false;
  this.named = new Set();

  this.errors = [];
}

ExportMap.get = function (source, context) {

  var path = resolve(source, context)
  if (path == null) return null

  return ExportMap.for(path, context.settings)
}

ExportMap.for = function (path, settings) {
  var exportMap = exportCache.get(path)
  if (exportMap != null) return exportMap

  exportMap = ExportMap.parse(path, settings)

  exportCache.set(path, exportMap)

  // Object.freeze(exportMap);
  // Object.freeze(exportMap.named);

  return exportMap
}

ExportMap.parse = function (path, settings) {
  var m = new ExportMap(settings)

  if (isCore(path)) return m; // skip parsing

  try {
    var ast = parse(path);
  } catch (err) {
    m.errors.push(err);
    return m; // can't continue
  }

  ast.body.forEach(function (n) {
    m.captureDefault(n);
    m.captureAll(n, path);
    m.captureNamedDeclaration(n);
  });

  return m;
};

ExportMap.prototype.captureDefault = function (n) {
  if (n.type !== "ExportDefaultDeclaration") return;

  this.hasDefault = true;
};

ExportMap.prototype.captureAll = function (n, path) {
  if (n.type !== "ExportAllDeclaration") return

  var remotePath = resolve.relative(n.source.value, path)
  if (remotePath == null) return

  var remoteMap = ExportMap.for(remotePath, this.settings)

  remoteMap.named.forEach(function (name) { this.named.add(name) }.bind(this))
}

ExportMap.prototype.captureNamedDeclaration = function (n) {
  if (n.type !== "ExportNamedDeclaration") return;

  // capture declaration
  if (n.declaration != null)
    switch (n.declaration.type) {
      case "FunctionDeclaration":
      case "ClassDeclaration":
        this.named.add(n.declaration.id.name);
        break;
      case "VariableDeclaration":
        n.declaration.declarations.forEach(function (d) {
          this.named.add(d.id.name);
        }.bind(this));
        break;
  }

  // capture specifiers
  n.specifiers.forEach(function (s) {
    this.named.add(s.exported.name);
  }.bind(this));
};

module.exports = ExportMap.get;
<commit_msg>cleanup<commit_after>'use strict'

var
  Map = require('es6-map'), // eslint-disable-line no-native-reassign
  Set = require('es6-set'), // eslint-disable-line no-native-reassign
  parse = require('./lib/parse'),
  resolve = require('./resolve'),
  isCore = require('resolve').isCore

var exportCache = new Map()

function ExportMap(settings) {
  this.settings = settings

  this.hasDefault = false
  this.named = new Set()

  this.errors = []
}

ExportMap.get = function (source, context) {

  var path = resolve(source, context)
  if (path == null) return null

  return ExportMap.for(path, context.settings)
}

ExportMap.for = function (path, settings) {
  var exportMap = exportCache.get(path)
  if (exportMap != null) return exportMap

  exportMap = ExportMap.parse(path, settings)

  exportCache.set(path, exportMap)

  // Object.freeze(exportMap)
  // Object.freeze(exportMap.named)

  return exportMap
}

ExportMap.parse = function (path, settings) {
  var m = new ExportMap(settings)

  if (isCore(path)) return m // skip parsing

  try {
    var ast = parse(path)
  } catch (err) {
    m.errors.push(err)
    return m // can't continue
  }

  ast.body.forEach(function (n) {
    m.captureDefault(n)
    m.captureAll(n, path)
    m.captureNamedDeclaration(n)
  })

  return m
}

ExportMap.prototype.captureDefault = function (n) {
  if (n.type !== 'ExportDefaultDeclaration') return

  this.hasDefault = true
}

ExportMap.prototype.captureAll = function (n, path) {
  if (n.type !== 'ExportAllDeclaration') return

  var remotePath = resolve.relative(n.source.value, path)
  if (remotePath == null) return

  var remoteMap = ExportMap.for(remotePath, this.settings)

  remoteMap.named.forEach(function (name) { this.named.add(name) }.bind(this))
}

ExportMap.prototype.captureNamedDeclaration = function (n) {
  if (n.type !== 'ExportNamedDeclaration') return

  // capture declaration
  if (n.declaration != null) {
    switch (n.declaration.type) {
      case 'FunctionDeclaration':
      case 'ClassDeclaration':
        this.named.add(n.declaration.id.name)
        break
      case 'VariableDeclaration':
        n.declaration.declarations.forEach(function (d) {
          this.named.add(d.id.name)
        }.bind(this))
        break
    }
  }

  // capture specifiers
  n.specifiers.forEach(function (s) {
    this.named.add(s.exported.name)
  }.bind(this))
}

module.exports = ExportMap.get
<|endoftext|>


<commit_before>function getData(username){
    var url = `https://api.github.com/users/${username}/repos`
    return (
        fetch(url)
        .then(function(response) {
            return response.json()
        })
        .catch(function(ex) {
            console.log('parsing failed', ex)
        })
    )
}

var api = {
    getData: getData
}

export default api<commit_msg>helper to fetch followers<commit_after>function getRepos(username){
    var url = `https://api.github.com/users/${username}/repos`
    return (
        fetch(url)
        .then(function(response) {
            return response.json()
        })
        .catch(function(ex) {
            console.log('parsing failed', ex)
        })
    )
}

function getFollowers(username){
    var url = `https://api.github.com/users/${username}/followers`
    return (
        fetch(url)
        .then(function(response) {
            return response.json()
        })
        .catch(function(ex) {
            console.log('parsing failed', ex)
        })
    )
}

var api = {
    getRepos: getRepos,
    getFollowers: getFollowers,
}

export default api<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import update from 'immutability-helper';
import {Table} from 'react-bootstrap';
import TextField from '../common/components/TextField';
import TextArea from "../common/components/TextArea";
import SingleSelect from '../common/components/SingleSelect';
import CheckBox from '../common/components/CheckBox';
import SimpleList from '../common/components/SimpleList';
import {getMeritBadgeNames} from '../common/redux/referenceActions';
import {getMeritBadgeByName, updateCourse, getCourseById, resetCurrentCourse, resetCurrentMeritBadge} from './adminActions';
import {validate} from '../common/util/validation';
import validationConfig from './ClassValidationConfig';

const recommendedLengthChoices = [
    {value: '1 hour', label: '1 hour'},
    {value: '2 hours', label: '2 hours'},
    {value: '3 hours', label: '3 hours'},
    {value: '4 hours', label: '4 hours'},
    {value: 'more than 4 hours', label: 'more than 4 hours'}
];

const recommendedSizeChoices = [
    {value: '2-6 students', label: '2-6 students'},
    {value: '4-8 students', label: '4-8 students'},
    {value: '6-12 students', label: '6-12 students'},
    {value: '10-20 students', label: '10-20 students'},
    {value: 'more than 20 students', label: 'more than 20 students'}
];

const INITIAL_STATE = {
    meritBadge: '',
    recommendedLength: '',
    recommendedSize: '',
    notes: '',
    counselors: ['Joe Smith'],
    preRequisites: {}
};

class EditCourse extends React.Component {

    constructor(){
        super();
        this.state = INITIAL_STATE;
        this.handleChange = this.handleChange.bind(this);
        this.handlePreReqChange = this.handlePreReqChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleAddMe = this.handleAddMe.bind(this);
        this.handleRemoveMe = this.handleRemoveMe.bind(this);
    }

    componentDidMount() {
        getMeritBadgeNames();
        if(this.props.match.params.courseId){
            getCourseById(this.props.match.params.courseId);
        }
    };

    componentWillUnmount(){
        resetCurrentCourse();
        resetCurrentMeritBadge();
    }

    currentCourseIsChanging(nextProps){
        return nextProps.admin.currentCourse !== this.props.admin.currentCourse;
    }

    componentWillReceiveProps(nextProps){
        if(this.currentCourseIsChanging(nextProps)){
            const courseLocalCopy = Object.assign({}, nextProps.admin.currentCourse);
            courseLocalCopy.preRequisites = this.convertStringArrayToTrueObjectProps(courseLocalCopy.preRequisites);
            this.setState(courseLocalCopy);
        }
    };

    handleAddMe(){
        const newCounselors = this.state.counselors.slice();
        newCounselors.push("Jerry Moore");
        this.setState({counselors: newCounselors});
    }

    handleRemoveMe(){
        const index = this.state.counselors.indexOf("Jerry Moore");
        let newCounselors = this.state.counselors.slice();
        if(index !== -1){
            newCounselors.splice(index, 1);
        }
        this.setState({counselors: newCounselors})
    }

    handlePreReqChange(field, value) {
        const newState = update(this.state, {preRequisites: {[field]: {$set: value}}});
        this.setState(newState);
    };

    handleChange(field, value) {
        this.setState({[field]: value});

        if(field === 'meritBadge' && value !== this.state.meritBadge){
            this.setState({preRequisites: {}});
            getMeritBadgeByName(value);
        }
    };

    handleSubmit(event) {
        event.preventDefault();
        const report = validate(this.state, validationConfig);
        if(report.allValid){
            const badge = this.props.admin.currentMeritBadge || {};
            const prerequisiteList = this.convertTrueObjectPropsToStringArray(this.state.preRequisites);
            const newCourse = Object.assign(
                {},
                this.state,
                    {
                        eagleRequired: badge.eagleRequired,
                        preRequisites: prerequisiteList,
                        numRequirements: badge.requirements.length,
                        imageUrl: badge.imageUrl
                    }
            );
            updateCourse(newCourse);
            this.setState({ displayErrors: false });
            this.props.history.push('/admin/courses'); // go back to courses screen
        } else {
            this.setState({ displayErrors: true });
        }
        this.setState({errorReport: report});
    };

    // TODO: get notes working!!!
    showSubRequirement(req, sub){
        return (
            <tr key={`${req.number}${sub.part}`}>

                    <CheckBox key={req.number + sub.part} propertyName={`item_${req.number}${sub.part}`} propertyValue={this.state.preRequisites[`item_${req.number}${sub.part}`]}
                              displayName=''
                              changeHandler={this.handlePreReqChange}/>

                    {`${sub.part}.  ${sub.text}`}

        );
    };

    showRequirement(req){
        const checkbox = req.subRequirements.length === 0
            ? <CheckBox key={req.number} propertyName={`item_${req.number}`} propertyValue={this.state.preRequisites[`item_${req.number}`]}
                        displayName=''
                        changeHandler={this.handlePreReqChange}/>
            : null;
        return (

                    {checkbox}

                    {`${req.number}.  ${req.description}`}

        );
    };

    showAllRequirements(requirements){

        const requirementList = [];
        _.each(requirements, req => {
            requirementList.push(this.showRequirement(req));
            requirementList.push(
                _.map(req.subRequirements, sub => { return (this.showSubRequirement(req, sub))})
            );
        });

        if(requirementList.length > 0){
            return (

                        Pre-Requisite
                        Requirement

                    {
                        requirementList
                    }

            );
        } else {
            return null;
        }
    };

    convertTrueObjectPropsToStringArray(object){
        const trueObjectProps = [];
        _.forOwn(object, function(value, field) {
            if(value){
                trueObjectProps.push(field);
            }
        });
        return _.map(trueObjectProps, preReq => preReq.replace('item_', '')).sort();
    }

    convertStringArrayToTrueObjectProps(array){
        const itemArray = _.map(array, item => `item_${item}`);
        const trueObjectProps = {};
        itemArray.forEach( item => trueObjectProps[item] = true);
        return trueObjectProps;
    }

    render(){

        const meritBadgeChoices = this.props.reference.meritBadgeNames.map( item => {return({value: item.name, label: item.name})});

        const classInfo = this.state;

        const requirements = (
            this.props.admin.currentMeritBadge
            && this.props.admin.currentMeritBadge.requirements) || [];

        const prerequisiteList = this.convertTrueObjectPropsToStringArray(this.state.preRequisites).join(', ');

        const index = this.state.counselors.indexOf("Jerry Moore");
        let teachingAlready = false;
        if(index !== -1){
            teachingAlready = true;
        }

        return (

                        <form onSubmit={this.handleSubmit} noValidate className={this.state.displayErrors ? 'displayErrors' : ''} >

Edit Course

                                <SingleSelect propertyName='meritBadge' propertyValue={classInfo.meritBadge} displayName='Merit Badge' options={meritBadgeChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                <SingleSelect propertyName='recommendedLength' propertyValue={classInfo.recommendedLength} displayName='Recommended Class Length' options={recommendedLengthChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                <SingleSelect propertyName='recommendedSize' propertyValue={classInfo.recommendedSize} displayName='Recommended Number of Students' options={recommendedSizeChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                <TextArea propertyName='notes' propertyValue={classInfo.notes} displayName='Notes' errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                        <SimpleList propertyName='counselors' displayName='Counselors' dataList={classInfo.counselors}/>

                                        <button type="button" className="btn btn-sm" disabled={teachingAlready} onClick={this.handleAddMe}>Add Me</button>

                                        <button type="button" className="btn btn-sm" onClick={this.handleRemoveMe}>Remove Me</button>

Choose Pre-requisites

                                <TextField disabled={true} propertyName='prerequisiteList' propertyValue={prerequisiteList} displayName='Pre-Requisites'/>

                                <button type="submit" className="btn btn-success btn-lg btn-block">Save</button>

                            {
                                this.showAllRequirements(requirements)
                            }
                        </form>

        );
    }

};

const mapStateToProps = ({reference, admin}) => {
    return {reference, admin};
};

export default withRouter(connect(mapStateToProps)(EditCourse));<commit_msg>- Edit Course Screen: add buttons to select all or none for pre-reqs<commit_after>import _ from 'lodash';
import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import update from 'immutability-helper';
import {Table} from 'react-bootstrap';
import TextField from '../common/components/TextField';
import TextArea from "../common/components/TextArea";
import SingleSelect from '../common/components/SingleSelect';
import CheckBox from '../common/components/CheckBox';
import SimpleList from '../common/components/SimpleList';
import {getMeritBadgeNames} from '../common/redux/referenceActions';
import {getMeritBadgeByName, updateCourse, getCourseById, resetCurrentCourse, resetCurrentMeritBadge} from './adminActions';
import {validate} from '../common/util/validation';
import validationConfig from './ClassValidationConfig';

const recommendedLengthChoices = [
    {value: '1 hour', label: '1 hour'},
    {value: '2 hours', label: '2 hours'},
    {value: '3 hours', label: '3 hours'},
    {value: '4 hours', label: '4 hours'},
    {value: 'more than 4 hours', label: 'more than 4 hours'}
];

const recommendedSizeChoices = [
    {value: '2-6 students', label: '2-6 students'},
    {value: '4-8 students', label: '4-8 students'},
    {value: '6-12 students', label: '6-12 students'},
    {value: '10-20 students', label: '10-20 students'},
    {value: 'more than 20 students', label: 'more than 20 students'}
];

const INITIAL_STATE = {
    meritBadge: '',
    recommendedLength: '',
    recommendedSize: '',
    notes: '',
    counselors: ['Joe Smith'],
    preRequisites: {}
};

class EditCourse extends React.Component {

    constructor(){
        super();
        this.state = INITIAL_STATE;
        this.handleChange = this.handleChange.bind(this);
        this.handlePreReqChange = this.handlePreReqChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleAddMe = this.handleAddMe.bind(this);
        this.handleRemoveMe = this.handleRemoveMe.bind(this);
        this.selectAllPrereqs = this.selectAllPrereqs.bind(this);
        this.unselectAllPrereqs = this.unselectAllPrereqs.bind(this);
    }

    componentDidMount() {
        getMeritBadgeNames();
        if(this.props.match.params.courseId){
            getCourseById(this.props.match.params.courseId);
        }
    };

    componentWillUnmount(){
        resetCurrentCourse();
        resetCurrentMeritBadge();
    }

    currentCourseIsChanging(nextProps){
        return nextProps.admin.currentCourse !== this.props.admin.currentCourse;
    }

    componentWillReceiveProps(nextProps){
        if(this.currentCourseIsChanging(nextProps)){
            const courseLocalCopy = Object.assign({}, nextProps.admin.currentCourse);
            courseLocalCopy.preRequisites = this.convertStringArrayToTrueObjectProps(courseLocalCopy.preRequisites);
            this.setState(courseLocalCopy);
        }
    };

    handleAddMe(){
        const newCounselors = this.state.counselors.slice();
        newCounselors.push("Jerry Moore");
        this.setState({counselors: newCounselors});
    }

    handleRemoveMe(){
        const index = this.state.counselors.indexOf("Jerry Moore");
        let newCounselors = this.state.counselors.slice();
        if(index !== -1){
            newCounselors.splice(index, 1);
        }
        this.setState({counselors: newCounselors})
    }

    selectAllPrereqs(){
        const requirements = (
            this.props.admin.currentMeritBadge
            && this.props.admin.currentMeritBadge.requirements) || [];

        const newPrereqs = {};
        _.each(requirements, req => {
            if(req.subRequirements.length === 0){
                newPrereqs[`item_${req.number}`] = true;
            }
            _.each(req.subRequirements, sub => {
                newPrereqs[`item_${req.number}${sub.part}`] = true;
            });
        });
        this.setState({preRequisites: newPrereqs});
    };

    unselectAllPrereqs(){
        this.setState({preRequisites: {}});
    };

    handlePreReqChange(field, value) {
        const newState = update(this.state, {preRequisites: {[field]: {$set: value}}});
        this.setState(newState);
    };

    handleChange(field, value) {
        this.setState({[field]: value});

        if(field === 'meritBadge' && value !== this.state.meritBadge){
            this.setState({preRequisites: {}});
            getMeritBadgeByName(value);
        }
    };

    handleSubmit(event) {
        event.preventDefault();
        const report = validate(this.state, validationConfig);
        if(report.allValid){
            const badge = this.props.admin.currentMeritBadge || {};
            const prerequisiteList = this.convertTrueObjectPropsToStringArray(this.state.preRequisites);
            const newCourse = Object.assign(
                {},
                this.state,
                    {
                        eagleRequired: badge.eagleRequired,
                        preRequisites: prerequisiteList,
                        numRequirements: badge.requirements.length,
                        imageUrl: badge.imageUrl
                    }
            );
            updateCourse(newCourse);
            this.setState({ displayErrors: false });
            this.props.history.push('/admin/courses'); // go back to courses screen
        } else {
            this.setState({ displayErrors: true });
        }
        this.setState({errorReport: report});
    };

    showPrereqButtons(requirements) {
        if(requirements.length > 0){
            return (

                        <button type="button" className="btn btn-sm" onClick={this.selectAllPrereqs}>Select All</button>

                        <button type="button" className="btn btn-sm" onClick={this.unselectAllPrereqs}>Unselect All</button>

            );
        } else {
            return null;
        }
    };

    // TODO: get notes working!!!
    showSubRequirement(req, sub){
        return (
            <tr key={`${req.number}${sub.part}`}>

                    <CheckBox key={req.number + sub.part} propertyName={`item_${req.number}${sub.part}`} propertyValue={this.state.preRequisites[`item_${req.number}${sub.part}`]}
                              displayName=''
                              changeHandler={this.handlePreReqChange}/>

                    {`${sub.part}.  ${sub.text}`}

        );
    };

    showRequirement(req){
        const checkbox = req.subRequirements.length === 0
            ? <CheckBox key={req.number} propertyName={`item_${req.number}`} propertyValue={this.state.preRequisites[`item_${req.number}`]}
                        displayName=''
                        changeHandler={this.handlePreReqChange}/>
            : null;
        return (

                    {checkbox}

                    {`${req.number}.  ${req.description}`}

        );
    };

    showAllRequirements(requirements){

        const requirementList = [];
        _.each(requirements, req => {
            requirementList.push(this.showRequirement(req));
            requirementList.push(
                _.map(req.subRequirements, sub => { return (this.showSubRequirement(req, sub))})
            );
        });

        if(requirementList.length > 0){
            return (

                        Pre-Requisite
                        Requirement

                    {
                        requirementList
                    }

            );
        } else {
            return null;
        }
    };

    convertTrueObjectPropsToStringArray(object){
        const trueObjectProps = [];
        _.forOwn(object, function(value, field) {
            if(value){
                trueObjectProps.push(field);
            }
        });
        return _.map(trueObjectProps, preReq => preReq.replace('item_', '')).sort();
    }

    convertStringArrayToTrueObjectProps(array){
        const itemArray = _.map(array, item => `item_${item}`);
        const trueObjectProps = {};
        itemArray.forEach( item => trueObjectProps[item] = true);
        return trueObjectProps;
    }

    render(){

        const meritBadgeChoices = this.props.reference.meritBadgeNames.map( item => {return({value: item.name, label: item.name})});

        const classInfo = this.state;

        const requirements = (
            this.props.admin.currentMeritBadge
            && this.props.admin.currentMeritBadge.requirements) || [];

        const prerequisiteList = this.convertTrueObjectPropsToStringArray(this.state.preRequisites).join(', ');

        const index = this.state.counselors.indexOf("Jerry Moore");
        let teachingAlready = false;
        if(index !== -1){
            teachingAlready = true;
        }

        return (

                        <form onSubmit={this.handleSubmit} noValidate className={this.state.displayErrors ? 'displayErrors' : ''} >

Edit Course

                                <SingleSelect propertyName='meritBadge' propertyValue={classInfo.meritBadge} displayName='Merit Badge' options={meritBadgeChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                <SingleSelect propertyName='recommendedLength' propertyValue={classInfo.recommendedLength} displayName='Recommended Class Length' options={recommendedLengthChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                <SingleSelect propertyName='recommendedSize' propertyValue={classInfo.recommendedSize} displayName='Recommended Number of Students' options={recommendedSizeChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                <TextArea propertyName='notes' propertyValue={classInfo.notes} displayName='Notes' errors={this.state.errorReport} changeHandler={this.handleChange}/>

                                        <SimpleList propertyName='counselors' displayName='Counselors' dataList={classInfo.counselors}/>

                                        <button type="button" className="btn btn-sm" disabled={teachingAlready} onClick={this.handleAddMe}>Add Me</button>

                                        <button type="button" className="btn btn-sm" onClick={this.handleRemoveMe}>Remove Me</button>

Choose Pre-requisites

                                <TextField disabled={true} propertyName='prerequisiteList' propertyValue={prerequisiteList} displayName='Pre-Requisites'/>

                                <button type="submit" className="btn btn-success btn-lg btn-block">Save</button>

                            {
                                this.showPrereqButtons(requirements)
                            }

                            {
                                this.showAllRequirements(requirements)
                            }
                        </form>

        );
    }

};

const mapStateToProps = ({reference, admin}) => {
    return {reference, admin};
};

export default withRouter(connect(mapStateToProps)(EditCourse));<|endoftext|>


<commit_before>'use strict';

angular.module('casusMIT3.index', ['ngRoute','AdalAngular'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/index', {
    templateUrl: 'index/index.html',
    controller: 'indexCtrl',
    requireADLogin: true
  });
}])

.controller('indexCtrl', ['adalAuthenticationService', '$http', '$scope', function(adalService,$http,$scope) {

  $scope.reports;
  test();

  function test(){
    $http.get('https://api.powerbi.com/beta/myorg/reports')
      .then(function (response) {
        $scope.reports = response.data.value;
        $scope.selectedReport = $scope.reports[0].embedUrl;
        console.log("het is gelukt");
      });

}

  function tst() {
    var iframe = document.getElementById("report");
    iframe.addEventListener("load", function () {
      var token = adal.getCachedToken("https://analysis.windows.net/powerbi/api");
      iframe.contentWindow.postMessage(JSON.stringify({
            action: "loadReport",
            accesToken: token
          }),
          "*");
    });
  }

}]);<commit_msg>Added Power BI Data factory<commit_after>'use strict';

angular.module('casusMIT3.index', ['ngRoute','AdalAngular'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/index', {
    templateUrl: 'index/index.html',
    controller: 'indexCtrl',
    requireADLogin: true
  });
}])

.controller('indexCtrl', ['adalAuthenticationService', '$http', '$scope', function(adalService,$http,$scope) {

  $scope.reports;
  test();

  function test(){
    $http.get('https://api.powerbi.com/beta/myorg/reports')
      .then(function (response) {
        console.log("het is gelukt");
        $scope.reports = response.data.value;
        $scope.selectedReport = $scope.reports[0].embedUrl;
        console.log("het is gelukt");
      });

}

  function tst() {
    var iframe = document.getElementById("report");
    iframe.addEventListener("load", function () {
      var token = adal.getCachedToken("https://analysis.windows.net/powerbi/api");
      iframe.contentWindow.postMessage(JSON.stringify({
            action: "loadReport",
            accesToken: token
          }),
          "*");
    });
  }

}]);<|endoftext|>


<commit_before>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('kinghunt.services', []).
  value('version', '0.1.0').
  value('credits', [
    {name: 'chess.js', url: 'https://github.com/jhlywa/chess.js'},
    {name: 'chessboardjs', url: 'https://github.com/oakmac/chessboardjs'},
    {name: 'Yet Another Chess Problem Database', url: 'http://www.yacpdb.org/'}
  ]).
  factory('gameSvc', [function() {
    var gameObj = (function() {
      var game;

      return {
        getGame: function() {
          if  (!game) {
            game = new Chess();
          }
          return game;
        },

        getMovesRemaining: function(goalMoves) {
          // TODO: at present, only for "w to play & mate" scenarios; expand for more scenarios
          var fenObj = gameObj.fenToObject(game.fen());
          var remaining = goalMoves - fenObj.fullmove;
          return (fenObj.turn === 'w') ? remaining + 1 : remaining;
        },

        getStatus: function(goalMoves) {
          var moveColor = game.turn();
          var isMate = game.in_checkmate();
          var remaining = gameObj.getMovesRemaining(goalMoves);
          var status = {
            turn: moveColor,
            situation: "",
            progress: ""
          };

          if (isMate) {
            status.situation = ' checkmated';
          } else if (game.in_draw()) {
            status.situation = ' Drawn';
            status.progress = 'FAILED';
          } else if (game.in_check() === true) {
            status.situation = ' is in check';
          } else {
            status.situation = ' to move';
          }

          if (isMate && remaining >= 0) {
            status.progress = "SOLVED";
          } else if (remaining < 1) {
            status.progress = "FAILED";
          } else {
            status.progress = "(" + remaining +  " to go)";
          }
          return status;
        },

        isPromotable: function(source, target, pce, newPos, oldPos, colorMoving) {
          var color = pce.substr(0, 1);
          var piece = pce.substr(1);
          var fromFile = source.charCodeAt(0);
          var toFile = target.charCodeAt(0);
          var fromRank = source.substr(1);
          var toRank = target.substr(1);

          var isToLastRank = (color === 'b') ?
              fromRank === "2" && toRank === "1" :
              fromRank === "7" && toRank === "8";

          // there must be an opposing piece on the landing square, and it must be one file over
          function isPawnCapture() {
            var landingPiece = oldPos[target];
            var diffFile = Math.abs(fromFile - toFile) === 1;
            return landingPiece && landingPiece.substr(0, 1) !== color && diffFile;
          }

          return piece === 'P' && isToLastRank && ((fromFile === toFile) || isPawnCapture());
        },

        promote: function(scope, moveCfg, color) {
          var promise = scope.overlay.open(color);
          promise.then(function(piece) {
            var move;
            moveCfg.promotion = piece;
            move = game.move(moveCfg);
            // illegal move
            if (move === null) {
              game.undo();
              return 'snapback';
            }

            scope.board.position(gameObj.fenToObject(game.fen()).position);
            scope.setStatus(gameObj.getStatus(scope.goalMoves));
          });
        },

        getBoardConfig: function(scope) {
          return {
            position: scope.problem.fen,
            draggable: true,
            onDragStart: function(source, piece, position, orientation) {
              var turn = game.turn();
              if (game.game_over() === true ||
                  (turn === 'w' && piece.search(/^b/) === 0) ||
                  (turn === 'b' && piece.search(/^w/) === 0)) {
                return false;
              }
            },
            onDrop: function(source, target, piece, newPos, oldPos, colorMoving) {
              var moveCfg = {
                from: source,
                to: target
              };

              var move;

              if (gameObj.isPromotable(source, target, piece, newPos, oldPos, colorMoving)) {
                gameObj.promote(scope, moveCfg, piece.charAt(0));
              } else {
                // TODO: DRY this up
                move = game.move(moveCfg);
                // illegal move
                if (move === null) {
                  return 'snapback';
                }

                scope.setStatus(gameObj.getStatus(scope.goalMoves));
                scope.$apply();
              }
            },

            onSnapbackEnd: function() {
              scope.board.position(game.fen());
            }
          };
        },

        fenToObject: function(fen) {
          var parts = fen.split(/\s+/);
          return {
            position: parts[0],
            turn: parts[1] || 'w',
            castle: parts[2] || '-',
            enpassant: parts[3] || '-',
            halfmove: parts[4] || 0,
            fullmove: parts[5] || 1
          };
        }
      };
    }());

    return gameObj;
  }]).
  factory('storageSvc', ['$window', '$q', function($window, $q) {
    var request = $window.indexedDB.open("KingHunt");
    var db;
    var storageSvc;
    var readyDfd = $q.defer();
    var readyPromise = readyDfd.promise;

    // initialization
    request.onerror = function(event) {
      readyDfd.reject();
    };
    request.onsuccess = function(event) {
      db = request.result;
      readyDfd.resolve();
    };
    request.onupgradeneeded = function(evt) {};

    storageSvc = {
      ready: function(fn) {
        return readyPromise.then(fn);
      },

      filterSolved: function(value, solvedProblems) {
        var solvedIds;
        var dfd = $q.defer();
        if (value) { // if true, we want to filter out solved problems
          solvedIds = Object.keys(solvedProblems);
        } else { // otherwise, return the whole schmear

        }
        return dfd.promise;
      },

      getBook: function() {

      },

      setBook: function(book) {

      },

      getSolved: function(id) {

      },

      markSolved: function(id, value) {

      }
    };

    // CRUD

    return storageSvc;
  }]).
  factory("bookSvc", ['storageSvc', function($window, $q) {

    var bookSvc = {};
    var book = {};
    var solved = {};
    var skipSolved = false;

    bookSvc =  {

      getFenById: function(id) {
        var problems = book.problems;
        var i, flen;
        for (i = 0, flen = problems.length; i < flen; i++) {
          if (problems[i].id === id) {
            return problems[i];
          }
        }
      },

      getProblems: function() {
        return book.problems || [];
      },

      getNext: function(id) {
        var problems = book.problems;
        var i, flen;
        for (i = 0, flen = problems.length; i < flen; i++) {
          if (problems[i].id === id) {
            return (problems[i + 1]) ? problems[i + 1] : null;
          }
        }
      },

      getPrev: function(id) {
        var problems = book.problems;
        var i, flen;
        for (i = 0, flen = problems.length; i < flen; i++) {
          if (problems[i].id === id) {
            return (problems[i - 1]) ? problems[i - 1] : null;
          }
        }
      },

      setSkipSolved: function(value, $scope) {
        skipSolved = value;
        storageSvc.filterSolved(value, solved).then(function() {
          $scope.$apply();
        });
      },

      getSkipSolved: function() {
        return skipSolved;
      },

      toggleSkipSolved: function() {
        skipSolved = !skipSolved;
      },

      setBook: function(newBook) {
        book = newBook;
        // $scope.$apply();
      },

      // TODO: unstub; move to indexedDB
      loadSolved: function(s) {
        solved = s;
        // $scope.$apply();
      },

      isSolved: function(id) {
        return solved[id];
      },

      // TODO: unstub
      markSolved: function(id, value) {
        if (value) { solved[id] = value; }
        else { delete solved[id]; }
      }

    }; // bookSvc

    return bookSvc;
  }]);

<commit_msg>major rewriting still going on--going asynch for storage<commit_after>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('kinghunt.services', []).
  value('version', '0.1.0').
  value('credits', [
    {name: 'chess.js', url: 'https://github.com/jhlywa/chess.js'},
    {name: 'chessboardjs', url: 'https://github.com/oakmac/chessboardjs'},
    {name: 'Yet Another Chess Problem Database', url: 'http://www.yacpdb.org/'}
  ]).
  factory('gameSvc', [function() {
    var gameObj = (function() {
      var game;

      return {
        getGame: function() {
          if  (!game) {
            game = new Chess();
          }
          return game;
        },

        getMovesRemaining: function(goalMoves) {
          // TODO: at present, only for "w to play & mate" scenarios; expand for more scenarios
          var fenObj = gameObj.fenToObject(game.fen());
          var remaining = goalMoves - fenObj.fullmove;
          return (fenObj.turn === 'w') ? remaining + 1 : remaining;
        },

        getStatus: function(goalMoves) {
          var moveColor = game.turn();
          var isMate = game.in_checkmate();
          var remaining = gameObj.getMovesRemaining(goalMoves);
          var status = {
            turn: moveColor,
            situation: "",
            progress: ""
          };

          if (isMate) {
            status.situation = ' checkmated';
          } else if (game.in_draw()) {
            status.situation = ' Drawn';
            status.progress = 'FAILED';
          } else if (game.in_check() === true) {
            status.situation = ' is in check';
          } else {
            status.situation = ' to move';
          }

          if (isMate && remaining >= 0) {
            status.progress = "SOLVED";
          } else if (remaining < 1) {
            status.progress = "FAILED";
          } else {
            status.progress = "(" + remaining +  " to go)";
          }
          return status;
        },

        isPromotable: function(source, target, pce, newPos, oldPos, colorMoving) {
          var color = pce.substr(0, 1);
          var piece = pce.substr(1);
          var fromFile = source.charCodeAt(0);
          var toFile = target.charCodeAt(0);
          var fromRank = source.substr(1);
          var toRank = target.substr(1);

          var isToLastRank = (color === 'b') ?
              fromRank === "2" && toRank === "1" :
              fromRank === "7" && toRank === "8";

          // there must be an opposing piece on the landing square, and it must be one file over
          function isPawnCapture() {
            var landingPiece = oldPos[target];
            var diffFile = Math.abs(fromFile - toFile) === 1;
            return landingPiece && landingPiece.substr(0, 1) !== color && diffFile;
          }

          return piece === 'P' && isToLastRank && ((fromFile === toFile) || isPawnCapture());
        },

        promote: function(scope, moveCfg, color) {
          var promise = scope.overlay.open(color);
          promise.then(function(piece) {
            var move;
            moveCfg.promotion = piece;
            move = game.move(moveCfg);
            // illegal move
            if (move === null) {
              game.undo();
              return 'snapback';
            }

            scope.board.position(gameObj.fenToObject(game.fen()).position);
            scope.setStatus(gameObj.getStatus(scope.goalMoves));
          });
        },

        getBoardConfig: function(scope) {
          return {
            position: scope.problem.fen,
            draggable: true,
            onDragStart: function(source, piece, position, orientation) {
              var turn = game.turn();
              if (game.game_over() === true ||
                  (turn === 'w' && piece.search(/^b/) === 0) ||
                  (turn === 'b' && piece.search(/^w/) === 0)) {
                return false;
              }
            },
            onDrop: function(source, target, piece, newPos, oldPos, colorMoving) {
              var moveCfg = {
                from: source,
                to: target
              };

              var move;

              if (gameObj.isPromotable(source, target, piece, newPos, oldPos, colorMoving)) {
                gameObj.promote(scope, moveCfg, piece.charAt(0));
              } else {
                // TODO: DRY this up
                move = game.move(moveCfg);
                // illegal move
                if (move === null) {
                  return 'snapback';
                }

                scope.setStatus(gameObj.getStatus(scope.goalMoves));
                scope.$apply();
              }
            },

            onSnapbackEnd: function() {
              scope.board.position(game.fen());
            }
          };
        },

        fenToObject: function(fen) {
          var parts = fen.split(/\s+/);
          return {
            position: parts[0],
            turn: parts[1] || 'w',
            castle: parts[2] || '-',
            enpassant: parts[3] || '-',
            halfmove: parts[4] || 0,
            fullmove: parts[5] || 1
          };
        }
      };
    }());

    return gameObj;
  }]).
  factory('storageSvc', ['$window', '$q', function($window, $q) {
    var request = $window.indexedDB.open("KingHunt");
    var db;
    var storageSvc;
    var readyDfd = $q.defer();
    var readyPromise = readyDfd.promise;

    // initialization
    request.onerror = function(event) {
      readyDfd.reject();
    };
    request.onsuccess = function(event) {
      db = request.result;
      readyDfd.resolve();
    };
    request.onupgradeneeded = function(evt) {};

    storageSvc = {
      ready: function(fn) {
        return readyPromise.then(fn);
      },

      filterProblems: function(value, solvedProblems) {
        var solvedIds;
        var store = db.transaction(["solved"], "readonly").objectStore("solved");
        var dfd = $q.defer();
        var request = store.getAll();

        request.onsuccess = function(e) {
          var problems = e.result || [];
          var filtered;
          if (value) { // if true, we want to filter out solved problems
            solvedIds = Object.keys(solvedProblems);
            problems = e.result.reduce(function(acc, problem) {
              return (solvedIds.some(function(sid) { return sid === currentProblem.id; })) ?
                  acc :
                  acc.push(problem);
            }, []);
          }
          dfd.resolve(problems);
        };

        request.onerror = function(e) {
          dfd.reject();
          //TODO: do something to handle the error
        };

        return dfd.promise;
      },

      markProblemSolved: function(id, value) {
        var dfd = $q.defer();

        return dfd.promise;
      },

      getSolved: function() {
        var dfd = $q.defer();

        return dfd.promise;
      },

      getBook: function() {
        var dfd = $q.defer();

        return dfd.promise;
      }

    };

    return storageSvc;
  }]).
  factory("bookSvc", ['storageSvc', function(storageSvc) {

    var bookSvc;
    var book = {};
    var solved = {};
    var skipSolved = false;

    bookSvc =  {

      getFenById: function(id) {
        var problems = book.problems;
        var i, flen;
        for (i = 0, flen = problems.length; i < flen; i++) {
          if (problems[i].id === id) {
            return problems[i];
          }
        }
      },

      getProblems: function() {
        return book.problems || [];
      },

      getNext: function(id) {
        var problems = book.problems;
        var i, flen;
        for (i = 0, flen = problems.length; i < flen; i++) {
          if (problems[i].id === id) {
            return (problems[i + 1]) ? problems[i + 1] : null;
          }
        }
      },

      getPrev: function(id) {
        var problems = book.problems;
        var i, flen;
        for (i = 0, flen = problems.length; i < flen; i++) {
          if (problems[i].id === id) {
            return (problems[i - 1]) ? problems[i - 1] : null;
          }
        }
      },

      setSkipSolved: function(value, $scope) {
        skipSolved = value;
        storageSvc.filterSolved(value, solved).then(function() {
          $scope.$apply();
        });
      },

      getSkipSolved: function() {
        return skipSolved;
      },

      toggleSkipSolved: function() {
        skipSolved = !skipSolved;
      },

      loadBook: function(newBook) {
        book = newBook;
        // $scope.$apply();
      },

      // TODO: unstub; move to indexedDB
      loadSolved: function(s) {
        solved = s;
        // $scope.$apply();
      },

      isSolved: function(id) {
        return solved[id];
      },

      // TODO: unstub
      markSolved: function(id, value) {
        if (value) { solved[id] = value; }
        else { delete solved[id]; }
      }

    }; // bookSvc

    bookSvc.loadSolved(storageSvc.getSolved());
    bookSvc.loadBook(storageSvc.getBook());
    return bookSvc;
  }]);

<|endoftext|>


<commit_before>function getStatusFetch (endpoint) {
  console.log('fetch', endpoint);
  const JSON_REQUEST = {
    method: 'get',
    mode: 'no-cors',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  };

  // TODO: Well shit if the client is hosted on HTTPS, the status cannot be retrieved from HTTP
  return fetch(endpoint, JSON_REQUEST)
    .then((response) => response.json())
    .then((result) => {
      return result;
    });
}

function getStatusXHR (endpoint) {
  return new Promise((resolve, reject) => {

    console.log('xhr', endpoint);
    var xhr = new XMLHttpRequest();
    xhr.open('GET', endpoint);
    xhr.responseType = 'json';

    xhr.onload = function () {
      console.log(xhr.response);
      resolve(xhr.response);
    };

    xhr.onerror = function (err) {
      console.log("Houston, we've got a problem.");
      console.log(err);
      console.log(xhr);
      reject();
    };
    xhr.send();
  });
}

module.exports = getStatusFetch || getStatusXHR;
<commit_msg>remove Fetch method<commit_after>function getStatusXHR (endpoint) {
  return new Promise((resolve, reject) => {

    console.log('xhr', endpoint);
    var xhr = new XMLHttpRequest();
    xhr.open('GET', endpoint);
    xhr.responseType = 'json';

    xhr.onload = function () {
      console.log(xhr.response);
      resolve(xhr.response);
    };

    xhr.onerror = function (err) {
      console.log("Houston, we've got a problem.");
      console.log(err);
      console.log(xhr);
      reject();
    };
    xhr.send();
  });
}

module.exports = getStatusXHR;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Entry from '../../Entry';

export default class Group extends Component {
  static propTypes = {
    cacheBustParam: PropTypes.string.isRequired,
    imagePath: PropTypes.string.isRequired,
    imageType: PropTypes.string.isRequired,
    theme: PropTypes.object.isRequired,
    group: PropTypes.object.isRequired,
    emojis: PropTypes.object.isRequired,
    checkMouseDown: PropTypes.func.isRequired,
    onEmojiSelect: PropTypes.func.isRequired,
    onEmojiMouseDown: PropTypes.func.isRequired,
    useNativeArt: PropTypes.bool,
    isActive: PropTypes.bool,
  };

  state = {
    hasRenderedEmoji: false,
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.isActiveGroup) {
      this.setState({ hasRenderedEmoji: true });
    }
  }

  shouldComponentUpdate = (nextProps) => {
    if (this.state.hasRenderedEmoji) {
      return false;
    }

    return nextProps.isActive;
  };

  renderCategory = (category) => {
    const {
      cacheBustParam,
      imagePath,
      imageType,
      theme = {},
      emojis,
      checkMouseDown,
      onEmojiSelect,
      onEmojiMouseDown,
      useNativeArt,
      isActive,
    } = this.props;

    const categoryEmojis = emojis[category];

    return Object.keys(categoryEmojis).map((key) => (

        {isActive && <Entry
          emoji={categoryEmojis[key][0]}
          theme={theme}
          imagePath={imagePath}
          imageType={imageType}
          cacheBustParam={cacheBustParam}
          toneSet={categoryEmojis[key].length > 1 ? categoryEmojis[key] : null}
          checkMouseDown={checkMouseDown}
          onEmojiSelect={onEmojiSelect}
          onEmojiMouseDown={onEmojiMouseDown}
          useNativeArt={useNativeArt}
        />}

    ));
  };

  render() {
    const {
      theme = {},
      group,
    } = this.props;

    return (

 { this.container = element; }}
      >

{group.title}

 { this.list = element; }}
        >
          {group.categories.map((category) => this.renderCategory(category))}

    );
  }
}
<commit_msg>fix variable name<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Entry from '../../Entry';

export default class Group extends Component {
  static propTypes = {
    cacheBustParam: PropTypes.string.isRequired,
    imagePath: PropTypes.string.isRequired,
    imageType: PropTypes.string.isRequired,
    theme: PropTypes.object.isRequired,
    group: PropTypes.object.isRequired,
    emojis: PropTypes.object.isRequired,
    checkMouseDown: PropTypes.func.isRequired,
    onEmojiSelect: PropTypes.func.isRequired,
    onEmojiMouseDown: PropTypes.func.isRequired,
    useNativeArt: PropTypes.bool,
    isActive: PropTypes.bool,
  };

  state = {
    hasRenderedEmoji: false,
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.isActive) {
      this.setState({ hasRenderedEmoji: true });
    }
  }

  shouldComponentUpdate = (nextProps) => {
    if (this.state.hasRenderedEmoji) {
      return false;
    }

    return nextProps.isActive;
  };

  renderCategory = (category) => {
    const {
      cacheBustParam,
      imagePath,
      imageType,
      theme = {},
      emojis,
      checkMouseDown,
      onEmojiSelect,
      onEmojiMouseDown,
      useNativeArt,
      isActive,
    } = this.props;

    const categoryEmojis = emojis[category];

    return Object.keys(categoryEmojis).map((key) => (

        {isActive && <Entry
          emoji={categoryEmojis[key][0]}
          theme={theme}
          imagePath={imagePath}
          imageType={imageType}
          cacheBustParam={cacheBustParam}
          toneSet={categoryEmojis[key].length > 1 ? categoryEmojis[key] : null}
          checkMouseDown={checkMouseDown}
          onEmojiSelect={onEmojiSelect}
          onEmojiMouseDown={onEmojiMouseDown}
          useNativeArt={useNativeArt}
        />}

    ));
  };

  render() {
    const {
      theme = {},
      group,
    } = this.props;

    return (

 { this.container = element; }}
      >

{group.title}

 { this.list = element; }}
        >
          {group.categories.map((category) => this.renderCategory(category))}

    );
  }
}
<|endoftext|>


<commit_before>var image_cache = [];
var curr_image = 0;
var slideshow_running = 0;
var music;
var currProfile;

function openSettings() {
	var profile = currProfile;
	localStorage.setItem("profile_queue", profile);
	window.location = "settings.html";
}

function cleanDumpingGround() {
    var dg = document.getElementById("images").value; //dumping ground contents
    while(dg.indexOf(" ") >= 0)
        dg = dg.replace(" ", "");
    while(dg.indexOf(",,") >= 0)
        dg = dg.replace(",,", ",");

    if(dg.charAt(0) == ",")
        dg = dg.substr(1, dg.length);

    document.getElementById("images").value = dg;
}

function moveArrayElement(arr, fromIndex, toIndex) {
    var element = arr[fromIndex];
    arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, element);
    return arr;
}

function preview() {
    cleanDumpingGround();
	var images = document.getElementById("images").value;
	if(images.indexOf(",") >= 0)
		images = images.split(",");
	else
		images = [images];
	image_cache = images;
	document.getElementById("preview").innerHTML = "";
	for(var i in images) {
		if(i !== undefined && i !== null) {
			var img = document.createElement("IMG");
			img.src = images[i];
			img.height="100";
			document.getElementById("preview").appendChild(img);
		}
	}
}

function showHide(id) {
	if(document.getElementById(id).hidden === true)
		document.getElementById(id).hidden = false;
	else
		document.getElementById(id).hidden = true;
}

function view() {
	preview();
	var profile = JSON.parse(localStorage.getItem(currProfile + "(profile)"));

    window.scrollTo(0, 0);
	//lockdown the editor
	document.getElementById("editor").hidden = true;
	//unlock presentation board
	document.getElementById("board").hidden = false;
	document.getElementById("bg").src = image_cache[0];
	document.getElementById("fg").src = image_cache[0];
	slideshow_running = 1;
	//no scrolling
	document.body.style.overflow = "hidden";

    //border styling fix:
    var bordercolor = profile.bordercolor;
    var borderwidth = profile.borderwidth;
    document.getElementById("fg").style.border = borderwidth + "px solid " + bordercolor;

	//play music
    if(profile.songfile !== undefined && profile.songfile !== null) {
        music = document.createElement("VIDEO");
        var source = document.createElement("SOURCE");
        source.type = "audio/mp3";
        source.src = profile.songfile;
        music.appendChild(source);
        music.autoplay = true;
        music.controls = true;
        music.hidden = true;
        document.body.appendChild(music);
        music.play();
    }
}

function changeImage(src) {
	document.getElementById("bg").src = src;
	document.getElementById("fg").src = src;
}

function next() {
	var max = image_cache.length - 1;
	if(curr_image + 1 > max) {
		curr_image = 0;
	} else {
		curr_image++;
	}
	var src = image_cache[curr_image];
	changeImage(src);
}

function previous() {
	if(curr_image - 1 < 0) {
		curr_image = image_cache.length - 1;
	} else {
		curr_image--;
	}
	var src = image_cache[curr_image];
	changeImage(src);
}

function saveProfile() {
	preview();
	var name = document.getElementById("save-profile-name").value;
	var images = document.getElementById("images").value;

	var profiles = localStorage.getItem("profiles");
	if(profiles === undefined || profiles === null || profiles === "") {
		localStorage.setItem("profiles", "");
		profiles = [name];
	} else {
        profiles = JSON.parse(profiles);
		if(profiles.indexOf(name) < 0)
			profiles.unshift(name); //no spaces between commas and items
        else {
            profiles = moveArrayElement(profiles, profiles.indexOf(name), 0);
        }

	}
    localStorage.setItem("profiles", JSON.stringify(profiles));
	var thisProf = JSON.parse(localStorage.getItem(name + "(profile)"));
    var newProf = {}; //the new profiles
    newProf.name = name;
    newProf.images = images.split(",");
    try {
		newProf.brightness = thisProf.brightness;
		newProf.bordercolor = thisProf.bordercolor;
		newProf.borderwidth = thisProf.borderwidth;
		newProf.songfile = thisProf.songfile;
	} catch(TypeError) {
		//if the settings have not been defined yet
		//just do nothing here
	}

    localStorage.setItem(name + "(profile)", JSON.stringify(newProf));

    //refresh the page to clear up things
	window.location = "index.html";
}

function changeBGBrightness() {
	var profile = JSON.parse(localStorage.getItem(currProfile + "(profile)"));
	document.getElementById("bg").style.opacity = (parseInt(profile.brightness)/100) + "";

}

function loadProfile() {
	var name = document.getElementById("load-profile-name").value;
	currProfile = name;
    var profile = JSON.parse(localStorage.getItem(name + "(profile)"));
	var images = profile.images;
	var bordercolor = profile.bordercolor;
	var borderwidth = profile.borderwidth;
	var songfile = profile.songfile;
	document.getElementById("save-profile-name").value = name; //make it easier for the user to save
	//show in editor
	document.getElementById("images").value = images;
	//change stylings to show up in the presentation
	changeBGBrightness();
	document.getElementById("fg").style.border = borderwidth + "px solid " + bordercolor;
    preview();
}

function deleteProfile() {
	var name = document.getElementById("delete-profile-name").value;
	var request = confirm("Are you sure you want to delete " + name + ". This action cannot be reversed");
	if(request !== true) return 0; //if user exits prompt, then it doesn't show up as false, which is why we say anything but true, then exit

    var profiles = JSON.parse(localStorage.getItem("profiles"));
    // start/end splice
    var splice1 = profiles.indexOf(name);
    var splice2 = splice1 + 1;
    profiles.splice(splice1, splice2);
    localStorage.setItem("profiles", JSON.stringify(profiles));

    localStorage.setItem(name + "(profile)", undefined);
}

function addImage() {
    preview();
    var url = document.getElementById("newImageToAdd").value;
    document.getElementById("images").value = document.getElementById("images").value + ", " + url;
    document.getElementById("newImageToAdd").value = ""; //remove url after done, so that we can reuse the input field
    preview();
}

function removeImage() {
    preview();
    var url = document.getElementById("removeImage").value;
    var dumpingGround = document.getElementById("images").value;
    dumpingGround = dumpingGround.replace(url, "");
    dumpingGround = dumpingGround.split(","); document.getElementById("images").value = dumpingGround + ""; document.getElementById("removeImage").value = ""; //remove url after done, so that we can reuse the input field
    cleanDumpingGround();
    preview();
}

function swapImages() {
    var img1 = document.getElementById("swap-image1").value;
    var img2 = document.getElementById("swap-image2").value;
    var dg = document.getElementById("images").value;
    dg = dg.replace(img1, img1 + "*&*");
    dg = dg.replace(img2, img1);
    dg = dg.replace(img1 + "*&*", img2);
    document.getElementById("images").value = dg;
    preview();
}

function replaceImage() {
    var i_out = document.getElementById("sub-image-out").value;
    var i_in = document.getElementById("sub-image-in").value;
    var dg = document.getElementById("images").value;
    dg = dg.replace(i_out, i_in);
    document.getElementById("images").value = dg;
    preview();

}

function squeezeImage() {
    var dg = document.getElementById("images").value;
    var newImg = document.getElementById("squeeze-image").value;
    var pos = document.getElementById("squeeze-location").value;
    if(pos == "beg" || pos == "end") {
        if(pos == "beg") dg = newImg + "," + dg;
        else dg = dg + "," + newImg;
    } else {
        var after = document.getElementById("squeeze-after").value;
        dg = dg.replace(after, after + "," + newImg);
    }
    document.getElementById("images").value = dg;
    preview();
}

$(document).ready(function() {
	$(document).scroll(function() {
		if(slideshow_running)
			document.body.style.overflow = "hidden";
		else
			document.body.style.overflow = "scroll";
	});

	$(document).keydown(function(e) {
		if(slideshow_running) {
			switch(e.which) {
				case 37: //left
					previous();
				break;

				case 39: //right
					next();
				break;

				case 40: //down
					showHide("board");
					showHide("editor");
					slideshow_running = 0;
					document.body.style.overflow = "scroll";
					music.pause();
				break;

				default:
					return 0;
			}
			e.preventDefault();
		}
	});

	//settings the brightness of the background
	$("#bg-dimmer").change(changeBGBrightness);

	//automatically load profiles browse things
    try {
        var profiles = JSON.parse(localStorage.getItem("profiles"));
        for(var i in profiles) {
            if(profiles[i] !== "") {
                var foo = document.createElement("OPTION");
                foo.innerHTML = profiles[i];
                foo.value = profiles[i];
                document.getElementById("load-profile-name").appendChild(foo);
            }
        }
	    //and do the same for deleting profiles
        for(var i in profiles) {
            if(profiles[i] !== "") {
                var foo = document.createElement("OPTION");
                foo.innerHTML = profiles[i];
                foo.value = profiles[i];
                document.getElementById("delete-profile-name").appendChild(foo);
            }
        }
    } catch(SyntaxError) {
        //then just do nothing
    }

	//load the last made profile on startup
	try { //incase there is no length to profiles (in the if statement)
		if(localStorage.getItem("profiles").length > 1)
			loadProfile();
	} catch(TypeError) {
		//do nothing
	}

	currProfile = document.getElementById("load-profile-name").value

    preview();
});
<commit_msg>New keyboard shortcuts<commit_after>var image_cache = [];
var curr_image = 0;
var slideshow_running = 0;
var music;
var currProfile;

function openSettings() {
	var profile = currProfile;
	localStorage.setItem("profile_queue", profile);
	window.location = "settings.html";
}

function cleanDumpingGround() {
    var dg = document.getElementById("images").value; //dumping ground contents
    while(dg.indexOf(" ") >= 0)
        dg = dg.replace(" ", "");
    while(dg.indexOf(",,") >= 0)
        dg = dg.replace(",,", ",");

    if(dg.charAt(0) == ",")
        dg = dg.substr(1, dg.length);

    document.getElementById("images").value = dg;
}

function moveArrayElement(arr, fromIndex, toIndex) {
    var element = arr[fromIndex];
    arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, element);
    return arr;
}

function preview() {
    cleanDumpingGround();
	var images = document.getElementById("images").value;
	if(images.indexOf(",") >= 0)
		images = images.split(",");
	else
		images = [images];
	image_cache = images;
	document.getElementById("preview").innerHTML = "";
	for(var i in images) {
		if(i !== undefined && i !== null) {
			var img = document.createElement("IMG");
			img.src = images[i];
			img.height="100";
			document.getElementById("preview").appendChild(img);
		}
	}
}

function showHide(id) {
	if(document.getElementById(id).hidden === true)
		document.getElementById(id).hidden = false;
	else
		document.getElementById(id).hidden = true;
}

function view() {
	preview();
	var profile = JSON.parse(localStorage.getItem(currProfile + "(profile)"));

    window.scrollTo(0, 0);
	//lockdown the editor
	document.getElementById("editor").hidden = true;
	//unlock presentation board
	document.getElementById("board").hidden = false;
	document.getElementById("bg").src = image_cache[0];
	document.getElementById("fg").src = image_cache[0];
	slideshow_running = 1;
	//no scrolling
	document.body.style.overflow = "hidden";

    //border styling fix:
    var bordercolor = profile.bordercolor;
    var borderwidth = profile.borderwidth;
    document.getElementById("fg").style.border = borderwidth + "px solid " + bordercolor;

	//play music
    if(profile.songfile !== undefined && profile.songfile !== null) {
        music = document.createElement("VIDEO");
        var source = document.createElement("SOURCE");
        source.type = "audio/mp3";
        source.src = profile.songfile;
        music.appendChild(source);
        music.autoplay = true;
        music.controls = true;
        music.hidden = true;
        document.body.appendChild(music);
        music.play();
    }
}

function changeImage(src) {
	document.getElementById("bg").src = src;
	document.getElementById("fg").src = src;
}

function next() {
	var max = image_cache.length - 1;
	if(curr_image + 1 > max) {
		curr_image = 0;
	} else {
		curr_image++;
	}
	var src = image_cache[curr_image];
	changeImage(src);
}

function previous() {
	if(curr_image - 1 < 0) {
		curr_image = image_cache.length - 1;
	} else {
		curr_image--;
	}
	var src = image_cache[curr_image];
	changeImage(src);
}

function saveProfile() {
	preview();
	var name = document.getElementById("save-profile-name").value;
	var images = document.getElementById("images").value;

	var profiles = localStorage.getItem("profiles");
	if(profiles === undefined || profiles === null || profiles === "") {
		localStorage.setItem("profiles", "");
		profiles = [name];
	} else {
        profiles = JSON.parse(profiles);
		if(profiles.indexOf(name) < 0)
			profiles.unshift(name); //no spaces between commas and items
        else {
            profiles = moveArrayElement(profiles, profiles.indexOf(name), 0);
        }

	}
    localStorage.setItem("profiles", JSON.stringify(profiles));
	var thisProf = JSON.parse(localStorage.getItem(name + "(profile)"));
    var newProf = {}; //the new profiles
    newProf.name = name;
    newProf.images = images.split(",");
    try {
		newProf.brightness = thisProf.brightness;
		newProf.bordercolor = thisProf.bordercolor;
		newProf.borderwidth = thisProf.borderwidth;
		newProf.songfile = thisProf.songfile;
	} catch(TypeError) {
		//if the settings have not been defined yet
		//just do nothing here
	}

    localStorage.setItem(name + "(profile)", JSON.stringify(newProf));

    //refresh the page to clear up things
	window.location = "index.html";
}

function changeBGBrightness() {
	var profile = JSON.parse(localStorage.getItem(currProfile + "(profile)"));
	document.getElementById("bg").style.opacity = (parseInt(profile.brightness)/100) + "";

}

function loadProfile() {
	var name = document.getElementById("load-profile-name").value;
	currProfile = name;
    var profile = JSON.parse(localStorage.getItem(name + "(profile)"));
	var images = profile.images;
	var bordercolor = profile.bordercolor;
	var borderwidth = profile.borderwidth;
	var songfile = profile.songfile;
	document.getElementById("save-profile-name").value = name; //make it easier for the user to save
	//show in editor
	document.getElementById("images").value = images;
	//change stylings to show up in the presentation
	changeBGBrightness();
	document.getElementById("fg").style.border = borderwidth + "px solid " + bordercolor;
    preview();
}

function deleteProfile() {
	var name = document.getElementById("delete-profile-name").value;
	var request = confirm("Are you sure you want to delete " + name + ". This action cannot be reversed");
	if(request !== true) return 0; //if user exits prompt, then it doesn't show up as false, which is why we say anything but true, then exit

    var profiles = JSON.parse(localStorage.getItem("profiles"));
    // start/end splice
    var splice1 = profiles.indexOf(name);
    var splice2 = splice1 + 1;
    profiles.splice(splice1, splice2);
    localStorage.setItem("profiles", JSON.stringify(profiles));

    localStorage.setItem(name + "(profile)", undefined);
}

function addImage() {
    preview();
    var url = document.getElementById("newImageToAdd").value;
    document.getElementById("images").value = document.getElementById("images").value + ", " + url;
    document.getElementById("newImageToAdd").value = ""; //remove url after done, so that we can reuse the input field
    preview();
}

function removeImage() {
    preview();
    var url = document.getElementById("removeImage").value;
    var dumpingGround = document.getElementById("images").value;
    dumpingGround = dumpingGround.replace(url, "");
    dumpingGround = dumpingGround.split(","); document.getElementById("images").value = dumpingGround + ""; document.getElementById("removeImage").value = ""; //remove url after done, so that we can reuse the input field
    cleanDumpingGround();
    preview();
}

function swapImages() {
    var img1 = document.getElementById("swap-image1").value;
    var img2 = document.getElementById("swap-image2").value;
    var dg = document.getElementById("images").value;
    dg = dg.replace(img1, img1 + "*&*");
    dg = dg.replace(img2, img1);
    dg = dg.replace(img1 + "*&*", img2);
    document.getElementById("images").value = dg;
    preview();
}

function replaceImage() {
    var i_out = document.getElementById("sub-image-out").value;
    var i_in = document.getElementById("sub-image-in").value;
    var dg = document.getElementById("images").value;
    dg = dg.replace(i_out, i_in);
    document.getElementById("images").value = dg;
    preview();

}

function squeezeImage() {
    var dg = document.getElementById("images").value;
    var newImg = document.getElementById("squeeze-image").value;
    var pos = document.getElementById("squeeze-location").value;
    if(pos == "beg" || pos == "end") {
        if(pos == "beg") dg = newImg + "," + dg;
        else dg = dg + "," + newImg;
    } else {
        var after = document.getElementById("squeeze-after").value;
        dg = dg.replace(after, after + "," + newImg);
    }
    document.getElementById("images").value = dg;
    preview();
}

$(document).ready(function() {
	$(document).scroll(function() {
		if(slideshow_running)
			document.body.style.overflow = "hidden";
		else
			document.body.style.overflow = "scroll";
	});

	$(document).keydown(function(e) {
		if(slideshow_running) {
			switch(e.which) {
				case 37: //left
					previous();
				break;

				case 39: //right
					next();
				break;

				case 40: //down
					showHide("board");
					showHide("editor");
					slideshow_running = 0;
					document.body.style.overflow = "scroll";
					music.pause();
				break;

                case 27: //esc(ape)
                    showHide("board");
                    showHide("editor");
                    slideshow_running = 0;
                    document.body.style.overflow = "scroll";
                    music.pause();

                case 32: //space(bar)
                    next();
                    break;

                case 8: //backspace
                    previous();
                    break;

                case 46: //delete (in case the user is on a mac) or has a keyboard that uses delte instead of backspace (such as some chromebooks)
                    previous();
                    break;

				default:
					return 0;
			}
			e.preventDefault();
		}
        else {
            switch(e.which) {
                case 116: //F5 (the present button for MS powerpoint)
                    view();
                    break;
                case 107: //plus button (SHIFT + =)
                    document.getElementById("newImageToAdd").focus();
                    break;
                case 109: //minus button (or dash/hyphen)
                    document.getElementById("removeImage").focus();

                default:
                    return 0;
            }
            e.preventDefault();
        }
	});

	//settings the brightness of the background
	$("#bg-dimmer").change(changeBGBrightness);

	//automatically load profiles browse things
    try {
        var profiles = JSON.parse(localStorage.getItem("profiles"));
        for(var i in profiles) {
            if(profiles[i] !== "") {
                var foo = document.createElement("OPTION");
                foo.innerHTML = profiles[i];
                foo.value = profiles[i];
                document.getElementById("load-profile-name").appendChild(foo);
            }
        }
	    //and do the same for deleting profiles
        for(var i in profiles) {
            if(profiles[i] !== "") {
                var foo = document.createElement("OPTION");
                foo.innerHTML = profiles[i];
                foo.value = profiles[i];
                document.getElementById("delete-profile-name").appendChild(foo);
            }
        }
    } catch(SyntaxError) {
        //then just do nothing
    }

	//load the last made profile on startup
	try { //incase there is no length to profiles (in the if statement)
		if(localStorage.getItem("profiles").length > 1)
			loadProfile();
	} catch(TypeError) {
		//do nothing
	}

	currProfile = document.getElementById("load-profile-name").value

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


<commit_before> chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(request);
    App = Ember.Application.create({
        rootElement: '#app'
    });

    App.ApiData = request;

    App.ChromeDevToolsTimetreeView = Ember.Timetree.TimetreeView.extend({
        timeTickFormat: Ember.computed(function() {
            var minTime = this.get('xScale').domain()[0];
            var minTime = d3.min(this.content.mapProperty('start'));
            return function(d) {
                return parseInt(d - minTime) + 'ms';
            };
        }).property(),

        durationFormatter: function(n) {
            return (n.end - n.start) + 'ms';
        }
    });
});

<commit_msg>add_comment_to_timeline.js<commit_after> //Listener for resources to generate timeline
 chrome.runtime.onMessage.addListener(
     function(request, sender, sendResponse) {
         //bootstrap ember application
         App = Ember.Application.create({
             rootElement: '#app'
         });

         App.ApiData = request;

         //helper directory for ChromeDev like timeline
         App.ChromeDevToolsTimetreeView = Ember.Timetree.TimetreeView.extend({
             timeTickFormat: Ember.computed(function() {
                 var minTime = this.get('xScale').domain()[0];
                 var minTime = d3.min(this.content.mapProperty('start'));
                 return function(d) {
                     return parseInt(d - minTime) + 'ms';
                 };
             }).property(),

             durationFormatter: function(n) {
                 return (n.end - n.start) + 'ms';
             }
         });
     });<|endoftext|>


<commit_before>
//some common java script functions which are used throughout the web site.
//note, these are for use on BOTH the PUBLIC and PRIVATE page.
//created by rjp, 1/2004.

// To be run at startup to enable the css drop downs
// See http://www.alistapart.com/articles/dropdowns/
// Attaches :hover function to LI class for IE 5.01+,
// normally IE doesn't support :hover property
// for things over than  tags
sfHover = function() {
    if (document.getElementById("dropDown")) {
        var sfEls1 = document.getElementById("dropDown").getElementsByTagName("TD");
        var sfEls2 = document.getElementById("dropDown").getElementsByTagName("LI");
        for (var i=0; i<sfEls1.length; i++) {
            sfEls1[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls1[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
        for (var i=0; i<sfEls2.length; i++) {
            sfEls2[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls2[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
    }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// This is a handy little function for seeing what properties an object has
function showProperties ( obj ) {
    var result = "";

    for ( var i in obj ) {
        result += "obj." + i + " = " + obj[i] + "
\n";
    }
    document.write ( result );
}

function checkBrowserVersion() {
    var match = /Microsoft/i;

    if (match.test(navigator.appName)) {
        document.write("
Warning: Internet Explorer is not standards compliant and you should not use it on this web site or elsewhere.
 Aside from cosmetic defects in page rendering, error checking routines may not work correctly and you may be randomly logged out of the site.

 Please download and use Safari or Firefox, or read the web browser tip sheet for information on other free browsers.
");
    }
}

//
// for validation of form input
//

// returns true if the input is in a proper format for a last name
function properLastName(input) {
    if ((!input) || input == "") { return false; }
    var match = /^[A-Za-z,-.\'][A-Za-z ,-.\']*$/;
    return match.test(input);
}

// returns true if the input is in a proper format for an initial
function properInitial(input) {
    if ((!input) || input == "") { return false; }
    var match1 = /^[A-Z][A-Za-z .]*$/;
    var match2 = /[.]/;
    return (match1.test(input) && match2.test(input));
}

// returns true if it's a proper year format which begins with a 1 or 2,
// ie, 1900 and something or 2000 something.
function properYear(input) {
    if ((!input) || input == "") { return false; }
    var match = /^[12]\d{3}$/;
    return match.test(input);
}

//
// by rjp, 2/2004, modified by PS
function guessTaxonRank(taxon) {
    var isSpecies = /^[A-Z][a-z]+[ ][a-z]+\n?$/;
    var isSubspecies = /^[A-Z][a-z]+[ ][a-z]+[ ][a-z]+\n?$/;
    var isHigher = /^[A-Z][a-z]+\n?$/;

    //alert ("taxon = '" + taxon + "'");
    if (isSubspecies.test(taxon)) {
        return "subspecies";
    } else if (isSpecies.test(taxon)) {
        return "species";
    } else if (isHigher.test(taxon)) {
        return "higher";
    } else {
        return "invalid";
    }
}

// Error is a JavaScript class for error reporting..
// To use it, first create a new instance of the object, for example
// var err = new Error();  // you can optionally pass an error message in the constructor
// Then, call the add() method each time you want to add an error to it.
// err.add("my error message");
// When finished, you can print the alert by calling the showAlert method,
// or you can directly grab the string.
// err.showAlert();  //displays the alert message with the entire error
// alert(err);  // same thing

// constructor, optionally pass it the first error message.
//
// by rjp, 2/2004
function Error(msg) {
    this.starting = "\tPlease fix the following errors:\n\n";
    this.message = "";
    this.internalcount = 0;

    if (msg) {
        this.message = "* " + msg;
    }

    this.ending = "\n\nRefer to the tip sheet for instructions.";
}

// adds an error with a bullet point to the list of error messages
Error.prototype.add = function(msg) {
    this.message += "\n* " + msg;
    this.internalcount += 1;
}

Error.prototype.count = function() {
    return this.internalcount;
}

// displays an alert message with the error
Error.prototype.showAlert = function() {
    alert(this);
}

// converts the error object to a string.
Error.prototype.toString = function() {
    return this.starting + this.message + this.ending;
}

// pass this method another Error object, and it will append the
// new object onto the end of itself.
Error.prototype.appendErrors = function(newError) {
    this.message += newError.message;
    this.internalcount += newError.internalcount;
}

// End of error class.

//show a popup window with the passed URL.
function tipsPopup (URL,width,height) {
    var width  = (width == null) ? 640 : width;
    var height = (height== null) ? 480 : height;
    window.open(URL, 'tips', 'toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

//show a popup window with the passed URL.
function imagePopup (URL,width,height) {
    var width  = (width == null) ? 800 : width;
    var height = (height== null) ? 600 : height;
    window.open(URL, 'imageview', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

// Show a popup with a map in it.  this is kept distinct from the other two popups because if we include
// the full url in the javascript, search engines will still spider it, which is bad since the map
// generation is ultra heavyweight
function mapPopup(collection_no) {
    var link = 'bridge'+'.pl'+
               '?action=displayMapOfCollection'+
               '&display_header=NO'+
               '&collection_no='+collection_no;
    window.open(link,'mapview','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600');
}

//if java script is turned on, then this will
//print a hidden input field so we can check from the perl
//code and see that it was turned on.
function javascriptOnCheck() {
    document.writeln("<INPUT type=\"hidden\" name=\"javascripton\" value=\"yes\"></INPUT>");
}

// Email addresses pass through a simple javascript, which most automated scripts won't execute
// before being displayed
function descram(part2r,part1r) {
    var em = "";
    for (i = 0; i <= part2r.length; i++) {
      em = part2r.charAt(i) + em;
    }
    em = "@" + em;
    for (i = 0; i <= part1r.length; i++) {
      em = part1r.charAt(i) + em;
    }
    document.write(em);
}

//pass this function a checkbox.
function checkAll(checkbox,the_class){
    var state = checkbox.checked;
    var frm = document.forms[0];
    var like_class = new RegExp(the_class);
    for(var i=0; i < frm.elements.length; i++){
        if (like_class.test(frm.elements[i].className)) {
            frm.elements[i].checked = state;
        }
    }
}

// used in the PAST module to hide or show lines of text that pop up next
//  to data points in plots on mouse over; assumes that the named elements
//  are single lines of text stacked on top of each other
function showHide(what)    {
    var elems = document.getElementsByName(what);
    for (var i=0,a; a=elems[i]; i++)    {
        if ( a.style.visibility != "hidden" )    {
            a.style.visibility = "hidden";
            a.style.height = "0em";
        } else    {
            a.style.visibility = "visible";
            a.style.height = "1.25em";
        }
    }
}

function checkAllEmpty(frm,fields) {
    var element_count = 0;
    var empty_count = 0;
    for(i=0;i<frm.elements.length;i++) {
        var elem = frm.elements[i];
        for(j=0;j<fields.length;j++) {
            if (elem.name == fields[j]) {
                element_count++;
                if (elem.options) {
                    if (elem.selectedIndex == 0) empty_count++;
                } else {
                    if (elem.value == '') empty_count++;
                }
            }
        }
    }
    if (element_count == empty_count) {
        return true;
    } else {
        return false;
    }
}

function textClear (input)	{
	if ( input.value == input.defaultValue )	{
		input.value = "";
	}
}

function textRestore (input)	{
	if ( input.value == "" )	{
		input.value = input.defaultValue;
	}
}

function checkName(i,j)    {
	var name = document.forms[i].elements[j].value;
	if ( /[^A-Za-z0-9 :;,\-\(\)]/.test( name ) )	{
		alert("A search string can only include letters, commas, etc. ");
		return false;
	} else if ( /^[^A-Za-z0-9]/.test( name ) )	{
		alert("The search string must begin with a letter or number");
		return false;
	} else if ( / $/.test( name ) )	{
		alert("The search string can't end with a space");
		return false;
	} else if ( /[^A-Za-z0-9\)]$/.test( name ) )	{
		alert("The search string must end with a letter or number");
		return false;
	} else	{
		return true;
	}
}

<commit_msg>checkName permits periods in search strings to allow them to serve as wildcards; also, a bug fix in checkAll<commit_after>
//some common java script functions which are used throughout the web site.
//note, these are for use on BOTH the PUBLIC and PRIVATE page.
//created by rjp, 1/2004.

// To be run at startup to enable the css drop downs
// See http://www.alistapart.com/articles/dropdowns/
// Attaches :hover function to LI class for IE 5.01+,
// normally IE doesn't support :hover property
// for things over than  tags
sfHover = function() {
    if (document.getElementById("dropDown")) {
        var sfEls1 = document.getElementById("dropDown").getElementsByTagName("TD");
        var sfEls2 = document.getElementById("dropDown").getElementsByTagName("LI");
        for (var i=0; i<sfEls1.length; i++) {
            sfEls1[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls1[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
        for (var i=0; i<sfEls2.length; i++) {
            sfEls2[i].onmouseover=function() {
                this.className+=" sfhover";
            }
            sfEls2[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
    }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// This is a handy little function for seeing what properties an object has
function showProperties ( obj ) {
    var result = "";

    for ( var i in obj ) {
        result += "obj." + i + " = " + obj[i] + "
\n";
    }
    document.write ( result );
}

function checkBrowserVersion() {
    var match = /Microsoft/i;

    if (match.test(navigator.appName)) {
        document.write("
Warning: Internet Explorer is not standards compliant and you should not use it on this web site or elsewhere.
 Aside from cosmetic defects in page rendering, error checking routines may not work correctly and you may be randomly logged out of the site.

 Please download and use Safari or Firefox, or read the web browser tip sheet for information on other free browsers.
");
    }
}

//
// for validation of form input
//

// returns true if the input is in a proper format for a last name
function properLastName(input) {
    if ((!input) || input == "") { return false; }
    var match = /^[A-Za-z,-.\'][A-Za-z ,-.\']*$/;
    return match.test(input);
}

// returns true if the input is in a proper format for an initial
function properInitial(input) {
    if ((!input) || input == "") { return false; }
    var match1 = /^[A-Z][A-Za-z .]*$/;
    var match2 = /[.]/;
    return (match1.test(input) && match2.test(input));
}

// returns true if it's a proper year format which begins with a 1 or 2,
// ie, 1900 and something or 2000 something.
function properYear(input) {
    if ((!input) || input == "") { return false; }
    var match = /^[12]\d{3}$/;
    return match.test(input);
}

//
// by rjp, 2/2004, modified by PS
function guessTaxonRank(taxon) {
    var isSpecies = /^[A-Z][a-z]+[ ][a-z]+\n?$/;
    var isSubspecies = /^[A-Z][a-z]+[ ][a-z]+[ ][a-z]+\n?$/;
    var isHigher = /^[A-Z][a-z]+\n?$/;

    //alert ("taxon = '" + taxon + "'");
    if (isSubspecies.test(taxon)) {
        return "subspecies";
    } else if (isSpecies.test(taxon)) {
        return "species";
    } else if (isHigher.test(taxon)) {
        return "higher";
    } else {
        return "invalid";
    }
}

// Error is a JavaScript class for error reporting..
// To use it, first create a new instance of the object, for example
// var err = new Error();  // you can optionally pass an error message in the constructor
// Then, call the add() method each time you want to add an error to it.
// err.add("my error message");
// When finished, you can print the alert by calling the showAlert method,
// or you can directly grab the string.
// err.showAlert();  //displays the alert message with the entire error
// alert(err);  // same thing

// constructor, optionally pass it the first error message.
//
// by rjp, 2/2004
function Error(msg) {
    this.starting = "\tPlease fix the following errors:\n\n";
    this.message = "";
    this.internalcount = 0;

    if (msg) {
        this.message = "* " + msg;
    }

    this.ending = "\n\nRefer to the tip sheet for instructions.";
}

// adds an error with a bullet point to the list of error messages
Error.prototype.add = function(msg) {
    this.message += "\n* " + msg;
    this.internalcount += 1;
}

Error.prototype.count = function() {
    return this.internalcount;
}

// displays an alert message with the error
Error.prototype.showAlert = function() {
    alert(this);
}

// converts the error object to a string.
Error.prototype.toString = function() {
    return this.starting + this.message + this.ending;
}

// pass this method another Error object, and it will append the
// new object onto the end of itself.
Error.prototype.appendErrors = function(newError) {
    this.message += newError.message;
    this.internalcount += newError.internalcount;
}

// End of error class.

//show a popup window with the passed URL.
function tipsPopup (URL,width,height) {
    var width  = (width == null) ? 640 : width;
    var height = (height== null) ? 480 : height;
    window.open(URL, 'tips', 'toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

//show a popup window with the passed URL.
function imagePopup (URL,width,height) {
    var width  = (width == null) ? 800 : width;
    var height = (height== null) ? 600 : height;
    window.open(URL, 'imageview', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width='+width+',height='+height);
}

// Show a popup with a map in it.  this is kept distinct from the other two popups because if we include
// the full url in the javascript, search engines will still spider it, which is bad since the map
// generation is ultra heavyweight
function mapPopup(collection_no) {
    var link = 'bridge'+'.pl'+
               '?action=displayMapOfCollection'+
               '&display_header=NO'+
               '&collection_no='+collection_no;
    window.open(link,'mapview','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600');
}

//if java script is turned on, then this will
//print a hidden input field so we can check from the perl
//code and see that it was turned on.
function javascriptOnCheck() {
    document.writeln("<INPUT type=\"hidden\" name=\"javascripton\" value=\"yes\"></INPUT>");
}

// Email addresses pass through a simple javascript, which most automated scripts won't execute
// before being displayed
function descram(part2r,part1r) {
    var em = "";
    for (i = 0; i <= part2r.length; i++) {
      em = part2r.charAt(i) + em;
    }
    em = "@" + em;
    for (i = 0; i <= part1r.length; i++) {
      em = part1r.charAt(i) + em;
    }
    document.write(em);
}

//pass this function a checkbox.
function checkAll(checkbox,the_class){
    var state = checkbox.checked;
    var frm = document.forms[1];
    var like_class = new RegExp(the_class);
    for(var i=0; i < frm.elements.length; i++){
        if (like_class.test(frm.elements[i].className)) {
            frm.elements[i].checked = state;
        }
    }
}

// used in the PAST module to hide or show lines of text that pop up next
//  to data points in plots on mouse over; assumes that the named elements
//  are single lines of text stacked on top of each other
function showHide(what)    {
    var elems = document.getElementsByName(what);
    for (var i=0,a; a=elems[i]; i++)    {
        if ( a.style.visibility != "hidden" )    {
            a.style.visibility = "hidden";
            a.style.height = "0em";
        } else    {
            a.style.visibility = "visible";
            a.style.height = "1.25em";
        }
    }
}

function checkAllEmpty(frm,fields) {
    var element_count = 0;
    var empty_count = 0;
    for(i=0;i<frm.elements.length;i++) {
        var elem = frm.elements[i];
        for(j=0;j<fields.length;j++) {
            if (elem.name == fields[j]) {
                element_count++;
                if (elem.options) {
                    if (elem.selectedIndex == 0) empty_count++;
                } else {
                    if (elem.value == '') empty_count++;
                }
            }
        }
    }
    if (element_count == empty_count) {
        return true;
    } else {
        return false;
    }
}

function textClear (input)	{
	if ( input.value == input.defaultValue )	{
		input.value = "";
	}
}

function textRestore (input)	{
	if ( input.value == "" )	{
		input.value = input.defaultValue;
	}
}

function checkName(i,j)    {
	var name = document.forms[i].elements[j].value;
	if ( /[^A-Za-z0-9 \.:;,\-\(\)]/.test( name ) )	{
		alert("A search string can only include letters, commas, etc. ");
		return false;
	} else if ( /^[^A-Za-z0-9]/.test( name ) )	{
		alert("The search string must begin with a letter or number");
		return false;
	} else if ( / $/.test( name ) )	{
		alert("The search string can't end with a space");
		return false;
	} else if ( /[^A-Za-z0-9\)]$/.test( name ) )	{
		alert("The search string must end with a letter or number");
		return false;
	} else	{
		return true;
	}
}

<|endoftext|>


<commit_before><commit_msg>Display the source image in robotoff-asker, and allow users to zoom in to the original image.<commit_after><|endoftext|>