<commit_before>import React                    from 'react';
import {RouteHandler, Link} from 'react-router';
import 'styles/bootstrap.css';
import 'styles/clean-blog.css';
import CleanBlogJS from 'lib/clean-blog';
import glucoseActions from '../actions/glucoseAction';
import glucoseStore from '../stores/glucoseStore';
import trend from './trend';
import _ from 'lodash';
import moment from 'moment-timezone';
import GlucoseChart from './glucoseChart';
import NextReading from './timer';

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
        this.state = {};
    }

    componentDidMount() {
        glucoseStore.listen(this.onChange);
        var gState = glucoseStore.getState();
        var history = gState.glucose;
        if (history) {
            if (history.length > 0) {
                history = _.sortBy(history, 'time').reverse();
                gState.glucose = history[0].glucose;
                gState.history = history;
            }
        }

        this.setState(gState);
    }

    componentWillUnmount() {
        clearInterval(window.timer);
        glucoseStore.unlisten(this.onChange);
    }

    onChange(event) {
        var newState = glucoseStore.getState();
        this.setState(newState);
    }

    render() {
        var glucose = 'Not available';
        var sorted;
        if (this.state.glucose) {
            if (this.state.glucose == 401) {
                glucose = 'HIGH';
            } else {
                glucose = this.state.glucose;
            }
        }
        var currentTrend = 'Not available';
        if (this.state.trend) {
            var currentT = trend.trendsToText(this.state.trend) + '';
			currentTrend =

;
        }
        var lastReading = 'Not Available';
        if (this.state.lastEntry) {
            var last = new Date(this.state.lastEntry);
            var ampm = 'AM';
            if (last.getHours() == 0) {
                lastReading = '12:';
            } else if (last.getHours() == 12) {
                lastReading = '12:';
                ampm = 'PM'
            } else if (last.getHours() > 12) {
                lastReading = last.getHours() - 12 + ':';
                ampm = 'PM';
            } else {
                lastReading = last.getHours() + ':';
            }
            if (last.getMinutes() < 10) {
                lastReading += '0' + last.getMinutes();
            } else {
                lastReading += last.getMinutes();
            }
            if (last.getSeconds() < 10) {
                lastReading += ':0' + last.getSeconds();
            } else {
                lastReading += ':' + last.getSeconds();
            }
            lastReading += ' ' + ampm;
        }

        var noData =

;
        if (this.state.data != true) {
            noData =
Not getting any data from Dexcom
;
        }

        return (

                    {noData}

Current Reading: {glucose}
                                Direction: {currentTrend}

Last Reading: {lastReading}
                                <NextReading status={this.state.status} lastEntry={this.state.lastEntry}/>

                    <GlucoseChart history={this.state.history}/>

        );
    }
}

export default Main;
<commit_msg>worst practices abound<commit_after>import React                    from 'react';
import {RouteHandler, Link} from 'react-router';
import 'styles/bootstrap.css';
import 'styles/clean-blog.css';
import CleanBlogJS from 'lib/clean-blog';
import glucoseActions from '../actions/glucoseAction';
import glucoseStore from '../stores/glucoseStore';
import trend from './trend';
import _ from 'lodash';
import moment from 'moment-timezone';
import GlucoseChart from './glucoseChart';
import NextReading from './timer';

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
        this.state = {};
    }

    componentDidMount() {
        glucoseStore.listen(this.onChange);
        var gState = glucoseStore.getState();
        var history = gState.glucose;
        if (history) {
            if (history.length > 0) {
                history = _.sortBy(history, 'time').reverse();
                gState.glucose = history[0].glucose;
                gState.history = history;
            }
        }

        this.setState(gState);
    }

    componentWillUnmount() {
        clearInterval(window.timer);
        glucoseStore.unlisten(this.onChange);
    }

    onChange(event) {
        var newState = glucoseStore.getState();
        this.setState(newState);
    }

    render() {
        var glucose = 'Not available';
        var sorted;
        if (this.state.glucose) {
            if (this.state.glucose == 401) {
                glucose = 'HIGH';
            } else {
                glucose = this.state.glucose;
            }
        }
        var currentTrend = 'Not available';
        if (this.state.trend) {
            var currentT = trend.trendsToText(this.state.trend) + '';
			console.log(currentT);
			currentTrend =

;
        }
        var lastReading = 'Not Available';
        if (this.state.lastEntry) {
            var last = new Date(this.state.lastEntry);
            var ampm = 'AM';
            if (last.getHours() == 0) {
                lastReading = '12:';
            } else if (last.getHours() == 12) {
                lastReading = '12:';
                ampm = 'PM'
            } else if (last.getHours() > 12) {
                lastReading = last.getHours() - 12 + ':';
                ampm = 'PM';
            } else {
                lastReading = last.getHours() + ':';
            }
            if (last.getMinutes() < 10) {
                lastReading += '0' + last.getMinutes();
            } else {
                lastReading += last.getMinutes();
            }
            if (last.getSeconds() < 10) {
                lastReading += ':0' + last.getSeconds();
            } else {
                lastReading += ':' + last.getSeconds();
            }
            lastReading += ' ' + ampm;
        }

        var noData =

;
        if (this.state.data != true) {
            noData =
Not getting any data from Dexcom
;
        }

        return (

                    {noData}

Current Reading: {glucose}
                                Direction: {currentTrend}

Last Reading: {lastReading}
                                <NextReading status={this.state.status} lastEntry={this.state.lastEntry}/>

                    <GlucoseChart history={this.state.history}/>

        );
    }
}

export default Main;
<|endoftext|>


<commit_before>/* @flow */

import { createRoute, isSameRoute, isIncludedRoute } from '../util/route'
import { _Vue } from '../install'

// work around weird flow bug
const toTypes: Array<Function> = [String, Object]
const eventTypes: Array<Function> = [String, Array]

export default {
  name: 'router-link',
  props: {
    to: {
      type: toTypes,
      required: true
    },
    tag: {
      type: String,
      default: 'a'
    },
    exact: Boolean,
    append: Boolean,
    replace: Boolean,
    activeClass: String,
    event: {
      type: eventTypes,
      default: 'click'
    }
  },
  render (h: Function) {
    const router = this.$router
    const current = this.$route
    const { location, route, href } = router.resolve(this.to, current, this.append)

    const classes = {}
    const globalActiveClass = router.options.linkActiveClass
    // Support global empty active class
    const activeClassFallback = globalActiveClass == null
            ? 'router-link-active'
            : globalActiveClass
    const activeClass = this.activeClass == null
            ? activeClassFallback
            : this.activeClass
    const compareTarget = location.path
      ? createRoute(null, location, null, router)
      : route

    classes[activeClass] = this.exact
      ? isSameRoute(current, compareTarget)
      : isIncludedRoute(current, compareTarget)

    const handler = e => {
      if (guardEvent(e)) {
        if (this.replace) {
          router.replace(location)
        } else {
          router.push(location)
        }
      }
    }

    const on = { click: guardEvent }
    if (Array.isArray(this.event)) {
      this.event.forEach(e => { on[e] = handler })
    } else {
      on[this.event] = handler
    }

    const data: any = {
      class: classes
    }

    if (this.tag === 'a') {
      data.on = on
      data.attrs = { href }
    } else {
      // find the first <a> child and apply listener and href
      const a = findAnchor(this.$slots.default)
      if (a) {
        // in case the <a> is a static node
        a.isStatic = false
        const extend = _Vue.util.extend
        const aData = a.data = extend({}, a.data)
        aData.on = on
        const aAttrs = a.data.attrs = extend({}, a.data.attrs)
        aAttrs.href = href
      } else {
        // doesn't have <a> child, apply listener to self
        data.on = on
      }
    }

    return h(this.tag, data, this.$slots.default)
  }
}

function guardEvent (e) {
  // don't redirect with control keys
  if (e.metaKey || e.ctrlKey || e.shiftKey) return
  // don't redirect when preventDefault called
  if (e.defaultPrevented) return
  // don't redirect on right click
  if (e.button !== undefined && e.button !== 0) return
  // don't redirect if `target="_blank"`
  if (e.currentTarget && e.currentTarget.getAttribute) {
    const target = e.currentTarget.getAttribute('target')
    if (/\b_blank\b/i.test(target)) return
  }
  // this may be a Weex event which doesn't have this method
  if (e.preventDefault) {
    e.preventDefault()
  }
  return true
}

