<commit_before>
/*!
 * Express - Server
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var url = require('url')
  , view = require('./view')
  , connect = require('connect')
  , utils = connect.utils
  , queryString = require('querystring')
  , router = require('connect').router;

/**
 * Initialize a new `Server` with optional `middleware`.
 *
 * @param {Array} middleware
 * @api public
 */

var Server = exports = module.exports = function Server(middleware){
  var self = this;
  this.config = {};
  this.settings = {};
  this.redirects = {};
  this.isCallbacks = {};
  this.viewHelpers = {};
  this.dynamicViewHelpers = {};
  this.errorHandlers = [];
  connect.Server.call(this, middleware || []);

  // Default "home" to /
  this.set('home', '/');

  // Set "env" to NODE_ENV, defaulting to "development"
  this.set('env', process.env.NODE_ENV || 'development');

  // Expose objects to each other
  this.use(function(req, res, next){
    req.query = {};
    res.headers = { 'X-Powered-By': 'Express' };
    req.app = res.app = self;
    req.res = res;
    res.req = req;
    req.next = next;
    // Assign req.params.get
    if (req.url.indexOf('?') > 0) {
      var query = url.parse(req.url).query;
      req.query = exports.parseQueryString(query);
    }
    next();
  });

  // Use router, expose as app.get(), etc
  var fn = router(function(app){ self.routes = app; });
  this.__defineGetter__('router', function(){
    this.__usedRouter = true;
    return fn;
  });

  // Default production configuration
  this.configure('production', function(){
    this.enable('cache views');
  });
};

/**
 * Inherit from `connect.Server`.
 */

Server.prototype.__proto__ = connect.Server.prototype;

/**
 * Support swappable querystring parsers.
 */

exports.parseQueryString = queryString.parse;

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listen = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listen.apply(this, arguments);
};

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listenFD = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listenFD.apply(this, arguments);
};

/**
 * Register error handlers. This is automatically
 * called from within `Server#listen()` and `Server#listenFD()`.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.registerErrorHandlers = function(){
  this.errorHandlers.forEach(function(fn){
    this.use(function(err, req, res, next){
      fn.apply(this, arguments);
    });
  }, this);
  return this;
};

/**
 * Proxy `connect.Server#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} middleware
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.use = function(route, middleware){
  if (typeof route !== 'string') {
    middleware = route, route = '/';
  }

  connect.Server.prototype.use.call(this, route, middleware);

  // Mounted an app
  if (middleware instanceof Server) {
    // Home is /:route/:home
    var app = middleware
      , home = app.set('home');
    if (home === '/') home = '';
    app.set('home', (app.route || '') + home);
    app.parent = this;
    // Mounted hook
    if (app.__mounted) app.__mounted.call(app, this);
  }

  return this;
};

/**
 * Assign a callback `fn` which is called
 * when this `Server` is passed to `Server#use()`.
 *
 * Examples:
 *
 *    var app = express.createServer(),
 *        blog = express.createServer();
 *
 *    blog.mounted(function(parent){
 *        // parent is app
 *        // "this" is blog
 *    });
 *
 *    app.use(blog);
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.mounted = function(fn){
  this.__mounted = fn;
  return this;
};

/**
 * See: view.register.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.register = function(){
  view.register.apply(this, arguments);
  return this;
};

/**
 * Register the given view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.helpers =
Server.prototype.locals = function(obj){
  utils.merge(this.viewHelpers, obj);
  return this;
};

/**
 * Register the given dynamic view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.dynamicHelpers = function(obj){
  utils.merge(this.dynamicViewHelpers, obj);
  return this;
};

/**
 * Map the given param placeholder `name`(s) to the given callback `fn`.
 *
 * Param mapping is used to provide pre-conditions to routes
 * which us normalized placeholders. For example ":user_id" may
 * attempt to load the user from the database, where as ":num" may
 * pass the value through `parseInt(num, 10)`.
 *
 * When the callback function accepts only a single argument, the
 * value of placeholder is passed:
 *
 *    app.param('page', function(n){ return parseInt(n, 10); });
 *
 * After which "/users/:page" would automatically provide us with
 * an integer for `req.params.page`. If desired we could use the callback
 * signature shown below, and immediately `next(new Error('invalid page'))`
 * when `parseInt` fails.
 *
 * Alternatively the callback may accept the request, response, next, and
 * the value, acting like middlware:
 *
 *    app.param('userId', function(req, res, next, id){
 *      User.find(id, function(err, user){
 *        if (err) {
 *          next(err);
 *        } else if (user) {
 *          req.user = user;
 *          next();
 *        } else {
 *          next(new Error('failed to load user'));
 *        }
 *      });
 *    });
 *
 * Now every time ":userId" is present, the associated user object
 * will be loaded and assigned before the route handler is invoked.
 *
 * @param {String|Array} name
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.param = function(name, fn){
  if (Array.isArray(name)) {
    name.forEach(function(name){
      this.param(name, fn);
    }, this);
  } else {
    if (':' == name[0]) name = name.substr(1);
    this.routes.param(name, fn);
  }
  return this;
};

/**
 * Assign a custom exception handler callback `fn`.
 * These handlers are always _last_ in the middleware stack.
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.error = function(fn){
  this.errorHandlers.push(fn);
  return this;
};

/**
 * Register the given callback `fn` for the given `type`.
 *
 * @param {String} type
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.is = function(type, fn){
  if (!fn) return this.isCallbacks[type];
  this.isCallbacks[type] = fn;
  return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server|Mixed} for chaining, or the setting value
 * @api public
 */

Server.prototype.set = function(setting, val){
  if (val === undefined) {
    if (this.settings.hasOwnProperty(setting)) {
      return this.settings[setting];
    } else if (this.parent) {
      return this.parent.set(setting);
    }
  } else {
    this.settings[setting] = val;
    return this;
  }
};

/**
 * Check if `setting` is enabled.
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

Server.prototype.enabled = function(setting){
  return !!this.set(setting);
};

/**
 * Check if `setting` is disabled.
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

Server.prototype.disabled = function(setting){
  return !this.set(setting);
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.enable = function(setting){
  return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.disable = function(setting){
  return this.set(setting, false);
};

/**
 * Redirect `key` to `url`.
 *
 * @param {String} key
 * @param {String} url
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.redirect = function(key, url){
  this.redirects[key] = url;
  return this;
};

/**
 * Configure callback for the given `env`.
 *
 * @param {String} env
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.configure = function(env, fn){
  if (typeof env === 'function') {
    fn = env, env = 'all';
  }
  if ('all' == env || env == this.settings.env) {
    fn.call(this);
  }
  return this;
};

// Generate routing methods

(function(method){
  Server.prototype[method] = function(path, fn){
    var self = this;

    // Ensure router is mounted
    if (!this.__usedRouter) {
      this.use(this.router);
    }

    // Route specific middleware support
    if (arguments.length > 2) {
      var args = Array.prototype.slice.call(arguments, 1);
      fn = args.pop();
      (function stack(middleware){
        middleware.forEach(function(fn){
          if (Array.isArray(fn)) {
            stack(fn);
          } else {
            self[method](path, fn);
          }
        });
      })(args);
    }

    // Generate the route
    this.routes[method](path, fn);
    return this;
  };
  return arguments.callee;
})('get')('post')('put')('delete')('all');

// Alias delete as "del"

Server.prototype.del = Server.prototype.delete;
<commit_msg>Generating methods based on connect.router.methods<commit_after>
/*!
 * Express - Server
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var url = require('url')
  , view = require('./view')
  , connect = require('connect')
  , utils = connect.utils
  , queryString = require('querystring')
  , router = require('connect').router
  , methods = router.methods.concat(['del', 'all']);

/**
 * Initialize a new `Server` with optional `middleware`.
 *
 * @param {Array} middleware
 * @api public
 */

var Server = exports = module.exports = function Server(middleware){
  var self = this;
  this.config = {};
  this.settings = {};
  this.redirects = {};
  this.isCallbacks = {};
  this.viewHelpers = {};
  this.dynamicViewHelpers = {};
  this.errorHandlers = [];
  connect.Server.call(this, middleware || []);

  // Default "home" to /
  this.set('home', '/');

  // Set "env" to NODE_ENV, defaulting to "development"
  this.set('env', process.env.NODE_ENV || 'development');

  // Expose objects to each other
  this.use(function(req, res, next){
    req.query = {};
    res.headers = { 'X-Powered-By': 'Express' };
    req.app = res.app = self;
    req.res = res;
    res.req = req;
    req.next = next;
    // Assign req.params.get
    if (req.url.indexOf('?') > 0) {
      var query = url.parse(req.url).query;
      req.query = exports.parseQueryString(query);
    }
    next();
  });

  // Use router, expose as app.get(), etc
  var fn = router(function(app){ self.routes = app; });
  this.__defineGetter__('router', function(){
    this.__usedRouter = true;
    return fn;
  });

  // Default production configuration
  this.configure('production', function(){
    this.enable('cache views');
  });
};

