More eslint fixes; eslint in php; add eslint to travis (#2419)

* Add eslint to travis.yml

* Update eslint package versions and apply new indent rules

* Enable the brace-style and block-style eslint rules

* Enable the 'curly' eslint rule

* Enable the 'keyword-spacing' eslint rule

* Enable the 'key-spacing' eslint rule

* Enable the 'object-curly-spacing' eslint rule

* Enable the 'no-new-object' eslint rule

* Only disable the no-caller eslint rule in the one affected file

* Enable the 'no-unused-vars' eslint rule for local variables

* Add linting of JS in .php files
This commit is contained in:
Matt N 2019-01-19 07:32:40 -08:00 committed by Isaac Connor
parent 35fb4366b6
commit a1a42345e3
40 changed files with 1335 additions and 1095 deletions

View File

@ -2,7 +2,7 @@
# libraries # libraries
web/api/lib web/api/lib
web/includes/csrf/csrf-magic.js web/includes/csrf/
web/js/videojs.zoomrotate.js web/js/videojs.zoomrotate.js
web/skins/classic/js/bootstrap.js web/skins/classic/js/bootstrap.js
web/skins/classic/js/chosen web/skins/classic/js/chosen
@ -13,3 +13,7 @@ web/skins/classic/js/jquery.js
web/skins/classic/js/moment.js web/skins/classic/js/moment.js
web/skins/classic/js/video.js web/skins/classic/js/video.js
web/tools/mootools web/tools/mootools
# Cannot be parsed as JS
web/skins/classic/includes/export_functions.php
web/skins/classic/views/events.php

View File

@ -5,26 +5,46 @@ module.exports = {
"browser": true, "browser": true,
}, },
"extends": ["google"], "extends": ["google"],
"overrides": [{
// eslint-plugin-html handles eol-last slightly different - it applies to
// each set of script tags, so we turn it off here.
"files": "**/*.*php",
"rules": {
"eol-last": "off",
"indent": "off",
},
}],
"plugins": [
"html",
"php-markup",
],
"rules": { "rules": {
"brace-style": "off",
"camelcase": "off", "camelcase": "off",
"comma-dangle": "off", "comma-dangle": "off",
"guard-for-in": "off", "guard-for-in": "off",
"key-spacing": "off",
"max-len": "off", "max-len": "off",
"new-cap": ["error", { "new-cap": ["error", {
capIsNewExceptions: ["Error", "Warning", "Debug", "Polygon_calcArea", "Play", "Stop"], capIsNewExceptions: ["Error", "Warning", "Debug", "Polygon_calcArea", "Play", "Stop"],
newIsCapExceptionPattern: "^Asset\.." newIsCapExceptionPattern: "^Asset\.."
}], }],
"no-array-constructor": "off", "no-array-constructor": "off",
"no-caller": "off", "no-unused-vars": ["error", {
"no-new-object": "off", "vars": "local",
"no-unused-vars": "off", "args": "none",
"ignoreRestSiblings": false
}],
"no-var": "off", "no-var": "off",
"object-curly-spacing": "off",
"prefer-rest-params": "off", "prefer-rest-params": "off",
"quotes": "off", "quotes": "off",
"require-jsdoc": "off", "require-jsdoc": "off",
"spaced-comment": "off", "spaced-comment": "off",
}, },
"settings": {
"php/php-extensions": [".php"],
"php/markup-replacement": {"php": "", "=": "0"},
"php/keep-eol": false,
"php/remove-whitespace": false,
"php/remove-empty-line": false,
"php/remove-php-lint": false
},
}; };

View File

@ -32,24 +32,28 @@ install:
- update-binfmts --enable qemu-arm - update-binfmts --enable qemu-arm
env: env:
global: - SMPFLAGS=-j4 OS=el DIST=7
- SMPFLAGS=-j4 - SMPFLAGS=-j4 OS=fedora DIST=27 DOCKER_REPO=knnniggett/packpack
matrix: - SMPFLAGS=-j4 OS=fedora DIST=28 DOCKER_REPO=knnniggett/packpack
- OS=el DIST=7 - SMPFLAGS=-j4 OS=fedora DIST=29 DOCKER_REPO=knnniggett/packpack
- OS=fedora DIST=27 DOCKER_REPO=knnniggett/packpack - SMPFLAGS=-j4 OS=ubuntu DIST=trusty
- OS=fedora DIST=28 DOCKER_REPO=knnniggett/packpack - SMPFLAGS=-j4 OS=ubuntu DIST=xenial
- OS=fedora DIST=29 DOCKER_REPO=knnniggett/packpack - SMPFLAGS=-j4 OS=ubuntu DIST=trusty ARCH=i386
- OS=ubuntu DIST=trusty - SMPFLAGS=-j4 OS=ubuntu DIST=xenial ARCH=i386
- OS=ubuntu DIST=xenial - SMPFLAGS=-j4 OS=raspbian DIST=stretch ARCH=armhf DOCKER_REPO=knnniggett/packpack
- OS=ubuntu DIST=trusty ARCH=i386
- OS=ubuntu DIST=xenial ARCH=i386
- OS=raspbian DIST=stretch ARCH=armhf DOCKER_REPO=knnniggett/packpack
compiler: compiler:
- gcc - gcc
services: services:
- mysql - mysql
- docker - docker
jobs:
include:
- name: eslint
install: npm install -g eslint@5.12.0 eslint-config-google@0.11.0 eslint-plugin-html@5.0.0 eslint-plugin-php-markup@0.2.5
script: eslint --ext .php,.js .
script: script:
- utils/packpack/startpackpack.sh - utils/packpack/startpackpack.sh
@ -65,4 +69,3 @@ deploy:
script: utils/packpack/rsync_xfer.sh script: utils/packpack/rsync_xfer.sh
on: on:
branch: master branch: master

View File