function findAnchor (children) {
  if (children) {
    let child
    for (let i = 0; i < children.length; i++) {
      child = children[i]
      if (child.tag === 'a') {
        return child
      }
      if (child.children && (child = findAnchor(child.children))) {
        return child
      }
    }
  }
}
<commit_msg>add router-link prop: `exact-active-class` & router option: `linkExactActiveClass` (#1361)<commit_after>/* @flow */

import { createRoute, isSameRoute, isIncludedRoute } from '../util/route'
import { _Vue } from '../install'

// work around weird flow bug
const toTypes: Array<Function> = [String, Object]
const eventTypes: Array<Function> = [String, Array]

export default {
  name: 'router-link',
  props: {
    to: {
      type: toTypes,
      required: true
    },
    tag: {
      type: String,
      default: 'a'
    },
    exact: Boolean,
    append: Boolean,
    replace: Boolean,
    activeClass: String,
    exactActiveClass: String,
    event: {
      type: eventTypes,
      default: 'click'
    }
  },
  render (h: Function) {
    const router = this.$router
    const current = this.$route
    const { location, route, href } = router.resolve(this.to, current, this.append)

    const classes = {}
    const globalActiveClass = router.options.linkActiveClass
    const globalExactActiveClass = router.options.linkExactActiveClass
    // Support global empty active class
    const activeClassFallback = globalActiveClass == null
            ? 'router-link-active'
            : globalActiveClass
    const exactActiveClassFallback = globalExactActiveClass == null
            ? 'router-link-exact-active'
            : globalExactActiveClass
    const activeClass = this.activeClass == null
            ? activeClassFallback
            : this.activeClass
    const exactActiveClass = this.exactActiveClass == null
            ? exactActiveClassFallback
            : this.exactActiveClass
    const compareTarget = location.path
      ? createRoute(null, location, null, router)
      : route

    classes[exactActiveClass] = isSameRoute(current, compareTarget)
    classes[activeClass] = this.exact
      ? classes[exactActiveClass]
      : isIncludedRoute(current, compareTarget)

    const handler = e => {
      if (guardEvent(e)) {
        if (this.replace) {
          router.replace(location)
        } else {
          router.push(location)
        }
      }
    }

    const on = { click: guardEvent }
    if (Array.isArray(this.event)) {
      this.event.forEach(e => { on[e] = handler })
    } else {
      on[this.event] = handler
    }

    const data: any = {
      class: classes
    }

    if (this.tag === 'a') {
      data.on = on
      data.attrs = { href }
    } else {
      // find the first <a> child and apply listener and href
      const a = findAnchor(this.$slots.default)
      if (a) {
        // in case the <a> is a static node
        a.isStatic = false
        const extend = _Vue.util.extend
        const aData = a.data = extend({}, a.data)
        aData.on = on
        const aAttrs = a.data.attrs = extend({}, a.data.attrs)
        aAttrs.href = href
      } else {
        // doesn't have <a> child, apply listener to self
        data.on = on
      }
    }

    return h(this.tag, data, this.$slots.default)
  }
}

function guardEvent (e) {
  // don't redirect with control keys
  if (e.metaKey || e.ctrlKey || e.shiftKey) return
  // don't redirect when preventDefault called
  if (e.defaultPrevented) return
  // don't redirect on right click
  if (e.button !== undefined && e.button !== 0) return
  // don't redirect if `target="_blank"`
  if (e.currentTarget && e.currentTarget.getAttribute) {
    const target = e.currentTarget.getAttribute('target')
    if (/\b_blank\b/i.test(target)) return
  }
  // this may be a Weex event which doesn't have this method
  if (e.preventDefault) {
    e.preventDefault()
  }
  return true
}

function findAnchor (children) {
  if (children) {
    let child
    for (let i = 0; i < children.length; i++) {
      child = children[i]
      if (child.tag === 'a') {
        return child
      }
      if (child.children && (child = findAnchor(child.children))) {
        return child
      }
    }
  }
}
<|endoftext|>


<commit_before>import React, {Component, PropTypes, isValidElement, cloneElement} from 'react'
import cx from 'classnames'

import './list.scss'

export default class List extends Component {
	static propTypes = {
		canSelect: PropTypes.bool,
		children: PropTypes.any.isRequired,
		className: PropTypes.string,
		onChange: PropTypes.func,
		seperator: PropTypes.string,
		type: PropTypes.oneOf(['inline', 'number', 'bullet', 'plain']).isRequired,
	}

	static defaultProps = {
		type: 'inline',
	}

	render() {
		const contents = React.Children.map(this.props.children, child =>
			isValidElement(child) && child.type === 'li'
				? cloneElement(child, {className: 'list-item'})
				:
{child}

		)

		const className = cx('list', `list--${this.props.type}`, this.props.className)

		if (this.props.type === 'number') {
			return
{contents}

		}

		return
{contents}

	}
}
<commit_msg>allow specifying the className on list children<commit_after>import React, {Component, PropTypes, isValidElement, cloneElement} from 'react'
import cx from 'classnames'

import './list.scss'

export default class List extends Component {
	static propTypes = {
		canSelect: PropTypes.bool,
		children: PropTypes.any.isRequired,
		className: PropTypes.string,
		onChange: PropTypes.func,
		seperator: PropTypes.string,
		type: PropTypes.oneOf(['inline', 'number', 'bullet', 'plain']).isRequired,
	}

	static defaultProps = {
		type: 'inline',
	}

	render() {
		const contents = React.Children.map(this.props.children, child =>
			isValidElement(child) && child.type === 'li'
				? cloneElement(child, {className: cx('list-item', child.props.className)})
				:
{child}

		)

		const className = cx('list', `list--${this.props.type}`, this.props.className)

		if (this.props.type === 'number') {
			return
{contents}

		}

		return
{contents}

	}
}
<|endoftext|>


<commit_before>import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Landing from './landing';
import Dashboard from './dashboard';
import WishlistPublic from './wishlistPublic';
import WishlistPrivate from './wishlistPrivate';
import Pairing from './pairing';
import Messaging from './messaging';
import SecureOrg from './secureOrg';

const Main = (props) => {
  return (

      <Switch>
        <Route exact path="/" component={Landing} />
        <Route path="/dashboard" component={Dashboard} />
        <Route path="/wishlist" component={WishlistPublic} />
        <Route path="/secure/wishlist" component={WishlistPrivate} /> {/* Secure */}
        <Route path="/secure/pairing" component={Pairing} /> {/* Secure */}
        <Route path="/secure/messaging" component={Messaging} /> {/* Secure */}
        <Route path="/secure/org" component={SecureOrg} /> {/* Secure */}
      </Switch>

          <button>
            Home
          </button>

  )
}

export default Main;<commit_msg>Linter source formatting correctionp<commit_after>import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Landing from './landing';
import Dashboard from './dashboard';
import WishlistPublic from './wishlistPublic';
import WishlistPrivate from './wishlistPrivate';
import Pairing from './pairing';
import Messaging from './messaging';
import SecureOrg from './secureOrg';

const Main = (props) => {
  return (

      <Switch>
        <Route exact path="/" component={Landing} />
        <Route path="/dashboard" component={Dashboard} />
        <Route path="/wishlist" component={WishlistPublic} />
        <Route path="/secure/wishlist" component={WishlistPrivate} /> {/* Secure */}
        <Route path="/secure/pairing" component={Pairing} /> {/* Secure */}
        <Route path="/secure/messaging" component={Messaging} /> {/* Secure */}
        <Route path="/secure/org" component={SecureOrg} /> {/* Secure */}
      </Switch>

          <button>
            Home
          </button>

  );
};

export default Main;<|endoftext|>


<commit_before>import React from 'react'
import _ from 'lodash'

const SIZE = 30
    , HEIGHT = 2 * SIZE
    , WIDTH = Math.sqrt(3) / 2 * HEIGHT

export default class Tile extends React.Component {

  render() {
    const { x, y, data } = this.props

    let points = [
      [0          , .25 * HEIGHT]
    , [.5 * WIDTH , 0           ]
    , [WIDTH      , .25 * HEIGHT]
    , [WIDTH      , .75 * HEIGHT]
    , [.5 * WIDTH , HEIGHT      ]
    , [0          , .75 * HEIGHT]
    ]

    const origin = {
      x: x * WIDTH  + y % 2 * 1/2 * WIDTH
    , y: y * 3/4 * HEIGHT
    }

    points = _.map(points, function(tuple) { return (origin.x + tuple[0]) + ',' + (origin.y + tuple[1]) }).join(' ')

    const textStyle = {
      fontFamily: 'Consolas',
      fontSize  : '12px',
      fill      : '#ffffff',
      stroke    : '#000000'
    }

    return (
      <g>
        <polygon points={ points } fill="rgba(255,0,0,.3)" stroke="black"/>
        <text x={ origin.x + 1 * WIDTH / 3 } y={ origin.y + 1 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[0] }</text>
        <text x={ origin.x + 2 * WIDTH / 3 } y={ origin.y + 1 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[1] }</text>
        <text x={ origin.x + 1 * WIDTH / 3 } y={ origin.y + 2 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[2] }</text>
        <text x={ origin.x + 2 * WIDTH / 3 } y={ origin.y + 2 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[3] }</text>
        <text x={ origin.x + 1 * WIDTH / 2 } y={ origin.y + 4 * HEIGHT / 5 } style={ textStyle }>{ data.fidsi[4] }</text>
      </g>
    )
  }

}
<commit_msg>Improve functional treatment of polygon points<commit_after>import React from 'react'
import _ from 'lodash'

const SIZE = 30
    , HEIGHT = 2 * SIZE
    , WIDTH = Math.sqrt(3) / 2 * HEIGHT

export default class Tile extends React.Component {

  render() {
    const { x, y, data } = this.props
        , points = [
            [0          , .25 * HEIGHT]
          , [.5 * WIDTH , 0           ] // top
          , [WIDTH      , .25 * HEIGHT]
          , [WIDTH      , .75 * HEIGHT]
          , [.5 * WIDTH , HEIGHT      ] // bottom
          , [0          , .75 * HEIGHT]
          ]
        , origin = [
            x * WIDTH  + y % 2 * 1/2 * WIDTH // x coord
          , y * 3/4 * HEIGHT // y coord
          ]

    function translateToOrigin(coord, idx) {
      return origin[idx] + coord
    }

    const pointsStr = _
      .chain(points) // [[x1,y1],[x2,y2]]
      .map(_.partial(_.map, _, translateToOrigin)) // adds origin x/y, [[x1',y1'],[x2',y2']]
      .map(_.partial(_.join, _, ',')) // transform coord to string, ["x1,y1","x2,y2"]
      .join(' ') // add all points, "x1,y1 x2,y2"
      .value()

    const textStyle = {
      fontFamily: 'Consolas',
      fontSize  : '12px',
      fill      : '#ffffff',
      stroke    : '#000000'
    }

    return (
      <g>
        <polygon points={ pointsStr } fill="rgba(255,0,0,.3)" stroke="black"/>
        <text x={ origin[0] + 1 * WIDTH / 3 } y={ origin[1] + 1 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[0] }</text>
        <text x={ origin[0] + 2 * WIDTH / 3 } y={ origin[1] + 1 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[1] }</text>
        <text x={ origin[0] + 1 * WIDTH / 3 } y={ origin[1] + 2 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[2] }</text>
        <text x={ origin[0] + 2 * WIDTH / 3 } y={ origin[1] + 2 * HEIGHT / 3 } style={ textStyle }>{ data.fidsi[3] }</text>
        <text x={ origin[0] + 1 * WIDTH / 2 } y={ origin[1] + 4 * HEIGHT / 5 } style={ textStyle }>{ data.fidsi[4] }</text>
      </g>
    )
  }

}
<|endoftext|>


<commit_before><commit_msg>Gram Schmidt in EMC6<commit_after><|endoftext|>


<commit_before><commit_msg>[API.Notification] Refactoring parameters and update comments<commit_after><|endoftext|>


<commit_before><commit_msg>     <commit_after><|endoftext|>


<commit_before><commit_msg>cancel to routeStopPage<commit_after><|endoftext|>


<commit_before><commit_msg>Allow ES explain, fix check of search engine (#74)<commit_after><|endoftext|>


<commit_before>define(["jquery", "text!./simpletablethemed.css"], function($, cssContent) {'use strict';
	$("


<commit_before><commit_msg>unfollow without deleting from db<commit_after><|endoftext|>


<commit_before><commit_msg>Strip conflict info in `scrubNexsonForTransport`<commit_after><|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name DomEvent
 * @namespace
 * @private
 */
var DomEvent = {
	add: function(el, events) {
		for (var type in events) {
			var func = events[type];
			if (el.addEventListener) {
				el.addEventListener(type, func, false);
			} else if (el.attachEvent) {
				// Make a bound closure that calls on the right object and
				// passes on the global event object as a parameter.
				el.attachEvent('on' + type, func.bound = function() {
					func.call(el, window.event);
				});
			}
		}
	},

	remove: function(el, events) {
		for (var type in events) {
			var func = events[type];
			if (el.removeEventListener) {
				el.removeEventListener(type, func, false);
			} else if (el.detachEvent) {
				// Remove the bound closure instead of func itself
				el.detachEvent('on' + type, func.bound);
			}
		}
	},

	getPoint: function(event) {
		var pos = event.targetTouches
				? event.targetTouches.length
					? event.targetTouches[0]
					: event.changedTouches[0]
				: event;
		return new Point(
			pos.pageX || pos.clientX + document.documentElement.scrollLeft,
			pos.pageY || pos.clientY + document.documentElement.scrollTop
		);
	},

	getTarget: function(event) {
		return event.target || event.srcElement;
	},

	getOffset: function(event, target) {
		// Remove target offsets from page coordinates
		return DomEvent.getPoint(event).subtract(DomElement.getOffset(
				target || DomEvent.getTarget(event)));
	},

	preventDefault: function(event) {
		if (event.preventDefault) {
			event.preventDefault();
		} else {
			// IE
			event.returnValue = false;
		}
	},

	stopPropagation: function(event) {
		if (event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}
	},

	stop: function(event) {
		DomEvent.stopPropagation(event);
		DomEvent.preventDefault(event);
	}
};

DomEvent.requestAnimationFrame = new function() {
	var nativeRequest = DomElement.getPrefixValue(window,
			'requestAnimationFrame'),
		requested = false,
		callbacks = [],
		focused = true,
		timer;

	DomEvent.add(window, {
		focus: function() {
			focused = true;
		},
		blur: function() {
			focused = false;
		}
	});

	function handleCallbacks() {
		// Checks all installed callbacks for element visibility and
		// execute if needed.
		for (var i = callbacks.length - 1; i >= 0; i--) {
			var entry = callbacks[i],
				func = entry[0],
				el = entry[1];
			if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true'
					|| focused) && DomElement.isInView(el)) {
				// Only remove from the list once the callback was called. This
				// could take a long time based on visibility. But this way we
				// are sure to keep the animation loop running.
				callbacks.splice(i, 1);
				func();
			}
		}
		if (nativeRequest) {
			if (callbacks.length) {
				// If we haven't processed all callbacks yet, we need to keep
				// the loop running, as otherwise it would die off.
				nativeRequest(handleCallbacks);
			} else {
				requested = false;
			}
		}
	}

	return function(callback, element) {
		// Add to the list of callbacks to be called in the next animation
		// frame.
		callbacks.push([callback, element]);
		if (nativeRequest) {
			// Handle animation natively. We only need to request the frame
			// once for all collected callbacks.
			if (!requested) {
				nativeRequest(handleCallbacks);
				requested = true;
			}
		} else if (!timer) {
			// Install interval timer that checks all callbacks. This
			// results in faster animations than repeatedly installing
			// timout timers.
			timer = setInterval(handleCallbacks, 1000 / 60);
		}
	};
};
<commit_msg>Remove legacy browser code since we're not supporting IE8 and below.<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name DomEvent
 * @namespace
 * @private
 */
var DomEvent = {
	add: function(el, events) {
		for (var type in events)
			el.addEventListener(type, events[type], false);
	},

	remove: function(el, events) {
		for (var type in events)
			el.removeEventListener(type, events[type], false);
	},

	getPoint: function(event) {
		var pos = event.targetTouches
				? event.targetTouches.length
					? event.targetTouches[0]
					: event.changedTouches[0]
				: event;
		return new Point(
			pos.pageX || pos.clientX + document.documentElement.scrollLeft,
			pos.pageY || pos.clientY + document.documentElement.scrollTop
		);
	},

	getTarget: function(event) {
		return event.target || event.srcElement;
	},

	getOffset: function(event, target) {
		// Remove target offsets from page coordinates
		return DomEvent.getPoint(event).subtract(DomElement.getOffset(
				target || DomEvent.getTarget(event)));
	},

	preventDefault: function(event) {
		if (event.preventDefault) {
			event.preventDefault();
		} else {
			// IE
			event.returnValue = false;
		}
	},

	stopPropagation: function(event) {
		if (event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}
	},

	stop: function(event) {
		DomEvent.stopPropagation(event);
		DomEvent.preventDefault(event);
	}
};

DomEvent.requestAnimationFrame = new function() {
	var nativeRequest = DomElement.getPrefixValue(window,
			'requestAnimationFrame'),
		requested = false,
		callbacks = [],
		focused = true,
		timer;

	DomEvent.add(window, {
		focus: function() {
			focused = true;
		},
		blur: function() {
			focused = false;
		}
	});

	function handleCallbacks() {
		// Checks all installed callbacks for element visibility and
		// execute if needed.
		for (var i = callbacks.length - 1; i >= 0; i--) {
			var entry = callbacks[i],
				func = entry[0],
				el = entry[1];
			if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true'
					|| focused) && DomElement.isInView(el)) {
				// Only remove from the list once the callback was called. This
				// could take a long time based on visibility. But this way we
				// are sure to keep the animation loop running.
				callbacks.splice(i, 1);
				func();
			}
		}
		if (nativeRequest) {
			if (callbacks.length) {
				// If we haven't processed all callbacks yet, we need to keep
				// the loop running, as otherwise it would die off.
				nativeRequest(handleCallbacks);
			} else {
				requested = false;
			}
		}
	}

	return function(callback, element) {
		// Add to the list of callbacks to be called in the next animation
		// frame.
		callbacks.push([callback, element]);
		if (nativeRequest) {
			// Handle animation natively. We only need to request the frame
			// once for all collected callbacks.
			if (!requested) {
				nativeRequest(handleCallbacks);
				requested = true;
			}
		} else if (!timer) {
			// Install interval timer that checks all callbacks. This
			// results in faster animations than repeatedly installing
			// timout timers.
			timer = setInterval(handleCallbacks, 1000 / 60);
		}
	};
};
<|endoftext|>


<commit_before>var root = typeof global !== 'undefined' ? global : window;

/**
 * Global object with classes, properties and methods you can access in fireball editor.
 *
 * @module Editor
 * @main Editor
 */

if (!root.Editor) {
    // Always export Editor globally.
    root.Editor = {};
}

//// extends engine
//require('./extends/runtime');

require('./serialize');
require('./get-node-dump');

module.exports = Editor;
<commit_msg>redirect log methods to fireball console<commit_after>var root = typeof global !== 'undefined' ? global : window;

/**
 * Global object with classes, properties and methods you can access in fireball editor.
 *
 * @module Editor
 * @main Editor
 */

if (!root.Editor) {
    // Always export Editor globally.
    root.Editor = {};
}

//// extends engine
//require('./extends/runtime');

require('./serialize');
require('./get-node-dump');

// redirect log methods to fireball console
Fire.log = Editor.log;
Fire.info = Editor.info;
Fire.warn = Editor.warn;
Fire.error = Editor.error;

module.exports = Editor;
<|endoftext|>


<commit_before>function call(fn, ...args) {
  let context

  if (Array.isArray(fn)) {
    context = fn[1]
    fn = fn[0]
  }

  if (typeof fn !== 'function') {
    throw new TypeError(
      'The first argument to "call" must be a function or an array containing a function'
    )
  }

  return { effect: 'call', fn, context, args }
}

function callHandler(effect) {
  let { fn, context, args } = effect

  if (typeof fn !== 'function') {
    throw new TypeError('"fn" must be a function')
  }

  let value = args ? fn.apply(context, args) : fn.call(context)
  return { effect: '_resolve', value }
}

module.exports.factory = call
module.exports.handler = callHandler
<commit_msg>Swap the context/fn order in the "call" effect<commit_after>function call(fn, ...args) {
  let context

  if (Array.isArray(fn)) {
    context = fn[0]
    fn = fn[1]
  }

  if (typeof fn !== 'function') {
    throw new TypeError(
      'The first argument to "call" must be a function or an array containing a function'
    )
  }

  return { effect: 'call', fn, context, args }
}

function callHandler(effect) {
  let { fn, context, args } = effect

  if (typeof fn !== 'function') {
    throw new TypeError('"fn" must be a function')
  }

  let value = args ? fn.apply(context, args) : fn.call(context)
  return { effect: '_resolve', value }
}

module.exports.factory = call
module.exports.handler = callHandler
<|endoftext|>


<commit_before>JanusFireboxParser = function() {
}

JanusFireboxParser.prototype.parse = function(source, baseurl, datapath) {
  var xml = this.parseXML(source, false, true);
  var rooms = this.getAsArray(this.arrayget(xml, 'fireboxroom._children.room', {}));
  var room = {_children: {}};
  for (var i = 0; i < rooms.length; i++) {
    var attrs = Object.keys(rooms[i]).filter(function(k) { return (k[0] != '_'); });
    attrs.forEach(function(k) {
      room[k] = rooms[i][k];
    });
    if (rooms[i]._children) {
      Object.keys(rooms[i]._children).forEach(function(k) {
        room._children[k] = rooms[i]._children[k];
      });
    }
  }
  var roomdata = this.getRoomData(xml, room, baseurl, datapath);
  roomdata.source = source;
  return roomdata;
}
JanusFireboxParser.prototype.getRoomData = function(xml, room, baseurl, datapath) {
  var assets = this.parseAssets(xml, baseurl, datapath);

  var parseNode = this.parseNode.bind(this);

  var roomdata = {
    assets: assets,
    room: this.parseNode(room)
  };
  for (var k in room._children) {
    var objects = this.getAsArray(room._children[k]);
    roomdata[k] = objects.map(parseNode);
  }

  // TODO - some rooms have orphan objects, outside of the <Room> tag.
  // We should parse these too, but I don't have any examples to test with
/*
  var orphantypes = ['link', 'image', 'image3d', 'video', 'sound', 'text', 'paragraph', 'light', 'particle', 'ghost'];
  for (var i = 0; i < orphantypes.length; i++) {
    var type = orphantypes[i],
        orphans = this.getAsArray(this.arrayget(xml, 'fireboxroom._children.' + type));
    if (orphans && orphans.length > 0) {
      if (!roomdata[type]) roomdata[type] = [];
      roomdata[type].push.apply(roomdata[type], orphans);
    }
  };
*/
  return roomdata;
}
JanusFireboxParser.prototype.getAsArray = function(arr) {
  return (arr instanceof Array ? arr : [arr]);
}
JanusFireboxParser.prototype.parseAssets = function(xml, baseurl, datapath) {
  var assetxml = this.arrayget(xml, 'fireboxroom._children.assets.0', {});
  var objectassets = this.getAsArray(this.arrayget(assetxml, "_children.assetobject", []));
  var soundassets = this.getAsArray(this.arrayget(assetxml, "_children.assetsound", []));
  var imageassets = this.getAsArray(this.arrayget(assetxml, "_children.assetimage", []));
  var videoassets = this.getAsArray(this.arrayget(assetxml, "_children.assetvideo", []));
  var scriptassets = this.getAsArray(this.arrayget(assetxml, "_children.assetscript", []));
  var ghostassets = this.getAsArray(this.arrayget(assetxml, "_children.assetghost", []));
  var websurfaceassets = this.getAsArray(this.arrayget(assetxml, "_children.assetwebsurface", []));
  var assetlist = [];
  if (!datapath) {
    datapath = 'http://web.janusvr.com/media';
  }
  var fixURLEncoding = this.fixURLEncoding.bind(this);
  imageassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({ assettype:'image', name:n.id, src: src, baseurl: baseurl, hasalpha: n.hasalpha, proxy: n.proxy });
  });
  videoassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype:'video',
      name:n.id,
      src: src,
      loop: n.loop,
      sbs3d: n.sbs3d == 'true',
      ou3d: n.ou3d == 'true',
      auto_play: n.auto_play == 'true',
      baseurl: baseurl,
      proxy: n.proxy && n.proxy != 'false'
    });
  });
  soundassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype:'sound',
      name:n.id,
      src: src,
      baseurl: baseurl
    });
  });
  var websurfaces = {};
  websurfaceassets.forEach(function(n) { websurfaces[n.id] = n; });
  scriptassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype:'script',
      name: src,
      src: src,
      baseurl: baseurl
    });
  });

  var objlist = [];
  objectassets.forEach(function(n) {
    if (n.src) {
      var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
      var mtlsrc = (n.mtl && n.mtl.match(/^file:/) ? n.mtl.replace(/^file:/, datapath) : n.mtl);
      if (mtlsrc && !mtlsrc.match(/^(https?:)?\/\//)) mtlsrc = baseurl + mtlsrc;
      var srcparts = src.split(' ');
      src = srcparts[0];
      assetlist.push({assettype: 'model', name: n.id, src: src, mtl: mtlsrc, tex_linear: n.tex_linear, tex0: n.tex || n.tex0 || srcparts[1], tex1: n.tex1 || srcparts[2], tex2: n.tex2 || srcparts[3], tex3: n.tex3 || srcparts[4]});
    }
  });
  var assets = {
    object: objectassets,
    image: imageassets,
    sound: soundassets,
    video: videoassets,
    websurfaces: websurfaces,
    scripts: scriptassets,
    ghosts: ghostassets,
    assetlist: assetlist
  };
  return assets;
}

JanusFireboxParser.prototype.getVectorValue = function(vector, defaultvalue) {
  if (typeof defaultvalue == 'undefined') {
    defaultvalue = null;//[0,0,0];
  }
  if (typeof vector == 'string') {
    return vector.split(' ').map(parseFloat);
  } else if (vector instanceof THREE.Vector3) {
    return vector.toArray();
  } else if (typeof vector == 'undefined') {
    return defaultvalue;
  }
  return vector;
}
JanusFireboxParser.prototype.parseNode = function(n) {
  var nodeinfo = {};
  var attrs = Object.keys(n);
  attrs.forEach(function(k) {
    nodeinfo[k] = (n[k] == 'false' ? false : n[k]);
  });

  nodeinfo.pos = this.getVectorValue(n.pos);
  nodeinfo.scale = this.getVectorValue(n.scale, [1,1,1]);
  nodeinfo.orientation = this.getOrientation(n.xdir, n.ydir || n.up, n.zdir || n.fwd);
  nodeinfo.col = (n.col ? (n.col[0] == '#' ? [parseInt(n.col.substr(1,2), 16)/255, parseInt(n.col.substr(3, 2), 16)/255, parseInt(n.col.substr(5, 2), 16)/255] : n.col) : null);

  var minscale = 1e-6;
/*
  nodeinfo.scale[0] = Math.max(minscale, nodeinfo.scale[0]);
  nodeinfo.scale[1] = Math.max(minscale, nodeinfo.scale[1]);
  nodeinfo.scale[2] = Math.max(minscale, nodeinfo.scale[2]);
*/
  if (nodeinfo.scale[0] < minscale && nodeinfo.scale[0] > -minscale) nodeinfo.scale[0] = minscale;
  if (nodeinfo.scale[1] < minscale && nodeinfo.scale[1] > -minscale) nodeinfo.scale[1] = minscale;
  if (nodeinfo.scale[2] < minscale && nodeinfo.scale[2] > -minscale) nodeinfo.scale[2] = minscale;

  return nodeinfo;
}

JanusFireboxParser.prototype.getOrientation = function(xdir, ydir, zdir) {
  if (xdir) {
    xdir = (xdir instanceof THREE.Vector3 ? xdir : new THREE.Vector3().fromArray(xdir.split(' '))).normalize();
  } else {
    xdir = new THREE.Vector3(1,0,0);
  }
  if (ydir) {
    ydir = (ydir instanceof THREE.Vector3 ? ydir : new THREE.Vector3().fromArray(ydir.split(' '))).normalize();
  } else {
    ydir = new THREE.Vector3(0,1,0);
  }
  if (zdir) {
    zdir = (zdir instanceof THREE.Vector3 ? zdir : new THREE.Vector3().fromArray(zdir.split(' '))).normalize();
  } else {
    zdir = new THREE.Vector3(0,0,1);
  }

  var newydir = ydir.clone().sub(zdir).multiplyScalar(ydir.dot(zdir)).normalize();
  xdir.crossVectors(ydir, zdir).normalize();

  var mat4 = new THREE.Matrix4().makeBasis(xdir, ydir, zdir);
  var quat = new THREE.Quaternion();
  var pos = new THREE.Vector3();
  var scale = new THREE.Vector3();
  //quat.setFromRotationMatrix(mat4);
  mat4.decompose(pos, quat, scale);
  quat.normalize();
  //quat.multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0)));
  return quat;
}
JanusFireboxParser.prototype.parseXML = function(imgxml, leaf, forceLower) {
  var node, root, parent, xmldoc;
  if (imgxml.nodeName) {
    xmldoc = node = imgxml;
  } else {
    try {
      if (window.DOMParser) {
        var parser = new DOMParser();
        xmldoc = parser.parseFromString(imgxml,"application/xml");
        node = xmldoc.firstChild;
      } else {
        node = new ActiveXObject("Microsoft.XMLDOM");
        node.async = "false";
        node.loadXML(imgxml).firstChild;
      }

      // Chrome doesn't throw an exception for malformed XML, so we look for a <parsererror> xml tag
      var parsererrors = node.getElementsByTagName("parsererror");
      if (parsererrors.length > 0) {
        // Extract the message from the first div child of the <parsererror> element
        var errorel = parsererrors[0].getElementsByTagName('div')[0] || parsererrors[0];
        throw new JanusFireboxParserException(errorel.innerHTML);
      }
    } catch (e) {
      throw new JanusFireboxParserException(e.message);
    }
  }
  root = {};
  if (!leaf) {
    var rootname = node.tagName;
    if (forceLower) rootname = rootname.toLowerCase();
    if (!root[rootname]) root[rootname] = {};
    parent = root[rootname];
    //node = parent[node.tagName];
  } else {
    parent = root;
  }
  if (node.attributes) {
    for (var i = 0; i < node.attributes.length; i++) {
      var name = node.attributes[i].nodeName;
      if (forceLower) name = name.toLowerCase();
      var value = node.attributes[i].nodeValue;
      parent[name] = value;
    }
  }
  if (node.childNodes) {
    for (var j = 0; j < node.childNodes.length; j++) {
      var child = node.childNodes[j];
      var nodename = child.nodeName;
      if (forceLower) nodename = nodename.toLowerCase();
      if (!parent._children) parent._children = {};
      if (!parent._children[nodename]) {
        parent._children[nodename] = [];
      } else if (parent._children[nodename].constructor !== Array) {
        parent._children[nodename] = [parent._children[nodename]];
      }
      if (node.getElementsByTagName(child.tagName).length > 0) {
        parent._children[nodename].push(this.parseXML(child, true, forceLower));
      } else if (child.nodeName) {
        if (child.nodeName == "#text" || child.nodeName == "#cdata-section") {
          // this gets confused if you have multiple text/cdata nodes...
          if (!child.nodeValue.match(/^[\s\n]*$/m)) {
            parent._content = child.nodeValue;
          }
        } else {
          parent._children[nodename] = parent._children[nodename].concat(this.parseXML(child, true, forceLower));
        }
      }
    }
  }
  return root;
};

/**
 * Retrieves specified dot-separated value from a multilevel object element
 *
 * @function JanusFireboxParser.arrayget
 * @param {object} obj
 * @param {string} name
 * @param {object|number|string} [defval] default value if none found
*/
JanusFireboxParser.prototype.arrayget = function(obj, name, defval) {
  var ptr = obj;
  var x = name.split(".");
  for (var i = 0; i < x.length; i++) {
    if (ptr==null || (!(ptr[x[i]] instanceof Array) && !(ptr[x[i]] instanceof Object) && i != x.length-1)) {
      ptr = null;
      break;
    }
    ptr = ptr[x[i]];
  }
  if (typeof ptr == "undefined" || ptr === null) {
    return (typeof defval == "undefined" ? null : defval);
  }
  return ptr;
};

/**
 * Fixes encoding of URL strings if they weren't properly encoded
 *
 * @function JanusFireboxParser.fixURLEncoding
 * @param {string} url
 * @returns {string} encoded URL
*/
JanusFireboxParser.prototype.fixURLEncoding = function(url) {
  var fixed = url;
  if (url.indexOf(' ') != -1) {
    fixed = encodeURI(url);
  }
  return fixed;
};

/**
 * Exception class for XML parse errors
 */
function JanusFireboxParserException(msg) {
  this.message = msg;
}
<commit_msg>Pass sbs3d ou3d and reverse3d parameters for image assets<commit_after>JanusFireboxParser = function() {
}

JanusFireboxParser.prototype.parse = function(source, baseurl, datapath) {
  var xml = this.parseXML(source, false, true);
  var rooms = this.getAsArray(this.arrayget(xml, 'fireboxroom._children.room', {}));
  var room = {_children: {}};
  for (var i = 0; i < rooms.length; i++) {
    var attrs = Object.keys(rooms[i]).filter(function(k) { return (k[0] != '_'); });
    attrs.forEach(function(k) {
      room[k] = rooms[i][k];
    });
    if (rooms[i]._children) {
      Object.keys(rooms[i]._children).forEach(function(k) {
        room._children[k] = rooms[i]._children[k];
      });
    }
  }
  var roomdata = this.getRoomData(xml, room, baseurl, datapath);
  roomdata.source = source;
  return roomdata;
}
JanusFireboxParser.prototype.getRoomData = function(xml, room, baseurl, datapath) {
  var assets = this.parseAssets(xml, baseurl, datapath);

  var parseNode = this.parseNode.bind(this);

  var roomdata = {
    assets: assets,
    room: this.parseNode(room)
  };
  for (var k in room._children) {
    var objects = this.getAsArray(room._children[k]);
    roomdata[k] = objects.map(parseNode);
  }

  // TODO - some rooms have orphan objects, outside of the <Room> tag.
  // We should parse these too, but I don't have any examples to test with
/*
  var orphantypes = ['link', 'image', 'image3d', 'video', 'sound', 'text', 'paragraph', 'light', 'particle', 'ghost'];
  for (var i = 0; i < orphantypes.length; i++) {
    var type = orphantypes[i],
        orphans = this.getAsArray(this.arrayget(xml, 'fireboxroom._children.' + type));
    if (orphans && orphans.length > 0) {
      if (!roomdata[type]) roomdata[type] = [];
      roomdata[type].push.apply(roomdata[type], orphans);
    }
  };
*/
  return roomdata;
}
JanusFireboxParser.prototype.getAsArray = function(arr) {
  return (arr instanceof Array ? arr : [arr]);
}
JanusFireboxParser.prototype.parseAssets = function(xml, baseurl, datapath) {
  var assetxml = this.arrayget(xml, 'fireboxroom._children.assets.0', {});
  var objectassets = this.getAsArray(this.arrayget(assetxml, "_children.assetobject", []));
  var soundassets = this.getAsArray(this.arrayget(assetxml, "_children.assetsound", []));
  var imageassets = this.getAsArray(this.arrayget(assetxml, "_children.assetimage", []));
  var videoassets = this.getAsArray(this.arrayget(assetxml, "_children.assetvideo", []));
  var scriptassets = this.getAsArray(this.arrayget(assetxml, "_children.assetscript", []));
  var ghostassets = this.getAsArray(this.arrayget(assetxml, "_children.assetghost", []));
  var websurfaceassets = this.getAsArray(this.arrayget(assetxml, "_children.assetwebsurface", []));
  var assetlist = [];
  if (!datapath) {
    datapath = 'http://web.janusvr.com/media';
  }
  var fixURLEncoding = this.fixURLEncoding.bind(this);
  imageassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype: 'image',
      name: n.id,
      src: src,
      baseurl: baseurl,
      hasalpha: n.hasalpha,
      proxy: n.proxy,
      sbs3d: n.sbs3d,
      ou3d: n.ou3d,
      reverse3d: n.reverse3d,
    });
  });
  videoassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype:'video',
      name:n.id,
      src: src,
      loop: n.loop,
      sbs3d: n.sbs3d == 'true',
      ou3d: n.ou3d == 'true',
      auto_play: n.auto_play == 'true',
      baseurl: baseurl,
      proxy: n.proxy && n.proxy != 'false'
    });
  });
  soundassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype:'sound',
      name:n.id,
      src: src,
      baseurl: baseurl
    });
  });
  var websurfaces = {};
  websurfaceassets.forEach(function(n) { websurfaces[n.id] = n; });
  scriptassets.forEach(function(n) {
    var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
    assetlist.push({
      assettype:'script',
      name: src,
      src: src,
      baseurl: baseurl
    });
  });

  var objlist = [];
  objectassets.forEach(function(n) {
    if (n.src) {
      var src = fixURLEncoding(n.src.match(/^file:/) ? n.src.replace(/^file:/, datapath) : n.src);
      var mtlsrc = (n.mtl && n.mtl.match(/^file:/) ? n.mtl.replace(/^file:/, datapath) : n.mtl);
      if (mtlsrc && !mtlsrc.match(/^(https?:)?\/\//)) mtlsrc = baseurl + mtlsrc;
      var srcparts = src.split(' ');
      src = srcparts[0];
      assetlist.push({assettype: 'model', name: n.id, src: src, mtl: mtlsrc, tex_linear: n.tex_linear, tex0: n.tex || n.tex0 || srcparts[1], tex1: n.tex1 || srcparts[2], tex2: n.tex2 || srcparts[3], tex3: n.tex3 || srcparts[4]});
    }
  });
  var assets = {
    object: objectassets,
    image: imageassets,
    sound: soundassets,
    video: videoassets,
    websurfaces: websurfaces,
    scripts: scriptassets,
    ghosts: ghostassets,
    assetlist: assetlist
  };
  return assets;
}

JanusFireboxParser.prototype.getVectorValue = function(vector, defaultvalue) {
  if (typeof defaultvalue == 'undefined') {
    defaultvalue = null;//[0,0,0];
  }
  if (typeof vector == 'string') {
    return vector.split(' ').map(parseFloat);
  } else if (vector instanceof THREE.Vector3) {
    return vector.toArray();
  } else if (typeof vector == 'undefined') {
    return defaultvalue;
  }
  return vector;
}
JanusFireboxParser.prototype.parseNode = function(n) {
  var nodeinfo = {};
  var attrs = Object.keys(n);
  attrs.forEach(function(k) {
    nodeinfo[k] = (n[k] == 'false' ? false : n[k]);
  });

  nodeinfo.pos = this.getVectorValue(n.pos);
  nodeinfo.scale = this.getVectorValue(n.scale, [1,1,1]);
  nodeinfo.orientation = this.getOrientation(n.xdir, n.ydir || n.up, n.zdir || n.fwd);
  nodeinfo.col = (n.col ? (n.col[0] == '#' ? [parseInt(n.col.substr(1,2), 16)/255, parseInt(n.col.substr(3, 2), 16)/255, parseInt(n.col.substr(5, 2), 16)/255] : n.col) : null);

  var minscale = 1e-6;
/*
  nodeinfo.scale[0] = Math.max(minscale, nodeinfo.scale[0]);
  nodeinfo.scale[1] = Math.max(minscale, nodeinfo.scale[1]);
  nodeinfo.scale[2] = Math.max(minscale, nodeinfo.scale[2]);
*/
  if (nodeinfo.scale[0] < minscale && nodeinfo.scale[0] > -minscale) nodeinfo.scale[0] = minscale;
  if (nodeinfo.scale[1] < minscale && nodeinfo.scale[1] > -minscale) nodeinfo.scale[1] = minscale;
  if (nodeinfo.scale[2] < minscale && nodeinfo.scale[2] > -minscale) nodeinfo.scale[2] = minscale;

  return nodeinfo;
}

JanusFireboxParser.prototype.getOrientation = function(xdir, ydir, zdir) {
  if (xdir) {
    xdir = (xdir instanceof THREE.Vector3 ? xdir : new THREE.Vector3().fromArray(xdir.split(' '))).normalize();
  } else {
    xdir = new THREE.Vector3(1,0,0);
  }
  if (ydir) {
    ydir = (ydir instanceof THREE.Vector3 ? ydir : new THREE.Vector3().fromArray(ydir.split(' '))).normalize();
  } else {
    ydir = new THREE.Vector3(0,1,0);
  }
  if (zdir) {
    zdir = (zdir instanceof THREE.Vector3 ? zdir : new THREE.Vector3().fromArray(zdir.split(' '))).normalize();
  } else {
    zdir = new THREE.Vector3(0,0,1);
  }

  var newydir = ydir.clone().sub(zdir).multiplyScalar(ydir.dot(zdir)).normalize();
  xdir.crossVectors(ydir, zdir).normalize();

  var mat4 = new THREE.Matrix4().makeBasis(xdir, ydir, zdir);
  var quat = new THREE.Quaternion();
  var pos = new THREE.Vector3();
  var scale = new THREE.Vector3();
  //quat.setFromRotationMatrix(mat4);
  mat4.decompose(pos, quat, scale);
  quat.normalize();
  //quat.multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0)));
  return quat;
}
JanusFireboxParser.prototype.parseXML = function(imgxml, leaf, forceLower) {
  var node, root, parent, xmldoc;
  if (imgxml.nodeName) {
    xmldoc = node = imgxml;
  } else {
    try {
      if (window.DOMParser) {
        var parser = new DOMParser();
        xmldoc = parser.parseFromString(imgxml,"application/xml");
        node = xmldoc.firstChild;
      } else {
        node = new ActiveXObject("Microsoft.XMLDOM");
        node.async = "false";
        node.loadXML(imgxml).firstChild;
      }

      // Chrome doesn't throw an exception for malformed XML, so we look for a <parsererror> xml tag
      var parsererrors = node.getElementsByTagName("parsererror");
      if (parsererrors.length > 0) {
        // Extract the message from the first div child of the <parsererror> element
        var errorel = parsererrors[0].getElementsByTagName('div')[0] || parsererrors[0];
        throw new JanusFireboxParserException(errorel.innerHTML);
      }
    } catch (e) {
      throw new JanusFireboxParserException(e.message);
    }
  }
  root = {};
  if (!leaf) {
    var rootname = node.tagName;
    if (forceLower) rootname = rootname.toLowerCase();
    if (!root[rootname]) root[rootname] = {};
    parent = root[rootname];
    //node = parent[node.tagName];
  } else {
    parent = root;
  }
  if (node.attributes) {
    for (var i = 0; i < node.attributes.length; i++) {
      var name = node.attributes[i].nodeName;
      if (forceLower) name = name.toLowerCase();
      var value = node.attributes[i].nodeValue;
      parent[name] = value;
    }
  }
  if (node.childNodes) {
    for (var j = 0; j < node.childNodes.length; j++) {
      var child = node.childNodes[j];
      var nodename = child.nodeName;
      if (forceLower) nodename = nodename.toLowerCase();
      if (!parent._children) parent._children = {};
      if (!parent._children[nodename]) {
        parent._children[nodename] = [];
      } else if (parent._children[nodename].constructor !== Array) {
        parent._children[nodename] = [parent._children[nodename]];
      }
      if (node.getElementsByTagName(child.tagName).length > 0) {
        parent._children[nodename].push(this.parseXML(child, true, forceLower));
      } else if (child.nodeName) {
        if (child.nodeName == "#text" || child.nodeName == "#cdata-section") {
          // this gets confused if you have multiple text/cdata nodes...
          if (!child.nodeValue.match(/^[\s\n]*$/m)) {
            parent._content = child.nodeValue;
          }
        } else {
          parent._children[nodename] = parent._children[nodename].concat(this.parseXML(child, true, forceLower));
        }
      }
    }
  }
  return root;
};

/**
 * Retrieves specified dot-separated value from a multilevel object element
 *
 * @function JanusFireboxParser.arrayget
 * @param {object} obj
 * @param {string} name
 * @param {object|number|string} [defval] default value if none found
*/
JanusFireboxParser.prototype.arrayget = function(obj, name, defval) {
  var ptr = obj;
  var x = name.split(".");
  for (var i = 0; i < x.length; i++) {
    if (ptr==null || (!(ptr[x[i]] instanceof Array) && !(ptr[x[i]] instanceof Object) && i != x.length-1)) {
      ptr = null;
      break;
    }
    ptr = ptr[x[i]];
  }
  if (typeof ptr == "undefined" || ptr === null) {
    return (typeof defval == "undefined" ? null : defval);
  }
  return ptr;
};

/**
 * Fixes encoding of URL strings if they weren't properly encoded
 *
 * @function JanusFireboxParser.fixURLEncoding
 * @param {string} url
 * @returns {string} encoded URL
*/
JanusFireboxParser.prototype.fixURLEncoding = function(url) {
  var fixed = url;
  if (url.indexOf(' ') != -1) {
    fixed = encodeURI(url);
  }
  return fixed;
};

/**
 * Exception class for XML parse errors
 */
function JanusFireboxParserException(msg) {
  this.message = msg;
}
<|endoftext|>


<commit_before>(function()
{
	window.renderQueue = {
    queue: [],
    process: 0,

    /////////////////////////////////////////////////////////////
    addToQueue: function(tid,bustCache) // Add a render job to the queue //
    {
			bustCache = bustCache || false;

      if (this.queue.length == 0) // Show queue if it was hidden
      {
        $("#renderQueue").fadeIn(400);
      }

      var ttype = $(".titles.active #"+tid).attr("type");

      if ($("#q"+tid).length == 0) // check for duplicates
      {
        var startNum = this.queue.push({'id':tid, 'type':ttype, bustCache:bustCache}); // Add title id to the queue
        var titleName = $(".titles.active #"+tid).text().trim(); // Get actual title for queue status box
    	  $('#renderQueue').append('

✓



 ' + titleName + '

');
      }
      else if ($("#q"+tid).css("background-color") == "rgb(0, 255, 0)")
      {
        $("#q"+tid).remove();
        this.addToQueue(tid);
      }
    },

    /////////////////////////////////////////////////////////////////////////////
    removeFromQueue: function(castaway) // Remove a single item from the queue //
    {
      var ttype = $("#"+castaway).attr("type");
      var index, i;
      //var index = this.queue.indexOf({'id':castaway, 'type':ttype});
      for (i=0; i < this.queue.length; i++) // I know this is the nieve way...
      {
        if (this.queue[i].id == castaway)
        {
          index = i;
        }
      }

      if (!this.queue[index]) // See if it is even there
      {
        this.pruneQueue(); // prune queue if not
        return;
      }

      var tempID = this.queue[index].id;
      this.queue.splice(index, 1);

      if (this.queue.length == 0)
      {
        setTimeout('$("#renderQueue").fadeOut(400)', 401); // Hide empty queue
      }

      $("#q"+tempID).fadeOut(400, function(){
        $("#q"+tempID).remove();
      });

    },

    ////////////////////////////////////////////////////////////////////////////
    moveInQueue: function(destination, traveler) // Move an item in the queue //
    {
      var ttype = $("#"+traveler).attr("type");

      var startIndex, i;
      //var index = this.queue.indexOf({'id':castaway, 'type':ttype});
      for (i=0; i < this.queue.length; i++) // I know this is the nieve way...
      {
        if (this.queue[i].id == traveler)
        {
          index = i;
        }
      }

      var tempItem = this.queue.splice(startIndex,1);
      var tempName = this.queue[destination].id;

      $("#q"+tempItem[0].id).fadeOut(400, function(){
        $(this).insertBefore( $("#q"+tempName) );
        $(this).fadeIn(400);
      });

      this.queue.splice(destination, 0, tempItem[0]);

      //alert(this.queue[destination]);
    },

    //////////////////////////////////////////////////////////////////////////////////
    processQueue: function(index, recursive) // Start rendering queue (single pass) //
    {

      index = index ? index : 0;

      if (this.queue.length == 0) // Don't mess with an empty queue
      {
        alert("Render Queue is already complete!");
        return;
      }
      else if ((process == 1) && (recursive == 0)) // If processing is happening when called from the UI...
      {
        process = 0; // Pause the processing (naive)
        $("#process").html(""); // Play Icon
      }
      else
      {
        process = 1; // Processing starts
        $("#process").html(""); // Pause Icon
      }

      var url_str;

			var bustCache = '?bustCache=true';

      if (this.queue[index].type == "general")
      {
        url_str = "im_render_title.php?id="+this.queue[index].id;
      } else if (this.queue[index].type == "player") {
        url_str = "im_render_statscard.php?id="+this.queue[index].id;
      }

			if(this.queue[index].bustCache) {
				url_str += bustCache;
			}

    	$.ajax({	// Render a title
    		type: "GET",
    		url: url_str,
        accepts: "image/png",
        async: true,
        timeout: 20000,
    		success: function(data) {
          $("#q"+this.queue[index].id).fadeOut(400, function(){
            $(this).css("background-color", "00FF00"); // Mark as green on the list
          });
          $("#q"+this.queue[index].id).fadeIn(400);

          this.queue.splice(index,1); // Remove first element from queue (it is now done)
          }.bind(renderQueue),
        error: function() {
    			$("#q"+this.queue[index].id).css("background-color", "FF0000"); // Mark as red on list
          index += 1;
    		}.bind(renderQueue),
        complete: function() {
          // Check before recursively calling
          if ((this.queue.length != 0) && (this.queue.length > index) && (process == 1))
          {
            setTimeout(this.processQueue(index, 1));
          }
          else
          {
            process = 0; // Processing has ended
            setTimeout('$("#process").html("")', 801); // Play Icon (timed after color updates)
            setTimeout( 'renderQueue.pruneQueue()' , 408); // Prune when finished
          }
        }.bind(renderQueue)
    	});
    },

    ///////////////////////////////////////////////////////////
    pruneQueue: function() // Remove finished jobs from list //
    {
      if (this.queue.length == 0)
      {
        setTimeout('$("#renderQueue").fadeOut(400)', 401); // Hide empty queue
      }
      $(".queueItem").each( function(i)
      {
        if ($(this).css("background-color") == "rgb(0, 255, 0)")
        {
          $(this).fadeOut(400, function(){
            $(this).remove();
          });
        };
      });
    },

    /////////////////////////////////////////////////////////////
    destroyQueue: function() // Erase queue without predjudice //
    {
      if (this.queue.length == 0) // Don't bother prompting if done
      {
        this.pruneQueue();
      }
      else if(confirm("Permanently remove all jobs?"))
      {
        this.queue.length = 0;
        $(".queueItem").each( function()
        {
          $(this).remove();
        });
        $("#renderQueue").fadeOut(402); // Hide empty queue
      }
    }
	};
}());

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function scoreTitleUpdate(homeTeamScore, awayTeamScore, gameStatus) // Auto-queue the lower third title on score change //
{
  //alert("scoreTitleUpdate called with \nHome: " + homeTeamScore + "\nAway: " + awayTeamScore + "\nString: " + gameStatus);

  var url = "/scoreboard/";
  var tempHome = -1;
  var tempAway = -1;
  var scoreTitleId = -1;

  $("#pane ul li").each( function() {
    if ($(this).text().indexOf("(Score Lower Third)") > 0)
    {
      scoreTitleId = $(this).attr('id');
      return;
    }
  });

  var tempStatus = "Current Score"
  var updateStatus = scoreTitleId + "=gameStatus&text=" + tempStatus;

  $.getJSON(url+"team/1", function(data) { // 1 is home
    $.each(data, function(key, value) {
      if (key == "score")
      {
        if (parseInt(homeTeamScore) == -9001)
        {
          homeTeamScore = value;
          return;
        }

        tempHome = value;
        var updateHome = scoreTitleId + "=hScore&text=" + tempHome;

        if (parseInt(tempHome) != parseInt(homeTeamScore))
        {
          $.ajax({
            type: "POST",
            async: false,
            url: "cdb_update.php",
            data: updateHome,
            success: function() {
              homeTeamScore = tempHome;
              $.ajax({
                type: "POST",
                url: "cdb_update.php",
                data: updateStatus,
                success: function() {
                  window.renderQueue.addToQueue( scoreTitleId );
                }
              });
            }
          });
        }

        return;
      }
    });
  });

  $.getJSON(url+"team/0", function(data) { // 0 is away
    $.each(data, function(key, value) {
      if (key == "score")
      {
        if (parseInt(awayTeamScore) == -9001)
        {
          awayTeamScore = value;
          return;
        }

        tempAway = value;
        var updateAway = scoreTitleId + "=vScore&text=" + tempAway;

        if (parseInt(tempAway) != parseInt(awayTeamScore))
        {
          $.ajax({
            type: "POST",
            async: false,
            url: "cdb_update.php",
            data: updateAway,
            success: function() {
              awayTeamScore = tempAway;
              $.ajax({
                type: "POST",
                url: "cdb_update.php",
                data: updateStatus,
                success: function() {
                  window.renderQueue.addToQueue( ScoreTitleId );
                }
              });
            }
          });
        }

        return;
      }
    });
  });

  setTimeout(function(){scoreTitleUpdate(homeTeamScore, awayTeamScore, gameStatus);}, 10000);
};

$(window).on('beforeunload', function()
{
  if ((eventIdNum) && (parseInt(window.renderQueue.queue.length) != 0)){ // Only in the LIVE UI on empty queue
    return "WARNING: Leaving or reloading will mess up the queue.\n\nQueueing is very important in the titling system and the UK.\n";
  }
});

$(document).ready( function()
{
  $("#renderQueue").hide(); // Hide queue status box until it is needed.

  if (eventIdNum) { // Only in the LIVE UI
    setTimeout(function(){scoreTitleUpdate( -9001, -9001, "Current Score")}, 1000); // Start auto score update
  }
});

<commit_msg>I can't believe this worked, or even appeared to work.<commit_after>(function()
{
	window.renderQueue = {
    queue: [],
    process: 0,

    /////////////////////////////////////////////////////////////
    addToQueue: function(tid,bustCache) // Add a render job to the queue //
    {
			bustCache = bustCache || false;

      if (this.queue.length == 0) // Show queue if it was hidden
      {
        $("#renderQueue").fadeIn(400);
      }

      var ttype = $(".titles.active #"+tid).attr("type");

      if ($("#q"+tid).length == 0) // check for duplicates
      {
        var startNum = this.queue.push({'id':tid, 'type':ttype, bustCache:bustCache}); // Add title id to the queue
        var titleName = $(".titles.active #"+tid).text().trim(); // Get actual title for queue status box
    	  $('#renderQueue').append('

✓



 ' + titleName + '

');
      }
      else if ($("#q"+tid).css("background-color") == "rgb(0, 255, 0)")
      {
        $("#q"+tid).remove();
        this.addToQueue(tid);
      }
    },

    /////////////////////////////////////////////////////////////////////////////
    removeFromQueue: function(castaway) // Remove a single item from the queue //
    {
      var ttype = $("#"+castaway).attr("type");
      var index, i;
      //var index = this.queue.indexOf({'id':castaway, 'type':ttype});
      for (i=0; i < this.queue.length; i++) // I know this is the nieve way...
      {
        if (this.queue[i].id == castaway)
        {
          index = i;
        }
      }

      if (!this.queue[index]) // See if it is even there
      {
        this.pruneQueue(); // prune queue if not
        return;
      }

      var tempID = this.queue[index].id;
      this.queue.splice(index, 1);

      if (this.queue.length == 0)
      {
        setTimeout('$("#renderQueue").fadeOut(400)', 401); // Hide empty queue
      }

      $("#q"+tempID).fadeOut(400, function(){
        $("#q"+tempID).remove();
      });

    },

    ////////////////////////////////////////////////////////////////////////////
    moveInQueue: function(destination, traveler) // Move an item in the queue //
    {
      var ttype = $("#"+traveler).attr("type");

      var startIndex, i;
      //var index = this.queue.indexOf({'id':castaway, 'type':ttype});
      for (i=0; i < this.queue.length; i++) // I know this is the nieve way...
      {
        if (this.queue[i].id == traveler)
        {
          index = i;
        }
      }

      var tempItem = this.queue.splice(startIndex,1);
      var tempName = this.queue[destination].id;

      $("#q"+tempItem[0].id).fadeOut(400, function(){
        $(this).insertBefore( $("#q"+tempName) );
        $(this).fadeIn(400);
      });

      this.queue.splice(destination, 0, tempItem[0]);

      //alert(this.queue[destination]);
    },

    //////////////////////////////////////////////////////////////////////////////////
    processQueue: function(index, recursive) // Start rendering queue (single pass) //
    {

      index = index ? index : 0;

      if (this.queue.length == 0) // Don't mess with an empty queue
      {
        alert("Render Queue is already complete!");
        return;
      }
      else if ((process == 1) && (recursive == 0)) // If processing is happening when called from the UI...
      {
        process = 0; // Pause the processing (naive)
        $("#process").html(""); // Play Icon
      }
      else
      {
        process = 1; // Processing starts
        $("#process").html(""); // Pause Icon
      }

      var url_str;

			var bustCache = '&bustCache=true';

      if (this.queue[index].type == "general")
      {
        url_str = "im_render_title.php?id="+this.queue[index].id;
      } else if (this.queue[index].type == "player") {
        url_str = "im_render_statscard.php?id="+this.queue[index].id;
      }

			if(this.queue[index].bustCache) {
				url_str += bustCache;
			}

    	$.ajax({	// Render a title
    		type: "GET",
    		url: url_str,
        accepts: "image/png",
        async: true,
        timeout: 20000,
    		success: function(data) {
          $("#q"+this.queue[index].id).fadeOut(400, function(){
            $(this).css("background-color", "00FF00"); // Mark as green on the list
          });
          $("#q"+this.queue[index].id).fadeIn(400);

          this.queue.splice(index,1); // Remove first element from queue (it is now done)
          }.bind(renderQueue),
        error: function() {
    			$("#q"+this.queue[index].id).css("background-color", "FF0000"); // Mark as red on list
          index += 1;
    		}.bind(renderQueue),
        complete: function() {
          // Check before recursively calling
          if ((this.queue.length != 0) && (this.queue.length > index) && (process == 1))
          {
            setTimeout(this.processQueue(index, 1));
          }
          else
          {
            process = 0; // Processing has ended
            setTimeout('$("#process").html("")', 801); // Play Icon (timed after color updates)
            setTimeout( 'renderQueue.pruneQueue()' , 408); // Prune when finished
          }
        }.bind(renderQueue)
    	});
    },

    ///////////////////////////////////////////////////////////
    pruneQueue: function() // Remove finished jobs from list //
    {
      if (this.queue.length == 0)
      {
        setTimeout('$("#renderQueue").fadeOut(400)', 401); // Hide empty queue
      }
      $(".queueItem").each( function(i)
      {
        if ($(this).css("background-color") == "rgb(0, 255, 0)")
        {
          $(this).fadeOut(400, function(){
            $(this).remove();
          });
        };
      });
    },

    /////////////////////////////////////////////////////////////
    destroyQueue: function() // Erase queue without predjudice //
    {
      if (this.queue.length == 0) // Don't bother prompting if done
      {
        this.pruneQueue();
      }
      else if(confirm("Permanently remove all jobs?"))
      {
        this.queue.length = 0;
        $(".queueItem").each( function()
        {
          $(this).remove();
        });
        $("#renderQueue").fadeOut(402); // Hide empty queue
      }
    }
	};
}());

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function scoreTitleUpdate(homeTeamScore, awayTeamScore, gameStatus) // Auto-queue the lower third title on score change //
{
  //alert("scoreTitleUpdate called with \nHome: " + homeTeamScore + "\nAway: " + awayTeamScore + "\nString: " + gameStatus);

  var url = "/scoreboard/";
  var tempHome = -1;
  var tempAway = -1;
  var scoreTitleId = -1;

  $("#pane ul li").each( function() {
    if ($(this).text().indexOf("(Score Lower Third)") > 0)
    {
      scoreTitleId = $(this).attr('id');
      return;
    }
  });

  var tempStatus = "Current Score"
  var updateStatus = scoreTitleId + "=gameStatus&text=" + tempStatus;

  $.getJSON(url+"team/1", function(data) { // 1 is home
    $.each(data, function(key, value) {
      if (key == "score")
      {
        if (parseInt(homeTeamScore) == -9001)
        {
          homeTeamScore = value;
          return;
        }

        tempHome = value;
        var updateHome = scoreTitleId + "=hScore&text=" + tempHome;

        if (parseInt(tempHome) != parseInt(homeTeamScore))
        {
          $.ajax({
            type: "POST",
            async: false,
            url: "cdb_update.php",
            data: updateHome,
            success: function() {
              homeTeamScore = tempHome;
              $.ajax({
                type: "POST",
                url: "cdb_update.php",
                data: updateStatus,
                success: function() {
                  window.renderQueue.addToQueue( scoreTitleId );
                }
              });
            }
          });
        }

        return;
      }
    });
  });

  $.getJSON(url+"team/0", function(data) { // 0 is away
    $.each(data, function(key, value) {
      if (key == "score")
      {
        if (parseInt(awayTeamScore) == -9001)
        {
          awayTeamScore = value;
          return;
        }

        tempAway = value;
        var updateAway = scoreTitleId + "=vScore&text=" + tempAway;

        if (parseInt(tempAway) != parseInt(awayTeamScore))
        {
          $.ajax({
            type: "POST",
            async: false,
            url: "cdb_update.php",
            data: updateAway,
            success: function() {
              awayTeamScore = tempAway;
              $.ajax({
                type: "POST",
                url: "cdb_update.php",
                data: updateStatus,
                success: function() {
                  window.renderQueue.addToQueue( ScoreTitleId );
                }
              });
            }
          });
        }

        return;
      }
    });
  });

  setTimeout(function(){scoreTitleUpdate(homeTeamScore, awayTeamScore, gameStatus);}, 10000);
};

$(window).on('beforeunload', function()
{
  if ((eventIdNum) && (parseInt(window.renderQueue.queue.length) != 0)){ // Only in the LIVE UI on empty queue
    return "WARNING: Leaving or reloading will mess up the queue.\n\nQueueing is very important in the titling system and the UK.\n";
  }
});

$(document).ready( function()
{
  $("#renderQueue").hide(); // Hide queue status box until it is needed.

  if (eventIdNum) { // Only in the LIVE UI
    setTimeout(function(){scoreTitleUpdate( -9001, -9001, "Current Score")}, 1000); // Start auto score update
  }
});

<|endoftext|>