/**
 * Inherit from `connect.Server`.
 */

Server.prototype.__proto__ = connect.Server.prototype;

/**
 * Support swappable querystring parsers.
 */

exports.parseQueryString = queryString.parse;

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listen = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listen.apply(this, arguments);
};

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listenFD = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listenFD.apply(this, arguments);
};

/**
 * Register error handlers. This is automatically
 * called from within `Server#listen()` and `Server#listenFD()`.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.registerErrorHandlers = function(){
  this.errorHandlers.forEach(function(fn){
    this.use(function(err, req, res, next){
      fn.apply(this, arguments);
    });
  }, this);
  return this;
};

/**
 * Proxy `connect.Server#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} middleware
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.use = function(route, middleware){
  if (typeof route !== 'string') {
    middleware = route, route = '/';
  }

  connect.Server.prototype.use.call(this, route, middleware);

  // Mounted an app
  if (middleware instanceof Server) {
    // Home is /:route/:home
    var app = middleware
      , home = app.set('home');
    if (home === '/') home = '';
    app.set('home', (app.route || '') + home);
    app.parent = this;
    // Mounted hook
    if (app.__mounted) app.__mounted.call(app, this);
  }

  return this;
};

/**
 * Assign a callback `fn` which is called
 * when this `Server` is passed to `Server#use()`.
 *
 * Examples:
 *
 *    var app = express.createServer(),
 *        blog = express.createServer();
 *
 *    blog.mounted(function(parent){
 *        // parent is app
 *        // "this" is blog
 *    });
 *
 *    app.use(blog);
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.mounted = function(fn){
  this.__mounted = fn;
  return this;
};

/**
 * See: view.register.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.register = function(){
  view.register.apply(this, arguments);
  return this;
};

/**
 * Register the given view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.helpers =
Server.prototype.locals = function(obj){
  utils.merge(this.viewHelpers, obj);
  return this;
};

/**
 * Register the given dynamic view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.dynamicHelpers = function(obj){
  utils.merge(this.dynamicViewHelpers, obj);
  return this;
};

/**
 * Map the given param placeholder `name`(s) to the given callback `fn`.
 *
 * Param mapping is used to provide pre-conditions to routes
 * which us normalized placeholders. For example ":user_id" may
 * attempt to load the user from the database, where as ":num" may
 * pass the value through `parseInt(num, 10)`.
 *
 * When the callback function accepts only a single argument, the
 * value of placeholder is passed:
 *
 *    app.param('page', function(n){ return parseInt(n, 10); });
 *
 * After which "/users/:page" would automatically provide us with
 * an integer for `req.params.page`. If desired we could use the callback
 * signature shown below, and immediately `next(new Error('invalid page'))`
 * when `parseInt` fails.
 *
 * Alternatively the callback may accept the request, response, next, and
 * the value, acting like middlware:
 *
 *    app.param('userId', function(req, res, next, id){
 *      User.find(id, function(err, user){
 *        if (err) {
 *          next(err);
 *        } else if (user) {
 *          req.user = user;
 *          next();
 *        } else {
 *          next(new Error('failed to load user'));
 *        }
 *      });
 *    });
 *
 * Now every time ":userId" is present, the associated user object
 * will be loaded and assigned before the route handler is invoked.
 *
 * @param {String|Array} name
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.param = function(name, fn){
  if (Array.isArray(name)) {
    name.forEach(function(name){
      this.param(name, fn);
    }, this);
  } else {
    if (':' == name[0]) name = name.substr(1);
    this.routes.param(name, fn);
  }
  return this;
};

/**
 * Assign a custom exception handler callback `fn`.
 * These handlers are always _last_ in the middleware stack.
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.error = function(fn){
  this.errorHandlers.push(fn);
  return this;
};

/**
 * Register the given callback `fn` for the given `type`.
 *
 * @param {String} type
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.is = function(type, fn){
  if (!fn) return this.isCallbacks[type];
  this.isCallbacks[type] = fn;
  return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server|Mixed} for chaining, or the setting value
 * @api public
 */

Server.prototype.set = function(setting, val){
  if (val === undefined) {
    if (this.settings.hasOwnProperty(setting)) {
      return this.settings[setting];
    } else if (this.parent) {
      return this.parent.set(setting);
    }
  } else {
    this.settings[setting] = val;
    return this;
  }
};

