<commit_before>angular.module('save-my-gas')

.controller('gasStationController',
function(
	$scope,
	GasStation,
	simulatorService,
	vehicleService,
	vehicles
) {
	$scope.title = 'busca de preços de postoso de combustível'

	$scope.vehicles = vehicles
	var lastRefuelValue = null
	var selectedVehicle = null
	var radius = 50

	simulatorService.verifyVehiclesRefuels()

	$scope.vehicleSelected = function(vehicle) {
		if (vehicle && vehicle.id) {
			$scope.vehicleId = vehicle.id
			selectedVehicle = simulatorService.getVehicleById($scope.vehicleId)
			simulatorService.verifyVehicleRefuels($scope.vehicleId)
				.then(function(count) {
					simulatorService.getLastRefuelValue($scope.vehicleId)
						.then(function(lastRefuelVal) {
							lastRefuelValue = lastRefuelVal
							initGeolocation()
						})
						.catch(function() {
							$scope.vehicleId = null
							selectedVehicle = null
						})
				})
		} else {
			$scope.vehicleId = null
			selectedVehicle = null
		}
	}

	var initGeolocation = function() {
		if (navigator.geolocation) {
			var positionSuccess = function(pos) {
				$scope.geolocation = pos.coords

				// initMap($scope.geolocation)
			}
			var positionError = function(err) {
				Materialize.toast('Não foi possível obter sua localização')
			}
			navigator.geolocation.getCurrentPosition(positionSuccess, positionError)
		} else {
			Materialize.toast('Não foi possível obter sua localização porque seu navegador não suporta essa funcionalidade')
				// initMap()
		}
	}

	var getNearGasStations = function(geolocation) {
		$scope.collection = GasStation.find({
				where: {
					geolocation: {
						near: geolocation,
						maxDistance: radius,
						unit: 'kilometers'
					}
				},
				limit: 10,
				include: {
					relation: 'fuelPrices',
					scope: {
						order: 'date DESC',
						limit: 1
					},
					relation: 'city'
				}
			}
		})

		$scope.collection.then(function(collection) {
			collection.forEatch(function(gasStation) {
				gasStation.curretPrice = null
				if(gasStation.fuelPrices && gasStation.fuelPrices.length) {
					gasStation.curretPrice = gasStation.fuelPrices[0].sale
				}

				//calculation
				gasStation.arriveValue = null
			})
		})
}
})

.controller('gasStationViewController',
	function(
		$scope
	) {})
<commit_msg>updated web-app<commit_after>angular.module('save-my-gas')

.controller('gasStationController',
	function(
		$scope,
		GasStation,
		simulatorService,
		vehicleService,
		vehicles
	) {
		$scope.title = 'busca de preços de postoso de combustível'

		$scope.vehicles = vehicles
		var lastRefuelValue = null
		var selectedVehicle = null
		var radius = 50

		simulatorService.verifyVehiclesRefuels()

		$scope.vehicleSelected = function(vehicle) {
			if (vehicle && vehicle.id) {
				$scope.vehicleId = vehicle.id
				selectedVehicle = simulatorService.getVehicleById($scope.vehicleId)
				simulatorService.verifyVehicleRefuels($scope.vehicleId)
					.then(function(count) {
						simulatorService.getLastRefuelValue($scope.vehicleId)
							.then(function(lastRefuelVal) {
								lastRefuelValue = lastRefuelVal
								initGeolocation()
							})
							.catch(function() {
								$scope.vehicleId = null
								selectedVehicle = null
							})
					})
			} else {
				$scope.vehicleId = null
				selectedVehicle = null
			}
		}

		var initGeolocation = function() {
			if (navigator.geolocation) {
				var positionSuccess = function(pos) {
					$scope.geolocation = pos.coords

					// initMap($scope.geolocation)
				}
				var positionError = function(err) {
					Materialize.toast('Não foi possível obter sua localização')
				}
				navigator.geolocation.getCurrentPosition(positionSuccess, positionError)
			} else {
				Materialize.toast('Não foi possível obter sua localização porque seu navegador não suporta essa funcionalidade')
					// initMap()
			}
		}

		var getNearGasStations = function(geolocation) {
			$scope.collection = GasStation.find({
				where: {
					geolocation: {
						near: geolocation,
						maxDistance: radius,
						unit: 'kilometers'
					}
				},
				limit: 10,
				include: {
					relation: 'fuelPrices',
					scope: {
						order: 'date DESC',
						limit: 1
					},
					relation: 'city'
				}
			})

			$scope.collection.then(function(collection) {
				collection.forEatch(function(gasStation) {
					gasStation.curretPrice = null
					if (gasStation.fuelPrices && gasStation.fuelPrices.length) {
						gasStation.curretPrice = gasStation.fuelPrices[0].sale
					}

					//calculation
					gasStation.arriveValue = null
				})
			})
		}
	})

.controller('gasStationViewController',
	function(
		$scope
	) {})
<|endoftext|>


<commit_before>/**
 * Vosao CMS. Simple CMS for Google App Engine.
 * Copyright (C) 2009 Vosao development team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) 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 General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * email: vosao.dev@gmail.com
 */

var rootFolder;
var browserMode = 'ckeditor';

$(function(){
    $("#tabs").tabs();
	Vosao.initJSONRpc(loadData);
    if (Vosao.getQueryParam('mode')) {
    	browserMode = Vosao.getQueryParam('mode');
    }
    window.scrollbars.visible = true;
});

function loadData() {
	loadFolderTree();
	loadTree();
}

function loadFolderTree() {
	Vosao.jsonrpc.folderService.getTree(function(rootItem) {
        rootFolder = rootItem;
        $("#folders-tree").html(renderFolderList(rootItem));
       	$("#folders-tree").treeview();
       	selectFolder();
    });
}

function selectFolder() {
   	if ($.cookie('fileBrowserPath')) {
   		Vosao.jsonrpc.folderService.getFolderByPath(function(r) {
   			if (r) {
   		   		onFolderSelected(r.entity.id);
   			}
   			else {
   		   		onFolderSelected(rootFolder.entity.id);
   			}
   		}, $.cookie('fileBrowserPath'));
		$.cookie('fileBrowserPath', null, {path:'/', expires: 10});
   	}
   	else {
   		onFolderSelected(rootFolder.entity.id);
   	}
}

/**
 * Render ul/li list for folder item and subitems.
 * @param item - java class TreeItemDecorator<FolderEntity>
 */
function renderFolderList(item) {
   	var titleLink = "" + item.entity.title
       	    + "";
    var s = "
" + titleLink;
    if (item.children.list.length > 0) {
        s += "
\n";
        for (var i = 0; i < item.children.list.length; i++) {
            var childItem = item.children.list[i];
            s += renderFolderList(childItem);
        }
        s += "
\n";
    }
    s += "
\n"
    return s;
}

function onFolderSelected(folderId) {
	Vosao.jsonrpc.folderService.getFolderPath(function(folderPath) {
		if (folderPath) {
			$('#currentFolder').html(folderPath);
		}
		else {
			$('#currentFolder').html('/');
		}
		Vosao.jsonrpc.fileService.getByFolder(function(files) {
            var result = "";
            for (i = 0; i < files.list.length; i++) {
                var file = files.list[i];
                var title = " title=\"" + file.title + "\"";
                var onClick = " onclick=\"onFileSelected(" + file.id + ")\"";
                var thumbnail = '';
                if (Vosao.isImage(file.filename)) {
                    thumbnail = '';
                }
                result += "

" + thumbnail
                    + "
" + file.filename
                    + "

\n";
            }
            $("#files").html(result);
        }, folderId);
    }, folderId);
}

function onFileSelected(fileId) {
	Vosao.jsonrpc.fileService.getFilePath(function(path) {
       	if (browserMode == 'ckeditor') {
       		window.opener.CKEDITOR.tools.callFunction(1, path);
       		window.close();
       	}
       	if (browserMode == 'page') {
       		window.opener.setResource(path);
       		window.close();
       	}
    }, fileId);
}

function onPageSelected(path) {
   	if (browserMode == 'ckeditor') {
   		window.opener.CKEDITOR.tools.callFunction(1, path);
   		window.close();
   	}
   	if (browserMode == 'page') {
   		window.opener.setResource(path);
   		window.close();
   	}
}

function loadTree() {
	Vosao.jsonrpc.pageService.getTree(function(r) {
		$('#pages-tree').html(renderPage(r));
		$("#pages-tree").treeview({
			animated: "fast",
			collapsed: true
		});
	});
}

function renderPage(vo) {
	var pageUrl = vo.entity.friendlyURL;
	var p = vo.entity.hasPublishedVersion ? 'published' : 'unpublished';
	var html = '
 '
			+ ' '
			+ vo.entity.title
			+ '';
	if (vo.children.list.length > 0) {
		html += '
';
		$.each(vo.children.list, function(n, value) {
			html += renderPage(value);
		});
		html += '
';
	}
	return html + '
';
}
<commit_msg>http://code.google.com/p/vosao/issues/detail?id=156<commit_after>/**
 * Vosao CMS. Simple CMS for Google App Engine.
 * Copyright (C) 2009 Vosao development team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) 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 General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * email: vosao.dev@gmail.com
 */

var rootFolder;
var browserMode = 'ckeditor';

