<commit_before>(function(window) {
  'use strict';

  function calendar(config) {

    var startDay,
    thisMonth,
    thisYear,
    askedDate,
    fullDateFormat,
    daysInMonth,
    firstDayInMonth

    initialize()

    function generateCalendarMonthArray(firstDayInMonth, daysInMonth) {
      // expected return: an array which contains week array
      var arrMonth = []
      var arrWeek = []
      var arrDate = 0
      // keep looping while date still not = total days in month
      while (arrDate !== daysInMonth) {
        // reset the week array on new loop
        arrWeek = []
        for (var i = 0; i < 7; i++) {
          if (arrDate === 0 && i < firstDayInMonth || arrDate >= daysInMonth) {
            arrWeek.push(0);
          } else {
            arrDate += 1
            arrWeek.push(arrDate)
          }
        }
        arrMonth.push(arrWeek)
      }
      return arrMonth
    }

    function generateDayNumber(startDay, threshold) {
      var dayInNumber = []
      for (var i = 0; i < 7; i++) {
        dayInNumber.push(absoluteThreshold(i + startDay, threshold))
      }
      return dayInNumber
    }

    function absoluteThreshold(day, threshold) {
      if (day < 0) {
        return (day % threshold) + threshold
      } else if (day >= threshold) {
        return day % threshold
      }
      return day
    }

    function initialize() {
      if (typeof config === 'undefined') {
        config = {}
      }

      if (typeof config.startDay === 'undefined') {
        config.startDay = 'Sun'
      }

      if (typeof config.startDay === 'string') {
        config.startDay = config.startDay.toUpperCase()
      }

      if (config.startDay === 'SUN' || config.startDay === 'SUNDAY') {
        config.startDay = 0
      }

      if (config.startDay === 'MON' || config.startDay === 'MONDAY') {
        config.startDay = 1
      }

      if (config.startDay === 'SAT' || config.startDay === 'SATURDAY') {
        config.startDay = 6
      }

      if (config.month >= 13 || config.month <= 0) {
        return alert('specify month between 1 and 12')
      }

      if (config.year <= 0) {
        return alert('specify a valid year')
      }

      // if startDay is undefined, return startDay as Sunday
      startDay = config.startDay || 0,
      thisMonth = config.month || moment().format('MM'),
      thisYear = config.year || moment().format('YYYY'),
      askedDate = thisYear.toString().concat(',').concat(thisMonth.toString()).concat(',').concat('01'),
      fullDateFormat = 'YYYY,MM,DD',
      daysInMonth = moment(askedDate, fullDateFormat).daysInMonth(),
      firstDayInMonth = absoluteThreshold(moment(askedDate, fullDateFormat).format('d') - startDay, 7)

      return {
        data: generateCalendarMonthArray(firstDayInMonth, daysInMonth),
        dayNumber: generateDayNumber(startDay, 7),
        month: thisMonth,
        year: thisYear,
        startDay: startDay
      }
    }
  }

  window.calendar = calendar

})(window)
<commit_msg>fix init month and year<commit_after>(function(window) {
  'use strict';

  function calendar(config) {

    var startDay,
    thisMonth,
    thisYear,
    askedDate,
    fullDateFormat,
    daysInMonth,
    firstDayInMonth
    initSuccess

    initialize()

    if (initSuccess) {
      return {
        data: generateCalendarMonthArray(firstDayInMonth, daysInMonth),
        dayNumber: generateDayNumber(startDay, 7),
        month: thisMonth,
        year: thisYear,
        startDay: startDay
      }
    }

    function generateCalendarMonthArray(firstDayInMonth, daysInMonth) {
      // expected return: an array which contains week array
      var arrMonth = []
      var arrWeek = []
      var arrDate = 0
      // keep looping while date still not = total days in month
      while (arrDate !== daysInMonth) {
        // reset the week array on new loop
        arrWeek = []
        for (var i = 0; i < 7; i++) {
          if (arrDate === 0 && i < firstDayInMonth || arrDate >= daysInMonth) {
            arrWeek.push(0);
          } else {
            arrDate += 1
            arrWeek.push(arrDate)
          }
        }
        arrMonth.push(arrWeek)
      }
      return arrMonth
    }

    function generateDayNumber(startDay, threshold) {
      var dayInNumber = []
      for (var i = 0; i < 7; i++) {
        dayInNumber.push(absoluteThreshold(i + startDay, threshold))
      }
      return dayInNumber
    }

    function absoluteThreshold(day, threshold) {
      if (day < 0) {
        return (day % threshold) + threshold
      } else if (day >= threshold) {
        return day % threshold
      }
      return day
    }

    function initialize() {
      if (typeof config === 'undefined') {
        config = {}
      }

      if (typeof config.startDay === 'undefined') {
        config.startDay = 'Sun'
      }

      if (typeof config.startDay === 'string') {
        config.startDay = config.startDay.toUpperCase()
      }

      if (config.startDay === 'SUN' || config.startDay === 'SUNDAY') {
        config.startDay = 0
      }

      if (config.startDay === 'MON' || config.startDay === 'MONDAY') {
        config.startDay = 1
      }

      if (config.startDay === 'SAT' || config.startDay === 'SATURDAY') {
        config.startDay = 6
      }

      if (config.month >= 13 || config.month <= 0) {
        return alert('specify month between 1 and 12')
      }

      if (config.year <= 0) {
        return alert('specify a valid year')
      }

      // if startDay is undefined, return startDay as Sunday
      startDay = config.startDay || 0,
      thisMonth = config.month || moment().format('MM'),
      thisYear = config.year || moment().format('YYYY'),
      askedDate = thisYear.toString().concat(',').concat(thisMonth.toString()).concat(',').concat('01'),
      fullDateFormat = 'YYYY,MM,DD',
      daysInMonth = moment(askedDate, fullDateFormat).daysInMonth(),
      firstDayInMonth = absoluteThreshold(moment(askedDate, fullDateFormat).format('d') - startDay, 7)
      initSuccess = true
    }
  }

  window.calendar = calendar

})(window)
<|endoftext|>


<commit_before>var url = location.href;
var splitURL = url.split("/");
var finalParse = splitURL[splitURL.length-1].split(".");

document.title=finalParse[0];<commit_msg>CamTools improvements<commit_after>var url = location.href;
var splitURL = url.split("/");
var finalParse = splitURL[splitURL.length-1].split(".");

var newTitle = "";

for (var i=0; i<finalParse.length-1; i++) {
	newTitle = newTitle + finalParse[i] + " ";
}

document.title=newTitle;<|endoftext|>


<commit_before>'use strict';
angular.module('cat')
    .directive('catAutofocus', function CatAutofocusDirective($timeout) {
        return {
            restrict: 'A',
            link: function CatAutofocusLink(scope, element) {
                $timeout(function () {
                    element[0].focus();
                }, 100);
            }
        };
    });
<commit_msg>added support for cat-select (select2) to the catAutofocus directive<commit_after>'use strict';
angular.module('cat')
    .directive('catAutofocus', function CatAutofocusDirective($timeout) {
        return {
            restrict: 'A',
            link: function CatAutofocusLink(scope, element) {
                $timeout(function () {
                    if (!_.isUndefined(element.data('select2'))) {
                        element.select2('open');
                    } else {
                        element[0].focus();
                    }
                }, 100);
            }
        };
    });
<|endoftext|>


<commit_before>'use strict';

var saveSettings = function (settings) {
    chrome.storage.sync.set({
        settings: JSON.stringify(settings)
    });
};

var cancelOptions = function () {
    window.close();
};

chrome.storage.sync.get('settings', function (items) {
    var settings = JSON.parse(items.settings), service, serviceList = '', definition;

    getOptionSettings(settings);

    return;
    // @todo extend and move into own object/method as well as in general options.js
    for (service in settings.serviceExceptions)
    {
        if (settings.serviceExceptions.hasOwnProperty(service)) {
            serviceList += '
' + service + ': ';
                for (definition in settings.serviceExceptions[service]) {
                    if (settings.serviceExceptions[service].hasOwnProperty(definition)) {
                        serviceList += '' + definition + ': '+ settings.serviceExceptions[service][definition] + ' - ';
                    }
                }
            serviceList += '
';
        }
    }

    $('show-saved-options').innerHTML = serviceList;
});

(function () {
    /** translations */
    var optionsTitle = chrome.i18n.getMessage("optionsTitle"),
        lengthLabel = chrome.i18n.getMessage("lengthLabel"),
        repeatLabel = chrome.i18n.getMessage("repeatLabel"),
        iterationLabel = chrome.i18n.getMessage("iterationLabel"),
        autosendLabel = chrome.i18n.getMessage("autosendLabel"),
        compatibleLabel = chrome.i18n.getMessage("compatibleLabel"),
        servicenameLabel = chrome.i18n.getMessage("servicenameOptionLabel"),
        defservicenameLabel = chrome.i18n.getMessage("defservicenameLabel"),
        defservicenamePrefixLabel = chrome.i18n.getMessage("defservicenamePrefixLabel"),
        defservicenameSuffixLabel = chrome.i18n.getMessage("defservicenameSuffixLabel"),
        spaceHead = chrome.i18n.getMessage("spaceHead"),
        requiredLabel = chrome.i18n.getMessage("requiredLabel"),
        allowedLabel = chrome.i18n.getMessage("allowedLabel"),
        forbiddenLabel = chrome.i18n.getMessage("forbiddenLabel"),
        optionStatus = chrome.i18n.getMessage("optionStatus"),
        saveOptionsText = chrome.i18n.getMessage("saveOptions"),
        cancelOptionsText = chrome.i18n.getMessage("cancelOptions"),
        linkText = chrome.i18n.getMessage("linkText"),
        linkText1 = chrome.i18n.getMessage("linkText1"),
        linkText2 = chrome.i18n.getMessage("linkText2");

    document.title = optionsTitle;
    $('length-label').innerText = lengthLabel;
    $('repeat-label').innerText = repeatLabel;
    $('iteration-label').innerText = iterationLabel;
    $('compatible-label').innerText = compatibleLabel;
    $('autosend-label').innerText = autosendLabel;
    $('servicename-label').innerText = servicenameLabel;
    $('defservicename-label').innerText = defservicenameLabel;
    $('defservicename-prefix-label').innerText = defservicenamePrefixLabel;
    $('defservicename-suffix-label').innerText = defservicenameSuffixLabel;
    $('space-head').innerText = spaceHead;
    $('required-label').innerText = requiredLabel;
    $('allowed-label').innerText = allowedLabel;
    $('forbidden-label').innerText = forbiddenLabel;
    $('option-status').innerText = optionStatus;
    $('save-options').innerText = saveOptionsText;
    $('cancel-options').innerText = cancelOptionsText;
    $('link-text').innerText = linkText;
    $('link-to-vault-1').innerText = linkText1;
    $('link-to-vault-2').innerText = linkText2;

    // set symbol description
    $('symbol-description').title = '!"#$%&\'()*+,./:;<=>?@[\\]^{|}~';
})();<commit_msg>show overwritten page options<commit_after>'use strict';