/**
 * Check if `setting` is enabled.
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

Server.prototype.enabled = function(setting){
  return !!this.set(setting);
};

/**
 * Check if `setting` is disabled.
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

Server.prototype.disabled = function(setting){
  return !this.set(setting);
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.enable = function(setting){
  return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.disable = function(setting){
  return this.set(setting, false);
};

/**
 * Redirect `key` to `url`.
 *
 * @param {String} key
 * @param {String} url
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.redirect = function(key, url){
  this.redirects[key] = url;
  return this;
};

/**
 * Configure callback for the given `env`.
 *
 * @param {String} env
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.configure = function(env, fn){
  if (typeof env === 'function') {
    fn = env, env = 'all';
  }
  if ('all' == env || env == this.settings.env) {
    fn.call(this);
  }
  return this;
};

// Generate routing methods

function generateMethod(method){
  Server.prototype[method] = function(path, fn){
    var self = this;

    // Ensure router is mounted
    if (!this.__usedRouter) {
      this.use(this.router);
    }

    // Route specific middleware support
    if (arguments.length > 2) {
      var args = Array.prototype.slice.call(arguments, 1);
      fn = args.pop();
      (function stack(middleware){
        middleware.forEach(function(fn){
          if (Array.isArray(fn)) {
            stack(fn);
          } else {
            self[method](path, fn);
          }
        });
      })(args);
    }

    // Generate the route
    this.routes[method](path, fn);
    return this;
  };
  return arguments.callee;
}

methods.forEach(generateMethod);

// Alias delete as "del"

Server.prototype.del = Server.prototype.delete;
<|endoftext|>


<commit_before>var IE10 = (navigator.userAgent.match(/(MSIE 10.0)/g) ? true : false);
if (IE10) {
	$('html').addClass('ie10');
}
var IE11 = (navigator.userAgent.match(/(MSIE 11.0)/g) ? true : false);
if (IE11) {
	$('html').addClass('ie11');
}

$(function() {

    // Accordion
    $(".accordion:not(.accordion-open) .accordion-content").css("display", "none");
    $('.accordion-title').click(function(){
		var labelText = $(this).text() === $(this).attr('data-close')? $(this).attr('data-initial') : $(this).attr('data-close');
		$(this).parent().toggleClass('accordion-open');
        $(this).next(".accordion-content").slideToggle();
        $(this).text(labelText);
    });

    // Add the "focus" value to class attribute
    $('.block-label').focusin( function() {
        $(this).addClass('focus');
    });

    // Remove the "focus" value to class attribute
    $('.block-label').focusout( function() {
        $(this).removeClass('focus');
    });

    // Help & Feedback container
    $(".feedback-container").css("display", "none");
    $('.feedback, .feed-close').click(function(){
     	$( ".feedback-container" ).toggle();
    });

    // Mobile specific - Nav
    $('#helper-toggle').click(function(){
     	$("#sidebar").toggle();
     	$(this).toggleClass("open-helper");
        return true;
    });

    // Non JS message
    $(".js-message").css("display", "none");
    $(".feed-close").css("display", "block");

    //add new window message aria
      $(document).ready(function() {
        $("a[rel='external']").attr("aria-label" , "This link opens in a new window");
      });

    // smooth scroll
    $('a[href^="#"]').bind('click.smoothscroll', function (e) {
        e.preventDefault();
        var target = this.hash,
            $target = $(target);
        $('html, body').animate({
            scrollTop: $(target).offset().top - 40
        }, 750, 'swing', function () {
            window.location.hash = target;
        });
    });

});

$(document).ready(function() {

    if (typeof console !== 'undefined') {
        console.log("document on ready " + areCookiesEnabled() );
    }

    if (areCookiesEnabled())  {
        $('#no-cookies').toggle(false);
        $('#content').toggle(true);
    } else {
        $('#no-cookies').toggle(true);
        $('#content').toggle(false);
    }

});

function areCookiesEnabled(){

    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }

    return (cookieEnabled);

}

function trackEvent(category, action, label, value){
    ga('send', 'event', getConfigurationObject(category, action, label, value));
}

function getConfigurationObject(category, action, label, value){
    var configurationObject = {};
    if (typeof category != 'undefined') configurationObject.eventCategory = category;
    if (typeof action != 'undefined') configurationObject.eventAction = action;
    if (typeof label != 'undefined') configurationObject.eventLabel = label;
    if (typeof value != 'undefined') configurationObject.eventValue = value;
    return configurationObject;
}

function trackVirtualPageView(category){
    ga('send', 'pageview', category);
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name,value) {
    var c_value=escape(value);
    document.cookie=c_name + "=" + c_value+";path=/";
}

function trackTiming(category, variable, timemeasured){
    if (0 < timemeasured && timemeasured <  36000000) {
        ga('send', 'timing', {
          'timingCategory': category,
          'timingVar': variable,
          'timingValue': timemeasured
        });
    }
}

// Selection Buttons
(function () {
  "use strict";
  var root = this,
      $ = root.jQuery;

  if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }

  var SelectionButtons = function (elmsOrSelector, opts) {
    var $elms;

    this.selectedClass = 'selected';
    this.focusedClass = 'focused';
    if (opts !== undefined) {
      $.each(opts, function (optionName, optionObj) {
        this[optionName] = optionObj;
      }.bind(this));
    }
    if (typeof elmsOrSelector === 'string') {
      $elms = $(elmsOrSelector);
      this.selector = elmsOrSelector;
      this.setInitialState($(this.selector));
    } else {
      this.$elms = elmsOrSelector;
      this.setInitialState(this.$elms);
    }
    this.addEvents();
  };
  SelectionButtons.prototype.addEvents = function () {
    if (typeof this.$elms !== 'undefined') {
      this.addElementLevelEvents();
    } else {
      this.addDocumentLevelEvents();
    }
  };
  SelectionButtons.prototype.setInitialState = function ($elms) {
    $elms.each(function (idx, elm) {
      var $elm = $(elm);

      if ($elm.is(':checked')) {
        this.markSelected($elm);
      }
    }.bind(this));
  };
  SelectionButtons.prototype.markFocused = function ($elm, state) {
    if (state === 'focused') {
      $elm.parent('label').addClass(this.focusedClass);
    } else {
      $elm.parent('label').removeClass(this.focusedClass);
    }
  };
  SelectionButtons.prototype.markSelected = function ($elm) {
    var radioName;

    if ($elm.attr('type') === 'radio') {
      radioName = $elm.attr('name');
      $($elm[0].form).find('input[name="' + radioName + '"]')
        .parent('label')
        .removeClass(this.selectedClass);
      $elm.parent('label').addClass(this.selectedClass);
    } else { // checkbox
      if ($elm.is(':checked')) {
        $elm.parent('label').addClass(this.selectedClass);
      } else {
        $elm.parent('label').removeClass(this.selectedClass);
      }
    }
  };
  SelectionButtons.prototype.addElementLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'element' });

    this.$elms
      .on('click', this.clickHandler)
      .on('focus blur', this.focusHandler);
  };
  SelectionButtons.prototype.addDocumentLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'document' });

    $(document)
      .on('click', this.selector, this.clickHandler)
      .on('focus blur', this.selector, this.focusHandler);
  };
  SelectionButtons.prototype.getClickHandler = function () {
    return function (e) {
      this.markSelected($(e.target));
    }.bind(this);
  };
  SelectionButtons.prototype.getFocusHandler = function (opts) {
    var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';

    return function (e) {
      var state = (e.type === focusEvent) ? 'focused' : 'blurred';

      this.markFocused($(e.target), state);
    }.bind(this);
  };
  SelectionButtons.prototype.destroy = function () {
    if (typeof this.selector !== 'undefined') {
      $(document)
        .off('click', this.selector, this.clickHandler)
        .off('focus blur', this.selector, this.focusHandler);
    } else {
      this.$elms
        .off('click', this.clickHandler)
        .off('focus blur', this.focusHandler);
    }
  };

  root.GOVUK.SelectionButtons = SelectionButtons;
}).call(this);

$(document).ready(function() {

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox'], .block-checkbox input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Details/summary polyfill
  // See /javascripts/vendor/details.polyfill.js

  // Cookie Banner
  if(getCookie("seen_cookie_message") === undefined){
    $("#global-cookie-message").show();
    var d = new Date;
    d.setTime(d.getTime() + 28 * 24 * 60 * 60 * 1e3);
    setCookie("seen_cookie_message", "yes; expires=" + d.toGMTString());
  }

});<commit_msg>CADS-583 added maxlength aria-label to input fields<commit_after>var IE10 = (navigator.userAgent.match(/(MSIE 10.0)/g) ? true : false);
if (IE10) {
	$('html').addClass('ie10');
}
var IE11 = (navigator.userAgent.match(/(MSIE 11.0)/g) ? true : false);
if (IE11) {
	$('html').addClass('ie11');
}

$(function() {

    // Accordion
    $(".accordion:not(.accordion-open) .accordion-content").css("display", "none");
    $('.accordion-title').click(function(){
		var labelText = $(this).text() === $(this).attr('data-close')? $(this).attr('data-initial') : $(this).attr('data-close');
		$(this).parent().toggleClass('accordion-open');
        $(this).next(".accordion-content").slideToggle();
        $(this).text(labelText);
    });

    // Add the "focus" value to class attribute
    $('.block-label').focusin( function() {
        $(this).addClass('focus');
    });

    // Remove the "focus" value to class attribute
    $('.block-label').focusout( function() {
        $(this).removeClass('focus');
    });

    // Help & Feedback container
    $(".feedback-container").css("display", "none");
    $('.feedback, .feed-close').click(function(){
     	$( ".feedback-container" ).toggle();
    });

    // Mobile specific - Nav
    $('#helper-toggle').click(function(){
     	$("#sidebar").toggle();
     	$(this).toggleClass("open-helper");
        return true;
    });

    // Non JS message
    $(".js-message").css("display", "none");
    $(".feed-close").css("display", "block");

    //add new window message aria
      $(document).ready(function() {
        $("a[rel='external']").attr("aria-label" , "This link opens in a new window");
      });

      //add field length contextual for screen readers
      $(function() {
        var value = $(".form-control").attr("maxlength");
        $(".form-control").attr("aria-label" ,"Maximum " + value + " characters'");
      })

    // smooth scroll
    $('a[href^="#"]').bind('click.smoothscroll', function (e) {
        e.preventDefault();
        var target = this.hash,
            $target = $(target);
        $('html, body').animate({
            scrollTop: $(target).offset().top - 40
        }, 750, 'swing', function () {
            window.location.hash = target;
        });
    });

});

$(document).ready(function() {

    if (typeof console !== 'undefined') {
        console.log("document on ready " + areCookiesEnabled() );
    }

    if (areCookiesEnabled())  {
        $('#no-cookies').toggle(false);
        $('#content').toggle(true);
    } else {
        $('#no-cookies').toggle(true);
        $('#content').toggle(false);
    }

});

function areCookiesEnabled(){

    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }

    return (cookieEnabled);

}

function trackEvent(category, action, label, value){
    ga('send', 'event', getConfigurationObject(category, action, label, value));
}

function getConfigurationObject(category, action, label, value){
    var configurationObject = {};
    if (typeof category != 'undefined') configurationObject.eventCategory = category;
    if (typeof action != 'undefined') configurationObject.eventAction = action;
    if (typeof label != 'undefined') configurationObject.eventLabel = label;
    if (typeof value != 'undefined') configurationObject.eventValue = value;
    return configurationObject;
}

function trackVirtualPageView(category){
    ga('send', 'pageview', category);
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name,value) {
    var c_value=escape(value);
    document.cookie=c_name + "=" + c_value+";path=/";
}

function trackTiming(category, variable, timemeasured){
    if (0 < timemeasured && timemeasured <  36000000) {
        ga('send', 'timing', {
          'timingCategory': category,
          'timingVar': variable,
          'timingValue': timemeasured
        });
    }
}

// Selection Buttons
(function () {
  "use strict";
  var root = this,
      $ = root.jQuery;

  if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }

  var SelectionButtons = function (elmsOrSelector, opts) {
    var $elms;

    this.selectedClass = 'selected';
    this.focusedClass = 'focused';
    if (opts !== undefined) {
      $.each(opts, function (optionName, optionObj) {
        this[optionName] = optionObj;
      }.bind(this));
    }
    if (typeof elmsOrSelector === 'string') {
      $elms = $(elmsOrSelector);
      this.selector = elmsOrSelector;
      this.setInitialState($(this.selector));
    } else {
      this.$elms = elmsOrSelector;
      this.setInitialState(this.$elms);
    }
    this.addEvents();
  };
  SelectionButtons.prototype.addEvents = function () {
    if (typeof this.$elms !== 'undefined') {
      this.addElementLevelEvents();
    } else {
      this.addDocumentLevelEvents();
    }
  };
  SelectionButtons.prototype.setInitialState = function ($elms) {
    $elms.each(function (idx, elm) {
      var $elm = $(elm);

      if ($elm.is(':checked')) {
        this.markSelected($elm);
      }
    }.bind(this));
  };
  SelectionButtons.prototype.markFocused = function ($elm, state) {
    if (state === 'focused') {
      $elm.parent('label').addClass(this.focusedClass);
    } else {
      $elm.parent('label').removeClass(this.focusedClass);
    }
  };
  SelectionButtons.prototype.markSelected = function ($elm) {
    var radioName;

    if ($elm.attr('type') === 'radio') {
      radioName = $elm.attr('name');
      $($elm[0].form).find('input[name="' + radioName + '"]')
        .parent('label')
        .removeClass(this.selectedClass);
      $elm.parent('label').addClass(this.selectedClass);
    } else { // checkbox
      if ($elm.is(':checked')) {
        $elm.parent('label').addClass(this.selectedClass);
      } else {
        $elm.parent('label').removeClass(this.selectedClass);
      }
    }
  };
  SelectionButtons.prototype.addElementLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'element' });

    this.$elms
      .on('click', this.clickHandler)
      .on('focus blur', this.focusHandler);
  };
  SelectionButtons.prototype.addDocumentLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'document' });

    $(document)
      .on('click', this.selector, this.clickHandler)
      .on('focus blur', this.selector, this.focusHandler);
  };
  SelectionButtons.prototype.getClickHandler = function () {
    return function (e) {
      this.markSelected($(e.target));
    }.bind(this);
  };
  SelectionButtons.prototype.getFocusHandler = function (opts) {
    var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';

    return function (e) {
      var state = (e.type === focusEvent) ? 'focused' : 'blurred';

      this.markFocused($(e.target), state);
    }.bind(this);
  };
  SelectionButtons.prototype.destroy = function () {
    if (typeof this.selector !== 'undefined') {
      $(document)
        .off('click', this.selector, this.clickHandler)
        .off('focus blur', this.selector, this.focusHandler);
    } else {
      this.$elms
        .off('click', this.clickHandler)
        .off('focus blur', this.focusHandler);
    }
  };

  root.GOVUK.SelectionButtons = SelectionButtons;
}).call(this);

$(document).ready(function() {

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox'], .block-checkbox input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Details/summary polyfill
  // See /javascripts/vendor/details.polyfill.js

  // Cookie Banner
  if(getCookie("seen_cookie_message") === undefined){
    $("#global-cookie-message").show();
    var d = new Date;
    d.setTime(d.getTime() + 28 * 24 * 60 * 60 * 1e3);
    setCookie("seen_cookie_message", "yes; expires=" + d.toGMTString());
  }

});<|endoftext|>


<commit_before>
// Express - Static - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

var path = require('path'),
    posix = require('posix')

// --- InvalidPathError

InvalidPathError = ExpressError.extend({
  name: 'InvalidPathError',
  init: function(path) {
    this.message = "`" + path + "' is not a valid path"
  }
})

// --- File

exports.File = Class({

  /**
   * Initialize with file _path_.
   *
   * @param  {string} path
   * @api public
   */

  init: function(path) {
    this.path = path
    if (path.indexOf('..') != -1) throw new InvalidPathError(path)
  },

  /**
   * Transfer static file to the given _request_.
   *
   *  - Ensures the file exists
   *  - Ensures the file is a regular file (not FIFO, Socket, etc)
   *  - Automatically assigns content type
   *
   * @param  {Request} request
   * @api public
   */

  send: function(request) {
    var file = this.path
    path.exists(file, function(exists){
      if (!exists) request.halt()
      posix.stat(file).addCallback(function(stats){
        if (!stats.isFile()) request.halt()
        posix.cat(file, 'binary').addCallback(function(content){
          request.contentType(file)
          request.halt(200, content, 'binary')
        })
      })
    })
  }
})<commit_msg>Static file caching. Closes #136<commit_after>
// Express - Static - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