$(function(){
    $("#tabs").tabs();
	Vosao.initJSONRpc(loadData);
    if (Vosao.getQueryParam('mode')) {
    	browserMode = Vosao.getQueryParam('mode');
    }
    window.scrollbars.visible = true;
});

function loadData() {
	loadFolderTree();
	loadTree();
}

function loadFolderTree() {
	Vosao.jsonrpc.folderService.getTree(function(rootItem) {
        rootFolder = rootItem;
        $("#folders-tree").html(renderFolderList(rootItem));
       	$("#folders-tree").treeview();
       	selectFolder();
    });
}

function selectFolder() {
   	if ($.cookie('fileBrowserPath')) {
   		Vosao.jsonrpc.folderService.getFolderByPath(function(r) {
   			if (r) {
   		   		onFolderSelected(r.entity.id);
   			}
   			else {
   		   		onFolderSelected(rootFolder.entity.id);
   			}
   		}, $.cookie('fileBrowserPath'));
		$.cookie('fileBrowserPath', null, {path:'/', expires: 10});
   	}
   	else {
   		onFolderSelected(rootFolder.entity.id);
   	}
}

/**
 * Render ul/li list for folder item and subitems.
 * @param item - java class TreeItemDecorator<FolderEntity>
 */
function renderFolderList(item) {
   	var titleLink = "" + item.entity.title
       	    + "";
    var s = "
" + titleLink;
    if (item.children.list.length > 0) {
        s += "
\n";
        for (var i = 0; i < item.children.list.length; i++) {
            var childItem = item.children.list[i];
            s += renderFolderList(childItem);
        }
        s += "
\n";
    }
    s += "
\n"
    return s;
}

function onFolderSelected(folderId) {
	Vosao.jsonrpc.folderService.getFolderPath(function(folderPath) {
		if (folderPath) {
			$('#currentFolder').html(folderPath);
		}
		else {
			$('#currentFolder').html('/');
		}
		Vosao.jsonrpc.fileService.getByFolder(function(files) {
            var result = "";
            for (i = 0; i < files.list.length; i++) {
                var file = files.list[i];
                var title = " title=\"" + file.title + "\"";
                var onClick = " onclick=\"onFileSelected(" + file.id + ")\"";
                var thumbnail = '';
                if (Vosao.isImage(file.filename)) {
                    thumbnail = '';
                }
                result += "

" + thumbnail
                    + "
" + file.filename
                    + "

\n";
            }
            $("#files").html(result);
        }, folderId);
    }, folderId);
}

function onFileSelected(fileId) {
	Vosao.jsonrpc.fileService.getFilePath(function(path) {
       	if (browserMode == 'ckeditor') {
       		var funcNum = Vosao.getQueryParam('CKEditorFuncNum');
       		window.opener.CKEDITOR.tools.callFunction(funcNum, path);
       		window.close();
       	}
       	if (browserMode == 'page') {
       		window.opener.setResource(path);
       		window.close();
       	}
    }, fileId);
}

function onPageSelected(path) {
   	if (browserMode == 'ckeditor') {
   		var funcNum = Vosao.getQueryParam('CKEditorFuncNum');
   		window.opener.CKEDITOR.tools.callFunction(funcNum, path);
   		window.close();
   	}
   	if (browserMode == 'page') {
   		window.opener.setResource(path);
   		window.close();
   	}
}

function loadTree() {
	Vosao.jsonrpc.pageService.getTree(function(r) {
		$('#pages-tree').html(renderPage(r));
		$("#pages-tree").treeview({
			animated: "fast",
			collapsed: true
		});
	});
}