var saveSettings = function (settings) {
    chrome.storage.sync.set({
        settings: JSON.stringify(settings)
    });
};

var cancelOptions = function () {
    window.close();
};

chrome.storage.sync.get('settings', function (items) {
    var settings = JSON.parse(items.settings), service, serviceList = '', definition;

    getOptionSettings(settings);

    // @todo extend and move into own object/method as well as in general options.js
    for (service in settings.serviceExceptions)
    {
        if (settings.serviceExceptions.hasOwnProperty(service)) {
            serviceList += '
' + service + ': ';
                for (definition in settings.serviceExceptions[service]) {
                    if (settings.serviceExceptions[service].hasOwnProperty(definition)) {
                        serviceList += '' + definition + ': '+ settings.serviceExceptions[service][definition] + ' - ';
                    }
                }
            serviceList += '
';
        }
    }

    $('show-saved-options').innerHTML = serviceList;
});

(function () {
    /** translations */
    var optionsTitle = chrome.i18n.getMessage("optionsTitle"),
        lengthLabel = chrome.i18n.getMessage("lengthLabel"),
        repeatLabel = chrome.i18n.getMessage("repeatLabel"),
        iterationLabel = chrome.i18n.getMessage("iterationLabel"),
        autosendLabel = chrome.i18n.getMessage("autosendLabel"),
        compatibleLabel = chrome.i18n.getMessage("compatibleLabel"),
        browserActionLabel = chrome.i18n.getMessage("browserActionLabel"),
        servicenameLabel = chrome.i18n.getMessage("servicenameOptionLabel"),
        defservicenameLabel = chrome.i18n.getMessage("defservicenameLabel"),
        defservicenamePrefixLabel = chrome.i18n.getMessage("defservicenamePrefixLabel"),
        defservicenameSuffixLabel = chrome.i18n.getMessage("defservicenameSuffixLabel"),
        spaceHead = chrome.i18n.getMessage("spaceHead"),
        requiredLabel = chrome.i18n.getMessage("requiredLabel"),
        allowedLabel = chrome.i18n.getMessage("allowedLabel"),
        forbiddenLabel = chrome.i18n.getMessage("forbiddenLabel"),
        optionStatus = chrome.i18n.getMessage("optionStatus"),
        saveOptionsText = chrome.i18n.getMessage("saveOptions"),
        cancelOptionsText = chrome.i18n.getMessage("cancelOptions"),
        linkText = chrome.i18n.getMessage("linkText"),
        linkText1 = chrome.i18n.getMessage("linkText1"),
        linkText2 = chrome.i18n.getMessage("linkText2");

    document.title = optionsTitle;
    $('length-label').innerText = lengthLabel;
    $('repeat-label').innerText = repeatLabel;
    $('iteration-label').innerText = iterationLabel;
    $('compatible-label').innerText = compatibleLabel;
    $('use-browser-action-label').innerText = browserActionLabel;
    $('autosend-label').innerText = autosendLabel;
    $('servicename-label').innerText = servicenameLabel;
    $('defservicename-label').innerText = defservicenameLabel;
    $('defservicename-prefix-label').innerText = defservicenamePrefixLabel;
    $('defservicename-suffix-label').innerText = defservicenameSuffixLabel;
    $('space-head').innerText = spaceHead;
    $('required-label').innerText = requiredLabel;
    $('allowed-label').innerText = allowedLabel;
    $('forbidden-label').innerText = forbiddenLabel;
    $('option-status').innerText = optionStatus;
    $('save-options').innerText = saveOptionsText;
    $('cancel-options').innerText = cancelOptionsText;
    $('link-text').innerText = linkText;
    $('link-to-vault-1').innerText = linkText1;
    $('link-to-vault-2').innerText = linkText2;

    // set symbol description
    $('symbol-description').title = '!"#$%&\'()*+,./:;<=>?@[\\]^{|}~';
})();<|endoftext|>


<commit_before>/**
 * These tests do not test that Express/Connect/Passport/etc middleware is
 * working/loaded as needed - only that `custom` middleware is working/loaded.
 */
var express = require('express'),
    request = require('supertest'),
    should = require('should');

/**
 * Tests that `flash` is available to the session.
 */
function testConnectFlash(req, res, next) {
  res.locals.messages.should.be.an.Object;
  req.session.flash.should.be.an.Object;
  res.locals.messages.should.eql(req.session.flash);
  next();
}

/**
 * Tests that the `user` locals var is set, which requires custom middleware.
 * This DOES NOT test authentication -- ONLY that if the `logged_in` property is
 * set to true on the session, that the local `user` var will be set.
 */
function testLoadUserLocal(req, res, next) {
  req.session.passport.should.be.an.Object;
  (res.locals.user === req.session.passport.user).should.be.true;
  next();
}

// Set up the tests.
var app = express();
app.session = {
  logged_in: true,
  passport: {
    user: null
  }
};
app.set('ROOT PATH', '/test/path');
app.set('REDIS SECRET', 'test-secret');
require('../../config/environment/dev')(app);

// Enable the test middleware - required to access the `req` request objects.
// This middleware needs to be registered in order for the test suite below
// to have access to the middleware.
app.use(testConnectFlash);
app.use(testLoadUserLocal);

describe('Core middleware module', function() {
  // TODO: This before hook feels really awkward. Should revisit establishing
  // sessions like this.
  beforeEach(function(done) {
    app.request.session = app.session;
    var session = app.request.session;
    session.logged_in.should.be.true;
    session.passport.should.be.an.Object;
    done();
  });

  it('should register the core middleware', function(done) {
    request(app)
      .get('/')
      .end(done);
  });
});

<commit_msg>Linted some annotations.<commit_after>/**
 * These tests do not test that Express/Connect/Passport/etc middleware is
 * working/loaded as needed - only that `custom` middleware is working/loaded.
 */
var express = require('express'),
    request = require('supertest'),
    should = require('should');

/**
 * Tests that `flash` is available to the session.
 * @param {http.IncomingMessage} req Node/Express request object.
 * @param {http.ServerResponse} res Node/Express response object.
 * @param {Function} next Callback function.
 */
function testConnectFlash(req, res, next) {
  res.locals.messages.should.be.an.Object;
  req.session.flash.should.be.an.Object;
  res.locals.messages.should.eql(req.session.flash);
  next();
}

/**
 * Tests that the `user` locals var is set, which requires custom middleware.
 * This DOES NOT test authentication -- ONLY that if the `logged_in` property is
 * set to true on the session, that the local `user` var will be set.
 * @param {http.IncomingMessage} req Node/Express request object.
 * @param {http.ServerResponse} res Node/Express response object.
 * @param {Function} next Callback function.
 */
function testLoadUserLocal(req, res, next) {
  req.session.passport.should.be.an.Object;
  (res.locals.user === req.session.passport.user).should.be.true;
  next();
}

// Set up the tests.
var app = express();
app.session = {
  logged_in: true,
  passport: {
    user: null
  }
};
app.set('ROOT PATH', '/test/path');
app.set('REDIS SECRET', 'test-secret');
require('../../config/environment/dev')(app);

// Enable the test middleware - required to access the `req` request objects.
// This middleware needs to be registered in order for the test suite below
// to have access to the middleware.
app.use(testConnectFlash);
app.use(testLoadUserLocal);

describe('Core middleware module', function() {
  // TODO: This before hook feels really awkward. Should revisit establishing
  // sessions like this.
  beforeEach(function(done) {
    app.request.session = app.session;
    var session = app.request.session;
    session.logged_in.should.be.true;
    session.passport.should.be.an.Object;
    done();
  });

  it('should register the core middleware', function(done) {
    request(app)
      .get('/')
      .end(done);
  });
});
<|endoftext|>


<commit_before>import React from "react";
import Link from "gatsby-link";
import "../css/markdown-styles.css";
import Helmet from "react-helmet";
import { rhythm } from "../utils/typography";

class BlogIndex extends React.Component {
  render() {
    const siteTitle = this.props.data.site.siteMetadata.title;
    const posts = this.props.data.allMarkdownRemark.edges;

    return (

        <Helmet title={this.props.data.site.siteMetadata.title} />
        {posts.map(post => {
          if (
            post.node.path !== "/404/" &&
            post.node.frontmatter.path === "/intro/"
          ) {
            const title = post.node.frontmatter.title || post.node.path;
            return (

            );
          }
        })}

    );
  }
}

export default BlogIndex;

export const pageQuery = graphql`
  query IndexQuery {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___title], order: DESC }) {
      edges {
        node {
          excerpt
          html
          frontmatter {
            path
          }
          frontmatter {
            title
          }
        }
      }
    }
  }
`;
<commit_msg>prod weirdness<commit_after>import React from "react";
import Link from "gatsby-link";
import "../css/markdown-styles.css";
import Helmet from "react-helmet";
import { rhythm } from "../utils/typography";

class BlogIndex extends React.Component {
  render() {
    const siteTitle = this.props.data.site.siteMetadata.title;
    const posts = this.props.data.allMarkdownRemark.edges;

    return (

        <Helmet title={this.props.data.site.siteMetadata.title} />
        {posts ? posts.map(post => {
          if (
            post.node.path !== "/404/" &&
            post.node.frontmatter.path === "/intro/"
          ) {
            const title = post.node.frontmatter.title || post.node.path;

            console.log(post.node.frontmatter.path);
            return (

            );
          }
        }) :
:(
}

    );
  }
}

export default BlogIndex;

export const pageQuery = graphql`
  query IndexQuery {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___title], order: DESC }) {
      edges {
        node {
          excerpt
          html
          frontmatter {
            path
          }
          frontmatter {
            title
          }
        }
      }
    }
  }
`;
<|endoftext|>


<commit_before>import React from "react";

const label = {
  display: "inline-block",
  fontWeight: 700,
  marginBottom: 0.25
};

const input = {
  border: "1px solid",
  borderColor: "blue",
  marginBottom: 0.25,
  resize: "none",
  width: "100%"
};

const button = {
  fontSize: "1em",
  margin: "1em",
  padding: "0.25em 1em",
  border: "2px solid #78BE20",
  borderRadius: "3px",
  color: "white",
  cursor: "pointer",
  background: "#78BE20"
};

class Profile extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      title: "Mr",
      firstName: "Darran",
      lastName: "Keil",
      email: " Darran.keil@intrepidgroup.travel",
      notepad: 'This booking has been paid',
    };
  }

  upload() {
    if (webBrowser) {
      webBrowser.sendTerminalCommand('N.' + this.state.lastName + '/' + this.state.firstName + this.state.title);
      webBrowser.sendTerminalCommand('MT.' + this.state.email);
      webBrowser.sendTerminalCommand('NP.' + this.state.notepad);
      alert('Profile has been moved, please close window and refresh Smartpoint(*R)');
    }
  }

  render() {
    return (

Profile

        Title
          <input style={input} type="text" value={this.state.title} />
          First name
          <input style={input} type="text" value={this.state.firstName} />
          Last name
          <input style={input} type="text" value={this.state.lastName} />
          Email
          <input style={input} type="email" value={this.state.email} />
          Notepad
          <input style={input} type="text" value={this.state.notepad} />
          <button style={button} onClick={this.upload.bind(this)}>
            Upload
          </button>

Travelport Pacific 2017

    );
  }
}

