_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q46200
|
train
|
function(moduleName, context) {
var module = modules[moduleName].creator(context);
if (!context.getElement) {
// Add in a default getElement function that matches the first module element
// Developer should stub this out if there are more than one instance of this module
context.getElement = function() {
return document.querySelector('[data-module="' + moduleName + '"]');
};
}
return module;
}
|
javascript
|
{
"resource": ""
}
|
|
q46201
|
train
|
function(behaviorName, context) {
var behaviorData = behaviors[behaviorName];
if (behaviorData) {
// getElement on behaviors must be stubbed
if (!context.getElement) {
context.getElement = function() {
throw new Error('You must stub `getElement` for behaviors.');
};
}
return behaviors[behaviorName].creator(context);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q46202
|
train
|
function() {
var todoList = [];
Object.keys(todos).forEach(function(id) {
todoList.push(todos[id]);
});
return todoList;
}
|
javascript
|
{
"resource": ""
}
|
|
q46203
|
train
|
function() {
var me = this;
Object.keys(todos).forEach(function(id) {
if (todos[id].completed) {
me.remove(id);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46204
|
train
|
function(title) {
var todoId = counter++;
todos[todoId] = {
id: todoId,
title: title,
completed: false
};
return todoId;
}
|
javascript
|
{
"resource": ""
}
|
|
q46205
|
isServiceBeingInstantiated
|
train
|
function isServiceBeingInstantiated(serviceName) {
for (var i = 0, len = serviceStack.length; i < len; i++) {
if (serviceStack[i] === serviceName) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46206
|
error
|
train
|
function error(exception) {
if (typeof customErrorHandler === 'function') {
customErrorHandler(exception);
return;
}
if (globalConfig.debug) {
throw exception;
} else {
application.fire('error', {
exception: exception
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46207
|
createAndBindEventDelegate
|
train
|
function createAndBindEventDelegate(eventDelegates, element, handler) {
var delegate = new Box.DOMEventDelegate(element, handler, globalConfig.eventTypes);
eventDelegates.push(delegate);
delegate.attachEvents();
}
|
javascript
|
{
"resource": ""
}
|
q46208
|
callMessageHandler
|
train
|
function callMessageHandler(instance, name, data) {
// If onmessage is an object call message handler with the matching key (if any)
if (instance.onmessage !== null && typeof instance.onmessage === 'object' && instance.onmessage.hasOwnProperty(name)) {
instance.onmessage[name].call(instance, data);
// Otherwise if message name exists in messages call onmessage with name, data
} else if (indexOf(instance.messages || [], name) !== -1) {
instance.onmessage.call(instance, name, data);
}
}
|
javascript
|
{
"resource": ""
}
|
q46209
|
train
|
function(data) {
if (globalConfig.debug) {
// We grab console via getGlobal() so we can stub it out in tests
var globalConsole = this.getGlobal('console');
if (globalConsole && globalConsole.warn) {
globalConsole.warn(data);
}
} else {
application.fire('warning', data);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46210
|
train
|
function(data) {
if (globalConfig.debug) {
// We grab console via getGlobal() so we can stub it out in tests
var globalConsole = this.getGlobal('console');
if (globalConsole && globalConsole.info) {
globalConsole.info(data);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46211
|
parseRoutes
|
train
|
function parseRoutes() {
// Regexs to convert a route (/file/:fileId) into a regex
var optionalParam = /\((.*?)\)/g,
namedParam = /(\(\?)?:\w+/g,
splatParam = /\*\w+/g,
escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g,
namedParamCallback = function(match, optional) {
return optional ? match : '([^\/]+)';
},
route,
regexRoute;
for (var i = 0, len = pageRoutes.length; i < len; i++) {
route = pageRoutes[i];
regexRoute = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, namedParamCallback)
.replace(splatParam, '(.*?)');
regexRoutes.push(new RegExp('^' + regexRoute + '$'));
}
}
|
javascript
|
{
"resource": ""
}
|
q46212
|
broadcastStateChanged
|
train
|
function broadcastStateChanged(fragment) {
var globMatches = matchGlob(fragment);
if (!!globMatches) {
application.broadcast('statechanged', {
url: fragment,
prevUrl: prevUrl,
params: globMatches.splice(1) // Get everything after the URL
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46213
|
train
|
function(state, title, fragment) {
prevUrl = history.state.hash;
// First push the state
history.pushState(state, title, fragment);
// Then make the AJAX request
broadcastStateChanged(fragment);
}
|
javascript
|
{
"resource": ""
}
|
|
q46214
|
getClosestTodoElement
|
train
|
function getClosestTodoElement(element) {
var matchesSelector = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector;
while (element) {
if (matchesSelector.bind(element)('li')) {
return element;
} else {
element = element.parentNode;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46215
|
train
|
function(event, element, elementType) {
if (elementType === 'delete-btn') {
var todoEl = getClosestTodoElement(element),
todoId = getClosestTodoId(element);
moduleEl.querySelector('#todo-list').removeChild(todoEl);
todosDB.remove(todoId);
context.broadcast('todoremoved', {
id: todoId
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46216
|
train
|
function(event, element, elementType) {
if (elementType === 'mark-as-complete-checkbox') {
var todoEl = getClosestTodoElement(element),
todoId = getClosestTodoId(element);
if (element.checked) {
todoEl.classList.add('completed');
todosDB.markAsComplete(todoId);
} else {
todoEl.classList.remove('completed');
todosDB.markAsIncomplete(todoId);
}
context.broadcast('todostatuschange');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46217
|
train
|
function(event, element, elementType) {
if (elementType === 'todo-label') {
var todoEl = getClosestTodoElement(element);
event.preventDefault();
event.stopPropagation();
this.showEditor(todoEl);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46218
|
train
|
function(event, element, elementType) {
if (elementType === 'edit-input') {
var todoEl = getClosestTodoElement(element);
if (event.keyCode === ENTER_KEY) {
this.saveLabel(todoEl);
this.hideEditor(todoEl);
} else if (event.keyCode === ESCAPE_KEY) {
this.hideEditor(todoEl);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46219
|
train
|
function(todoEl) {
var todoId = getClosestTodoId(todoEl),
editInputEl = todoEl.querySelector('.edit'),
title = todosDB.get(todoId).title; // Grab current label
// Set the edit input value to current label
editInputEl.value = title;
todoEl.classList.add('editing');
// Place user cursor in the input
editInputEl.focus();
}
|
javascript
|
{
"resource": ""
}
|
|
q46220
|
train
|
function(todoEl) {
var todoId = getClosestTodoId(todoEl),
editInputEl = todoEl.querySelector('.edit'),
newTitle = (editInputEl.value).trim();
todoEl.querySelector('label').textContent = newTitle;
todosDB.edit(todoId, newTitle);
}
|
javascript
|
{
"resource": ""
}
|
|
q46221
|
isListCompleted
|
train
|
function isListCompleted() {
var todos = todosDB.getList();
var len = todos.length;
var isComplete = len > 0;
for (var i = 0; i < len; i++) {
if (!todos[i].completed) {
isComplete = false;
break;
}
}
return isComplete;
}
|
javascript
|
{
"resource": ""
}
|
q46222
|
train
|
function(event, element, elementType) {
if (elementType === 'select-all-checkbox') {
var shouldMarkAsComplete = element.checked;
if (shouldMarkAsComplete) {
todosDB.markAllAsComplete();
} else {
todosDB.markAllAsIncomplete();
}
this.renderList();
context.broadcast('todostatuschange');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46223
|
train
|
function(name, data) {
switch(name) {
case 'todoadded':
case 'todoremoved':
this.renderList();
this.updateSelectAllCheckbox();
break;
case 'todostatuschange':
this.updateSelectAllCheckbox();
break;
case 'statechanged':
setFilterByUrl(data.url);
this.renderList();
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46224
|
train
|
function(id, title, isCompleted) {
var todoTemplateEl = moduleEl.querySelector('.todo-template-container li'),
newTodoEl = todoTemplateEl.cloneNode(true);
// Set the label of the todo
newTodoEl.querySelector('label').textContent = title;
newTodoEl.setAttribute('data-todo-id', id);
if (isCompleted) {
newTodoEl.classList.add('completed');
newTodoEl.querySelector('input[type="checkbox"]').checked = true;
}
return newTodoEl;
}
|
javascript
|
{
"resource": ""
}
|
|
q46225
|
train
|
function() {
// Clear the todo list first
this.clearList();
var todos = todosDB.getList(),
todo;
// Render todos - factor in the current filter as well
for (var i = 0, len = todos.length; i < len; i++) {
todo = todos[i];
if (!filter
|| (filter === 'incomplete' && !todo.completed)
|| (filter === 'complete' && todo.completed)) {
this.addTodoItem(todo.id, todo.title, todo.completed);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46226
|
train
|
function(type, handler) {
var handlers = this._handlers[type],
i,
len;
if (typeof handlers === 'undefined') {
handlers = this._handlers[type] = [];
}
for (i = 0, len = handlers.length; i < len; i++) {
if (handlers[i] === handler) {
// prevent duplicate handlers
return;
}
}
handlers.push(handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q46227
|
DOMEventDelegate
|
train
|
function DOMEventDelegate(element, handler, eventTypes) {
/**
* The DOM element that this object is handling events for.
* @type {HTMLElement}
*/
this.element = element;
/**
* Object on which event handlers are available.
* @type {Object}
* @private
*/
this._handler = handler;
/**
* List of event types to handle (make sure these events bubble!)
* @type {string[]}
* @private
*/
this._eventTypes = eventTypes || DEFAULT_EVENT_TYPES;
/**
* Tracks event handlers whose this-value is bound to the correct
* object.
* @type {Object}
* @private
*/
this._boundHandler = {};
/**
* Indicates if events have been attached.
* @type {boolean}
* @private
*/
this._attached = false;
}
|
javascript
|
{
"resource": ""
}
|
q46228
|
train
|
function() {
if (!this._attached) {
forEachEventType(this._eventTypes, this._handler, function(eventType) {
var that = this;
function handleEvent() {
that._handleEvent.apply(that, arguments);
}
Box.DOM.on(this.element, eventType, handleEvent);
this._boundHandler[eventType] = handleEvent;
}, this);
this._attached = true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46229
|
train
|
function() {
forEachEventType(this._eventTypes, this._handler, function(eventType) {
Box.DOM.off(this.element, eventType, this._boundHandler[eventType]);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q46230
|
train
|
function(url) {
var linkEls = moduleEl.querySelectorAll('a');
for (var i = 0, len = linkEls.length; i < len; i++) {
if (url === linkEls[i].pathname) {
linkEls[i].classList.add('selected');
} else {
linkEls[i].classList.remove('selected');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46231
|
train
|
function() {
var todos = todosDB.getList();
var completedCount = 0;
for (var i = 0, len = todos.length; i < len; i++) {
if (todos[i].completed) {
completedCount++;
}
}
var itemsLeft = todos.length - completedCount;
this.updateItemsLeft(itemsLeft);
this.updateCompletedButton(completedCount);
}
|
javascript
|
{
"resource": ""
}
|
|
q46232
|
train
|
function(itemsLeft) {
var itemText = itemsLeft === 1 ? 'item' : 'items';
moduleEl.querySelector('.items-left-counter').textContent = itemsLeft;
moduleEl.querySelector('.items-left-text').textContent = itemText + ' left';
}
|
javascript
|
{
"resource": ""
}
|
|
q46233
|
resolveConfig
|
train
|
function resolveConfig({
filePath,
stylelintPath,
stylelintConfig,
prettierOptions
}) {
const resolve = resolveConfig.resolve;
const stylelint = requireRelative(stylelintPath, filePath, 'stylelint');
const linterAPI = stylelint.createLinter();
if (stylelintConfig) {
return Promise.resolve(resolve(stylelintConfig, prettierOptions));
}
return linterAPI
.getConfigForFile(filePath)
.then(({ config }) => resolve(config, prettierOptions));
}
|
javascript
|
{
"resource": ""
}
|
q46234
|
train
|
function() {
var xhr = $.ajaxSettings.xhr();
if (!xhr.upload) return xhr;
xhr.upload.addEventListener('progress', function(e) {
options.progress(e.loaded / e.total);
});
return xhr;
}
|
javascript
|
{
"resource": ""
}
|
|
q46235
|
buildRequest
|
train
|
async function buildRequest(method, url, params, options) {
let param = {};
let config = {};
if (noneBodyMethod.indexOf(method) >= 0) {
param = { params: { ...params }, ...reqConfig, ...options };
} else {
param = JSON.stringify(params);
config = {
...reqConfig,
headers: {
'Content-Type': 'application/json',
...csrfConfig,
},
};
config = Object.assign({}, config, options);
}
return axios[method](url, param, config);
}
|
javascript
|
{
"resource": ""
}
|
q46236
|
renderRoutes
|
train
|
function renderRoutes() {
return (
<Switch>
{
routes.map(route => (
<Route key={route.path || ''} {...route} />
))
}
</Switch>
);
}
|
javascript
|
{
"resource": ""
}
|
q46237
|
isAlreadyReplicating
|
train
|
function isAlreadyReplicating(state, feed_id, ignore_id) {
for(var id in state.peers) {
if(id !== ignore_id) {
var peer = state.peers[id]
if(peer.notes && getReceive(peer.notes[id])) return id
if(peer.replicating && peer.replicating[feed_id] && peer.replicating[feed_id].rx) return id
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q46238
|
isAvailable
|
train
|
function isAvailable(state, feed_id, ignore_id) {
for(var peer_id in state.peers) {
if(peer_id != ignore_id) {
var peer = state.peers[peer_id]
//BLOCK: check wether id has blocked this peer
if((peer.clock && peer.clock[feed_id] || 0) > (state.clock[feed_id] || 0) && isShared(state, feed_id, peer_id)) {
return true
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46239
|
eachFrom
|
train
|
function eachFrom(keys, key, iter) {
var i = keys.indexOf(key)
if(!~i) return
//start at 1 because we want to visit all keys but key.
for(var j = 1; j < keys.length; j++)
if(iter(keys[(j+i)%keys.length], j))
return
}
|
javascript
|
{
"resource": ""
}
|
q46240
|
WebRtcPeerRecvonly
|
train
|
function WebRtcPeerRecvonly(options, callback) {
if (!(this instanceof WebRtcPeerRecvonly)) {
return new WebRtcPeerRecvonly(options, callback)
}
WebRtcPeerRecvonly.super_.call(this, 'recvonly', options, callback)
}
|
javascript
|
{
"resource": ""
}
|
q46241
|
sendMessage
|
train
|
function sendMessage(e) {
var txt = $('#msgtxt').val().trim();
if(!txt) return;
$('#messages').append(createMsgBox(txt));
socket.emit('sendmsg', txt, function(evtJson) {
var evt = JSON.parse(evtJson),
reply = evt['Reply-Text'].split(' '), //0 = +OK, 1 = uuid
$elm = $('#messages').children().last().removeClass('sending');
if(reply[0] == '+OK')
$elm.addClass('sent').data('uuid', reply[1]);
else
$elm.addClass('failed').data('error', evt['Reply-Text']);
});
$('#msgtxt').val('');
}
|
javascript
|
{
"resource": ""
}
|
q46242
|
openChat
|
train
|
function openChat() {
var num = validateNum();
if(num) {
socket.emit('setup', num, function() {
number = num;
$('#num').hide();
$('#chat').show();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46243
|
validateNum
|
train
|
function validateNum() {
var pass = true,
num = '';
['#areacode', '#phnum1', '#phnum2'].forEach(function(id) {
var $e = $(id),
val = $e.val();
if(!val || val.length !== parseInt($e.attr('maxlength'), 10)) {
pass = false;
$e.addClass('error');
}
else
num += val;
});
if(!pass) return false;
return num;
}
|
javascript
|
{
"resource": ""
}
|
q46244
|
train
|
function() {
if (this.$visible) {
return;
}
this.$visible = true;
var pc = editablePromiseCollection();
//own show
pc.when(this.$onshow());
//clear errors
this.$setError(null, '');
//children show
angular.forEach(this.$editables, function(editable) {
pc.when(editable.show());
});
//wait promises and activate
pc.then({
onWait: angular.bind(this, this.$setWaiting),
onTrue: angular.bind(this, this.$activate),
onFalse: angular.bind(this, this.$activate),
onString: angular.bind(this, this.$activate)
});
// add to internal list of shown forms
// setTimeout needed to prevent closing right after opening (e.g. when trigger by button)
setTimeout(angular.bind(this, function() {
// clear `clicked` to get ready for clicks on visible form
this._clicked = false;
if(editableUtils.indexOf(shown, this) === -1) {
shown.push(this);
}
}), 0);
}
|
javascript
|
{
"resource": ""
}
|
|
q46245
|
train
|
function(name, msg) {
angular.forEach(this.$editables, function(editable) {
if(!name || editable.name === name) {
editable.setError(msg);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46246
|
getNearest
|
train
|
function getNearest($select, value) {
var delta = {};
angular.forEach($select.children('option'), function(opt, i){
var optValue = angular.element(opt).attr('value');
if(optValue === '') return;
var distance = Math.abs(optValue - value);
if(typeof delta.distance === 'undefined' || distance < delta.distance) {
delta = {value: optValue, distance: distance};
}
});
return delta.value;
}
|
javascript
|
{
"resource": ""
}
|
q46247
|
writeProviderEntry
|
train
|
function writeProviderEntry (store, cid, peer, time, callback) {
const dsKey = [
makeProviderKey(cid),
'/',
utils.encodeBase32(peer.id)
].join('')
store.put(new Key(dsKey), Buffer.from(varint.encode(time)), callback)
}
|
javascript
|
{
"resource": ""
}
|
q46248
|
loadProviders
|
train
|
function loadProviders (store, cid, callback) {
pull(
store.query({ prefix: makeProviderKey(cid) }),
pull.map((entry) => {
const parts = entry.key.toString().split('/')
const lastPart = parts[parts.length - 1]
const rawPeerId = utils.decodeBase32(lastPart)
return [new PeerId(rawPeerId), readTime(entry.value)]
}),
pull.collect((err, res) => {
if (err) {
return callback(err)
}
return callback(null, new Map(res))
})
)
}
|
javascript
|
{
"resource": ""
}
|
q46249
|
handleMessage
|
train
|
function handleMessage (peer, msg, callback) {
// update the peer
dht._add(peer, (err) => {
if (err) {
log.error('Failed to update the kbucket store')
log.error(err)
}
// get handler & exectue it
const handler = getMessageHandler(msg.type)
if (!handler) {
log.error(`no handler found for message type: ${msg.type}`)
return callback()
}
handler(peer, msg, callback)
})
}
|
javascript
|
{
"resource": ""
}
|
q46250
|
train
|
function () {
this.writeDebug('reset');
locationset = [];
featuredset = [];
normalset = [];
markers = [];
firstRun = false;
$(document).off('click.'+pluginName, '.' + this.settings.locationList + ' li');
if ( $('.' + this.settings.locationList + ' .bh-sl-close-directions-container').length ) {
$('.bh-sl-close-directions-container').remove();
}
if (this.settings.inlineDirections === true) {
// Remove directions panel if it's there
var $adp = $('.' + this.settings.locationList + ' .adp');
if ( $adp.length > 0 ) {
$adp.remove();
$('.' + this.settings.locationList + ' ul').fadeIn();
}
$(document).off('click', '.' + this.settings.locationList + ' li .loc-directions a');
}
if (this.settings.pagination === true) {
$(document).off('click.'+pluginName, '.bh-sl-pagination li');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46251
|
train
|
function () {
this.writeDebug('formFiltersReset');
if (this.settings.taxonomyFilters === null) {
return;
}
var $inputs = $('.' + this.settings.taxonomyFiltersContainer + ' input'),
$selects = $('.' + this.settings.taxonomyFiltersContainer + ' select');
if ( typeof($inputs) !== 'object') {
return;
}
// Loop over the input fields
$inputs.each(function() {
if ($(this).is('input[type="checkbox"]') || $(this).is('input[type="radio"]')) {
$(this).prop('checked',false);
}
});
// Loop over select fields
$selects.each(function() {
$(this).prop('selectedIndex',0);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46252
|
train
|
function() {
this.writeDebug('mapReload');
this.reset();
reload = true;
if ( this.settings.taxonomyFilters !== null ) {
this.formFiltersReset();
this.taxonomyFiltersInit();
}
if ((olat) && (olng)) {
this.settings.mapSettings.zoom = originalZoom;
this.processForm();
}
else {
this.mapping(mappingObj);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46253
|
train
|
function (notifyText) {
this.writeDebug('notify',notifyText);
if (this.settings.callbackNotify) {
this.settings.callbackNotify.call(this, notifyText);
}
else {
alert(notifyText);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46254
|
train
|
function(param) {
this.writeDebug('getQueryString',param);
if(param) {
param = param.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + param + '=([^&#]*)'),
results = regex.exec(location.search);
return (results === null) ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46255
|
train
|
function () {
this.writeDebug('_formEventHandler');
var _this = this;
// ASP.net or regular submission?
if (this.settings.noForm === true) {
$(document).on('click.'+pluginName, '.' + this.settings.formContainer + ' button', function (e) {
_this.processForm(e);
});
$(document).on('keydown.'+pluginName, function (e) {
if (e.keyCode === 13 && $('#' + _this.settings.addressID).is(':focus')) {
_this.processForm(e);
}
});
}
else {
$(document).on('submit.'+pluginName, '#' + this.settings.formID, function (e) {
_this.processForm(e);
});
}
// Reset button trigger
if ($('.bh-sl-reset').length && $('#' + this.settings.mapID).length) {
$(document).on('click.' + pluginName, '.bh-sl-reset', function () {
_this.mapReload();
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46256
|
train
|
function (lat, lng, address, geocodeData, map) {
this.writeDebug('_getData',arguments);
var _this = this,
northEast = '',
southWest = '',
formattedAddress = '';
// Define extra geocode result info
if (typeof geocodeData !== 'undefined' && typeof geocodeData.geometry.bounds !== 'undefined') {
formattedAddress = geocodeData.formatted_address;
northEast = JSON.stringify( geocodeData.geometry.bounds.getNorthEast() );
southWest = JSON.stringify( geocodeData.geometry.bounds.getSouthWest() );
}
// Before send callback
if (this.settings.callbackBeforeSend) {
this.settings.callbackBeforeSend.call(this, lat, lng, address, formattedAddress, northEast, southWest, map);
}
// Raw data
if(_this.settings.dataRaw !== null) {
// XML
if( dataTypeRead === 'xml' ) {
return $.parseXML(_this.settings.dataRaw);
}
// JSON
else if (dataTypeRead === 'json') {
if (Array.isArray && Array.isArray(_this.settings.dataRaw)) {
return _this.settings.dataRaw;
}
else if (typeof _this.settings.dataRaw === 'string') {
return JSON.parse(_this.settings.dataRaw);
}
else {
return [];
}
}
}
// Remote data
else {
var d = $.Deferred();
// Loading
if (this.settings.loading === true) {
$('.' + this.settings.formContainer).append('<div class="' + this.settings.loadingContainer +'"></div>');
}
// Data to pass with the AJAX request
var ajaxData = {
'origLat' : lat,
'origLng' : lng,
'origAddress': address,
'formattedAddress': formattedAddress,
'boundsNorthEast' : northEast,
'boundsSouthWest' : southWest
};
// Set up extra object for custom extra data to be passed with the AJAX request
if (this.settings.ajaxData !== null && typeof this.settings.ajaxData === 'object') {
$.extend(ajaxData, this.settings.ajaxData);
}
// AJAX request
$.ajax({
type : 'GET',
url : this.settings.dataLocation + (this.settings.dataType === 'jsonp' ? (this.settings.dataLocation.match(/\?/) ? '&' : '?') + 'callback=?' : ''),
// Passing the lat, lng, address, formatted address and bounds with the AJAX request so they can optionally be used by back-end languages
data : ajaxData,
dataType : dataTypeRead,
jsonpCallback: (this.settings.dataType === 'jsonp' ? this.settings.callbackJsonp : null)
}).done(function(p) {
d.resolve(p);
// Loading remove
if (_this.settings.loading === true) {
$('.' + _this.settings.formContainer + ' .' + _this.settings.loadingContainer).remove();
}
}).fail(d.reject);
return d.promise();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46257
|
train
|
function () {
this.writeDebug('_start');
var _this = this,
doAutoGeo = this.settings.autoGeocode,
latlng;
// Full map blank start
if (_this.settings.fullMapStartBlank !== false) {
var $mapDiv = $('#' + _this.settings.mapID);
$mapDiv.addClass('bh-sl-map-open');
var myOptions = _this.settings.mapSettings;
myOptions.zoom = _this.settings.fullMapStartBlank;
latlng = new google.maps.LatLng(this.settings.defaultLat, this.settings.defaultLng);
myOptions.center = latlng;
// Create the map
_this.map = new google.maps.Map(document.getElementById(_this.settings.mapID), myOptions);
// Re-center the map when the browser is re-sized
google.maps.event.addDomListener(window, 'resize', function() {
var center = _this.map.getCenter();
google.maps.event.trigger(_this.map, 'resize');
_this.map.setCenter(center);
});
// Only do this once
_this.settings.fullMapStartBlank = false;
myOptions.zoom = originalZoom;
}
else {
// If a default location is set
if (this.settings.defaultLoc === true) {
this.defaultLocation();
}
// If there is already have a value in the address bar
if ($.trim($('#' + this.settings.addressID).val()) !== ''){
_this.writeDebug('Using Address Field');
_this.processForm(null);
doAutoGeo = false; // No need for additional processing
}
// If show full map option is true
else if (this.settings.fullMapStart === true) {
if ((this.settings.querystringParams === true && this.getQueryString(this.settings.addressID)) || (this.settings.querystringParams === true && this.getQueryString(this.settings.searchID)) || (this.settings.querystringParams === true && this.getQueryString(this.settings.maxDistanceID))) {
_this.writeDebug('Using Query String');
this.processForm(null);
doAutoGeo = false; // No need for additional processing
}
else {
this.mapping(null);
}
}
}
// HTML5 auto geolocation API option
if (this.settings.autoGeocode === true && doAutoGeo === true) {
_this.writeDebug('Auto Geo');
_this.htmlGeocode();
}
// HTML5 geolocation API button option
if (this.settings.autoGeocode !== null) {
_this.writeDebug('Button Geo');
$(document).on('click.'+pluginName, '#' + this.settings.geocodeID, function () {
_this.htmlGeocode();
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46258
|
train
|
function() {
this.writeDebug('htmlGeocode',arguments);
var _this = this;
if (_this.settings.sessionStorage === true && window.sessionStorage && window.sessionStorage.getItem('myGeo')){
_this.writeDebug('Using Session Saved Values for GEO');
_this.autoGeocodeQuery(JSON.parse(window.sessionStorage.getItem('myGeo')));
return false;
}
else if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
_this.writeDebug('Current Position Result');
// To not break autoGeocodeQuery then we create the obj to match the geolocation format
var pos = {
coords: {
latitude : position.coords.latitude,
longitude: position.coords.longitude,
accuracy : position.coords.accuracy
}
};
// Have to do this to get around scope issues
if (_this.settings.sessionStorage === true && window.sessionStorage) {
window.sessionStorage.setItem('myGeo',JSON.stringify(pos));
}
// Callback
if (_this.settings.callbackAutoGeoSuccess) {
_this.settings.callbackAutoGeoSuccess.call(this, pos);
}
_this.autoGeocodeQuery(pos);
}, function(error){
_this._autoGeocodeError(error);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46259
|
train
|
function (thisObj) {
thisObj.writeDebug('reverseGoogleGeocode',arguments);
var geocoder = new google.maps.Geocoder();
this.geocode = function (request, callbackFunction) {
geocoder.geocode(request, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
var result = {};
result.address = results[0].formatted_address;
callbackFunction(result);
}
} else {
callbackFunction(null);
throw new Error('Reverse geocode was not successful for the following reason: ' + status);
}
});
};
}
|
javascript
|
{
"resource": ""
}
|
|
q46260
|
train
|
function (num, dec) {
this.writeDebug('roundNumber',arguments);
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
|
javascript
|
{
"resource": ""
}
|
|
q46261
|
train
|
function (obj) {
this.writeDebug('hasEmptyObjectVals',arguments);
var objTest = true;
for(var key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] !== '' && obj[key].length !== 0) {
objTest = false;
}
}
}
return objTest;
}
|
javascript
|
{
"resource": ""
}
|
|
q46262
|
train
|
function () {
this.writeDebug('modalClose');
// Callback
if (this.settings.callbackModalClose) {
this.settings.callbackModalClose.call(this);
}
// Reset the filters
filters = {};
// Undo category selections
$('.' + this.settings.overlay + ' select').prop('selectedIndex', 0);
$('.' + this.settings.overlay + ' input').prop('checked', false);
// Hide the modal
$('.' + this.settings.overlay).hide();
}
|
javascript
|
{
"resource": ""
}
|
|
q46263
|
train
|
function (loopcount) {
this.writeDebug('_createLocationVariables',arguments);
var value;
locationData = {};
for (var key in locationset[loopcount]) {
if (locationset[loopcount].hasOwnProperty(key)) {
value = locationset[loopcount][key];
if (key === 'distance' || key === 'altdistance') {
value = this.roundNumber(value, 2);
}
locationData[key] = value;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46264
|
train
|
function(locationsarray) {
this.writeDebug('sortAlpha',arguments);
var property = (this.settings.sortBy.hasOwnProperty('prop') && typeof this.settings.sortBy.prop !== 'undefined') ? this.settings.sortBy.prop : 'name';
if (this.settings.sortBy.hasOwnProperty('order') && this.settings.sortBy.order.toString() === 'desc') {
locationsarray.sort(function (a, b) {
return b[property].toLowerCase().localeCompare(a[property].toLowerCase());
});
} else {
locationsarray.sort(function (a, b) {
return a[property].toLowerCase().localeCompare(b[property].toLowerCase());
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46265
|
train
|
function(locationsarray) {
this.writeDebug('sortDate',arguments);
var property = (this.settings.sortBy.hasOwnProperty('prop') && typeof this.settings.sortBy.prop !== 'undefined') ? this.settings.sortBy.prop : 'date';
if (this.settings.sortBy.hasOwnProperty('order') && this.settings.sortBy.order.toString() === 'desc') {
locationsarray.sort(function (a, b) {
return new Date(b[property]).getTime() - new Date(a[property]).getTime();
});
} else {
locationsarray.sort(function (a, b) {
return new Date(a[property]).getTime() - new Date(b[property]).getTime();
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46266
|
train
|
function (locationsarray) {
this.writeDebug('sortNumerically',arguments);
var property = (
this.settings.sortBy !== null &&
this.settings.sortBy.hasOwnProperty('prop') &&
typeof this.settings.sortBy.prop !== 'undefined'
) ? this.settings.sortBy.prop : 'distance';
if (this.settings.sortBy !== null && this.settings.sortBy.hasOwnProperty('order') && this.settings.sortBy.order.toString() === 'desc') {
locationsarray.sort(function (a, b) {
return ((b[property] < a[property]) ? -1 : ((b[property] > a[property]) ? 1 : 0));
});
} else {
locationsarray.sort(function (a, b) {
return ((a[property] < b[property]) ? -1 : ((a[property] > b[property]) ? 1 : 0));
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46267
|
train
|
function (data, filters) {
this.writeDebug('filterData',arguments);
var filterTest = true;
for (var k in filters) {
if (filters.hasOwnProperty(k)) {
// Exclusive filtering
if (this.settings.exclusiveFiltering === true || (this.settings.exclusiveTax !== null && Array.isArray(this.settings.exclusiveTax) && this.settings.exclusiveTax.indexOf(k) !== -1)) {
var filterTests = filters[k];
var exclusiveTest = [];
if (typeof data[k] !== 'undefined') {
for (var l = 0; l < filterTests.length; l++) {
exclusiveTest[l] = new RegExp(filterTests[l], 'i').test(data[k].replace(/([^\x00-\x7F]|[.*+?^=!:${}()|\[\]\/\\]|&\s+)/g, ''));
}
}
if (exclusiveTest.indexOf(true) === -1) {
filterTest = false;
}
}
// Inclusive filtering
else {
if (typeof data[k] === 'undefined' || !(new RegExp(filters[k].join(''), 'i').test(data[k].replace(/([^\x00-\x7F]|[.*+?^=!:${}()|\[\]\/\\]|&\s+)/g, '')))) {
filterTest = false;
}
}
}
}
if (filterTest) {
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46268
|
train
|
function (currentPage) {
this.writeDebug('paginationSetup',arguments);
var pagesOutput = '';
var totalPages;
var $paginationList = $('.bh-sl-pagination-container .bh-sl-pagination');
// Total pages
if ( this.settings.storeLimit === -1 || locationset.length < this.settings.storeLimit ) {
totalPages = locationset.length / this.settings.locationsPerPage;
} else {
totalPages = this.settings.storeLimit / this.settings.locationsPerPage;
}
// Current page check
if (typeof currentPage === 'undefined') {
currentPage = 0;
}
// Initial pagination setup
if ($paginationList.length === 0) {
pagesOutput = this._paginationOutput(currentPage, totalPages);
}
// Update pagination on page change
else {
// Remove the old pagination
$paginationList.empty();
// Add the numbers
pagesOutput = this._paginationOutput(currentPage, totalPages);
}
$paginationList.append(pagesOutput);
}
|
javascript
|
{
"resource": ""
}
|
|
q46269
|
train
|
function (markerUrl, markerWidth, markerHeight) {
this.writeDebug('markerImage',arguments);
var markerImg;
// User defined marker dimensions
if (typeof markerWidth !== 'undefined' && typeof markerHeight !== 'undefined') {
markerImg = {
url: markerUrl,
size: new google.maps.Size(markerWidth, markerHeight),
scaledSize: new google.maps.Size(markerWidth, markerHeight)
};
}
// Default marker dimensions: 32px x 32px
else {
markerImg = {
url: markerUrl,
size: new google.maps.Size(32, 32),
scaledSize: new google.maps.Size(32, 32)
};
}
return markerImg;
}
|
javascript
|
{
"resource": ""
}
|
|
q46270
|
train
|
function (point, name, address, letter, map, category) {
this.writeDebug('createMarker',arguments);
var marker, markerImg, letterMarkerImg;
var categories = [];
// Custom multi-marker image override (different markers for different categories
if (this.settings.catMarkers !== null) {
if (typeof category !== 'undefined') {
// Multiple categories
if (category.indexOf(',') !== -1) {
// Break the category variable into an array if there are multiple categories for the location
categories = category.split(',');
// With multiple categories the color will be determined by the last matched category in the data
for(var i = 0; i < categories.length; i++) {
if (categories[i] in this.settings.catMarkers) {
markerImg = this.markerImage(this.settings.catMarkers[categories[i]][0], parseInt(this.settings.catMarkers[categories[i]][1]), parseInt(this.settings.catMarkers[categories[i]][2]));
}
}
}
// Single category
else {
if (category in this.settings.catMarkers) {
markerImg = this.markerImage(this.settings.catMarkers[category][0], parseInt(this.settings.catMarkers[category][1]), parseInt(this.settings.catMarkers[category][2]));
}
}
}
}
// Custom single marker image override
if (this.settings.markerImg !== null) {
if (this.settings.markerDim === null) {
markerImg = this.markerImage(this.settings.markerImg);
}
else {
markerImg = this.markerImage(this.settings.markerImg, this.settings.markerDim.width, this.settings.markerDim.height);
}
}
// Marker setup
if (this.settings.callbackCreateMarker) {
// Marker override callback
marker = this.settings.callbackCreateMarker.call(this, map, point, letter, category);
}
else {
// Create the default markers
if (this.settings.disableAlphaMarkers === true || this.settings.storeLimit === -1 || this.settings.storeLimit > 26 || this.settings.catMarkers !== null || this.settings.markerImg !== null || (this.settings.fullMapStart === true && firstRun === true && (isNaN(this.settings.fullMapStartListLimit) || this.settings.fullMapStartListLimit > 26 || this.settings.fullMapStartListLimit === -1))) {
marker = new google.maps.Marker({
position : point,
map : map,
draggable: false,
icon: markerImg // Reverts to default marker if nothing is passed
});
}
else {
// Letter markers image
letterMarkerImg = {
url: 'https://mt.googleapis.com/vt/icon/name=icons/spotlight/spotlight-waypoint-b.png&text=' + letter + '&psize=16&font=fonts/Roboto-Regular.ttf&color=ff333333&ax=44&ay=48'
};
// Letter markers
marker = new google.maps.Marker({
position : point,
map : map,
icon : letterMarkerImg,
draggable: false
});
}
}
return marker;
}
|
javascript
|
{
"resource": ""
}
|
|
q46271
|
train
|
function (currentMarker, storeStart, page) {
this.writeDebug('_defineLocationData',arguments);
var indicator = '';
this._createLocationVariables(currentMarker.get('id'));
var altDistLength,
distLength;
if (locationData.distance <= 1) {
if (this.settings.lengthUnit === 'km') {
distLength = this.settings.kilometerLang;
altDistLength = this.settings.mileLang;
}
else {
distLength = this.settings.mileLang;
altDistLength = this.settings.kilometerLang;
}
}
else {
if (this.settings.lengthUnit === 'km') {
distLength = this.settings.kilometersLang;
altDistLength = this.settings.milesLang;
}
else {
distLength = this.settings.milesLang;
altDistLength = this.settings.kilometersLang;
}
}
// Set up alpha character
var markerId = currentMarker.get('id');
// Use dot markers instead of alpha if there are more than 26 locations
if (this.settings.disableAlphaMarkers === true || this.settings.storeLimit === -1 || this.settings.storeLimit > 26 || (this.settings.fullMapStart === true && firstRun === true && (isNaN(this.settings.fullMapStartListLimit) || this.settings.fullMapStartListLimit > 26 || this.settings.fullMapStartListLimit === -1))) {
indicator = markerId + 1;
}
else {
if (page > 0) {
indicator = String.fromCharCode('A'.charCodeAt(0) + (storeStart + markerId));
}
else {
indicator = String.fromCharCode('A'.charCodeAt(0) + markerId);
}
}
// Define location data
return {
location: [$.extend(locationData, {
'markerid' : markerId,
'marker' : indicator,
'altlength': altDistLength,
'length' : distLength,
'origin' : originalOrigin
})]
};
}
|
javascript
|
{
"resource": ""
}
|
|
q46272
|
train
|
function (marker, storeStart, page) {
this.writeDebug('listSetup',arguments);
// Define the location data
var locations = this._defineLocationData(marker, storeStart, page);
// Set up the list template with the location data
var listHtml = listTemplate(locations);
$('.' + this.settings.locationList + ' > ul').append(listHtml);
}
|
javascript
|
{
"resource": ""
}
|
|
q46273
|
train
|
function (marker) {
var markerImg;
// Reset the previously selected marker
if ( typeof prevSelectedMarkerAfter !== 'undefined' ) {
prevSelectedMarkerAfter.setIcon( prevSelectedMarkerBefore );
}
// Change the selected marker icon
if (this.settings.selectedMarkerImgDim === null) {
markerImg = this.markerImage(this.settings.selectedMarkerImg);
} else {
markerImg = this.markerImage(this.settings.selectedMarkerImg, this.settings.selectedMarkerImgDim.width, this.settings.selectedMarkerImgDim.height);
}
// Save the marker before switching it
prevSelectedMarkerBefore = marker.icon;
marker.setIcon( markerImg );
// Save the marker to a variable so it can be reverted when another marker is clicked
prevSelectedMarkerAfter = marker;
}
|
javascript
|
{
"resource": ""
}
|
|
q46274
|
train
|
function (marker, location, infowindow, storeStart, page) {
this.writeDebug('createInfowindow',arguments);
var _this = this;
// Define the location data
var locations = this._defineLocationData(marker, storeStart, page);
// Set up the infowindow template with the location data
var formattedAddress = infowindowTemplate(locations);
// Opens the infowindow when list item is clicked
if (location === 'left') {
infowindow.setContent(formattedAddress);
infowindow.open(marker.get('map'), marker);
}
// Opens the infowindow when the marker is clicked
else {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(formattedAddress);
infowindow.open(marker.get('map'), marker);
// Focus on the list
var markerId = marker.get('id');
var $selectedLocation = $('.' + _this.settings.locationList + ' li[data-markerid=' + markerId + ']');
if ($selectedLocation.length > 0) {
// Marker click callback
if (_this.settings.callbackMarkerClick) {
_this.settings.callbackMarkerClick.call(this, marker, markerId, $selectedLocation, locationset[markerId]);
}
$('.' + _this.settings.locationList + ' li').removeClass('list-focus');
$selectedLocation.addClass('list-focus');
// Scroll list to selected marker
var $container = $('.' + _this.settings.locationList);
$container.animate({
scrollTop: $selectedLocation.offset().top - $container.offset().top + $container.scrollTop()
});
}
// Custom selected marker override
if (_this.settings.selectedMarkerImg !== null) {
_this.changeSelectedMarker(marker);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46275
|
train
|
function (position) {
this.writeDebug('autoGeocodeQuery',arguments);
var _this = this,
distance = null,
$distanceInput = $('#' + this.settings.maxDistanceID),
originAddress;
// Query string parameters
if (this.settings.querystringParams === true) {
// Check for distance query string parameters
if (this.getQueryString(this.settings.maxDistanceID)){
distance = this.getQueryString(this.settings.maxDistanceID);
if ($distanceInput.val() !== '') {
distance = $distanceInput.val();
}
}
else{
// Get the distance if set
if (this.settings.maxDistance === true) {
distance = $distanceInput.val() || '';
}
}
}
else {
// Get the distance if set
if (this.settings.maxDistance === true) {
distance = $distanceInput.val() || '';
}
}
// The address needs to be determined for the directions link
var r = new this.reverseGoogleGeocode(this);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
r.geocode({'latLng': latlng}, function (data) {
if (data !== null) {
originAddress = addressInput = data.address;
olat = mappingObj.lat = position.coords.latitude;
olng = mappingObj.lng = position.coords.longitude;
mappingObj.origin = originAddress;
mappingObj.distance = distance;
_this.mapping(mappingObj);
// Fill in the search box.
if (typeof originAddress !== 'undefined') {
$('#' + _this.settings.addressID).val(originAddress);
}
} else {
// Unable to geocode
_this.notify(_this.settings.addressErrorAlert);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46276
|
train
|
function() {
this.writeDebug('defaultLocation');
var _this = this,
distance = null,
$distanceInput = $('#' + this.settings.maxDistanceID),
originAddress;
// Query string parameters
if (this.settings.querystringParams === true) {
// Check for distance query string parameters
if (this.getQueryString(this.settings.maxDistanceID)){
distance = this.getQueryString(this.settings.maxDistanceID);
if ($distanceInput.val() !== '') {
distance = $distanceInput.val();
}
}
else {
// Get the distance if set
if (this.settings.maxDistance === true) {
distance = $distanceInput.val() || '';
}
}
}
else {
// Get the distance if set
if (this.settings.maxDistance === true) {
distance = $distanceInput.val() || '';
}
}
// The address needs to be determined for the directions link
var r = new this.reverseGoogleGeocode(this);
var latlng = new google.maps.LatLng(this.settings.defaultLat, this.settings.defaultLng);
r.geocode({'latLng': latlng}, function (data) {
if (data !== null) {
originAddress = addressInput = data.address;
olat = mappingObj.lat = _this.settings.defaultLat;
olng = mappingObj.lng = _this.settings.defaultLng;
mappingObj.distance = distance;
mappingObj.origin = originAddress;
_this.mapping(mappingObj);
} else {
// Unable to geocode
_this.notify(_this.settings.addressErrorAlert);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46277
|
train
|
function (newPage) {
this.writeDebug('paginationChange',arguments);
// Page change callback
if (this.settings.callbackPageChange) {
this.settings.callbackPageChange.call(this, newPage);
}
mappingObj.page = newPage;
this.mapping(mappingObj);
}
|
javascript
|
{
"resource": ""
}
|
|
q46278
|
train
|
function(markerID) {
this.writeDebug('getAddressByMarker',arguments);
var formattedAddress = "";
// Set up formatted address
if(locationset[markerID].address){ formattedAddress += locationset[markerID].address + ' '; }
if(locationset[markerID].address2){ formattedAddress += locationset[markerID].address2 + ' '; }
if(locationset[markerID].city){ formattedAddress += locationset[markerID].city + ', '; }
if(locationset[markerID].state){ formattedAddress += locationset[markerID].state + ' '; }
if(locationset[markerID].postal){ formattedAddress += locationset[markerID].postal + ' '; }
if(locationset[markerID].country){ formattedAddress += locationset[markerID].country + ' '; }
return formattedAddress;
}
|
javascript
|
{
"resource": ""
}
|
|
q46279
|
train
|
function() {
this.writeDebug('clearMarkers');
var locationsLimit = null;
if (locationset.length < this.settings.storeLimit) {
locationsLimit = locationset.length;
}
else {
locationsLimit = this.settings.storeLimit;
}
for (var i = 0; i < locationsLimit; i++) {
markers[i].setMap(null);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46280
|
train
|
function(origin, locID, map) {
this.writeDebug('directionsRequest',arguments);
// Directions request callback
if (this.settings.callbackDirectionsRequest) {
this.settings.callbackDirectionsRequest.call(this, origin, locID, map, locationset[locID]);
}
var destination = this.getAddressByMarker(locID);
if (destination) {
// Hide the location list
$('.' + this.settings.locationList + ' ul').hide();
// Remove the markers
this.clearMarkers();
// Clear the previous directions request
if (directionsDisplay !== null && typeof directionsDisplay !== 'undefined') {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
// Directions request
directionsDisplay.setMap(map);
directionsDisplay.setPanel($('.bh-sl-directions-panel').get(0));
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
$('.' + this.settings.locationList).prepend('<div class="bh-sl-close-directions-container"><div class="' + this.settings.closeIcon + '"></div></div>');
}
$(document).off('click', '.' + this.settings.locationList + ' li .loc-directions a');
}
|
javascript
|
{
"resource": ""
}
|
|
q46281
|
train
|
function() {
this.writeDebug('closeDirections');
// Close directions callback
if (this.settings.callbackCloseDirections) {
this.settings.callbackCloseDirections.call(this);
}
// Remove the close icon, remove the directions, add the list back
this.reset();
if ((olat) && (olng)) {
if (this.countFilters() === 0) {
this.settings.mapSettings.zoom = originalZoom;
}
else {
this.settings.mapSettings.zoom = 0;
}
this.processForm(null);
}
$(document).off('click.'+pluginName, '.' + this.settings.locationList + ' .bh-sl-close-icon');
}
|
javascript
|
{
"resource": ""
}
|
|
q46282
|
train
|
function($lengthSwap) {
this.writeDebug('lengthUnitSwap',arguments);
if ($lengthSwap.val() === 'alt-distance') {
$('.' + this.settings.locationList + ' .loc-alt-dist').show();
$('.' + this.settings.locationList + ' .loc-default-dist').hide();
} else if ($lengthSwap.val() === 'default-distance') {
$('.' + this.settings.locationList + ' .loc-default-dist').show();
$('.' + this.settings.locationList + ' .loc-alt-dist').hide();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46283
|
train
|
function (data, lat, lng, origin, maxDistance) {
this.writeDebug('locationsSetup',arguments);
if (typeof origin !== 'undefined') {
if (!data.distance) {
data.distance = this.geoCodeCalcCalcDistance(lat, lng, data.lat, data.lng, GeoCodeCalc.EarthRadius);
// Alternative distance length unit
if (this.settings.lengthUnit === 'm') {
// Miles to kilometers
data.altdistance = parseFloat(data.distance)*1.609344;
} else if (this.settings.lengthUnit === 'km') {
// Kilometers to miles
data.altdistance = parseFloat(data.distance)/1.609344;
}
}
}
// Create the array
if (this.settings.maxDistance === true && typeof maxDistance !== 'undefined' && maxDistance !== null) {
if (data.distance <= maxDistance) {
locationset.push( data );
}
else {
return;
}
}
else if (this.settings.maxDistance === true && this.settings.querystringParams === true && typeof maxDistance !== 'undefined' && maxDistance !== null) {
if (data.distance <= maxDistance) {
locationset.push( data );
}
else {
return;
}
}
else {
locationset.push( data );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46284
|
train
|
function() {
this.writeDebug('sorting',arguments);
var _this = this,
$mapDiv = $('#' + _this.settings.mapID),
$sortSelect = $('#' + _this.settings.sortID);
if ($sortSelect.length === 0) {
return;
}
$sortSelect.on('change.'+pluginName, function (e) {
e.stopPropagation();
// Reset pagination.
if (_this.settings.pagination === true) {
_this.paginationChange(0);
}
var sortMethod,
sortVal;
sortMethod = (typeof $(this).find(':selected').attr('data-method') !== 'undefined') ? $(this).find(':selected').attr('data-method') : 'distance';
sortVal = $(this).val();
_this.settings.sortBy.method = sortMethod;
_this.settings.sortBy.prop = sortVal;
// Callback
if (_this.settings.callbackSorting) {
_this.settings.callbackSorting.call(this, _this.settings.sortBy);
}
if ($mapDiv.hasClass('bh-sl-map-open')) {
_this.mapping(mappingObj);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46285
|
train
|
function() {
this.writeDebug('order',arguments);
var _this = this,
$mapDiv = $('#' + _this.settings.mapID),
$orderSelect = $('#' + _this.settings.orderID);
if ($orderSelect.length === 0) {
return;
}
$orderSelect.on('change.'+pluginName, function (e) {
e.stopPropagation();
// Reset pagination.
if (_this.settings.pagination === true) {
_this.paginationChange(0);
}
_this.settings.sortBy.order = $(this).val();
// Callback
if (_this.settings.callbackOrder) {
_this.settings.callbackOrder.call(this, _this.settings.order);
}
if ($mapDiv.hasClass('bh-sl-map-open')) {
_this.mapping(mappingObj);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46286
|
train
|
function () {
this.writeDebug('countFilters');
var filterCount = 0;
if (!this.isEmptyObject(filters)) {
for (var key in filters) {
if (filters.hasOwnProperty(key)) {
filterCount += filters[key].length;
}
}
}
return filterCount;
}
|
javascript
|
{
"resource": ""
}
|
|
q46287
|
train
|
function(key) {
this.writeDebug('_existingRadioFilters',arguments);
$('#' + this.settings.taxonomyFilters[key] + ' input[type=radio]').each(function () {
if ($(this).prop('checked')) {
var filterVal = $(this).val();
// Only add the taxonomy id if it doesn't already exist
if (typeof filterVal !== 'undefined' && filterVal !== '' && filters[key].indexOf(filterVal) === -1) {
filters[key] = [filterVal];
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46288
|
train
|
function () {
this.writeDebug('checkFilters');
for(var key in this.settings.taxonomyFilters) {
if (this.settings.taxonomyFilters.hasOwnProperty(key)) {
// Find the existing checked boxes for each checkbox filter
this._existingCheckedFilters(key);
// Find the existing selected value for each select filter
this._existingSelectedFilters(key);
// Find the existing value for each radio button filter
this._existingRadioFilters(key);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46289
|
train
|
function( taxonomy, value ) {
this.writeDebug('selectQueryStringFilters', arguments);
var $taxGroupContainer = $('#' + this.settings.taxonomyFilters[taxonomy]);
// Handle checkboxes.
if ( $taxGroupContainer.find('input[type="checkbox"]').length ) {
for ( var i = 0; i < value.length; i++ ) {
$taxGroupContainer.find('input:checkbox[value="' + value[i] + '"]').prop('checked', true);
}
}
// Handle select fields.
if ( $taxGroupContainer.find('select').length ) {
// Only expecting one value for select fields.
$taxGroupContainer.find('option[value="' + value[0] + '"]').prop('selected', true);
}
// Handle radio buttons.
if ( $taxGroupContainer.find('input[type="radio"]').length ) {
// Only one value for radio button.
$taxGroupContainer.find('input:radio[value="' + value[0] + '"]').prop('checked', true);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46290
|
train
|
function () {
this.writeDebug('checkQueryStringFilters',arguments);
// Loop through the filters.
for(var key in filters) {
if (filters.hasOwnProperty(key)) {
var filterVal = this.getQueryString(key);
// Check for multiple values separated by comma.
if ( filterVal.indexOf( ',' ) !== -1 ) {
filterVal = filterVal.split( ',' );
}
// Only add the taxonomy id if it doesn't already exist
if (typeof filterVal !== 'undefined' && filterVal !== '' && filters[key].indexOf(filterVal) === -1) {
if ( Array.isArray( filterVal ) ) {
filters[key] = filterVal;
} else {
filters[key] = [filterVal];
}
}
// Select the filters indicated in the query string.
if ( filters[key].length ) {
this.selectQueryStringFilters( key, filters[key] );
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46291
|
train
|
function (filterContainer) {
this.writeDebug('getFilterKey',arguments);
for (var key in this.settings.taxonomyFilters) {
if (this.settings.taxonomyFilters.hasOwnProperty(key)) {
for (var i = 0; i < this.settings.taxonomyFilters[key].length; i++) {
if (this.settings.taxonomyFilters[key] === filterContainer) {
return key;
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46292
|
train
|
function () {
this.writeDebug('taxonomyFiltersInit');
// Set up the filters
for(var key in this.settings.taxonomyFilters) {
if (this.settings.taxonomyFilters.hasOwnProperty(key)) {
filters[key] = [];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46293
|
train
|
function(markers, map) {
this.writeDebug('checkVisibleMarkers',arguments);
var _this = this;
var locations, listHtml;
// Empty the location list
$('.' + this.settings.locationList + ' ul').empty();
// Set up the new list
$(markers).each(function(x, marker){
if (map.getBounds().contains(marker.getPosition())) {
// Define the location data
_this.listSetup(marker, 0, 0);
// Set up the list template with the location data
listHtml = listTemplate(locations);
$('.' + _this.settings.locationList + ' > ul').append(listHtml);
}
});
// Re-add the list background colors
$('.' + this.settings.locationList + ' ul li:even').css('background', this.settings.listColor1);
$('.' + this.settings.locationList + ' ul li:odd').css('background', this.settings.listColor2);
}
|
javascript
|
{
"resource": ""
}
|
|
q46294
|
train
|
function(map) {
this.writeDebug('dragSearch',arguments);
var newCenter = map.getCenter(),
newCenterCoords,
_this = this;
// Save the new zoom setting
this.settings.mapSettings.zoom = map.getZoom();
olat = mappingObj.lat = newCenter.lat();
olng = mappingObj.lng = newCenter.lng();
// Determine the new origin addresss
var newAddress = new this.reverseGoogleGeocode(this);
newCenterCoords = new google.maps.LatLng(mappingObj.lat, mappingObj.lng);
newAddress.geocode({'latLng': newCenterCoords}, function (data) {
if (data !== null) {
mappingObj.origin = addressInput = data.address;
_this.mapping(mappingObj);
} else {
// Unable to geocode
_this.notify(_this.settings.addressErrorAlert);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46295
|
train
|
function() {
this.writeDebug('emptyResult',arguments);
var center,
locList = $('.' + this.settings.locationList + ' ul'),
myOptions = this.settings.mapSettings,
noResults;
// Create the map
this.map = new google.maps.Map(document.getElementById(this.settings.mapID), myOptions);
// Callback
if (this.settings.callbackNoResults) {
this.settings.callbackNoResults.call(this, this.map, myOptions);
}
// Empty the location list
locList.empty();
// Append the no results message
noResults = $('<li><div class="bh-sl-noresults-title">' + this.settings.noResultsTitle + '</div><br><div class="bh-sl-noresults-desc">' + this.settings.noResultsDesc + '</li>').hide().fadeIn();
locList.append(noResults);
// Center on the original origin or 0,0 if not available
if ((olat) && (olng)) {
center = new google.maps.LatLng(olat, olng);
} else {
center = new google.maps.LatLng(0, 0);
}
this.map.setCenter(center);
if (originalZoom) {
this.map.setZoom(originalZoom);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46296
|
train
|
function(map, origin, originPoint) {
this.writeDebug('originMarker',arguments);
if (this.settings.originMarker !== true) {
return;
}
var marker,
originImg = '';
if (typeof origin !== 'undefined') {
if (this.settings.originMarkerImg !== null) {
if (this.settings.originMarkerDim === null) {
originImg = this.markerImage(this.settings.originMarkerImg);
}
else {
originImg = this.markerImage(this.settings.originMarkerImg, this.settings.originMarkerDim.width, this.settings.originMarkerDim.height);
}
}
else {
originImg = {
url: 'https://mt.googleapis.com/vt/icon/name=icons/spotlight/spotlight-waypoint-a.png'
};
}
marker = new google.maps.Marker({
position : originPoint,
map : map,
icon : originImg,
draggable: false
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46297
|
train
|
function() {
this.writeDebug('modalWindow');
if (this.settings.modal !== true) {
return;
}
var _this = this;
// Callback
if (_this.settings.callbackModalOpen) {
_this.settings.callbackModalOpen.call(this);
}
// Pop up the modal window
$('.' + _this.settings.overlay).fadeIn();
// Close modal when close icon is clicked and when background overlay is clicked
$(document).on('click.'+pluginName, '.' + _this.settings.closeIcon + ', .' + _this.settings.overlay, function () {
_this.modalClose();
});
// Prevent clicks within the modal window from closing the entire thing
$(document).on('click.'+pluginName, '.' + _this.settings.modalWindow, function (e) {
e.stopPropagation();
});
// Close modal when escape key is pressed
$(document).on('keyup.'+pluginName, function (e) {
if (e.keyCode === 27) {
_this.modalClose();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46298
|
train
|
function(nearestLoc, infowindow, storeStart, page) {
this.writeDebug('openNearestLocation',arguments);
if (this.settings.openNearest !== true || typeof nearestLoc === 'undefined' || (this.settings.fullMapStart === true && firstRun === true) || (this.settings.defaultLoc === true && firstRun === true)) {
return;
}
var _this = this;
// Callback
if (_this.settings.callbackNearestLoc) {
_this.settings.callbackNearestLoc.call(this, _this.map, nearestLoc, infowindow, storeStart, page);
}
var markerId = 0;
var selectedMarker = markers[markerId];
_this.createInfowindow(selectedMarker, 'left', infowindow, storeStart, page);
// Scroll list to selected marker
var $container = $('.' + _this.settings.locationList);
var $selectedLocation = $('.' + _this.settings.locationList + ' li[data-markerid=' + markerId + ']');
// Focus on the list
$('.' + _this.settings.locationList + ' li').removeClass('list-focus');
$selectedLocation.addClass('list-focus');
$container.animate({
scrollTop: $selectedLocation.offset().top - $container.offset().top + $container.scrollTop()
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46299
|
train
|
function(map, infowindow, storeStart, page) {
this.writeDebug('listClick',arguments);
var _this = this;
$(document).on('click.' + pluginName, '.' + _this.settings.locationList + ' li', function () {
var markerId = $(this).data('markerid');
var selectedMarker = markers[markerId];
// List click callback
if (_this.settings.callbackListClick) {
_this.settings.callbackListClick.call(this, markerId, selectedMarker, locationset[markerId], map);
}
map.panTo(selectedMarker.getPosition());
var listLoc = 'left';
if (_this.settings.bounceMarker === true) {
selectedMarker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
selectedMarker.setAnimation(null);
_this.createInfowindow(selectedMarker, listLoc, infowindow, storeStart, page);
}, 700
);
}
else {
_this.createInfowindow(selectedMarker, listLoc, infowindow, storeStart, page);
}
// Custom selected marker override
if (_this.settings.selectedMarkerImg !== null) {
_this.changeSelectedMarker(selectedMarker);
}
// Focus on the list
$('.' + _this.settings.locationList + ' li').removeClass('list-focus');
$('.' + _this.settings.locationList + ' li[data-markerid=' + markerId + ']').addClass('list-focus');
});
// Prevent bubbling from list content links
$(document).on('click.'+pluginName, '.' + _this.settings.locationList + ' li a', function(e) {
e.stopPropagation();
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.