function renderPage(vo) {
	var pageUrl = vo.entity.friendlyURL;
	var p = vo.entity.hasPublishedVersion ? 'published' : 'unpublished';
	var html = '
 '
			+ ' '
			+ vo.entity.title
			+ '';
	if (vo.children.list.length > 0) {
		html += '
';
		$.each(vo.children.list, function(n, value) {
			html += renderPage(value);
		});
		html += '
';
	}
	return html + '
';
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * Sets up global variables typical in most JavaScript environments.
 *
 * 1. Global timers (via `setTimeout` etc).
 * 2. Global console object.
 * 3. Hooks for printing stack traces with source maps.
 *
 * Leaves enough room in the environment for implementing your own:
 * 1. Require system.
 * 2. Bridged modules.
 *
 * @providesModule InitializeJavaScriptAppEngine
 */

/* eslint global-strict: 0 */
/* globals GLOBAL: true, window: true */

// Just to make sure the JS gets packaged up.
require('RCTDebugComponentOwnership');
require('RCTDeviceEventEmitter');
require('PerformanceLogger');
require('regenerator/runtime');

if (typeof GLOBAL === 'undefined') {
  GLOBAL = this;
}

if (typeof window === 'undefined') {
  window = GLOBAL;
}

function handleError(e, isFatal) {
  try {
    require('ExceptionsManager').handleException(e, isFatal);
  } catch(ee) {
    console.log('Failed to print error: ', ee.message);
  }
}

function setUpRedBoxErrorHandler() {
  var ErrorUtils = require('ErrorUtils');
  ErrorUtils.setGlobalHandler(handleError);
}

function setUpRedBoxConsoleErrorHandler() {
  // ExceptionsManager transitively requires Promise so we install it after
  var ExceptionsManager = require('ExceptionsManager');
  var Platform = require('Platform');
  // TODO (#6925182): Enable console.error redbox on Android
  if (__DEV__ && Platform.OS === 'ios') {
    ExceptionsManager.installConsoleErrorReporter();
  }
}

function setupFlowChecker() {
  if (__DEV__) {
    var checkFlowAtRuntime = require('checkFlowAtRuntime');
    checkFlowAtRuntime();
  }
}

/**
 * Sets up a set of window environment wrappers that ensure that the
 * BatchedBridge is flushed after each tick. In both the case of the
 * `UIWebView` based `RCTJavaScriptCaller` and `RCTContextCaller`, we
 * implement our own custom timing bridge that should be immune to
 * unexplainably dropped timing signals.
 */
function setUpTimers() {
  var JSTimers = require('JSTimers');
  GLOBAL.setTimeout = JSTimers.setTimeout;
  GLOBAL.setInterval = JSTimers.setInterval;
  GLOBAL.setImmediate = JSTimers.setImmediate;
  GLOBAL.clearTimeout = JSTimers.clearTimeout;
  GLOBAL.clearInterval = JSTimers.clearInterval;
  GLOBAL.clearImmediate = JSTimers.clearImmediate;
  GLOBAL.cancelAnimationFrame = JSTimers.clearInterval;
  GLOBAL.requestAnimationFrame = function(cb) {
    /*requestAnimationFrame() { [native code] };*/  // Trick scroller library
    return JSTimers.requestAnimationFrame(cb);      // into thinking it's native
  };
}

function setUpAlert() {
  var RCTAlertManager = require('NativeModules').AlertManager;
  if (!GLOBAL.alert) {
    GLOBAL.alert = function(text) {
      var alertOpts = {
        title: 'Alert',
        message: '' + text,
        buttons: [{'cancel': 'OK'}],
      };
      RCTAlertManager.alertWithArgs(alertOpts, function () {});
    };
  }
}

function setUpPromise() {
  // The native Promise implementation throws the following error:
  // ERROR: Event loop not supported.
  GLOBAL.Promise = require('Promise');
}

function setUpXHR() {
  // The native XMLHttpRequest in Chrome dev tools is CORS aware and won't
  // let you fetch anything from the internet
  GLOBAL.XMLHttpRequest = require('XMLHttpRequest');
  GLOBAL.FormData = require('FormData');

  var fetchPolyfill = require('fetch');
  GLOBAL.fetch = fetchPolyfill.fetch;
  GLOBAL.Headers = fetchPolyfill.Headers;
  GLOBAL.Request = fetchPolyfill.Request;
  GLOBAL.Response = fetchPolyfill.Response;
}

function setUpGeolocation() {
  GLOBAL.navigator = GLOBAL.navigator || {};
  GLOBAL.navigator.geolocation = require('Geolocation');
}

function setUpWebSockets() {
  GLOBAL.WebSocket = require('WebSocket');
}

function setupProfile() {
  console.profile = console.profile || GLOBAL.consoleProfile || function () {};
  console.profileEnd = console.profileEnd || GLOBAL.consoleProfileEnd || function () {};
  require('BridgeProfiling').swizzleReactPerf();
}

function setUpProcessEnv() {
  GLOBAL.process = {env: {NODE_ENV: __DEV__ ? 'development' : 'production'}};
}

setUpRedBoxErrorHandler();
setUpTimers();
setUpAlert();
setUpPromise();
setUpXHR();
setUpRedBoxConsoleErrorHandler();
setUpGeolocation();
setUpWebSockets();
setupProfile();
setUpProcessEnv();
setupFlowChecker();
<commit_msg>Update `GLOBAL.process` instead of over-writing during initialization.<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * Sets up global variables typical in most JavaScript environments.
 *
 * 1. Global timers (via `setTimeout` etc).
 * 2. Global console object.
 * 3. Hooks for printing stack traces with source maps.
 *
 * Leaves enough room in the environment for implementing your own:
 * 1. Require system.
 * 2. Bridged modules.
 *
 * @providesModule InitializeJavaScriptAppEngine
 */

/* eslint global-strict: 0 */
/* globals GLOBAL: true, window: true */

// Just to make sure the JS gets packaged up.
require('RCTDebugComponentOwnership');
require('RCTDeviceEventEmitter');
require('PerformanceLogger');
require('regenerator/runtime');

if (typeof GLOBAL === 'undefined') {
  GLOBAL = this;
}

if (typeof window === 'undefined') {
  window = GLOBAL;
}

function handleError(e, isFatal) {
  try {
    require('ExceptionsManager').handleException(e, isFatal);
  } catch(ee) {
    console.log('Failed to print error: ', ee.message);
  }
}

function setUpRedBoxErrorHandler() {
  var ErrorUtils = require('ErrorUtils');
  ErrorUtils.setGlobalHandler(handleError);
}

function setUpRedBoxConsoleErrorHandler() {
  // ExceptionsManager transitively requires Promise so we install it after
  var ExceptionsManager = require('ExceptionsManager');
  var Platform = require('Platform');
  // TODO (#6925182): Enable console.error redbox on Android
  if (__DEV__ && Platform.OS === 'ios') {
    ExceptionsManager.installConsoleErrorReporter();
  }
}

function setupFlowChecker() {
  if (__DEV__) {
    var checkFlowAtRuntime = require('checkFlowAtRuntime');
    checkFlowAtRuntime();
  }
}

/**
 * Sets up a set of window environment wrappers that ensure that the
 * BatchedBridge is flushed after each tick. In both the case of the
 * `UIWebView` based `RCTJavaScriptCaller` and `RCTContextCaller`, we
 * implement our own custom timing bridge that should be immune to
 * unexplainably dropped timing signals.
 */
function setUpTimers() {
  var JSTimers = require('JSTimers');
  GLOBAL.setTimeout = JSTimers.setTimeout;
  GLOBAL.setInterval = JSTimers.setInterval;
  GLOBAL.setImmediate = JSTimers.setImmediate;
  GLOBAL.clearTimeout = JSTimers.clearTimeout;
  GLOBAL.clearInterval = JSTimers.clearInterval;
  GLOBAL.clearImmediate = JSTimers.clearImmediate;
  GLOBAL.cancelAnimationFrame = JSTimers.clearInterval;
  GLOBAL.requestAnimationFrame = function(cb) {
    /*requestAnimationFrame() { [native code] };*/  // Trick scroller library
    return JSTimers.requestAnimationFrame(cb);      // into thinking it's native
  };
}

function setUpAlert() {
  var RCTAlertManager = require('NativeModules').AlertManager;
  if (!GLOBAL.alert) {
    GLOBAL.alert = function(text) {
      var alertOpts = {
        title: 'Alert',
        message: '' + text,
        buttons: [{'cancel': 'OK'}],
      };
      RCTAlertManager.alertWithArgs(alertOpts, function () {});
    };
  }
}

function setUpPromise() {
  // The native Promise implementation throws the following error:
  // ERROR: Event loop not supported.
  GLOBAL.Promise = require('Promise');
}

function setUpXHR() {
  // The native XMLHttpRequest in Chrome dev tools is CORS aware and won't
  // let you fetch anything from the internet
  GLOBAL.XMLHttpRequest = require('XMLHttpRequest');
  GLOBAL.FormData = require('FormData');

  var fetchPolyfill = require('fetch');
  GLOBAL.fetch = fetchPolyfill.fetch;
  GLOBAL.Headers = fetchPolyfill.Headers;
  GLOBAL.Request = fetchPolyfill.Request;
  GLOBAL.Response = fetchPolyfill.Response;
}

function setUpGeolocation() {
  GLOBAL.navigator = GLOBAL.navigator || {};
  GLOBAL.navigator.geolocation = require('Geolocation');
}

function setUpWebSockets() {
  GLOBAL.WebSocket = require('WebSocket');
}

function setupProfile() {
  console.profile = console.profile || GLOBAL.consoleProfile || function () {};
  console.profileEnd = console.profileEnd || GLOBAL.consoleProfileEnd || function () {};
  require('BridgeProfiling').swizzleReactPerf();
}

function setUpProcessEnv() {
  GLOBAL.process = GLOBAL.process || {};
  GLOBAL.process.env = {NODE_ENV: __DEV__ ? 'development' : 'production'};
}

setUpRedBoxErrorHandler();
setUpTimers();
setUpAlert();
setUpPromise();
setUpXHR();
setUpRedBoxConsoleErrorHandler();
setUpGeolocation();
setUpWebSockets();
setupProfile();
setUpProcessEnv();
setupFlowChecker();
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/* init table sorter defaults */
if ( $.tablesorter ) {
	$.tablesorter.defaults.cssAsc  = 'headerSortUp ui-state-focus';
	$.tablesorter.defaults.cssDesc = 'headerSortDown ui-state-focus';
	$.tablesorter.defaults.header  = 'header ui-widget-header';
	$.tablesorter.defaults.widgets = ['zebra'];
	$.tablesorter.defaults.widgetZebra = {
		css : ["odd ui-state-default", "even ui-state-default"]
	};
}

/* initializes static widgets */
function initStaticWidgets(elem) {
	// hover states on the static widgets - form elements
	var el = elem ? $(elem) : $(document);
	el.find('button, input[type!=checkbox], .dynhover').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	).addClass('ui-state-default ui-corner-all');
	// fix attribute selector in IE
	el.find('input[type=text], input[type=password], input[type=file]').addClass('inputText');

	// make buttones nicer by applying equal width - not working in IE ;(
	el.find('button, input[type=submit], input[type=reset], input[type=button]').each(function(i) {
		var txt = $(this).text();
		var apply = txt && txt.length > 1;
		if (apply) $(this).css('min-width', '8em');
	});

	// add default table styling - colors and fonts from the theme
	el.find('table.nicetable').addClass('ui-widget');
	el.find('table.nicetable th').addClass('ui-widget-header');

	// add default styling for table sorter
	el.find("table.tablesorter tbody").addClass("ui-widget-content");

	// add theme styling to the status line
	el.find('.statline').addClass('ui-state-highlight')

	el.find('table.tablesorter').trigger("update").trigger("applyWidgets");
}

/* automatically executed on load */
$(document).ready(function() {
	// init table-sorter tables - only once!
	var tables = $('table.tablesorter:not(.noauto)');
	if (tables.size() > 0) tables.tablesorter();

	// init navigation
	$('#technav div.ui-state-default').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	);

	// register global ajax error handler
	$(document).ajaxError( function(event, req) {
		var text = req.responseXML ? x = req.responseXML :
				(req.responseText ? x = req.responseText : req.statusText);
		Xalert('The request failed:

' + text + '
', 'AJAX Error');
	});

	initStaticWidgets();
});

/* A helper function, used together with tablesorter, when the cells contains mixed text and links. As example:
	elem.tablesorter({
		textExtraction: mixedLinksExtraction
	});
*/
function mixedLinksExtraction(node) {
	var l = node.getElementsByTagName('a');
	return l && l.length > 0 ? l[0].innerHTML : node.innerHTML;
};

/* Java-like MessageFormat method. Usage:
	'hello {0}'.msgFormat('world')
*/
String.prototype.msgFormat = function(/* variable arguments*/) {
	var i=0; var s=this;
	while(i<arguments.length) s=s.replace('{'+i+'}',arguments[i++]);
	return s;
}

/* replacement for confirm() method, needs 'action' parameter to work.
 * if action is not set - then default confirm() method is used. */
function Xconfirm(/* String */text, /* Callback function */action, /* String */title) {
	if (!$.isFunction(action)) return confirm(text);
	if (title === undefined) title = "";

	Xdialog(text).dialog({
		modal: true,
		title: title,
		buttons: {
			"Yes": function() {
				$(this).dialog('close');
				action();
			},
			"No": function() {
				$(this).dialog('close');
			}
		}
	});
	return false;
}
function Xalert(/* String */text, /* String */title) {
	if (title === undefined) title = "";

	Xdialog(text).dialog({
		modal: true,
		title: title,
		width: '70%',
		buttons: {
			"Ok": function() {
				$(this).dialog('close');
			}
		}
	});
	return false;
}
/* a helper function used by Xconfirm & Xalert */
function Xdialog(text) {
	var dialog = $('#dialog'); // use existing dialog element

	if ( dialog.size() == 0 ) { // doesn't exists
		var element = document.createElement( 'div' );
		$('body').append(element);
		dialog = $(element);
	}

	// init dialog
	dialog.html(text).dialog('destroy'); // set text & reset dialog
	return dialog;
}

/* String */ function wordWrap( /* String */ msg ) {
	var userAgent = navigator.userAgent.toLowerCase();
	var isMozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );

	return isMozilla ? msg.split('').join(String.fromCharCode('8203')) : msg;
}

/* content of the old ui.js */

/* Element */ function clearChildren( /* Element */ element ) {
	while (element.firstChild) {
		element.removeChild(element.firstChild);
	}
	return element;
}

/* String */ function serialize( /* Element */ element ) {
	var result = "";

	if (element) {
		if (element.nodeValue) {
			result = element.nodeValue;
		} else {
			result += "<" + element.tagName;

			var attrs = element.attributes;
			for (var i=0; i < attrs.length; i++) {
				if (attrs[i].nodeValue) {
					result += " " + attrs[i].nodeName + "='" + attrs[i].nodeValue + "'";
				}
			}

			var children = element.childNodes;
			if (children && children.length) {
				result += ">";

				for (var i=0; i < children.length; i++) {
					result += serialize( children[i] );
				}
				result += "</" + element.tagName + ">";
			} else {
				result += "/>";
			}
		}
	}

	return result;
}