export default Profile;
<commit_msg>change email address<commit_after>import React from "react";

const label = {
  display: "inline-block",
  fontWeight: 700,
  marginBottom: 0.25
};

const input = {
  border: "1px solid",
  borderColor: "blue",
  marginBottom: 0.25,
  resize: "none",
  width: "100%"
};

const button = {
  fontSize: "1em",
  margin: "1em",
  padding: "0.25em 1em",
  border: "2px solid #78BE20",
  borderRadius: "3px",
  color: "white",
  cursor: "pointer",
  background: "#78BE20"
};

class Profile extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      title: "Mr",
      firstName: "Darran",
      lastName: "Keil",
      email: "Darran.keil@intrepidgroup.travel",
      notepad: 'Cost centre code XYZ123',
    };
  }

  upload() {
    if (webBrowser) {
      webBrowser.sendTerminalCommand('N.' + this.state.lastName + '/' + this.state.firstName + this.state.title);
      webBrowser.sendTerminalCommand('MT.' + this.state.email);
      webBrowser.sendTerminalCommand('NP.' + this.state.notepad);
      alert('Profile has been moved, please close window and refresh Smartpoint(*R)');
    }
  }

  render() {
    return (

Profile

        Title
          <input style={input} type="text" value={this.state.title} />
          First name
          <input style={input} type="text" value={this.state.firstName} />
          Last name
          <input style={input} type="text" value={this.state.lastName} />
          Email
          <input style={input} type="email" value={this.state.email} />
          Notepad
          <input style={input} type="text" value={this.state.notepad} />
          <button style={button} onClick={this.upload.bind(this)}>
            Upload
          </button>

Travelport Pacific 2017

    );
  }
}

export default Profile;
<|endoftext|>


<commit_before>var direction = 0
var orientation = 0
var angle = 0
var origin = undefined
var selectedFace

/* Resets the cube's orientation and angle and also restores to default all
rotation vectors */
function reset() {
    orientation = 0
    angle = 0

    /*** Y-axis rotation data reset ***/
    frontFaceRot.origin.x = 0
    frontFaceRot.origin.y = frontFaceContainer.height / 2

    leftFaceRot.origin.x = leftFaceContainer.width
    leftFaceRot.origin.y = leftFaceContainer.height / 2

    rightFaceRot.origin.x = 0
    rightFaceRot.origin.y = rightFaceContainer.height / 2

    /*** X-axis rotation data reset ***/
    topFaceRot.origin.x = topFaceContainer.width / 2
    topFaceRot.origin.y = topFaceContainer.height

    bottomFaceRot.origin.x = bottomFaceContainer.width / 2
    bottomFaceRot.origin.y = 0

    /*** angles reset ***/
    frontFaceRot.angle = 0
    leftFaceRot.angle = 270
    rightFaceRot.angle = 90
    topFaceRot.angle = 90
    bottomFaceRot.angle = 270
}

function getOrientation(delta) {
    if (delta < 0)
        return 1
    return 2
}

function mapToOrigin(mouse) {
    return [mouse.x - container.width / 2, -mouse.y - container.height / 2]
}

/* Initiates cube rotation */
function initRotation(mouse) {
    origin = mapToOrigin(mouse)
}

/** Rotates the cube based on current mouse position. Once the cube rotation
axis is selected, the cube will rotate only around that given axis. */
function rotate(mouse) {
    // first we need to map cursor's (0,0) coordinate, which points to top-left
    // corner cube's origin
    var coords = mapToOrigin(mouse)

    // now compute the axis along which to rotate
    if (!direction) {
        var dx = Math.abs(coords[0] - origin[0])
        var dy = Math.abs(coords[1] - origin[1])

        if (dy > dx)
            direction = 2
        else
            direction = 1
    }
    // the actual rotation is performed in this section
    else {
        var face = frontFaceContainer
        var faceRot = frontFaceRot
        var nextFace, nextFaceRot, a, o, delta

        // based on the direction and orientation values, the faces to be
        // rotated are determined dynamically and the rotation vectors of the
        // front face are updated accordingly
        if (direction == 1) {
            delta = coords[0] - origin[0]
            a = 90 * delta / container.width

            if (!orientation) {
                orientation = getOrientation(delta)
                faceRot.axis.x = 0
                faceRot.axis.y = 1
            }

            if (orientation == 1) {
                faceRot.origin.x = face.width
                faceRot.origin.y = face.height / 2
                nextFace = rightFaceContainer
                nextFaceRot = rightFaceRot
            }
            else {
                faceRot.origin.x = 0
                faceRot.origin.y = face.height / 2
                nextFace = leftFaceContainer
                nextFaceRot = leftFaceRot
            }
        }
        else {
            delta = coords[1] - origin[1]
            a = 90 * delta / container.height

            if (!orientation) {
                orientation = getOrientation(delta)
                faceRot.axis.x = 1
                faceRot.axis.y = 0
            }

            if (orientation == 1) {
                faceRot.origin.x = face.width / 2
                faceRot.origin.y = 0
                nextFace = topFaceContainer
                nextFaceRot = topFaceRot
            }
            else {
                faceRot.origin.x = face.width / 2
                faceRot.origin.y = face.height
                nextFace = bottomFaceContainer
                nextFaceRot = bottomFaceRot
            }
        }

        // update the origin for next delta computations
        origin = coords

        // check if we have reached the maximum rotation angle skip any
        // processing
        if (Math.abs(angle + a) >= 90)
            return

        angle += a

        // check if we have to switch to another face
        if (o != orientation && ((orientation == 1 && angle > 0) || (orientation == 2 && angle < 0))) {
            reset()
        }
        else {
            if (direction == 1) {
                face.x += delta
                nextFace.x += delta
            }
            else {
                face.y += -delta
                nextFace.y += delta
            }

            faceRot.angle += a
            nextFaceRot.angle += a
        }
    }
}

/** Call this function when the rotation is done. Returns the selected face */
function finishRotation() {
    if (Math.abs(angle) > 45) {
        if (direction == 1) {
            if (orientation == 1)
                return 3
            else
                return 1
        }
        else {
            if (orientation == 1)
                return 2
            else
                return 4
        }
    }
    else
        return 0
}
<commit_msg>Added a lock during face snapping transition, which lets the cube ignore any events when it's rotating to avoid graphical glitches and artefacts.<commit_after>var direction = 0
var orientation = 0
var angle = 0
var origin = undefined
var selectedFace
var lock = false

/* Resets the cube's orientation and angle and also restores to default all
rotation vectors */
function reset() {
    orientation = 0
    angle = 0

    /*** Y-axis rotation data reset ***/
    frontFaceRot.origin.x = 0
    frontFaceRot.origin.y = frontFaceContainer.height / 2

    leftFaceRot.origin.x = leftFaceContainer.width
    leftFaceRot.origin.y = leftFaceContainer.height / 2

    rightFaceRot.origin.x = 0
    rightFaceRot.origin.y = rightFaceContainer.height / 2

    /*** X-axis rotation data reset ***/
    topFaceRot.origin.x = topFaceContainer.width / 2
    topFaceRot.origin.y = topFaceContainer.height

    bottomFaceRot.origin.x = bottomFaceContainer.width / 2
    bottomFaceRot.origin.y = 0

    /*** angles reset ***/
    frontFaceRot.angle = 0
    leftFaceRot.angle = 270
    rightFaceRot.angle = 90
    topFaceRot.angle = 90
    bottomFaceRot.angle = 270
}

function getOrientation(delta) {
    if (delta < 0)
        return 1
    return 2
}

function mapToOrigin(mouse) {
    return [mouse.x - container.width / 2, -mouse.y - container.height / 2]
}

/* Initiates cube rotation */
function initRotation(mouse) {
    if (lock)
        return

    origin = mapToOrigin(mouse)
}

/** Rotates the cube based on current mouse position. Once the cube rotation
axis is selected, the cube will rotate only around that given axis. */
function rotate(mouse) {
    if (lock)
        return

    // first we need to map cursor's (0,0) coordinate, which points to top-left
    // corner cube's origin
    var coords = mapToOrigin(mouse)

    // now compute the axis along which to rotate
    if (!direction) {
        var dx = Math.abs(coords[0] - origin[0])
        var dy = Math.abs(coords[1] - origin[1])

        if (dy > dx)
            direction = 2
        else
            direction = 1
    }
    // the actual rotation is performed in this section
    else {
        var face = frontFaceContainer
        var faceRot = frontFaceRot
        var nextFace, nextFaceRot, a, o, delta

        // based on the direction and orientation values, the faces to be
        // rotated are determined dynamically and the rotation vectors of the
        // front face are updated accordingly
        if (direction == 1) {
            delta = coords[0] - origin[0]
            a = 90 * delta / container.width

            if (!orientation) {
                orientation = getOrientation(delta)
                faceRot.axis.x = 0
                faceRot.axis.y = 1
            }

            if (orientation == 1) {
                faceRot.origin.x = face.width
                faceRot.origin.y = face.height / 2
                nextFace = rightFaceContainer
                nextFaceRot = rightFaceRot
            }
            else {
                faceRot.origin.x = 0
                faceRot.origin.y = face.height / 2
                nextFace = leftFaceContainer
                nextFaceRot = leftFaceRot
            }
        }
        else {
            delta = coords[1] - origin[1]
            a = 90 * delta / container.height

            if (!orientation) {
                orientation = getOrientation(delta)
                faceRot.axis.x = 1
                faceRot.axis.y = 0
            }

            if (orientation == 1) {
                faceRot.origin.x = face.width / 2
                faceRot.origin.y = 0
                nextFace = topFaceContainer
                nextFaceRot = topFaceRot
            }
            else {
                faceRot.origin.x = face.width / 2
                faceRot.origin.y = face.height
                nextFace = bottomFaceContainer
                nextFaceRot = bottomFaceRot
            }
        }

        // update the origin for next delta computations
        origin = coords

        // check if we have reached the maximum rotation angle skip any
        // processing
        if (Math.abs(angle + a) >= 90)
            return

        angle += a

        // check if we have to switch to another face
        if (o != orientation && ((orientation == 1 && angle > 0) || (orientation == 2 && angle < 0))) {
            reset()
        }
        else {
            if (direction == 1) {
                face.x += delta
                nextFace.x += delta
            }
            else {
                face.y += -delta
                nextFace.y += delta
            }

            faceRot.angle += a
            nextFaceRot.angle += a
        }
    }
}