var path = require('path'),
    posix = require('posix')

// --- InvalidPathError

InvalidPathError = ExpressError.extend({
  name: 'InvalidPathError',
  init: function(path) {
    this.message = "`" + path + "' is not a valid path"
  }
})

// --- File

exports.File = Class({

  /**
   * Initialize with file _path_.
   *
   * @param  {string} path
   * @api public
   */

  init: function(path) {
    this.path = path
    if (path.indexOf('..') != -1) throw new InvalidPathError(path)
  },

  /**
   * Transfer static file to the given _request_.
   *
   *  - Ensures the file exists
   *  - Ensures the file is a regular file (not FIFO, Socket, etc)
   *  - Automatically assigns content type
   *
   * @param  {Request} request
   * @api public
   */

  send: function(request) {
    var cache, file = this.path
    if (cache = request.cache.get(file))
      request.contentType(cache.type),
      request.halt(200, cache.content)
    path.exists(file, function(exists){
      if (!exists) request.halt()
      posix.stat(file).addCallback(function(stats){
        if (!stats.isFile()) request.halt()
        posix.cat(file, 'binary').addCallback(function(content){
          request.contentType(file)
          request.cache.set(file, { type: file, content: content })
          request.halt(200, content, 'binary')
        })
      })
    })
  }
})<|endoftext|>


<commit_before>/* AeroGear Cordova Plugin
* https://github.com/aerogear/aerogear-pushplugin-cordova
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

    var exec = require("cordova/exec");

    /**
     * This is a global variable called push exposed by cordova
     * @status Stable
     * @constructs Push
    */
    var Push = function(){};

    /**
        Registers the device with the APNS (iOS) or GCM (Android) and the Unified Push server.
        @param {Function} success - callback to be executed if the request results in success
        @param {Function} [error] - callback to be executed if the request results in error
        @param {Object} options - object to hold all registiation options
        @param {String} options.ecb - callback to be executed if a message arrives
        @param {String} [options.badge] - ios specific - enable badge in message registation
        @param {String} [options.sound] - ios specific - enable sound in message registation
        @param {String} [options.alert] - ios specific - enable alert messages in message registation
        @param {String|Array|Object} options.pushConfig - A configuration for the Unified Push server, so that it can register this device. If an object or array containing objects is used, the objects can have the following properties:
        @param {String} [options.pushConfig.senderId] - android specific - the id representing the Google project ID
        @param {String} options.pushConfig.variantID - the id representing the mobile application variant
        @param {String} options.pushConfig.variantSecret - the secret for the mobile application variant
        @param {String} options.pushConfig.pushServerURL - the location of the UnifiedPush server
        @param {String} [options.pushConfig.alias] - Application specific alias to identify users with the system. Common use case would be an email address or a username.
        @returns {void}
        @example

        var pushConfig = {
            senderID: "<senderID>",
            pushServerURL: "<pushServerURL>",
            variantID: "<variantID>",
            variantSecret: "<variantSecret>",
            alias: "<alias>"
        }

        push.register(successHandler, errorHandler, {"badge": "true", "sound": "true",
            "alert": "true", "ecb": "onNotification", pushConfig: pushConfig});
    */
    Push.prototype.register = function (successCallback, errorCallback, options) {
        if (errorCallback == null) {
            errorCallback = function () {
            }
        }

        if (typeof successCallback != "function") {
            console.log("Push.register failure: success callback parameter must be a function");
            return;
        }

        cordova.exec(successCallback, errorCallback, "PushPlugin", "register", [options]);
    };

    /**
        Unregisters the device with the APNS (iOS) or GCM (Android) and the Unified Push server.
        @status Stable
        @param {Function} success - callback to be executed if the request results in success
        @param {Function} [error] - callback to be executed if the request results in error
        @returns {void}
        @example

        push.unregister(successHandler, errorHandler);
    */
    Push.prototype.unregister = function (successCallback, errorCallback) {
        if (errorCallback == null) {
            errorCallback = function () {
            }
        }

        if (typeof successCallback != "function") {
            console.log("Push.unregister failure: success callback parameter must be a function");
            return;
        }

        cordova.exec(successCallback, errorCallback, "PushPlugin", "unregister", []);
    };

    /**
        Call this to set the application icon badge -- ios specific
        @status Stable
        @param {Function} success - callback to be executed if the request results in success
        @param {String|Number} [badge] - the badge number to set on the application icon
        @returns {void}
        @example

        push.setApplicationIconBadgeNumber(successHandler, errorHandler);
    */
    Push.prototype.setApplicationIconBadgeNumber = function (successCallback, badge) {
        if (typeof successCallback != "function") {
            console.log("Push.setApplicationIconBadgeNumber failure: success callback parameter must be a function");
            return;
        }

        cordova.exec(successCallback, successCallback, "PushPlugin", "setApplicationIconBadgeNumber", [
            {badge: badge}
        ]);
    };

    module.exports = new Push();