/* Element */ function th( /* String */ cssClass, /* Map */ attrs, /* Element[] */ children ) {
	return createElement( "th", cssClass, attrs, children );
}

/* Element */ function tr( /* String */ cssClass, /* Map */ attrs, /* Element[] */ children ) {
	return createElement( "tr", cssClass, attrs, children );
}

/* Element */ function td( /* String */ cssClass, /* Map */ attrs, /* Element[] */ children ) {
	return createElement( "td", cssClass, attrs, children );
}

/* Element */ function text( /* String */ textValue ) {
	return document.createTextNode( textValue );
}

/* Element */ function createElement( /* String */ name, /* String */ cssClass, /* Map */ attrs, /* Element[] */ children  ) {
	var sb = ["<", name];

	if (attrs && attrs.name) {
		sb.push(" name='", attrs.name, "'");
	}

	if (attrs && attrs.type) {
		sb.push(" type='", attrs.type, "'");
	}

	sb.push(">");

	var el = $(sb.join(""));

	if (cssClass) {
		el.addClass(cssClass);
	}
	if (attrs) {
		for (var lab in attrs) {
			if ("style" == lab) {
				var styles = attrs[lab];
				for (var styleName in styles) {
					el.css(styleName, styles[styleName]);
				}
			} else if ("name" == lab || "type" == lab) {
				//skip
			} else {
				el.attr( lab, attrs[lab] );
			}
		}
	}

	var element = el.get()[0];

	if (children && children.length) {
		for (var i=0; i < children.length; i++) {
			element.appendChild( children[i] );
		}
	}

	return element;
}

/* Element */ function addText( /* Element */ element, /* String */ textValue ) {
	if (element && textValue) {
		element.appendChild( text( textValue ) );
	}
	return element;
}

/**
 * Sets the name cookie at the appRoot (/system/console by default) path
 * to last for 20 years.
 * @param name The name of the cookie
 * @param value The value for the cookie
 */
function setCookie( /* String */name, /* String */value) {
	var date = new Date();
	date.setFullYear(date.getFullYear() + 20);
	$.cookies.del("felix-webconsole-" + name);
	$.cookies.set("felix-webconsole-" + name, value, {
		expiresAt : date,
		path : appRoot
	});
}

/**
 * Returns the value of the name cookie or nothing if the cookie does
 * not exist or is not accessible.
 * @param name The name of the cookie
 */
/* String */ function getCookie(/*String */name) {
    return $.cookies.get("felix-webconsole-" + name);
}

// language selection element
var langSelect = false;
$(document).ready(function() {
	langSelect = $('#langSelect').hover(
		function() { $(this).find('.flags').show('blind') },
		function() { $(this).find('.flags').hide('blind') });
	langSelect.find('.flags img').click(function() {
		setCookie("locale", $(this).attr('alt'));
		location.reload();
	});
	var locale = getCookie("locale");
	if (locale) {
		if ( !$.datepicker.regional[locale] ) locale = '';
		$.datepicker.setDefaults($.datepicker.regional[locale]);
	}
});
<commit_msg>Fixed FELIX-3404 Web Admin Log Plugin stops listing of log entries if message is null. https://issues.apache.org/jira/browse/FELIX-3404<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/* init table sorter defaults */
if ( $.tablesorter ) {
	$.tablesorter.defaults.cssAsc  = 'headerSortUp ui-state-focus';
	$.tablesorter.defaults.cssDesc = 'headerSortDown ui-state-focus';
	$.tablesorter.defaults.header  = 'header ui-widget-header';
	$.tablesorter.defaults.widgets = ['zebra'];
	$.tablesorter.defaults.widgetZebra = {
		css : ["odd ui-state-default", "even ui-state-default"]
	};
}

/* initializes static widgets */
function initStaticWidgets(elem) {
	// hover states on the static widgets - form elements
	var el = elem ? $(elem) : $(document);
	el.find('button, input[type!=checkbox], .dynhover').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	).addClass('ui-state-default ui-corner-all');
	// fix attribute selector in IE
	el.find('input[type=text], input[type=password], input[type=file]').addClass('inputText');

	// make buttones nicer by applying equal width - not working in IE ;(
	el.find('button, input[type=submit], input[type=reset], input[type=button]').each(function(i) {
		var txt = $(this).text();
		var apply = txt && txt.length > 1;
		if (apply) $(this).css('min-width', '8em');
	});

	// add default table styling - colors and fonts from the theme
	el.find('table.nicetable').addClass('ui-widget');
	el.find('table.nicetable th').addClass('ui-widget-header');

	// add default styling for table sorter
	el.find("table.tablesorter tbody").addClass("ui-widget-content");

	// add theme styling to the status line
	el.find('.statline').addClass('ui-state-highlight')

	el.find('table.tablesorter').trigger("update").trigger("applyWidgets");
}

/* automatically executed on load */
$(document).ready(function() {
	// init table-sorter tables - only once!
	var tables = $('table.tablesorter:not(.noauto)');
	if (tables.size() > 0) tables.tablesorter();

	// init navigation
	$('#technav div.ui-state-default').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	);

	// register global ajax error handler
	$(document).ajaxError( function(event, req) {
		var text = req.responseXML ? x = req.responseXML :
				(req.responseText ? x = req.responseText : req.statusText);
		Xalert('The request failed:

' + text + '
', 'AJAX Error');
	});

	initStaticWidgets();
});

/* A helper function, used together with tablesorter, when the cells contains mixed text and links. As example:
	elem.tablesorter({
		textExtraction: mixedLinksExtraction
	});
*/
function mixedLinksExtraction(node) {
	var l = node.getElementsByTagName('a');
	return l && l.length > 0 ? l[0].innerHTML : node.innerHTML;
};

/* Java-like MessageFormat method. Usage:
	'hello {0}'.msgFormat('world')
*/
String.prototype.msgFormat = function(/* variable arguments*/) {
	var i=0; var s=this;
	while(i<arguments.length) s=s.replace('{'+i+'}',arguments[i++]);
	return s;
}

/* replacement for confirm() method, needs 'action' parameter to work.
 * if action is not set - then default confirm() method is used. */
function Xconfirm(/* String */text, /* Callback function */action, /* String */title) {
	if (!$.isFunction(action)) return confirm(text);
	if (title === undefined) title = "";

	Xdialog(text).dialog({
		modal: true,
		title: title,
		buttons: {
			"Yes": function() {
				$(this).dialog('close');
				action();
			},
			"No": function() {
				$(this).dialog('close');
			}
		}
	});
	return false;
}
function Xalert(/* String */text, /* String */title) {
	if (title === undefined) title = "";

	Xdialog(text).dialog({
		modal: true,
		title: title,
		width: '70%',
		buttons: {
			"Ok": function() {
				$(this).dialog('close');
			}
		}
	});
	return false;
}
/* a helper function used by Xconfirm & Xalert */
function Xdialog(text) {
	var dialog = $('#dialog'); // use existing dialog element

	if ( dialog.size() == 0 ) { // doesn't exists
		var element = document.createElement( 'div' );
		$('body').append(element);
		dialog = $(element);
	}

	// init dialog
	dialog.html(text).dialog('destroy'); // set text & reset dialog
	return dialog;
}

/* String */ function wordWrap( /* String */ msg ) {
	if (msg) {
		var userAgent = navigator.userAgent.toLowerCase();
		var isMozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );

		return isMozilla ? msg.split('').join(String.fromCharCode('8203')) : msg;
	} else {
		return '';
	}
}

/* content of the old ui.js */

/* Element */ function clearChildren( /* Element */ element ) {
	while (element.firstChild) {
		element.removeChild(element.firstChild);
	}
	return element;
}

/* String */ function serialize( /* Element */ element ) {
	var result = "";

	if (element) {
		if (element.nodeValue) {
			result = element.nodeValue;
		} else {
			result += "<" + element.tagName;

			var attrs = element.attributes;
			for (var i=0; i < attrs.length; i++) {
				if (attrs[i].nodeValue) {
					result += " " + attrs[i].nodeName + "='" + attrs[i].nodeValue + "'";
				}
			}

			var children = element.childNodes;
			if (children && children.length) {
				result += ">";

				for (var i=0; i < children.length; i++) {
					result += serialize( children[i] );
				}
				result += "</" + element.tagName + ">";
			} else {
				result += "/>";
			}
		}
	}

	return result;
}

/* Element */ function th( /* String */ cssClass, /* Map */ attrs, /* Element[] */ children ) {
	return createElement( "th", cssClass, attrs, children );
}

/* Element */ function tr( /* String */ cssClass, /* Map */ attrs, /* Element[] */ children ) {
	return createElement( "tr", cssClass, attrs, children );
}

/* Element */ function td( /* String */ cssClass, /* Map */ attrs, /* Element[] */ children ) {
	return createElement( "td", cssClass, attrs, children );
}

/* Element */ function text( /* String */ textValue ) {
	return document.createTextNode( textValue );
}