/** Call this function when the rotation is done. Returns the selected face */
function finishRotation() {
    if (lock)
        return
    else
        lock = true

    if (Math.abs(angle) > 45) {
        if (direction == 1) {
            if (orientation == 1)
                return 3
            else
                return 1
        }
        else {
            if (orientation == 1)
                return 2
            else
                return 4
        }
    }
    else
        return 0
}
<|endoftext|>


<commit_before>Behaviour.register({
	'.TableListField .externallink' : {
		onclick: function(e) {
			window.open(e.target.href);
			Event.stop(e);
			return false;
		}
	}
});

CMSWorkflow = {
	setOption: function(key, value) {
		if (typeof(this.data) == 'undefined') {
			this.data = {};
		}
		this.data[key] = value;
	},
	getOption: function(key) {
		if (typeof(this.data) != 'undefined' && typeof(this.data[key]) != 'undefined') {
			return this.data[key];
		}
		return null;
	},
	/**
	 * Prompt for input from the user and then submit the given form via ajax.
	 */
	submitWithPromptedMessage : function(form, button, msgVar, msgPrompt) {
		var messageEl = CMSWorkflow.createPromptElement(msgVar, msgPrompt);
		if (!messageEl) {
			return;
		}
		form.appendChild(messageEl);

		Ajax.SubmitForm(form, button, {
			onSuccess: Ajax.Evaluator,
			onFailure: ajaxErrorHandler
		});

		// Once Ajax.SubmitForm has been calld, this element is no longer necessary
		form.removeChild(messageEl);
	},

	createPromptElement: function(varName, promptText) {
		var message = prompt(promptText, "");
		if (message === null) {
			// User canceled prompt box
			return null;
		}
		var messageEl = document.createElement("input");
		messageEl.type = "hidden";
		messageEl.name = varName;
		messageEl.value = message;
		return messageEl;
	},

	/**
	 * Simple behaviour for an ajax button
	 */
	WorkflowButton : {
		onclick: function() {
			$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoExpiryTZConverter_TZ'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoExpiryTZConverter_From_Date'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoExpiryTZConverter_From_Time'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['DeletionScheduling'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['WorkflowComment'] = true;

			if (EmbargoExpiry.embargoUnsaved || EmbargoExpiry.expiryUnsaved) {
				if (!confirm('Your embargo/expiry date changes have not been saved. Do you wish to continue?')) {
					return false;
				}
			}

			if ($('Form_EditForm').isChanged()) {
				if(!confirm('You have unsaved changes. You will lose them if you click OK.')) return false;
			}

			Ajax.SubmitForm($('Form_EditForm'), this.name, {
				onSuccess: Ajax.Evaluator,
				onFailure: ajaxErrorHandler
			});
			return false;
		}
	},

	showHideExpiry: {
		onclick: function() {
			if ($('deleteImmediate').checked) {
				$('expiryField').style.display = 'none';
			} else {
				$('expiryField').style.display = 'block';
			}
		}
	}
};

Behaviour.register({
	'#deleteImmediate' : CMSWorkflow.showHideExpiry,
	'#deleteLater' : CMSWorkflow.showHideExpiry,
	'#Form_EditForm_action_cms_requestedit' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_approve' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_deny' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_cancel' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_comment' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_publish' : CMSWorkflow.WorkflowButton,
	'#WorkflowActions #Form_EditForm_action_cms_requestpublication' : CMSWorkflow.WorkflowButton,
	'#WorkflowActions #Form_EditForm_action_cms_requestdeletefromlive' : CMSWorkflow.WorkflowButton
});

// Create these actions
function action_cms_requestpublication_right(e) {
	if ($('Form_EditForm').isChanged()) {
		if(!confirm('You have unsaved changes. You will lose them if you click to continue requesting publication.'))
			return false;
	}

	return CMSWorkflow.submitWithPromptedMessage(
			$('Form_EditForm'), 'action_cms_requestpublication',
			'WorkflowComment',
			'Please comment on the change you are asking to have published.'
	);
}

function action_cms_requestdeletefromlive_right(e) {
	CMSWorkflow.submitWithPromptedMessage(
			$('Form_EditForm'), 'action_cms_requestdeletefromlive',
			'WorkflowComment',
			'Please comment on why you are asking to have this page deleted.'
	);
}

var EmbargoExpiry = {
	embargoUnsaved: false,
	expiryUnsaved: false,
	init: function() {
		$('EmbargoDate_Date').addEventListener('change', EmbargoExpiry.embargoChange, false);
		$('EmbargoDate_Time').addEventListener('change', EmbargoExpiry.embargoChange, false);
		$('ExpiryDate_Date').addEventListener('change', EmbargoExpiry.expiryChange, false);
		$('ExpiryDate_Time').addEventListener('change', EmbargoExpiry.expiryChange, false);

		EmbargoExpiry.fieldCheck();

		var ids = EmbargoExpiry.ids('embargo');
		if($(ids.dateField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.dateField).name] = true;
		if($(ids.timeField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.timeField).name] = true;
		ids = EmbargoExpiry.ids('expiry');
		if($(ids.dateField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.dateField).name] = true;
		if($(ids.timeField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.timeField).name] = true;

		$('Form_EditForm').changeDetection_fieldsToIgnore['ExpiryDate[TimeZone]'] = true;
		$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoDate[TimeZone]'] = true;

		EmbargoExpiry.embargoUnsaved = false;
		EmbargoExpiry.expiryUnsaved = false;
	},
	save: function(what, el) {
		EmbargoExpiry.fieldCheck();

		var url = 'admin/cms_setembargoexpiry?wfRequest='+$('WorkflowRequest_ID').value;
		var ids = EmbargoExpiry.ids(what);

		url += '&' + escape($(ids.dateField).name)+'='+escape($(ids.dateField).value)+'&' + escape($(ids.timeField).name) + '='+escape($(ids.timeField).value);
		if (what == 'embargo') {
			EmbargoExpiry.embargoUnsaved = false;
		} else if (what == 'expiry') {
			EmbargoExpiry.expiryUnsaved = false;
		}

		if ($(ids.timezoneField)) {
			var timezone = $(ids.timezoneField).options[$(ids.timezoneField).selectedIndex].value;
			url += '&' + escape($(ids.timezoneField).name) + '='+escape(timezone);
		}

		if ($(ids.dateField).value == '' || $(ids.timeField).value == '') {
			alert('You must fill out the '+what+' date and time fields');
			return;
		}

		$(el.id).className = 'action loading';
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(t) {
				data = eval('('+t.responseText+')');
				if (data.status == 'success') {
					$(ids.wholeMessage).style.display = 'block';
					$(ids.dateTime).innerHTML = eval('data.message.'+ids.what);
				} else { EmbargoExpiry.errorAlert(data); }
			},
			onFailure: function(t) { EmbargoExpiry.errorAlert(data); },
			onComplete: function(t) { $(el.id).className = 'action'; }
		});
	},
	reset: function(what, el) {
		var elIds = EmbargoExpiry.ids(what);
		var url = 'admin/cms_setembargoexpiry?wfRequest='+$('WorkflowRequest_ID').value;

		$(elIds.dateField).value = '';
		$(elIds.timeField).value = '';

		EmbargoExpiry.fieldCheck();

		if (what == 'embargo') {
			url += '&ResetEmbargo';
			EmbargoExpiry.embargoUnsaved = false;
		} else if (what == 'expiry') {
			url += '&ResetExpiry';
			EmbargoExpiry.expiryUnsaved = false;
		}

		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(t) {
				data = eval('('+t.responseText+')');
				if (data.status == 'success') {
					$(elIds.wholeMessage).style.display = 'none';
				} else {
					EmbargoExpiry.errorAlert(data);
				}
			},
			onFailure: function(t) { EmbargoExpiry.errorAlert(t); },
			onComplete: function(t) { $(el.id).className = 'action'; }
		});
	},
	errorAlert: function(data) {
		EmbargoExpiry.fieldCheck();
		alert("There was an error processing that request:\n\n"+data.message);
	},
	ids: function(forWhat) {
		switch(forWhat) {
			case 'expiry':
				return {
					resetButton: 'resetExpiryButton',
					saveButton: 'saveExpiryButton',
					dateField: 'ExpiryDate-date',
					timeField: 'ExpiryDate-time',
					timezoneField: 'ExpiryDate_TimeZone',
					wholeMessage: 'embargoExpiry-expiryStatus',
					dateTime: 'expiryDate',
					what: 'expiry'
				};
			case 'embargo':
				return {
					resetButton: 'resetEmbargoButton',
					saveButton: 'saveEmbargoButton',
					dateField: 'EmbargoDate-date',
					timeField: 'EmbargoDate-time',
					timezoneField: 'EmbargoDate_TimeZone',
					wholeMessage: 'embargoExpiry-embargoStatus',
					dateTime: 'embargoDate',
					what: 'embargo'
				};
		}
	},
	embargoChange: function() {
		EmbargoExpiry.embargoUnsaved = true;
		EmbargoExpiry.fieldCheck();
	},
	expiryChange: function() {
		EmbargoExpiry.expiryUnsaved = true;
		EmbargoExpiry.fieldCheck();
	},
	eButton: function(id) {
		Element.removeClassName(id, 'disabled');
		$(id).disabled = false;
	},
	dButton: function(id) {
		Element.addClassName(id, 'disabled');
		$(id).disabled = true;
	},
	fieldCheck: function() {
		if (EmbargoExpiry.originalValues === null) {
			EmbargoExpiry.originalValues = true;
		}

		ids = EmbargoExpiry.ids('embargo');
		// Only call this logic if the date field & save button exist, otherwise it's unnecessary
		if($(ids.dateField) && $(ids.saveButton)) {
			if ($(ids.dateField).value == '' || $(ids.timeField).value == '') {
				EmbargoExpiry.dButton(ids.saveButton);
				EmbargoExpiry.dButton(ids.resetButton);
			} else {
				EmbargoExpiry.eButton(ids.saveButton);
				EmbargoExpiry.eButton(ids.resetButton);
			}
		}

		ids = EmbargoExpiry.ids('expiry');
		// Only call this logic if the date field & save button exist, otherwise it's unnecessary
		if($(ids.dateField) && $(ids.saveButton)) {
			if ($(ids.dateField).value == '' || $(ids.timeField).value == '') {
				EmbargoExpiry.dButton(ids.saveButton);
				EmbargoExpiry.dButton(ids.resetButton);
				EmbargoExpiry.setExpiryWarning(false);
			} else {
				EmbargoExpiry.eButton(ids.saveButton);
				EmbargoExpiry.eButton(ids.resetButton);
				EmbargoExpiry.setExpiryWarning(true);
			}
		}
	},
	setExpiryWarning: function(shouldDisplay) {
		var el = $('ExpiryWorkflowWarning');
		if(el) el.style.display = shouldDisplay ? '' : 'none';
	}
};