<commit_msg>example server url<commit_after>/* AeroGear Cordova Plugin
* https://github.com/aerogear/aerogear-pushplugin-cordova
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

    var exec = require("cordova/exec");

    /**
     * This is a global variable called push exposed by cordova
     * @status Stable
     * @constructs Push
    */
    var Push = function(){};

    /**
        Registers the device with the APNS (iOS) or GCM (Android) and the Unified Push server.
        @param {Function} success - callback to be executed if the request results in success
        @param {Function} [error] - callback to be executed if the request results in error
        @param {Object} options - object to hold all registiation options
        @param {String} options.ecb - callback to be executed if a message arrives
        @param {String} [options.badge] - ios specific - enable badge in message registation
        @param {String} [options.sound] - ios specific - enable sound in message registation
        @param {String} [options.alert] - ios specific - enable alert messages in message registation
        @param {String|Array|Object} options.pushConfig - A configuration for the Unified Push server, so that it can register this device. If an object or array containing objects is used, the objects can have the following properties:
        @param {String} [options.pushConfig.senderId] - android specific - the id representing the Google project ID
        @param {String} options.pushConfig.variantID - the id representing the mobile application variant
        @param {String} options.pushConfig.variantSecret - the secret for the mobile application variant
        @param {String} options.pushConfig.pushServerURL - the location of the UnifiedPush server e.g. http(s)//host:port/context
        @param {String} [options.pushConfig.alias] - Application specific alias to identify users with the system. Common use case would be an email address or a username.
        @returns {void}
        @example

        var pushConfig = {
            senderID: "<senderID>",
            pushServerURL: "<pushServerURL>",
            variantID: "<variantID>",
            variantSecret: "<variantSecret>",
            alias: "<alias>"
        }

        push.register(successHandler, errorHandler, {"badge": "true", "sound": "true",
            "alert": "true", "ecb": "onNotification", pushConfig: pushConfig});
    */
    Push.prototype.register = function (successCallback, errorCallback, options) {
        if (errorCallback == null) {
            errorCallback = function () {
            }
        }

        if (typeof successCallback != "function") {
            console.log("Push.register failure: success callback parameter must be a function");
            return;
        }

        cordova.exec(successCallback, errorCallback, "PushPlugin", "register", [options]);
    };

    /**
        Unregisters the device with the APNS (iOS) or GCM (Android) and the Unified Push server.
        @status Stable
        @param {Function} success - callback to be executed if the request results in success
        @param {Function} [error] - callback to be executed if the request results in error
        @returns {void}
        @example

        push.unregister(successHandler, errorHandler);
    */
    Push.prototype.unregister = function (successCallback, errorCallback) {
        if (errorCallback == null) {
            errorCallback = function () {
            }
        }

        if (typeof successCallback != "function") {
            console.log("Push.unregister failure: success callback parameter must be a function");
            return;
        }

        cordova.exec(successCallback, errorCallback, "PushPlugin", "unregister", []);
    };

    /**
        Call this to set the application icon badge -- ios specific
        @status Stable
        @param {Function} success - callback to be executed if the request results in success
        @param {String|Number} [badge] - the badge number to set on the application icon
        @returns {void}
        @example

        push.setApplicationIconBadgeNumber(successHandler, errorHandler);
    */
    Push.prototype.setApplicationIconBadgeNumber = function (successCallback, badge) {
        if (typeof successCallback != "function") {
            console.log("Push.setApplicationIconBadgeNumber failure: success callback parameter must be a function");
            return;
        }

        cordova.exec(successCallback, successCallback, "PushPlugin", "setApplicationIconBadgeNumber", [
            {badge: badge}
        ]);
    };

    module.exports = new Push();
<|endoftext|>


<commit_before>var app = angular.module('BlueCube.directives', []);

app.directive('uicolorpicker', function() {
	console.log("Called");
		return {
			restrict: 'E',
			require: 'ngModel',
			scope: false,
			replace: true,
			template: "<input type='text' id='colourpicker'/>",
			link: function(scope, element, attrs, ngModel) {
							var input = element.find('input');
							var options = angular.extend({
								color: ngModel.$viewValue,
								flat: true,
								showInput: false,
								showButtons: false,
								move: function(color) {
												scope.$apply(function() {
													ngModel.$setViewValue(color.toHexString());
												});
											}
							}, scope.$eval(attrs.options));

							ngModel.$render = function() {
								input.spectrum('set', ngModel.$viewValue || '');
							};

							input.spectrum(options);
						}
		};
});
<commit_msg>Standardise how the directives file is setup to match all of the other javascript files I use.<commit_after>angular.module('BlueCube.directives', [])

.directive('uicolorpicker', function() {
	console.log("Called");
		return {
			restrict: 'E',
			require: 'ngModel',
			scope: false,
			replace: true,
			template: "<input type='text' id='colourpicker'/>",
			link: function(scope, element, attrs, ngModel) {
							var input = element.find('input');
							var options = angular.extend({
								color: ngModel.$viewValue,
								flat: true,
								showInput: false,
								showButtons: false,
								move: function(color) {
												scope.$apply(function() {
													ngModel.$setViewValue(color.toHexString());
												});
											}
							}, scope.$eval(attrs.options));

							ngModel.$render = function() {
								input.spectrum('set', ngModel.$viewValue || '');
							};

							input.spectrum(options);
						}
		};
});
<|endoftext|>


<commit_before>// Copyright 2011 Marcel Laverdet
"use strict";
this.create = create;
this.invoke = invoke;
this.construct = construct;

var Fiber = require('../util/require')('fibers', module.parent.filename);

/**
 * container for the context that the runtime maintains across async calls
 */
var globals = require('../globals');
var future = require("streamline/lib/util/future").future;

/**
 * Creates a function that builds a fiber when called and automatically returns a future.
 *
 * rewrite:
 * function foo(arg, _) {
 *	 ...
 * }
 * ->
 * var foo = create(foo(arg, _) {
 *	 ...
 * }, 1);
 */

function create(fn, idx) {
	function F() {
		var cb = arguments[idx];
		if (!cb) return future.call(this, F, arguments, idx);

		// Start a new fiber
		var that = this,
			args = arguments;
		Fiber(function() {
			var val;
			globals.emitter && globals.emitter.emit("resume");
			try {
				val = fn.apply(that, args);
			} catch (err) {
				return cb(err);
			} finally {
				globals.emitter && globals.emitter.emit("yield");
			}
			cb(null, val);
		}).run();
	};

	// Memoize the original function for fast passing later
	F.fstreamlineFunction = fn;
	return F;
}

/**
 * Invokes an async function and yields currently running fiber until it callsback.
 *
 * rewrite:
 * fs.readFile(file, _);
 * ->
 * invoke(fs, 'readFile', [file], 1);
 */

function invoke(that, fn, args, idx) {
	// Resolve the function to be called
	if (typeof fn !== 'function') {
		if (typeof that === 'function' && that.fstreamlineFunction && fn === 'call') {
			return that.fstreamlineFunction.apply(args[0], args.slice(1));
		}
		fn = that[fn];
	}

	// If we're waiting on a fstreamline.create function we can just call it directly instead
	if (fn.fstreamlineFunction) {
		try {
			return fn.fstreamlineFunction.apply(that, args);
		} catch (e) {
			throw makeError(e, false);
		}
	}

	// Setup callback to resume fiber after it's yielded
	var fiber = Fiber.current;
	var err, val, yielded = false, cx;
	args[idx] = function(e, v) {
		if (!yielded) {
			yielded = true;
			err = e;
			val = v;
		} else {
			globals.context = cx;
			globals.emitter && globals.emitter.emit("resume");
			try {
				if (e) {
					fiber.throwInto(e);
				} else {
					fiber.run(v);
				}
			} finally {
				globals.emitter && globals.emitter.emit("yield");
			}
		}
	};

	// Invoke the function and yield
	fn.apply(that, args);
	if (yielded) {
		if (err) {
			throw err;
		}
		return val;
	}
	yielded = true;
	cx = globals.context;
	try {
		return Fiber.yield();
	} catch (e) {
		throw makeError(e, true);
	}
}