/* Element */ function createElement( /* String */ name, /* String */ cssClass, /* Map */ attrs, /* Element[] */ children  ) {
	var sb = ["<", name];

	if (attrs && attrs.name) {
		sb.push(" name='", attrs.name, "'");
	}

	if (attrs && attrs.type) {
		sb.push(" type='", attrs.type, "'");
	}

	sb.push(">");

	var el = $(sb.join(""));

	if (cssClass) {
		el.addClass(cssClass);
	}
	if (attrs) {
		for (var lab in attrs) {
			if ("style" == lab) {
				var styles = attrs[lab];
				for (var styleName in styles) {
					el.css(styleName, styles[styleName]);
				}
			} else if ("name" == lab || "type" == lab) {
				//skip
			} else {
				el.attr( lab, attrs[lab] );
			}
		}
	}

	var element = el.get()[0];

	if (children && children.length) {
		for (var i=0; i < children.length; i++) {
			element.appendChild( children[i] );
		}
	}

	return element;
}

/* Element */ function addText( /* Element */ element, /* String */ textValue ) {
	if (element && textValue) {
		element.appendChild( text( textValue ) );
	}
	return element;
}

/**
 * Sets the name cookie at the appRoot (/system/console by default) path
 * to last for 20 years.
 * @param name The name of the cookie
 * @param value The value for the cookie
 */
function setCookie( /* String */name, /* String */value) {
	var date = new Date();
	date.setFullYear(date.getFullYear() + 20);
	$.cookies.del("felix-webconsole-" + name);
	$.cookies.set("felix-webconsole-" + name, value, {
		expiresAt : date,
		path : appRoot
	});
}

/**
 * Returns the value of the name cookie or nothing if the cookie does
 * not exist or is not accessible.
 * @param name The name of the cookie
 */
/* String */ function getCookie(/*String */name) {
    return $.cookies.get("felix-webconsole-" + name);
}

// language selection element
var langSelect = false;
$(document).ready(function() {
	langSelect = $('#langSelect').hover(
		function() { $(this).find('.flags').show('blind') },
		function() { $(this).find('.flags').hide('blind') });
	langSelect.find('.flags img').click(function() {
		setCookie("locale", $(this).attr('alt'));
		location.reload();
	});
	var locale = getCookie("locale");
	if (locale) {
		if ( !$.datepicker.regional[locale] ) locale = '';
		$.datepicker.setDefaults($.datepicker.regional[locale]);
	}
});
<|endoftext|>


<commit_before>// See gregfranko.com/blog/jquery-best-practices
//
// IIFE: Immediately Invoked Function Expression
(function(main_iife_function) {
        main_iife_function(window.jQuery, window, document);
    }(function($,window,document) {
        var unique = function(arr) {
            return arr.filter(function(value, index, array) {
                return array.indexOf(value) === index;
            });
        };
        $(function() {

            // hide/show the time_length_val input depending on the time_length_choice
            cval = $("#id_time_length_choice").val();
            console.log("time_length_val ready, choice val=", cval);
            if (cval === '' || cval === '0') {
                console.log("time_length_val show");
                $( "#id_time_length_val" ).show();
            }
            else {
                console.log("time_length_val hide");
                $( "#id_time_length_val" ).hide();
            }

            // console.log("time is " + (typeof time == "undefined"))

            // var ncharts = $("div[id^='time-series']").length
            // console.log("ncharts=",ncharts)

            console.log("DOM is ready!");

            $("div[id^='time-series']").each(function(index) {

                var vnames =  $( this ).data("variables");
                var vunits =  $( this ).data("units");
                var long_names =  $( this ).data("long_names");
                if (long_names.length == 0) {
                    long_names = vnames;
                }
                console.log("time-series, time.length=",time.length);
                console.log("vnames=",vnames,", vunits=",vunits);

                // series and yAxis are arrays of dictionaries
                var yAxis = [];

                var unique_units = unique(vunits);
                console.log("unique_units=",unique_units);
                var opposite = false;
                for (var unit of unique_units) {
                    console.log("unit=",unit);
                    ya = {
                        opposite: opposite,
                        title: {
                            text: unit,
                        },
                    };
                    yAxis.push(ya);
                    opposite = !opposite;
                }

                var series = [];
                for (var iv = 0; iv < vnames.length; iv++ ) {
                    var vname = vnames[iv];
                    var vunit = vunits[iv];
                    var long_name = long_names[iv];
                    var vseries = {};
                    var vdata = [];
                    for (var i = 0; i < time.length; i++) {
                        // var d = new Date((time0 + time[i])*1000);
                        // d += d.utcOffset
                        vdata.push([(time0 + time[i])*1000, data[vname][i]]);
                    }
                    vseries['data'] = vdata;
                    if (unique_units.length > 1) {
                        vseries['name'] = vname + '(' + vunit + ')';
                    }
                    else {
                        vseries['name'] = vname;
                    }
                    vseries['yAxis'] = unique_units.indexOf(vunit);
                    vseries['tooltip'] = {
                        // valueSuffix: long_name,
                        pointFormat: '\u25CF ' + long_name + ',{series.name}: {point.y}
',
                    };
                    /* a checkbox allows one to "select" the series, but
                     * I'm not sure what that does. Clicking it doesn't
                     * make the series disappear. That is done by clicking
                     * on the name in the legend, which by default goes below
                     * the xaxis.
                     * Supposidly if you return anything other than false,
                     * the default action is to toggle the selected state
                     * of the series.
                        events: {
                            checkboxClick: function (event) {
                                alert('The checkbox is now ' + event.checked);
                                return false;
                            }
                        },
                     */
                    series.push(vseries);
                }

                $( this ).highcharts('StockChart',{
                    chart: {
                        type: 'line',
                        // zoomType: 'x',
                        // panning: true,
                        // panKey: 'shift',
                        spacingLeft: 20,
                        spacingRight: 20,
                        // marginLeft: 20,
                        // marginRight: 20,
                    },
                    xAxis: {
                        type: 'datetime',
                        dateTimeLabelFormats: {
                            millisecond: '%H:%M:%S.%L',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%Y
%m-%d',
                            month: '%Y
%m',
                            year: '%Y'
                        },
                        startOnTick: false,
                        endOnTick: false,
                        title: {
                            text: 'time'
                        },
                    },
                    yAxis: yAxis,
                    series: series,
                    legend: {
                        enabled: true,
                        rtl: false,
                    },
                });
            });

            $("div[id^='heatmap']").each(function(index) {

                var vnames =  $( this ).data("variables");
                var vunits =  $( this ).data("units");
                var long_names = $( this ).data("long_names");

                console.log("heatmap, vnames=",vnames,
                        ",time.length=",time.length,
                        ",dim2.length=",dim2['data'].length);

                if (long_names.length == 0) {
                    long_names = vnames;
                }

                // var vname =  $( this ).data("variable");
                // var units =  $( this ).data("units");
                // var long_name =  $( this ).data("long_name");
                // var dim2_name =  $( this ).data("dim2_name");
                var dim2_name = dim2['name'];
                var dim2_units = dim2['units'];

                for (var iv = 0; iv < vnames.length; iv++) {
                    vname = vnames[iv];
                    long_name = long_names[iv];
                    units = vunits[iv];

                    minval = Number.POSITIVE_INFINITY;
                    maxval = Number.NEGATIVE_INFINITY;

                    var datetime = true;

                    if (datetime) {
                        mintime = (time0 + time[0]) * 1000;
                        maxtime = (time0 + time[time.length-1]) * 1000;
                    }
                    else {
                        // mintime = time[0] * 1000;
                        // maxtime = time[time.length-1] * 1000;
                        mintime = time[0];
                        maxtime = time[time.length-1];
                    }

                    mindim2 = dim2['data'][0];
                    maxdim2 = dim2['data'][dim2['data'].length-1];

                    var chart_data = [];
                    for (var i = 0; i < time.length; i++) {
                        if (datetime) {
                            var tx = (time0 + time[i]) * 1000;
                        }
                        else {
                            // var tx = time[i] * 1000;
                            var tx = time[i];
                        }
                        for (var j = 0; j < dim2['data'].length; j++) {
                            dx = data[vname][i][j];
                            if (dx !== null) {
                                minval = Math.min(minval,dx);
                                maxval = Math.max(maxval,dx);
                            }
                            chart_data.push([tx, dim2['data'][j],dx]);
                        }
                    }
                    console.log("heatmap, chart_data.length=",chart_data.length,
                            ", chart_data[0].length=",chart_data[0].length);
                    console.log("heatmap, minval=",minval,", maxval=",maxval);

                    console.log("heatmap, colsize=", (maxtime - mintime) / 20);
                    // var colsize = 3600 * 1000;
                    var colsize = (maxtime - mintime) / (time.length - 1);
                    var rowsize = (maxdim2 - mindim2) / (dim2.length - 1);

                    /*
                    for (var i = 0; i < chart_data.length; i++) {
                        if (chart_data[i][2] === null) {
                            chart_data[i][2] = minval;
                        }
                    }
                    */

                    for (var i = 0; i < chart_data.length && i < 10; i++) {
                        for (var j = 0; j < chart_data[i].length; j++) {
                            console.log("chart_data[",i,"]=",
                                chart_data[i][0],",",chart_data[i][1],",",chart_data[i][2]);
                        }
                    }

                    $( this ).highcharts({
                        chart: {
                            type: 'heatmap',
                            marginTop: 40,
                            marginBottom: 40,
                            zoomType: 'x',
                            panning: true,
                            panKey: 'shift',
                        },
                        title: {
                            text: long_name + '(' + units + ')'
                        },
                        xAxis: {
                            type: 'datetime',
                            dateTimeLabelFormats: {
                                millisecond: '%H:%M:%S.%L',
                                second: '%H:%M:%S',
                                minute: '%H:%M',
                                hour: '%H:%M',
                                day: '%Y
%m-%d',
                                month: '%Y
%m',
                                year: '%Y'
                            },
                            /*
                            min: mintime,
                            max: maxtime,
                            */
                            title: {
                                text: 'time'
                            },
                            /*
                            tickPixelInterval: (maxtime - mintime) / 100,
                            ordinal: false,
                            */
                        },
                        yAxis: {
                            title: {
                                text: dim2_name + '(' + dim2_units + ')'
                            },
                            min: mindim2,
                            max: maxdim2,
                            tickWidth: 2,
                            /*
                            ordinal: false,
                            */
                        },
                        colorAxis: {
                            stops: [
                                [0, '#3060cf'],
                                [0.5, '#fffbbc'],
                                [0.9, '#c4463a']
                            ],
                            min: minval,
                            max: maxval,
                            // minColor: '#FFFFFF',
                            // maxColor: Highcharts.getOptions().colors[0]
                        },
                        legend: {
                            title: vname,
                            reversed: true,
                            align: 'right',
                            layout: 'vertical',
                            margin: 15,
                            verticalAlign: 'bottom'
                        },
                        series:[{
                            data: chart_data,
                            colsize: colsize,
                            rowsize: rowsize,
                            tooltip: {
                                enabled: true,
                                /*
                                headerFormat: vname + "
",
                                */
                                headerFormat: '',
                                pointFormat: 'time:{point.x:%H:%M},' + dim2_name + ':{point.y},' + vname + ':{point.value}'
                            }
                        }],
                    });
                }
            });
            $("div[id^='hc-time-series']").each(function(index) {

                var vname =  $( this ).data("variable");
                var units =  $( this ).data("units");
                var long_name =  $( this ).data("long_name");
                if (long_name.length == 0) {
                    long_name = vname;
                }

                console.log("time-series, time.length=",time.length,
                        ",data.length=",data.length);

                var chart_data = [];
                for (var i = 0; i < time.length; i++) {
                    // var d = new Date((time0 + time[i])*1000);
                    // d += d.utcOffset
                    chart_data.push([(time0 + time[i])*1000, data[vname][i]]);
                }

                $( this ).highcharts({
                    chart: {
                        type: 'line',
                        zoomType: 'x',
                        panning: true,
                        panKey: 'shift',
                        marginLeft: 100,
                    },
                    title: {
                        text: long_name
                    },
                    xAxis: {
                        type: 'datetime',
                        dateTimeLabelFormats: {
                            millisecond: '%H:%M:%S.%L',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%e. %b',
                            month: '%b \'%y',
                            year: '%Y'
                        },
                        title: {
                            text: 'time'
                        },
                    },
                    yAxis: {
                        title: {
                            text: vname + '(' + units + ')'
                        },
                    },
                    series:[{
                        data: chart_data
                    }],
                });
            });
            /*
            $("#id_time_length_choice").change(function() {
                console.log("time_length_choice change, val=",$(this).val());
                if ($(this).val() == '0' || $(this).val() == '') {
                    $("#id_time_length_val").show();
                }
                else {
                    $("#id_time_length_val").hide();
                }
            });
            */
        });
    })
);