Behaviour.register({
	'#EmbargoDate_Time' : {
		initialize: EmbargoExpiry.init
	}
});

var autoSave_original = autoSave;
autoSave = function(confirmation, callAfter) {
	if (EmbargoExpiry.embargoUnsaved || EmbargoExpiry.expiryUnsaved) {
		if (!confirm('Your embargo/expiry date changes have not been saved. Do you wish to continue?')) {
			return false;
		}
	}
	return autoSave_original(confirmation, callAfter);
};

var save_original = CMSForm.prototype.save;
CMSForm.prototype.save = function(ifChanged, callAfter, action, publish) {
	if (EmbargoExpiry.embargoUnsaved || EmbargoExpiry.expiryUnsaved) {
		if (!confirm('Your embargo/expiry date changes have not been saved. Do you wish to continue?')) {
			_AJAX_LOADING = false;
			if($('Form_EditForm_action_save') && $('Form_EditForm_action_save').stopLoading) $('Form_EditForm_action_save').stopLoading();
			if($('Form_EditForm_action_publish') && $('Form_EditForm_action_publish').stopLoading) $('Form_EditForm_action_publish').stopLoading();
			return false;
		}
	}
	return save_original.call(this, ifChanged, callAfter, action, publish);
};

function action_publish_right(e) {
	var messageEl = null;
	if (CMSWorkflow.getOption('noPromptForAdmin')) {
		messageEl = document.createElement("input");
		messageEl.type = "hidden";
		messageEl.name = 'WorkflowComment';
	} else {
		messageEl = CMSWorkflow.createPromptElement('WorkflowComment', 'Please comment on this publication, if applicable.');
	}
	$('Form_EditForm').appendChild(messageEl);

	// Don't need to restore the button state after ajax success because the form is replaced completely
	var btn = jQuery('#Form_EditForm_action_publish');
	btn.val(ss.i18n._t('CMSMAIN.PUBLISHING')).addClass('loading').attr('disabled', 'disabled');
	$('Form_EditForm').save(false, null, 'cms_publishwithcomment', true);
	$('Form_EditForm').removeChild(messageEl);
}

/**
 * UI behaviour for the "Access" tab
 */
Behaviour.register({
	'#Form_EditForm_CanApproveType input': {
		initialize: function() {
			if(this.checked) this.click();
		},
		onclick: function() {
			$('ApproverGroups').style.display = (this.value == 'OnlyTheseUsers') ? 'block' : 'none';
		}
	},
	'#Form_EditForm_CanPublishType input': {
		initialize: function() {
			if(this.checked) this.click();
		},
		onclick: function() {
			$('PublisherGroups').style.display = (this.value == 'OnlyTheseUsers') ? 'block' : 'none';
		}
	}
});
<commit_msg>ENHANCEMENT Limiting selectable date ranges for start/end dates in workflow reports (via jQuery.datepicker)<commit_after>Behaviour.register({
	'.TableListField .externallink' : {
		onclick: function(e) {
			window.open(e.target.href);
			Event.stop(e);
			return false;
		}
	}
});

CMSWorkflow = {
	setOption: function(key, value) {
		if (typeof(this.data) == 'undefined') {
			this.data = {};
		}
		this.data[key] = value;
	},
	getOption: function(key) {
		if (typeof(this.data) != 'undefined' && typeof(this.data[key]) != 'undefined') {
			return this.data[key];
		}
		return null;
	},
	/**
	 * Prompt for input from the user and then submit the given form via ajax.
	 */
	submitWithPromptedMessage : function(form, button, msgVar, msgPrompt) {
		var messageEl = CMSWorkflow.createPromptElement(msgVar, msgPrompt);
		if (!messageEl) {
			return;
		}
		form.appendChild(messageEl);

		Ajax.SubmitForm(form, button, {
			onSuccess: Ajax.Evaluator,
			onFailure: ajaxErrorHandler
		});

		// Once Ajax.SubmitForm has been calld, this element is no longer necessary
		form.removeChild(messageEl);
	},

	createPromptElement: function(varName, promptText) {
		var message = prompt(promptText, "");
		if (message === null) {
			// User canceled prompt box
			return null;
		}
		var messageEl = document.createElement("input");
		messageEl.type = "hidden";
		messageEl.name = varName;
		messageEl.value = message;
		return messageEl;
	},

	/**
	 * Simple behaviour for an ajax button
	 */
	WorkflowButton : {
		onclick: function() {
			$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoExpiryTZConverter_TZ'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoExpiryTZConverter_From_Date'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoExpiryTZConverter_From_Time'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['DeletionScheduling'] = true;
			$('Form_EditForm').changeDetection_fieldsToIgnore['WorkflowComment'] = true;

			if (EmbargoExpiry.embargoUnsaved || EmbargoExpiry.expiryUnsaved) {
				if (!confirm('Your embargo/expiry date changes have not been saved. Do you wish to continue?')) {
					return false;
				}
			}

			if ($('Form_EditForm').isChanged()) {
				if(!confirm('You have unsaved changes. You will lose them if you click OK.')) return false;
			}

			Ajax.SubmitForm($('Form_EditForm'), this.name, {
				onSuccess: Ajax.Evaluator,
				onFailure: ajaxErrorHandler
			});
			return false;
		}
	},

	showHideExpiry: {
		onclick: function() {
			if ($('deleteImmediate').checked) {
				$('expiryField').style.display = 'none';
			} else {
				$('expiryField').style.display = 'block';
			}
		}
	}
};

Behaviour.register({
	'#deleteImmediate' : CMSWorkflow.showHideExpiry,
	'#deleteLater' : CMSWorkflow.showHideExpiry,
	'#Form_EditForm_action_cms_requestedit' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_approve' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_deny' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_cancel' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_comment' : CMSWorkflow.WorkflowButton,
	'#Form_EditForm_action_cms_publish' : CMSWorkflow.WorkflowButton,
	'#WorkflowActions #Form_EditForm_action_cms_requestpublication' : CMSWorkflow.WorkflowButton,
	'#WorkflowActions #Form_EditForm_action_cms_requestdeletefromlive' : CMSWorkflow.WorkflowButton
});

// Create these actions
function action_cms_requestpublication_right(e) {
	if ($('Form_EditForm').isChanged()) {
		if(!confirm('You have unsaved changes. You will lose them if you click to continue requesting publication.'))
			return false;
	}

	return CMSWorkflow.submitWithPromptedMessage(
			$('Form_EditForm'), 'action_cms_requestpublication',
			'WorkflowComment',
			'Please comment on the change you are asking to have published.'
	);
}

function action_cms_requestdeletefromlive_right(e) {
	CMSWorkflow.submitWithPromptedMessage(
			$('Form_EditForm'), 'action_cms_requestdeletefromlive',
			'WorkflowComment',
			'Please comment on why you are asking to have this page deleted.'
	);
}

var EmbargoExpiry = {
	embargoUnsaved: false,
	expiryUnsaved: false,
	init: function() {
		$('EmbargoDate_Date').addEventListener('change', EmbargoExpiry.embargoChange, false);
		$('EmbargoDate_Time').addEventListener('change', EmbargoExpiry.embargoChange, false);
		$('ExpiryDate_Date').addEventListener('change', EmbargoExpiry.expiryChange, false);
		$('ExpiryDate_Time').addEventListener('change', EmbargoExpiry.expiryChange, false);

		EmbargoExpiry.fieldCheck();

		var ids = EmbargoExpiry.ids('embargo');
		if($(ids.dateField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.dateField).name] = true;
		if($(ids.timeField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.timeField).name] = true;
		ids = EmbargoExpiry.ids('expiry');
		if($(ids.dateField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.dateField).name] = true;
		if($(ids.timeField)) $('Form_EditForm').changeDetection_fieldsToIgnore[$(ids.timeField).name] = true;

		$('Form_EditForm').changeDetection_fieldsToIgnore['ExpiryDate[TimeZone]'] = true;
		$('Form_EditForm').changeDetection_fieldsToIgnore['EmbargoDate[TimeZone]'] = true;

		EmbargoExpiry.embargoUnsaved = false;
		EmbargoExpiry.expiryUnsaved = false;
	},
	save: function(what, el) {
		EmbargoExpiry.fieldCheck();

		var url = 'admin/cms_setembargoexpiry?wfRequest='+$('WorkflowRequest_ID').value;
		var ids = EmbargoExpiry.ids(what);

		url += '&' + escape($(ids.dateField).name)+'='+escape($(ids.dateField).value)+'&' + escape($(ids.timeField).name) + '='+escape($(ids.timeField).value);
		if (what == 'embargo') {
			EmbargoExpiry.embargoUnsaved = false;
		} else if (what == 'expiry') {
			EmbargoExpiry.expiryUnsaved = false;
		}

		if ($(ids.timezoneField)) {
			var timezone = $(ids.timezoneField).options[$(ids.timezoneField).selectedIndex].value;
			url += '&' + escape($(ids.timezoneField).name) + '='+escape(timezone);
		}

		if ($(ids.dateField).value == '' || $(ids.timeField).value == '') {
			alert('You must fill out the '+what+' date and time fields');
			return;
		}

		$(el.id).className = 'action loading';
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(t) {
				data = eval('('+t.responseText+')');
				if (data.status == 'success') {
					$(ids.wholeMessage).style.display = 'block';
					$(ids.dateTime).innerHTML = eval('data.message.'+ids.what);
				} else { EmbargoExpiry.errorAlert(data); }
			},
			onFailure: function(t) { EmbargoExpiry.errorAlert(data); },
			onComplete: function(t) { $(el.id).className = 'action'; }
		});
	},
	reset: function(what, el) {
		var elIds = EmbargoExpiry.ids(what);
		var url = 'admin/cms_setembargoexpiry?wfRequest='+$('WorkflowRequest_ID').value;

		$(elIds.dateField).value = '';
		$(elIds.timeField).value = '';

		EmbargoExpiry.fieldCheck();

		if (what == 'embargo') {
			url += '&ResetEmbargo';
			EmbargoExpiry.embargoUnsaved = false;
		} else if (what == 'expiry') {
			url += '&ResetExpiry';
			EmbargoExpiry.expiryUnsaved = false;
		}

		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(t) {
				data = eval('('+t.responseText+')');
				if (data.status == 'success') {
					$(elIds.wholeMessage).style.display = 'none';
				} else {
					EmbargoExpiry.errorAlert(data);
				}
			},
			onFailure: function(t) { EmbargoExpiry.errorAlert(t); },
			onComplete: function(t) { $(el.id).className = 'action'; }
		});
	},
	errorAlert: function(data) {
		EmbargoExpiry.fieldCheck();
		alert("There was an error processing that request:\n\n"+data.message);
	},
	ids: function(forWhat) {
		switch(forWhat) {
			case 'expiry':
				return {
					resetButton: 'resetExpiryButton',
					saveButton: 'saveExpiryButton',
					dateField: 'ExpiryDate-date',
					timeField: 'ExpiryDate-time',
					timezoneField: 'ExpiryDate_TimeZone',
					wholeMessage: 'embargoExpiry-expiryStatus',
					dateTime: 'expiryDate',
					what: 'expiry'
				};
			case 'embargo':
				return {
					resetButton: 'resetEmbargoButton',
					saveButton: 'saveEmbargoButton',
					dateField: 'EmbargoDate-date',
					timeField: 'EmbargoDate-time',
					timezoneField: 'EmbargoDate_TimeZone',
					wholeMessage: 'embargoExpiry-embargoStatus',
					dateTime: 'embargoDate',
					what: 'embargo'
				};
		}
	},
	embargoChange: function() {
		EmbargoExpiry.embargoUnsaved = true;
		EmbargoExpiry.fieldCheck();
	},
	expiryChange: function() {
		EmbargoExpiry.expiryUnsaved = true;
		EmbargoExpiry.fieldCheck();
	},
	eButton: function(id) {
		Element.removeClassName(id, 'disabled');
		$(id).disabled = false;
	},
	dButton: function(id) {
		Element.addClassName(id, 'disabled');
		$(id).disabled = true;
	},
	fieldCheck: function() {
		if (EmbargoExpiry.originalValues === null) {
			EmbargoExpiry.originalValues = true;
		}

		ids = EmbargoExpiry.ids('embargo');
		// Only call this logic if the date field & save button exist, otherwise it's unnecessary
		if($(ids.dateField) && $(ids.saveButton)) {
			if ($(ids.dateField).value == '' || $(ids.timeField).value == '') {
				EmbargoExpiry.dButton(ids.saveButton);
				EmbargoExpiry.dButton(ids.resetButton);
			} else {
				EmbargoExpiry.eButton(ids.saveButton);
				EmbargoExpiry.eButton(ids.resetButton);
			}
		}

		ids = EmbargoExpiry.ids('expiry');
		// Only call this logic if the date field & save button exist, otherwise it's unnecessary
		if($(ids.dateField) && $(ids.saveButton)) {
			if ($(ids.dateField).value == '' || $(ids.timeField).value == '') {
				EmbargoExpiry.dButton(ids.saveButton);
				EmbargoExpiry.dButton(ids.resetButton);
				EmbargoExpiry.setExpiryWarning(false);
			} else {
				EmbargoExpiry.eButton(ids.saveButton);
				EmbargoExpiry.eButton(ids.resetButton);
				EmbargoExpiry.setExpiryWarning(true);
			}
		}
	},
	setExpiryWarning: function(shouldDisplay) {
		var el = $('ExpiryWorkflowWarning');
		if(el) el.style.display = shouldDisplay ? '' : 'none';
	}
};

