<commit_before>import { utils } from "stylelint";
import { namespace } from "../../utils";

export const ruleName = namespace("each-key-value-single-line");

export const messages = utils.ruleMessages(ruleName, {
  expected:
    "Use @each $key, $value in $map syntax instead of $value: map-get($map, $key)"
});

export default function(primary) {
  return (root, result) => {
    const validOptions = utils.validateOptions(result, ruleName, {
      actual: primary
    });

    if (!validOptions) {
      return;
    }

    root.walkAtRules("each", rule => {
      const parts = separateEachParams(rule.params);

      // If loop is fetching both key + value, return
      if (parts[0].length == 2) {
        return;
      }

      // If didn't call map-keys, return.
      if (!didCallMapKeys(parts[1])) {
        return;
      }

      // Loop over decls inside of each statement and loop for variable assignments.
      rule.walkDecls(innerDecl => {
        // Check that this decl is a map-get call
        if (innerDecl.prop[0] !== "$") {
          return;
        }
        console.log("test");

        if (!didCallMapGet(innerDecl.value)) {
          return;
        }

        // Check map_name + key_name match.
        const map_get_parts = mapGetParameters(innerDecl.value);

        // Check map names match.
        if (map_get_parts[0] !== mapName(parts[1])) {
          return;
        }

        // Match key names match.
        if (map_get_parts[1] !== parts[0][0]) {
          return;
        }

        utils.report({
          message: messages.rejected,
          node: rule,
          result,
          ruleName
        });
      });
    });
  };
}

// Takes in a param string from node.params
// Returns: [[key variable, value variable], map_decl] (all Strings)
function separateEachParams(paramString) {
  const parts = paramString.split("in");
  return [parts[0].split(",").map(s => s.trim()), parts[1].trim()];
}

function didCallMapKeys(map_decl) {
  return map_decl.match(/map-keys\(.*\)/);
}

function didCallMapGet(map_decl) {
  return map_decl.match(/map-get\((.*),(.*)\)/);
}

// Fetch the name of the map from a map-keys() call.
function mapName(map_decl) {
  if (didCallMapKeys(map_decl)) {
    return map_decl.match(/map-keys\((.*)\)/)[1];
  } else {
    return map_decl;
  }
}

// Returns the parameters of a map-get call
// Returns [map variable, key_variable]
function mapGetParameters(mapGetDecl) {
  const parts = mapGetDecl.match(/map-get\((.*), ?(.*)\)/);
  return [parts[1], parts[2]];
}
<commit_msg>linter fixes<commit_after>import { utils } from "stylelint";
import { namespace } from "../../utils";

export const ruleName = namespace("each-key-value-single-line");

export const messages = utils.ruleMessages(ruleName, {
  expected:
    "Use @each $key, $value in $map syntax instead of $value: map-get($map, $key)"
});

export default function(primary) {
  return (root, result) => {
    const validOptions = utils.validateOptions(result, ruleName, {
      actual: primary
    });

    if (!validOptions) {
      return;
    }

    root.walkAtRules("each", rule => {
      const parts = separateEachParams(rule.params);

      // If loop is fetching both key + value, return
      if (parts[0].length === 2) {
        return;
      }

      // If didn't call map-keys, return.
      if (!didCallMapKeys(parts[1])) {
        return;
      }

      // Loop over decls inside of each statement and loop for variable assignments.
      rule.walkDecls(innerDecl => {
        // Check that this decl is a map-get call
        if (innerDecl.prop[0] !== "$") {
          return;
        }

        if (!didCallMapGet(innerDecl.value)) {
          return;
        }

        // Check map_name + key_name match.
        const map_get_parts = mapGetParameters(innerDecl.value);

        // Check map names match.
        if (map_get_parts[0] !== mapName(parts[1])) {
          return;
        }

        // Match key names match.
        if (map_get_parts[1] !== parts[0][0]) {
          return;
        }

        utils.report({
          message: messages.rejected,
          node: rule,
          result,
          ruleName
        });
      });
    });
  };
}

// Takes in a param string from node.params
// Returns: [[key variable, value variable], map_decl] (all Strings)
function separateEachParams(paramString) {
  const parts = paramString.split("in");

  return [parts[0].split(",").map(s => s.trim()), parts[1].trim()];
}

function didCallMapKeys(map_decl) {
  return map_decl.match(/map-keys\(.*\)/);
}

function didCallMapGet(map_decl) {
  return map_decl.match(/map-get\((.*),(.*)\)/);
}

// Fetch the name of the map from a map-keys() call.
function mapName(map_decl) {
  if (didCallMapKeys(map_decl)) {
    return map_decl.match(/map-keys\((.*)\)/)[1];
  } else {
    return map_decl;
  }
}

// Returns the parameters of a map-get call
// Returns [map variable, key_variable]
function mapGetParameters(mapGetDecl) {
  const parts = mapGetDecl.match(/map-get\((.*), ?(.*)\)/);

  return [parts[1], parts[2]];
}
<|endoftext|>


<commit_before>const moment = require('moment')
const { mapValues, get } = require('lodash')
const { buildCompanyUrl } = require('./company.service')