<commit_msg>Remove unused hc-time-series function. Set valueDecimals: 6.<commit_after>// See gregfranko.com/blog/jquery-best-practices
//
// IIFE: Immediately Invoked Function Expression
(function(main_iife_function) {
        main_iife_function(window.jQuery, window, document);
    }(function($,window,document) {
        var unique = function(arr) {
            return arr.filter(function(value, index, array) {
                return array.indexOf(value) === index;
            });
        };
        $(function() {

            // hide/show the time_length_val input depending on the time_length_choice
            cval = $("#id_time_length_choice").val();
            console.log("time_length_val ready, choice val=", cval);
            if (cval === '' || cval === '0') {
                console.log("time_length_val show");
                $( "#id_time_length_val" ).show();
            }
            else {
                console.log("time_length_val hide");
                $( "#id_time_length_val" ).hide();
            }

            // console.log("time is " + (typeof time == "undefined"))

            // var ncharts = $("div[id^='time-series']").length
            // console.log("ncharts=",ncharts)

            console.log("DOM is ready!");

            $("div[id^='time-series']").each(function(index) {

                var vnames =  $( this ).data("variables");
                var vunits =  $( this ).data("units");
                var long_names =  $( this ).data("long_names");
                if (long_names.length == 0) {
                    long_names = vnames;
                }
                console.log("time-series, time.length=",time.length);
                console.log("vnames=",vnames,", vunits=",vunits);

                // series and yAxis are arrays of dictionaries
                var yAxis = [];

                var unique_units = unique(vunits);
                console.log("unique_units=",unique_units);
                var opposite = false;
                for (var unit of unique_units) {
                    console.log("unit=",unit);
                    ya = {
                        opposite: opposite,
                        title: {
                            text: unit,
                        },
                    };
                    yAxis.push(ya);
                    opposite = !opposite;
                }

                var series = [];
                for (var iv = 0; iv < vnames.length; iv++ ) {
                    var vname = vnames[iv];
                    var vunit = vunits[iv];
                    var long_name = long_names[iv];
                    var vseries = {};
                    var vdata = [];
                    for (var i = 0; i < time.length; i++) {
                        // var d = new Date((time0 + time[i])*1000);
                        // d += d.utcOffset
                        vdata.push([(time0 + time[i])*1000, data[vname][i]]);
                    }
                    vseries['data'] = vdata;
                    if (unique_units.length > 1) {
                        vseries['name'] = vname + '(' + vunit + ')';
                    }
                    else {
                        vseries['name'] = vname;
                    }
                    vseries['yAxis'] = unique_units.indexOf(vunit);
                    vseries['tooltip'] = {
                        // valueSuffix: long_name,
                        pointFormat: '\u25CF ' + long_name + ',{series.name}: {point.y}
',
                        valueDecimals: 6,
                    };
                    /* a checkbox allows one to "select" the series, but
                     * I'm not sure what that does. Clicking it doesn't
                     * make the series disappear. That is done by clicking
                     * on the name in the legend, which by default goes below
                     * the xaxis.
                     * Supposidly if you return anything other than false,
                     * the default action is to toggle the selected state
                     * of the series.
                        events: {
                            checkboxClick: function (event) {
                                alert('The checkbox is now ' + event.checked);
                                return false;
                            }
                        },
                     */
                    series.push(vseries);
                }

                $( this ).highcharts('StockChart',{
                    chart: {
                        type: 'line',
                        // zoomType: 'x',
                        // panning: true,
                        // panKey: 'shift',
                        spacingLeft: 20,
                        spacingRight: 20,
                        // marginLeft: 20,
                        // marginRight: 20,
                    },
                    xAxis: {
                        type: 'datetime',
                        dateTimeLabelFormats: {
                            millisecond: '%H:%M:%S.%L',
                            second: '%H:%M:%S',
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%Y
%m-%d',
                            month: '%Y
%m',
                            year: '%Y'
                        },
                        startOnTick: false,
                        endOnTick: false,
                        title: {
                            text: 'time'
                        },
                    },
                    yAxis: yAxis,
                    series: series,
                    legend: {
                        enabled: true,
                        rtl: false,
                    },
                });
            });

            $("div[id^='heatmap']").each(function(index) {

                var vnames =  $( this ).data("variables");
                var vunits =  $( this ).data("units");
                var long_names = $( this ).data("long_names");

                console.log("heatmap, vnames=",vnames,
                        ",time.length=",time.length,
                        ",dim2.length=",dim2['data'].length);

                if (long_names.length == 0) {
                    long_names = vnames;
                }

                // var vname =  $( this ).data("variable");
                // var units =  $( this ).data("units");
                // var long_name =  $( this ).data("long_name");
                // var dim2_name =  $( this ).data("dim2_name");
                var dim2_name = dim2['name'];
                var dim2_units = dim2['units'];

                for (var iv = 0; iv < vnames.length; iv++) {
                    vname = vnames[iv];
                    long_name = long_names[iv];
                    units = vunits[iv];

                    minval = Number.POSITIVE_INFINITY;
                    maxval = Number.NEGATIVE_INFINITY;

                    var datetime = true;

                    if (datetime) {
                        mintime = (time0 + time[0]) * 1000;
                        maxtime = (time0 + time[time.length-1]) * 1000;
                    }
                    else {
                        // mintime = time[0] * 1000;
                        // maxtime = time[time.length-1] * 1000;
                        mintime = time[0];
                        maxtime = time[time.length-1];
                    }

                    mindim2 = dim2['data'][0];
                    maxdim2 = dim2['data'][dim2['data'].length-1];

                    var chart_data = [];
                    for (var i = 0; i < time.length; i++) {
                        if (datetime) {
                            var tx = (time0 + time[i]) * 1000;
                        }
                        else {
                            // var tx = time[i] * 1000;
                            var tx = time[i];
                        }
                        for (var j = 0; j < dim2['data'].length; j++) {
                            dx = data[vname][i][j];
                            if (dx !== null) {
                                minval = Math.min(minval,dx);
                                maxval = Math.max(maxval,dx);
                            }
                            chart_data.push([tx, dim2['data'][j],dx]);
                        }
                    }
                    console.log("heatmap, chart_data.length=",chart_data.length,
                            ", chart_data[0].length=",chart_data[0].length);
                    console.log("heatmap, minval=",minval,", maxval=",maxval);

                    console.log("heatmap, colsize=", (maxtime - mintime) / 20);
                    // var colsize = 3600 * 1000;
                    var colsize = (maxtime - mintime) / (time.length - 1);
                    var rowsize = (maxdim2 - mindim2) / (dim2.length - 1);

                    /*
                    for (var i = 0; i < chart_data.length; i++) {
                        if (chart_data[i][2] === null) {
                            chart_data[i][2] = minval;
                        }
                    }
                    */

                    for (var i = 0; i < chart_data.length && i < 10; i++) {
                        for (var j = 0; j < chart_data[i].length; j++) {
                            console.log("chart_data[",i,"]=",
                                chart_data[i][0],",",chart_data[i][1],",",chart_data[i][2]);
                        }
                    }

                    $( this ).highcharts({
                        chart: {
                            type: 'heatmap',
                            marginTop: 40,
                            marginBottom: 40,
                            zoomType: 'x',
                            panning: true,
                            panKey: 'shift',
                        },
                        title: {
                            text: long_name + '(' + units + ')'
                        },
                        xAxis: {
                            type: 'datetime',
                            dateTimeLabelFormats: {
                                millisecond: '%H:%M:%S.%L',
                                second: '%H:%M:%S',
                                minute: '%H:%M',
                                hour: '%H:%M',
                                day: '%Y
%m-%d',
                                month: '%Y
%m',
                                year: '%Y'
                            },
                            /*
                            min: mintime,
                            max: maxtime,
                            */
                            title: {
                                text: 'time'
                            },
                            /*
                            tickPixelInterval: (maxtime - mintime) / 100,
                            ordinal: false,
                            */
                        },
                        yAxis: {
                            title: {
                                text: dim2_name + '(' + dim2_units + ')'
                            },
                            min: mindim2,
                            max: maxdim2,
                            tickWidth: 2,
                            /*
                            ordinal: false,
                            */
                        },
                        colorAxis: {
                            stops: [
                                [0, '#3060cf'],
                                [0.5, '#fffbbc'],
                                [0.9, '#c4463a']
                            ],
                            min: minval,
                            max: maxval,
                            // minColor: '#FFFFFF',
                            // maxColor: Highcharts.getOptions().colors[0]
                        },
                        legend: {
                            title: vname,
                            reversed: true,
                            align: 'right',
                            layout: 'vertical',
                            margin: 15,
                            verticalAlign: 'bottom'
                        },
                        series:[{
                            data: chart_data,
                            colsize: colsize,
                            rowsize: rowsize,
                            tooltip: {
                                enabled: true,
                                /*
                                headerFormat: vname + "
",
                                */
                                headerFormat: '',
                                pointFormat: 'time:{point.x:%H:%M},' + dim2_name + ':{point.y},' + vname + ':{point.value}'
                            }
                        }],
                    });
                }
            });
            /*
            $("#id_time_length_choice").change(function() {
                console.log("time_length_choice change, val=",$(this).val());
                if ($(this).val() == '0' || $(this).val() == '') {
                    $("#id_time_length_val").show();
                }
                else {
                    $("#id_time_length_val").hide();
                }
            });
            */
        });
    })
);