Behaviour.register({
	'#EmbargoDate_Time' : {
		initialize: EmbargoExpiry.init
	}
});

var autoSave_original = autoSave;
autoSave = function(confirmation, callAfter) {
	if (EmbargoExpiry.embargoUnsaved || EmbargoExpiry.expiryUnsaved) {
		if (!confirm('Your embargo/expiry date changes have not been saved. Do you wish to continue?')) {
			return false;
		}
	}
	return autoSave_original(confirmation, callAfter);
};

var save_original = CMSForm.prototype.save;
CMSForm.prototype.save = function(ifChanged, callAfter, action, publish) {
	if (EmbargoExpiry.embargoUnsaved || EmbargoExpiry.expiryUnsaved) {
		if (!confirm('Your embargo/expiry date changes have not been saved. Do you wish to continue?')) {
			_AJAX_LOADING = false;
			if($('Form_EditForm_action_save') && $('Form_EditForm_action_save').stopLoading) $('Form_EditForm_action_save').stopLoading();
			if($('Form_EditForm_action_publish') && $('Form_EditForm_action_publish').stopLoading) $('Form_EditForm_action_publish').stopLoading();
			return false;
		}
	}
	return save_original.call(this, ifChanged, callAfter, action, publish);
};

function action_publish_right(e) {
	var messageEl = null;
	if (CMSWorkflow.getOption('noPromptForAdmin')) {
		messageEl = document.createElement("input");
		messageEl.type = "hidden";
		messageEl.name = 'WorkflowComment';
	} else {
		messageEl = CMSWorkflow.createPromptElement('WorkflowComment', 'Please comment on this publication, if applicable.');
	}
	$('Form_EditForm').appendChild(messageEl);

	// Don't need to restore the button state after ajax success because the form is replaced completely
	var btn = jQuery('#Form_EditForm_action_publish');
	btn.val(ss.i18n._t('CMSMAIN.PUBLISHING')).addClass('loading').attr('disabled', 'disabled');
	$('Form_EditForm').save(false, null, 'cms_publishwithcomment', true);
	$('Form_EditForm').removeChild(messageEl);
}

/**
 * UI behaviour for the "Access" tab
 */
Behaviour.register({
	'#Form_EditForm_CanApproveType input': {
		initialize: function() {
			if(this.checked) this.click();
		},
		onclick: function() {
			$('ApproverGroups').style.display = (this.value == 'OnlyTheseUsers') ? 'block' : 'none';
		}
	},
	'#Form_EditForm_CanPublishType input': {
		initialize: function() {
			if(this.checked) this.click();
		},
		onclick: function() {
			$('PublisherGroups').style.display = (this.value == 'OnlyTheseUsers') ? 'block' : 'none';
		}
	}
});

(function($) {
	// Limit date range for start/end date on reports
	$('.ReportAdmin input[name="StartDate\[date\]"], .ReportAdmin .field.datetime input[name="EndDate\[date\]"]').live('change', function(e) {
		// Don't apply if ssDatepicker plugin isn't present (e.g. in SilverStripe 2.4),
		// or if no datepicker has been applied to the field (configurable via the "showcalendar" option in DateField.php)
		if(!$.fn.ssDatepicker || !$(this).data('datepicker')) return;

		var $thisField = $(this), isStart = $thisField.is('[name="StartDate\[date\]"]'), isEnd = !isStart;

		var holder = $thisField.parents('form'),
			otherFieldName = isStart ? 'EndDate\[date\]' : 'StartDate\[date\]',
			$otherField = holder.find('input[name="' + otherFieldName + '"]');

		$otherField.ssDatepicker();
		$otherField.datepicker(
			'option',
			isStart ? 'minDate' : 'maxDate',
			$.datepicker.parseDate($otherField.datepicker('option', 'dateFormat'), $thisField.val())
		);
	});
}(jQuery));<|endoftext|>