function construct(constructor, i) {
	var key = '__async' + i;
	return constructor[key] || (constructor[key] = function() {
		var that = Object.create(constructor.prototype);
		(constructor.fstreamlineFunction || constructor).apply(that, arguments);
		return that;
	});
}

// Double stack capture size because we may filter out half of them
Error.stackTraceLimit *= 2;

// Wraps an error to fix stacktrace

function makeError(e, incomplete) {
	if (!(e instanceof Error) || e.streamlined) return e;
	var extra;
	if (incomplete) {
		extra = {};
		Error.captureStackTrace(extra);
	}
	var ne = Object.create(e);
	ne.streamlined = e;
	Object.defineProperty(ne, 'stack', {
		get: function() {
			return e.stack && e.stack.split('\n').concat(extra ? extra.stack.split('\n').slice(2) : []).filter(function(frame) {
				return frame.indexOf('streamline/lib/fibers/runtime.js') < 0 &&
					frame.indexOf('streamline/lib/util/future.js') < 0;
			}).join('\n');
		},
		enumerable: true,
	});
	return ne;
}
require("streamline/lib/fibers/builtins");
<commit_msg>fixed futures stacktrace<commit_after>// Copyright 2011 Marcel Laverdet
"use strict";
this.create = create;
this.invoke = invoke;
this.construct = construct;

var Fiber = require('../util/require')('fibers', module.parent.filename);

/**
 * container for the context that the runtime maintains across async calls
 */
var globals = require('../globals');
var future = require("streamline/lib/util/future").future;

/**
 * Creates a function that builds a fiber when called and automatically returns a future.
 *
 * rewrite:
 * function foo(arg, _) {
 *	 ...
 * }
 * ->
 * var foo = create(foo(arg, _) {
 *	 ...
 * }, 1);
 */

function create(fn, idx) {
	function F() {
		var cb = arguments[idx];
		if (!cb) return future.call(this, F, arguments, idx);

		// Start a new fiber
		var that = this,
			args = arguments;
		Fiber(function() {
			var val;
			globals.emitter && globals.emitter.emit("resume");
			try {
				val = fn.apply(that, args);
			} catch (err) {
				return cb(err);
			} finally {
				globals.emitter && globals.emitter.emit("yield");
			}
			cb(null, val);
		}).run();
	};

	// Memoize the original function for fast passing later
	F.fstreamlineFunction = fn;
	return F;
}

/**
 * Invokes an async function and yields currently running fiber until it callsback.
 *
 * rewrite:
 * fs.readFile(file, _);
 * ->
 * invoke(fs, 'readFile', [file], 1);
 */

function invoke(that, fn, args, idx) {
	// Resolve the function to be called
	if (typeof fn !== 'function') {
		if (typeof that === 'function' && that.fstreamlineFunction && fn === 'call') {
			return that.fstreamlineFunction.apply(args[0], args.slice(1));
		}
		fn = that[fn];
	}

	// If we're waiting on a fstreamline.create function we can just call it directly instead
	if (fn.fstreamlineFunction) {
		try {
			return fn.fstreamlineFunction.apply(that, args);
		} catch (e) {
			throw makeError(e, false);
		}
	}

	// Setup callback to resume fiber after it's yielded
	var fiber = Fiber.current;
	var err, val, yielded = false, cx;
	args[idx] = function(e, v) {
		if (!yielded) {
			yielded = true;
			err = e;
			val = v;
		} else {
			globals.context = cx;
			globals.emitter && globals.emitter.emit("resume");
			try {
				if (e) {
					fiber.throwInto(e);
				} else {
					fiber.run(v);
				}
			} finally {
				globals.emitter && globals.emitter.emit("yield");
			}
		}
	};

	// Invoke the function and yield
	fn.apply(that, args);
	if (yielded) {
		if (err) {
			throw makeError(err, true);
		}
		return val;
	}
	yielded = true;
	cx = globals.context;
	try {
		return Fiber.yield();
	} catch (e) {
		throw makeError(e, true);
	}
}

function construct(constructor, i) {
	var key = '__async' + i;
	return constructor[key] || (constructor[key] = function() {
		var that = Object.create(constructor.prototype);
		(constructor.fstreamlineFunction || constructor).apply(that, arguments);
		return that;
	});
}

// Double stack capture size because we may filter out half of them
Error.stackTraceLimit *= 2;

// Wraps an error to fix stacktrace

function makeError(e, incomplete) {
	if (!(e instanceof Error)) return e;
	var extra;
	if (incomplete) {
		extra = {};
		Error.captureStackTrace(extra);
	}
	var ne = Object.create(e);
	Object.defineProperty(ne, 'stack', {
		get: function() {
			return (e.stack + (extra ? extra.stack : "")).split('\n').filter(function(frame) {
				return frame.indexOf('streamline/lib/fibers/runtime.js') < 0 &&
					frame.indexOf('streamline/lib/util/future.js') < 0;
			}).join('\n');
		},
		enumerable: true,
	});
	return ne;
}
require("streamline/lib/fibers/builtins");
<|endoftext|>


<commit_before>function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

/*function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}*/

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation = navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 100, enableHighAccuracy: true });
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
    },
    successInitGeoLocate: function(pos) {
        this.initAmount += 1;
        this.naviMarker.setLatLng(new L.LatLng(pos.coords.latitude, pos.coords.longitude));
        if (this.initAmount < 10) {
            navigator.geolocation.clearWatch(this.watchGeoLocation);
            this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
        }
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        alert('nope: ' + error.code + '\n' +
            'message: ' + error.message + '\n');

        cordova.plugins.settings.openSetting("settings", function(){alert("poszlo")}, function(){alert("nieposzlo")});
    }
}

var navigationSystem = new NavigationSystem();
<commit_msg>refs #5<commit_after>function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

/*function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}*/

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation = navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 100, enableHighAccuracy: true });
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
    },
    successInitGeoLocate: function(pos) {
        this.initAmount += 1;
        this.naviMarker.setLatLng(new L.LatLng(pos.coords.latitude, pos.coords.longitude));
        if (this.initAmount < 10) {
            navigator.geolocation.clearWatch(this.watchGeoLocation);
            this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
        }
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        alert('nope: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }
}

function onRequestSuccess(success){
    console.log("Successfully requested accuracy: "+success.message);
}

function onRequestFailure(error){
    console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
    if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
        if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
            cordova.plugins.diagnostic.switchToLocationSettings();
        }
    }
}

cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);

//var navigationSystem = new NavigationSystem();
<|endoftext|>


<commit_before>var spawn = require('child_process').spawnSync;
var fs = require('fs');
var Promise = require('bluebird');

var FileProcessor = function(appConfig, fileNode, filePath) {
  this.appConfig = appConfig;
  this.fileNode = fileNode;
  this.filePath = filePath;
};

FileProcessor.prototype.run = function() {
  console.log("Processing file: ", this.filePath, this.fileNode.id);

  var self = this;
  var filePath = this.filePath;
  var stat;

  if (self.fileExists()) {
    stat = self.fileStat();
  }

  if (self.isCompleted(stat)) {
    return self.deleteFromSource().then(() => {
      if (self.appConfig.filebotEnabled()) {
        self.processWithFilebot(stat);
      }
      console.log("File done 1");
    });
  } else {
    return self.downloadFile().then(() => {
      var afterStat;

      if (self.fileExists()) {
        afterStat = self.fileStat();
      }

      if (self.isCompleted(afterStat)) {
        return self.deleteFromSource().then(() => {
          if (self.appConfig.filebotEnabled()) {
            self.processWithFilebot(afterStat);
          }
          console.log("File done 2");
        });
      } else {
        if (self.appConfig.filebotEnabled()) {
          self.processWithFilebot(afterStat);
        }
        console.log("File done 3");
      }
    });
  }
};

FileProcessor.prototype.fileExists = function() {
  return fs.existsSync(this.filePath);
};

FileProcessor.prototype.fileStat = function() {
  return fs.statSync(this.filePath);
};

FileProcessor.prototype.downloadFile = function() {
  console.log('downloading ' + this.filePath + '...');

  return new Promise((resolve) => {
    var ariaPath = this.appConfig.aria2cPath();
    var url = this.downloadUrl(this.fileNode.id);
    var containingDirectory = this.filePath.replace(/\/[^\/]+$/, '');

    var spawnArgs = ['--file-allocation=none', '-x6', '-d', containingDirectory, url];

    console.log(ariaPath, spawnArgs);
    spawn(ariaPath, spawnArgs, { stdio: 'inherit' });

    return resolve();
  });
};

FileProcessor.prototype.downloadUrl = function(fileId) {
  var token = this.appConfig.putIoToken();
  return 'https://api.put.io/v2/'+'files/'+fileId+'/download?oauth_token='+token;
}