<|endoftext|>


<commit_before>function logTestModule(module){
  console.log('\n==========\n' + module + '\n==========\n')
}
function logTestProto(proto){
  console.log('==> ' + proto)
}
var MAGNET = "magnet:?xt=urn:btih:6a9759bffd5c0af65319979fb7832189f4f3c35d&dn=sintel.mp4&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&tr=wss%3A%2F%2Ftracker.webtorrent.io&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel-1024-surround.mp4"

/*
* TEST LOG
*/
logTestModule('Log')
var Log = require('./log.js')

logTestProto('print')
Log.print('Print ok')

logTestProto('echo')
Log.echo('Echo ok')

/*
* TEST CLIENT
*/
logTestModule('Client')
var Client = require('./client.js')
var c = new Client()

logTestProto('on start')
c.on('start', function(hash){
  console.log('Client start trigger')
  console.log('Hash: ' + hash)

  logTestProto('getTorrent')
  var torrent = c.getTorrent()
  console.log('Torrent: ')
  console.log(torrent)
})

logTestProto('on download')
c.on('download', function(torrent){
  console.log('Client download trigger')
  console.log('Torrent: ')
  console.log(torrent)

  logTestProto('stop')
  c.stop()
})

logTestProto('on done')
c.on('done', function(hash, name){
  console.log('Client done trigger')
  console.log('Hash: ' + hash + '\nName: ' + name)
})

c.download(MAGNET)
<commit_msg>delete instances<commit_after>function logTestModule(module){
  console.log('\n==========\n' + module + '\n==========\n')
}
function logTestProto(proto){
  console.log('==> ' + proto)
}
var MAGNET = "magnet:?xt=urn:btih:6a9759bffd5c0af65319979fb7832189f4f3c35d&dn=sintel.mp4&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&tr=wss%3A%2F%2Ftracker.webtorrent.io&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel-1024-surround.mp4"

/*
* TEST LOG
*/
logTestModule('Log')
var Log = require('./log.js')

logTestProto('print')
Log.print('Print ok')

logTestProto('echo')
Log.echo('Echo ok')

delete Log
/*
* TEST CLIENT
*/
logTestModule('Client')
var Client = require('./client.js')
var c = new Client()

logTestProto('on start')
c.on('start', function(hash){
  console.log('Client start trigger')
  console.log('Hash: ' + hash)

  logTestProto('getTorrent')
  var torrent = c.getTorrent()
  console.log('Torrent: ')
  console.log(torrent)
})

logTestProto('on download')
c.on('download', function(torrent){
  console.log('Client download trigger')
  console.log('Torrent: ')
  console.log(torrent)

  logTestProto('stop')
  c.stop()
})

logTestProto('on done')
c.on('done', function(hash, name){
  console.log('Client done trigger')
  console.log('Hash: ' + hash + '\nName: ' + name)
})

c.download(MAGNET)

delete Client
delete c
<|endoftext|>


<commit_before>import defRules from './rules'
import {
  devices
}  from './util'

const allDevices = Object.keys(devices).map(key => devices[key])

const severity = function (val) {
  switch (val) {
    case 0:
    case 'off':
      return 'off'

    case 1:
    case 'warn':
      return 'warn'

    case 2:
    case 'error':
      return 'error'

    default:
      throw new Error(`react-a11y: invalid severity ${val}`)
  }
}

const normalize = function (opts = 'off') {
  if ( Array.isArray(opts) ) {
    opts[0] = severity(opts[0])
    return opts
  } else {
    return [ severity(opts) ]
  }
}

export default class Suite {

  constructor (React, ReactDOM, options) {
    this.options  = options
    this.React    = React
    this.ReactDOM = ReactDOM

    if (!this.React && !this.React.createElement) {
      throw new Error('Missing parameter: React')
    }

    const {
      plugins = []
    } = this.options

    // prepare all rules by including every plugin and saving their rules
    // namespaced like plugin/rule
    this.rules = plugins
      .map(function (name) {
        try {
          const mod   = require(`react-a11y-plugin-${name}`)
          const rules = 'default' in mod ? mod.default : mod
          return Object.keys(rules).reduce((acc, key) => ({
              ...acc
            , [`${name}/${key}`]: rules[key]
            }), {})
        } catch (err) {
          throw new Error(`Could not find react-a11y-plugin-${name}`)
        }
      })
      .reduce((acc, next) => ({ ...acc, ...next }), defRules)
  }

  test (tagName, props, children, done) {
    Object.keys(this.options.rules)
      .forEach(function (key) {
          // find ruleopts
          const opts = normalize(this.options.rules[key])
          const [
            sev
          , ...options
          ] = opts

          if ( sev !== 'off' ) {
            const ctx = {
              report (info) {
                const {
                  devices = allDevices
                } = info

                // TODO: fix this and failureHandler to accept all info
                // TODO: add ability to ignore by device class
                done({
                  ...info
                , tagName
                , props
                , severity: sev
                })
              }
            , options
            , React:    this.React
            , ReactDOM: this.ReactDOM
            }

            if ( !(key in this.rules) ) {
              throw new Error(`react-a11y: rule ${key} not found,`
                            + `maybe you're missing a plugin?`)
            }

            const tests = this.rules[key](ctx)

            if ( tagName in tests ) {
              tests[tagName](props, children)
            } else if ( '_any_' in tests ) {
              tests._any_(tagName, props, children)
            }
          }
      }.bind(this))
  }
}
<commit_msg>add rule name to reporter info<commit_after>import defRules from './rules'
import {
  devices
}  from './util'

const allDevices = Object.keys(devices).map(key => devices[key])

const severity = function (val) {
  switch (val) {
    case 0:
    case 'off':
      return 'off'

    case 1:
    case 'warn':
      return 'warn'

    case 2:
    case 'error':
      return 'error'

    default:
      throw new Error(`react-a11y: invalid severity ${val}`)
  }
}

const normalize = function (opts = 'off') {
  if ( Array.isArray(opts) ) {
    opts[0] = severity(opts[0])
    return opts
  } else {
    return [ severity(opts) ]
  }
}

export default class Suite {