<commit_before>jQuery.entwine("dependentdropdown", function($) {

	$(":input.dependent-dropdown").entwine({
		onmatch: function() {
			var drop = this;
			var depends = ($(":input[name=" + drop.data('depends') + "]"));

			this.parents('.field:first').addClass('dropdown');

			depends.change(function () {
				if(!this.value) {
					drop.disable(drop.data('unselected'));
				} else {
					drop.disable("Loading...")

					$.get(drop.data('link'), { val: this.value }, function(data) {
						drop.enable();

						if(drop.data('empty') || drop.data('empty') === "") {
							drop.append($("<option />").val("").text(drop.data('empty')))
						}

						$.each(data, function(k, v) {
							drop.append($("<option />").val(k).text(v))
						});
						drop.trigger("liszt:updated");
					});
				}
			});

			if(!depends.val()) {
				drop.disable(drop.data('unselected'));
			}
		},
		disable: function(text){
			this.empty().append($("<option />").val("").text(text)).attr("disabled", "disabled").trigger("liszt:updated");
		},
		enable: function(){
			this.empty().removeAttr("disabled").next().removeClass('chzn-disabled');
		}
	});

});<commit_msg>Update dependentdropdownfield.js<commit_after>jQuery.entwine("dependentdropdown", function($) {

	$(":input.dependent-dropdown").entwine({
		onmatch: function() {
			var drop = this;
			var depends = ($(":input[name=" + drop.data('depends').replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\$&") + "]"));

			this.parents('.field:first').addClass('dropdown');

			depends.change(function () {
				if(!this.value) {
					drop.disable(drop.data('unselected'));
				} else {
					drop.disable("Loading...")

					$.get(drop.data('link'), { val: this.value }, function(data) {
						drop.enable();

						if(drop.data('empty') || drop.data('empty') === "") {
							drop.append($("<option />").val("").text(drop.data('empty')))
						}

						$.each(data, function(k, v) {
							drop.append($("<option />").val(k).text(v))
						});
						drop.trigger("liszt:updated");
					});
				}
			});

			if(!depends.val()) {
				drop.disable(drop.data('unselected'));
			}
		},
		disable: function(text){
			this.empty().append($("<option />").val("").text(text)).attr("disabled", "disabled").trigger("liszt:updated");
		},
		enable: function(){
			this.empty().removeAttr("disabled").next().removeClass('chzn-disabled');
		}
	});

});
<|endoftext|>


<commit_before>/**
 * Patterns gallery - A simple gallery
 *
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../registry",
    "photoswipe"
], function($, patterns) {
    var gallery = {
        name: "gallery",
        trigger: ".pat-gallery",

        init: function($el) {
            return $el;
        }
    };

    patterns.register(gallery);
    return gallery;
});
<commit_msg>Work around bungle bug (it ignores dependencies).<commit_after>/**
 * Patterns gallery - A simple gallery
 *
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../registry",
    "klass", // Workaround because bungle is ignoring dependencies currently
    "photoswipe"
], function($, patterns) {
    var gallery = {
        name: "gallery",
        trigger: ".pat-gallery",

        init: function($el) {
            return $el;
        }
    };

    patterns.register(gallery);
    return gallery;
});
<|endoftext|>


<commit_before>"use strict";

var CityTour = CityTour || {};

CityTour.PathFinder = function() {
  var targetMapX = 0.0;
  var targetMapZ = 0.0;
  var deltaX = 0.0;
  var deltaZ = 1.0;

  var determineNextTargetPoint = function() {
    var oldTargetMapX = targetMapX;
    var oldTargetMapZ = targetMapZ;

    while (oldTargetMapX === targetMapX && oldTargetMapZ === targetMapZ) {
      if (deltaX === 0.0) {
        targetMapX = Math.floor(Math.random() * CityTour.Config.BLOCK_ROWS) - CityTour.Config.HALF_BLOCK_ROWS;
      }
      else if (deltaZ === 0.0) {
        targetMapZ = Math.floor(Math.random() * CityTour.Config.BLOCK_COLUMNS) - CityTour.Config.HALF_BLOCK_COLUMNS;
      }
    }

    deltaX = (deltaX === 0.0) ? 1.0 : 0.0;
    deltaZ = (deltaZ === 0.0) ? 1.0 : 0.0;
  };

  var pathFinder = {};

  pathFinder.targetMapX = function() { return targetMapX; };
  pathFinder.targetMapZ = function() { return targetMapZ; };

  pathFinder.nextTarget = function() {
    determineNextTargetPoint();
  };

  return pathFinder;
};

CityTour.DijktrasPathFinder = function(roadNetwork) {
  var Node = function(x, z) {
    return {
      isVisited: false,
      distance:  Number.POSITIVE_INFINITY,
      previous:  null,
      x:         x,
      z:         z,
    };
  };

  var chooseNewTarget = function() {
    var newTargetMapX = Number.POSITIVE_INFINITY;
    var newTargetMapZ = Number.POSITIVE_INFINITY;

    while (!roadNetwork.hasIntersection(newTargetMapX, newTargetMapZ)) {
      newTargetMapX = (Math.round(Math.random() * CityTour.Config.BLOCK_COLUMNS)) - CityTour.Config.HALF_BLOCK_COLUMNS;
      newTargetMapZ = (Math.round(Math.random() * CityTour.Config.BLOCK_ROWS)) - CityTour.Config.HALF_BLOCK_ROWS;
    }

    return [newTargetMapX, newTargetMapZ];
  };

  var extractShortestPath = function(nodes, endX, endZ) {
    var path = [];
    var currentNode = nodes[endX][endZ];
    var previous;

    while (currentNode.previous) {
      path.unshift([currentNode.x, currentNode.z]);

      previous = currentNode.previous;
      currentNode = nodes[previous[0]][previous[1]];
    }

    return path;
  };

  var evaluateNodeConnections = function(currentNode, nodes, unvisitedSet) {
    var x = currentNode.x;
    var z = currentNode.z;

    var evaluateAdjancentNode = function(adjacentX, adjacentZ) {
      var adjacentNode, candidateDistance;

      if (roadNetwork.hasEdgeBetween(x, z, adjacentX, adjacentZ)) {
        adjacentNode = nodes[adjacentX][adjacentZ];

        if (!adjacentNode) {
          adjacentNode = new Node(adjacentX, adjacentZ);
          nodes[adjacentX][adjacentZ] = adjacentNode;
          unvisitedSet.add(adjacentNode);
        }
        if (!adjacentNode.isVisited) {
          candidateDistance = currentNode.distance + 1;
          if (candidateDistance < adjacentNode.distance) {
            adjacentNode.distance = candidateDistance;
            adjacentNode.previous = [x, z];
          }
        }
      }
    };

    evaluateAdjancentNode(x - 1, z);
    evaluateAdjancentNode(x + 1, z);
    evaluateAdjancentNode(x, z - 1);
    evaluateAdjancentNode(x, z + 1);

    currentNode.isVisited = true;
  };

  var unvisitedNodeWithShortestLength = function(unvisitedSet) {
    var shortestLength = Number.POSITIVE_INFINITY;
    var shortestLengthNode = null;

    unvisitedSet.forEach(function(node) {
      if (node.distance < shortestLength) {
        shortestLength = node.distance;
        shortestLengthNode = node;
      }
    });

    return shortestLengthNode;
  };

  var simplifyPath = function(path) {
    var xRun = 0;
    var zRun = 0;
    var previousX = null;
    var previousZ = null;

    var simplifiedPath = [];

    var i, x, z;
    for (i = 0; i < path.length; i++) {
      x = path[i][0];
      z = path[i][1];
      xRun = (x === previousX) ? xRun + 1 : 0;
      zRun = (z === previousZ) ? zRun + 1 : 0;

      if (((xRun === 1 && zRun === 0) || (xRun === 0 && zRun === 1)) && (i > 1)) {
        simplifiedPath.push([previousX, previousZ]);
      }

      previousX = x;
      previousZ = z;
    };

    simplifiedPath.push([x, z]);

    return simplifiedPath;
  };

  var findShortestPath = function(startX, startZ, endX, endZ) {
    var nodes = [];
    var unvisitedSet = new Set();
    var x;

    for (x = -CityTour.Config.HALF_BLOCK_COLUMNS; x <= CityTour.Config.HALF_BLOCK_COLUMNS; x++) {
      nodes[x] = [];
    }

    var currentNode;

    nodes[startX][startZ] = new Node(startX, startZ);
    currentNode = nodes[startX][startZ];
    currentNode.distance = 0;

    while(currentNode.x != endX || currentNode.z != endZ) {
      evaluateNodeConnections(currentNode, nodes, unvisitedSet);
      unvisitedSet.delete(currentNode);

      currentNode = unvisitedNodeWithShortestLength(unvisitedSet);
    }

    var path = extractShortestPath(nodes, endX, endZ);
    path = simplifyPath(path);

    return path;
  };

  var targetMapX = 0;
  var targetMapZ = 0;
  var subTargetMapX = 0;
  var subTargetMapZ = 0;

  var path = [];

  var dijktrasPathFinder = {};

  dijktrasPathFinder.targetMapX = function() { return subTargetMapX; };
  dijktrasPathFinder.targetMapZ = function() { return subTargetMapZ; };

  dijktrasPathFinder.nextTarget = function() {
    if (path.length === 0) {
      var newTargetCoordinates = chooseNewTarget();
      path = findShortestPath(targetMapX, targetMapZ, newTargetCoordinates[0], newTargetCoordinates[1]);

      targetMapX = newTargetCoordinates[0];
      targetMapZ = newTargetCoordinates[1];
    }

    var nextTargetPoint = path.splice(0, 1);
    subTargetMapX = nextTargetPoint[0][0];
    subTargetMapZ = nextTargetPoint[0][1];
  };

  return dijktrasPathFinder;
};
<commit_msg>Fixing target point generation in path finding<commit_after>"use strict";

var CityTour = CityTour || {};

CityTour.PathFinder = function() {
  var targetMapX = 0.0;
  var targetMapZ = 0.0;
  var deltaX = 0.0;
  var deltaZ = 1.0;

  var determineNextTargetPoint = function() {
    var oldTargetMapX = targetMapX;
    var oldTargetMapZ = targetMapZ;

    while (oldTargetMapX === targetMapX && oldTargetMapZ === targetMapZ) {
      if (deltaX === 0.0) {
        targetMapX = Math.floor(Math.random() * CityTour.Config.BLOCK_ROWS) - CityTour.Config.HALF_BLOCK_ROWS;
      }
      else if (deltaZ === 0.0) {
        targetMapZ = Math.floor(Math.random() * CityTour.Config.BLOCK_COLUMNS) - CityTour.Config.HALF_BLOCK_COLUMNS;
      }
    }

    deltaX = (deltaX === 0.0) ? 1.0 : 0.0;
    deltaZ = (deltaZ === 0.0) ? 1.0 : 0.0;
  };

  var pathFinder = {};

  pathFinder.targetMapX = function() { return targetMapX; };
  pathFinder.targetMapZ = function() { return targetMapZ; };

  pathFinder.nextTarget = function() {
    determineNextTargetPoint();
  };

  return pathFinder;
};

CityTour.DijktrasPathFinder = function(roadNetwork) {
  var Node = function(x, z) {
    return {
      isVisited: false,
      distance:  Number.POSITIVE_INFINITY,
      previous:  null,
      x:         x,
      z:         z,
    };
  };

  var chooseNewTarget = function() {
    var newTargetMapX;
    var newTargetMapZ;

    do {
      newTargetMapX = (Math.round(Math.random() * CityTour.Config.BLOCK_COLUMNS)) - CityTour.Config.HALF_BLOCK_COLUMNS;
      newTargetMapZ = (Math.round(Math.random() * CityTour.Config.BLOCK_ROWS)) - CityTour.Config.HALF_BLOCK_ROWS;
    } while (!roadNetwork.hasIntersection(newTargetMapX, newTargetMapZ));

    return [newTargetMapX, newTargetMapZ];
  };

  var extractShortestPath = function(nodes, endX, endZ) {
    var path = [];
    var currentNode = nodes[endX][endZ];
    var previous;

    while (currentNode.previous) {
      path.unshift([currentNode.x, currentNode.z]);

      previous = currentNode.previous;
      currentNode = nodes[previous[0]][previous[1]];
    }

    return path;
  };

  var evaluateNodeConnections = function(currentNode, nodes, unvisitedSet) {
    var x = currentNode.x;
    var z = currentNode.z;

    var evaluateAdjancentNode = function(adjacentX, adjacentZ) {
      var adjacentNode, candidateDistance;

      if (roadNetwork.hasEdgeBetween(x, z, adjacentX, adjacentZ)) {
        adjacentNode = nodes[adjacentX][adjacentZ];

        if (!adjacentNode) {
          adjacentNode = new Node(adjacentX, adjacentZ);
          nodes[adjacentX][adjacentZ] = adjacentNode;
          unvisitedSet.add(adjacentNode);
        }
        if (!adjacentNode.isVisited) {
          candidateDistance = currentNode.distance + 1;
          if (candidateDistance < adjacentNode.distance) {
            adjacentNode.distance = candidateDistance;
            adjacentNode.previous = [x, z];
          }
        }
      }
    };

    evaluateAdjancentNode(x - 1, z);
    evaluateAdjancentNode(x + 1, z);
    evaluateAdjancentNode(x, z - 1);
    evaluateAdjancentNode(x, z + 1);

    currentNode.isVisited = true;
  };

  var unvisitedNodeWithShortestLength = function(unvisitedSet) {
    var shortestLength = Number.POSITIVE_INFINITY;
    var shortestLengthNode = null;

    unvisitedSet.forEach(function(node) {
      if (node.distance < shortestLength) {
        shortestLength = node.distance;
        shortestLengthNode = node;
      }
    });

    return shortestLengthNode;
  };

  var simplifyPath = function(path) {
    var xRun = 0;
    var zRun = 0;
    var previousX = null;
    var previousZ = null;

    var simplifiedPath = [];

    var i, x, z;
    for (i = 0; i < path.length; i++) {
      x = path[i][0];
      z = path[i][1];
      xRun = (x === previousX) ? xRun + 1 : 0;
      zRun = (z === previousZ) ? zRun + 1 : 0;

      if (((xRun === 1 && zRun === 0) || (xRun === 0 && zRun === 1)) && (i > 1)) {
        simplifiedPath.push([previousX, previousZ]);
      }

      previousX = x;
      previousZ = z;
    };

    simplifiedPath.push([x, z]);

    return simplifiedPath;
  };

  var findShortestPath = function(startX, startZ, endX, endZ) {
    var nodes = [];
    var unvisitedSet = new Set();
    var x;

    for (x = -CityTour.Config.HALF_BLOCK_COLUMNS; x <= CityTour.Config.HALF_BLOCK_COLUMNS; x++) {
      nodes[x] = [];
    }

    var currentNode;

    nodes[startX][startZ] = new Node(startX, startZ);
    currentNode = nodes[startX][startZ];
    currentNode.distance = 0;

    while(currentNode.x != endX || currentNode.z != endZ) {
      evaluateNodeConnections(currentNode, nodes, unvisitedSet);
      unvisitedSet.delete(currentNode);

      currentNode = unvisitedNodeWithShortestLength(unvisitedSet);
    }

    var path = extractShortestPath(nodes, endX, endZ);
    path = simplifyPath(path);

    return path;
  };

  var targetMapX = 0;
  var targetMapZ = 0;
  var subTargetMapX = 0;
  var subTargetMapZ = 0;

  var path = [];

  var dijktrasPathFinder = {};

  dijktrasPathFinder.targetMapX = function() { return subTargetMapX; };
  dijktrasPathFinder.targetMapZ = function() { return subTargetMapZ; };

  dijktrasPathFinder.nextTarget = function() {
    if (path.length === 0) {
      var newTargetCoordinates = chooseNewTarget();
      path = findShortestPath(targetMapX, targetMapZ, newTargetCoordinates[0], newTargetCoordinates[1]);

      targetMapX = newTargetCoordinates[0];
      targetMapZ = newTargetCoordinates[1];
    }

    var nextTargetPoint = path.splice(0, 1);
    subTargetMapX = nextTargetPoint[0][0];
    subTargetMapZ = nextTargetPoint[0][1];
  };

  return dijktrasPathFinder;
};
<|endoftext|>


<commit_before>import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import '../node_modules/leaflet-measure/dist/leaflet-measure'
import '../node_modules/leaflet-measure/dist/leaflet-measure.css'
import 'leaflet.nontiledlayer'
import 'leaflet.gridlayer.googlemutant'
import {MAX_ZOOM} from './constants'

export default class Map {

  constructor() {
    this.map = L.map("map", {
                 zoom: 10,
                 center: [42.284829, -8.553642],
                 zoomControl: false,
                 attributionControl: true,
                 maxZoom: MAX_ZOOM
    })

    L.control.zoom({position: 'bottomright'}).addTo(this.map)

    const measureOptions = {
      position: 'topright',
      localization: 'es',

      primaryLengthUnit: 'meters',
      secondaryLengthUnit: 'kilometers',
      primaryAreaUnit: 'sqmeters',

      captureZIndex: 10000
    }

    const measureControl = L.control.measure(measureOptions)
    measureControl.addTo(this.map)

    const pnoa = L.tileLayer.wms('http://www.ign.es/wms-inspire/pnoa-ma?', {
      maxZoom: MAX_ZOOM,
      layers: 'OI.OrthoimageCoverage',
      format: 'image/png',
      attribution: 'PNOA cedido por © Instituto Geográfico Nacional de España'
    }).addTo(this.map)

    const satellite = L.gridLayer.googleMutant({
      maxZoom: MAX_ZOOM,
      type: 'satellite' // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
    })

    const catastroUrl = 'https://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?'

    const catastroBase = L.nonTiledLayer.wms(
      catastroUrl,
      {
        maxZoom: MAX_ZOOM,
        layers: 'Catastro',
        format: 'image/png',
        transparent: false,
        attribution: 'Dirección General del Catastro'
      }
    )

    const catastroOverlay = L.nonTiledLayer.wms(catastroUrl, {
      maxZoom: MAX_ZOOM,
      layers: 'Catastro',
      format: 'image/png',
      transparent: true,
      attribution: 'DG del Catastro'
    }).addTo(this.map)

    this.highlight = L.geoJSON(null, {
      pointToLayer:  function (ftr, latLng) {
        return L.circleMarker(latLng);
      },
      style: (feature) => {
        const { properties } = feature
        return properties
      },
      onEachFeature: (feature, layer) => {
        this.map.fitBounds(layer.getBounds())
      }
    }).addTo(this.map)

    const baseMaps = {
      PNOA: pnoa,
      Catastro: catastroBase,
      'Google Satellite': satellite
    }

    const overLays = {
      'Catastro' : catastroOverlay,
      //'Catastro.wms': Spain_Catastro
    }

    /* Configuración Control de Capas */
    const layerControl = L.control.layers(baseMaps, overLays, {collapsed:false})
    layerControl.addTo(this.map)

    var htmlObject = layerControl.getContainer()
    $('#panel-capas').append(htmlObject)

  }

  clearHighLight() {
    this.highlight.clearLayers()
  }

  loadGeoJson(geoJson) {
    this.clearHighLight()
    this.highlight.addData(geoJson)
  }
}