FileProcessor.prototype.isCompleted = function(stat) {
  if (stat && stat.size == this.fileNode.size) {
    var partialDownloadExists = fs.existsSync(this.filePath+'.aria2');

    if (!partialDownloadExists) {
      return true;
    }
  };

  return false;
};

FileProcessor.prototype.deleteFromSource = function() {
  console.log('deleting ' + this.fileNode.name + ' from put.io');

  return this.appConfig.apiConnection().files.deleteFiles([this.fileNode.id]);
};

FileProcessor.prototype.processWithFilebot = function(stat) {
  if (this.isProbablyVideoFileSize(stat.size)) {
    var filebotPath = this.appConfig.filebotPath();
    var spawnArgs = [
      '--conflict', 'override',
      '-rename',
      '-no-xattr',
      '-non-strict',
      '--format', ,`'${this.appConfig.filebotFormat()}'`,
      this.filePath
    ];

    console.log('processing ' + this.filePath + ' with filebot');
    console.log(filebotPath, spawnArgs);
    spawn(filebotPath, spawnArgs, { stdio: 'inherit' });
  }
};

FileProcessor.prototype.isProbablyVideoFileSize = function(fileSize) {
  return fileSize > 20 * 1024 * 1024;
};

module.exports = FileProcessor;
<commit_msg>Extra format segment<commit_after>var spawn = require('child_process').spawnSync;
var fs = require('fs');
var Promise = require('bluebird');

var FileProcessor = function(appConfig, fileNode, filePath) {
  this.appConfig = appConfig;
  this.fileNode = fileNode;
  this.filePath = filePath;
};

FileProcessor.prototype.run = function() {
  console.log("Processing file: ", this.filePath, this.fileNode.id);

  var self = this;
  var filePath = this.filePath;
  var stat;

  if (self.fileExists()) {
    stat = self.fileStat();
  }

  if (self.isCompleted(stat)) {
    return self.deleteFromSource().then(() => {
      if (self.appConfig.filebotEnabled()) {
        self.processWithFilebot(stat);
      }
      console.log("File done 1");
    });
  } else {
    return self.downloadFile().then(() => {
      var afterStat;

      if (self.fileExists()) {
        afterStat = self.fileStat();
      }

      if (self.isCompleted(afterStat)) {
        return self.deleteFromSource().then(() => {
          if (self.appConfig.filebotEnabled()) {
            self.processWithFilebot(afterStat);
          }
          console.log("File done 2");
        });
      } else {
        if (self.appConfig.filebotEnabled()) {
          self.processWithFilebot(afterStat);
        }
        console.log("File done 3");
      }
    });
  }
};

FileProcessor.prototype.fileExists = function() {
  return fs.existsSync(this.filePath);
};

FileProcessor.prototype.fileStat = function() {
  return fs.statSync(this.filePath);
};

FileProcessor.prototype.downloadFile = function() {
  console.log('downloading ' + this.filePath + '...');

  return new Promise((resolve) => {
    var ariaPath = this.appConfig.aria2cPath();
    var url = this.downloadUrl(this.fileNode.id);
    var containingDirectory = this.filePath.replace(/\/[^\/]+$/, '');

    var spawnArgs = ['--file-allocation=none', '-x6', '-d', containingDirectory, url];

    console.log(ariaPath, spawnArgs);
    spawn(ariaPath, spawnArgs, { stdio: 'inherit' });

    return resolve();
  });
};

FileProcessor.prototype.downloadUrl = function(fileId) {
  var token = this.appConfig.putIoToken();
  return 'https://api.put.io/v2/'+'files/'+fileId+'/download?oauth_token='+token;
}

FileProcessor.prototype.isCompleted = function(stat) {
  if (stat && stat.size == this.fileNode.size) {
    var partialDownloadExists = fs.existsSync(this.filePath+'.aria2');

    if (!partialDownloadExists) {
      return true;
    }
  };

  return false;
};

FileProcessor.prototype.deleteFromSource = function() {
  console.log('deleting ' + this.fileNode.name + ' from put.io');

  return this.appConfig.apiConnection().files.deleteFiles([this.fileNode.id]);
};

FileProcessor.prototype.processWithFilebot = function(stat) {
  if (this.isProbablyVideoFileSize(stat.size)) {
    var filebotPath = this.appConfig.filebotPath();
    var spawnArgs = [
      '--conflict', 'override',
      '-rename',
      '-no-xattr',
      '-non-strict',
      '--format', `'${this.appConfig.filebotFormat()}'`,
      this.filePath
    ];

    console.log('processing ' + this.filePath + ' with filebot');
    console.log(filebotPath, spawnArgs);
    spawn(filebotPath, spawnArgs, { stdio: 'inherit' });
  }
};

FileProcessor.prototype.isProbablyVideoFileSize = function(fileSize) {
  return fileSize > 20 * 1024 * 1024;
};

module.exports = FileProcessor;
<|endoftext|>


<commit_before>function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

/*function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}*/

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation = navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 100, enableHighAccuracy: true });
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });

    },
    successInitGeoLocate: function(pos) {
        this.initAmount += 1;
        this.naviMarker.setLatLng(new L.LatLng(pos.coords.latitude, pos.coords.longitude));
        if (this.initAmount < 10) {
            navigator.geolocation.clearWatch(this.watchGeoLocation);
            this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
        }
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        if(typeof cordova.plugins.settings.openSetting != undefined)
            cordova.plugins.settings.openSetting("settings", function(){console.log("opened nfc settings")},function(){alert('error: ' + error.code + '\n' +
            'message: ' + error.message + '\n');});
        alert('nope: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }
}

var navigationSystem = new NavigationSystem();
<commit_msg>refs #5<commit_after>function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

/*function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}*/

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation = navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 100, enableHighAccuracy: true });
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });

    },
    successInitGeoLocate: function(pos) {
        this.initAmount += 1;
        this.naviMarker.setLatLng(new L.LatLng(pos.coords.latitude, pos.coords.longitude));
        if (this.initAmount < 10) {
            navigator.geolocation.clearWatch(this.watchGeoLocation);
            this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
        }
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        alert('nope: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
        if(typeof cordova.plugins.settings.openSetting != undefined)
            cordova.plugins.settings.openSetting("settings", function(){alert("poszlo")}, function(){alert("nieposzlo")});
    }
}

var navigationSystem = new NavigationSystem();
<|endoftext|>


<commit_before>import React from 'react';
// import PropTypes from 'prop-types';
import BaseView from './../core/base-view';
import {connect} from 'react-redux';
// import {Link} from 'react-router';
import Proc from './../lib/proc';
// import ajax from './../lib/ajax';
import _ from 'lodash';
import timer from './../lib/timer';
import api from './../user/api';
const mapGuide = require('./../../maps/map-guide.json');
const getDefaultState = () => ({
    users: [],
    timerCount: Infinity
});

class RoomView extends BaseView {
    sendMessage() {
        const view = this;

        api.post.pushToRoomKey(null, {
            chat: {
                publicId: view.props.userState.publicIdState.publicId,
                text: view.refs.chatInput.value
            }
        });
    }

    constructor() {
        super();

        this.state = getDefaultState();
    }

    componentWillUnmount() {
        const view = this;
        const {pingProc, roomStatesProc} = view.state;

        view.state = getDefaultState();

        api.get.leaveRoom();

        pingProc.destroy();
        roomStatesProc.destroy();
    }

    componentDidMount() {
        const view = this;

        const pingProc = new Proc(api.get.pingUserRoom, 1000);

        const roomStatesProc = new Proc(() => {
            api.get.getRoomStates({
                keys: [
                    'localization',
                    'landscape',
                    'building',
                    'unit',
                    'users',
                    'defaultMoney',
                    'unitLimit',
                    'gameName',
                    'password',
                    'chat',
                    'isTimerStarted',
                    'nextGameIs'
                ].join(',')
            }).then(rawResult => {
                view.setState(JSON.parse(rawResult).result);

                const {state} = view;
                const {users} = state;
                const {publicId} = view.props.userState.publicIdState;
                const user = _.find(users, {publicId});

                // auto set 'team' and 'color'
                if (user && !user.team) {
                    view.setUserProperty('team', view.refs.teamSelect.value);
                    view.setUserProperty('color', view.refs.colorSelect.value);
                }

                const zeroUserPublicId = users[0] ? users[0].publicId : null;

                // auto set 'defaultMoney' and 'unitLimit'
                if (publicId === zeroUserPublicId && !state.defaultMoney) {
                    view.setRoomState('defaultMoney', view.refs.defaultMoney.value);
                    view.setRoomState('unitLimit', view.refs.unitLimit.value);
                }

                if (state.isTimerStarted && state.timerCount === Infinity) {
                    timer(7, 1e3, count => {
                        console.log(count);
                        view.setState({timerCount: count});
                    }, () => alert(state.nextGameIs));
                }
            });
        }, 1000);

        view.setState({pingProc, roomStatesProc});
    }