function transformToApi (body) {
  const schema = {
    'client_relationship_manager': Object,
    'referral_source_adviser': Object,
    'referral_source_activity': Object,
    'referral_source_activity_marketing': Object,
    'referral_source_activity_website': Object,
    'investor_company': Object,
    'investment_type': Object,
    'fdi_type': Object,
    'non_fdi_type': Object,
    'sector': Object,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const relationshipMgr = body['is-relationship-manager']
  if (relationshipMgr !== 'No') {
    body.client_relationship_manager = relationshipMgr
  }

  const referralSource = body['is-relationship-manager']
  if (referralSource !== 'No') {
    body.referral_source_adviser = referralSource
  }

  const formatted = mapValues(schema, (type, key) => {
    const value = body[key]

    if (!value) {
      return
    }

    if (type === Array) {
      return [{ id: value }]
    }

    return { id: value }
  })

  formatted['estimated_land_date'] = `${body['land-date_year']}-${body['land-date_month']}-01`

  return Object.assign({}, body, formatted)
}

function transformFromApi (body) {
  const schema = {
    'client_relationship_manager': String,
    'referral_source_adviser': String,
    'referral_source_activity': String,
    'investor_company': String,
    'investment_type': String,
    'sector': String,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const formatted = mapValues(schema, (type, key) => {
    if (type === Array) {
      return get(body, `${key}[0].id`, '')
    }
    return get(body, `${key}.id`)
  })

  const date = new Date(body['estimated_land_date'])
  formatted['land-date_year'] = date.getFullYear()
  formatted['land-date_month'] = date.getMonth() + 1 // month is zero based index

  return Object.assign({}, body, formatted)
}

function formatProjectData (data) {
  return {
    'Client': {
      name: data.investor_company.name,
      url: buildCompanyUrl(data.investor_company),
    },
    'Type of investment': data.investment_type.name,
    'Primary sector': get(data, 'sector.name', null),
    'Sub-sector': null,
    'Business activity': data.business_activity,
    'Project description': data.description,
    'Non-disclosure agreement': data.nda_signed ? 'Signed' : 'Not signed',
    'Shareable with UK partners': null,
    'Anonymous description': null,
    'Estimated land date': data.estimated_land_date ? moment(data.estimated_land_date).format('MMMM YYYY') : null,
  }
}

function formatValueData (data) {
  return {
    'Total investment': data.total_investment,
    'Foreign equity investment': data.foreign_equity_investment,
    'Government assistance': data.government_assistance,
    'New jobs': data.number_new_jobs,
    'Average salary': data.average_salary,
    'Safeguarded jobs': data.number_safeguarded_jobs,
    'R&D budget': data.r_and_d_budget,
    'Non-FDI R&D project': data.non_fdi_r_and_d_budget,
    'New-to-world tech': data.new_tech_to_uk,
    'Export revenue': data.export_revenue,
  }
}

function formatRequirementsData (data) {
  return {
    'Main strategic drivers': data.strategic_drivers,
    'Client requirements': data.client_requirements,
    'Competitor countries': data.competitor_countries,
    'Possible UK locations': data.uk_region_locations,
    'Investment location': null,
    'UK recipient company': data.uk_company,
  }
}

function formatProjectStatusData (data) {
  return {
    id: data.id,
    name: data.name,
    projectCode: data.project_code,
    phaseName: data.phase.name,
  }
}

module.exports = {
  formatProjectData,
  formatValueData,
  formatRequirementsData,
  formatProjectStatusData,
  transformToApi,
  transformFromApi,
}
<commit_msg>Fix schema in investment formatting service<commit_after>const moment = require('moment')
const { mapValues, get } = require('lodash')
const { buildCompanyUrl } = require('./company.service')

function transformToApi (body) {
  const schema = {
    'client_relationship_manager': Object,
    'referral_source_adviser': Object,
    'referral_source_activity': Object,
    'referral_source_activity_marketing': Object,
    'referral_source_activity_website': Object,
    'investor_company': Object,
    'investment_type': Object,
    'fdi_type': Object,
    'non_fdi_type': Object,
    'sector': Object,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const relationshipMgr = body['is-relationship-manager']
  if (relationshipMgr !== 'No') {
    body.client_relationship_manager = relationshipMgr
  }

  const referralSource = body['is-referral-source']
  if (referralSource !== 'No') {
    body.referral_source_adviser = referralSource
  }

  const formatted = mapValues(schema, (type, key) => {
    const value = body[key]

    if (!value) {
      return
    }

    if (type === Array) {
      return [{ id: value }]
    }

    return { id: value }
  })

  formatted['estimated_land_date'] = `${body['land-date_year']}-${body['land-date_month']}-01`

  return Object.assign({}, body, formatted)
}

function transformFromApi (body) {
  const schema = {
    'client_relationship_manager': String,
    'referral_source_adviser': String,
    'referral_source_activity': String,
    'referral_source_activity_marketing': String,
    'referral_source_activity_website': String,
    'investor_company': String,
    'investment_type': String,
    'fdi_type': String,
    'non_fdi_type': String,
    'sector': String,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const formatted = mapValues(schema, (type, key) => {
    if (type === Array) {
      return get(body, `${key}[0].id`, '')
    }
    return get(body, `${key}.id`)
  })

  const date = new Date(body['estimated_land_date'])
  formatted['land-date_year'] = date.getFullYear()
  formatted['land-date_month'] = date.getMonth() + 1 // month is zero based index

  return Object.assign({}, body, formatted)
}

function formatProjectData (data) {
  return {
    'Client': {
      name: data.investor_company.name,
      url: buildCompanyUrl(data.investor_company),
    },
    'Type of investment': data.investment_type.name,
    'Primary sector': get(data, 'sector.name', null),
    'Sub-sector': null,
    'Business activity': data.business_activity,
    'Project description': data.description,
    'Non-disclosure agreement': data.nda_signed ? 'Signed' : 'Not signed',
    'Shareable with UK partners': null,
    'Anonymous description': null,
    'Estimated land date': data.estimated_land_date ? moment(data.estimated_land_date).format('MMMM YYYY') : null,
  }
}

function formatValueData (data) {
  return {
    'Total investment': data.total_investment,
    'Foreign equity investment': data.foreign_equity_investment,
    'Government assistance': data.government_assistance,
    'New jobs': data.number_new_jobs,
    'Average salary': data.average_salary,
    'Safeguarded jobs': data.number_safeguarded_jobs,
    'R&D budget': data.r_and_d_budget,
    'Non-FDI R&D project': data.non_fdi_r_and_d_budget,
    'New-to-world tech': data.new_tech_to_uk,
    'Export revenue': data.export_revenue,
  }
}

function formatRequirementsData (data) {
  return {
    'Main strategic drivers': data.strategic_drivers,
    'Client requirements': data.client_requirements,
    'Competitor countries': data.competitor_countries,
    'Possible UK locations': data.uk_region_locations,
    'Investment location': null,
    'UK recipient company': data.uk_company,
  }
}

function formatProjectStatusData (data) {
  return {
    id: data.id,
    name: data.name,
    projectCode: data.project_code,
    phaseName: data.phase.name,
  }
}

module.exports = {
  formatProjectData,
  formatValueData,
  formatRequirementsData,
  formatProjectStatusData,
  transformToApi,
  transformFromApi,
}
<|endoftext|>


<commit_before>/**
 * <%=nameC%>Controller
 *
 * @description :: Server-side logic for managing <%=name%>
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {

  add: function(req,res){
    res.view();
  },

  create: function(req, res) {

    var paramObj = {
      <% for(var i in attributes) { %>
        <%=attributes[i].name%> : req.param('<%=attributes[i].name%>')<%if(i < attributes.length - 1 ){%>,<%}%>
      <% } %>
    }

    // Create a <%=nameC%> with the params sent from
    // the sign-up form --> add.ejs
    <%=nameC%>.create(paramObj, function (err, <%=name%>) {

      if (err) {
        sails.log.error(err);

        if(err.ValidationError){

          error_object = validator(<%=nameC%>, err.ValidationError);

          req.flash('error', error_object);

          return res.redirect('/<%=name%>/add');

        } else {
          return res.serverError();
        }

      } else {
        return res.redirect('/<%=name%>/show/' + <%=name%>.id);
      }
    });
  },

  show: function(req, res, next) {
    <%=nameC%>.findOne(req.param('id'), function (err, <%=name%>) {
      if (err) {
        return next(err);
      } else {
        if (!<%=name%>) {
          return res.notFound();
        } else {

          res.view({
            <%=name%>: <%=name%>
          });
        }
      }
    });
  },

  index: function(req, res, next) {
    <%=nameC%>.find(function (err, <%=namePlural%>) {
      if (err) {
        return next(err);
      } else {
        res.view({
          <%=namePlural%>: <%=namePlural%>
        });
      }
    });
  },

  edit: function(req, res, next) {

    <%=nameC%>.findOne(req.param('id'), function (err, <%=name%>) {
      if (err) {
        return next(err);
      } else {
        if (!<%=name%>) {
          return res.notFound();
        } else {
          res.view({
            <%=name%>: <%=name%>
          });
        }
      }
    });
  },

  update: function(req, res, next) {

    var paramObj = {
      <% for(var i in attributes) { %>
        <%=attributes[i].name%> : req.param('<%=attributes[i].name%>')<%if(i < attributes.length - 1 ){%>,<%}%>
      <% } %>
    }

    <%=nameC%>.update(req.param('id'), paramObj, function (err) {
      if (err) {
        sails.log.error(err);

        if(err.ValidationError){

          error_object = validator(<%=nameC%>, err.ValidationError);

          req.flash('error', error_object);

          return res.redirect('/<%=name%>/edit/' + req.param('id'));

        } else {
          return res.serverError();
        }

      } else {
        res.redirect('/<%=name%>/show/' + req.param('id'));
      }
    });
  },

  destroy: function(req, res, next) {

    <%=nameC%>.findOne(req.param('id'), function (err, <%=name%>) {
      if (err) {
        return next(err);
      } else {
        if (!<%=name%>) {
          return res.notFound();
        } else {
          <%=nameC%>.destroy(req.param('id'), function (err) {
            if (err) {
              return next(err);
            } else {
              res.redirect('/<%=name%>');
            }
          });
        }
      }
    });
  }

};

<commit_msg>handle errors on update<commit_after>/**
 * <%=nameC%>Controller
 *
 * @description :: Server-side logic for managing <%=name%>
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {

  add: function(req,res){
    res.view();
  },

  create: function(req, res) {

    var paramObj = {
      <% for(var i in attributes) { %>
        <%=attributes[i].name%> : req.param('<%=attributes[i].name%>')<%if(i < attributes.length - 1 ){%>,<%}%>
      <% } %>
    }

    // Create a <%=nameC%> with the params sent from
    // the sign-up form --> add.ejs
    <%=nameC%>.create(paramObj, function (err, <%=name%>) {

      if (err) {
        sails.log.error(err);

        if(err.ValidationError){

          error_object = validator(<%=nameC%>, err.ValidationError);

          req.flash('error', error_object);

          return res.redirect('/<%=name%>/add');

        } else {
          return res.serverError();
        }

      } else {
        return res.redirect('/<%=name%>/show/' + <%=name%>.id);
      }
    });
  },

  show: function(req, res, next) {
    <%=nameC%>.findOne(req.param('id'), function (err, <%=name%>) {
      if (err) {
        return next(err);
      } else {
        if (!<%=name%>) {
          return res.notFound();
        } else {

          res.view({
            <%=name%>: <%=name%>
          });
        }
      }
    });
  },

  index: function(req, res, next) {
    <%=nameC%>.find(function (err, <%=namePlural%>) {
      if (err) {
        return next(err);
      } else {
        res.view({
          <%=namePlural%>: <%=namePlural%>
        });
      }
    });
  },

  edit: function(req, res, next) {

    <%=nameC%>.findOne(req.param('id'), function (err, <%=name%>) {
      if (err) {
        return next(err);
      } else {
        if (!<%=name%>) {
          return res.notFound();
        } else {
          var paramObj = req.flash('paramObj')
            , obj = (paramObj[0]) ? paramObj[0] : {};

          res.view({
            <%=name%>: _.defaults(obj, <%=name%>)
          });
        }
      }
    });
  },

  update: function(req, res, next) {

    var paramObj = {
      <% for(var i in attributes) { %>
        <%=attributes[i].name%> : req.param('<%=attributes[i].name%>')<%if(i < attributes.length - 1 ){%>,<%}%>
      <% } %>
    }

    <%=nameC%>.update(req.param('id'), paramObj, function (err) {
      if (err) {
        sails.log.error(err);

        if(err.ValidationError){

          error_object = validator(<%=nameC%>, err.ValidationError);

          req.flash('error', error_object);

          req.flash('paramObj', paramObj);

          return res.redirect('/<%=name%>/edit/' + req.param('id'));

        } else {
          return res.serverError();
        }

      } else {
        res.redirect('/<%=name%>/show/' + req.param('id'));
      }
    });
  },

  destroy: function(req, res, next) {

    <%=nameC%>.findOne(req.param('id'), function (err, <%=name%>) {
      if (err) {
        return next(err);
      } else {
        if (!<%=name%>) {
          return res.notFound();
        } else {
          <%=nameC%>.destroy(req.param('id'), function (err) {
            if (err) {
              return next(err);
            } else {
              res.redirect('/<%=name%>');
            }
          });
        }
      }
    });
  }

};

<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

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.
*/

'use strict';

var React = require('react');
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');

module.exports = React.createClass({
    displayName: 'LeftPanel',

    onHideClick: function() {
        dis.dispatch({
            action: 'hide_left_panel',
        });
    },

    render: function() {
        var RoomList = sdk.getComponent('organisms.RoomList');
        var BottomLeftMenu = sdk.getComponent('molecules.BottomLeftMenu');
        var IncomingCallBox = sdk.getComponent('molecules.voip.IncomingCallBox');

        var collapseButton;
        var classes = "mx_LeftPanel";
        if (this.props.collapsed) {
            classes += " collapsed";
        }
        else {
            //collapseButton = <img className="mx_LeftPanel_hideButton" onClick={ this.onHideClick } src="img/hide.png" width="12" height="20" alt="<"/>
        }

        return (

                { collapseButton }
                <IncomingCallBox />
                <RoomList selectedRoom={this.props.selectedRoom} collapsed={this.props.collapsed}/>
                <BottomLeftMenu collapsed={this.props.collapsed}/>

        );
    }
});

<commit_msg>comment for the hidden collapse button<commit_after>/*
Copyright 2015 OpenMarket Ltd

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.
*/

'use strict';

var React = require('react');
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');

module.exports = React.createClass({
    displayName: 'LeftPanel',

    onHideClick: function() {
        dis.dispatch({
            action: 'hide_left_panel',
        });
    },

    render: function() {
        var RoomList = sdk.getComponent('organisms.RoomList');
        var BottomLeftMenu = sdk.getComponent('molecules.BottomLeftMenu');
        var IncomingCallBox = sdk.getComponent('molecules.voip.IncomingCallBox');

        var collapseButton;
        var classes = "mx_LeftPanel";
        if (this.props.collapsed) {
            classes += " collapsed";
        }
        else {
            // Hide the collapse button until we work out how to display it in the new skin
            // collapseButton = <img className="mx_LeftPanel_hideButton" onClick={ this.onHideClick } src="img/hide.png" width="12" height="20" alt="<"/>
        }

        return (

                { collapseButton }
                <IncomingCallBox />
                <RoomList selectedRoom={this.props.selectedRoom} collapsed={this.props.collapsed}/>
                <BottomLeftMenu collapsed={this.props.collapsed}/>

        );
    }
});

<|endoftext|>


<commit_before>/**
 * `modules/analytics` data store: service tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 *
 * Internal dependencies
 */
import {
	createTestRegistry,
	provideUserInfo,
	unsubscribeFromAll,
} from '../../../../../tests/js/utils';
import * as fixtures from './__fixtures__';
import { STORE_NAME } from './constants';

describe( 'module/analytics service store', () => {
	const userData = {
		id: 1,
		email: 'admin@example.com',
		name: 'admin',
		picture: 'https://path/to/image',
	};
	const baseURI = 'https://analytics.google.com/analytics/web/';

	let registry;

	beforeAll( () => {
		registry = createTestRegistry();
		provideUserInfo( registry, userData );
		registry.dispatch( STORE_NAME ).receiveGetSettings( fixtures.settings.default );
	} );

	afterAll( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'selectors', () => {
		describe( 'getServiceURL', () => {
			it( 'retrieves the correct URL with no arguments', async () => {
				const serviceURL = registry.select( STORE_NAME ).getServiceURL();
				expect( serviceURL ).toBe( `${ baseURI }?authuser=${ encodeURIComponent( userData.email ) }` );
			} );

			it( 'adds the path parameter', () => {
				const expectedURL = `${ baseURI }?authuser=${ encodeURIComponent( userData.email ) }#/test/path/to/deeplink`;
				const serviceURLNoSlashes = registry.select( STORE_NAME ).getServiceURL( { path: 'test/path/to/deeplink' } );
				expect( serviceURLNoSlashes ).toEqual( expectedURL );
				const serviceURLWithLeadingSlash = registry.select( STORE_NAME ).getServiceURL( { path: '/test/path/to/deeplink' } );
				expect( serviceURLWithLeadingSlash ).toEqual( expectedURL );
			} );

			it( 'adds query args', async () => {
				const path = '/test/path/to/deeplink';
				const query = {
					authuser: userData.email,
					param1: '1',
					param2: '2',
				};
				const serviceURL = registry.select( STORE_NAME ).getServiceURL( { path, query } );
				expect( serviceURL.startsWith( baseURI ) ).toBe( true );
				expect( serviceURL.endsWith( `#${ path }` ) ).toBe( true );
				expect( serviceURL ).toMatchQueryParameters( query );
			} );
		} );

		describe( 'getServiceReportURL', () => {
			const type = 'test-type';

			it( 'requires a report type', () => {
				expect( () => registry.select( STORE_NAME ).getServiceReportURL() )
					.toThrow( 'type is required' );
			} );

			it( 'returns `undefined` when no accountID is set', () => {
				expect( registry.select( STORE_NAME ).getAccountID() ).toBeFalsy();

				expect( registry.select( STORE_NAME ).getServiceReportURL( type ) ).toBeUndefined();
			} );

			it( 'returns `undefined` when no internalWebPropertyID is set', () => {
				registry.dispatch( STORE_NAME ).setAccountID( '12345' );
				expect( registry.select( STORE_NAME ).getInternalWebPropertyID() ).toBeFalsy();

				expect( registry.select( STORE_NAME ).getServiceReportURL( type ) ).toBeUndefined();
			} );

			it( 'returns `undefined` when no profileID is set', () => {
				registry.dispatch( STORE_NAME ).setAccountID( '12345' );
				registry.dispatch( STORE_NAME ).setInternalWebPropertyID( '34567' );
				expect( registry.select( STORE_NAME ).getProfileID() ).toBeFalsy();

				expect( registry.select( STORE_NAME ).getServiceReportURL( type ) ).toBeUndefined();
			} );

			describe( 'with necessary account data', () => {
				const [ accountID, internalWebPropertyID, profileID ] = [ '12345', '34567', '56789' ];

				beforeEach( () => {
					registry.dispatch( STORE_NAME ).setAccountID( accountID );
					registry.dispatch( STORE_NAME ).setInternalWebPropertyID( internalWebPropertyID );
					registry.dispatch( STORE_NAME ).setProfileID( profileID );
				} );

				it( 'returns a service URL for the given report type for the current account, property, and profile', () => {
					const reportServiceURL = registry.select( STORE_NAME ).getServiceReportURL( type );
					const url = new URL( reportServiceURL );
					expect( reportServiceURL.startsWith( baseURI ) ).toBe( true );
					expect( url.hash ).toBe( `#/report/${ type }/a${ accountID }w${ internalWebPropertyID }p${ profileID }/` );
				} );

				it( 'returns a service URL for the given report type including any extra report-specific arguments', () => {
					const reportArgs = { foo: 'bar' };
					const reportServiceURL = registry.select( STORE_NAME ).getServiceReportURL( type, reportArgs );
					const url = new URL( reportServiceURL );
					expect( reportServiceURL.startsWith( baseURI ) ).toBe( true );
					// For more details about how `reportArgs` are handled, see assets/js/modules/analytics/util/report-args.test.js.
					expect( url.hash ).toBe(
						`#/report/${ type }/a${ accountID }w${ internalWebPropertyID }p${ profileID }/foo%3Dbar/`
					);
				} );
			} );
		} );
	} );
} );
<commit_msg>Fix test for getServiceReportURL escaping.<commit_after>/**
 * `modules/analytics` data store: service tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 *
 * Internal dependencies
 */
import {
	createTestRegistry,
	provideUserInfo,
	unsubscribeFromAll,
} from '../../../../../tests/js/utils';
import * as fixtures from './__fixtures__';
import { STORE_NAME } from './constants';

describe( 'module/analytics service store', () => {
	const userData = {
		id: 1,
		email: 'admin@example.com',
		name: 'admin',
		picture: 'https://path/to/image',
	};
	const baseURI = 'https://analytics.google.com/analytics/web/';

	let registry;

	beforeAll( () => {
		registry = createTestRegistry();
		provideUserInfo( registry, userData );
		registry.dispatch( STORE_NAME ).receiveGetSettings( fixtures.settings.default );
	} );

	afterAll( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'selectors', () => {
		describe( 'getServiceURL', () => {
			it( 'retrieves the correct URL with no arguments', async () => {
				const serviceURL = registry.select( STORE_NAME ).getServiceURL();
				expect( serviceURL ).toBe( `${ baseURI }?authuser=${ encodeURIComponent( userData.email ) }` );
			} );

			it( 'adds the path parameter', () => {
				const expectedURL = `${ baseURI }?authuser=${ encodeURIComponent( userData.email ) }#/test/path/to/deeplink`;
				const serviceURLNoSlashes = registry.select( STORE_NAME ).getServiceURL( { path: 'test/path/to/deeplink' } );
				expect( serviceURLNoSlashes ).toEqual( expectedURL );
				const serviceURLWithLeadingSlash = registry.select( STORE_NAME ).getServiceURL( { path: '/test/path/to/deeplink' } );
				expect( serviceURLWithLeadingSlash ).toEqual( expectedURL );
			} );

			it( 'adds query args', async () => {
				const path = '/test/path/to/deeplink';
				const query = {
					authuser: userData.email,
					param1: '1',
					param2: '2',
				};
				const serviceURL = registry.select( STORE_NAME ).getServiceURL( { path, query } );
				expect( serviceURL.startsWith( baseURI ) ).toBe( true );
				expect( serviceURL.endsWith( `#${ path }` ) ).toBe( true );
				expect( serviceURL ).toMatchQueryParameters( query );
			} );
		} );

		describe( 'getServiceReportURL', () => {
			const type = 'test-type';

			it( 'requires a report type', () => {
				expect( () => registry.select( STORE_NAME ).getServiceReportURL() )
					.toThrow( 'type is required' );
			} );

			it( 'returns `undefined` when no accountID is set', () => {
				expect( registry.select( STORE_NAME ).getAccountID() ).toBeFalsy();

				expect( registry.select( STORE_NAME ).getServiceReportURL( type ) ).toBeUndefined();
			} );

			it( 'returns `undefined` when no internalWebPropertyID is set', () => {
				registry.dispatch( STORE_NAME ).setAccountID( '12345' );
				expect( registry.select( STORE_NAME ).getInternalWebPropertyID() ).toBeFalsy();

				expect( registry.select( STORE_NAME ).getServiceReportURL( type ) ).toBeUndefined();
			} );

			it( 'returns `undefined` when no profileID is set', () => {
				registry.dispatch( STORE_NAME ).setAccountID( '12345' );
				registry.dispatch( STORE_NAME ).setInternalWebPropertyID( '34567' );
				expect( registry.select( STORE_NAME ).getProfileID() ).toBeFalsy();

				expect( registry.select( STORE_NAME ).getServiceReportURL( type ) ).toBeUndefined();
			} );

			describe( 'with necessary account data', () => {
				const [ accountID, internalWebPropertyID, profileID ] = [ '12345', '34567', '56789' ];

				beforeEach( () => {
					registry.dispatch( STORE_NAME ).setAccountID( accountID );
					registry.dispatch( STORE_NAME ).setInternalWebPropertyID( internalWebPropertyID );
					registry.dispatch( STORE_NAME ).setProfileID( profileID );
				} );

				it( 'returns a service URL for the given report type for the current account, property, and profile', () => {
					const reportServiceURL = registry.select( STORE_NAME ).getServiceReportURL( type );
					const url = new URL( reportServiceURL );
					expect( reportServiceURL.startsWith( baseURI ) ).toBe( true );
					expect( url.hash ).toBe( `#/report/${ type }/a${ accountID }w${ internalWebPropertyID }p${ profileID }/` );
				} );

				it( 'returns a service URL for the given report type including any extra report-specific arguments', () => {
					const reportArgs = { foo: 'bar' };
					const reportServiceURL = registry.select( STORE_NAME ).getServiceReportURL( type, reportArgs );
					const url = new URL( reportServiceURL );
					expect( reportServiceURL.startsWith( baseURI ) ).toBe( true );
					// For more details about how `reportArgs` are handled, see assets/js/modules/analytics/util/report-args.test.js.
					expect( url.hash ).toBe(
						`#/report/${ type }/a${ accountID }w${ internalWebPropertyID }p${ profileID }/foo=bar/`
					);
				} );
			} );
		} );
	} );
} );
<|endoftext|>


<commit_before>// __Dependencies__
var RestError = require('rest-error');

// __Private Methods__
function isDefinedAndNotNull (n) {
  if (n === null) return false;
  if (n === undefined) return false;
  return true;
}

function isPositiveInteger (n) {
  if (!isDefinedAndNotNull(n)) return false;
  n = Number(n);
  if (n < 1) return false;
  return n === Math.ceil(n);
}

function isNonNegativeInteger (n) {
  if (!isDefinedAndNotNull(n)) return false;
  n = Number(n);
  if (n < 0) return false;
  return n === Math.ceil(n);
}

// __Module Definition__
var decorator = module.exports = function () {
  var controller = this;

  function checkBadSelection (select) {
    var bad = false;
    controller.deselected().forEach(function (path) {
      var badPath = new RegExp('[+]?' + path + '\\b', 'i');
      if (badPath.exec(select)) bad = true;
    });
    return bad;
  }

  // Perform distinct query.
  this.query(function (request, response, next) {
    var distinct = request.query.distinct;
    if (!distinct) return next();
    if (controller.deselected(distinct)) {
      next(RestError.Forbidden('You may not find distinct values for the requested path'));
      return;
    }
    var query = controller.model().distinct(distinct, request.baucis.conditions);
    query.exec(function (error, values) {
      if (error) return next(error);
      request.baucis.documents = values;
      next();
    });
  });
  // Apply incoming request sort.
  this.query(function (request, response, next) {
    var sort = request.query.sort;
    if (sort) request.baucis.query.sort(sort);
    next();
  });
  // Apply controller select options to the query.
  this.query(function (request, response, next) {
    var select = controller.select();
    if (select) request.baucis.query.select(select);
    next();
  });
  // Apply incoming request select to the query.
  this.query(function (request, response, next) {
    var select = request.query.select;
    if (!select) return next();

    if (select.indexOf('+') !== -1) {
      return next(RestError.Forbidden('Including excluded fields is not permitted'));
    }
    if (checkBadSelection(select)) {
      return next(RestError.Forbidden('Including excluded fields is not permitted'));
    }

    request.baucis.query.select(select);
    next();
  });
  // Apply incoming request populate.
  this.query(function (request, response, next) {
    var populate = request.query.populate;
    var populateSelect = request._populateSelect;
    var error = null;

    if (populate) {
      if (typeof populate === 'string') {
        if (populate.indexOf('{') !== -1) populate = JSON.parse(populate);
        else if (populate.indexOf('[') !== -1) populate = JSON.parse(populate);
      }

      if (!Array.isArray(populate)) populate = [ populate ];

      populate.forEach(function (field) {
        if (error) return;
        if (checkBadSelection(field.path || field)) {
          return error = RestError.Forbidden('Including excluded fields is not permitted');
        }
        // Don't allow selecting fields from client when populating
        if (field.select && !populateSelect) {
          return error = RestError.Forbidden('Selecting fields of populated documents is not permitted');
        }

        request.baucis.query.populate(field);
      });
    }

    next(error);
  });
  // Apply incoming request skip.
  this.query(function (request, response, next) {
    var skip = request.query.skip;
    if (skip === undefined || skip === null) return next();
    if (!isNonNegativeInteger(skip)) {
      return next(RestError.BadRequest('Skip must be a non-negative integer if set'));
    }
    request.baucis.query.skip(skip);
    next();
  });
  // Apply incoming request limit.
  this.query(function (request, response, next) {
    var limit = request.query.limit;
    if (limit === undefined || limit === null) return next();
    if (!isPositiveInteger(limit)) {
      return next(RestError.BadRequest('Limit must be a positive integer if set'));
    }
    request.baucis.query.limit(limit);
    next();
  });
  // Set count flag.
  this.query(function (request, response, next) {
    if (!request.query.count) return next();
    if (request.query.count === 'false') return next();
    if (request.query.count !== 'true') {
      next(RestError.BadRequest('Count must be "true" or "false" if set'));
      return;
    }

    if (request.query.hint) {
      next(RestError.BadRequest('Hint can\'t be used with count'));
      return;
    }

    if (request.query.comment) {
      next(RestError.BadRequest('Comment can\'t be used with count'));
      return;
    }

    request.baucis.count = true;
    next();
  });
  // Check for query comment.
  this.query(function (request, response, next) {
    var comment = request.query.comment;
    if (!comment) return next();
    if (controller.comments()) request.baucis.query.comment(comment);
    else console.warn('Query comment was ignored.');
    next();
  });
  // Check for query hint.
  this.query(function (request, response, next) {
    var hint = request.query.hint;

    if (!hint) return next();
    if (!controller.hints()) {
      return next(RestError.Forbidden('Hints are not enabled for this resource'));
    }

    if (typeof hint === 'string') hint = JSON.parse(hint);
    // Convert the value for each path from stirng to number.
    Object.keys(hint).forEach(function (path) {
      hint[path] = Number(hint[path]);
    });
    request.baucis.query.hint(hint);

    next();
  });
};
<commit_msg>better semantics<commit_after>// __Dependencies__
var RestError = require('rest-error');

// __Private Methods__
function isDefinedAndNotNull (n) {
  if (n === null) return false;
  if (n === undefined) return false;
  return true;
}

function isPositiveInteger (n) {
  if (!isDefinedAndNotNull(n)) return false;
  n = Number(n);
  if (n < 1) return false;
  return n === Math.ceil(n);
}

function isNonNegativeInteger (n) {
  if (!isDefinedAndNotNull(n)) return false;
  n = Number(n);
  if (n < 0) return false;
  return n === Math.ceil(n);
}

// __Module Definition__
var decorator = module.exports = function () {
  var controller = this;

  function checkBadSelection (select) {
    var bad = false;
    controller.deselected().forEach(function (path) {
      var badPath = new RegExp('[+]?' + path + '\\b', 'i');
      if (badPath.exec(select)) bad = true;
    });
    return bad;
  }

  // Perform distinct query.
  this.query(function (request, response, next) {
    var distinct = request.query.distinct;
    if (!distinct) return next();
    if (controller.deselected(distinct)) {
      next(RestError.Forbidden('You may not find distinct values for the requested path'));
      return;
    }
    var query = controller.model().distinct(distinct, request.baucis.conditions);
    query.exec(function (error, values) {
      if (error) return next(error);
      request.baucis.documents = values;
      next();
    });
  });
  // Apply incoming request sort.
  this.query(function (request, response, next) {
    var sort = request.query.sort;
    if (sort) request.baucis.query.sort(sort);
    next();
  });
  // Apply controller select options to the query.
  this.query(function (request, response, next) {
    var select = controller.select();
    if (select) request.baucis.query.select(select);
    next();
  });
  // Apply incoming request select to the query.
  this.query(function (request, response, next) {
    var select = request.query.select;
    if (!select) return next();

    if (select.indexOf('+') !== -1) {
      return next(RestError.Forbidden('Including excluded fields is not permitted'));
    }
    if (checkBadSelection(select)) {
      return next(RestError.Forbidden('Including excluded fields is not permitted'));
    }

    request.baucis.query.select(select);
    next();
  });
  // Apply incoming request populate.
  this.query(function (request, response, next) {
    var populate = request.query.populate;
    var allowPopulateSelect = request.baucis.allowPopulateSelect;
    var error = null;

    if (populate) {
      if (typeof populate === 'string') {
        if (populate.indexOf('{') !== -1) populate = JSON.parse(populate);
        else if (populate.indexOf('[') !== -1) populate = JSON.parse(populate);
      }

      if (!Array.isArray(populate)) populate = [ populate ];

      populate.forEach(function (field) {
        if (error) return;
        if (checkBadSelection(field.path || field)) {
          return error = RestError.Forbidden('Including excluded fields is not permitted');
        }
        // Don't allow selecting fields from client when populating
        if (field.select && !allowPopulateSelect) {
          return error = RestError.Forbidden('Selecting fields of populated documents is not permitted');
        }

        request.baucis.query.populate(field);
      });
    }

    next(error);
  });
  // Apply incoming request skip.
  this.query(function (request, response, next) {
    var skip = request.query.skip;
    if (skip === undefined || skip === null) return next();
    if (!isNonNegativeInteger(skip)) {
      return next(RestError.BadRequest('Skip must be a non-negative integer if set'));
    }
    request.baucis.query.skip(skip);
    next();
  });
  // Apply incoming request limit.
  this.query(function (request, response, next) {
    var limit = request.query.limit;
    if (limit === undefined || limit === null) return next();
    if (!isPositiveInteger(limit)) {
      return next(RestError.BadRequest('Limit must be a positive integer if set'));
    }
    request.baucis.query.limit(limit);
    next();
  });
  // Set count flag.
  this.query(function (request, response, next) {
    if (!request.query.count) return next();
    if (request.query.count === 'false') return next();
    if (request.query.count !== 'true') {
      next(RestError.BadRequest('Count must be "true" or "false" if set'));
      return;
    }

    if (request.query.hint) {
      next(RestError.BadRequest('Hint can\'t be used with count'));
      return;
    }

    if (request.query.comment) {
      next(RestError.BadRequest('Comment can\'t be used with count'));
      return;
    }

    request.baucis.count = true;
    next();
  });
  // Check for query comment.
  this.query(function (request, response, next) {
    var comment = request.query.comment;
    if (!comment) return next();
    if (controller.comments()) request.baucis.query.comment(comment);
    else console.warn('Query comment was ignored.');
    next();
  });
  // Check for query hint.
  this.query(function (request, response, next) {
    var hint = request.query.hint;

    if (!hint) return next();
    if (!controller.hints()) {
      return next(RestError.Forbidden('Hints are not enabled for this resource'));
    }

    if (typeof hint === 'string') hint = JSON.parse(hint);
    // Convert the value for each path from stirng to number.
    Object.keys(hint).forEach(function (path) {
      hint[path] = Number(hint[path]);
    });
    request.baucis.query.hint(hint);

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


<commit_before>/**
This is a collection of javascript functions and whatnot
under the spree namespace that do stuff we find helpful.
Hopefully, this will evolve into a propper class.
**/

jQuery(function($) {

  // Add some tips
  $('.with-tip').tooltip();

  $('.js-show-index-filters').click(function(){
    $(".filter-well").slideToggle();
    $(this).parents(".filter-wrap").toggleClass("collapsed");
    $("span.icon", $(this)).toggleClass("icon-chevron-down");
  });

  $(".js-collapse-sidebar").click(function(){
    $(".main-right-sidebar").toggleClass("collapsed");
    $("section.content").toggleClass("sidebar-collapsed");
    $("span.icon", $(this)).toggleClass("icon-chevron-right");
    $("span.icon", $(this)).toggleClass("icon-chevron-left");
  });

  $('#main-sidebar').find('[data-toggle="collapse"]').on('click', function()
    {
      if($(this).find('.icon-chevron-left').length == 1){
        $(this).find('.icon-chevron-left').removeClass('icon-chevron-left').addClass('icon-chevron-down');
      }
      else {
        $(this).find('.icon-chevron-down').removeClass('icon-chevron-down').addClass('icon-chevron-left');
      }
    }
  )

  // Sidebar nav toggle functionality
  var sidebar_toggle = $('#sidebar-toggle');

  sidebar_toggle.on('click', function(){
    var wrapper = $('#wrapper');
    var main    = $('#main-part');

    if(wrapper.hasClass('sidebar-minimized')){
      wrapper.removeClass('sidebar-minimized');
      main
        .removeClass('col-sm-12 col-md-12 sidebar-collapsed')
        .addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
      $.cookie('sidebar-minimized', 'false', { path: '/admin' });
    }
    else {
      wrapper.addClass('sidebar-minimized');
      main
        .removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2')
        .addClass('col-sm-12 col-md-12 sidebar-collapsed');
      $.cookie('sidebar-minimized', 'true', { path: '/admin' });
    }
  });

  $('.sidebar-menu-item').mouseover(function(){
    if($('#wrapper').hasClass('sidebar-minimized')){
      $(this).addClass('menu-active');
      $(this).find('ul.nav').addClass('submenu-active');
    }
  });
  $('.sidebar-menu-item').mouseout(function(){
    if($('#wrapper').hasClass('sidebar-minimized')){
      $(this).removeClass('menu-active');
      $(this).find('ul.nav').removeClass('submenu-active');
    }
  });

  // TODO: remove this js temp behaviour and fix this decent
  // Temp quick search
  // When there was a search term, copy it
  $(".js-quick-search").val($(".js-quick-search-target").val());
  // Catch the quick search form submit and submit the real form
  $("#quick-search").submit(function(){
    $(".js-quick-search-target").val($(".js-quick-search").val());
    $("#table-filter form").submit();
    return false;
  });

  // Main menu active item submenu show
  var active_item = $('#sidebar').find('.selected');
  active_item.parent().addClass('in');
  active_item.parent().prev()
    .find('.icon-chevron-left')
    .removeClass('icon-chevron-left')
    .addClass('icon-chevron-down');

  // Replace ▼ and ▲ in sort_link with nicer icons
  $(".sort_link").each(function(){
    // Remove the   in the text
    var sort_link_text = $(this).text().replace('\xA0', '');

    if(sort_link_text.indexOf("▼") >= 0){
      $(this).text(sort_link_text.replace("▼",""));
      $(this).append('');
    } else if(sort_link_text.indexOf("▲") >= 0){
      $(this).text(sort_link_text.replace("▲",""));
      $(this).append('');
    }
  });

  // Clickable ransack filters
  $(".js-add-filter").click(function() {
    var ransack_field = $(this).data("ransack-field");
    var ransack_value = $(this).data("ransack-value");

    $("#" + ransack_field).val(ransack_value);
    $("#table-filter form").submit();
  });

  $(document).on("click", ".js-delete-filter", function() {
    var ransack_field = $(this).parents(".js-filter").data("ransack-field");

    $("#" + ransack_field).val('');
    $("#table-filter form").submit();
  });

  $(".js-filterable").each(function() {
    var $this = $(this);

    if ($this.val()) {
      var ransack_value, filter;
      var ransack_field = $this.attr("id");
      var label = $('label[for="' + ransack_field + '"]');

      if ($this.is("select")) {
        ransack_value = $this.find('option:selected').text();
      } else {
        ransack_value = $this.val();
      }

      label = label.text() + ': ' + ransack_value;
      filter = '' + label + '';

      $(".js-filters").append(filter).show();
    }
  });

  // per page dropdown
  // preserves all selected filters / queries supplied by user
  // changes only per_page value
  $(".js-per-page-select").change(function() {
    var form  = $(this).closest(".js-per-page-form");
    var url   = form.attr('action');
    var value = $(this).val().toString();
    if (url.match(/\?/)) {
      url += "&per_page=" + value;
    } else {
      url += "?per_page=" + value;
    }
    window.location = url;
  });

  // injects per_page settings to all available search forms
  // so when user changes some filters / queries per_page is preserved
  $(document).ready(function() {
    var perPageDropdown = $(".js-per-page-select:first");
    if (perPageDropdown.length) {
      var perPageValue = perPageDropdown.val().toString();
      var perPageInput = '<input type="hidden" name="per_page" value=' + perPageValue + ' />';
      $("#table-filter form").append(perPageInput);
    }
  });

  // Enable sidebar toggle
  $("[data-toggle='offcanvas']").click(function(e) {
    e.preventDefault();

    // If window is small enough, enable sidebar push menu
    if ($(window).width() <= 992) {
      $('.row-offcanvas').toggleClass('active');
      $('.left-side').removeClass("collapse-left");
      $(".right-side").removeClass("strech");
      $('.row-offcanvas').toggleClass("relative");
    } else {
      // Else, enable content streching
      $('.left-side').toggleClass("collapse-left");
      $(".right-side").toggleClass("strech");
    }
  });

  // Make flash messages disappear
  setTimeout('$(".alert-auto-disappear").slideUp()', 5000);

});

$.fn.visible = function(cond) { this[cond ? 'show' : 'hide' ]() };

show_flash = function(type, message) {
  var flash_div = $('.flash.' + type);
  if (flash_div.length == 0) {
    flash_div = $('
');
    $('#content').prepend(flash_div);
  }
  flash_div.html(message).show().delay(10000).slideUp();
}

// Apply to individual radio button that makes another element visible when checked
$.fn.radioControlsVisibilityOfElement = function(dependentElementSelector){
  if(!this.get(0)){ return  }
  showValue = this.get(0).value;
  radioGroup = $("input[name='" + this.get(0).name + "']");
  radioGroup.each(function(){
    $(this).click(function(){
      $(dependentElementSelector).visible(this.checked && this.value == showValue)
    });
    if(this.checked){ this.click() }
  });
}

handle_date_picker_fields = function(){
  $('.datepicker').datepicker({
    dateFormat: Spree.translations.date_picker,
    dayNames: Spree.translations.abbr_day_names,
    dayNamesMin: Spree.translations.abbr_day_names,
    firstDay: Spree.translations.first_day,
    monthNames: Spree.translations.month_names,
    prevText: Spree.translations.previous,
    nextText: Spree.translations.next,
    showOn: "focus"
  });

  // Correctly display range dates
  $('.date-range-filter .datepicker-from').datepicker('option', 'onSelect', function(selectedDate) {
    $(".date-range-filter .datepicker-to" ).datepicker( "option", "minDate", selectedDate );
  });
  $('.date-range-filter .datepicker-to').datepicker('option', 'onSelect', function(selectedDate) {
    $(".date-range-filter .datepicker-from" ).datepicker( "option", "maxDate", selectedDate );
  });
}

$(document).ready(function(){
  handle_date_picker_fields();
  $(".observe_field").on('change', function() {
    target = $(this).data("update");
    $(target).hide();
    $.ajax({ dataType: 'html',
             url: $(this).data("base-url")+encodeURIComponent($(this).val()),
             type: 'get',
             success: function(data){
               $(target).html(data);
               $(target).show();
             }
    });
  });

  var uniqueId = 1;
  $('.spree_add_fields').click(function() {
    var target = $(this).data("target");
    var new_table_row = $(target + ' tr:visible:last').clone();
    var new_id = new Date().getTime() + (uniqueId++);
    new_table_row.find("input, select").each(function () {
      var el = $(this);
      el.val("");
      el.prop("id", el.prop("id").replace(/\d+/, new_id))
      el.prop("name", el.prop("name").replace(/\d+/, new_id))
    })
    // When cloning a new row, set the href of all icons to be an empty "#"
    // This is so that clicking on them does not perform the actions for the
    // duplicated row
    new_table_row.find("a").each(function () {
      var el = $(this);
      el.prop('href', '#');
    })
    $(target).prepend(new_table_row);
  })

  $('body').on('click', '.delete-resource', function() {
    var el = $(this);
    if (confirm(el.data("confirm"))) {
      $.ajax({
        type: 'POST',
        url: $(this).prop("href"),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        dataType: 'script',
        success: function(response) {
          el.parents("tr").fadeOut('hide', function() {
            $(this).remove();
          });
        },
        error: function(response, textStatus, errorThrown) {
          show_flash('error', response.responseText);
        }
      });
    }
    return false;
  });

  $('body').on('click', 'a.spree_remove_fields', function() {
    el = $(this);
    el.prev("input[type=hidden]").val("1");
    el.closest(".fields").hide();
    if (el.prop("href").substr(-1) == '#') {
      el.parents("tr").fadeOut('hide');
    }else if (el.prop("href")) {
      $.ajax({
        type: 'POST',
        url: el.prop("href"),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        success: function(response) {
          el.parents("tr").fadeOut('hide');
        },
        error: function(response, textStatus, errorThrown) {
          show_flash('error', response.responseText);
        }

      })
    }
    return false;
  });

  $('body').on('click', '.select_properties_from_prototype', function(){
    $("#busy_indicator").show();
    var clicked_link = $(this);
    $.ajax({ dataType: 'script', url: clicked_link.prop("href"), type: 'get',
        success: function(data){
          clicked_link.parent("td").parent("tr").hide();
          $("#busy_indicator").hide();
        }
    });
    return false;
  });

  // Fix sortable helper
  var fixHelper = function(e, ui) {
      ui.children().each(function() {
          $(this).width($(this).width());
      });
      return ui;
  };

  $('table.sortable').ready(function(){
    var td_count = $(this).find('tbody tr:first-child td').length
    $('table.sortable tbody').sortable(
      {
        handle: '.handle',
        helper: fixHelper,
        placeholder: 'ui-sortable-placeholder',
        update: function(event, ui) {
          $("#progress").show();
          positions = {};
          $.each($('table.sortable tbody tr'), function(position, obj){
            reg = /spree_(\w+_?)+_(\d+)/;
            parts = reg.exec($(obj).prop('id'));
            if (parts) {
              positions['positions['+parts[2]+']'] = position;
            }
          });
          $.ajax({
            type: 'POST',
            dataType: 'script',
            url: $(ui.item).closest("table.sortable").data("sortable-link"),
            data: positions,
            success: function(data){ $("#progress").hide(); }
          });
        },
        start: function (event, ui) {
          // Set correct height for placehoder (from dragged tr)
          ui.placeholder.height(ui.item.height())
          // Fix placeholder content to make it correct width
          ui.placeholder.html("		")
        },
        stop: function (event, ui) {
          // Fix odd/even classes after reorder
          $("table.sortable tr:even").removeClass("odd even").addClass("even");
          $("table.sortable tr:odd").removeClass("odd even").addClass("odd");
        }

      });
  });

  $('a.dismiss').click(function() {
    $(this).parent().fadeOut();
  });

  window.Spree.advanceOrder = function() {
      $.ajax({
          type: "PUT",
          async: false,
          data: {
            token: Spree.api_key
          },
          url: Spree.url(Spree.routes.checkouts_api + "/" + order_number + "/advance")
      }).done(function() {
          window.location.reload();
      });
  }
});
<commit_msg>Fix multiple flash messages issue, Fetch flash div using alert class selector instead of flash<commit_after>/**
This is a collection of javascript functions and whatnot
under the spree namespace that do stuff we find helpful.
Hopefully, this will evolve into a propper class.
**/

jQuery(function($) {

  // Add some tips
  $('.with-tip').tooltip();

  $('.js-show-index-filters').click(function(){
    $(".filter-well").slideToggle();
    $(this).parents(".filter-wrap").toggleClass("collapsed");
    $("span.icon", $(this)).toggleClass("icon-chevron-down");
  });

  $(".js-collapse-sidebar").click(function(){
    $(".main-right-sidebar").toggleClass("collapsed");
    $("section.content").toggleClass("sidebar-collapsed");
    $("span.icon", $(this)).toggleClass("icon-chevron-right");
    $("span.icon", $(this)).toggleClass("icon-chevron-left");
  });

  $('#main-sidebar').find('[data-toggle="collapse"]').on('click', function()
    {
      if($(this).find('.icon-chevron-left').length == 1){
        $(this).find('.icon-chevron-left').removeClass('icon-chevron-left').addClass('icon-chevron-down');
      }
      else {
        $(this).find('.icon-chevron-down').removeClass('icon-chevron-down').addClass('icon-chevron-left');
      }
    }
  )

  // Sidebar nav toggle functionality
  var sidebar_toggle = $('#sidebar-toggle');

  sidebar_toggle.on('click', function(){
    var wrapper = $('#wrapper');
    var main    = $('#main-part');

    if(wrapper.hasClass('sidebar-minimized')){
      wrapper.removeClass('sidebar-minimized');
      main
        .removeClass('col-sm-12 col-md-12 sidebar-collapsed')
        .addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
      $.cookie('sidebar-minimized', 'false', { path: '/admin' });
    }
    else {
      wrapper.addClass('sidebar-minimized');
      main
        .removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2')
        .addClass('col-sm-12 col-md-12 sidebar-collapsed');
      $.cookie('sidebar-minimized', 'true', { path: '/admin' });
    }
  });

  $('.sidebar-menu-item').mouseover(function(){
    if($('#wrapper').hasClass('sidebar-minimized')){
      $(this).addClass('menu-active');
      $(this).find('ul.nav').addClass('submenu-active');
    }
  });
  $('.sidebar-menu-item').mouseout(function(){
    if($('#wrapper').hasClass('sidebar-minimized')){
      $(this).removeClass('menu-active');
      $(this).find('ul.nav').removeClass('submenu-active');
    }
  });

  // TODO: remove this js temp behaviour and fix this decent
  // Temp quick search
  // When there was a search term, copy it
  $(".js-quick-search").val($(".js-quick-search-target").val());
  // Catch the quick search form submit and submit the real form
  $("#quick-search").submit(function(){
    $(".js-quick-search-target").val($(".js-quick-search").val());
    $("#table-filter form").submit();
    return false;
  });

  // Main menu active item submenu show
  var active_item = $('#sidebar').find('.selected');
  active_item.parent().addClass('in');
  active_item.parent().prev()
    .find('.icon-chevron-left')
    .removeClass('icon-chevron-left')
    .addClass('icon-chevron-down');

  // Replace ▼ and ▲ in sort_link with nicer icons
  $(".sort_link").each(function(){
    // Remove the   in the text
    var sort_link_text = $(this).text().replace('\xA0', '');

    if(sort_link_text.indexOf("▼") >= 0){
      $(this).text(sort_link_text.replace("▼",""));
      $(this).append('');
    } else if(sort_link_text.indexOf("▲") >= 0){
      $(this).text(sort_link_text.replace("▲",""));
      $(this).append('');
    }
  });

  // Clickable ransack filters
  $(".js-add-filter").click(function() {
    var ransack_field = $(this).data("ransack-field");
    var ransack_value = $(this).data("ransack-value");

    $("#" + ransack_field).val(ransack_value);
    $("#table-filter form").submit();
  });

  $(document).on("click", ".js-delete-filter", function() {
    var ransack_field = $(this).parents(".js-filter").data("ransack-field");

    $("#" + ransack_field).val('');
    $("#table-filter form").submit();
  });

  $(".js-filterable").each(function() {
    var $this = $(this);

    if ($this.val()) {
      var ransack_value, filter;
      var ransack_field = $this.attr("id");
      var label = $('label[for="' + ransack_field + '"]');

      if ($this.is("select")) {
        ransack_value = $this.find('option:selected').text();
      } else {
        ransack_value = $this.val();
      }

      label = label.text() + ': ' + ransack_value;
      filter = '' + label + '';

      $(".js-filters").append(filter).show();
    }
  });

  // per page dropdown
  // preserves all selected filters / queries supplied by user
  // changes only per_page value
  $(".js-per-page-select").change(function() {
    var form  = $(this).closest(".js-per-page-form");
    var url   = form.attr('action');
    var value = $(this).val().toString();
    if (url.match(/\?/)) {
      url += "&per_page=" + value;
    } else {
      url += "?per_page=" + value;
    }
    window.location = url;
  });

  // injects per_page settings to all available search forms
  // so when user changes some filters / queries per_page is preserved
  $(document).ready(function() {
    var perPageDropdown = $(".js-per-page-select:first");
    if (perPageDropdown.length) {
      var perPageValue = perPageDropdown.val().toString();
      var perPageInput = '<input type="hidden" name="per_page" value=' + perPageValue + ' />';
      $("#table-filter form").append(perPageInput);
    }
  });

  // Enable sidebar toggle
  $("[data-toggle='offcanvas']").click(function(e) {
    e.preventDefault();

    // If window is small enough, enable sidebar push menu
    if ($(window).width() <= 992) {
      $('.row-offcanvas').toggleClass('active');
      $('.left-side').removeClass("collapse-left");
      $(".right-side").removeClass("strech");
      $('.row-offcanvas').toggleClass("relative");
    } else {
      // Else, enable content streching
      $('.left-side').toggleClass("collapse-left");
      $(".right-side").toggleClass("strech");
    }
  });

  // Make flash messages disappear
  setTimeout('$(".alert-auto-disappear").slideUp()', 5000);

});

$.fn.visible = function(cond) { this[cond ? 'show' : 'hide' ]() };

show_flash = function(type, message) {
  var flash_div = $('.alert-' + type);
  if (flash_div.length == 0) {
    flash_div = $('
');
    $('#content').prepend(flash_div);
  }
  flash_div.html(message).show().delay(10000).slideUp();
}

// Apply to individual radio button that makes another element visible when checked
$.fn.radioControlsVisibilityOfElement = function(dependentElementSelector){
  if(!this.get(0)){ return  }
  showValue = this.get(0).value;
  radioGroup = $("input[name='" + this.get(0).name + "']");
  radioGroup.each(function(){
    $(this).click(function(){
      $(dependentElementSelector).visible(this.checked && this.value == showValue)
    });
    if(this.checked){ this.click() }
  });
}

handle_date_picker_fields = function(){
  $('.datepicker').datepicker({
    dateFormat: Spree.translations.date_picker,
    dayNames: Spree.translations.abbr_day_names,
    dayNamesMin: Spree.translations.abbr_day_names,
    firstDay: Spree.translations.first_day,
    monthNames: Spree.translations.month_names,
    prevText: Spree.translations.previous,
    nextText: Spree.translations.next,
    showOn: "focus"
  });

  // Correctly display range dates
  $('.date-range-filter .datepicker-from').datepicker('option', 'onSelect', function(selectedDate) {
    $(".date-range-filter .datepicker-to" ).datepicker( "option", "minDate", selectedDate );
  });
  $('.date-range-filter .datepicker-to').datepicker('option', 'onSelect', function(selectedDate) {
    $(".date-range-filter .datepicker-from" ).datepicker( "option", "maxDate", selectedDate );
  });
}

$(document).ready(function(){
  handle_date_picker_fields();
  $(".observe_field").on('change', function() {
    target = $(this).data("update");
    $(target).hide();
    $.ajax({ dataType: 'html',
             url: $(this).data("base-url")+encodeURIComponent($(this).val()),
             type: 'get',
             success: function(data){
               $(target).html(data);
               $(target).show();
             }
    });
  });

  var uniqueId = 1;
  $('.spree_add_fields').click(function() {
    var target = $(this).data("target");
    var new_table_row = $(target + ' tr:visible:last').clone();
    var new_id = new Date().getTime() + (uniqueId++);
    new_table_row.find("input, select").each(function () {
      var el = $(this);
      el.val("");
      el.prop("id", el.prop("id").replace(/\d+/, new_id))
      el.prop("name", el.prop("name").replace(/\d+/, new_id))
    })
    // When cloning a new row, set the href of all icons to be an empty "#"
    // This is so that clicking on them does not perform the actions for the
    // duplicated row
    new_table_row.find("a").each(function () {
      var el = $(this);
      el.prop('href', '#');
    })
    $(target).prepend(new_table_row);
  })

  $('body').on('click', '.delete-resource', function() {
    var el = $(this);
    if (confirm(el.data("confirm"))) {
      $.ajax({
        type: 'POST',
        url: $(this).prop("href"),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        dataType: 'script',
        success: function(response) {
          el.parents("tr").fadeOut('hide', function() {
            $(this).remove();
          });
        },
        error: function(response, textStatus, errorThrown) {
          show_flash('error', response.responseText);
        }
      });
    }
    return false;
  });

  $('body').on('click', 'a.spree_remove_fields', function() {
    el = $(this);
    el.prev("input[type=hidden]").val("1");
    el.closest(".fields").hide();
    if (el.prop("href").substr(-1) == '#') {
      el.parents("tr").fadeOut('hide');
    }else if (el.prop("href")) {
      $.ajax({
        type: 'POST',
        url: el.prop("href"),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        success: function(response) {
          el.parents("tr").fadeOut('hide');
        },
        error: function(response, textStatus, errorThrown) {
          show_flash('error', response.responseText);
        }

      })
    }
    return false;
  });

  $('body').on('click', '.select_properties_from_prototype', function(){
    $("#busy_indicator").show();
    var clicked_link = $(this);
    $.ajax({ dataType: 'script', url: clicked_link.prop("href"), type: 'get',
        success: function(data){
          clicked_link.parent("td").parent("tr").hide();
          $("#busy_indicator").hide();
        }
    });
    return false;
  });

  // Fix sortable helper
  var fixHelper = function(e, ui) {
      ui.children().each(function() {
          $(this).width($(this).width());
      });
      return ui;
  };

  $('table.sortable').ready(function(){
    var td_count = $(this).find('tbody tr:first-child td').length
    $('table.sortable tbody').sortable(
      {
        handle: '.handle',
        helper: fixHelper,
        placeholder: 'ui-sortable-placeholder',
        update: function(event, ui) {
          $("#progress").show();
          positions = {};
          $.each($('table.sortable tbody tr'), function(position, obj){
            reg = /spree_(\w+_?)+_(\d+)/;
            parts = reg.exec($(obj).prop('id'));
            if (parts) {
              positions['positions['+parts[2]+']'] = position;
            }
          });
          $.ajax({
            type: 'POST',
            dataType: 'script',
            url: $(ui.item).closest("table.sortable").data("sortable-link"),
            data: positions,
            success: function(data){ $("#progress").hide(); }
          });
        },
        start: function (event, ui) {
          // Set correct height for placehoder (from dragged tr)
          ui.placeholder.height(ui.item.height())
          // Fix placeholder content to make it correct width
          ui.placeholder.html("		")
        },
        stop: function (event, ui) {
          // Fix odd/even classes after reorder
          $("table.sortable tr:even").removeClass("odd even").addClass("even");
          $("table.sortable tr:odd").removeClass("odd even").addClass("odd");
        }

      });
  });

  $('a.dismiss').click(function() {
    $(this).parent().fadeOut();
  });

  window.Spree.advanceOrder = function() {
      $.ajax({
          type: "PUT",
          async: false,
          data: {
            token: Spree.api_key
          },
          url: Spree.url(Spree.routes.checkouts_api + "/" + order_number + "/advance")
      }).done(function() {
          window.location.reload();
      });
  }
});
<|endoftext|>


<commit_before>/* global jasmine */
/* global expect */

define([
	'squire',
	"backbone",
	"sinon"
], function (Squire, Backbone, sinon) {
	describe("Router", function () {
		var Router, fetchSpy, homeViewInitializeSpy;
		beforeEach(function (done) {
			fetchSpy = jasmine.createSpy('fetchSpy');
			homeViewInitializeSpy = jasmine.createSpy('homeViewInitializeSpy');
			var injector = new Squire();
			injector.mock('collections/ModelCollection', Backbone.Collection.extend({
				fetch : fetchSpy
			}));
			injector.mock('views/HomeView', Backbone.View.extend({
				initialize : homeViewInitializeSpy
			}));
			injector.require(['controller/AppRouter'], function(router) {
				Router = router;
				done();
			});
		});
		it('Expects a modelCollection to have been created and fetched', function() {
			var router = new Router();
			expect(router.modelCollection).toBeDefined();
			expect(fetchSpy).toHaveBeenCalled();
		});

		// This broked when I added squire. Not sure how to fix
		xdescribe('Tests to see if the correct routes are taken', function() {
			var router;
			beforeEach(function() {
				router = new Router();

				try {
					Backbone.history.start({silent : true});
				} catch (e) {
				}
				router.navigate("elsewhere");

			});

			it("does not fire for unknown paths", function () {
				router.navigate("unknown", {trigger : true});
				expect(homeViewInitializeSpy).not.toHaveBeenCalled();
			});

			it("fires the default root with a blank hash", function () {
				router.navigate("", {trigger : true});
				expect(homeViewInitializeSpy.calls.count()).toEqual(1);
				expect(homeViewInitializeSpy.calls.argsFor(1)).toEqual([{collection : router.modelCollection}]);
			});
		});
	});
});<commit_msg>Added tests for handling errors when fetching the metadata.<commit_after>/* global jasmine */
/* global expect */

define([
	'squire',
	"backbone",
	"sinon",
	'jquery'
], function (Squire, Backbone, sinon, $) {
	describe("Router", function () {
		var Router, fetchSpy, homeViewInitializeSpy, modelDisplayViewInitializeSpy;
		var fetchDeferred;
		beforeEach(function (done) {
			fetchDeferred = $.Deferred();
			fetchSpy = jasmine.createSpy('fetchSpy').and.returnValue(fetchDeferred);
			homeViewInitializeSpy = jasmine.createSpy('homeViewInitializeSpy');
			modelDisplayViewInitializeSpy = jasmine.createSpy('modelDisplayViewInitializeSpy');
			var injector = new Squire();
			injector.mock('collections/ModelCollection', Backbone.Collection.extend({
				fetch : fetchSpy
			}));
			injector.mock('views/HomeView', Backbone.View.extend({
				initialize : homeViewInitializeSpy
			}));
			injector.mock('views/ModelDisplayView', Backbone.View.extend({
				initialize : modelDisplayViewInitializeSpy
			}));
			injector.require(['controller/AppRouter'], function(router) {
				Router = router;
				done();
			});
		});
		it('Expects a modelCollection to have been created and fetched', function() {
			var router = new Router();
			expect(router.modelCollection).toBeDefined();
			expect(fetchSpy).toHaveBeenCalled();
		});
		it('Expects a failed call to fetch to call the errorView', function() {
			var router = new Router();
			spyOn(router, 'errorView');
			fetchDeferred.reject();
			expect(router.errorView).toHaveBeenCalled();
		});
		it('Expects a successful call but no models in the model collection to call the errorView', function() {
			var router = new Router();
			spyOn(router, 'errorView');
			fetchDeferred.resolve();
			expect(router.errorView).toHaveBeenCalled();
		});
		it('Expects a successful call with models in the model collection not call the errorView', function() {
			var router = new Router();
			spyOn(router, 'errorView');
			router.modelCollection.add([new Backbone.Model()]);
			fetchDeferred.resolve();
			expect(router.errorView).not.toHaveBeenCalled();
		});

		// This broked when I added squire. Not sure how to fix
		xdescribe('Tests to see if the correct routes are taken', function() {
			var router;
			beforeEach(function() {
				router = new Router();

				try {
					Backbone.history.start({silent : true});
				} catch (e) {
				}
				router.navigate("elsewhere");

			});

			it("does not fire for unknown paths", function () {
				router.navigate("unknown", {trigger : true});
				expect(homeViewInitializeSpy).not.toHaveBeenCalled();
			});

			it("fires the default root with a blank hash", function () {
				router.navigate("", {trigger : true});
				expect(homeViewInitializeSpy.calls.count()).toEqual(1);
				expect(homeViewInitializeSpy.calls.argsFor(1)).toEqual([{collection : router.modelCollection}]);
			});
		});
	});
});<|endoftext|>


<commit_before>/*
 *  Open Source Routing Machine (OSRM) - Web (GUI) Interface
 *	Copyright (C) Pascal Neis, 2011
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU AFFERO General Public License as published by
 *	the Free Software Foundation; either version 3 of the License, or
 *	any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *	or see http://www.gnu.org/licenses/agpl.txt.
 */

/**
 * Title: Geocode.js
 * Description: JS file for geocoding
 *
 * @author Pascal Neis, pascal@neis-one.org
 * @version 0.1 2011-05-15
 */

//======================
// OBJECTS
var HOST_GEOCODE_URL = 'http://open.mapquestapi.com';
var GEOCODE_POST = HOST_GEOCODE_URL + '/nominatim/v1/search?format=json&json_callback=showResultsGeocode';
var searchType = 'search';

var isStartPointSet = false;
var isEndPointSet = false;

//======================
// FUNCTIONS
/*
 * geocodeAddress()-Function to read out textfield and send request to a OSM nominatim geocoder
 */
function geocodeAddress(tf){
	var freeform;

	if(tf == 'start'){
		freeform = document.getElementById('tfStartSearch').value;
	}
	if(tf == 'end'){
		freeform = document.getElementById('tfEndSearch').value;
	}

	if(freeform.match(/^\s*[-+]?[0-9]*\.?[0-9]+\s*,\s*[-+]?[0-9]*\.?[0-9]+\s*$/)){

		var marker;
		if(tf == 'start'){
			isStartPointSet = true;
			marker = 'start';
		}
		if(tf == 'end'){
			isEndPointSet = true;
			marker = 'end';
		}
		var coord = freeform.split(",");
                lonlat = new OpenLayers.LonLat(coord[1],coord[0]);
                setMarkerAndZoom(marker, lonlat);
                return;
	}

	document.getElementById('information').style.visibility = 'visible';
	document.getElementById('information').innerHTML =  '
One moment please ...
';

    var newURL = GEOCODE_POST + "&q="+freeform;
	var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = newURL;
    document.body.appendChild(script);
}

/*
 * showResultsGeocode()-Function to show the geocode result in a div
 */
function showResultsGeocode(response) {
    var html = '';
    var lonlat = '';

	if(response){
		html += '
Search Results:
';
		html += '
'
		var markername;
		if(getStatus()=='start'){
			markername = 'start'; isStartPointSet = true;
		}
		else if(getStatus()=='end'){
			markername = 'end';	isEndPointSet = true;
		}

		for(var i=0; i < response.length; i++){
			var result = response[i]; var resultNum = i+1;
        	//odd or even ?
        	var rowstyle='geocodeResultOdd';
        	if(i%2==0){ rowstyle='geocodeResultEven'; }

			html += '
';
			html += ''+resultNum+'	';
			html += '';
			if(result.display_name){
				var new_display_name = result.display_name;//.replace(/,/g, ",
")
				html += ''+new_display_name.trim()+'';
			}
			html += "
";

			//alert(result.lat + ", " + result.lon);
			if(lonlat == ''){
				lonlat = new OpenLayers.LonLat(result.lon,result.lat);
			}
		}
		html += '
';

		setMarkerAndZoom(markername, lonlat);
	}

    switch (searchType) {
		case "search":
			document.getElementById('information').style.display = "";
			document.getElementById('information').innerHTML = html;
			break;
	}
}

/*
 * setMarkerAndZoom()-Function to set a marker on the map and zoom
 */
function setMarkerAndZoom(markername,lonlat){
	setMarker(markername,lonlat);

	//Hack - FIXME !
	lonlat.lon -= 500;
	//Set Center
	map.setCenter(lonlat, 15);
}

/*
 * setMarker()-Function to set a marker on the map
 */
function setMarker(markername,lonlat){
	lonlat.transform(EPSG_4326, EPSG_900913);
	for(var i= 0; i<dragLayer.features.length; i++){
		if(dragLayer.features[i].name == markername){ dragLayer.removeFeatures([dragLayer.features[i]]); }
	}
	var point = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat));
	point.attributes = { icon: "img/start.png" };

	if(markername == 'start'){
		point.attributes = { icon: "img/start.png" };
	}
	else if(markername == 'end'){
		point.attributes = { icon: "img/end.png" };
	}

	point.name = markername;
	dragLayer.addFeatures([point]);
}

/*
 * getMarkerByName()-Function to return the marker-object by a name
 */
function getMarkerByName(markerName){
	for(var i= 0; i<dragLayer.features.length; i++){
		if(dragLayer.features[i].name == markerName){
			return dragLayer.features[i];
		}
	}
}
<commit_msg>support coordinates as start/end point: also accept semicolon as separator<commit_after>/*
 *  Open Source Routing Machine (OSRM) - Web (GUI) Interface
 *	Copyright (C) Pascal Neis, 2011
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU AFFERO General Public License as published by
 *	the Free Software Foundation; either version 3 of the License, or
 *	any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *	or see http://www.gnu.org/licenses/agpl.txt.
 */

/**
 * Title: Geocode.js
 * Description: JS file for geocoding
 *
 * @author Pascal Neis, pascal@neis-one.org
 * @version 0.1 2011-05-15
 */

//======================
// OBJECTS
var HOST_GEOCODE_URL = 'http://open.mapquestapi.com';
var GEOCODE_POST = HOST_GEOCODE_URL + '/nominatim/v1/search?format=json&json_callback=showResultsGeocode';
var searchType = 'search';

var isStartPointSet = false;
var isEndPointSet = false;

//======================
// FUNCTIONS
/*
 * geocodeAddress()-Function to read out textfield and send request to a OSM nominatim geocoder
 */
function geocodeAddress(tf){
	var freeform;

	if(tf == 'start'){
		freeform = document.getElementById('tfStartSearch').value;
	}
	if(tf == 'end'){
		freeform = document.getElementById('tfEndSearch').value;
	}

	if(freeform.match(/^\s*[-+]?[0-9]*\.?[0-9]+\s*[,;]\s*[-+]?[0-9]*\.?[0-9]+\s*$/)){

		var marker;
		if(tf == 'start'){
			isStartPointSet = true;
			marker = 'start';
		}
		if(tf == 'end'){
			isEndPointSet = true;
			marker = 'end';
		}
		var coord = freeform.split(/[,;]/);
                lonlat = new OpenLayers.LonLat(coord[1],coord[0]);
                setMarkerAndZoom(marker, lonlat);
                return;
	}

	document.getElementById('information').style.visibility = 'visible';
	document.getElementById('information').innerHTML =  '
One moment please ...
';

    var newURL = GEOCODE_POST + "&q="+freeform;
	var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = newURL;
    document.body.appendChild(script);
}

/*
 * showResultsGeocode()-Function to show the geocode result in a div
 */
function showResultsGeocode(response) {
    var html = '';
    var lonlat = '';

	if(response){
		html += '
Search Results:
';
		html += '
'
		var markername;
		if(getStatus()=='start'){
			markername = 'start'; isStartPointSet = true;
		}
		else if(getStatus()=='end'){
			markername = 'end';	isEndPointSet = true;
		}

		for(var i=0; i < response.length; i++){
			var result = response[i]; var resultNum = i+1;
        	//odd or even ?
        	var rowstyle='geocodeResultOdd';
        	if(i%2==0){ rowstyle='geocodeResultEven'; }

			html += '
';
			html += ''+resultNum+'	';
			html += '';
			if(result.display_name){
				var new_display_name = result.display_name;//.replace(/,/g, ",
")
				html += ''+new_display_name.trim()+'';
			}
			html += "
";

			//alert(result.lat + ", " + result.lon);
			if(lonlat == ''){
				lonlat = new OpenLayers.LonLat(result.lon,result.lat);
			}
		}
		html += '
';

		setMarkerAndZoom(markername, lonlat);
	}

    switch (searchType) {
		case "search":
			document.getElementById('information').style.display = "";
			document.getElementById('information').innerHTML = html;
			break;
	}
}

/*
 * setMarkerAndZoom()-Function to set a marker on the map and zoom
 */
function setMarkerAndZoom(markername,lonlat){
	setMarker(markername,lonlat);

	//Hack - FIXME !
	lonlat.lon -= 500;
	//Set Center
	map.setCenter(lonlat, 15);
}

/*
 * setMarker()-Function to set a marker on the map
 */
function setMarker(markername,lonlat){
	lonlat.transform(EPSG_4326, EPSG_900913);
	for(var i= 0; i<dragLayer.features.length; i++){
		if(dragLayer.features[i].name == markername){ dragLayer.removeFeatures([dragLayer.features[i]]); }
	}
	var point = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat));
	point.attributes = { icon: "img/start.png" };

	if(markername == 'start'){
		point.attributes = { icon: "img/start.png" };
	}
	else if(markername == 'end'){
		point.attributes = { icon: "img/end.png" };
	}

	point.name = markername;
	dragLayer.addFeatures([point]);
}

/*
 * getMarkerByName()-Function to return the marker-object by a name
 */
function getMarkerByName(markerName){
	for(var i= 0; i<dragLayer.features.length; i++){
		if(dragLayer.features[i].name == markerName){
			return dragLayer.features[i];
		}
	}
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Skip Paypal Validation - CAUTION!
// @namespace   NGPVAN
// @description Skip Oberon Paypal Validation
// @include     https://*.myngp.com/Tenant/Create*
// @include     https://*.myngp.com/Tenant/Update*
// @include     http://*.myngp.com/Tenant/Create*
// @include     http://*.myngp.com/Tenant/Update*
// @version     1.3
// ==/UserScript==

window.$(document).ready(function() {

	var addButton = function () {
		window.$(".paymentGatewayContainer :button[name^='PaymentGateway_']").parent(":visible").append("<button type='button' name='skipValidation'>Skip Validation</button>");
	};

	window.$("#AddGateway").click(addButton);

	addButton();

	var messages = window.ngp.tenant.update.paymentGateway.Messages;
	messages.TestSuccessful = "We have not necessarily verified this account as valid. Please look things over very carefully to ensure that these are the correct credentials.";

	messages.Changed += " Remember - We have not necessarily verified this account as valid.";

	window.$("[name='skipValidation']").click(function () {
		var $ = window.$;
		var ngp = window.ngp;

		var fakeButton = $(this);
		var button = fakeButton.prevAll(":button:visible");

        window.savingIndicator = new window.progressIndicator({ button: button, text: $('.indicatorText', window.$form).html() });
        var containingDivId = button[0].name.replace(".PrimaryAction", "");
        var paymentGateway = $('div[id="' + containingDivId + '"]');
		ngp.tenant.update.hidePaymentGatewayFields(paymentGateway);

		ngp.tenant.update.testPaymentGatewaySuccess(button);
		fakeButton.hide();
		ngp.FeedBack.update({DisplayMessageType: window.Constants.ResponseResultCode.Success});

		button.siblings(".hint").addClass("yellowbox");
		return false;
	});
});<commit_msg>updated skip paypal script version<commit_after>// ==UserScript==
// @name        Skip Paypal Validation - CAUTION!
// @namespace   NGPVAN
// @description Skip Oberon Paypal Validation
// @include     https://*.myngp.com/Tenant/Create*
// @include     https://*.myngp.com/Tenant/Update*
// @include     http://*.myngp.com/Tenant/Create*
// @include     http://*.myngp.com/Tenant/Update*
// @version     1.4
// ==/UserScript==

window.$(document).ready(function() {

	var addButton = function () {
		window.$(".paymentGatewayContainer :button[name^='PaymentGateway_']").parent(":visible").append("<button type='button' name='skipValidation'>Skip Validation</button>");
	};

	window.$("#AddGateway").click(addButton);

	addButton();

	var messages = window.ngp.tenant.update.paymentGateway.Messages;
	messages.TestSuccessful = "We have not necessarily verified this account as valid. Please look things over very carefully to ensure that these are the correct credentials.";

	messages.Changed += " Remember - We have not necessarily verified this account as valid.";

	window.$("[name='skipValidation']").click(function () {
		var $ = window.$;
		var ngp = window.ngp;

		var fakeButton = $(this);
		var button = fakeButton.prevAll(":button:visible");

        window.savingIndicator = new window.progressIndicator({ button: button, text: $('.indicatorText', window.$form).html() });
        var containingDivId = button[0].name.replace(".PrimaryAction", "");
        var paymentGateway = $('div[id="' + containingDivId + '"]');
		ngp.tenant.update.hidePaymentGatewayFields(paymentGateway);

		ngp.tenant.update.testPaymentGatewaySuccess(button);
		fakeButton.hide();
		ngp.FeedBack.update({DisplayMessageType: window.Constants.ResponseResultCode.Success});

		button.siblings(".hint").addClass("yellowbox");
		return false;
	});
});<|endoftext|>


<commit_before>import Ember from 'ember';

var NullReference, serialize;

var isPlainObject = function (o) {
  // This doesn't work for basic objects such as Object.create(null)
  return Object(o) === o && Object.getPrototypeOf(o) === Object.prototype;
};

var isCollaborativeList = function (object) {
  return object &&
    object.hasOwnProperty('insertAll') &&
    object.hasOwnProperty('pushAll') &&
    object.hasOwnProperty('removeRange');
};

var get = function () {
  if (Ember.isArray(arguments[0])) {
    return get.apply(this, arguments[0]);
  }

  var components = arguments;
  var cur = this;
  for (var i = 0; i < components.length; i++) {
    cur = cur._get(components[i]);
  }
  return cur;
};

var MapReference = function (model, parent, key, data) {
  this.model = model;
  this.parent = parent;
  this.key = key;
  this.data = data;
};

MapReference.isFor = function (data) {
  //return data instanceof gapi.drive.realtime.CollaborativeMap;
  return data &&
    data.hasOwnProperty('size') &&
    data.hasOwnProperty('keys') &&
    data.hasOwnProperty('values');
};

// this is used for debugging purposes to get a snapshot of the Google Drive data structure
MapReference.serialize = function (object) {
  var serialized = {};
  object.items().forEach(function (pair) {
    serialized[pair[0]] = serialize(pair[1]);
  });
  return serialized;
};

MapReference.prototype.path = function (key) {
  if (this.parent) {
    return this.parent.path(this.key) + (key ? '/' + key : '');
  } else {
    return key || '';
  }
};

MapReference.prototype.keys = function () {
  return this.data.keys();
};

MapReference.prototype.get = function (key, __components) {
  return get.apply(this, arguments);
};

MapReference.prototype._get = function (key) {
  var childData = this.data.get(key);
  if (NullReference.isFor(childData)) {
    return new NullReference(this.model, this, key);
  } else if (MapReference.isFor(childData)) {
    return new MapReference(this.model, this, key, childData);
  } else {
    return childData;
  }
};

MapReference.prototype.set = function (value) {
  if (arguments.length > 1) {
    if (arguments[1] !== undefined) {
      this.data.set(arguments[0], this._coerce(arguments[1]));
    }
  } else if (isPlainObject(value)) {

    var keys = Object.keys(value);
    for (var i = 0; i < keys.length; i++) {
      if (value[keys[i]] !== undefined) {
        this.data.set(keys[i], value[keys[i]]);
      }
    }
  } else {
    this.parent.set(this.key, value);
  }

  return this.parent ? this.parent.get(this.key) : this;
};

MapReference.prototype.value = function () {
  return serialize(this.data);
};

MapReference.prototype.delete = function (key) {
  this.data.delete(key);
  return this;
};

MapReference.prototype.clear = function () {
  this.data.clear();
  return this;
};

MapReference.prototype.materialize = function () {
  return this;
};

MapReference.prototype.changed = function (handler) {
  this.data.addEventListener(gapi.drive.realtime.EventType.OBJECT_CHANGED, handler);
  this.data.addEventListener(gapi.drive.realtime.EventType.VALUE_CHANGED, handler);
  return this;
};

MapReference.prototype._coerce = function (value) {
  if (isPlainObject(value)) {
    return this.model.createMap(value);
  } else {
    return value;
  }
};

MapReference.prototype.value = function () {
  return serialize(this.data);
};

var NullReference = function (model, parent, key) {
  this.model = model;
  this.parent = parent;
  this.key = key;
};

NullReference.isFor = function (data) {
  return data === null;
};

NullReference.prototype.path = function (key) {
  return this.parent.path(this.key) + (key ? '/' + key : '');
};

NullReference.prototype.keys = function () {
  return [];
};

NullReference.prototype.get = function (key, __components) {
  return get.apply(this, arguments);
};

NullReference.prototype._get = function (key) {
  return new NullReference(this.model, this, key);
};

NullReference.prototype.set = function (value) {
  var map = this.materialize();
  map.set(value);
  return map;
};

NullReference.prototype.delete = function (key) {
  return this;
};

NullReference.prototype.value = function () {
  return null;
};

NullReference.prototype.materialize = function () {
  var parent = this.parent.materialize();
  parent.set(
    this.key,
    this.model.createMap()
  );

  return parent.get(this.key);
};

NullReference.prototype.changed = function () {
  Ember.assert('You must materialize a NullReference before adding a listener to ' + this.path(), false);
};

var serializeList = function (object) {
  var serialized = [];
  object.asArray().forEach(function (item) {
    serialized.push(serialize(item));
  });
  return serialized;
};

var serialize = function (object) {
  if (MapReference.isFor(object)) {
    return MapReference.serialize(object);
  } else if (isCollaborativeList(object)) {
    return serializeList(object);
  } else {
    return object;
  }
};

export default MapReference;<commit_msg>Added array issue-specific fix to reference.js<commit_after>import Ember from 'ember';

var NullReference, serialize;

var isPlainObject = function (o) {
  // This doesn't work for basic objects such as Object.create(null)
  return Object(o) === o && Object.getPrototypeOf(o) === Object.prototype;
};

var isCollaborativeList = function (object) {
  return object &&
    object.hasOwnProperty('insertAll') &&
    object.hasOwnProperty('pushAll') &&
    object.hasOwnProperty('removeRange');
};

var get = function () {
  if (Ember.isArray(arguments[0])) {
    return get.apply(this, arguments[0]);
  }

  var components = arguments;
  var cur = this;
  for (var i = 0; i < components.length; i++) {
    cur = cur._get(components[i]);
  }
  return cur;
};

var MapReference = function (model, parent, key, data) {
  this.model = model;
  this.parent = parent;
  this.key = key;
  this.data = data;
};

MapReference.isFor = function (data) {
  //return data instanceof gapi.drive.realtime.CollaborativeMap;
  return data &&
    data.hasOwnProperty('size') &&
    data.hasOwnProperty('keys') &&
    data.hasOwnProperty('values');
};

// this is used for debugging purposes to get a snapshot of the Google Drive data structure
MapReference.serialize = function (object) {
  var serialized = {};
  object.items().forEach(function (pair) {
    if (pair[1] instanceof Array) {
      // gapi returns array properties with non-writable elements, so we need to remap them as a temporary fix
      serialized[pair[0]] = serialize(pair[1]).map(function (item) { return item; });
    } else {
      serialized[pair[0]] = serialize(pair[1]);
    }
  });
  return serialized;
};

MapReference.prototype.path = function (key) {
  if (this.parent) {
    return this.parent.path(this.key) + (key ? '/' + key : '');
  } else {
    return key || '';
  }
};

MapReference.prototype.keys = function () {
  return this.data.keys();
};

MapReference.prototype.get = function (key, __components) {
  return get.apply(this, arguments);
};

MapReference.prototype._get = function (key) {
  var childData = this.data.get(key);
  if (NullReference.isFor(childData)) {
    return new NullReference(this.model, this, key);
  } else if (MapReference.isFor(childData)) {
    return new MapReference(this.model, this, key, childData);
  } else {
    return childData;
  }
};

MapReference.prototype.set = function (value) {
  if (arguments.length > 1) {
    if (arguments[1] !== undefined) {
      this.data.set(arguments[0], this._coerce(arguments[1]));
    }
  } else if (isPlainObject(value)) {

    var keys = Object.keys(value);
    for (var i = 0; i < keys.length; i++) {
      if (value[keys[i]] !== undefined) {
        this.data.set(keys[i], value[keys[i]]);
      }
    }
  } else {
    this.parent.set(this.key, value);
  }

  return this.parent ? this.parent.get(this.key) : this;
};

MapReference.prototype.value = function () {
  return serialize(this.data);
};

MapReference.prototype.delete = function (key) {
  this.data.delete(key);
  return this;
};

MapReference.prototype.clear = function () {
  this.data.clear();
  return this;
};

MapReference.prototype.materialize = function () {
  return this;
};

MapReference.prototype.changed = function (handler) {
  this.data.addEventListener(gapi.drive.realtime.EventType.OBJECT_CHANGED, handler);
  this.data.addEventListener(gapi.drive.realtime.EventType.VALUE_CHANGED, handler);
  return this;
};

MapReference.prototype._coerce = function (value) {
  if (isPlainObject(value)) {
    return this.model.createMap(value);
  } else {
    return value;
  }
};

MapReference.prototype.value = function () {
  return serialize(this.data);
};

var NullReference = function (model, parent, key) {
  this.model = model;
  this.parent = parent;
  this.key = key;
};

NullReference.isFor = function (data) {
  return data === null;
};

NullReference.prototype.path = function (key) {
  return this.parent.path(this.key) + (key ? '/' + key : '');
};

NullReference.prototype.keys = function () {
  return [];
};

NullReference.prototype.get = function (key, __components) {
  return get.apply(this, arguments);
};

NullReference.prototype._get = function (key) {
  return new NullReference(this.model, this, key);
};

NullReference.prototype.set = function (value) {
  var map = this.materialize();
  map.set(value);
  return map;
};

NullReference.prototype.delete = function (key) {
  return this;
};

NullReference.prototype.value = function () {
  return null;
};

NullReference.prototype.materialize = function () {
  var parent = this.parent.materialize();
  parent.set(
    this.key,
    this.model.createMap()
  );

  return parent.get(this.key);
};

NullReference.prototype.changed = function () {
  Ember.assert('You must materialize a NullReference before adding a listener to ' + this.path(), false);
};

var serializeList = function (object) {
  var serialized = [];
  object.asArray().forEach(function (item) {
    serialized.push(serialize(item));
  });
  return serialized;
};

var serialize = function (object) {
  if (MapReference.isFor(object)) {
    return MapReference.serialize(object);
  } else if (isCollaborativeList(object)) {
    return serializeList(object);
  } else {
    return object;
  }
};

export default MapReference;<|endoftext|>