<commit_msg>Se cambia la url del pnoa a https<commit_after>import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import '../node_modules/leaflet-measure/dist/leaflet-measure'
import '../node_modules/leaflet-measure/dist/leaflet-measure.css'
import 'leaflet.nontiledlayer'
import 'leaflet.gridlayer.googlemutant'
import {MAX_ZOOM} from './constants'

export default class Map {

  constructor() {
    this.map = L.map("map", {
                 zoom: 10,
                 center: [42.284829, -8.553642],
                 zoomControl: false,
                 attributionControl: true,
                 maxZoom: MAX_ZOOM
    })

    L.control.zoom({position: 'bottomright'}).addTo(this.map)

    const measureOptions = {
      position: 'topright',
      localization: 'es',

      primaryLengthUnit: 'meters',
      secondaryLengthUnit: 'kilometers',
      primaryAreaUnit: 'sqmeters',

      captureZIndex: 10000
    }

    const measureControl = L.control.measure(measureOptions)
    measureControl.addTo(this.map)

    const pnoa = L.tileLayer.wms('https://www.ign.es/wms-inspire/pnoa-ma?', {
      maxZoom: MAX_ZOOM,
      layers: 'OI.OrthoimageCoverage',
      format: 'image/png',
      attribution: 'PNOA cedido por © Instituto Geográfico Nacional de España'
    }).addTo(this.map)

    const satellite = L.gridLayer.googleMutant({
      maxZoom: MAX_ZOOM,
      type: 'satellite' // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
    })

    const catastroUrl = 'https://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?'

    const catastroBase = L.nonTiledLayer.wms(
      catastroUrl,
      {
        maxZoom: MAX_ZOOM,
        layers: 'Catastro',
        format: 'image/png',
        transparent: false,
        attribution: 'Dirección General del Catastro'
      }
    )

    const catastroOverlay = L.nonTiledLayer.wms(catastroUrl, {
      maxZoom: MAX_ZOOM,
      layers: 'Catastro',
      format: 'image/png',
      transparent: true,
      attribution: 'DG del Catastro'
    }).addTo(this.map)

    this.highlight = L.geoJSON(null, {
      pointToLayer:  function (ftr, latLng) {
        return L.circleMarker(latLng);
      },
      style: (feature) => {
        const { properties } = feature
        return properties
      },
      onEachFeature: (feature, layer) => {
        this.map.fitBounds(layer.getBounds())
      }
    }).addTo(this.map)

    const baseMaps = {
      PNOA: pnoa,
      Catastro: catastroBase,
      'Google Satellite': satellite
    }

    const overLays = {
      'Catastro' : catastroOverlay,
      //'Catastro.wms': Spain_Catastro
    }

    /* Configuración Control de Capas */
    const layerControl = L.control.layers(baseMaps, overLays, {collapsed:false})
    layerControl.addTo(this.map)

    var htmlObject = layerControl.getContainer()
    $('#panel-capas').append(htmlObject)

  }

  clearHighLight() {
    this.highlight.clearLayers()
  }

  loadGeoJson(geoJson) {
    this.clearHighLight()
    this.highlight.addData(geoJson)
  }
}

<|endoftext|>


<commit_before>import _ from 'lodash'

function request() {
  return function() {
    throw new Error('rest.map.req is not implemented')
  }
}

function response(map) {

  function mapDocument(document) {
    const doc = {}
    document = document.toObject()

    _.forEach(document, function(val, key) {
      key = map[key] || key
      doc[key] = val
    })

    return doc
  }

  return function(req, res) {
    if (_.isArray(res.body)) {
      res.body = _.map(res.body, mapDocument)
      return
    }

    if (_.isObject(res.body)) {
      res.body = mapDocument(res.body)
      return
    }
  }

}

export default Object.freeze({
  req: request,
  res: response
})
<commit_msg>fix: handle lean documents<commit_after>import _ from 'lodash'

function request() {
  return function() {
    throw new Error('rest.map.req is not implemented')
  }
}

function response(map) {

  function mapDocument(document) {
    const doc = {}

    if (_.isFunction(document.toObject)) {
      document = document.toObject()
    }

    _.forEach(document, function(val, key) {
      key = map[key] || key
      doc[key] = val
    })

    return doc
  }

  return function(req, res) {
    if (_.isArray(res.body)) {
      res.body = _.map(res.body, mapDocument)
      return
    }

    if (_.isObject(res.body)) {
      res.body = mapDocument(res.body)
    }
  }

}

export default Object.freeze({
  req: request,
  res: response
})
<|endoftext|>


<commit_before>export default {
  size: {
    root: {
      desktop: '16px',
      mobile: '13px',
    },

    base: '1rem',
    lg: '1.25rem',
    sm: '0.875rem',
    xs: '0.75rem',
    xx: '0.625rem',
    h1: '2.5rem',
    h2: '2rem',
    h3: '1.75rem',
    h4: '1.5rem',
    h5: '1.25rem',
    h6: '1rem',
  },

  lineHeight: {
    base: 1.33,
    tall: 1.5,
  },

  font: {
    sans: "'Arial', 'Helvetica Neue', 'Helvetica', sans-serif",
    serif: "'Times New Roman', serif",
    mono: "Menlo, Monaco, 'Bitstream Vera Sans Mono', Consolas, Courier, monospace",
  },

  mixins: {
    antialiased: `
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    `,
  },
};
<commit_msg>Makes this a proper mixin<commit_after>import { css } from 'styled-components';

export default {
  size: {
    root: {
      desktop: '16px',
      mobile: '13px',
    },

    base: '1rem',
    lg: '1.25rem',
    sm: '0.875rem',
    xs: '0.75rem',
    xx: '0.625rem',
    h1: '2.5rem',
    h2: '2rem',
    h3: '1.75rem',
    h4: '1.5rem',
    h5: '1.25rem',
    h6: '1rem',
  },

  lineHeight: {
    base: 1.33,
    tall: 1.5,
  },

  font: {
    sans: "'Arial', 'Helvetica Neue', 'Helvetica', sans-serif",
    serif: "'Times New Roman', serif",
    mono: "Menlo, Monaco, 'Bitstream Vera Sans Mono', Consolas, Courier, monospace",
  },

  mixins: {
    antialiased: css`
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    `,
  },
};
<|endoftext|>