  constructor (React, ReactDOM, options) {
    this.options  = options
    this.React    = React
    this.ReactDOM = ReactDOM

    if (!this.React && !this.React.createElement) {
      throw new Error('Missing parameter: React')
    }

    const {
      plugins = []
    } = this.options

    // prepare all rules by including every plugin and saving their rules
    // namespaced like plugin/rule
    this.rules = plugins
      .map(function (name) {
        try {
          const mod   = require(`react-a11y-plugin-${name}`)
          const rules = 'default' in mod ? mod.default : mod
          return Object.keys(rules).reduce((acc, key) => ({
              ...acc
            , [`${name}/${key}`]: rules[key]
            }), {})
        } catch (err) {
          throw new Error(`Could not find react-a11y-plugin-${name}`)
        }
      })
      .reduce((acc, next) => ({ ...acc, ...next }), defRules)
  }

  test (tagName, props, children, done) {
    Object.keys(this.options.rules)
      .forEach(function (key) {
          // find ruleopts
          const opts = normalize(this.options.rules[key])
          const [
            sev
          , ...options
          ] = opts

          if ( sev !== 'off' ) {
            const ctx = {
              report (info) {
                const {
                  devices = allDevices
                } = info

                // TODO: fix this and failureHandler to accept all info
                // TODO: add ability to ignore by device class
                done({
                  ...info
                , tagName
                , props
                , severity: sev
                , rule: key
                })
              }
            , options
            , React:    this.React
            , ReactDOM: this.ReactDOM
            }

            if ( !(key in this.rules) ) {
              throw new Error(`react-a11y: rule ${key} not found,`
                            + `maybe you're missing a plugin?`)
            }

            const tests = this.rules[key](ctx)

            if ( tagName in tests ) {
              tests[tagName](props, children)
            } else if ( '_any_' in tests ) {
              tests._any_(tagName, props, children)
            }
          }
      }.bind(this))
  }
}
<|endoftext|>


<commit_before>jQuery(function ($) {

	// make columns selection draggable
    $('body.page-find .columns-overlay ul').sortable();

    // show/hide columns selection
    $('body.page-find .columns-select').click(function () {
        $('body.page-find .columns-overlay').toggle();
        return false;
    });

    // activate filter after click on

    $('body.page-find .filters li span').click(function () {
        var input = $(this).prev('input[type="checkbox"]');
        if (input.attr('checked')) {
        	input.removeAttr('checked');
        } else {
        	input.attr('checked', 'checked');
        }
    });

    // show filter after click on <select>
    $('body.page-find .filter-selector').change(function () {
        $('body.page-find .filter-' + $(this).val()).slideDown();
        $('body.page-find .filter-selector option[value="'+$(this).val()+'"]').attr('disabled', 'disabled');
        $(this).val('');
    });

    // hide filter on clear
    $('body.page-find .clear').click(function () {
    	var div = $(this).closest('div');
        div.slideUp('fast');
        $('input', div).attr('disabled', 'disabled');
        $('#search-form').submit();
        return false;
    });

    var map;
    var latlng = new google.maps.LatLng(46.8, 8.233333); // CH
    var myOptions = {
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        maxZoom: 18,
        minZoom: 5,
        mapTypeControl: false,
        zoom: 8
    };
    var overlay;
    var control;

    // show map
    $('body.page-find .map-select').click(function () {
        $('body.page-find .map-overlay').css('left', '50%');

        // init map for area selection
        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);

        // geometry control to draw on map
        control = new GeometryControl(map, function () {
            if (overlay) {
                overlay.overlay.setMap(null);
            }
        });

        //create searchbar
        var searchBar = document.createElement('div');
	    var inputSearch = document.createElement('input');
	    searchBar.appendChild(inputSearch);
	    searchBar.setAttribute('id', 'search_container');
	    inputSearch.setAttribute('id', 'search_input');
		map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBar);
		var ac = new google.maps.places.Autocomplete(inputSearch, {
			types : [ 'geocode' ]
		});
		ac.bindTo('bounds', map);

		google.maps.event.addListener(ac, 'place_changed', function() {
			var place = ac.getPlace();
			if (place.geometry.viewport) {
				map.fitBounds(place.geometry.viewport);
			} else {
				map.setCenter(place.geometry.location);
				map.setZoom(17);
			}
		});

		inputSearch.onfocus = function(){
			inputSearch.value = '';
		}

		google.maps.event.addListener(map, 'bounds_changed', function() {
			inputSearch.blur();
		});

		google.maps.event.addDomListener(inputSearch, 'keydown', function(e) {
			var key = e.keyCode ? e.keyCode : e.charCode;
            if (key == 13) {
            	if (e.preventDefault) {
            		e.preventDefault();
            	} else {
            		e.cancelBubble = true;
            		e.returnValue = false;
            	}
            }
		});

        control.addPolygon(function () {
            // don't hide polygon
            control.overlay.overlay.setMap(map);
            control.overlay.overlay.getPath().forEach(function (position) {
            	$('#search-form').append('<input type="hidden" name="geo[]" value="' + position.toUrlValue() + '" />')
            });
        	$('#search-form').submit();
        });

        // add overlay if geo is set
        if (Drupal.settings.find.geo.length > 1) {

            var path = [];
            for (var i = 0, l = Drupal.settings.find.geo.length; i < l; i++) {
                var values = Drupal.settings.find.geo[i].split(',');
                path.push(new google.maps.LatLng(values[0], values[1]));
            }

            overlay = new Polygon(map);
            overlay.overlay.setPath(path);
            map.fitBounds(overlay.getBounds());
        }
    });
    $('body.page-find .map-overlay .map-close').click(function () {
        $('.map-overlay').css('left', '-9000px');
    });
});
<commit_msg>reformatted<commit_after>jQuery(function($) {

	// make columns selection draggable
	$('body.page-find .columns-overlay ul').sortable();

	// show/hide columns selection
	$('body.page-find .columns-select').click(function() {
		$('body.page-find .columns-overlay').toggle();
		return false;
	});
	// activate filter after click on

	$('body.page-find .filters li span').click(function() {
		var input = $(this).prev('input[type="checkbox"]');
		if(input.attr('checked')) {
			input.removeAttr('checked');
		} else {
			input.attr('checked', 'checked');
		}
	});
	// show filter after click on <select>
	$('body.page-find .filter-selector').change(function() {
		$('body.page-find .filter-' + $(this).val()).slideDown();
		$('body.page-find .filter-selector option[value="' + $(this).val() + '"]').attr('disabled', 'disabled');
		$(this).val('');
	});
	// hide filter on clear
	$('body.page-find .clear').click(function() {
		var div = $(this).closest('div');
		div.slideUp('fast');
		$('input', div).attr('disabled', 'disabled');
		$('#search-form').submit();
		return false;
	});
	var map;
	var latlng = new google.maps.LatLng(46.8, 8.233333);
	// CH
	var myOptions = {
		center : latlng,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		maxZoom : 18,
		minZoom : 5,
		mapTypeControl : false,
		zoom : 8
	};
	var overlay;
	var control;

	// show map
	$('body.page-find .map-select').click(function() {
		$('body.page-find .map-overlay').css('left', '50%');

		// init map for area selection
		map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);

		// geometry control to draw on map
		control = new GeometryControl(map, function() {
			if(overlay) {
				overlay.overlay.setMap(null);
			}
		});
		//create searchbar
		var searchBar = document.createElement('div');
		var inputSearch = document.createElement('input');
		searchBar.appendChild(inputSearch);
		searchBar.setAttribute('id', 'search_container');
		inputSearch.setAttribute('id', 'search_input');
		map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBar);
		var ac = new google.maps.places.Autocomplete(inputSearch, {
			types : ['geocode']
		});
		ac.bindTo('bounds', map);

		google.maps.event.addListener(ac, 'place_changed', function() {
			var place = ac.getPlace();
			if(place.geometry.viewport) {
				map.fitBounds(place.geometry.viewport);
			} else {
				map.setCenter(place.geometry.location);
				map.setZoom(17);
			}
		});

		inputSearch.onfocus = function() {
			inputSearch.value = '';
		}

		google.maps.event.addListener(map, 'bounds_changed', function() {
			inputSearch.blur();
		});

		google.maps.event.addDomListener(inputSearch, 'keydown', function(e) {
			var key = e.keyCode ? e.keyCode : e.charCode;
			if(key == 13) {
				if(e.preventDefault) {
					e.preventDefault();
				} else {
					e.cancelBubble = true;
					e.returnValue = false;
				}
			}
		});

		control.addPolygon(function() {
			// don't hide polygon
			control.overlay.overlay.setMap(map);
			control.overlay.overlay.getPath().forEach(function(position) {
				$('#search-form').append('<input type="hidden" name="geo[]" value="' + position.toUrlValue() + '" />')
			});
			$('#search-form').submit();
		});
		// add overlay if geo is set
		if(Drupal.settings.find.geo.length > 1) {

			var path = [];
			for(var i = 0, l = Drupal.settings.find.geo.length; i < l; i++) {
				var values = Drupal.settings.find.geo[i].split(',');
				path.push(new google.maps.LatLng(values[0], values[1]));
			}
			overlay = new Polygon(map);
			overlay.overlay.setPath(path);
			map.fitBounds(overlay.getBounds());
		}
	});
	$('body.page-find .map-overlay .map-close').click(function() {
		$('.map-overlay').css('left', '-9000px');
	});
});
<|endoftext|>