@ -1,8 +1,20 @@
'use strict'; 'use strict';
var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor);
}
} return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor;
};
}();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Server = function() { var Server = function() {
function Server(json) { function Server(json) {

View File

@ -17,105 +17,103 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// //
if ( !window.console ) if ( !window.console ) {
{
window.console = window.console =
{ {
init:function() {}, init: function() {},
log:function() {}, log: function() {},
debug:function() {}, debug: function() {},
info:function() {}, info: function() {},
warn:function() {}, warn: function() {},
error:function() {} error: function() {}
}; };
} }
if ( !console.debug )//IE8 has console but doesn't have console.debug so lets alias it. if ( !console.debug ) {
// IE8 has console but doesn't have console.debug so lets alias it.
console.debug = console.log; console.debug = console.log;
}
var reportLogs = true; var reportLogs = true;
var debugParms; var debugParms;
var debugReq; var debugReq;
function logReport( level, message, file, line ) function logReport( level, message, file, line ) {
{ if ( !reportLogs ) {
if ( !reportLogs )
return; return;
}
if ( typeof(MooTools) == "undefined" ) if ( typeof(MooTools) == "undefined" ) {
return; return;
}
if ( arguments && arguments.callee && arguments.callee.caller && arguments.callee.caller.name ) /* eslint-disable no-caller */
if ( arguments && arguments.callee && arguments.callee.caller && arguments.callee.caller.name ) {
message += ' - '+arguments.callee.caller.caller.name+'()'; message += ' - '+arguments.callee.caller.caller.name+'()';
}
/* eslint-enable no-caller */
if ( !debugReq ) if ( !debugReq ) {
{ if ( Browser ) {
if ( Browser )
debugParms = "view=request&request=log&task=create&browser[name]="+Browser.name+"&browser[version]="+Browser.version+"&browser[platform]="+(Browser.Platform?Browser.Platform.name:'unknown'); debugParms = "view=request&request=log&task=create&browser[name]="+Browser.name+"&browser[version]="+Browser.version+"&browser[platform]="+(Browser.Platform?Browser.Platform.name:'unknown');
else } else {
debugParms = "view=request&request=log&task=create&browser[name]=unknown&browser[version]=unknown&browser[platform]=unknown"; debugParms = "view=request&request=log&task=create&browser[name]=unknown&browser[version]=unknown&browser[platform]=unknown";
debugReq = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'chain' } ); }
debugReq = new Request.JSON( {url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'chain'} );
} }
var requestParms = debugParms; var requestParms = debugParms;
requestParms += "&level="+level+"&message="+encodeURIComponent(message); requestParms += "&level="+level+"&message="+encodeURIComponent(message);
if ( file ) if ( file ) {
requestParms += "&file="+file; requestParms += "&file="+file;
else if ( location.search ) { } else if ( location.search ) {
//location.search is the querystring part, so ?blah=blah but there is almost never any value to this //location.search is the querystring part, so ?blah=blah but there is almost never any value to this
requestParms += "&file="+location.search; requestParms += "&file="+location.search;
} }
if ( line ) if ( line ) {
requestParms += "&line="+line; requestParms += "&line="+line;
}
debugReq.send( requestParms ); debugReq.send( requestParms );
} }
function Panic( message ) function Panic( message ) {
{
console.error( message ); console.error( message );
logReport( "PNC", message ); logReport( "PNC", message );
alert( "PANIC: "+message ); alert( "PANIC: "+message );
} }
function Fatal( message ) function Fatal( message ) {
{
console.error( message ); console.error( message );
logReport( "FAT", message ); logReport( "FAT", message );
alert( "FATAL: "+message ); alert( "FATAL: "+message );
} }
function Error( message ) function Error( message ) {
{
console.error( message ); console.error( message );
logReport( "ERR", message ); logReport( "ERR", message );
} }
function Warning( message ) function Warning( message ) {
{
console.warn( message ); console.warn( message );
logReport( "WAR", message ); logReport( "WAR", message );
} }
function Info( message ) function Info( message ) {
{
console.info( message ); console.info( message );
logReport( "INF", message ); logReport( "INF", message );
} }
function Debug( message ) function Debug( message ) {
{
console.debug( message ); console.debug( message );
//logReport( "DBG", message ); //logReport( "DBG", message );
} }
function Dump( value, label ) function Dump( value, label ) {
{ if ( label ) {
if ( label )
console.debug( label+" => " ); console.debug( label+" => " );
}
console.debug( value ); console.debug( value );
} }
window.onerror = window.onerror =
function( message, url, line ) function( message, url, line ) {
{
logReport( "ERR", message, url, line ); logReport( "ERR", message, url, line );
}; };

View File

@ -6,15 +6,11 @@ var zmMooToolsVersion = '1.3.2';
/* /*
* Firstly, lets check that mootools has been included and thus is present * Firstly, lets check that mootools has been included and thus is present
*/ */
if ( typeof(MooTools) == "undefined" ) if ( typeof(MooTools) == "undefined" ) {
{
alert( "MooTools not found! Please check that it was installed correctly in ZoneMinder web root." ); alert( "MooTools not found! Please check that it was installed correctly in ZoneMinder web root." );
} } else {
else
{
/* Version check */ /* Version check */
if ( MooTools.version < zmMooToolsVersion ) if ( MooTools.version < zmMooToolsVersion ) {
{
alert( "MooTools version "+MooTools.version+" found.\nVersion "+zmMooToolsVersion+" required, please check that it was installed correctly in ZoneMinder web root." ); alert( "MooTools version "+MooTools.version+" found.\nVersion "+zmMooToolsVersion+" required, please check that it was installed correctly in ZoneMinder web root." );
} }
} }

View File

@ -1,52 +1,46 @@
var Overlay = new Class({ var Overlay = new Class({
Implements: [Options, Events], Implements: [Options, Events],
initialize: function( id, options ) initialize: function( id, options ) {
{
this.setOptions( options ); this.setOptions( options );
this.mask = new Mask( document.body, { 'maskMargins': false, 'class': 'overlayMask' } ); this.mask = new Mask( document.body, {'maskMargins': false, 'class': 'overlayMask'} );
this.id = id?id:'overlay'; this.id = id?id:'overlay';
if ( typeOf(this.id) == 'string' ) if ( typeOf(this.id) == 'string' ) {
{ if ( $(this.id) ) {
if ( $(this.id) )
this.element = $(this.id); this.element = $(this.id);
} }
else } else {
{
this.element = this.id; this.element = this.id;
this.id = this.element.get('id'); this.id = this.element.get('id');
} }
if ( !this.element ) if ( !this.element ) {
{ this.element = new Element( 'div', {'id': this.id, 'class': 'overlay', 'styles': {'display': 'none'}} );
this.element = new Element( 'div', { 'id': this.id, 'class': 'overlay', 'styles': { 'display': 'none' } } ); if ( this.options.title || this.options.buttons ) {
if ( this.options.title || this.options.buttons ) var overlayHeader = new Element( 'div', {'class': 'overlayHeader'} );
{ if ( this.options.title ) {
var overlayHeader = new Element( 'div', { 'class': 'overlayHeader' } ); var overlayTitle = new Element( 'div', {'class': 'overlayTitle', 'text': this.options.title} );
if ( this.options.title )
{
var overlayTitle = new Element( 'div', { 'class': 'overlayTitle', 'text': this.options.title } );
overlayHeader.grab( overlayTitle ); overlayHeader.grab( overlayTitle );
} }
if ( this.options.buttons ) if ( this.options.buttons ) {
{ var overlayToolbar = new Element( 'div', {'class': 'overlayToolbar'} );
var overlayToolbar = new Element( 'div', { 'class': 'overlayToolbar' } );
this.options.buttons.each( this.options.buttons.each(
function( button ) function( button ) {
{ var overlayButton = new Element( 'button', {'text': button.text} );
var overlayButton = new Element( 'button', { 'text': button.text } ); if ( button.id ) {
if ( button.id )
overlayButton.setProperty( 'id', button.id ); overlayButton.setProperty( 'id', button.id );
if ( button.events ) }
if ( button.events ) {
overlayButton.set( 'events', events ); overlayButton.set( 'events', events );
}
overlayToolbar.grab( overlayButton ); overlayToolbar.grab( overlayButton );
} }
); );
overlayHeader.grab( overlayTitle ); overlayHeader.grab( overlayTitle );
} }
this.element.grab( overlayHeader ); this.element.grab( overlayHeader );
var overlayBody = new Element( 'div', { 'class': 'overlayBody' } ); var overlayBody = new Element( 'div', {'class': 'overlayBody'} );
var overlayContent = new Element( 'div', { 'class': 'overlayContent' } ); var overlayContent = new Element( 'div', {'class': 'overlayContent'} );
overlayContent.grab( this.options.content ); overlayContent.grab( this.options.content );
overlayBody.grab( overlayContent ); overlayBody.grab( overlayContent );
this.element.grab( overlayBody ); this.element.grab( overlayBody );
@ -55,8 +49,7 @@ var Overlay = new Class({
this.element.inject( this.target ); this.element.inject( this.target );
} }
}, },
show: function() show: function() {
{
this.mask.show(); this.mask.show();
$(window).addEvent( 'resize', this.update.bind(this) ); $(window).addEvent( 'resize', this.update.bind(this) );
$(window).addEvent( 'scroll', this.update.bind(this) ); $(window).addEvent( 'scroll', this.update.bind(this) );
@ -65,30 +58,25 @@ var Overlay = new Class({
this.element.position(); this.element.position();
this.mask.position(); this.mask.position();
}, },
hideComplete: function() hideComplete: function() {
{
$(window).removeEvent( 'resize', this.update.bind(this) ); $(window).removeEvent( 'resize', this.update.bind(this) );
$(window).removeEvent( 'scroll', this.update.bind(this) ); $(window).removeEvent( 'scroll', this.update.bind(this) );
this.element.hide(); this.element.hide();
this.mask.hide(); this.mask.hide();
}, },
hide: function() hide: function() {
{ new Fx.Tween( this.element, {duration: 400, transition: Fx.Transitions.Sine, onComplete: this.hideComplete.bind(this)} ).start( 'opacity', 1.0, 0 );
new Fx.Tween( this.element, { duration: 400, transition: Fx.Transitions.Sine, onComplete: this.hideComplete.bind(this) } ).start( 'opacity', 1.0, 0 );
}, },
update: function() update: function() {
{
this.element.position(); this.element.position();
this.mask.position(); this.mask.position();
}, },
showAnimation:function() showAnimation: function() {
{
showOverlay(); showOverlay();
//console.log( "Showing overlay loading" ); //console.log( "Showing overlay loading" );
if ( !this.loading ) if ( !this.loading ) {
{ this.loading = new Element( 'div', {'id': 'loading'+this.key, 'styles': {'display': 'none'}} );
this.loading = new Element( 'div', { 'id': 'loading'+this.key, 'styles': { 'display':'none' } } );
this.loading.grab( this.loadingImage ); this.loading.grab( this.loadingImage );
document.body.grab( this.loading ); document.body.grab( this.loading );
} }
@ -97,35 +85,36 @@ var Overlay = new Class({
$(window).addEvent( 'resize', this.update.bind(this) ); $(window).addEvent( 'resize', this.update.bind(this) );
$(window).addEvent( 'scroll', this.update.bind(this) ); $(window).addEvent( 'scroll', this.update.bind(this) );
}, },
hideAnimation:function() hideAnimation: function() {
{
$(window).removeEvent( 'resize', this.update.bind(this) ); $(window).removeEvent( 'resize', this.update.bind(this) );
$(window).removeEvent( 'scroll', this.update.bind(this) ); $(window).removeEvent( 'scroll', this.update.bind(this) );
if ( this.loading ) if ( this.loading ) {
this.loading.setStyle( 'display', 'none' ); this.loading.setStyle( 'display', 'none' );
} }
}
}); });
function setupOverlays() function setupOverlays() {
{
try { try {
$$('.overlay').each( $$('.overlay').each(
function( overlay ) function( overlay ) {
{
overlay.element = new Overlay( overlay.get('id') ); overlay.element = new Overlay( overlay.get('id') );
overlay.getElements('.overlayCloser').each( overlay.getElements('.overlayCloser').each(
function( closer ) function( closer ) {
{ closer.addEvent( 'click', function() {
closer.addEvent( 'click', function() { overlay.element.hide(); } ); overlay.element.hide();
} );
} }
); );
overlay.overlayShow = function() { overlay.element.show(); }; overlay.overlayShow = function() {
overlay.overlayHide = function() { overlay.element.hide(); }; overlay.element.show();
};
overlay.overlayHide = function() {
overlay.element.hide();
};
} }
); );
} } catch ( e ) {
catch ( e )
{
alert( e ); alert( e );
} }
} }

View File

@ -286,9 +286,9 @@ function exportEventImages( $event, $exportDetail, $exportFrames, $myfilelist )
* Visit http://www.dynamicdrive.com/ for full source code * Visit http://www.dynamicdrive.com/ for full source code
***********************************************/ ***********************************************/
var eventWidth = <?php echo$event->Width()?>; var eventWidth = <?php echo $event->Width(); ?>;
var eventHeight = <?php echo$event->Height()?>; var eventHeight = <?php echo $event->Height(); ?>;
var variableslide=[<?php echo$slides?>]; var variableslide=[<?php echo $slides; ?>];
//configure the below 3 variables to set the dimension/background color of the slideshow //configure the below 3 variables to set the dimension/background color of the slideshow

View File

@ -121,11 +121,11 @@ echo output_link_if_exists( array(
<script src="<?php echo cache_bust('js/Server.js'); ?>"></script> <script src="<?php echo cache_bust('js/Server.js'); ?>"></script>
<script nonce="<?php echo $cspNonce; ?>"> <script nonce="<?php echo $cspNonce; ?>">
jQuery(document).ready(function(){ jQuery(document).ready(function() {
jQuery("#flip").click(function(){ jQuery("#flip").click(function() {
jQuery("#panel").slideToggle("slow"); jQuery("#panel").slideToggle("slow");
jQuery("#flip").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up'); jQuery("#flip").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
Cookie.write( 'zmHeaderFlip', jQuery('#flip').hasClass('glyphicon-menu-up') ? 'up' : 'down', { duration: 10*365 } ); Cookie.write( 'zmHeaderFlip', jQuery('#flip').hasClass('glyphicon-menu-up') ? 'up' : 'down', {duration: 10*365} );
}); });
}); });
var $j = jQuery.noConflict(); var $j = jQuery.noConflict();

View File

@ -23,51 +23,53 @@
// //
// Javascript window sizes // Javascript window sizes
/* eslint-disable key-spacing */
var popupSizes = { var popupSizes = {
'bandwidth': { 'width': 300, 'height': 200 }, 'bandwidth': {'width': 300, 'height': 200},
'console': { 'width': 750, 'height': 312 }, 'console': {'width': 750, 'height': 312},
'control': { 'width': 380, 'height': 480 }, 'control': {'width': 380, 'height': 480},
'controlcaps': { 'width': 780, 'height': 320 }, 'controlcaps': {'width': 780, 'height': 320},
'controlcap': { 'width': 400, 'height': 400 }, 'controlcap': {'width': 400, 'height': 400},
'cycle': { 'addWidth': 32, 'minWidth': 384, 'addHeight': 62 }, 'cycle': {'addWidth': 32, 'minWidth': 384, 'addHeight': 62},
'device': { 'width': 260, 'height': 150 }, 'device': {'width': 260, 'height': 150},
'devices': { 'width': 400, 'height': 240 }, 'devices': {'width': 400, 'height': 240},
'donate': { 'width': 500, 'height': 280 }, 'donate': {'width': 500, 'height': 280},
'download': { 'width': 350, 'height': 315 }, 'download': {'width': 350, 'height': 315},
'event': { 'addWidth': 108, 'minWidth': 496, 'addHeight': 230, 'minHeight': 540 }, 'event': {'addWidth': 108, 'minWidth': 496, 'addHeight': 230, 'minHeight': 540},
'eventdetail': { 'width': 600, 'height': 420 }, 'eventdetail': {'width': 600, 'height': 420},
'events': { 'width': 1220, 'height': 780 }, 'events': {'width': 1220, 'height': 780},
'export': { 'width': 400, 'height': 340 }, 'export': {'width': 400, 'height': 340},
'filter': { 'width': 900, 'height': 700 }, 'filter': {'width': 900, 'height': 700},
'frame': { 'addWidth': 32, 'minWidth': 384, 'addHeight': 200 }, 'frame': {'addWidth': 32, 'minWidth': 384, 'addHeight': 200},
'frames': { 'addWidth': 600, 'addHeight': 600 }, 'frames': {'addWidth': 600, 'addHeight': 600},
'function': { 'width': 350, 'height': 260 }, 'function': {'width': 350, 'height': 260},
'group': { 'width': 760, 'height': 600 }, 'group': {'width': 760, 'height': 600},
'groups': { 'width': 540, 'height': 420 }, 'groups': {'width': 540, 'height': 420},
'image': { 'addWidth': 48, 'addHeight': 80 }, 'image': {'addWidth': 48, 'addHeight': 80},
'log': { 'width': 1080, 'height': 720 }, 'log': {'width': 1080, 'height': 720},
'login': { 'width': 720, 'height': 480 }, 'login': {'width': 720, 'height': 480},
'logout': { 'width': 260, 'height': 150 }, 'logout': {'width': 260, 'height': 150},
'monitor': { 'width': 800, 'height': 780 }, 'monitor': {'width': 800, 'height': 780},
'monitorpreset':{ 'width': 440, 'height': 210 }, 'monitorpreset':{'width': 440, 'height': 210},
'monitorprobe': { 'width': 500, 'height': 275 }, 'monitorprobe': {'width': 500, 'height': 275},
'monitorselect':{ 'width': 160, 'height': 200 }, 'monitorselect':{'width': 160, 'height': 200},
'montage': { 'width': -1, 'height': -1 }, 'montage': {'width': -1, 'height': -1},
'onvifprobe': { 'width': 700, 'height': 550 }, 'onvifprobe': {'width': 700, 'height': 550},
'optionhelp': { 'width': 400, 'height': 400 }, 'optionhelp': {'width': 400, 'height': 400},
'options': { 'width': 1000, 'height': 660 }, 'options': {'width': 1000, 'height': 660},
'preset': { 'width': 300, 'height': 220 }, 'preset': {'width': 300, 'height': 220},
'server': { 'width': 600, 'height': 405 }, 'server': {'width': 600, 'height': 405},
'settings': { 'width': 220, 'height': 235 }, 'settings': {'width': 220, 'height': 235},
'state': { 'width': 400, 'height': 170 }, 'state': {'width': 400, 'height': 170},
'stats': { 'width': 840, 'height': 200 }, 'stats': {'width': 840, 'height': 200},
'storage': { 'width': 600, 'height': 405 }, 'storage': {'width': 600, 'height': 405},
'timeline': { 'width': 760, 'height': 540 }, 'timeline': {'width': 760, 'height': 540},
'user': { 'width': 360, 'height': 720 }, 'user': {'width': 360, 'height': 720},
'version': { 'width': 360, 'height': 185 }, 'version': {'width': 360, 'height': 185},
'video': { 'width': 420, 'height': 360 }, 'video': {'width': 420, 'height': 360},
'videoview': { 'addWidth': 48, 'addHeight': 80 }, 'videoview': {'addWidth': 48, 'addHeight': 80},
'watch': { 'addWidth': 96, 'minWidth': 420, 'addHeight': 384 }, 'watch': {'addWidth': 96, 'minWidth': 420, 'addHeight': 384},
'zone': { 'addWidth': 520, 'addHeight': 260, 'minHeight': 600 }, 'zone': {'addWidth': 520, 'addHeight': 260, 'minHeight': 600},
'zones': { 'addWidth': 72, 'addHeight': 232 } 'zones': {'addWidth': 72, 'addHeight': 232}
}; };
/* eslint-enable key-spacing */

View File

@ -23,52 +23,54 @@
// //
// Javascript window sizes // Javascript window sizes
/* eslint-disable key-spacing */
var popupSizes = { var popupSizes = {
'bandwidth': { 'width': 300, 'height': 220 }, 'bandwidth': {'width': 300, 'height': 220},
'console': { 'width': 750, 'height': 312 }, 'console': {'width': 750, 'height': 312},
'control': { 'width': 380, 'height': 480 }, 'control': {'width': 380, 'height': 480},
'controlcaps': { 'width': 780, 'height': 320 }, 'controlcaps': {'width': 780, 'height': 320},
'controlcap': { 'width': 400, 'height': 400 }, 'controlcap': {'width': 400, 'height': 400},
'cycle': { 'addWidth': 32, 'minWidth': 384, 'addHeight': 62 }, 'cycle': {'addWidth': 32, 'minWidth': 384, 'addHeight': 62},
'device': { 'width': 260, 'height': 150 }, 'device': {'width': 260, 'height': 150},
'devices': { 'width': 400, 'height': 240 }, 'devices': {'width': 400, 'height': 240},
'donate': { 'width': 500, 'height': 280 }, 'donate': {'width': 500, 'height': 280},
'download': { 'width': 350, 'height': 215 }, 'download': {'width': 350, 'height': 215},
'event': { 'addWidth': 108, 'minWidth': 496, 'addHeight': 230, 'minHeight': 540 }, 'event': {'addWidth': 108, 'minWidth': 496, 'addHeight': 230, 'minHeight': 540},
'eventdetail': { 'width': 600, 'height': 420 }, 'eventdetail': {'width': 600, 'height': 420},
'events': { 'width': 1020, 'height': 780 }, 'events': {'width': 1020, 'height': 780},
'export': { 'width': 400, 'height': 340 }, 'export': {'width': 400, 'height': 340},
'filter': { 'width': 820, 'height': 700 }, 'filter': {'width': 820, 'height': 700},
'frame': { 'addWidth': 32, 'minWidth': 384, 'addHeight': 200 }, 'frame': {'addWidth': 32, 'minWidth': 384, 'addHeight': 200},
'frames': { 'width': 600, 'height': 700 }, 'frames': {'width': 600, 'height': 700},
'function': { 'width': 400, 'height': 250 }, 'function': {'width': 400, 'height': 250},
'group': { 'width': 660, 'height': 520 }, 'group': {'width': 660, 'height': 520},
'groups': { 'width': 440, 'height': 220 }, 'groups': {'width': 440, 'height': 220},
'image': { 'addWidth': 48, 'addHeight': 80 }, 'image': {'addWidth': 48, 'addHeight': 80},
'log': { 'width': 1080, 'height': 720 }, 'log': {'width': 1080, 'height': 720},
'login': { 'width': 720, 'height': 480 }, 'login': {'width': 720, 'height': 480},
'logout': { 'width': 460, 'height': 300 }, 'logout': {'width': 460, 'height': 300},
'monitor': { 'width': 700, 'height': 680 }, 'monitor': {'width': 700, 'height': 680},
'monitorpreset':{ 'width': 440, 'height': 200 }, 'monitorpreset':{'width': 440, 'height': 200},
'monitorprobe': { 'width': 500, 'height': 240 }, 'monitorprobe': {'width': 500, 'height': 240},
'monitorselect':{ 'width': 160, 'height': 200 }, 'monitorselect':{'width': 160, 'height': 200},
'monitors': { 'width': 300, 'height': 640 }, 'monitors': {'width': 300, 'height': 640},
'montage': { 'width': -1, 'height': -1 }, 'montage': {'width': -1, 'height': -1},
'onvifprobe': { 'width': 700, 'height': 550 }, 'onvifprobe': {'width': 700, 'height': 550},
'optionhelp': { 'width': 400, 'height': 320 }, 'optionhelp': {'width': 400, 'height': 320},
'options': { 'width': 1000, 'height': 660 }, 'options': {'width': 1000, 'height': 660},
'preset': { 'width': 300, 'height': 120 }, 'preset': {'width': 300, 'height': 120},
'server': { 'width': 600, 'height': 405 }, 'server': {'width': 600, 'height': 405},
'settings': { 'width': 220, 'height': 225 }, 'settings': {'width': 220, 'height': 225},
'state': { 'width': 370, 'height': 134 }, 'state': {'width': 370, 'height': 134},
'stats': { 'width': 840, 'height': 200 }, 'stats': {'width': 840, 'height': 200},
'storage': { 'width': 600, 'height': 405 }, 'storage': {'width': 600, 'height': 405},
'timeline': { 'width': 760, 'height': 540 }, 'timeline': {'width': 760, 'height': 540},
'user': { 'width': 360, 'height': 720 }, 'user': {'width': 360, 'height': 720},
'version': { 'width': 360, 'height': 140 }, 'version': {'width': 360, 'height': 140},
'video': { 'width': 420, 'height': 360 }, 'video': {'width': 420, 'height': 360},
'videoview': { 'addWidth': 48, 'addHeight': 80 }, 'videoview': {'addWidth': 48, 'addHeight': 80},
'watch': { 'addWidth': 96, 'minWidth': 420, 'addHeight': 384 }, 'watch': {'addWidth': 96, 'minWidth': 420, 'addHeight': 384},
'zone': { 'addWidth': 450, 'addHeight': 200, 'minHeight': 450 }, 'zone': {'addWidth': 450, 'addHeight': 200, 'minHeight': 450},
'zones': { 'addWidth': 72, 'addHeight': 232 } 'zones': {'addWidth': 72, 'addHeight': 232}
}; };
/* eslint-enable key-spacing */

View File

@ -31,42 +31,47 @@ function checkSize() {
var prevW = w; var prevW = w;
var h = window.outerHeight; var h = window.outerHeight;
var prevH = h; var prevH = h;
if (h > screen.availHeight) if (h > screen.availHeight) {
h = screen.availHeight; h = screen.availHeight;
if (w > screen.availWidth) }
if (w > screen.availWidth) {
w = screen.availWidth; w = screen.availWidth;
if (w != prevW || h != prevH) }
if (w != prevW || h != prevH) {
window.resizeTo(w, h); window.resizeTo(w, h);
} }
} }
}
} }
// Deprecated // Deprecated
function newWindow( url, name, width, height ) { function newWindow( url, name, width, height ) {
var windowId = window.open( url, name, popupOptions+",width="+width+",height="+height ); window.open( url, name, popupOptions+",width="+width+",height="+height );
} }
function getPopupSize( tag, width, height ) { function getPopupSize( tag, width, height ) {
if ( typeof popupSizes == 'undefined' ) { if ( typeof popupSizes == 'undefined' ) {
Error( "Can't find any window sizes" ); Error( "Can't find any window sizes" );
return( { 'width': 0, 'height': 0 } ); return ( {'width': 0, 'height': 0} );
} }
var popupSize = Object.clone( popupSizes[tag] ); var popupSize = Object.clone( popupSizes[tag] );
if ( !popupSize ) { if ( !popupSize ) {
Error( "Can't find window size for tag '"+tag+"'" ); Error( "Can't find window size for tag '"+tag+"'" );
return( { 'width': 0, 'height': 0 } ); return ( {'width': 0, 'height': 0} );
} }
if ( popupSize.width && popupSize.height ) { if ( popupSize.width && popupSize.height ) {
if ( width || height ) if ( width || height ) {
Warning( "Ignoring passed dimensions "+width+"x"+height+" when getting popup size for tag '"+tag+"'" ); Warning( "Ignoring passed dimensions "+width+"x"+height+" when getting popup size for tag '"+tag+"'" );
return( popupSize ); }
return ( popupSize );
} }
if ( popupSize.addWidth ) { if ( popupSize.addWidth ) {
popupSize.width = popupSize.addWidth; popupSize.width = popupSize.addWidth;
if ( !width ) if ( !width ) {
Error( "Got addWidth but no passed width when getting popup size for tag '"+tag+"'" ); Error( "Got addWidth but no passed width when getting popup size for tag '"+tag+"'" );
else } else {
popupSize.width += parseInt(width); popupSize.width += parseInt(width);
}
} else if ( width ) { } else if ( width ) {
popupSize.width = width; popupSize.width = width;
Error( "Got passed width but no addWidth when getting popup size for tag '"+tag+"'" ); Error( "Got passed width but no addWidth when getting popup size for tag '"+tag+"'" );
@ -77,10 +82,11 @@ function getPopupSize( tag, width, height ) {
} }
if ( popupSize.addHeight ) { if ( popupSize.addHeight ) {
popupSize.height = popupSize.addHeight; popupSize.height = popupSize.addHeight;
if ( !height ) if ( !height ) {
Error( "Got addHeight but no passed height when getting popup size for tag '"+tag+"'" ); Error( "Got addHeight but no passed height when getting popup size for tag '"+tag+"'" );
else } else {
popupSize.height += parseInt(height); popupSize.height += parseInt(height);
}
} else if ( height ) { } else if ( height ) {
popupSize.height = height; popupSize.height = height;
Error( "Got passed height but no addHeight when getting popup size for tag '"+tag+"'" ); Error( "Got passed height but no addHeight when getting popup size for tag '"+tag+"'" );
@ -89,7 +95,7 @@ function getPopupSize( tag, width, height ) {
Warning( "Adjusting to minimum height ("+popupSize.minHeight+") when getting popup size for tag '"+tag+"' because calculated height is " + popupSize.height ); Warning( "Adjusting to minimum height ("+popupSize.minHeight+") when getting popup size for tag '"+tag+"' because calculated height is " + popupSize.height );
popupSize.height = popupSize.minHeight; popupSize.height = popupSize.minHeight;
} }
return( popupSize ); return ( popupSize );
} }
function zmWindow() { function zmWindow() {
@ -105,10 +111,12 @@ function zmWindow() {
function createPopup( url, name, tag, width, height ) { function createPopup( url, name, tag, width, height ) {
var popupSize = getPopupSize( tag, width, height ); var popupSize = getPopupSize( tag, width, height );
var popupDimensions = ""; var popupDimensions = "";
if ( popupSize.width > 0 ) if ( popupSize.width > 0 ) {
popupDimensions += ",width="+popupSize.width; popupDimensions += ",width="+popupSize.width;
if ( popupSize.height > 0 ) }
if ( popupSize.height > 0 ) {
popupDimensions += ",height="+popupSize.height; popupDimensions += ",height="+popupSize.height;
}
var popup = window.open( url+"&popup=1", name, popupOptions+popupDimensions ); var popup = window.open( url+"&popup=1", name, popupOptions+popupDimensions );
if ( ! popup ) { if ( ! popup ) {
// if popup blocking is enabled, the popup won't be defined. // if popup blocking is enabled, the popup won't be defined.
@ -174,8 +182,9 @@ $j(document).ready(function() {
function createEventPopup( eventId, eventFilter, width, height ) { function createEventPopup( eventId, eventFilter, width, height ) {
var url = '?view=event&eid='+eventId; var url = '?view=event&eid='+eventId;
if ( eventFilter ) if ( eventFilter ) {
url += eventFilter; url += eventFilter;
}
var name = 'zmEvent'; var name = 'zmEvent';
var popupSize = getPopupSize( 'event', width, height ); var popupSize = getPopupSize( 'event', width, height );
var popup = window.open( url, name, popupOptions+",width="+popupSize.width+",height="+popupSize.height ); var popup = window.open( url, name, popupOptions+",width="+popupSize.width+",height="+popupSize.height );
@ -228,16 +237,17 @@ function refreshWindow() {
function refreshParentWindow() { function refreshParentWindow() {
if ( refreshParent ) { if ( refreshParent ) {
if ( window.opener ) { if ( window.opener ) {
if ( refreshParent == true ) if ( refreshParent == true ) {
window.opener.location.reload( true ); window.opener.location.reload( true );
else } else {
window.opener.location.href = refreshParent; window.opener.location.href = refreshParent;
} }
} }
}
} }
if ( currentView != 'none' && currentView != 'login' ) { if ( currentView != 'none' && currentView != 'login' ) {
$j.ajaxSetup({timeout: AJAX_TIMEOUT }); //sets timeout for all getJSON. $j.ajaxSetup({timeout: AJAX_TIMEOUT}); //sets timeout for all getJSON.
$j(document).ready(function() { $j(document).ready(function() {
if ($j('.navbar').length) { if ($j('.navbar').length) {
@ -289,26 +299,29 @@ function secsToTime( seconds ) {
} else if ( seconds < 60*60 ) { } else if ( seconds < 60*60 ) {
var timeMins = parseInt(seconds/60); var timeMins = parseInt(seconds/60);
var timeSecs = seconds%60; var timeSecs = seconds%60;
if ( timeSecs < 10 ) if ( timeSecs < 10 ) {
timeSecs = '0'+timeSecs.toString().substr( 0, 4 ); timeSecs = '0'+timeSecs.toString().substr( 0, 4 );
else } else {
timeSecs = timeSecs.toString().substr( 0, 5 ); timeSecs = timeSecs.toString().substr( 0, 5 );
}
timeString = timeMins+":"+timeSecs; timeString = timeMins+":"+timeSecs;
} else { } else {
var timeHours = parseInt(seconds/3600); var timeHours = parseInt(seconds/3600);
var timeMins = (seconds%3600)/60; var timeMins = (seconds%3600)/60;
var timeSecs = seconds%60; var timeSecs = seconds%60;
if ( timeMins < 10 ) if ( timeMins < 10 ) {
timeMins = '0'+timeMins.toString().substr( 0, 4 ); timeMins = '0'+timeMins.toString().substr( 0, 4 );
else } else {
timeMins = timeMins.toString().substr( 0, 5 ); timeMins = timeMins.toString().substr( 0, 5 );
if ( timeSecs < 10 ) }
if ( timeSecs < 10 ) {
timeSecs = '0'+timeSecs.toString().substr( 0, 4 ); timeSecs = '0'+timeSecs.toString().substr( 0, 4 );
else } else {
timeSecs = timeSecs.toString().substr( 0, 5 ); timeSecs = timeSecs.toString().substr( 0, 5 );
}
timeString = timeHours+":"+timeMins+":"+timeSecs; timeString = timeHours+":"+timeMins+":"+timeSecs;
} }
return( timeString ); return ( timeString );
} }
function submitTab(evt) { function submitTab(evt) {
@ -327,9 +340,11 @@ function submitThisForm() {
function toggleCheckbox( element, name ) { function toggleCheckbox( element, name ) {
var form = element.form; var form = element.form;
var checked = element.checked; var checked = element.checked;
for (var i = 0; i < form.elements.length; i++) for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name.indexOf(name) == 0) if (form.elements[i].name.indexOf(name) == 0) {
form.elements[i].checked = checked; form.elements[i].checked = checked;
}
}
} }
function configureDeleteButton( element ) { function configureDeleteButton( element ) {
@ -349,7 +364,7 @@ function configureDeleteButton( element ) {
} }
function confirmDelete( message ) { function confirmDelete( message ) {
return( confirm( message?message:'Are you sure you wish to delete?' ) ); return ( confirm( message?message:'Are you sure you wish to delete?' ) );
} }
if ( refreshParent ) { if ( refreshParent ) {
@ -369,7 +384,7 @@ function convertLabelFormat(LabelFormat, monitorName) {
//convert label format from strftime to moment's format (modified from //convert label format from strftime to moment's format (modified from
//https://raw.githubusercontent.com/benjaminoakes/moment-strftime/master/lib/moment-strftime.js //https://raw.githubusercontent.com/benjaminoakes/moment-strftime/master/lib/moment-strftime.js
//added %f and %N below (TODO: add %Q) //added %f and %N below (TODO: add %Q)
var replacements = { "a": 'ddd', "A": 'dddd', "b": 'MMM', "B": 'MMMM', "d": 'DD', "e": 'D', "F": 'YYYY-MM-DD', "H": 'HH', "I": 'hh', "j": 'DDDD', "k": 'H', "l": 'h', "m": 'MM', "M": 'mm', "p": 'A', "S": 'ss', "u": 'E', "w": 'd', "W": 'WW', "y": 'YY', "Y": 'YYYY', "z": 'ZZ', "Z": 'z', 'f': 'SS', 'N': "["+monitorName+"]", '%': '%' }; var replacements = {"a": 'ddd', "A": 'dddd', "b": 'MMM', "B": 'MMMM', "d": 'DD', "e": 'D', "F": 'YYYY-MM-DD', "H": 'HH', "I": 'hh', "j": 'DDDD', "k": 'H', "l": 'h', "m": 'MM', "M": 'mm', "p": 'A', "S": 'ss', "u": 'E', "w": 'd', "W": 'WW', "y": 'YY', "Y": 'YYYY', "z": 'ZZ', "Z": 'z', 'f': 'SS', 'N': "["+monitorName+"]", '%': '%'};
var momentLabelFormat = Object.keys(replacements).reduce(function(momentFormat, key) { var momentLabelFormat = Object.keys(replacements).reduce(function(momentFormat, key) {
var value = replacements[key]; var value = replacements[key];
return momentFormat.replace("%" + key, value); return momentFormat.replace("%" + key, value);
@ -389,26 +404,26 @@ function addVideoTimingTrack(video, LabelFormat, monitorName, duration, startTim
} }
} }
/* /*
var labelFormat = convertLabelFormat(LabelFormat, monitorName); var labelFormat = convertLabelFormat(LabelFormat, monitorName);
var webvttformat = 'HH:mm:ss.SSS', webvttdata="WEBVTT\n\n"; var webvttformat = 'HH:mm:ss.SSS', webvttdata="WEBVTT\n\n";
startTime = moment(startTime); startTime = moment(startTime);
var seconds = moment({s:0}), endduration = moment({s:duration}); var seconds = moment({s:0}), endduration = moment({s:duration});
while(seconds.isBefore(endduration)){ while(seconds.isBefore(endduration)){
webvttdata += seconds.format(webvttformat) + " --> "; webvttdata += seconds.format(webvttformat) + " --> ";
seconds.add(1,'s'); seconds.add(1,'s');
webvttdata += seconds.format(webvttformat) + "\n"; webvttdata += seconds.format(webvttformat) + "\n";
webvttdata += startTime.format(labelFormat) + "\n\n"; webvttdata += startTime.format(labelFormat) + "\n\n";
startTime.add(1, 's'); startTime.add(1, 's');
} }
var track = document.createElement('track'); var track = document.createElement('track');
track.kind = "captions"; track.kind = "captions";
track.srclang = "en"; track.srclang = "en";
track.label = "English"; track.label = "English";
track['default'] = true; track['default'] = true;
track.src = 'data:plain/text;charset=utf-8,'+encodeURIComponent(webvttdata); track.src = 'data:plain/text;charset=utf-8,'+encodeURIComponent(webvttdata);
video.appendChild(track); video.appendChild(track);
} }
*/ */
@ -424,7 +439,7 @@ function scaleToFit(baseWidth, baseHeight, scaleEl, bottomEl) {
var ratio = baseWidth / baseHeight; var ratio = baseWidth / baseHeight;
var container = $j('#content'); var container = $j('#content');
var viewPort = $j(window); var viewPort = $j(window);
// jquery does not provide a bottom offet, and offset dows not include margins. outerHeight true minus false gives total vertical margins. // jquery does not provide a bottom offet, and offset dows not include margins. outerHeight true minus false gives total vertical margins.
var bottomLoc = bottomEl.offset().top + (bottomEl.outerHeight(true) - bottomEl.outerHeight()) + bottomEl.outerHeight(true); var bottomLoc = bottomEl.offset().top + (bottomEl.outerHeight(true) - bottomEl.outerHeight()) + bottomEl.outerHeight(true);
var newHeight = viewPort.height() - (bottomLoc - scaleEl.outerHeight(true)); var newHeight = viewPort.height() - (bottomLoc - scaleEl.outerHeight(true));
var newWidth = ratio * newHeight; var newWidth = ratio * newHeight;
@ -433,7 +448,9 @@ function scaleToFit(baseWidth, baseHeight, scaleEl, bottomEl) {
newHeight = newWidth / ratio; newHeight = newWidth / ratio;
} }
var autoScale = Math.round(newWidth / baseWidth * SCALE_BASE); var autoScale = Math.round(newWidth / baseWidth * SCALE_BASE);
var scales = $j('#scale option').map(function() {return parseInt($j(this).val());}).get(); var scales = $j('#scale option').map(function() {
return parseInt($j(this).val());
}).get();
scales.shift(); scales.shift();
var closest; var closest;
$j(scales).each(function() { //Set zms scale to nearest regular scale. Zoom does not like arbitrary scale values. $j(scales).each(function() { //Set zms scale to nearest regular scale. Zoom does not like arbitrary scale values.

View File

@ -1,5 +1,5 @@
var probeReq = new Request.JSON( { url:thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getProbeResponse } ); var probeReq = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getProbeResponse} );
function probe( url_e ) { function probe( url_e ) {
probeReq.send( "request=add_monitors&action=probe&url="+url_e.value ); probeReq.send( "request=add_monitors&action=probe&url="+url_e.value );
@ -22,7 +22,7 @@ function getProbeResponse( respObj, respText ) {
return; return;
} }
results_div.innerHTML = 'No streams found.'; results_div.innerHTML = 'No streams found.';
//console.log("No streams: " + respText); //console.log("No streams: " + respText);
} }
} // end function getProbeResponse } // end function getProbeResponse
@ -37,7 +37,7 @@ function parseStreams( Streams ) {
results_div.innerHTML = ''; results_div.innerHTML = '';
var html = ''; var html = '';
for( i in Streams ) { for ( i in Streams ) {
var stream = Streams[i]; var stream = Streams[i];
if ( stream.url ) { if ( stream.url ) {
html += '<p>'+stream.Monitor.Name + ' at ' + stream.url; html += '<p>'+stream.Monitor.Name + ' at ' + stream.url;
@ -69,10 +69,12 @@ function addMonitor(url) {
popup_url = '?view=monitor&mid='+mid+'&newMonitor[Path]='+url; popup_url = '?view=monitor&mid='+mid+'&newMonitor[Path]='+url;
keys = Object.keys( Monitor ); keys = Object.keys( Monitor );
for ( i in Monitor ) { for ( i in Monitor ) {
if ( ! Monitor[i] ) if ( ! Monitor[i] ) {
continue; continue;
if ( Monitor[i] == 'null' ) }
if ( Monitor[i] == 'null' ) {
Monitor[i]=''; Monitor[i]='';
}
popup_url += '&newMonitor['+i+']='+Monitor[i]; popup_url += '&newMonitor['+i+']='+Monitor[i];
} }
createPopup( popup_url, 'zmMonitor'+mid, 'monitor' ); createPopup( popup_url, 'zmMonitor'+mid, 'monitor' );
@ -84,12 +86,12 @@ function import_csv( form ) {
//formData.append('file', $('#file')[0].files[0]); //formData.append('file', $('#file')[0].files[0]);
$j.ajax({ $j.ajax({
url : thisUrl+"?request=add_monitors&action=import", url: thisUrl+"?request=add_monitors&action=import",
type : 'POST', type: 'POST',
data : formData, data: formData,
processData: false, // tell jQuery not to process the data processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType contentType: false, // tell jQuery not to set contentType
success : function(data) { success: function(data) {
var json = JSON.parse(data); var json = JSON.parse(data);
parseStreams( json.Streams ); parseStreams( json.Streams );
} }

View File

@ -40,7 +40,6 @@ function addMonitor(element) {
function cloneMonitor(element) { function cloneMonitor(element) {
var form = element.form; var form = element.form;
var dupParam;
var monitorId=-1; var monitorId=-1;
// get the value of the first checkbox // get the value of the first checkbox
for ( var i = 0; i < form.elements.length; i++ ) { for ( var i = 0; i < form.elements.length; i++ ) {
@ -79,10 +78,13 @@ function editMonitor( element ) {
//break; //break;
} }
} // end foreach checkboxes } // end foreach checkboxes
if ( monitorIds.length == 1 ) if ( monitorIds.length == 1 ) {
createPopup( '?view=monitor&mid='+monitorIds[0], 'zmMonitor'+monitorIds[0], 'monitor' ); createPopup( '?view=monitor&mid='+monitorIds[0], 'zmMonitor'+monitorIds[0], 'monitor' );
else if ( monitorIds.length > 1 ) } else if ( monitorIds.length > 1 ) {
createPopup( '?view=monitors&'+(monitorIds.map(function(mid) {return 'mids[]='+mid;}).join('&')), 'zmMonitors', 'monitors' ); createPopup( '?view=monitors&'+(monitorIds.map(function(mid) {
return 'mids[]='+mid;
}).join('&')), 'zmMonitors', 'monitors' );
}
} }
function deleteMonitor( element ) { function deleteMonitor( element ) {
@ -116,17 +118,19 @@ function reloadWindow() {
function initPage() { function initPage() {
reloadWindow.periodical( consoleRefreshTimeout ); reloadWindow.periodical( consoleRefreshTimeout );
if ( showVersionPopup ) if ( showVersionPopup ) {
createPopup( '?view=version', 'zmVersion', 'version' ); createPopup( '?view=version', 'zmVersion', 'version' );
if ( showDonatePopup ) }
if ( showDonatePopup ) {
createPopup( '?view=donate', 'zmDonate', 'donate' ); createPopup( '?view=donate', 'zmDonate', 'donate' );
}
// Makes table sortable // Makes table sortable
$j( function() { $j( function() {
$j( "#consoleTableBody" ).sortable({ $j( "#consoleTableBody" ).sortable({
handle: ".glyphicon-sort", handle: ".glyphicon-sort",
update: applySort, update: applySort,
axis:'Y' } ); axis: 'Y'} );
$j( "#consoleTableBody" ).disableSelection(); $j( "#consoleTableBody" ).disableSelection();
} ); } );
} }
@ -135,7 +139,7 @@ function applySort(event, ui) {
var monitor_ids = $j(this).sortable('toArray'); var monitor_ids = $j(this).sortable('toArray');
var ajax = new Request.JSON( { var ajax = new Request.JSON( {
url: 'index.php?request=console', url: 'index.php?request=console',
data: { monitor_ids: monitor_ids, action: 'sort' }, data: {monitor_ids: monitor_ids, action: 'sort'},
method: 'post', method: 'post',
timeout: AJAX_TIMEOUT timeout: AJAX_TIMEOUT
} ); } );

View File

@ -1,9 +1,10 @@
var controlParms = "view=request&request=control"; var controlParms = "view=request&request=control";
var controlReq = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, onSuccess: getControlResponse } ); var controlReq = new Request.JSON( {url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, onSuccess: getControlResponse} );
function getControlResponse( respObj, respText ) { function getControlResponse( respObj, respText ) {
if ( !respObj ) if ( !respObj ) {
return; return;
}
//console.log( respText ); //console.log( respText );
if ( respObj.result != 'Ok' ) { if ( respObj.result != 'Ok' ) {
alert( "Control response was status = "+respObj.status+"\nmessage = "+respObj.message ); alert( "Control response was status = "+respObj.status+"\nmessage = "+respObj.message );
@ -21,18 +22,20 @@ function controlCmd( control, event, xtell, ytell ) {
if ( xtell ) { if ( xtell ) {
var xge = parseInt( (x*100)/coords.width ); var xge = parseInt( (x*100)/coords.width );
if ( xtell == -1 ) if ( xtell == -1 ) {
xge = 100 - xge; xge = 100 - xge;
else if ( xtell == 2 ) } else if ( xtell == 2 ) {
xge = 2*(50 - xge); xge = 2*(50 - xge);
}
locParms += "&xge="+xge; locParms += "&xge="+xge;
} }
if ( ytell ) { if ( ytell ) {
var yge = parseInt( (y*100)/coords.height ); var yge = parseInt( (y*100)/coords.height );
if ( ytell == -1 ) if ( ytell == -1 ) {
yge = 100 - yge; yge = 100 - yge;
else if ( ytell == 2 ) } else if ( ytell == 2 ) {
yge = 2*(50 - yge); yge = 2*(50 - yge);
}
locParms += "&yge="+yge; locParms += "&yge="+yge;
} }
} }

View File

@ -16,8 +16,8 @@ function validateForm( form ) {
if ( errors.length ) { if ( errors.length ) {
alert( errors.join( "\n" ) ); alert( errors.join( "\n" ) );
return( false ); return ( false );
} }
return( true ); return ( true );
} }

View File

@ -1,9 +1,10 @@
function submitForm( element ) { function submitForm( element ) {
var form = element.form; var form = element.form;
if ( form.option.selectedIndex == 0 ) if ( form.option.selectedIndex == 0 ) {
form.view.value = currentView; form.view.value = currentView;
else } else {
form.view.value = 'none'; form.view.value = 'none';
}
form.submit(); form.submit();
} }

View File

@ -6,10 +6,11 @@ var exportTimer = null;
function exportProgress() { function exportProgress() {
var tickerText = $('exportProgressTicker').get('text'); var tickerText = $('exportProgressTicker').get('text');
if ( tickerText.length < 1 || tickerText.length > 4 ) if ( tickerText.length < 1 || tickerText.length > 4 ) {
$('exportProgressTicker').set( 'text', '.' ); $('exportProgressTicker').set( 'text', '.' );
else } else {
$('exportProgressTicker').appendText( '.' ); $('exportProgressTicker').appendText( '.' );
}
} }
function exportResponse( respObj, respText ) { function exportResponse( respObj, respText ) {
@ -19,7 +20,7 @@ function exportResponse( respObj, respText ) {
function exportEvent( form ) { function exportEvent( form ) {
var parms = 'view=request&request=event&action=download'; var parms = 'view=request&request=event&action=download';
parms += '&'+$(form).toQueryString(); parms += '&'+$(form).toQueryString();
var query = new Request.JSON( { url: thisUrl, method: 'post', data: parms, onSuccess: exportResponse } ); var query = new Request.JSON( {url: thisUrl, method: 'post', data: parms, onSuccess: exportResponse} );
query.send(); query.send();
$('exportProgress').removeClass( 'hidden' ); $('exportProgress').removeClass( 'hidden' );
$('exportProgress').setProperty( 'class', 'warnText' ); $('exportProgress').setProperty( 'class', 'warnText' );

View File

@ -2,7 +2,7 @@ var vid = null;
function vjsReplay() { function vjsReplay() {
var endTime = (Date.parse(eventData.EndTime)).getTime(); var endTime = (Date.parse(eventData.EndTime)).getTime();
switch(replayMode.value) { switch (replayMode.value) {
case 'none': case 'none':
break; break;
case 'single': case 'single':
@ -40,7 +40,7 @@ function vjsReplay() {
} }
} }
$j.ajaxSetup({timeout: AJAX_TIMEOUT }); //sets timeout for all getJSON. $j.ajaxSetup({timeout: AJAX_TIMEOUT}); //sets timeout for all getJSON.
var cueFrames = null; //make cueFrames available even if we don't send another ajax query var cueFrames = null; //make cueFrames available even if we don't send another ajax query
@ -69,7 +69,7 @@ function renderAlarmCues(containerEl) {
var alarmHtml = ""; var alarmHtml = "";
var pixSkew = 0; var pixSkew = 0;
var skip = 0; var skip = 0;
var num_cueFrames = cueFrames.length; var num_cueFrames = cueFrames.length;
for ( var i = 0; i < num_cueFrames; i++ ) { for ( var i = 0; i < num_cueFrames; i++ ) {
skip = 0; skip = 0;
frame = cueFrames[i]; frame = cueFrames[i];
@ -165,8 +165,9 @@ function changeScale() {
newWidth = eventData.Width * scale / SCALE_BASE; newWidth = eventData.Width * scale / SCALE_BASE;
newHeight = eventData.Height * scale / SCALE_BASE; newHeight = eventData.Height * scale / SCALE_BASE;
} }
if ( !(streamMode == 'stills') ) if ( !(streamMode == 'stills') ) {
eventViewer.width(newWidth); //stills handles its own width eventViewer.width(newWidth);
} //stills handles its own width
eventViewer.height(newHeight); eventViewer.height(newHeight);
if ( !vid ) { // zms needs extra sizing if ( !vid ) { // zms needs extra sizing
streamScale(scale == "auto" ? autoScale : scale); streamScale(scale == "auto" ? autoScale : scale);
@ -189,7 +190,7 @@ function changeScale() {
function changeReplayMode() { function changeReplayMode() {
var replayMode = $('replayMode').get('value'); var replayMode = $('replayMode').get('value');
Cookie.write('replayMode', replayMode, { duration: 10*365 }); Cookie.write('replayMode', replayMode, {duration: 10*365});
refreshWindow(); refreshWindow();
} }
@ -212,12 +213,14 @@ function getCmdResponse( respObj, respText ) {
zmsBroke = false; zmsBroke = false;
if ( streamCmdTimer ) if ( streamCmdTimer ) {
streamCmdTimer = clearTimeout(streamCmdTimer); streamCmdTimer = clearTimeout(streamCmdTimer);
}
streamStatus = respObj.status; streamStatus = respObj.status;
if ( streamStatus.progress >= Math.round(parseFloat(eventData.Length)) ) if ( streamStatus.progress >= Math.round(parseFloat(eventData.Length)) ) {
streamStatus.progress = parseFloat(eventData.Length); //Limit progress to reality streamStatus.progress = parseFloat(eventData.Length);
} //Limit progress to reality
var eventId = streamStatus.event; var eventId = streamStatus.event;
if ( lastEventId ) { if ( lastEventId ) {
@ -240,18 +243,20 @@ function getCmdResponse( respObj, respText ) {
} }
$j('#progressValue').html(secsToTime(parseInt(streamStatus.progress))); $j('#progressValue').html(secsToTime(parseInt(streamStatus.progress)));
$j('#zoomValue').html(streamStatus.zoom); $j('#zoomValue').html(streamStatus.zoom);
if ( streamStatus.zoom == "1.0" ) if ( streamStatus.zoom == "1.0" ) {
setButtonState( $('zoomOutBtn'), 'unavail' ); setButtonState( $('zoomOutBtn'), 'unavail' );
else } else {
setButtonState( $('zoomOutBtn'), 'inactive' ); setButtonState( $('zoomOutBtn'), 'inactive' );
}
updateProgressBar(); updateProgressBar();
if ( streamStatus.auth ) { if ( streamStatus.auth ) {
// Try to reload the image stream. // Try to reload the image stream.
var streamImg = $j('#evtStream'); var streamImg = $j('#evtStream');
if ( streamImg ) if ( streamImg ) {
streamImg.src = streamImg.src.replace( /auth=\w+/i, 'auth='+streamStatus.auth ); streamImg.src = streamImg.src.replace( /auth=\w+/i, 'auth='+streamStatus.auth );
}
} // end if haev a new auth hash } // end if haev a new auth hash
streamCmdTimer = streamQuery.delay( streamTimeout ); //Timeout is refresh rate for progressBox and time display streamCmdTimer = streamQuery.delay( streamTimeout ); //Timeout is refresh rate for progressBox and time display
@ -275,8 +280,9 @@ function pauseClicked() {
} }
function vjsPause() { function vjsPause() {
if ( intervalRewind ) if ( intervalRewind ) {
stopFastRev(); stopFastRev();
}
streamPause(); streamPause();
} }
@ -305,8 +311,9 @@ function playClicked( ) {
} }
function vjsPlay() { //catches if we change mode programatically function vjsPlay() { //catches if we change mode programatically
if ( intervalRewind ) if ( intervalRewind ) {
stopFastRev(); stopFastRev();
}
$j('#rateValue').html(vid.playbackRate()); $j('#rateValue').html(vid.playbackRate());
Cookie.write('zmEventRate', vid.playbackRate()*100, {duration: 10*365}); Cookie.write('zmEventRate', vid.playbackRate()*100, {duration: 10*365});
streamPlay(); streamPlay();
@ -332,8 +339,9 @@ function streamFastFwd( action ) {
if ( vid ) { if ( vid ) {
if ( revSpeed != .5 ) stopFastRev(); if ( revSpeed != .5 ) stopFastRev();
vid.playbackRate(rates[rates.indexOf(vid.playbackRate()*100)-1]/100); vid.playbackRate(rates[rates.indexOf(vid.playbackRate()*100)-1]/100);
if ( rates.indexOf(vid.playbackRate()*100)-1 == -1 ) if ( rates.indexOf(vid.playbackRate()*100)-1 == -1 ) {
setButtonState($('fastFwdBtn'), 'unavail'); setButtonState($('fastFwdBtn'), 'unavail');
}
$j('#rateValue').html(vid.playbackRate()); $j('#rateValue').html(vid.playbackRate());
Cookie.write('zmEventRate', vid.playbackRate()*100, {duration: 10*365}); Cookie.write('zmEventRate', vid.playbackRate()*100, {duration: 10*365});
} else { } else {
@ -534,8 +542,9 @@ function getEventResponse( respObj, respText ) {
eventData = respObj.event; eventData = respObj.event;
var eventStills = $('eventStills'); var eventStills = $('eventStills');
if ( eventStills && !$('eventStills').hasClass( 'hidden' ) && currEventId != eventData.Id ) if ( eventStills && !$('eventStills').hasClass( 'hidden' ) && currEventId != eventData.Id ) {
resetEventStills(); resetEventStills();
}
currEventId = eventData.Id; currEventId = eventData.Id;
$('dataId').set( 'text', eventData.Id ); $('dataId').set( 'text', eventData.Id );
@ -578,7 +587,7 @@ function getEventResponse( respObj, respText ) {
nearEventsQuery( eventData.Id ); nearEventsQuery( eventData.Id );
} // end function getEventResponse } // end function getEventResponse
var eventReq = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getEventResponse } ); var eventReq = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getEventResponse} );
function eventQuery( eventId ) { function eventQuery( eventId ) {
var eventParms = "view=request&request=status&entity=event&id="+eventId; var eventParms = "view=request&request=status&entity=event&id="+eventId;
@ -593,8 +602,9 @@ var PrevEventDefVideoPath = "";
var NextEventDefVideoPath = ""; var NextEventDefVideoPath = "";
function getNearEventsResponse( respObj, respText ) { function getNearEventsResponse( respObj, respText ) {
if ( checkStreamForErrors( "getNearEventsResponse", respObj ) ) if ( checkStreamForErrors( "getNearEventsResponse", respObj ) ) {
return; return;
}
prevEventId = respObj.nearevents.PrevEventId; prevEventId = respObj.nearevents.PrevEventId;
nextEventId = respObj.nearevents.NextEventId; nextEventId = respObj.nearevents.NextEventId;
prevEventStartTime = Date.parse(respObj.nearevents.PrevEventStartTime); prevEventStartTime = Date.parse(respObj.nearevents.PrevEventStartTime);
@ -610,7 +620,7 @@ function getNearEventsResponse( respObj, respText ) {
$j('#nextBtn').prop('disabled', nextEventId == 0 ? true : false).attr('class', nextEventId == 0 ? 'unavail' : 'inactive'); $j('#nextBtn').prop('disabled', nextEventId == 0 ? true : false).attr('class', nextEventId == 0 ? 'unavail' : 'inactive');
} }
var nearEventsReq = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getNearEventsResponse } ); var nearEventsReq = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getNearEventsResponse} );
function nearEventsQuery( eventId ) { function nearEventsQuery( eventId ) {
var parms = "view=request&request=status&entity=nearevents&id="+eventId+filterQuery+sortQuery; var parms = "view=request&request=status&entity=nearevents&id="+eventId+filterQuery+sortQuery;
@ -633,9 +643,12 @@ function loadEventThumb( event, frame, loadImage ) {
thumbImg.setProperty( 'class', frame.Type=='Alarm'?'alarm':'normal' ); thumbImg.setProperty( 'class', frame.Type=='Alarm'?'alarm':'normal' );
thumbImg.setProperty( 'title', frame.FrameId+' / '+((frame.Type=='Alarm')?frame.Score:0) ); thumbImg.setProperty( 'title', frame.FrameId+' / '+((frame.Type=='Alarm')?frame.Score:0) );
thumbImg.removeEvents( 'click' ); thumbImg.removeEvents( 'click' );
thumbImg.addEvent( 'click', function() { locateImage( frame.FrameId, true ); } ); thumbImg.addEvent( 'click', function() {
if ( loadImage ) locateImage( frame.FrameId, true );
} );
if ( loadImage ) {
loadEventImage( event, frame ); loadEventImage( event, frame );
}
} ).pass( loadImage ) } ).pass( loadImage )
} }
); );
@ -655,17 +668,18 @@ function loadEventImage( event, frame ) {
} }
$('eventImageBar').setStyle( 'width', event.Width ); $('eventImageBar').setStyle( 'width', event.Width );
if ( frame.Type=='Alarm' ) if ( frame.Type=='Alarm' ) {
$('eventImageStats').removeClass( 'hidden' ); $('eventImageStats').removeClass( 'hidden' );
else } else {
$('eventImageStats').addClass( 'hidden' ); $('eventImageStats').addClass( 'hidden' );
}
thumbImg.addClass( 'selected' ); thumbImg.addClass( 'selected' );
thumbImg.setOpacity( 0.5 ); thumbImg.setOpacity( 0.5 );
if ( eventImagePanel.getStyle( 'display' ) == 'none' ) { if ( eventImagePanel.getStyle( 'display' ) == 'none' ) {
eventImagePanel.setOpacity( 0 ); eventImagePanel.setOpacity( 0 );
eventImagePanel.setStyle( 'display', 'inline-block' ); eventImagePanel.setStyle( 'display', 'inline-block' );
new Fx.Tween( eventImagePanel, { duration: 500, transition: Fx.Transitions.Sine } ).start( 'opacity', 0, 1 ); new Fx.Tween( eventImagePanel, {duration: 500, transition: Fx.Transitions.Sine} ).start( 'opacity', 0, 1 );
} }
eventImg.setProperties( { eventImg.setProperties( {
@ -683,7 +697,6 @@ function loadEventImage( event, frame ) {
} }
function hideEventImageComplete() { function hideEventImageComplete() {
var eventImg = $('eventImage');
var thumbImg = $('eventThumb'+$('eventImage').getProperty( 'alt' )); var thumbImg = $('eventThumb'+$('eventImage').getProperty( 'alt' ));
if ( thumbImg ) { if ( thumbImg ) {
thumbImg.removeClass('selected'); thumbImg.removeClass('selected');
@ -698,8 +711,9 @@ function hideEventImageComplete() {
} }
function hideEventImage() { function hideEventImage() {
if ( $('eventImagePanel').getStyle( 'display' ) != 'none' ) if ( $('eventImagePanel').getStyle( 'display' ) != 'none' ) {
new Fx.Tween( $('eventImagePanel'), { duration: 500, transition: Fx.Transitions.Sine, onComplete: hideEventImageComplete } ).start( 'opacity', 1, 0 ); new Fx.Tween( $('eventImagePanel'), {duration: 500, transition: Fx.Transitions.Sine, onComplete: hideEventImageComplete} ).start( 'opacity', 1, 0 );
}
} }
function resetEventStills() { function resetEventStills() {
@ -709,13 +723,15 @@ function resetEventStills() {
slider = new Slider( $('thumbsSlider'), $('thumbsKnob'), { slider = new Slider( $('thumbsSlider'), $('thumbsKnob'), {
/*steps: eventData.Frames,*/ /*steps: eventData.Frames,*/
onChange: function( step ) { onChange: function( step ) {
if ( !step ) if ( !step ) {
step = 0; step = 0;
}
var fid = parseInt((step * eventData.Frames)/this.options.steps); var fid = parseInt((step * eventData.Frames)/this.options.steps);
if ( fid < 1 ) if ( fid < 1 ) {
fid = 1; fid = 1;
else if ( fid > eventData.Frames ) } else if ( fid > eventData.Frames ) {
fid = eventData.Frames; fid = eventData.Frames;
}
checkFrames( eventData.Id, fid, ($j('#eventImagePanel').css('display')=='none'?'':'true')); checkFrames( eventData.Id, fid, ($j('#eventImagePanel').css('display')=='none'?'':'true'));
scroll.toElement( 'eventThumb'+fid ); scroll.toElement( 'eventThumb'+fid );
} }
@ -724,8 +740,9 @@ function resetEventStills() {
} }
function getFrameResponse( respObj, respText ) { function getFrameResponse( respObj, respText ) {
if ( checkStreamForErrors( "getFrameResponse", respObj ) ) if ( checkStreamForErrors( "getFrameResponse", respObj ) ) {
return; return;
}
var frame = respObj.frameimage; var frame = respObj.frameimage;
@ -734,15 +751,16 @@ function getFrameResponse( respObj, respText ) {
return; return;
} }
if ( !eventData['frames'] ) if ( !eventData['frames'] ) {
eventData['frames'] = new Object(); eventData['frames'] = {};
}
eventData['frames'][frame.FrameId] = frame; eventData['frames'][frame.FrameId] = frame;
loadEventThumb( eventData, frame, respObj.loopback=="true" ); loadEventThumb( eventData, frame, respObj.loopback=="true" );
} }
var frameReq = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'chain', onSuccess: getFrameResponse } ); var frameReq = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'chain', onSuccess: getFrameResponse} );
function frameQuery( eventId, frameId, loadImage ) { function frameQuery( eventId, frameId, loadImage ) {
var parms = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId+"&loopback="+loadImage; var parms = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId+"&loopback="+loadImage;
@ -757,22 +775,27 @@ function checkFrames( eventId, frameId, loadImage ) {
return; return;
} }
if ( !eventData['frames'] ) if ( !eventData['frames'] ) {
eventData['frames'] = new Object(); eventData['frames'] = {};
}
currFrameId = frameId; currFrameId = frameId;
var loFid = frameId - frameBatch/2; var loFid = frameId - frameBatch/2;
if ( loFid < 1 ) if ( loFid < 1 ) {
loFid = 1; loFid = 1;
}
var hiFid = loFid + (frameBatch-1); var hiFid = loFid + (frameBatch-1);
if ( hiFid > eventData.Frames ) if ( hiFid > eventData.Frames ) {
hiFid = eventData.Frames; hiFid = eventData.Frames;
}
for ( var fid = loFid; fid <= hiFid; fid++ ) { for ( var fid = loFid; fid <= hiFid; fid++ ) {
if ( !$('eventThumb'+fid) ) { if ( !$('eventThumb'+fid) ) {
var img = new Element( 'img', { 'id': 'eventThumb'+fid, 'src': 'graphics/transparent.png', 'alt': fid, 'class': 'placeholder' } ); var img = new Element( 'img', {'id': 'eventThumb'+fid, 'src': 'graphics/transparent.png', 'alt': fid, 'class': 'placeholder'} );
img.addEvent( 'click', function() { eventData['frames'][fid] = null; checkFrames( eventId, fid ); } ); img.addEvent( 'click', function() {
eventData['frames'][fid] = null; checkFrames( eventId, fid );
} );
frameQuery( eventId, fid, loadImage && (fid == frameId) ); frameQuery( eventId, fid, loadImage && (fid == frameId) );
var imgs = $('eventThumbs').getElements( 'img' ); var imgs = $('eventThumbs').getElements( 'img' );
var injected = false; var injected = false;
@ -784,9 +807,9 @@ function checkFrames( eventId, frameId, loadImage ) {
function( thumbImg, index ) { function( thumbImg, index ) {
if ( parseInt(img.getProperty( 'alt' )) < parseInt(thumbImg.getProperty( 'alt' )) ) { if ( parseInt(img.getProperty( 'alt' )) < parseInt(thumbImg.getProperty( 'alt' )) ) {
img.inject( thumbImg, 'before' ); img.inject( thumbImg, 'before' );
return( true ); return ( true );
} }
return( false ); return ( false );
} }
); );
} }
@ -809,30 +832,35 @@ function checkFrames( eventId, frameId, loadImage ) {
} }
function locateImage( frameId, loadImage ) { function locateImage( frameId, loadImage ) {
if ( slider ) if ( slider ) {
slider.fireEvent( 'tick', slider.toPosition( parseInt((frameId-1)*slider.options.steps/eventData.Frames) )); slider.fireEvent( 'tick', slider.toPosition( parseInt((frameId-1)*slider.options.steps/eventData.Frames) ));
}
checkFrames( eventData.Id, frameId, loadImage ); checkFrames( eventData.Id, frameId, loadImage );
scroll.toElement( 'eventThumb'+frameId ); scroll.toElement( 'eventThumb'+frameId );
} }
function prevImage() { function prevImage() {
if ( currFrameId > 1 ) if ( currFrameId > 1 ) {
locateImage( parseInt(currFrameId)-1, true ); locateImage( parseInt(currFrameId)-1, true );
}
} }
function nextImage() { function nextImage() {
if ( currFrameId < eventData.Frames ) if ( currFrameId < eventData.Frames ) {
locateImage( parseInt(currFrameId)+1, true ); locateImage( parseInt(currFrameId)+1, true );
}
} }
function prevThumbs() { function prevThumbs() {
if ( currFrameId > 1 ) if ( currFrameId > 1 ) {
locateImage( parseInt(currFrameId)>10?(parseInt(currFrameId)-10):1, $('eventImagePanel').getStyle('display')!="none" ); locateImage( parseInt(currFrameId)>10?(parseInt(currFrameId)-10):1, $('eventImagePanel').getStyle('display')!="none" );
}
} }
function nextThumbs() { function nextThumbs() {
if ( currFrameId < eventData.Frames ) if ( currFrameId < eventData.Frames ) {
locateImage( parseInt(currFrameId)<(eventData.Frames-10)?(parseInt(currFrameId)+10):eventData.Frames, $('eventImagePanel').getStyle('display')!="none" ); locateImage( parseInt(currFrameId)<(eventData.Frames-10)?(parseInt(currFrameId)+10):eventData.Frames, $('eventImagePanel').getStyle('display')!="none" );
}
} }
function prevEvent() { function prevEvent() {
@ -850,19 +878,22 @@ function nextEvent() {
} }
function getActResponse( respObj, respText ) { function getActResponse( respObj, respText ) {
if ( checkStreamForErrors( "getActResponse", respObj ) ) if ( checkStreamForErrors( "getActResponse", respObj ) ) {
return; return;
}
if ( respObj.refreshEvent ) if ( respObj.refreshEvent ) {
eventQuery( eventData.Id ); eventQuery( eventData.Id );
}
} }
var actReq = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getActResponse } ); var actReq = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getActResponse} );
function actQuery( action, parms ) { function actQuery( action, parms ) {
var actParms = "view=request&request=event&id="+eventData.Id+"&action="+action; var actParms = "view=request&request=event&id="+eventData.Id+"&action="+action;
if ( parms != null ) if ( parms != null ) {
actParms += "&"+Object.toQueryString( parms ); actParms += "&"+Object.toQueryString( parms );
}
actReq.send( actParms ); actReq.send( actParms );
} }
@ -874,7 +905,7 @@ function deleteEvent() {
function renameEvent() { function renameEvent() {
var newName = $('eventName').get('value'); var newName = $('eventName').get('value');
actQuery( 'rename', { eventName: newName } ); actQuery( 'rename', {eventName: newName} );
} }
function editEvent() { function editEvent() {
@ -931,7 +962,7 @@ function showStills() {
scroll = new Fx.Scroll( 'eventThumbs', { scroll = new Fx.Scroll( 'eventThumbs', {
wait: false, wait: false,
duration: 500, duration: 500,
offset: { 'x': 0, 'y': 0 }, offset: {'x': 0, 'y': 0},
transition: Fx.Transitions.Quad.easeInOut transition: Fx.Transitions.Quad.easeInOut
} }
); );
@ -1002,8 +1033,12 @@ function initPage() {
vid.on('ended', vjsReplay); vid.on('ended', vjsReplay);
vid.on('play', vjsPlay); vid.on('play', vjsPlay);
vid.on('pause', vjsPause); vid.on('pause', vjsPause);
vid.on('click', function(event) {handleClick(event);}); vid.on('click', function(event) {
vid.on('timeupdate', function() {$j('#progressValue').html(secsToTime(Math.floor(vid.currentTime())));}); handleClick(event);
});
vid.on('timeupdate', function() {
$j('#progressValue').html(secsToTime(Math.floor(vid.currentTime())));
});
if ( rate > 1 ) { if ( rate > 1 ) {
// rate should be 100 = 1x, etc. // rate should be 100 = 1x, etc.
@ -1018,9 +1053,12 @@ function initPage() {
console.log('No element with id tag imageFeed found.'); console.log('No element with id tag imageFeed found.');
} else { } else {
var streamImg = imageFeed.getElement('img'); var streamImg = imageFeed.getElement('img');
if ( !streamImg ) if ( !streamImg ) {
streamImg = imageFeed.getElement('object'); streamImg = imageFeed.getElement('object');
$(streamImg).addEvent( 'click', function( event ) { handleClick( event ); } ); }
$(streamImg).addEvent( 'click', function( event ) {
handleClick( event );
} );
} }
} }
} }

View File

@ -8,9 +8,11 @@ function closeWindows() {
function toggleCheckbox( element, name ) { function toggleCheckbox( element, name ) {
var form = element.form; var form = element.form;
var checked = element.checked; var checked = element.checked;
for (var i = 0; i < form.elements.length; i++) for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name.indexOf(name) == 0) if (form.elements[i].name.indexOf(name) == 0) {
form.elements[i].checked = checked; form.elements[i].checked = checked;
}
}
form.viewBtn.disabled = !(canViewEvents && checked); form.viewBtn.disabled = !(canViewEvents && checked);
form.editBtn.disabled = !(canEditEvents && checked); form.editBtn.disabled = !(canEditEvents && checked);
form.archiveBtn.disabled = unarchivedEvents?!checked:true; form.archiveBtn.disabled = unarchivedEvents?!checked:true;
@ -33,8 +35,9 @@ function configureButton( element, name ) {
} }
} }
} }
if ( !element.checked ) if ( !element.checked ) {
form.toggleCheck.checked = false; form.toggleCheck.checked = false;
}
form.viewBtn.disabled = !(canViewEvents && checked); form.viewBtn.disabled = !(canViewEvents && checked);
form.editBtn.disabled = !(canEditEvents && checked); form.editBtn.disabled = !(canEditEvents && checked);
form.archiveBtn.disabled = (!checked)||(!unarchivedEvents); form.archiveBtn.disabled = (!checked)||(!unarchivedEvents);

View File

@ -4,11 +4,12 @@ function configureExportButton( element ) {
var checkCount = 0; var checkCount = 0;
var radioCount = 0; var radioCount = 0;
for ( var i = 0; i < form.elements.length; i++ ) { for ( var i = 0; i < form.elements.length; i++ ) {
if ( form.elements[i].type == "checkbox" && form.elements[i].checked ) if ( form.elements[i].type == "checkbox" && form.elements[i].checked ) {
checkCount++; checkCount++;
else if ( form.elements[i].type == "radio" && form.elements[i].checked ) } else if ( form.elements[i].type == "radio" && form.elements[i].checked ) {
radioCount++; radioCount++;
} }
}
form.elements['exportButton'].disabled = (checkCount == 0 || radioCount == 0); form.elements['exportButton'].disabled = (checkCount == 0 || radioCount == 0);
} }
@ -20,10 +21,11 @@ var exportTimer = null;
function exportProgress() { function exportProgress() {
var tickerText = $('exportProgressTicker').get('text'); var tickerText = $('exportProgressTicker').get('text');
if ( tickerText.length < 1 || tickerText.length > 4 ) if ( tickerText.length < 1 || tickerText.length > 4 ) {
$('exportProgressTicker').set( 'text', '.' ); $('exportProgressTicker').set( 'text', '.' );
else } else {
$('exportProgressTicker').appendText( '.' ); $('exportProgressTicker').appendText( '.' );
}
} }
function exportResponse( respObj, respText ) { function exportResponse( respObj, respText ) {
@ -33,7 +35,7 @@ function exportResponse( respObj, respText ) {
function exportEvent( form ) { function exportEvent( form ) {
var parms = 'view=request&request=event&action=export'; var parms = 'view=request&request=event&action=export';
parms += '&'+$(form).toQueryString(); parms += '&'+$(form).toQueryString();
var query = new Request.JSON( { url: thisUrl, method: 'post', data: parms, onSuccess: exportResponse } ); var query = new Request.JSON( {url: thisUrl, method: 'post', data: parms, onSuccess: exportResponse} );
query.send(); query.send();
$('exportProgress').removeClass( 'hidden' ); $('exportProgress').removeClass( 'hidden' );
$('exportProgress').setProperty( 'class', 'warnText' ); $('exportProgress').setProperty( 'class', 'warnText' );

View File

@ -31,22 +31,23 @@ function updateButtons(element) {
form.elements['executeButton'].disabled = false; form.elements['executeButton'].disabled = false;
} else { } else {
var canExecute = false; var canExecute = false;
if ( form.elements['filter[AutoArchive]'] && form.elements['filter[AutoArchive]'].checked ) if ( form.elements['filter[AutoArchive]'] && form.elements['filter[AutoArchive]'].checked ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[AutoVideo]'] && form.elements['filter[AutoVideo]'].checked ) } else if ( form.elements['filter[AutoVideo]'] && form.elements['filter[AutoVideo]'].checked ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[AutoUpload]'] && form.elements['filter[AutoUpload]'].checked ) } else if ( form.elements['filter[AutoUpload]'] && form.elements['filter[AutoUpload]'].checked ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[AutoEmail]'] && form.elements['filter[AutoEmail]'].checked ) } else if ( form.elements['filter[AutoEmail]'] && form.elements['filter[AutoEmail]'].checked ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[AutoMessage]'] && form.elements['filter[AutoMessage]'].checked ) } else if ( form.elements['filter[AutoMessage]'] && form.elements['filter[AutoMessage]'].checked ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[AutoExecute]'].checked && form.elements['filter[AutoExecuteCmd]'].value != '' ) } else if ( form.elements['filter[AutoExecute]'].checked && form.elements['filter[AutoExecuteCmd]'].value != '' ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[AutoDelete]'].checked ) } else if ( form.elements['filter[AutoDelete]'].checked ) {
canExecute = true; canExecute = true;
else if ( form.elements['filter[UpdateDiskSpace]'].checked ) } else if ( form.elements['filter[UpdateDiskSpace]'].checked ) {
canExecute = true; canExecute = true;
}
form.elements['executeButton'].disabled = !canExecute; form.elements['executeButton'].disabled = !canExecute;
} }
if ( form.elements['filter[Name]'].value ) { if ( form.elements['filter[Name]'].value ) {

View File

@ -24,7 +24,7 @@ function changeScale() {
img.css('width', newWidth + 'px'); img.css('width', newWidth + 'px');
img.css('height', newHeight + 'px'); img.css('height', newHeight + 'px');
} }
Cookie.write( 'zmWatchScale', scale, { duration: 10*365 } ); Cookie.write( 'zmWatchScale', scale, {duration: 10*365} );
$j.each(controlsLinks, function(k, anchor) { //Make frames respect scale choices $j.each(controlsLinks, function(k, anchor) { //Make frames respect scale choices
anchor.prop('href', anchor.prop('href').replace(/scale=.*&/, 'scale=' + scale + '&')); anchor.prop('href', anchor.prop('href').replace(/scale=.*&/, 'scale=' + scale + '&'));
}); });

View File

@ -1,15 +1,15 @@
var logParms = "view=request&request=log&task=query"; var logParms = "view=request&request=log&task=query";
var logReq = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: logResponse } ); var logReq = new Request.JSON( {url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: logResponse} );
var logTimer = undefined; var logTimer = undefined;
var logTable = undefined; var logTable = undefined;
var logCodes = new Object({ var logCodes = {
'0': 'INF', '0': 'INF',
'-1': 'WAR', '-1': 'WAR',
'-2': 'ERR', '-2': 'ERR',
'-3': 'FAT', '-3': 'FAT',
'-4': 'PNC', '-4': 'PNC',
}); };
var minSampleTime = 2000; var minSampleTime = 2000;
var maxSampleTime = 16000; var maxSampleTime = 16000;
@ -27,8 +27,9 @@ var options = {};
function buildFetchParms( parms ) { function buildFetchParms( parms ) {
var fetchParms = logParms+'&limit='+maxLogFetch; var fetchParms = logParms+'&limit='+maxLogFetch;
if ( parms ) if ( parms ) {
fetchParms += '&'+parms; fetchParms += '&'+parms;
}
Object.each(filter, Object.each(filter,
function( value, key ) { function( value, key ) {
fetchParms += '&filter['+key+']='+value; fetchParms += '&filter['+key+']='+value;
@ -46,8 +47,9 @@ function fetchPrevLogs() {
} }
function logResponse( respObj ) { function logResponse( respObj ) {
if ( logTimer ) if ( logTimer ) {
logTimer = clearTimeout( logTimer ); logTimer = clearTimeout( logTimer );
}
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
if ( respObj.logs.length > 0 ) { if ( respObj.logs.length > 0 ) {
@ -56,22 +58,25 @@ function logResponse( respObj ) {
try { try {
respObj.logs.each( respObj.logs.each(
function( log ) { function( log ) {
if ( ( !maxLogTime ) || ( log.TimeKey > maxLogTime ) ) if ( ( !maxLogTime ) || ( log.TimeKey > maxLogTime ) ) {
maxLogTime = log.TimeKey; maxLogTime = log.TimeKey;
if ( ( !minLogTime ) || ( log.TimeKey < minLogTime ) ) }
if ( ( !minLogTime ) || ( log.TimeKey < minLogTime ) ) {
minLogTime = log.TimeKey; minLogTime = log.TimeKey;
var row = logTable.push( [{ content: log.DateTime, properties: { style: 'white-space: nowrap' }}, log.Component, log.Server, log.Pid, log.Code, log.Message, log.File, log.Line] ); }
var row = logTable.push( [{content: log.DateTime, properties: {style: 'white-space: nowrap'}}, log.Component, log.Server, log.Pid, log.Code, log.Message, log.File, log.Line] );
delete log.Message; delete log.Message;
row.tr.store( 'log', log ); row.tr.store( 'log', log );
if ( log.Level <= -3 ) if ( log.Level <= -3 ) {
row.tr.addClass( 'log-fat' ); row.tr.addClass( 'log-fat' );
else if ( log.Level <= -2 ) } else if ( log.Level <= -2 ) {
row.tr.addClass( 'log-err' ); row.tr.addClass( 'log-err' );
else if ( log.Level <= -1 ) } else if ( log.Level <= -1 ) {
row.tr.addClass( 'log-war' ); row.tr.addClass( 'log-war' );
else if ( log.Level > 0 ) } else if ( log.Level > 0 ) {
row.tr.addClass( 'log-dbg' ); row.tr.addClass( 'log-dbg' );
}
if ( !firstLoad ) { if ( !firstLoad ) {
var color = document.defaultView.getComputedStyle(row.tr, null).getPropertyValue('color'); var color = document.defaultView.getComputedStyle(row.tr, null).getPropertyValue('color');
var colorParts = color.match(/^rgb.*\((\d+),\s*(\d+),\s*(\d+)/); var colorParts = color.match(/^rgb.*\((\d+),\s*(\d+),\s*(\d+)/);
@ -83,11 +88,12 @@ function logResponse( respObj ) {
if ( typeof(respObj.options) == 'object' ) { if ( typeof(respObj.options) == 'object' ) {
$j.each( respObj.options, $j.each( respObj.options,
function( field ) { function( field ) {
if ( options[field] ) if ( options[field] ) {
options[field] = Object.assign(options[field], respObj.options[field]); options[field] = Object.assign(options[field], respObj.options[field]);
else } else {
options[field] = respObj.options[field]; options[field] = respObj.options[field];
} }
}
); );
} }
updateFilterSelectors(); updateFilterSelectors();
@ -101,21 +107,24 @@ function logResponse( respObj ) {
$('availLogs').set('text', respObj.available); $('availLogs').set('text', respObj.available);
$('displayLogs').set('text', logCount); $('displayLogs').set('text', logCount);
if ( firstLoad ) { if ( firstLoad ) {
if ( logCount < displayLimit ) if ( logCount < displayLimit ) {
fetchPrevLogs(); fetchPrevLogs();
} }
}
logTable.reSort(); logTable.reSort();
} catch( e ) { } catch ( e ) {
console.error( e ); console.error( e );
} }
logTimeout /= 2; logTimeout /= 2;
if ( logTimeout < minSampleTime ) if ( logTimeout < minSampleTime ) {
logTimeout = minSampleTime; logTimeout = minSampleTime;
}
} else { } else {
firstLoad = false; firstLoad = false;
logTimeout *= 2; logTimeout *= 2;
if ( logTimeout > maxSampleTime ) if ( logTimeout > maxSampleTime ) {
logTimeout = maxSampleTime; logTimeout = maxSampleTime;
}
} // end logs.length > 0 } // end logs.length > 0
} // end if result == Ok } // end if result == Ok
logTimer = fetchNextLogs.delay( logTimeout ); logTimer = fetchNextLogs.delay( logTimeout );
@ -161,9 +170,10 @@ function filterLog() {
return; return;
} }
var value = selector.get('value'); var value = selector.get('value');
if ( value ) if ( value ) {
filter[field] = value; filter[field] = value;
} }
}
); );
refreshLog(); refreshLog();
} }
@ -200,7 +210,7 @@ function exportRequest() {
$('exportError').hide(); $('exportError').hide();
if ( form.validate() ) { if ( form.validate() ) {
var exportParms = "view=request&request=log&task=export"; var exportParms = "view=request&request=log&task=export";
var exportReq = new Request.JSON( { url: thisUrl, method: 'post', link: 'cancel', onSuccess: exportResponse, onFailure: exportFail } ); var exportReq = new Request.JSON( {url: thisUrl, method: 'post', link: 'cancel', onSuccess: exportResponse, onFailure: exportFail} );
var selection = form.getElement('input[name=selector]:checked').get('value'); var selection = form.getElement('input[name=selector]:checked').get('value');
if ( selection == 'filter' || selection == 'current' ) { if ( selection == 'filter' || selection == 'current' ) {
$$('#filters select').each( $$('#filters select').each(
@ -254,16 +264,18 @@ function updateFilterSelectors() {
} }
); );
} }
if ( filter[key] ) if ( filter[key] ) {
selector.set('value', filter[key]); selector.set('value', filter[key]);
} }
}
); );
} }
function initPage() { function initPage() {
displayLimit = initialDisplayLimit; displayLimit = initialDisplayLimit;
for ( var i = 1; i <= 9; i++ ) for ( var i = 1; i <= 9; i++ ) {
logCodes[''+i] = 'DB'+i; logCodes[''+i] = 'DB'+i;
}
logTable = new HtmlTable( $('logTable'), logTable = new HtmlTable( $('logTable'),
{ {
zebra: true, zebra: true,
@ -279,10 +291,11 @@ function initPage() {
if ( logCount > displayLimit ) { if ( logCount > displayLimit ) {
var rows = tbody.getElements( 'tr' ); var rows = tbody.getElements( 'tr' );
var startIndex; var startIndex;
if ( sortReversed ) if ( sortReversed ) {
startIndex = displayLimit; startIndex = displayLimit;
else } else {
startIndex = 0; startIndex = 0;
}
for ( var i = startIndex; logCount > displayLimit; i++ ) { for ( var i = startIndex; logCount > displayLimit; i++ ) {
rows[i].destroy(); rows[i].destroy();
logCount--; logCount--;

View File

@ -6,22 +6,24 @@ function updateMonitorDimensions( element ) {
if ( form.elements['preserveAspectRatio'].checked ) { if ( form.elements['preserveAspectRatio'].checked ) {
var monitorWidth = parseInt(form.elements['newMonitor[Width]'].value); var monitorWidth = parseInt(form.elements['newMonitor[Width]'].value);
var monitorHeight = parseInt(form.elements['newMonitor[Height]'].value); var monitorHeight = parseInt(form.elements['newMonitor[Height]'].value);
switch( element.name ) { switch ( element.name ) {
case 'newMonitor[Width]': case 'newMonitor[Width]':
if ( monitorWidth >= 0 ) if ( monitorWidth >= 0 ) {
form.elements['newMonitor[Height]'].value = Math.round((monitorWidth * heightFactor) / widthFactor); form.elements['newMonitor[Height]'].value = Math.round((monitorWidth * heightFactor) / widthFactor);
else } else {
form.elements['newMonitor[Height]'].value = ''; form.elements['newMonitor[Height]'].value = '';
}
break; break;
case 'newMonitor[Height]': case 'newMonitor[Height]':
if ( monitorHeight >= 0 ) if ( monitorHeight >= 0 ) {
form.elements['newMonitor[Width]'].value = Math.round((monitorHeight * widthFactor) / heightFactor); form.elements['newMonitor[Width]'].value = Math.round((monitorHeight * widthFactor) / heightFactor);
else } else {
form.elements['newMonitor[Width]'].value = ''; form.elements['newMonitor[Width]'].value = '';
}
break; break;
} }
} }
return( false ); return ( false );
} }
function loadLocations( element ) { function loadLocations( element ) {

View File

@ -1,4 +1,4 @@
var requestQueue = new Request.Queue( { concurrent: monitorData.length, stopOnFailure: false } ); var requestQueue = new Request.Queue( {concurrent: monitorData.length, stopOnFailure: false} );
function Monitor( monitorData ) { function Monitor( monitorData ) {
this.id = monitorData.id; this.id = monitorData.id;
@ -9,27 +9,32 @@ function Monitor( monitorData ) {
this.lastAlarmState = STATE_IDLE; this.lastAlarmState = STATE_IDLE;
this.streamCmdParms = 'view=request&request=stream&connkey='+this.connKey; this.streamCmdParms = 'view=request&request=stream&connkey='+this.connKey;
this.onclick = monitorData.onclick; this.onclick = monitorData.onclick;
if ( auth_hash ) if ( auth_hash ) {
this.streamCmdParms += '&auth='+auth_hash; this.streamCmdParms += '&auth='+auth_hash;
}
this.streamCmdTimer = null; this.streamCmdTimer = null;
this.type = monitorData.type; this.type = monitorData.type;
this.refresh = monitorData.refresh; this.refresh = monitorData.refresh;
this.start = function( delay ) { this.start = function( delay ) {
if ( this.streamCmdQuery ) if ( this.streamCmdQuery ) {
this.streamCmdTimer = this.streamCmdQuery.delay( delay, this ); this.streamCmdTimer = this.streamCmdQuery.delay( delay, this );
else } else {
console.log("No streamCmdQuery"); console.log("No streamCmdQuery");
}
}; };
this.setStateClass = function( element, stateClass ) { this.setStateClass = function( element, stateClass ) {
if ( !element.hasClass( stateClass ) ) { if ( !element.hasClass( stateClass ) ) {
if ( stateClass != 'alarm' ) if ( stateClass != 'alarm' ) {
element.removeClass( 'alarm' ); element.removeClass( 'alarm' );
if ( stateClass != 'alert' ) }
if ( stateClass != 'alert' ) {
element.removeClass( 'alert' ); element.removeClass( 'alert' );
if ( stateClass != 'idle' ) }
if ( stateClass != 'idle' ) {
element.removeClass( 'idle' ); element.removeClass( 'idle' );
}
element.addClass( stateClass ); element.addClass( stateClass );
} }
}; };
@ -49,8 +54,9 @@ function Monitor( monitorData ) {
} }
if ( 0 ) { if ( 0 ) {
// Requeue, but want to wait a while. // Requeue, but want to wait a while.
if ( this.streamCmdTimer ) if ( this.streamCmdTimer ) {
this.streamCmdTimer = clearTimeout( this.streamCmdTimer ); this.streamCmdTimer = clearTimeout( this.streamCmdTimer );
}
var streamCmdTimeout = 1000*statusRefreshTimeout; var streamCmdTimeout = 1000*statusRefreshTimeout;
this.streamCmdTimer = this.streamCmdQuery.delay( streamCmdTimeout, this, true ); this.streamCmdTimer = this.streamCmdQuery.delay( streamCmdTimeout, this, true );
requestQueue.resume(); requestQueue.resume();
@ -59,8 +65,9 @@ function Monitor( monitorData ) {
}; };
this.getStreamCmdResponse = function( respObj, respText ) { this.getStreamCmdResponse = function( respObj, respText ) {
if ( this.streamCmdTimer ) if ( this.streamCmdTimer ) {
this.streamCmdTimer = clearTimeout( this.streamCmdTimer ); this.streamCmdTimer = clearTimeout( this.streamCmdTimer );
}
var stream = $j('#liveStream'+this.id)[0]; var stream = $j('#liveStream'+this.id)[0];
@ -70,12 +77,13 @@ function Monitor( monitorData ) {
this.alarmState = this.status.state; this.alarmState = this.status.state;
var stateClass = ""; var stateClass = "";
if ( this.alarmState == STATE_ALARM ) if ( this.alarmState == STATE_ALARM ) {
stateClass = "alarm"; stateClass = "alarm";
else if ( this.alarmState == STATE_ALERT ) } else if ( this.alarmState == STATE_ALERT ) {
stateClass = "alert"; stateClass = "alert";
else } else {
stateClass = "idle"; stateClass = "idle";
}
if ( (!COMPACT_MONTAGE) && (this.type != 'WebSite') ) { if ( (!COMPACT_MONTAGE) && (this.type != 'WebSite') ) {
$('fpsValue'+this.id).set( 'text', this.status.fps ); $('fpsValue'+this.id).set( 'text', this.status.fps );
@ -111,8 +119,9 @@ function Monitor( monitorData ) {
if ( this.status.auth ) { if ( this.status.auth ) {
if ( this.status.auth != auth_hash ) { if ( this.status.auth != auth_hash ) {
// Try to reload the image stream. // Try to reload the image stream.
if ( stream ) if ( stream ) {
stream.src = stream.src.replace( /auth=\w+/i, 'auth='+this.status.auth ); stream.src = stream.src.replace( /auth=\w+/i, 'auth='+this.status.auth );
}
console.log("Changed auth from " + auth_hash + " to " + this.status.auth ); console.log("Changed auth from " + auth_hash + " to " + this.status.auth );
auth_hash = this.status.auth; auth_hash = this.status.auth;
} }
@ -208,12 +217,12 @@ function selectLayout( element ) {
if ( ! layout ) { if ( ! layout ) {
return; return;
} }
Cookie.write( 'zmMontageLayout', layout_id, { duration: 10*365 } ); Cookie.write( 'zmMontageLayout', layout_id, {duration: 10*365} );
if ( layouts[layout_id].Name != 'Freeform' ) { // 'montage_freeform.css' ) { if ( layouts[layout_id].Name != 'Freeform' ) { // 'montage_freeform.css' ) {
Cookie.write( 'zmMontageScale', '', { duration: 10*365 } ); Cookie.write( 'zmMontageScale', '', {duration: 10*365} );
$('scale').set('value', '' ); $('scale').set('value', '' );
$('width').set('value', ''); $('width').set('value', '');
if ( 1 ) { if ( 1 ) {
for ( var x = 0; x < monitors.length; x++ ) { for ( var x = 0; x < monitors.length; x++ ) {
var monitor = monitors[x]; var monitor = monitors[x];
var streamImg = $( 'liveStream'+monitor.id ); var streamImg = $( 'liveStream'+monitor.id );
@ -235,7 +244,7 @@ if ( 1 ) {
zonesSVG.style.width = ''; zonesSVG.style.width = '';
} }
} // end foreach monitor } // end foreach monitor
} }
} }
} }
@ -252,10 +261,12 @@ function changeSize() {
console.log("Error finding frame for " + monitor.id ); console.log("Error finding frame for " + monitor.id );
continue; continue;
} }
if ( width ) if ( width ) {
monitor_frame.css('width', width+'px'); monitor_frame.css('width', width+'px');
if ( height ) }
if ( height ) {
monitor_frame.css('height', height+'px'); monitor_frame.css('height', height+'px');
}
/*Stream could be an applet so can't use moo tools*/ /*Stream could be an applet so can't use moo tools*/
var streamImg = $( 'liveStream'+monitor.id ); var streamImg = $( 'liveStream'+monitor.id );
if ( streamImg ) { if ( streamImg ) {
@ -278,9 +289,9 @@ function changeSize() {
} }
} }
$('scale').set('value', '' ); $('scale').set('value', '' );
Cookie.write( 'zmMontageScale', '', { duration: 10*365 } ); Cookie.write( 'zmMontageScale', '', {duration: 10*365} );
Cookie.write( 'zmMontageWidth', width, { duration: 10*365 } ); Cookie.write( 'zmMontageWidth', width, {duration: 10*365} );
Cookie.write( 'zmMontageHeight', height, { duration: 10*365 } ); Cookie.write( 'zmMontageHeight', height, {duration: 10*365} );
selectLayout('#zmMontageLayout'); selectLayout('#zmMontageLayout');
} // end function changeSize() } // end function changeSize()
@ -288,9 +299,9 @@ function changeScale() {
var scale = $('scale').get('value'); var scale = $('scale').get('value');
$('width').set('value', ''); $('width').set('value', '');
$('height').set('value', ''); $('height').set('value', '');
Cookie.write( 'zmMontageScale', scale, { duration: 10*365 } ); Cookie.write( 'zmMontageScale', scale, {duration: 10*365} );
Cookie.write( 'zmMontageWidth', '', { duration: 10*365 } ); Cookie.write( 'zmMontageWidth', '', {duration: 10*365} );
Cookie.write( 'zmMontageHeight', '', { duration: 10*365 } ); Cookie.write( 'zmMontageHeight', '', {duration: 10*365} );
if ( ! scale ) { if ( ! scale ) {
selectLayout('#zmMontageLayout'); selectLayout('#zmMontageLayout');
return; return;
@ -306,10 +317,12 @@ function changeScale() {
console.log("Error finding frame for " + monitor.id ); console.log("Error finding frame for " + monitor.id );
continue; continue;
} }
if ( width ) if ( width ) {
monitor_frame.css('width', width+'px'); monitor_frame.css('width', width+'px');
if ( height ) }
if ( height ) {
monitor_frame.css('height', height+'px'); monitor_frame.css('height', height+'px');
}
/*Stream could be an applet so can't use moo tools*/ /*Stream could be an applet so can't use moo tools*/
var streamImg = $j('#liveStream'+monitor.id )[0]; var streamImg = $j('#liveStream'+monitor.id )[0];
if ( streamImg ) { if ( streamImg ) {
@ -399,7 +412,7 @@ function initPage() {
jQuery("#hdrbutton").click(function() { jQuery("#hdrbutton").click(function() {
jQuery("#flipMontageHeader").slideToggle("slow"); jQuery("#flipMontageHeader").slideToggle("slow");
jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up'); jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
Cookie.write( 'zmMontageHeaderFlip', jQuery('#hdrbutton').hasClass('glyphicon-menu-up') ? 'up' : 'down', { duration: 10*365 } ); Cookie.write( 'zmMontageHeaderFlip', jQuery('#hdrbutton').hasClass('glyphicon-menu-up') ? 'up' : 'down', {duration: 10*365} );
}); });
}); });
if ( Cookie.read('zmMontageHeaderFlip') == 'down' ) { if ( Cookie.read('zmMontageHeaderFlip') == 'down' ) {
@ -423,8 +436,9 @@ function initPage() {
// What is the purpose of this code? I think it just starts up a second ajax thread, // What is the purpose of this code? I think it just starts up a second ajax thread,
//increasing the load on the server. //increasing the load on the server.
for ( var i = 0; i < monitorData.length; i++ ) { for ( var i = 0; i < monitorData.length; i++ ) {
if ( monitors[i].type == 'WebSite' ) if ( monitors[i].type == 'WebSite' ) {
continue; continue;
}
var delay = Math.round( (Math.random()+0.75)*statusRefreshTimeout ); var delay = Math.round( (Math.random()+0.75)*statusRefreshTimeout );
console.log("Delay for monitor " + monitorData[i].id + " is " + delay ); console.log("Delay for monitor " + monitorData[i].id + " is " + delay );
monitors[i].streamCmdQuery.delay( delay, monitors[i] ); monitors[i].streamCmdQuery.delay( delay, monitors[i] );

View File

@ -21,8 +21,9 @@ function evaluateLoadTimes() {
freeTimeLastIntervals[imageLoadTimesEvaluated++] = 1 - ((end - start)/currentDisplayInterval); freeTimeLastIntervals[imageLoadTimesEvaluated++] = 1 - ((end - start)/currentDisplayInterval);
if ( imageLoadTimesEvaluated < imageLoadTimesNeeded ) return; if ( imageLoadTimesEvaluated < imageLoadTimesNeeded ) return;
var avgFrac=0; var avgFrac=0;
for ( var i=0; i < imageLoadTimesEvaluated; i++ ) for ( var i=0; i < imageLoadTimesEvaluated; i++ ) {
avgFrac += freeTimeLastIntervals[i]; avgFrac += freeTimeLastIntervals[i];
}
avgFrac = avgFrac / imageLoadTimesEvaluated; avgFrac = avgFrac / imageLoadTimesEvaluated;
// The larger this is(positive) the faster we can go // The larger this is(positive) the faster we can go
if (avgFrac >= 0.9) currentDisplayInterval = (currentDisplayInterval * 0.50).toFixed(1); // we can go much faster if (avgFrac >= 0.9) currentDisplayInterval = (currentDisplayInterval * 0.50).toFixed(1); // we can go much faster
@ -49,8 +50,9 @@ function getFrame( monId, time ) {
for ( var event_id in events ) { for ( var event_id in events ) {
// Search for the event matching this time. Would be more efficient if we had events indexed by monitor // Search for the event matching this time. Would be more efficient if we had events indexed by monitor
Event = events[event_id]; Event = events[event_id];
if ( Event.MonitorId != monId || Event.StartTimeSecs > time || Event.EndTimeSecs < time ) if ( Event.MonitorId != monId || Event.StartTimeSecs > time || Event.EndTimeSecs < time ) {
continue; continue;
}
var duration = Event.EndTimeSecs - Event.StartTimeSecs; var duration = Event.EndTimeSecs - Event.StartTimeSecs;
if ( ! Event.FramesById ) { if ( ! Event.FramesById ) {
@ -61,16 +63,16 @@ function getFrame( monId, time ) {
// Need to get frame by time, not some fun calc that assumes frames have the same mlength. // Need to get frame by time, not some fun calc that assumes frames have the same mlength.
// Frames are not sorted. // Frames are not sorted.
for ( var frame_id in Event.FramesById ) { for ( var frame_id in Event.FramesById ) {
if ( 0 ) { if ( 0 ) {
if ( frame == 0 ) { if ( frame == 0 ) {
console.log("Found frame for time " + time ); console.log("Found frame for time " + time );
console.log(Frame); console.log(Frame);
Frame = Event.FramesById[frame_id]; Frame = Event.FramesById[frame_id];
break; break;
} }
frame --; frame --;
continue; continue;
} }
if ( if (
Event.FramesById[frame_id].TimeStampSecs == time Event.FramesById[frame_id].TimeStampSecs == time
|| ( || (
@ -87,7 +89,7 @@ console.log(Frame);
} }
} // end foreach frame in the event. } // end foreach frame in the event.
if ( ! Frame ) { if ( ! Frame ) {
console.log("Didn't find frame for " + time ); console.log("Didn't find frame for " + time );
return null; return null;
} }
} // end foreach event } // end foreach event
@ -110,11 +112,10 @@ function getImageSource( monId, time ) {
var Frame = getFrame(monId, time); var Frame = getFrame(monId, time);
if ( Frame ) { if ( Frame ) {
// Adjust for bulk frames // Adjust for bulk frames
var frame_id;
if ( Frame.NextFrameId ) { if ( Frame.NextFrameId ) {
var duration = Frame.NextTimeStampSecs - Frame.TimeStampSecs; var duration = Frame.NextTimeStampSecs - Frame.TimeStampSecs;
frame_id = Frame.FrameId + parseInt( (Frame.NextFrameId-Frame.FrameId) * ( time-Frame.TimeStampSecs )/duration ); frame_id = Frame.FrameId + parseInt( (Frame.NextFrameId-Frame.FrameId) * ( time-Frame.TimeStampSecs )/duration );
//console.log("Have NextFrame: duration: " + duration + " frame_id = " + frame_id + " from " + Frame.NextFrameId + ' - ' + Frame.FrameId + " time: " + (time-Frame.TimeStampSecs) ); //console.log("Have NextFrame: duration: " + duration + " frame_id = " + frame_id + " from " + Frame.NextFrameId + ' - ' + Frame.FrameId + " time: " + (time-Frame.TimeStampSecs) );
//} else { //} else {
//console.log("No NextFrame"); //console.log("No NextFrame");
} }
@ -234,11 +235,11 @@ function timerFire() {
outputUpdate(currentTimeSecs); // In live mode we basically do nothing but redisplay outputUpdate(currentTimeSecs); // In live mode we basically do nothing but redisplay
} else if ( currentTimeSecs + playSecsperInterval >= maxTimeSecs ) { } else if ( currentTimeSecs + playSecsperInterval >= maxTimeSecs ) {
// beyond the end just stop // beyond the end just stop
console.log("Current time " + currentTimeSecs + " + " + playSecsperInterval + " >= " + maxTimeSecs + " so stopping"); console.log("Current time " + currentTimeSecs + " + " + playSecsperInterval + " >= " + maxTimeSecs + " so stopping");
setSpeed(0); setSpeed(0);
outputUpdate(currentTimeSecs); outputUpdate(currentTimeSecs);
} else { } else {
//console.log("Current time " + currentTimeSecs + " + " + playSecsperInterval ); //console.log("Current time " + currentTimeSecs + " + " + playSecsperInterval );
outputUpdate(playSecsperInterval + currentTimeSecs); outputUpdate(playSecsperInterval + currentTimeSecs);
} }
return; return;
@ -263,8 +264,9 @@ function drawSliderOnGraph(val) {
// if we have no data to display don't do the slider itself // if we have no data to display don't do the slider itself
var sliderX = parseInt( (val - minTimeSecs) / rangeTimeSecs * cWidth - sliderWidth/2); // position left side of slider var sliderX = parseInt( (val - minTimeSecs) / rangeTimeSecs * cWidth - sliderWidth/2); // position left side of slider
if ( sliderX < 0 ) sliderX = 0; if ( sliderX < 0 ) sliderX = 0;
if ( sliderX+sliderWidth > cWidth ) if ( sliderX+sliderWidth > cWidth ) {
sliderX=cWidth-sliderWidth-1; sliderX=cWidth-sliderWidth-1;
}
// If we have data already saved first restore it from LAST time // If we have data already saved first restore it from LAST time
@ -297,10 +299,11 @@ function drawSliderOnGraph(val) {
// try to get length and then when we get too close to the right switch to the left // try to get length and then when we get too close to the right switch to the left
var len = o.offsetWidth; var len = o.offsetWidth;
var x; var x;
if(sliderX > cWidth/2) if (sliderX > cWidth/2) {
x=sliderX - len - 10; x=sliderX - len - 10;
else } else {
x=sliderX + 10; x=sliderX + 10;
}
o.style.left=x.toString() + "px"; o.style.left=x.toString() + "px";
} }
@ -314,8 +317,9 @@ function drawSliderOnGraph(val) {
o.style.bottom=labbottom; o.style.bottom=labbottom;
o.style.font=labfont; o.style.font=labfont;
o.style.left="5px"; o.style.left="5px";
if ( numMonitors == 0 ) // we need a len calculation if we skipped the slider if ( numMonitors == 0 ) { // we need a len calculation if we skipped the slider
len = o.offsetWidth; len = o.offsetWidth;
}
// If the slider will overlay part of this suppress (this is the left side) // If the slider will overlay part of this suppress (this is the left side)
if ( len + 10 > sliderX || cWidth < len * 4 ) { if ( len + 10 > sliderX || cWidth < len * 4 ) {
// that last check is for very narrow browsers // that last check is for very narrow browsers
@ -377,20 +381,21 @@ function drawGraph() {
for ( var frame_id in Event.FramesById ) { for ( var frame_id in Event.FramesById ) {
var Frame = Event.FramesById[frame_id]; var Frame = Event.FramesById[frame_id];
if ( ! Frame.Score ) if ( ! Frame.Score ) {
continue; continue;
}
// Now put in scored frames (if any) // Now put in scored frames (if any)
var x1=parseInt( (Frame.TimeStampSecs - minTimeSecs) / rangeTimeSecs * cWidth); // round low end down var x1=parseInt( (Frame.TimeStampSecs - minTimeSecs) / rangeTimeSecs * cWidth); // round low end down
var x2=parseInt( (Frame.TimeStampSecs - minTimeSecs) / rangeTimeSecs * cWidth + 0.5 ); // round up var x2=parseInt( (Frame.TimeStampSecs - minTimeSecs) / rangeTimeSecs * cWidth + 0.5 ); // round up
if(x2-x1 < 2) x2=x1+2; // So it is visible make them all at least this number of seconds wide if (x2-x1 < 2) x2=x1+2; // So it is visible make them all at least this number of seconds wide
ctx.fillStyle=monitorColour[Event.MonitorId]; ctx.fillStyle=monitorColour[Event.MonitorId];
ctx.globalAlpha = 0.4 + 0.6 * (1 - Frame.Score/maxScore); // Background is scaled but even lowest is twice as dark as the background ctx.globalAlpha = 0.4 + 0.6 * (1 - Frame.Score/maxScore); // Background is scaled but even lowest is twice as dark as the background
ctx.fillRect(x1, monitorIndex[Event.MonitorId]*rowHeight, x2-x1, rowHeight); ctx.fillRect(x1, monitorIndex[Event.MonitorId]*rowHeight, x2-x1, rowHeight);
} // end foreach frame } // end foreach frame
} // end foreach Event } // end foreach Event
for(var i=0; i<numMonitors; i++) { for (var i=0; i<numMonitors; i++) {
// Note that this may be a sparse array // Note that this may be a sparse array
ctx.font= parseInt(rowHeight * timeLabelsFractOfRow).toString() + "px Georgia"; ctx.font= parseInt(rowHeight * timeLabelsFractOfRow).toString() + "px Georgia";
ctx.fillStyle="white"; ctx.fillStyle="white";
@ -439,17 +444,18 @@ function redrawScreen() {
$('ScaleDiv').style.display="none"; $('ScaleDiv').style.display="none";
$('fit').innerHTML="Scale"; $('fit').innerHTML="Scale";
var vh=window.innerHeight; var vh=window.innerHeight;
var vw=window.innerWidth;
var pos=$('monitors').getPosition(); var pos=$('monitors').getPosition();
var mh=(vh - pos.y - $('fps').getSize().y); var mh=(vh - pos.y - $('fps').getSize().y);
$('monitors').setStyle('height', mh.toString() + "px"); // leave a small gap at bottom $('monitors').setStyle('height', mh.toString() + "px"); // leave a small gap at bottom
if(maxfit2($('monitors').getSize().x, $('monitors').getSize().y) == 0) /// if we fail to fix we back out of fit mode -- ??? This may need some better handling if (maxfit2($('monitors').getSize().x, $('monitors').getSize().y) == 0) { /// if we fail to fix we back out of fit mode -- ??? This may need some better handling
fitMode=1-fitMode; fitMode=1-fitMode;
}
} else { } else {
// switch out of fit mode // switch out of fit mode
// if we fit, then monitors were absolutely positioned already (or will be) otherwise release them to float // if we fit, then monitors were absolutely positioned already (or will be) otherwise release them to float
for( var i=0; i<numMonitors; i++ ) for ( var i=0; i<numMonitors; i++ ) {
monitorCanvasObj[monitorPtr[i]].style.position=""; monitorCanvasObj[monitorPtr[i]].style.position="";
}
$('monitors').setStyle('height', "auto"); $('monitors').setStyle('height', "auto");
$('ScaleDiv').style.display="inline"; $('ScaleDiv').style.display="inline";
$('ScaleDiv').style.display="inline-flex"; $('ScaleDiv').style.display="inline-flex";
@ -481,22 +487,30 @@ function relMouseCoords(event) {
do { do {
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft; totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop; totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
} while(currentElement = currentElement.offsetParent); } while (currentElement = currentElement.offsetParent);
canvasX = event.pageX - totalOffsetX; canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY; canvasY = event.pageY - totalOffsetY;
return {x:canvasX, y:canvasY}; return {x: canvasX, y: canvasY};
} }
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords; HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
// These are the functions for mouse movement in the timeline. Note that touch is treated as a mouse move with mouse down // These are the functions for mouse movement in the timeline. Note that touch is treated as a mouse move with mouse down
var mouseisdown=false; var mouseisdown=false;
function mdown(event) {mouseisdown=true; mmove(event);} function mdown(event) {
function mup(event) {mouseisdown=false;} mouseisdown=true; mmove(event);
function mout(event) {mouseisdown=false;} // if we go outside treat it as release }
function tmove(event) {mouseisdown=true; mmove(event);} function mup(event) {
mouseisdown=false;
}
function mout(event) {
mouseisdown=false;
} // if we go outside treat it as release
function tmove(event) {
mouseisdown=true; mmove(event);
}
function mmove(event) { function mmove(event) {
if ( mouseisdown ) { if ( mouseisdown ) {
@ -546,7 +560,7 @@ function showScale(newscale) {
function setScale(newscale) { function setScale(newscale) {
// makes actual change // makes actual change
showScale(newscale); showScale(newscale);
for(var i=0; i<numMonitors; i++) { for (var i=0; i<numMonitors; i++) {
monitorCanvasObj[monitorPtr[i]].width=monitorWidth[monitorPtr[i]]*monitorNormalizeScale[monitorPtr[i]]*monitorZoomScale[monitorPtr[i]]*newscale; monitorCanvasObj[monitorPtr[i]].width=monitorWidth[monitorPtr[i]]*monitorNormalizeScale[monitorPtr[i]]*monitorZoomScale[monitorPtr[i]]*newscale;
monitorCanvasObj[monitorPtr[i]].height=monitorHeight[monitorPtr[i]]*monitorNormalizeScale[monitorPtr[i]]*monitorZoomScale[monitorPtr[i]]*newscale; monitorCanvasObj[monitorPtr[i]].height=monitorHeight[monitorPtr[i]]*monitorNormalizeScale[monitorPtr[i]]*monitorZoomScale[monitorPtr[i]]*newscale;
} }
@ -590,8 +604,9 @@ function clicknav(minSecs, maxSecs, live) {// we use the current time if we can
var maxStr = ""; var maxStr = "";
var currentStr = ""; var currentStr = "";
if ( minSecs > 0 ) { if ( minSecs > 0 ) {
if ( maxSecs > now ) if ( maxSecs > now ) {
maxSecs = parseInt(now); maxSecs = parseInt(now);
}
maxStr="&maxTime=" + secs2inputstr(maxSecs); maxStr="&maxTime=" + secs2inputstr(maxSecs);
$('maxTime').value = secs2inputstr(maxSecs); $('maxTime').value = secs2inputstr(maxSecs);
} }
@ -605,18 +620,22 @@ function clicknav(minSecs, maxSecs, live) {// we use the current time if we can
} }
var intervalStr="&displayinterval=" + currentDisplayInterval.toString(); var intervalStr="&displayinterval=" + currentDisplayInterval.toString();
if ( minSecs && maxSecs ) { if ( minSecs && maxSecs ) {
if ( currentTimeSecs > minSecs && currentTimeSecs < maxSecs ) // make sure time is in the new range if ( currentTimeSecs > minSecs && currentTimeSecs < maxSecs ) { // make sure time is in the new range
currentStr="&current=" + secs2dbstr(currentTimeSecs); currentStr="&current=" + secs2dbstr(currentTimeSecs);
} }
}
var liveStr="&live=0"; var liveStr="&live=0";
if ( live == 1 ) if ( live == 1 ) {
liveStr="&live=1"; liveStr="&live=1";
}
var zoomStr=""; var zoomStr="";
for ( var i=0; i < numMonitors; i++ ) for ( var i=0; i < numMonitors; i++ ) {
if ( monitorZoomScale[monitorPtr[i]] < 0.99 || monitorZoomScale[monitorPtr[i]] > 1.01 ) // allow for some up/down changes and just treat as 1 of almost 1 if ( monitorZoomScale[monitorPtr[i]] < 0.99 || monitorZoomScale[monitorPtr[i]] > 1.01 ) { // allow for some up/down changes and just treat as 1 of almost 1
zoomStr += "&z" + monitorPtr[i].toString() + "=" + monitorZoomScale[monitorPtr[i]].toFixed(2); zoomStr += "&z" + monitorPtr[i].toString() + "=" + monitorZoomScale[monitorPtr[i]].toFixed(2);
}
}
var uri = "?view=" + currentView + '&fit='+(fitMode==1?'1':'0') + minStr + maxStr + currentStr + intervalStr + liveStr + zoomStr + "&scale=" + $j("#scaleslider")[0].value + "&speed=" + speeds[$j("#speedslider")[0].value]; var uri = "?view=" + currentView + '&fit='+(fitMode==1?'1':'0') + minStr + maxStr + currentStr + intervalStr + liveStr + zoomStr + "&scale=" + $j("#scaleslider")[0].value + "&speed=" + speeds[$j("#speedslider")[0].value];
window.location = uri; window.location = uri;
@ -684,7 +703,6 @@ function maxfit2(divW, divH) {
var bestFitX2=[]; var bestFitX2=[];
var bestFitY=[]; var bestFitY=[];
var bestFitY2=[]; var bestFitY2=[];
var bestFitScale;
var minScale=0.05; var minScale=0.05;
var maxScale=5.00; var maxScale=5.00;
@ -694,8 +712,8 @@ function maxfit2(divW, divH) {
//monitorPtr.sort(compSize); //Sorts monitors by size in viewport. If enabled makes captions not line up with graphs. //monitorPtr.sort(compSize); //Sorts monitors by size in viewport. If enabled makes captions not line up with graphs.
while(1) { while (1) {
if( maxScale - minScale < 0.01 ) break; if ( maxScale - minScale < 0.01 ) break;
var thisScale = (maxScale + minScale) / 2; var thisScale = (maxScale + minScale) / 2;
var allFit=1; var allFit=1;
var thisArea=0; var thisArea=0;
@ -709,15 +727,17 @@ function maxfit2(divW, divH) {
var monId = monitorPtr[m]; var monId = monitorPtr[m];
function doesItFit(x, y, w, h, d) { // does block (w,h) fit at position (x,y) relative to edge and other nodes already done (0..d) function doesItFit(x, y, w, h, d) { // does block (w,h) fit at position (x,y) relative to edge and other nodes already done (0..d)
if(x+w>=divW) return 0; if (x+w>=divW) return 0;
if(y+h>=divH) return 0; if (y+h>=divH) return 0;
for(var i=0; i<=d; i++) for (var i=0; i<=d; i++) {
if( !( thisX[i]>x+w-1 || thisX2[i] < x || thisY[i] > y+h-1 || thisY2[i] < y ) ) return 0; if ( !( thisX[i]>x+w-1 || thisX2[i] < x || thisY[i] > y+h-1 || thisY2[i] < y ) ) return 0;
}
return 1; // it's OK return 1; // it's OK
} }
if ( borders <= 0 ) if ( borders <= 0 ) {
borders=$("Monitor"+monId).getStyle("border").toInt() * 2; // assume fixed size border, and added to both sides and top/bottom borders=$("Monitor"+monId).getStyle("border").toInt() * 2;
} // assume fixed size border, and added to both sides and top/bottom
// try fitting over first, then down. Each new one must land at either upper right or lower left corner of last (try in that order) // try fitting over first, then down. Each new one must land at either upper right or lower left corner of last (try in that order)
// Pick the one with the smallest Y, then smallest X if Y equal // Pick the one with the smallest Y, then smallest X if Y equal
var fitX = 999999999; var fitX = 999999999;
@ -756,7 +776,7 @@ function maxfit2(divW, divH) {
} }
if ( allFit == 1 ) { if ( allFit == 1 ) {
minScale=thisScale; minScale=thisScale;
if(bestFitArea<thisArea) { if (bestFitArea<thisArea) {
bestFitArea=thisArea; bestFitArea=thisArea;
bestFitX=thisX; bestFitX=thisX;
bestFitY=thisY; bestFitY=thisY;
@ -819,12 +839,13 @@ function clickMonitor(event, monId) {
var monitor_element = $("Monitor"+monId.toString()); var monitor_element = $("Monitor"+monId.toString());
var pos_x = event.offsetX ? (event.offsetX) : event.pageX - monitor_element.offsetLeft; var pos_x = event.offsetX ? (event.offsetX) : event.pageX - monitor_element.offsetLeft;
var pos_y = event.offsetY ? (event.offsetY) : event.pageY - monitor_element.offsetTop; var pos_y = event.offsetY ? (event.offsetY) : event.pageY - monitor_element.offsetTop;
if ( pos_x < monitor_element.width/4 && pos_y < monitor_element.height/4 ) if ( pos_x < monitor_element.width/4 && pos_y < monitor_element.height/4 ) {
zoom(monId, 1.15); zoom(monId, 1.15);
else if ( pos_x > monitor_element.width * 3/4 && pos_y < monitor_element.height/4 ) } else if ( pos_x > monitor_element.width * 3/4 && pos_y < monitor_element.height/4 ) {
zoom(monId, 1/1.15); zoom(monId, 1/1.15);
else } else {
showOneMonitor(monId); showOneMonitor(monId);
}
return; return;
} }
@ -837,7 +858,7 @@ function changeDateTime(e) {
if ( minTime.isAfter(maxTime) ) { if ( minTime.isAfter(maxTime) ) {
maxTime_element.parent().addClass('has-error'); maxTime_element.parent().addClass('has-error');
return; // Don't reload because we have invalid datetime filter. return; // Don't reload because we have invalid datetime filter.
} else { } else {
maxTime_element.parent().removeClass('has-error'); maxTime_element.parent().removeClass('has-error');
} }
@ -848,9 +869,11 @@ function changeDateTime(e) {
var fitStr ="&fit="+(fitMode?"1":"0"); var fitStr ="&fit="+(fitMode?"1":"0");
var zoomStr=""; var zoomStr="";
for ( var i=0; i < numMonitors; i++ ) for ( var i=0; i < numMonitors; i++ ) {
if ( monitorZoomScale[monitorPtr[i]] < 0.99 || monitorZoomScale[monitorPtr[i]] > 1.01 ) // allow for some up/down changes and just treat as 1 of almost 1 if ( monitorZoomScale[monitorPtr[i]] < 0.99 || monitorZoomScale[monitorPtr[i]] > 1.01 ) { // allow for some up/down changes and just treat as 1 of almost 1
zoomStr += "&z" + monitorPtr[i].toString() + "=" + monitorZoomScale[monitorPtr[i]].toFixed(2); zoomStr += "&z" + monitorPtr[i].toString() + "=" + monitorZoomScale[monitorPtr[i]].toFixed(2);
}
}
var uri = "?view=" + currentView + fitStr + minStr + maxStr + liveStr + zoomStr + "&scale=" + $j("#scaleslider")[0].value + "&speed=" + speeds[$j("#speedslider")[0].value]; var uri = "?view=" + currentView + fitStr + minStr + maxStr + liveStr + zoomStr + "&scale=" + $j("#scaleslider")[0].value + "&speed=" + speeds[$j("#speedslider")[0].value];
window.location = uri; window.location = uri;
@ -876,8 +899,12 @@ function initPage() {
monitorCanvasCtx[monId] = monitorCanvasObj[monId].getContext('2d'); monitorCanvasCtx[monId] = monitorCanvasObj[monId].getContext('2d');
var imageObject = monitorImageObject[monId] = new Image(); var imageObject = monitorImageObject[monId] = new Image();
imageObject.monId = monId; imageObject.monId = monId;
imageObject.onload = function() {imagedone(this, this.monId, true );}; imageObject.onload = function() {
imageObject.onerror = function() {imagedone(this, this.monId, false );}; imagedone(this, this.monId, true );
};
imageObject.onerror = function() {
imagedone(this, this.monId, false );
};
loadImage2Monitor( monId, monitorImageURL[monId] ); loadImage2Monitor( monId, monitorImageURL[monId] );
} }
} }
@ -914,6 +941,6 @@ function initPage() {
} }
}); });
} }
window.addEventListener("resize", redrawScreen, {passive:true}); window.addEventListener("resize", redrawScreen, {passive: true});
// Kick everything off // Kick everything off
window.addEvent( 'domready', initPage ); window.addEvent( 'domready', initPage );

View File

@ -29,7 +29,7 @@ function configureButtons( element ) {
(form.username == "") || (form.username == null) || (form.username == "") || (form.username == null) ||
(form.password == "") || (form.password == null); (form.password == "") || (form.password == null);
} }
if(form.elements.namedItem("saveBtn")) { if (form.elements.namedItem("saveBtn")) {
form.saveBtn.disabled = (form.probe.selectedIndex==0); form.saveBtn.disabled = (form.probe.selectedIndex==0);
} }
} }

View File

@ -1,5 +1,5 @@
function validateForm( form ) { function validateForm( form ) {
return( true ); return ( true );
} }
function submitForm( form ) { function submitForm( form ) {
@ -16,7 +16,7 @@ function limitRange( field, minValue, maxValue ) {
} }
function initPage() { function initPage() {
return( true ); return ( true );
} }
window.addEvent( 'domready', initPage ); window.addEvent( 'domready', initPage );

View File

@ -1,9 +1,10 @@
function submitForm( element ) { function submitForm( element ) {
var form = element.form; var form = element.form;
if ( form.option.selectedIndex == 0 ) if ( form.option.selectedIndex == 0 ) {
form.view.value = currentView; form.view.value = currentView;
else } else {
form.view.value = 'none'; form.view.value = 'none';
}
form.submit(); form.submit();
} }

View File

@ -12,7 +12,7 @@ function changeDateTime(e) {
} }
minTime_element[0].form.submit(); minTime_element[0].form.submit();
return; return;
var minStr = "&minTime="+($j('#minTime')[0].value); var minStr = "&minTime="+($j('#minTime')[0].value);
var maxStr = "&maxTime="+($j('#maxTime')[0].value); var maxStr = "&maxTime="+($j('#maxTime')[0].value);
@ -20,9 +20,11 @@ return;
var fitStr ="&fit="+(fitMode?"1":"0"); var fitStr ="&fit="+(fitMode?"1":"0");
var zoomStr=""; var zoomStr="";
for ( var i=0; i < numMonitors; i++ ) for ( var i=0; i < numMonitors; i++ ) {
if ( monitorZoomScale[monitorPtr[i]] < 0.99 || monitorZoomScale[monitorPtr[i]] > 1.01 ) // allow for some up/down changes and just treat as 1 of almost 1 if ( monitorZoomScale[monitorPtr[i]] < 0.99 || monitorZoomScale[monitorPtr[i]] > 1.01 ) { // allow for some up/down changes and just treat as 1 of almost 1
zoomStr += "&z" + monitorPtr[i].toString() + "=" + monitorZoomScale[monitorPtr[i]].toFixed(2); zoomStr += "&z" + monitorPtr[i].toString() + "=" + monitorZoomScale[monitorPtr[i]].toFixed(2);
}
}
var uri = "?view=" + currentView + fitStr + minStr + maxStr + liveStr + zoomStr + "&scale=" + $j("#scaleslider")[0].value + "&speed=" + speeds[$j("#speedslider")[0].value]; var uri = "?view=" + currentView + fitStr + minStr + maxStr + liveStr + zoomStr + "&scale=" + $j("#scaleslider")[0].value + "&speed=" + speeds[$j("#speedslider")[0].value];
window.location = uri; window.location = uri;

View File

@ -5,7 +5,7 @@ function validateForm(form) {
} }
if ( errors.length ) { if ( errors.length ) {
alert( errors.join( "\n" ) ); alert( errors.join( "\n" ) );
return( false ); return ( false );
} }
return( true ); return ( true );
} }

View File

@ -40,11 +40,11 @@ $j(document).ready(function() {
function stateStuff( action, runState, newState ) { function stateStuff( action, runState, newState ) {
var formData = { var formData = {
'view' : 'console', 'view': 'console',
'action' : action, 'action': action,
'apply' : 1, 'apply': 1,
'runState' : runState, 'runState': runState,
'newState' : newState 'newState': newState
}; };
console.log(formData); console.log(formData);

View File

@ -1,3 +1,4 @@
function validateForm(form) { function validateForm(form) {
var errors = []; var errors = [];
if ( !form.elements['newStorage[Name]'].value ) { if ( !form.elements['newStorage[Name]'].value ) {

View File

@ -16,19 +16,22 @@ function showEvent( eid, fid, width, height ) {
function createEventHtml( event, frame ) { function createEventHtml( event, frame ) {
var eventHtml = new Element( 'div' ); var eventHtml = new Element( 'div' );
if ( event.Archived > 0 ) if ( event.Archived > 0 ) {
eventHtml.addClass( 'archived' ); eventHtml.addClass( 'archived' );
}
new Element( 'p' ).inject( eventHtml ).set( 'text', monitors[event.MonitorId].Name ); new Element( 'p' ).inject( eventHtml ).set( 'text', monitors[event.MonitorId].Name );
new Element( 'p' ).inject( eventHtml ).set( 'text', event.Name+(frame?("("+frame.FrameId+")"):"") ); new Element( 'p' ).inject( eventHtml ).set( 'text', event.Name+(frame?("("+frame.FrameId+")"):"") );
new Element( 'p' ).inject( eventHtml ).set( 'text', event.StartTime+" - "+event.Length+"s" ); new Element( 'p' ).inject( eventHtml ).set( 'text', event.StartTime+" - "+event.Length+"s" );
new Element( 'p' ).inject( eventHtml ).set( 'text', event.Cause ); new Element( 'p' ).inject( eventHtml ).set( 'text', event.Cause );
if ( event.Notes ) if ( event.Notes ) {
new Element( 'p' ).inject( eventHtml ).set( 'text', event.Notes ); new Element( 'p' ).inject( eventHtml ).set( 'text', event.Notes );
if ( event.Archived > 0 ) }
if ( event.Archived > 0 ) {
new Element( 'p' ).inject( eventHtml ).set( 'text', archivedString ); new Element( 'p' ).inject( eventHtml ).set( 'text', archivedString );
}
return( eventHtml ); return ( eventHtml );
} }
function showEventDetail( eventHtml ) { function showEventDetail( eventHtml ) {
@ -66,7 +69,7 @@ function frameDataResponse( respObj, respText ) {
if ( !event['frames'] ) { if ( !event['frames'] ) {
console.log("No frames data in event response"); console.log("No frames data in event response");
event['frames'] = new Object(); event['frames'] = {};
} }
event['frames'][frame.FrameId] = frame; event['frames'][frame.FrameId] = frame;
@ -75,8 +78,8 @@ function frameDataResponse( respObj, respText ) {
previewEvent(frame.EventId, frame.FrameId); previewEvent(frame.EventId, frame.FrameId);
} }
var eventQuery = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse } ); var eventQuery = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse} );
var frameQuery = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse } ); var frameQuery = new Request.JSON( {url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse} );
function requestFrameData( eventId, frameId ) { function requestFrameData( eventId, frameId ) {
if ( !events[eventId] ) { if ( !events[eventId] ) {
@ -119,16 +122,17 @@ function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, dur
var sources = vid.getElementsByTagName('source'); var sources = vid.getElementsByTagName('source');
sources[0].src = newsource; sources[0].src = newsource;
var tracks = vid.getElementsByTagName('track'); var tracks = vid.getElementsByTagName('track');
if(tracks.length) { if (tracks.length) {
tracks[0].parentNode.removeChild(tracks[0]); tracks[0].parentNode.removeChild(tracks[0]);
} }
vid.load(); vid.load();
addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime);
vid.currentTime = fid/fps; vid.currentTime = fid/fps;
} else { } else {
if ( ! vid.seeking ) if ( ! vid.seeking ) {
vid.currentTime=fid/fps; vid.currentTime=fid/fps;
} }
}
} else { } else {
if ( vid ) vid.hide(); if ( vid ) vid.hide();
imageSrc.show(); imageSrc.show();

View File

@ -14,13 +14,14 @@ function validateForm( form, newUser ) {
} }
var monitorIds = new Array(); var monitorIds = new Array();
for ( var i = 0; i < form.elements['monitorIds'].options.length; i++ ) { for ( var i = 0; i < form.elements['monitorIds'].options.length; i++ ) {
if ( form.elements['monitorIds'].options[i].selected ) if ( form.elements['monitorIds'].options[i].selected ) {
monitorIds[monitorIds.length] = form.elements['monitorIds'].options[i].value; monitorIds[monitorIds.length] = form.elements['monitorIds'].options[i].value;
} }
}
form.elements['newUser[MonitorIds]'].value = monitorIds.join( ',' ); form.elements['newUser[MonitorIds]'].value = monitorIds.join( ',' );
if ( errors.length ) { if ( errors.length ) {
alert( errors.join( "\n" ) ); alert( errors.join( "\n" ) );
return( false ); return ( false );
} }
return( true ); return ( true );
} }

View File

@ -10,10 +10,11 @@ var generateVideoTimer = null;
function generateVideoProgress() { function generateVideoProgress() {
var tickerText = $('videoProgressTicker').get('text'); var tickerText = $('videoProgressTicker').get('text');
if ( tickerText.length < 1 || tickerText.length > 4 ) if ( tickerText.length < 1 || tickerText.length > 4 ) {
$('videoProgressTicker').set( 'text', '.' ); $('videoProgressTicker').set( 'text', '.' );
else } else {
$('videoProgressTicker').appendText( '.' ); $('videoProgressTicker').appendText( '.' );
}
} }
function generateVideoResponse( respObj, respText ) { function generateVideoResponse( respObj, respText ) {
@ -23,7 +24,7 @@ function generateVideoResponse( respObj, respText ) {
function generateVideo( form ) { function generateVideo( form ) {
var parms = 'view=request&request=event&action=video'; var parms = 'view=request&request=event&action=video';
parms += '&'+$(form).toQueryString(); parms += '&'+$(form).toQueryString();
var query = new Request.JSON( { url: thisUrl, method: 'post', data: parms, onSuccess: generateVideoResponse } ); var query = new Request.JSON( {url: thisUrl, method: 'post', data: parms, onSuccess: generateVideoResponse} );
query.send(); query.send();
$('videoProgress').removeClass( 'hidden' ); $('videoProgress').removeClass( 'hidden' );
$('videoProgress').setProperty( 'class', 'warnText' ); $('videoProgress').setProperty( 'class', 'warnText' );

View File

@ -8,20 +8,24 @@ function setButtonState(element, butClass) {
function showEvents() { function showEvents() {
$('ptzControls').addClass( 'hidden' ); $('ptzControls').addClass( 'hidden' );
$('events').removeClass( 'hidden' ); $('events').removeClass( 'hidden' );
if ( $('eventsControl') ) if ( $('eventsControl') ) {
$('eventsControl').addClass('hidden'); $('eventsControl').addClass('hidden');
if ( $('controlControl') ) }
if ( $('controlControl') ) {
$('controlControl').removeClass('hidden'); $('controlControl').removeClass('hidden');
}
showMode = "events"; showMode = "events";
} }
function showPtzControls() { function showPtzControls() {
$('events').addClass( 'hidden' ); $('events').addClass( 'hidden' );
$('ptzControls').removeClass( 'hidden' ); $('ptzControls').removeClass( 'hidden' );
if ( $('eventsControl') ) if ( $('eventsControl') ) {
$('eventsControl').removeClass('hidden'); $('eventsControl').removeClass('hidden');
if ( $('controlControl') ) }
if ( $('controlControl') ) {
$('controlControl').addClass('hidden'); $('controlControl').addClass('hidden');
}
showMode = "control"; showMode = "control";
} }
@ -40,7 +44,7 @@ function changeScale() {
newHeight = monitorHeight * scale / SCALE_BASE; newHeight = monitorHeight * scale / SCALE_BASE;
} }
Cookie.write( 'zmWatchScale'+monitorId, scale, { duration: 10*365 } ); Cookie.write( 'zmWatchScale'+monitorId, scale, {duration: 10*365} );
/*Stream could be an applet so can't use moo tools*/ /*Stream could be an applet so can't use moo tools*/
var streamImg = $('liveStream'+monitorId); var streamImg = $('liveStream'+monitorId);
@ -60,17 +64,18 @@ var lastAlarmState = STATE_IDLE;
function setAlarmState( currentAlarmState ) { function setAlarmState( currentAlarmState ) {
alarmState = currentAlarmState; alarmState = currentAlarmState;
var stateString = "Unknown";
var stateClass = ""; var stateClass = "";
if ( alarmState == STATE_ALARM ) if ( alarmState == STATE_ALARM ) {
stateClass = "alarm"; stateClass = "alarm";
else if ( alarmState == STATE_ALERT ) } else if ( alarmState == STATE_ALERT ) {
stateClass = "alert"; stateClass = "alert";
}
$('stateValue').set( 'text', stateStrings[alarmState] ); $('stateValue').set( 'text', stateStrings[alarmState] );
if ( stateClass ) if ( stateClass ) {
$('stateValue').setProperty( 'class', stateClass ); $('stateValue').setProperty( 'class', stateClass );
else } else {
$('stateValue').removeProperty( 'class' ); $('stateValue').removeProperty( 'class' );
}
var isAlarmed = ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ); var isAlarmed = ( alarmState == STATE_ALARM || alarmState == STATE_ALERT );
var wasAlarmed = ( lastAlarmState == STATE_ALARM || lastAlarmState == STATE_ALERT ); var wasAlarmed = ( lastAlarmState == STATE_ALARM || lastAlarmState == STATE_ALERT );
@ -81,11 +86,12 @@ function setAlarmState( currentAlarmState ) {
if ( newAlarm ) { if ( newAlarm ) {
if ( SOUND_ON_ALARM ) { if ( SOUND_ON_ALARM ) {
// Enable the alarm sound // Enable the alarm sound
if ( !canPlayPauseAudio ) if ( !canPlayPauseAudio ) {
$('alarmSound').removeClass( 'hidden' ); $('alarmSound').removeClass( 'hidden' );
else } else {
$('MediaPlayer').Play(); $('MediaPlayer').Play();
} }
}
if ( POPUP_ON_ALARM ) { if ( POPUP_ON_ALARM ) {
window.focus(); window.focus();
} }
@ -93,22 +99,25 @@ function setAlarmState( currentAlarmState ) {
if ( SOUND_ON_ALARM ) { if ( SOUND_ON_ALARM ) {
if ( oldAlarm ) { if ( oldAlarm ) {
// Disable alarm sound // Disable alarm sound
if ( !canPlayPauseAudio ) if ( !canPlayPauseAudio ) {
$('alarmSound').addClass( 'hidden' ); $('alarmSound').addClass( 'hidden' );
else } else {
$('MediaPlayer').Stop(); $('MediaPlayer').Stop();
} }
} }
if ( oldAlarm) //done with an event do a refresh }
if (oldAlarm) { // done with an event do a refresh
eventCmdQuery(); eventCmdQuery();
}
lastAlarmState = alarmState; lastAlarmState = alarmState;
} }
if ( monitorType != 'WebSite' ) { if ( monitorType != 'WebSite' ) {
var streamCmdParms = "view=request&request=stream&connkey="+connKey; var streamCmdParms = "view=request&request=stream&connkey="+connKey;
if ( auth_hash ) if ( auth_hash ) {
streamCmdParms += '&auth='+auth_hash; streamCmdParms += '&auth='+auth_hash;
}
var streamCmdReq = new Request.JSON( { var streamCmdReq = new Request.JSON( {
url: monitorUrl, url: monitorUrl,
method: 'get', method: 'get',
@ -134,8 +143,9 @@ function getStreamCmdFailure(xhr) {
function getStreamCmdResponse(respObj, respText) { function getStreamCmdResponse(respObj, respText) {
watchdogOk("stream"); watchdogOk("stream");
console.log('stream'); console.log('stream');
if ( streamCmdTimer ) if ( streamCmdTimer ) {
streamCmdTimer = clearTimeout(streamCmdTimer); streamCmdTimer = clearTimeout(streamCmdTimer);
}
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
// The get status command can get backed up, in which case we won't be able to get the semaphore and will exit. // The get status command can get backed up, in which case we won't be able to get the semaphore and will exit.
if ( respObj.status ) { if ( respObj.status ) {
@ -145,12 +155,13 @@ function getStreamCmdResponse(respObj, respText) {
setAlarmState(streamStatus.state); setAlarmState(streamStatus.state);
$('levelValue').set('text', streamStatus.level); $('levelValue').set('text', streamStatus.level);
if ( streamStatus.level > 95 ) if ( streamStatus.level > 95 ) {
$('levelValue').className = "alarm"; $('levelValue').className = "alarm";
else if ( streamStatus.level > 80 ) } else if ( streamStatus.level > 80 ) {
$('levelValue').className = "alert"; $('levelValue').className = "alert";
else } else {
$('levelValue').className = "ok"; $('levelValue').className = "ok";
}
var delayString = secsToTime(streamStatus.delay); var delayString = secsToTime(streamStatus.delay);
@ -171,15 +182,17 @@ function getStreamCmdResponse(respObj, respText) {
if ( streamStatus.rate == 1 ) { if ( streamStatus.rate == 1 ) {
streamCmdPlay(false); streamCmdPlay(false);
} else if ( streamStatus.rate > 0 ) { } else if ( streamStatus.rate > 0 ) {
if ( streamStatus.rate < 1 ) if ( streamStatus.rate < 1 ) {
streamCmdSlowFwd(false); streamCmdSlowFwd(false);
else
streamCmdFastFwd(false);
} else { } else {
if ( streamStatus.rate > -1 ) streamCmdFastFwd(false);
}
} else {
if ( streamStatus.rate > -1 ) {
streamCmdSlowRev(false); streamCmdSlowRev(false);
else } else {
streamCmdFastRev(false); streamCmdFastRev(false);
}
} // rate } // rate
} else { } else {
$('modeValue').set( 'text', "Live" ); $('modeValue').set( 'text', "Live" );
@ -190,10 +203,11 @@ function getStreamCmdResponse(respObj, respText) {
} // end if paused or delayed } // end if paused or delayed
$('zoomValue').set( 'text', streamStatus.zoom ); $('zoomValue').set( 'text', streamStatus.zoom );
if ( streamStatus.zoom == "1.0" ) if ( streamStatus.zoom == "1.0" ) {
setButtonState( $('zoomOutBtn'), 'unavail' ); setButtonState( $('zoomOutBtn'), 'unavail' );
else } else {
setButtonState( $('zoomOutBtn'), 'inactive' ); setButtonState( $('zoomOutBtn'), 'inactive' );
}
if ( canEditMonitors ) { if ( canEditMonitors ) {
if ( streamStatus.enabled ) { if ( streamStatus.enabled ) {
@ -219,8 +233,9 @@ function getStreamCmdResponse(respObj, respText) {
console.log("Have a new auth hash" + streamStatus.auth); console.log("Have a new auth hash" + streamStatus.auth);
// Try to reload the image stream. // Try to reload the image stream.
var streamImg = $('liveStream'); var streamImg = $('liveStream');
if ( streamImg ) if ( streamImg ) {
streamImg.src = streamImg.src.replace(/auth=\w+/i, 'auth='+streamStatus.auth); streamImg.src = streamImg.src.replace(/auth=\w+/i, 'auth='+streamStatus.auth);
}
} // end if have a new auth hash } // end if have a new auth hash
} // end if respObj.status } // end if respObj.status
} else { } else {
@ -240,8 +255,9 @@ function getStreamCmdResponse(respObj, respText) {
} }
var streamCmdTimeout = statusRefreshTimeout; var streamCmdTimeout = statusRefreshTimeout;
if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) {
streamCmdTimeout = streamCmdTimeout/5; streamCmdTimeout = streamCmdTimeout/5;
}
streamCmdTimer = streamCmdQuery.delay( streamCmdTimeout ); streamCmdTimer = streamCmdQuery.delay( streamCmdTimeout );
} }
@ -253,8 +269,9 @@ function streamCmdPause( action ) {
setButtonState( $('slowFwdBtn'), 'inactive' ); setButtonState( $('slowFwdBtn'), 'inactive' );
setButtonState( $('slowRevBtn'), 'inactive' ); setButtonState( $('slowRevBtn'), 'inactive' );
setButtonState( $('fastRevBtn'), 'inactive' ); setButtonState( $('fastRevBtn'), 'inactive' );
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_PAUSE ); streamCmdReq.send( streamCmdParms+"&command="+CMD_PAUSE );
}
} }
function streamCmdPlay( action ) { function streamCmdPlay( action ) {
@ -273,8 +290,9 @@ function streamCmdPlay( action ) {
setButtonState( $('slowRevBtn'), 'unavail' ); setButtonState( $('slowRevBtn'), 'unavail' );
setButtonState( $('fastRevBtn'), 'unavail' ); setButtonState( $('fastRevBtn'), 'unavail' );
} }
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_PLAY ); streamCmdReq.send( streamCmdParms+"&command="+CMD_PLAY );
}
} }
function streamCmdStop( action ) { function streamCmdStop( action ) {
@ -285,8 +303,9 @@ function streamCmdStop( action ) {
setButtonState( $('slowFwdBtn'), 'unavail' ); setButtonState( $('slowFwdBtn'), 'unavail' );
setButtonState( $('slowRevBtn'), 'unavail' ); setButtonState( $('slowRevBtn'), 'unavail' );
setButtonState( $('fastRevBtn'), 'unavail' ); setButtonState( $('fastRevBtn'), 'unavail' );
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_STOP ); streamCmdReq.send( streamCmdParms+"&command="+CMD_STOP );
}
setButtonState( $('stopBtn'), 'unavail' ); setButtonState( $('stopBtn'), 'unavail' );
setButtonState( $('playBtn'), 'active' ); setButtonState( $('playBtn'), 'active' );
} }
@ -299,8 +318,9 @@ function streamCmdFastFwd( action ) {
setButtonState( $('slowFwdBtn'), 'inactive' ); setButtonState( $('slowFwdBtn'), 'inactive' );
setButtonState( $('slowRevBtn'), 'inactive' ); setButtonState( $('slowRevBtn'), 'inactive' );
setButtonState( $('fastRevBtn'), 'inactive' ); setButtonState( $('fastRevBtn'), 'inactive' );
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_FASTFWD ); streamCmdReq.send( streamCmdParms+"&command="+CMD_FASTFWD );
}
} }
function streamCmdSlowFwd( action ) { function streamCmdSlowFwd( action ) {
@ -311,8 +331,9 @@ function streamCmdSlowFwd( action ) {
setButtonState( $('slowFwdBtn'), 'active' ); setButtonState( $('slowFwdBtn'), 'active' );
setButtonState( $('slowRevBtn'), 'inactive' ); setButtonState( $('slowRevBtn'), 'inactive' );
setButtonState( $('fastRevBtn'), 'inactive' ); setButtonState( $('fastRevBtn'), 'inactive' );
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_SLOWFWD ); streamCmdReq.send( streamCmdParms+"&command="+CMD_SLOWFWD );
}
setButtonState( $('pauseBtn'), 'active' ); setButtonState( $('pauseBtn'), 'active' );
setButtonState( $('slowFwdBtn'), 'inactive' ); setButtonState( $('slowFwdBtn'), 'inactive' );
} }
@ -325,8 +346,9 @@ function streamCmdSlowRev( action ) {
setButtonState( $('slowFwdBtn'), 'inactive' ); setButtonState( $('slowFwdBtn'), 'inactive' );
setButtonState( $('slowRevBtn'), 'active' ); setButtonState( $('slowRevBtn'), 'active' );
setButtonState( $('fastRevBtn'), 'inactive' ); setButtonState( $('fastRevBtn'), 'inactive' );
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_SLOWREV ); streamCmdReq.send( streamCmdParms+"&command="+CMD_SLOWREV );
}
setButtonState( $('pauseBtn'), 'active' ); setButtonState( $('pauseBtn'), 'active' );
setButtonState( $('slowRevBtn'), 'inactive' ); setButtonState( $('slowRevBtn'), 'inactive' );
} }
@ -339,8 +361,9 @@ function streamCmdFastRev( action ) {
setButtonState( $('slowFwdBtn'), 'inactive' ); setButtonState( $('slowFwdBtn'), 'inactive' );
setButtonState( $('slowRevBtn'), 'inactive' ); setButtonState( $('slowRevBtn'), 'inactive' );
setButtonState( $('fastRevBtn'), 'inactive' ); setButtonState( $('fastRevBtn'), 'inactive' );
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_FASTREV ); streamCmdReq.send( streamCmdParms+"&command="+CMD_FASTREV );
}
} }
function streamCmdZoomIn( x, y ) { function streamCmdZoomIn( x, y ) {
@ -365,26 +388,30 @@ function streamCmdQuery() {
if ( monitorType != 'WebSite' ) { if ( monitorType != 'WebSite' ) {
var statusCmdParms = "view=request&request=status&entity=monitor&id="+monitorId+"&element[]=Status&element[]=FrameRate"; var statusCmdParms = "view=request&request=status&entity=monitor&id="+monitorId+"&element[]=Status&element[]=FrameRate";
if ( auth_hash ) if ( auth_hash ) {
statusCmdParms += '&auth='+auth_hash; statusCmdParms += '&auth='+auth_hash;
var statusCmdReq = new Request.JSON( { url: monitorUrl, method: 'get', data: statusCmdParms, timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getStatusCmdResponse } ); }
var statusCmdReq = new Request.JSON( {url: monitorUrl, method: 'get', data: statusCmdParms, timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getStatusCmdResponse} );
var statusCmdTimer = null; var statusCmdTimer = null;
} }
function getStatusCmdResponse(respObj, respText) { function getStatusCmdResponse(respObj, respText) {
watchdogOk("status"); watchdogOk("status");
if ( statusCmdTimer ) if ( statusCmdTimer ) {
statusCmdTimer = clearTimeout(statusCmdTimer); statusCmdTimer = clearTimeout(statusCmdTimer);
}
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
$('fpsValue').set('text', respObj.monitor.FrameRate); $('fpsValue').set('text', respObj.monitor.FrameRate);
setAlarmState(respObj.monitor.Status); setAlarmState(respObj.monitor.Status);
} else } else {
checkStreamForErrors("getStatusCmdResponse", respObj); checkStreamForErrors("getStatusCmdResponse", respObj);
}
var statusCmdTimeout = statusRefreshTimeout; var statusCmdTimeout = statusRefreshTimeout;
if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) {
statusCmdTimeout = statusCmdTimeout/5; statusCmdTimeout = statusCmdTimeout/5;
}
statusCmdTimer = statusCmdQuery.delay( statusCmdTimeout ); statusCmdTimer = statusCmdQuery.delay( statusCmdTimeout );
} }
@ -394,8 +421,9 @@ function statusCmdQuery() {
if ( monitorType != 'WebSite' ) { if ( monitorType != 'WebSite' ) {
var alarmCmdParms = "view=request&request=alarm&id="+monitorId; var alarmCmdParms = "view=request&request=alarm&id="+monitorId;
if ( auth_hash ) if ( auth_hash ) {
alarmCmdParms += '&auth='+auth_hash; alarmCmdParms += '&auth='+auth_hash;
}
var alarmCmdReq = new Request.JSON( { var alarmCmdReq = new Request.JSON( {
url: monitorUrl, url: monitorUrl,
method: 'get', method: 'get',
@ -453,8 +481,9 @@ function deleteEvent( event, eventId ) {
if ( monitorType != 'WebSite' ) { if ( monitorType != 'WebSite' ) {
var eventCmdParms = "view=request&request=status&entity=events&id="+monitorId+"&count="+maxDisplayEvents+"&sort=Id%20desc"; var eventCmdParms = "view=request&request=status&entity=events&id="+monitorId+"&count="+maxDisplayEvents+"&sort=Id%20desc";
if ( auth_hash ) if ( auth_hash ) {
eventCmdParms += '&auth='+auth_hash; eventCmdParms += '&auth='+auth_hash;
}
var eventCmdReq = new Request.JSON( { var eventCmdReq = new Request.JSON( {
url: monitorUrl, url: monitorUrl,
method: 'get', method: 'get',
@ -474,8 +503,9 @@ function highlightRow( row ) {
function getEventCmdResponse( respObj, respText ) { function getEventCmdResponse( respObj, respText ) {
watchdogOk("event"); watchdogOk("event");
if ( eventCmdTimer ) if ( eventCmdTimer ) {
eventCmdTimer = clearTimeout( eventCmdTimer ); eventCmdTimer = clearTimeout( eventCmdTimer );
}
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
var dbEvents = respObj.events.reverse(); var dbEvents = respObj.events.reverse();
@ -483,54 +513,57 @@ function getEventCmdResponse( respObj, respText ) {
var eventListBody = $(eventList).getElement( 'tbody' ); var eventListBody = $(eventList).getElement( 'tbody' );
var eventListRows = $(eventListBody).getElements( 'tr' ); var eventListRows = $(eventListBody).getElements( 'tr' );
eventListRows.each( function( row ) { row.removeClass( 'updated' ); } ); eventListRows.each( function( row ) {
row.removeClass( 'updated' );
} );
for ( var i = 0; i < dbEvents.length; i++ ) { for ( var i = 0; i < dbEvents.length; i++ ) {
var event = dbEvents[i]; var event = dbEvents[i];
var row = $('event'+event.Id); var row = $('event'+event.Id);
var newEvent = (row == null ? true : false); var newEvent = (row == null ? true : false);
if ( newEvent ) { if ( newEvent ) {
row = new Element( 'tr', { 'id': 'event'+event.Id } ); row = new Element( 'tr', {'id': 'event'+event.Id} );
new Element( 'td', { 'class': 'colId' } ).inject( row ); new Element( 'td', {'class': 'colId'} ).inject( row );
new Element( 'td', { 'class': 'colName' } ).inject( row ); new Element( 'td', {'class': 'colName'} ).inject( row );
new Element( 'td', { 'class': 'colTime' } ).inject( row ); new Element( 'td', {'class': 'colTime'} ).inject( row );
new Element( 'td', { 'class': 'colSecs' } ).inject( row ); new Element( 'td', {'class': 'colSecs'} ).inject( row );
new Element( 'td', { 'class': 'colFrames' } ).inject( row ); new Element( 'td', {'class': 'colFrames'} ).inject( row );
new Element( 'td', { 'class': 'colScore' } ).inject( row ); new Element( 'td', {'class': 'colScore'} ).inject( row );
new Element( 'td', { 'class': 'colDelete' } ).inject( row ); new Element( 'td', {'class': 'colDelete'} ).inject( row );
var cells = row.getElements( 'td' ); var link = new Element( 'a', {'href': '#', 'events': {'click': createEventPopup.pass( [event.Id, '&filter[Query][terms][0][attr]=MonitorId&filter[Query][terms][0][op]=%3d&filter[Query][terms][0][val]='+monitorId+'&page=1&popup=1', event.Width, event.Height] )}});
var link = new Element( 'a', { 'href': '#', 'events': { 'click': createEventPopup.pass( [event.Id, '&filter[Query][terms][0][attr]=MonitorId&filter[Query][terms][0][op]=%3d&filter[Query][terms][0][val]='+monitorId+'&page=1&popup=1', event.Width, event.Height] ) } });
link.set( 'text', event.Id ); link.set( 'text', event.Id );
link.inject( row.getElement( 'td.colId' ) ); link.inject( row.getElement( 'td.colId' ) );
link = new Element( 'a', { 'href': '#', 'events': { 'click': createEventPopup.pass( [event.Id, '&filter[Query][terms][0][attr]=MonitorId&filter[Query][terms][0][op]=%3d&filter[Query][terms][0][val]='+monitorId+'&page=1&popup=1', event.Width, event.Height] ) } }); link = new Element( 'a', {'href': '#', 'events': {'click': createEventPopup.pass( [event.Id, '&filter[Query][terms][0][attr]=MonitorId&filter[Query][terms][0][op]=%3d&filter[Query][terms][0][val]='+monitorId+'&page=1&popup=1', event.Width, event.Height] )}});
link.set( 'text', event.Name ); link.set( 'text', event.Name );
link.inject( row.getElement( 'td.colName' ) ); link.inject( row.getElement( 'td.colName' ) );
row.getElement( 'td.colTime' ).set( 'text', event.StartTime ); row.getElement( 'td.colTime' ).set( 'text', event.StartTime );
row.getElement( 'td.colSecs' ).set( 'text', event.Length ); row.getElement( 'td.colSecs' ).set( 'text', event.Length );
link = new Element( 'a', { 'href': '#', 'events': { 'click': createFramesPopup.pass( [event.Id, event.Width, event.Height] ) } }); link = new Element( 'a', {'href': '#', 'events': {'click': createFramesPopup.pass( [event.Id, event.Width, event.Height] )}});
link.set( 'text', event.Frames+'/'+event.AlarmFrames ); link.set( 'text', event.Frames+'/'+event.AlarmFrames );
link.inject( row.getElement( 'td.colFrames' ) ); link.inject( row.getElement( 'td.colFrames' ) );
link = new Element( 'a', { 'href': '#', 'events': { 'click': createFramePopup.pass( [event.Id, '0', event.Width, event.Height] ) } }); link = new Element( 'a', {'href': '#', 'events': {'click': createFramePopup.pass( [event.Id, '0', event.Width, event.Height] )}});
link.set( 'text', event.AvgScore+'/'+event.MaxScore ); link.set( 'text', event.AvgScore+'/'+event.MaxScore );
link.inject( row.getElement( 'td.colScore' ) ); link.inject( row.getElement( 'td.colScore' ) );
link = new Element( 'a', { 'href': '#', 'title': deleteString, 'events': { 'click': function( e ) { deleteEvent( e, event.Id ); }, 'mouseover': highlightRow.pass( row ), 'mouseout': highlightRow.pass( row ) } }); link = new Element( 'a', {'href': '#', 'title': deleteString, 'events': {'click': function( e ) {
deleteEvent( e, event.Id );
}, 'mouseover': highlightRow.pass( row ), 'mouseout': highlightRow.pass( row )}});
link.set( 'text', 'X' ); link.set( 'text', 'X' );
link.inject( row.getElement( 'td.colDelete' ) ); link.inject( row.getElement( 'td.colDelete' ) );
if ( i == 0 ) if ( i == 0 ) {
row.inject( $(eventListBody) ); row.inject( $(eventListBody) );
else { } else {
row.inject( $(eventListBody), 'top' ); row.inject( $(eventListBody), 'top' );
if ( !eventCmdFirst ) if ( !eventCmdFirst ) {
row.addClass( 'recent' ); row.addClass( 'recent' );
} }
}
} else { } else {
row.getElement( 'td.colName a' ).set( 'text', event.Name ); row.getElement( 'td.colName a' ).set( 'text', event.Name );
row.getElement( 'td.colSecs' ).set( 'text', event.Length ); row.getElement( 'td.colSecs' ).set( 'text', event.Length );
@ -553,32 +586,37 @@ function getEventCmdResponse( respObj, respText ) {
rows[rows.length-1].destroy(); rows[rows.length-1].destroy();
rows.length--; rows.length--;
} }
} else } else {
checkStreamForErrors("getEventCmdResponse", respObj); checkStreamForErrors("getEventCmdResponse", respObj);
}
var eventCmdTimeout = eventsRefreshTimeout; var eventCmdTimeout = eventsRefreshTimeout;
if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) {
eventCmdTimeout = eventCmdTimeout/5; eventCmdTimeout = eventCmdTimeout/5;
}
eventCmdTimer = eventCmdQuery.delay( eventCmdTimeout ); eventCmdTimer = eventCmdQuery.delay( eventCmdTimeout );
eventCmdFirst = false; eventCmdFirst = false;
} }
function eventCmdQuery() { function eventCmdQuery() {
if ( eventCmdTimer ) //avoid firing another if we are firing one if ( eventCmdTimer ) { // avoid firing another if we are firing one
eventCmdTimer = clearTimeout( eventCmdTimer ); eventCmdTimer = clearTimeout( eventCmdTimer );
}
eventCmdReq.send(); eventCmdReq.send();
} }
if ( monitorType != 'WebSite' ) { if ( monitorType != 'WebSite' ) {
var controlParms = "view=request&request=control&id="+monitorId; var controlParms = "view=request&request=control&id="+monitorId;
if ( auth_hash ) if ( auth_hash ) {
controlParms += '&auth='+auth_hash; controlParms += '&auth='+auth_hash;
var controlReq = new Request.JSON( { url: monitorUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getControlResponse } ); }
var controlReq = new Request.JSON( {url: monitorUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: getControlResponse} );
} }
function getControlResponse( respObj, respText ) { function getControlResponse( respObj, respText ) {
if ( !respObj ) if ( !respObj ) {
return; return;
}
//console.log( respText ); //console.log( respText );
if ( respObj.result != 'Ok' ) { if ( respObj.result != 'Ok' ) {
alert( "Control response was status = "+respObj.status+"\nmessage = "+respObj.message ); alert( "Control response was status = "+respObj.status+"\nmessage = "+respObj.message );
@ -597,24 +635,27 @@ function controlCmd( control, event, xtell, ytell ) {
if ( xtell ) { if ( xtell ) {
var xge = parseInt( (x*100)/coords.width ); var xge = parseInt( (x*100)/coords.width );
if ( xtell == -1 ) if ( xtell == -1 ) {
xge = 100 - xge; xge = 100 - xge;
else if ( xtell == 2 ) } else if ( xtell == 2 ) {
xge = 2*(50 - xge); xge = 2*(50 - xge);
}
locParms += "&xge="+xge; locParms += "&xge="+xge;
} }
if ( ytell ) { if ( ytell ) {
var yge = parseInt( (y*100)/coords.height ); var yge = parseInt( (y*100)/coords.height );
if ( ytell == -1 ) if ( ytell == -1 ) {
yge = 100 - yge; yge = 100 - yge;
else if ( ytell == 2 ) } else if ( ytell == 2 ) {
yge = 2*(50 - yge); yge = 2*(50 - yge);
}
locParms += "&yge="+yge; locParms += "&yge="+yge;
} }
} }
controlReq.send( controlParms+"&control="+control+locParms ); controlReq.send( controlParms+"&control="+control+locParms );
if ( streamMode == "single" ) if ( streamMode == "single" ) {
fetchImage.pass( $('imageFeed').getElement('img') ).delay( 1000 ); fetchImage.pass( $('imageFeed').getElement('img') ).delay( 1000 );
}
} }
function controlCmdImage( x, y ) { function controlCmdImage( x, y ) {
@ -623,8 +664,9 @@ function controlCmdImage( x, y ) {
imageControlParms += "&control="+imageControlMode; imageControlParms += "&control="+imageControlMode;
controlReq.send( imageControlParms+"&x="+x+"&y="+y ); controlReq.send( imageControlParms+"&x="+x+"&y="+y );
if ( streamMode == "single" ) if ( streamMode == "single" ) {
fetchImage.pass( $('imageFeed').getElement('img') ).delay( 1000 ); fetchImage.pass( $('imageFeed').getElement('img') ).delay( 1000 );
}
} }
function fetchImage( streamImage ) { function fetchImage( streamImage ) {
@ -637,10 +679,11 @@ function handleClick( event ) {
var y = event.page.y - $(target).getTop(); var y = event.page.y - $(target).getTop();
if ( showMode == "events" || !imageControlMode ) { if ( showMode == "events" || !imageControlMode ) {
if ( event.shift ) if ( event.shift ) {
streamCmdPan( x, y ); streamCmdPan( x, y );
else } else {
streamCmdZoomIn( x, y ); streamCmdZoomIn( x, y );
}
} else { } else {
controlCmdImage( x, y ); controlCmdImage( x, y );
} }
@ -652,8 +695,9 @@ function appletRefresh() {
var parent = streamImg.getParent(); var parent = streamImg.getParent();
streamImg.dispose(); streamImg.dispose();
streamImg.inject( parent ); streamImg.inject( parent );
if ( appletRefreshTime ) if ( appletRefreshTime ) {
appletRefresh.delay( appletRefreshTime*1000 ); appletRefresh.delay( appletRefreshTime*1000 );
}
} else { } else {
appletRefresh.delay( 15*1000 ); //if we are paused or delayed check every 15 seconds if we are live yet... appletRefresh.delay( 15*1000 ); //if we are paused or delayed check every 15 seconds if we are live yet...
} }
@ -705,23 +749,28 @@ function initPage() {
if ( canStreamNative || streamMode == "single" ) { if ( canStreamNative || streamMode == "single" ) {
var streamImg = $('imageFeed').getElement('img'); var streamImg = $('imageFeed').getElement('img');
if ( !streamImg ) if ( !streamImg ) {
streamImg = $('imageFeed').getElement('object'); streamImg = $('imageFeed').getElement('object');
}
if ( streamMode == "single" ) { if ( streamMode == "single" ) {
streamImg.addEvent('click', fetchImage.pass(streamImg)); streamImg.addEvent('click', fetchImage.pass(streamImg));
fetchImage.pass(streamImg).periodical(imageRefreshTimeout); fetchImage.pass(streamImg).periodical(imageRefreshTimeout);
} else } else {
streamImg.addEvent('click', function(event) { handleClick(event); }); streamImg.addEvent('click', function(event) {
handleClick(event);
});
}
} }
if ( refreshApplet && appletRefreshTime ) if ( refreshApplet && appletRefreshTime ) {
appletRefresh.delay(appletRefreshTime*1000); appletRefresh.delay(appletRefreshTime*1000);
}
if ( scale == "auto" ) changeScale(); if ( scale == "auto" ) changeScale();
if ( window.history.length == 1 ) { if ( window.history.length == 1 ) {
$j('#closeControl').html(''); $j('#closeControl').html('');
} }
} else if ( monitorRefresh > 0 ) { } else if ( monitorRefresh > 0 ) {
var myReload = setInterval(reloadWebSite, monitorRefresh*1000); setInterval(reloadWebSite, monitorRefresh*1000);
} }
} }

View File

@ -49,9 +49,9 @@ function validateForm( form ) {
} }
if ( errors.length ) { if ( errors.length ) {
alert( errors.join( "\n" ) ); alert( errors.join( "\n" ) );
return( false ); return ( false );
} }
return( true ); return ( true );
} }
function submitForm( form ) { function submitForm( form ) {
@ -176,13 +176,15 @@ function applyPreset() {
} }
function toPixels( field, maxValue ) { function toPixels( field, maxValue ) {
if ( field.value != '' ) if ( field.value != '' ) {
field.value = Math.round((field.value*maxValue)/100); field.value = Math.round((field.value*maxValue)/100);
}
} }
function toPercent( field, maxValue ) { function toPercent( field, maxValue ) {
if ( field.value != '' ) if ( field.value != '' ) {
field.value = Math.round((100*100*field.value)/maxValue)/100; field.value = Math.round((100*100*field.value)/maxValue)/100;
}
} }
function applyZoneUnits() { function applyZoneUnits() {
@ -209,8 +211,9 @@ function applyZoneUnits() {
} }
function limitRange( field, minValue, maxValue ) { function limitRange( field, minValue, maxValue ) {
if ( field.value != '' ) if ( field.value != '' ) {
field.value = constrainValue( parseInt(field.value), parseInt(minValue), parseInt(maxValue) ); field.value = constrainValue( parseInt(field.value), parseInt(minValue), parseInt(maxValue) );
}
} }
function limitFilter( field ) { function limitFilter( field ) {
@ -250,9 +253,10 @@ function unsetActivePoint( index ) {
function getCoordString() { function getCoordString() {
var coords = new Array(); var coords = new Array();
for ( var i = 0; i < zone['Points'].length; i++ ) for ( var i = 0; i < zone['Points'].length; i++ ) {
coords[coords.length] = zone['Points'][i].x+','+zone['Points'][i].y; coords[coords.length] = zone['Points'][i].x+','+zone['Points'][i].y;
return( coords.join( " " ) ); }
return ( coords.join( " " ) );
} }
function updateZoneImage() { function updateZoneImage() {
@ -300,14 +304,16 @@ function updateActivePoint( index ) {
function addPoint( index ) { function addPoint( index ) {
var nextIndex = index+1; var nextIndex = index+1;
if ( index >= (zone['Points'].length-1) ) if ( index >= (zone['Points'].length-1) ) {
nextIndex = 0; nextIndex = 0;
}
var newX = parseInt(Math.round((zone['Points'][index]['x']+zone['Points'][nextIndex]['x'])/2)); var newX = parseInt(Math.round((zone['Points'][index]['x']+zone['Points'][nextIndex]['x'])/2));
var newY = parseInt(Math.round((zone['Points'][index]['y']+zone['Points'][nextIndex]['y'])/2)); var newY = parseInt(Math.round((zone['Points'][index]['y']+zone['Points'][nextIndex]['y'])/2));
if ( nextIndex == 0 ) if ( nextIndex == 0 ) {
zone['Points'][zone['Points'].length] = { 'x': newX, 'y': newY }; zone['Points'][zone['Points'].length] = {'x': newX, 'y': newY};
else } else {
zone['Points'].splice( nextIndex, 0, { 'x': newX, 'y': newY } ); zone['Points'].splice( nextIndex, 0, {'x': newX, 'y': newY} );
}
drawZonePoints(); drawZonePoints();
// drawZonePoints calls updateZoneImage // drawZonePoints calls updateZoneImage
//updateZoneImage(); //updateZoneImage();
@ -370,15 +376,17 @@ function saveChanges( element ) {
if ( form.elements['newZone[Type]'].value == 'Privacy' ) { if ( form.elements['newZone[Type]'].value == 'Privacy' ) {
alert( 'Capture process for this monitor will be restarted for the Privacy zone changes to take effect.' ); alert( 'Capture process for this monitor will be restarted for the Privacy zone changes to take effect.' );
} }
return( true ); return ( true );
} }
return( false ); return ( false );
} }
function drawZonePoints() { function drawZonePoints() {
$('imageFrame').getElements( 'div.zonePoint' ).each( function( element ) { element.destroy(); } ); $('imageFrame').getElements( 'div.zonePoint' ).each( function( element ) {
element.destroy();
} );
for ( var i = 0; i < zone['Points'].length; i++ ) { for ( var i = 0; i < zone['Points'].length; i++ ) {
var div = new Element( 'div', { 'id': 'point'+i, 'class': 'zonePoint', 'title': 'Point '+(i+1), 'styles': { 'left': zone['Points'][i].x, 'top': zone['Points'][i].y } } ); var div = new Element( 'div', {'id': 'point'+i, 'class': 'zonePoint', 'title': 'Point '+(i+1), 'styles': {'left': zone['Points'][i].x, 'top': zone['Points'][i].y}} );
div.addEvent( 'mouseover', highlightOn.pass( i ) ); div.addEvent( 'mouseover', highlightOn.pass( i ) );
div.addEvent( 'mouseout', highlightOff.pass( i ) ); div.addEvent( 'mouseout', highlightOff.pass( i ) );
div.inject( $('imageFrame') ); div.inject( $('imageFrame') );
@ -391,30 +399,33 @@ function drawZonePoints() {
} }
var tables = $('zonePoints').getElements( 'table' ); var tables = $('zonePoints').getElements( 'table' );
tables.each( function( table ) { table.getElement( 'tbody' ).empty(); } ); tables.each( function( table ) {
table.getElement( 'tbody' ).empty();
} );
for ( var i = 0; i < zone['Points'].length; i++ ) { for ( var i = 0; i < zone['Points'].length; i++ ) {
var row = new Element( 'tr', { 'id': 'row'+i } ); var row = new Element( 'tr', {'id': 'row'+i} );
row.addEvents( { 'mouseover': highlightOn.pass( i ), 'mouseout': highlightOff.pass( i ) } ); row.addEvents( {'mouseover': highlightOn.pass( i ), 'mouseout': highlightOff.pass( i )} );
var cell = new Element( 'td' ); var cell = new Element( 'td' );
cell.set( 'text', i+1 ); cell.set( 'text', i+1 );
cell.inject( row ); cell.inject( row );
cell = new Element( 'td' ); cell = new Element( 'td' );
var input = new Element( 'input', { 'id': 'newZone[Points]['+i+'][x]', 'name': 'newZone[Points]['+i+'][x]', 'value': zone['Points'][i].x, 'size': 5 } ); var input = new Element( 'input', {'id': 'newZone[Points]['+i+'][x]', 'name': 'newZone[Points]['+i+'][x]', 'value': zone['Points'][i].x, 'size': 5} );
input.addEvent( 'input', updateX.pass( i ) ); input.addEvent( 'input', updateX.pass( i ) );
input.inject( cell ); input.inject( cell );
cell.inject( row ); cell.inject( row );
cell = new Element( 'td' ); cell = new Element( 'td' );
input = new Element( 'input', { 'id': 'newZone[Points]['+i+'][y]', 'name': 'newZone[Points]['+i+'][y]', 'value': zone['Points'][i].y, 'size': 5 } ); input = new Element( 'input', {'id': 'newZone[Points]['+i+'][y]', 'name': 'newZone[Points]['+i+'][y]', 'value': zone['Points'][i].y, 'size': 5} );
input.addEvent( 'input', updateY.pass( i ) ); input.addEvent( 'input', updateY.pass( i ) );
input.inject( cell ); input.inject( cell );
cell.inject( row ); cell.inject( row );
cell = new Element( 'td' ); cell = new Element( 'td' );
new Element( 'a', { 'href': '#', 'events': { 'click': addPoint.pass( i ) } } ).set( 'text', '+' ).inject( cell ); new Element( 'a', {'href': '#', 'events': {'click': addPoint.pass( i )}} ).set( 'text', '+' ).inject( cell );
if ( zone['Points'].length > 3 ) if ( zone['Points'].length > 3 ) {
new Element( 'a', { 'id': 'delete'+i, 'href': '#', 'events': { 'click': delPoint.pass( i ) } } ).set( 'text', '-' ).inject( cell ); new Element( 'a', {'id': 'delete'+i, 'href': '#', 'events': {'click': delPoint.pass( i )}} ).set( 'text', '-' ).inject( cell );
}
cell.inject( row ); cell.inject( row );
row.inject( tables[i%tables.length].getElement( 'tbody' ) ); row.inject( tables[i%tables.length].getElement( 'tbody' ) );
@ -433,17 +444,18 @@ var lastAlarmState = STATE_IDLE;
function setAlarmState( currentAlarmState ) { function setAlarmState( currentAlarmState ) {
alarmState = currentAlarmState; alarmState = currentAlarmState;
var stateString = "Unknown";
var stateClass = ""; var stateClass = "";
if ( alarmState == STATE_ALARM ) if ( alarmState == STATE_ALARM ) {
stateClass = "alarm"; stateClass = "alarm";
else if ( alarmState == STATE_ALERT ) } else if ( alarmState == STATE_ALERT ) {
stateClass = "alert"; stateClass = "alert";
}
$('stateValue').set( 'text', stateStrings[alarmState] ); $('stateValue').set( 'text', stateStrings[alarmState] );
if ( stateClass ) if ( stateClass ) {
$('stateValue').setProperty( 'class', stateClass ); $('stateValue').setProperty( 'class', stateClass );
else } else {
$('stateValue').removeProperty( 'class' ); $('stateValue').removeProperty( 'class' );
}
var isAlarmed = ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ); var isAlarmed = ( alarmState == STATE_ALARM || alarmState == STATE_ALERT );
var wasAlarmed = ( lastAlarmState == STATE_ALARM || lastAlarmState == STATE_ALERT ); var wasAlarmed = ( lastAlarmState == STATE_ALARM || lastAlarmState == STATE_ALERT );
@ -454,27 +466,30 @@ function setAlarmState( currentAlarmState ) {
if ( newAlarm ) { if ( newAlarm ) {
if ( SOUND_ON_ALARM ) { if ( SOUND_ON_ALARM ) {
// Enable the alarm sound // Enable the alarm sound
if ( !canPlayPauseAudio ) if ( !canPlayPauseAudio ) {
$('alarmSound').removeClass( 'hidden' ); $('alarmSound').removeClass( 'hidden' );
else } else {
$('MediaPlayer').Play(); $('MediaPlayer').Play();
} }
} }
}
if ( SOUND_ON_ALARM ) { if ( SOUND_ON_ALARM ) {
if ( oldAlarm ) { if ( oldAlarm ) {
// Disable alarm sound // Disable alarm sound
if ( !canPlayPauseAudio ) if ( !canPlayPauseAudio ) {
$('alarmSound').addClass( 'hidden' ); $('alarmSound').addClass( 'hidden' );
else } else {
$('MediaPlayer').Stop(); $('MediaPlayer').Stop();
} }
} }
}
lastAlarmState = alarmState; lastAlarmState = alarmState;
} }
var streamCmdParms = "view=request&request=stream&connkey="+connKey; var streamCmdParms = "view=request&request=stream&connkey="+connKey;
if ( auth_hash ) if ( auth_hash ) {
streamCmdParms += '&auth='+auth_hash; streamCmdParms += '&auth='+auth_hash;
}
var streamCmdReq = new Request.JSON( { var streamCmdReq = new Request.JSON( {
url: monitorUrl, url: monitorUrl,
method: 'get', method: 'get',
@ -488,8 +503,9 @@ var streamStatus;
function getStreamCmdResponse( respObj, respText ) { function getStreamCmdResponse( respObj, respText ) {
watchdogOk("stream"); watchdogOk("stream");
if ( streamCmdTimer ) if ( streamCmdTimer ) {
streamCmdTimer = clearTimeout( streamCmdTimer ); streamCmdTimer = clearTimeout( streamCmdTimer );
}
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
streamStatus = respObj.status; streamStatus = respObj.status;
@ -497,8 +513,6 @@ function getStreamCmdResponse( respObj, respText ) {
setAlarmState( streamStatus.state ); setAlarmState( streamStatus.state );
var delayString = secsToTime( streamStatus.delay );
if ( streamStatus.paused == true ) { if ( streamStatus.paused == true ) {
streamCmdPause( false ); streamCmdPause( false );
} else if ( streamStatus.delayed == true && streamStatus.rate == 1 ) { } else if ( streamStatus.delayed == true && streamStatus.rate == 1 ) {
@ -509,15 +523,17 @@ function getStreamCmdResponse( respObj, respText ) {
if ( ! streamPause ) { if ( ! streamPause ) {
// Try to reload the image stream. // Try to reload the image stream.
var streamImg = $('liveStream'+monitorId); var streamImg = $('liveStream'+monitorId);
if ( streamImg ) if ( streamImg ) {
streamImg.src = streamImg.src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) )); streamImg.src = streamImg.src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) ));
} }
} }
}
if ( ! streamPause ) { if ( ! streamPause ) {
var streamCmdTimeout = statusRefreshTimeout; var streamCmdTimeout = statusRefreshTimeout;
if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) {
streamCmdTimeout = streamCmdTimeout/5; streamCmdTimeout = streamCmdTimeout/5;
}
streamCmdTimer = streamCmdQuery.delay( streamCmdTimeout ); streamCmdTimer = streamCmdQuery.delay( streamCmdTimeout );
} }
} }
@ -537,18 +553,21 @@ function streamCmdPauseToggle() {
} }
function streamCmdPause( action ) { function streamCmdPause( action ) {
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_PAUSE ); streamCmdReq.send( streamCmdParms+"&command="+CMD_PAUSE );
}
} }
function streamCmdPlay( action ) { function streamCmdPlay( action ) {
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_PLAY ); streamCmdReq.send( streamCmdParms+"&command="+CMD_PLAY );
}
} }
function streamCmdStop( action ) { function streamCmdStop( action ) {
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_STOP ); streamCmdReq.send( streamCmdParms+"&command="+CMD_STOP );
}
} }
function streamCmdQuery() { function streamCmdQuery() {
@ -556,8 +575,9 @@ function streamCmdQuery() {
} }
var statusCmdParms = "view=request&request=status&entity=monitor&id="+monitorId+"&element[]=Status&element[]=FrameRate"; var statusCmdParms = "view=request&request=status&entity=monitor&id="+monitorId+"&element[]=Status&element[]=FrameRate";
if ( auth_hash ) if ( auth_hash ) {
statusCmdParms += '&auth='+auth_hash; statusCmdParms += '&auth='+auth_hash;
}
var statusCmdReq = new Request.JSON( { var statusCmdReq = new Request.JSON( {
url: monitorUrl, url: monitorUrl,
method: 'get', method: 'get',
@ -570,19 +590,22 @@ var statusCmdTimer = null;
function getStatusCmdResponse( respObj, respText ) { function getStatusCmdResponse( respObj, respText ) {
watchdogOk("status"); watchdogOk("status");
if ( statusCmdTimer ) if ( statusCmdTimer ) {
statusCmdTimer = clearTimeout( statusCmdTimer ); statusCmdTimer = clearTimeout( statusCmdTimer );
}
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
$('fpsValue').set( 'text', respObj.monitor.FrameRate ); $('fpsValue').set( 'text', respObj.monitor.FrameRate );
setAlarmState( respObj.monitor.Status ); setAlarmState( respObj.monitor.Status );
} else } else {
checkStreamForErrors("getStatusCmdResponse", respObj); checkStreamForErrors("getStatusCmdResponse", respObj);
}
if ( ! streamPause ) { if ( ! streamPause ) {
var statusCmdTimeout = statusRefreshTimeout; var statusCmdTimeout = statusRefreshTimeout;
if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) if ( alarmState == STATE_ALARM || alarmState == STATE_ALERT ) {
statusCmdTimeout = statusCmdTimeout/5; statusCmdTimeout = statusCmdTimeout/5;
}
statusCmdTimer = statusCmdQuery.delay( statusCmdTimeout ); statusCmdTimer = statusCmdQuery.delay( statusCmdTimeout );
} }
} }
@ -601,8 +624,9 @@ function appletRefresh() {
var parent = streamImg.getParent(); var parent = streamImg.getParent();
streamImg.dispose(); streamImg.dispose();
streamImg.inject( parent ); streamImg.inject( parent );
if ( appletRefreshTime ) if ( appletRefreshTime ) {
appletRefresh.delay( appletRefreshTime*1000 ); appletRefresh.delay( appletRefreshTime*1000 );
}
} else { } else {
appletRefresh.delay( 15*1000 ); //if we are paused or delayed check every 15 seconds if we are live yet... appletRefresh.delay( 15*1000 ); //if we are paused or delayed check every 15 seconds if we are live yet...
} }
@ -683,16 +707,18 @@ function initPage() {
if ( canStreamNative || streamMode == "single" ) { if ( canStreamNative || streamMode == "single" ) {
var streamImg = $('imageFrame').getElement('img'); var streamImg = $('imageFrame').getElement('img');
if ( !streamImg ) if ( !streamImg ) {
streamImg = $('imageFrame').getElement('object'); streamImg = $('imageFrame').getElement('object');
}
if ( streamMode == "single" ) { if ( streamMode == "single" ) {
streamImg.addEvent( 'click', fetchImage.pass( streamImg ) ); streamImg.addEvent( 'click', fetchImage.pass( streamImg ) );
fetchImage.pass( streamImg ).periodical( imageRefreshTimeout ); fetchImage.pass( streamImg ).periodical( imageRefreshTimeout );
} }
} }
if ( refreshApplet && appletRefreshTime ) if ( refreshApplet && appletRefreshTime ) {
appletRefresh.delay( appletRefreshTime*1000 ); appletRefresh.delay( appletRefreshTime*1000 );
}
} }
function Polygon_calcArea( coords ) { function Polygon_calcArea( coords ) {

View File

@ -1,8 +1,9 @@
var streamCmdParms = "view=request&request=stream&connkey="+connKey; var streamCmdParms = "view=request&request=stream&connkey="+connKey;
var streamCmdReq = new Request.JSON( { url: monitorUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel' } ); var streamCmdReq = new Request.JSON( {url: monitorUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel'} );
function streamCmdQuit( action ) { function streamCmdQuit( action ) {
if ( action ) if ( action ) {
streamCmdReq.send( streamCmdParms+"&command="+CMD_QUIT ); streamCmdReq.send( streamCmdParms+"&command="+CMD_QUIT );
}
} }