    setUserProperty(key, value) {
        return api.post.setUserRoomState(null, {[key]: value});
    }

    setRoomState(key, value) {
        return api.post.setRoomState(null, {[key]: value});
    }

    startGame() {
        const view = this;

        view.setRoomState('isTimerStarted', true).then(() => {
            view.setRoomState('nextGameIs', '100');
        });
    }

    render() {
        const view = this;
        const {state} = view;
        const userPublicId = view.props.userState.publicIdState.publicId;
        const zeroUserPublicId = state.users[0] ? state.users[0].publicId : null;

        return

{state.nextGameIs}

the room

localization

{JSON.stringify(state.localization)}

users part

            {state.users.map(user =>

{user.publicId}

{JSON.stringify(user)}

                {userPublicId === user.publicId && view.state.timerCount >= 3 ?

                        <select
                            ref="teamSelect"
                            onChange={evt => view.setUserProperty('team', evt.currentTarget.value)}
                            defaultValue={user.team}>
                            {mapGuide.teamList.map(teamId =>
                                <option key={teamId}>{teamId}</option>
                            )}
                        </select>
                        <select
                            ref="colorSelect"
                            onChange={evt => view.setUserProperty('color', evt.currentTarget.value)}
                            defaultValue={user.color}>
                            {mapGuide.colorList.map(colorId =>
                                <option key={colorId}>{colorId}</option>
                            )}
                        </select>

 :

                        {user.color}, {user.team}

                }

)}

            {zeroUserPublicId === userPublicId ?

money limit

                    <select ref="defaultMoney"
                            onChange={evt => view.setRoomState('defaultMoney', evt.currentTarget.value)}>
                        {mapGuide.defaultMoneyList.map(money =>
                            <option key={money} value={money}>{money}</option>
                        )}
                    </select>

unit limit

                    <select ref="unitLimit"
                            onChange={evt => view.setRoomState('unitLimit', evt.currentTarget.value)}>
                        {mapGuide.unitLimitList.map(limit =>
                            <option key={limit} value={limit}>{limit}</option>
                        )}
                    </select>

 :

unit defaultMoney: {state.defaultMoney}

unit limit: {state.unitLimit}

            }

{JSON.stringify(state.chat)}

            <input ref="chatInput" type="text"/>
            <button onClick={() => view.sendMessage()}>sendMessage</button>

            {zeroUserPublicId !== userPublicId || state.isTimerStarted ?
                <button>disabled start game</button> :
                <button onClick={() => view.startGame()}>
                    start game
                </button>
            }

{view.state.timerCount}

            {view.state.timerCount === 0 &&
THE GAME HAS BEGUN!
}

;
    }
}

RoomView.propTypes = {};

export default connect(
    state => ({
        userState: state.userState
    }),
    {}
)(RoomView);
<commit_msg>refactoring...<commit_after>import React from 'react';
// import PropTypes from 'prop-types';
import BaseView from './../core/base-view';
import {connect} from 'react-redux';
// import {Link} from 'react-router';
import Proc from './../lib/proc';
// import ajax from './../lib/ajax';
import _ from 'lodash';
import timer from './../lib/timer';
import api from './../user/api';
const mapGuide = require('./../../maps/map-guide.json');
const getDefaultState = () => ({
    users: [],
    timerCount: Infinity
});

class RoomView extends BaseView {
    sendMessage() {
        const view = this;

        api.post.pushToRoomKey(null, {
            chat: {
                publicId: view.props.userState.publicIdState.publicId,
                text: view.refs.chatInput.value
            }
        });
    }

    constructor() {
        super();

        this.state = getDefaultState();
    }

    componentWillUnmount() {
        const view = this;
        const {pingProc, roomStatesProc} = view.state;

        view.state = getDefaultState();

        api.get.leaveRoom();

        pingProc.destroy();
        roomStatesProc.destroy();
    }

    componentDidMount() {
        const view = this;
        const pingProc = new Proc(api.get.pingUserRoom, 1000);
        const roomStatesProc = new Proc(() => {
            api.get
                .getRoomStates({
                    keys: [
                        'localization',
                        'landscape',
                        'building',
                        'unit',
                        'users',
                        'defaultMoney',
                        'unitLimit',
                        'gameName',
                        'password',
                        'chat',
                        'isTimerStarted',
                        'nextGameId'
                    ].join(',')
                })
                .then(rawResult => view.onRoomStateReceive(JSON.parse(rawResult).result));
        }, 1e3);

        view.setState({pingProc, roomStatesProc});
    }

    onRoomStateReceive(data) {
        const view = this;
        const {users} = data;
        const {publicId} = view.props.userState.publicIdState;
        const user = _.find(users, {publicId});
        const zeroUserPublicId = users[0] ? users[0].publicId : null;

        view.setState(data);

        // auto set 'team' and 'color'
        if (user && !user.team) {
            view.setUserProperty('team', view.refs.teamSelect.value);
            view.setUserProperty('color', view.refs.colorSelect.value);
        }

        // auto set 'defaultMoney' and 'unitLimit'
        if (publicId === zeroUserPublicId && !data.defaultMoney) {
            view.setRoomState('defaultMoney', view.refs.defaultMoney.value);
            view.setRoomState('unitLimit', view.refs.unitLimit.value);
        }

        // check preparing for game starting
        if (data.isTimerStarted && view.state.timerCount === Infinity) {
            timer(7, 1e3, count => {
                console.log(count);
                view.setState({timerCount: count});
            }, () => alert(data.nextGameId));
        }
    }

    setUserProperty(key, value) {
        return api.post.setUserRoomState(null, {[key]: value});
    }

    setRoomState(key, value) {
        return api.post.setRoomState(null, {[key]: value});
    }

    startGame() {
        const view = this;

        view.setRoomState('isTimerStarted', true).then(() => {
            view.setRoomState('nextGameId', '100');
        });
    }

    render() {
        const view = this;
        const {state} = view;
        const userPublicId = view.props.userState.publicIdState.publicId;
        const zeroUserPublicId = state.users[0] ? state.users[0].publicId : null;

        return

{state.nextGameId}

the room

localization

{JSON.stringify(state.localization)}

users part

            {state.users.map(user =>

{user.publicId}

{JSON.stringify(user)}

                {userPublicId === user.publicId && view.state.timerCount >= 3 ?

                        <select
                            ref="teamSelect"
                            onChange={evt => view.setUserProperty('team', evt.currentTarget.value)}
                            defaultValue={user.team}>
                            {mapGuide.teamList.map(teamId =>
                                <option key={teamId}>{teamId}</option>
                            )}
                        </select>
                        <select
                            ref="colorSelect"
                            onChange={evt => view.setUserProperty('color', evt.currentTarget.value)}
                            defaultValue={user.color}>
                            {mapGuide.colorList.map(colorId =>
                                <option key={colorId}>{colorId}</option>
                            )}
                        </select>

 :

                        {user.color}, {user.team}

                }

)}

            {zeroUserPublicId === userPublicId ?

money limit

                    <select ref="defaultMoney"
                            onChange={evt => view.setRoomState('defaultMoney', evt.currentTarget.value)}>
                        {mapGuide.defaultMoneyList.map(money =>
                            <option key={money} value={money}>{money}</option>
                        )}
                    </select>

unit limit

                    <select ref="unitLimit"
                            onChange={evt => view.setRoomState('unitLimit', evt.currentTarget.value)}>
                        {mapGuide.unitLimitList.map(limit =>
                            <option key={limit} value={limit}>{limit}</option>
                        )}
                    </select>

 :

unit defaultMoney: {state.defaultMoney}

unit limit: {state.unitLimit}

            }

{JSON.stringify(state.chat)}

            <input ref="chatInput" type="text"/>
            <button onClick={() => view.sendMessage()}>sendMessage</button>

            {zeroUserPublicId !== userPublicId || state.isTimerStarted ?
                <button>disabled start game</button> :
                <button onClick={() => view.startGame()}>
                    start game
                </button>
            }

{view.state.timerCount}

            {view.state.timerCount === 0 &&
THE GAME HAS BEGUN!
}

;
    }
}

RoomView.propTypes = {};

export default connect(
    state => ({
        userState: state.userState
    }),
    {}
)(RoomView);
<|endoftext|>