From 7c3c6e19124464d8b3519a97eb4af75056c8ecc3 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:06:47 +0000 Subject: [PATCH 01/12] Move OpenLayers.js to OpenLayers.min.js --- index.php | 2 +- OpenLayers.js => js/OpenLayers.min.js | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename OpenLayers.js => js/OpenLayers.min.js (100%) diff --git a/index.php b/index.php index 88935315..657bcfc2 100644 --- a/index.php +++ b/index.php @@ -17,7 +17,7 @@ - + diff --git a/OpenLayers.js b/js/OpenLayers.min.js similarity index 100% rename from OpenLayers.js rename to js/OpenLayers.min.js From f8fed2cf98ed6007a29960748a8311e3e8a987de Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:15:41 +0000 Subject: [PATCH 02/12] Move style_reset.css to style_reset.min.css --- about.php | 2 +- css/{style_reset.css => style_reset.min.css} | 0 data.html | 2 +- donate.php | 2 +- faq.html | 2 +- help/airline.html | 2 +- help/airport.html | 2 +- help/csv.html | 2 +- help/database.html | 2 +- help/privacy.html | 2 +- help/resetpw.php | 2 +- help/time.html | 2 +- help/trip.html | 2 +- html/alsearch.php | 2 +- html/apsearch.php | 2 +- html/import.php | 2 +- html/route-maps.php | 2 +- html/settings.php | 2 +- html/trip.php | 2 +- index.php | 2 +- php/import.php | 2 +- php/tripit_list_trips.php | 2 +- php/tripit_rendezvous.php | 2 +- 23 files changed, 22 insertions(+), 22 deletions(-) rename css/{style_reset.css => style_reset.min.css} (100%) diff --git a/about.php b/about.php index 71f9566b..655360bc 100644 --- a/about.php +++ b/about.php @@ -7,7 +7,7 @@ OpenFlights: About "> - + diff --git a/css/style_reset.css b/css/style_reset.min.css similarity index 100% rename from css/style_reset.css rename to css/style_reset.min.css diff --git a/data.html b/data.html index 0cf8630b..1f7d64ea 100644 --- a/data.html +++ b/data.html @@ -4,7 +4,7 @@ OpenFlights: Airport and airline data - + diff --git a/donate.php b/donate.php index c718d7c0..10d20478 100644 --- a/donate.php +++ b/donate.php @@ -3,7 +3,7 @@ OpenFlights: Donations and Elite Levels - + diff --git a/faq.html b/faq.html index 82c34cee..a9e9361d 100644 --- a/faq.html +++ b/faq.html @@ -2,7 +2,7 @@ OpenFlights: FAQ - + diff --git a/help/airline.html b/help/airline.html index 19d9c8f7..b1b54b6f 100644 --- a/help/airline.html +++ b/help/airline.html @@ -2,7 +2,7 @@ OpenFlights Help: Airport - + diff --git a/help/airport.html b/help/airport.html index 8d17926b..931c6a2f 100644 --- a/help/airport.html +++ b/help/airport.html @@ -2,7 +2,7 @@ OpenFlights Help: Airport - + diff --git a/help/csv.html b/help/csv.html index 0ab6138e..73a33f78 100644 --- a/help/csv.html +++ b/help/csv.html @@ -2,7 +2,7 @@ OpenFlights Help: CSV - + diff --git a/help/database.html b/help/database.html index a68d3024..02be4221 100644 --- a/help/database.html +++ b/help/database.html @@ -2,7 +2,7 @@ OpenFlights Help: Databases - + diff --git a/help/privacy.html b/help/privacy.html index 23721068..1e7bd907 100644 --- a/help/privacy.html +++ b/help/privacy.html @@ -2,7 +2,7 @@ OpenFlights: Privacy policy - + diff --git a/help/resetpw.php b/help/resetpw.php index cfefb9a6..2bece8a1 100644 --- a/help/resetpw.php +++ b/help/resetpw.php @@ -5,7 +5,7 @@ OpenFlights: Reset password - + diff --git a/help/time.html b/help/time.html index e77f90d4..cd1fd2b9 100644 --- a/help/time.html +++ b/help/time.html @@ -2,7 +2,7 @@ OpenFlights Help: Time - + diff --git a/help/trip.html b/help/trip.html index 664e7926..517d0685 100644 --- a/help/trip.html +++ b/help/trip.html @@ -2,7 +2,7 @@ OpenFlights Help: Trips - + diff --git a/html/alsearch.php b/html/alsearch.php index 49d104e5..e4456f2f 100644 --- a/html/alsearch.php +++ b/html/alsearch.php @@ -11,7 +11,7 @@ OpenFlights: <?php echo _("Airline search") ?> - + diff --git a/html/apsearch.php b/html/apsearch.php index 5c00aa2c..5bc04315 100644 --- a/html/apsearch.php +++ b/html/apsearch.php @@ -10,7 +10,7 @@ OpenFlights: <?php echo _("Airport search") ?> - + diff --git a/html/import.php b/html/import.php index f16c28b4..fd834f7c 100644 --- a/html/import.php +++ b/html/import.php @@ -5,7 +5,7 @@ OpenFlights: <?php echo _("Import data") ?> - + diff --git a/html/route-maps.php b/html/route-maps.php index 68a0b865..8157f5bc 100644 --- a/html/route-maps.php +++ b/html/route-maps.php @@ -2,7 +2,7 @@ OpenFlights: Route maps - + diff --git a/html/settings.php b/html/settings.php index da6e902f..5565c682 100644 --- a/html/settings.php +++ b/html/settings.php @@ -32,7 +32,7 @@ function condOut($arr, $key, $value, $true, $false) { echo _("Account settings"); } ?> - + diff --git a/html/trip.php b/html/trip.php index 61dd1c4a..7b051cc9 100644 --- a/html/trip.php +++ b/html/trip.php @@ -12,7 +12,7 @@ OpenFlights: <?php echo $trid ? _("Edit trip") : _("Add trip"); ?> - + diff --git a/index.php b/index.php index 657bcfc2..facc7822 100644 --- a/index.php +++ b/index.php @@ -11,7 +11,7 @@ - + " type="text/css"> diff --git a/php/import.php b/php/import.php index 3fcf0316..4e5bf460 100644 --- a/php/import.php +++ b/php/import.php @@ -7,7 +7,7 @@ OpenFlights: <?php echo _("Import") ?> - + diff --git a/php/tripit_list_trips.php b/php/tripit_list_trips.php index 5635afbc..cbb67059 100644 --- a/php/tripit_list_trips.php +++ b/php/tripit_list_trips.php @@ -527,7 +527,7 @@ function display_no_segments_message() { OpenFlights: <?php echo _("TripIt") ?> - + " type="text/css"> " type="text/css"> diff --git a/php/tripit_rendezvous.php b/php/tripit_rendezvous.php index 6f23c663..4da30fcb 100644 --- a/php/tripit_rendezvous.php +++ b/php/tripit_rendezvous.php @@ -14,7 +14,7 @@ OpenFlights: <?php echo _("TripIt") ?> - + From 7c3452722a5f656b3e11a969df780301448f400b Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:30:01 +0000 Subject: [PATCH 03/12] jquery.blockUI.js: Update to 2.70.0-2014.11.23 --- js/jquery.blockUI.js | 1057 +++++++++++++++++++++++------------------- 1 file changed, 589 insertions(+), 468 deletions(-) diff --git a/js/jquery.blockUI.js b/js/jquery.blockUI.js index 55b52a9f..90ce5d64 100644 --- a/js/jquery.blockUI.js +++ b/js/jquery.blockUI.js @@ -1,10 +1,10 @@ -/*! +/*! * jQuery blockUI plugin - * Version 2.39 (23-MAY-2011) - * @requires jQuery v1.2.3 or later + * Version 2.70.0-2014.11.23 + * Requires jQuery v1.7 or later * * Examples at: http://malsup.com/jquery/block/ - * Copyright (c) 2007-2010 M. Alsup + * Copyright (c) 2007-2013 M. Alsup * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html @@ -12,488 +12,609 @@ * Thanks to Amir-Hossein Sobhi for some excellent contributions! */ -;(function($) { - -if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) { - alert('blockUI requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery); - return; -} - -$.fn._fadeIn = $.fn.fadeIn; - -var noOp = function() {}; - -// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle -// retarded userAgent strings on Vista) -var mode = document.documentMode || 0; -var setExpr = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8); -var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode; - -// global $ methods for blocking/unblocking the entire page -$.blockUI = function(opts) { install(window, opts); }; -$.unblockUI = function(opts) { remove(window, opts); }; - -// convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) -$.growlUI = function(title, message, timeout, onClose) { - var $m = $('
'); - if (title) $m.append('

'+title+'

'); - if (message) $m.append('

'+message+'

'); - if (timeout == undefined) timeout = 3000; - $.blockUI({ - message: $m, fadeIn: 700, fadeOut: 1000, centerY: false, - timeout: timeout, showOverlay: false, - onUnblock: onClose, - css: $.blockUI.defaults.growlCSS - }); -}; - -// plugin method for blocking element content -$.fn.block = function(opts) { - return this.unblock({ fadeOut: 0 }).each(function() { - if ($.css(this,'position') == 'static') - this.style.position = 'relative'; - if ($.browser.msie) - this.style.zoom = 1; // force 'hasLayout' - install(this, opts); - }); -}; - -// plugin method for unblocking element content -$.fn.unblock = function(opts) { - return this.each(function() { - remove(this, opts); - }); -}; - -$.blockUI.version = 2.39; // 2nd generation blocking at no extra cost! - -// override these in your code to change the default behavior and style -$.blockUI.defaults = { - // message displayed when blocking (use null for no message) - message: '

Please wait...

', - - title: null, // title string; only used when theme == true - draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) - - theme: false, // set to true to use with jQuery UI themes - - // styles for the message when blocking; if you wish to disable - // these and use an external stylesheet then do this in your code: - // $.blockUI.defaults.css = {}; - css: { - padding: 0, - margin: 0, - width: '30%', - top: '40%', - left: '35%', - textAlign: 'center', - color: '#000', - border: '3px solid #aaa', - backgroundColor:'#fff', - cursor: 'wait' - }, - - // minimal style set used when themes are used - themedCSS: { - width: '30%', - top: '40%', - left: '35%' - }, - - // styles for the overlay - overlayCSS: { - backgroundColor: '#000', - opacity: 0.6, - cursor: 'wait' - }, - - // styles applied when using $.growlUI - growlCSS: { - width: '350px', - top: '10px', - left: '', - right: '10px', - border: 'none', - padding: '5px', - opacity: 0.6, - cursor: 'default', - color: '#fff', - backgroundColor: '#000', - '-webkit-border-radius': '10px', - '-moz-border-radius': '10px', - 'border-radius': '10px' - }, - - // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w - // (hat tip to Jorge H. N. de Vasconcelos) - iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', - - // force usage of iframe in non-IE browsers (handy for blocking applets) - forceIframe: false, - - // z-index for the blocking overlay - baseZ: 1000, - - // set these to true to have the message automatically centered - centerX: true, // <-- only effects element blocking (page block controlled via css above) - centerY: true, - - // allow body element to be stetched in ie6; this makes blocking look better - // on "short" pages. disable if you wish to prevent changes to the body height - allowBodyStretch: true, - - // enable if you want key and mouse events to be disabled for content that is blocked - bindEvents: true, - - // be default blockUI will supress tab navigation from leaving blocking content - // (if bindEvents is true) - constrainTabKey: true, - - // fadeIn time in millis; set to 0 to disable fadeIn on block - fadeIn: 200, - - // fadeOut time in millis; set to 0 to disable fadeOut on unblock - fadeOut: 400, - - // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock - timeout: 0, - - // disable if you don't want to show the overlay - showOverlay: true, - - // if true, focus will be placed in the first available input field when - // page blocking - focusInput: true, - - // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) - applyPlatformOpacityRules: true, - - // callback method invoked when fadeIn has completed and blocking message is visible - onBlock: null, - - // callback method invoked when unblocking has completed; the callback is - // passed the element that has been unblocked (which is the window object for page - // blocks) and the options that were passed to the unblock call: - // onUnblock(element, options) - onUnblock: null, - - // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 - quirksmodeOffsetHack: 4, - - // class name of the message block - blockMsgClass: 'blockMsg' -}; - -// private data and functions follow... - -var pageBlock = null; -var pageBlockEls = []; - -function install(el, opts) { - var full = (el == window); - var msg = opts && opts.message !== undefined ? opts.message : undefined; - opts = $.extend({}, $.blockUI.defaults, opts || {}); - opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); - var css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); - var themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); - msg = msg === undefined ? opts.message : msg; - - // remove the current block (if there is one) - if (full && pageBlock) - remove(window, {fadeOut:0}); - - // if an existing element is being used as the blocking content then we capture - // its current place in the DOM (and current display style) so we can restore - // it when we unblock - if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { - var node = msg.jquery ? msg[0] : msg; - var data = {}; - $(el).data('blockUI.history', data); - data.el = node; - data.parent = node.parentNode; - data.display = node.style.display; - data.position = node.style.position; - if (data.parent) - data.parent.removeChild(node); - } +;(function() { +/*jshint eqeqeq:false curly:false latedef:false */ +"use strict"; + + function setup($) { + $.fn._fadeIn = $.fn.fadeIn; + + var noOp = $.noop || function() {}; + + // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle + // confusing userAgent strings on Vista) + var msie = /MSIE/.test(navigator.userAgent); + var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent); + var mode = document.documentMode || 0; + var setExpr = $.isFunction( document.createElement('div').style.setExpression ); + + // global $ methods for blocking/unblocking the entire page + $.blockUI = function(opts) { install(window, opts); }; + $.unblockUI = function(opts) { remove(window, opts); }; + + // convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) + $.growlUI = function(title, message, timeout, onClose) { + var $m = $('
'); + if (title) $m.append('

'+title+'

'); + if (message) $m.append('

'+message+'

'); + if (timeout === undefined) timeout = 3000; + + // Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications + var callBlock = function(opts) { + opts = opts || {}; + + $.blockUI({ + message: $m, + fadeIn : typeof opts.fadeIn !== 'undefined' ? opts.fadeIn : 700, + fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000, + timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout, + centerY: false, + showOverlay: false, + onUnblock: onClose, + css: $.blockUI.defaults.growlCSS + }); + }; + + callBlock(); + var nonmousedOpacity = $m.css('opacity'); + $m.mouseover(function() { + callBlock({ + fadeIn: 0, + timeout: 30000 + }); + + var displayBlock = $('.blockMsg'); + displayBlock.stop(); // cancel fadeout if it has started + displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency + }).mouseout(function() { + $('.blockMsg').fadeOut(1000); + }); + // End konapun additions + }; + + // plugin method for blocking element content + $.fn.block = function(opts) { + if ( this[0] === window ) { + $.blockUI( opts ); + return this; + } + var fullOpts = $.extend({}, $.blockUI.defaults, opts || {}); + this.each(function() { + var $el = $(this); + if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked')) + return; + $el.unblock({ fadeOut: 0 }); + }); + + return this.each(function() { + if ($.css(this,'position') == 'static') { + this.style.position = 'relative'; + $(this).data('blockUI.static', true); + } + this.style.zoom = 1; // force 'hasLayout' in ie + install(this, opts); + }); + }; + + // plugin method for unblocking element content + $.fn.unblock = function(opts) { + if ( this[0] === window ) { + $.unblockUI( opts ); + return this; + } + return this.each(function() { + remove(this, opts); + }); + }; + + $.blockUI.version = 2.70; // 2nd generation blocking at no extra cost! + + // override these in your code to change the default behavior and style + $.blockUI.defaults = { + // message displayed when blocking (use null for no message) + message: '

Please wait...

', + + title: null, // title string; only used when theme == true + draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) + + theme: false, // set to true to use with jQuery UI themes + + // styles for the message when blocking; if you wish to disable + // these and use an external stylesheet then do this in your code: + // $.blockUI.defaults.css = {}; + css: { + padding: 0, + margin: 0, + width: '30%', + top: '40%', + left: '35%', + textAlign: 'center', + color: '#000', + border: '3px solid #aaa', + backgroundColor:'#fff', + cursor: 'wait' + }, + + // minimal style set used when themes are used + themedCSS: { + width: '30%', + top: '40%', + left: '35%' + }, + + // styles for the overlay + overlayCSS: { + backgroundColor: '#000', + opacity: 0.6, + cursor: 'wait' + }, + + // style to replace wait cursor before unblocking to correct issue + // of lingering wait cursor + cursorReset: 'default', + + // styles applied when using $.growlUI + growlCSS: { + width: '350px', + top: '10px', + left: '', + right: '10px', + border: 'none', + padding: '5px', + opacity: 0.6, + cursor: 'default', + color: '#fff', + backgroundColor: '#000', + '-webkit-border-radius':'10px', + '-moz-border-radius': '10px', + 'border-radius': '10px' + }, + + // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w + // (hat tip to Jorge H. N. de Vasconcelos) + /*jshint scripturl:true */ + iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', + + // force usage of iframe in non-IE browsers (handy for blocking applets) + forceIframe: false, + + // z-index for the blocking overlay + baseZ: 1000, + + // set these to true to have the message automatically centered + centerX: true, // <-- only effects element blocking (page block controlled via css above) + centerY: true, + + // allow body element to be stetched in ie6; this makes blocking look better + // on "short" pages. disable if you wish to prevent changes to the body height + allowBodyStretch: true, + + // enable if you want key and mouse events to be disabled for content that is blocked + bindEvents: true, + + // be default blockUI will supress tab navigation from leaving blocking content + // (if bindEvents is true) + constrainTabKey: true, + + // fadeIn time in millis; set to 0 to disable fadeIn on block + fadeIn: 200, + + // fadeOut time in millis; set to 0 to disable fadeOut on unblock + fadeOut: 400, + + // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock + timeout: 0, + + // disable if you don't want to show the overlay + showOverlay: true, + + // if true, focus will be placed in the first available input field when + // page blocking + focusInput: true, + + // elements that can receive focus + focusableElements: ':input:enabled:visible', + + // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) + // no longer needed in 2012 + // applyPlatformOpacityRules: true, + + // callback method invoked when fadeIn has completed and blocking message is visible + onBlock: null, + + // callback method invoked when unblocking has completed; the callback is + // passed the element that has been unblocked (which is the window object for page + // blocks) and the options that were passed to the unblock call: + // onUnblock(element, options) + onUnblock: null, + + // callback method invoked when the overlay area is clicked. + // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used. + onOverlayClick: null, + + // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 + quirksmodeOffsetHack: 4, + + // class name of the message block + blockMsgClass: 'blockMsg', + + // if it is already blocked, then ignore it (don't unblock and reblock) + ignoreIfBlocked: false + }; + + // private data and functions follow... + + var pageBlock = null; + var pageBlockEls = []; + + function install(el, opts) { + var css, themedCSS; + var full = (el == window); + var msg = (opts && opts.message !== undefined ? opts.message : undefined); + opts = $.extend({}, $.blockUI.defaults, opts || {}); + + if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked')) + return; + + opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); + css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); + if (opts.onOverlayClick) + opts.overlayCSS.cursor = 'pointer'; + + themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); + msg = msg === undefined ? opts.message : msg; + + // remove the current block (if there is one) + if (full && pageBlock) + remove(window, {fadeOut:0}); - $(el).data('blockUI.onUnblock', opts.onUnblock); - var z = opts.baseZ; - - // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; - // layer1 is the iframe layer which is used to supress bleed through of underlying content - // layer2 is the overlay layer which has opacity and a wait cursor (by default) - // layer3 is the message content that is displayed while blocking - - var lyr1 = ($.browser.msie || opts.forceIframe) - ? $('') - : $(''); - - var lyr2 = opts.theme - ? $('') - : $(''); - - var lyr3, s; - if (opts.theme && full) { - s = ''; - } - else if (opts.theme) { - s = ''; - } - else if (full) { - s = ''; - } - else { - s = ''; - } - lyr3 = $(s); + // if an existing element is being used as the blocking content then we capture + // its current place in the DOM (and current display style) so we can restore + // it when we unblock + if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { + var node = msg.jquery ? msg[0] : msg; + var data = {}; + $(el).data('blockUI.history', data); + data.el = node; + data.parent = node.parentNode; + data.display = node.style.display; + data.position = node.style.position; + if (data.parent) + data.parent.removeChild(node); + } - // if we have a message, style it - if (msg) { - if (opts.theme) { - lyr3.css(themedCSS); - lyr3.addClass('ui-widget-content'); - } - else - lyr3.css(css); - } + $(el).data('blockUI.onUnblock', opts.onUnblock); + var z = opts.baseZ; + + // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; + // layer1 is the iframe layer which is used to supress bleed through of underlying content + // layer2 is the overlay layer which has opacity and a wait cursor (by default) + // layer3 is the message content that is displayed while blocking + var lyr1, lyr2, lyr3, s; + if (msie || opts.forceIframe) + lyr1 = $(''); + else + lyr1 = $(''); + + if (opts.theme) + lyr2 = $(''); + else + lyr2 = $(''); + + if (opts.theme && full) { + s = ''; + } + else if (opts.theme) { + s = ''; + } + else if (full) { + s = ''; + } + else { + s = ''; + } + lyr3 = $(s); + + // if we have a message, style it + if (msg) { + if (opts.theme) { + lyr3.css(themedCSS); + lyr3.addClass('ui-widget-content'); + } + else + lyr3.css(css); + } - // style the overlay - if (!opts.theme && (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform)))) - lyr2.css(opts.overlayCSS); - lyr2.css('position', full ? 'fixed' : 'absolute'); - - // make iframe layer transparent in IE - if ($.browser.msie || opts.forceIframe) - lyr1.css('opacity',0.0); - - //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); - var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); - $.each(layers, function() { - this.appendTo($par); - }); - - if (opts.theme && opts.draggable && $.fn.draggable) { - lyr3.draggable({ - handle: '.ui-dialog-titlebar', - cancel: 'li' - }); - } + // style the overlay + if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/) + lyr2.css(opts.overlayCSS); + lyr2.css('position', full ? 'fixed' : 'absolute'); + + // make iframe layer transparent in IE + if (msie || opts.forceIframe) + lyr1.css('opacity',0.0); + + //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); + var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); + $.each(layers, function() { + this.appendTo($par); + }); + + if (opts.theme && opts.draggable && $.fn.draggable) { + lyr3.draggable({ + handle: '.ui-dialog-titlebar', + cancel: 'li' + }); + } - // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) - var expr = setExpr && (!$.boxModel || $('object,embed', full ? null : el).length > 0); - if (ie6 || expr) { - // give body 100% height - if (full && opts.allowBodyStretch && $.boxModel) - $('html,body').css('height','100%'); - - // fix ie6 issue when blocked element has a border width - if ((ie6 || !$.boxModel) && !full) { - var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); - var fixT = t ? '(0 - '+t+')' : 0; - var fixL = l ? '(0 - '+l+')' : 0; + // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) + var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0); + if (ie6 || expr) { + // give body 100% height + if (full && opts.allowBodyStretch && $.support.boxModel) + $('html,body').css('height','100%'); + + // fix ie6 issue when blocked element has a border width + if ((ie6 || !$.support.boxModel) && !full) { + var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); + var fixT = t ? '(0 - '+t+')' : 0; + var fixL = l ? '(0 - '+l+')' : 0; + } + + // simulate fixed position + $.each(layers, function(i,o) { + var s = o[0].style; + s.position = 'absolute'; + if (i < 2) { + if (full) + s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"'); + else + s.setExpression('height','this.parentNode.offsetHeight + "px"'); + if (full) + s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'); + else + s.setExpression('width','this.parentNode.offsetWidth + "px"'); + if (fixL) s.setExpression('left', fixL); + if (fixT) s.setExpression('top', fixT); + } + else if (opts.centerY) { + if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); + s.marginTop = 0; + } + else if (!opts.centerY && full) { + var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0; + var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; + s.setExpression('top',expression); + } + }); + } + + // show the message + if (msg) { + if (opts.theme) + lyr3.find('.ui-widget-content').append(msg); + else + lyr3.append(msg); + if (msg.jquery || msg.nodeType) + $(msg).show(); + } + + if ((msie || opts.forceIframe) && opts.showOverlay) + lyr1.show(); // opacity is zero + if (opts.fadeIn) { + var cb = opts.onBlock ? opts.onBlock : noOp; + var cb1 = (opts.showOverlay && !msg) ? cb : noOp; + var cb2 = msg ? cb : noOp; + if (opts.showOverlay) + lyr2._fadeIn(opts.fadeIn, cb1); + if (msg) + lyr3._fadeIn(opts.fadeIn, cb2); + } + else { + if (opts.showOverlay) + lyr2.show(); + if (msg) + lyr3.show(); + if (opts.onBlock) + opts.onBlock.bind(lyr3)(); + } + + // bind key and mouse events + bind(1, el, opts); + + if (full) { + pageBlock = lyr3[0]; + pageBlockEls = $(opts.focusableElements,pageBlock); + if (opts.focusInput) + setTimeout(focus, 20); + } + else + center(lyr3[0], opts.centerX, opts.centerY); + + if (opts.timeout) { + // auto-unblock + var to = setTimeout(function() { + if (full) + $.unblockUI(opts); + else + $(el).unblock(opts); + }, opts.timeout); + $(el).data('blockUI.timeout', to); + } } - // simulate fixed position - $.each([lyr1,lyr2,lyr3], function(i,o) { - var s = o[0].style; - s.position = 'absolute'; - if (i < 2) { - full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"') - : s.setExpression('height','this.parentNode.offsetHeight + "px"'); - full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"') - : s.setExpression('width','this.parentNode.offsetWidth + "px"'); - if (fixL) s.setExpression('left', fixL); - if (fixT) s.setExpression('top', fixT); + // remove the block + function remove(el, opts) { + var count; + var full = (el == window); + var $el = $(el); + var data = $el.data('blockUI.history'); + var to = $el.data('blockUI.timeout'); + if (to) { + clearTimeout(to); + $el.removeData('blockUI.timeout'); } - else if (opts.centerY) { - if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); - s.marginTop = 0; + opts = $.extend({}, $.blockUI.defaults, opts || {}); + bind(0, el, opts); // unbind events + + if (opts.onUnblock === null) { + opts.onUnblock = $el.data('blockUI.onUnblock'); + $el.removeData('blockUI.onUnblock'); } - else if (!opts.centerY && full) { - var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0; - var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; - s.setExpression('top',expression); + + var els; + if (full) // crazy selector to handle odd field errors in ie6/7 + els = $('body').children().filter('.blockUI').add('body > .blockUI'); + else + els = $el.find('>.blockUI'); + + // fix cursor issue + if ( opts.cursorReset ) { + if ( els.length > 1 ) + els[1].style.cursor = opts.cursorReset; + if ( els.length > 2 ) + els[2].style.cursor = opts.cursorReset; } - }); - } - // show the message - if (msg) { - if (opts.theme) - lyr3.find('.ui-widget-content').append(msg); - else - lyr3.append(msg); - if (msg.jquery || msg.nodeType) - $(msg).show(); - } + if (full) + pageBlock = pageBlockEls = null; - if (($.browser.msie || opts.forceIframe) && opts.showOverlay) - lyr1.show(); // opacity is zero - if (opts.fadeIn) { - var cb = opts.onBlock ? opts.onBlock : noOp; - var cb1 = (opts.showOverlay && !msg) ? cb : noOp; - var cb2 = msg ? cb : noOp; - if (opts.showOverlay) - lyr2._fadeIn(opts.fadeIn, cb1); - if (msg) - lyr3._fadeIn(opts.fadeIn, cb2); - } - else { - if (opts.showOverlay) - lyr2.show(); - if (msg) - lyr3.show(); - if (opts.onBlock) - opts.onBlock(); - } + if (opts.fadeOut) { + count = els.length; + els.stop().fadeOut(opts.fadeOut, function() { + if ( --count === 0) + reset(els,data,opts,el); + }); + } + else + reset(els, data, opts, el); + } - // bind key and mouse events - bind(1, el, opts); + // move blocking element back into the DOM where it started + function reset(els,data,opts,el) { + var $el = $(el); + if ( $el.data('blockUI.isBlocked') ) + return; + + els.each(function(i,o) { + // remove via DOM calls so we don't lose event handlers + if (this.parentNode) + this.parentNode.removeChild(this); + }); + + if (data && data.el) { + data.el.style.display = data.display; + data.el.style.position = data.position; + data.el.style.cursor = 'default'; // #59 + if (data.parent) + data.parent.appendChild(data.el); + $el.removeData('blockUI.history'); + } - if (full) { - pageBlock = lyr3[0]; - pageBlockEls = $(':input:enabled:visible',pageBlock); - if (opts.focusInput) - setTimeout(focus, 20); - } - else - center(lyr3[0], opts.centerX, opts.centerY); - - if (opts.timeout) { - // auto-unblock - var to = setTimeout(function() { - full ? $.unblockUI(opts) : $(el).unblock(opts); - }, opts.timeout); - $(el).data('blockUI.timeout', to); - } -}; - -// remove the block -function remove(el, opts) { - var full = (el == window); - var $el = $(el); - var data = $el.data('blockUI.history'); - var to = $el.data('blockUI.timeout'); - if (to) { - clearTimeout(to); - $el.removeData('blockUI.timeout'); - } - opts = $.extend({}, $.blockUI.defaults, opts || {}); - bind(0, el, opts); // unbind events + if ($el.data('blockUI.static')) { + $el.css('position', 'static'); // #22 + } - if (opts.onUnblock === null) { - opts.onUnblock = $el.data('blockUI.onUnblock'); - $el.removeData('blockUI.onUnblock'); - } + if (typeof opts.onUnblock == 'function') + opts.onUnblock(el,opts); - var els; - if (full) // crazy selector to handle odd field errors in ie6/7 - els = $('body').children().filter('.blockUI').add('body > .blockUI'); - else - els = $('.blockUI', el); + // fix issue in Safari 6 where block artifacts remain until reflow + var body = $(document.body), w = body.width(), cssW = body[0].style.width; + body.width(w-1).width(w); + body[0].style.width = cssW; + } - if (full) - pageBlock = pageBlockEls = null; + // bind/unbind the handler + function bind(b, el, opts) { + var full = el == window, $el = $(el); - if (opts.fadeOut) { - els.fadeOut(opts.fadeOut); - setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut); - } - else - reset(els, data, opts, el); -}; - -// move blocking element back into the DOM where it started -function reset(els,data,opts,el) { - els.each(function(i,o) { - // remove via DOM calls so we don't lose event handlers - if (this.parentNode) - this.parentNode.removeChild(this); - }); - - if (data && data.el) { - data.el.style.display = data.display; - data.el.style.position = data.position; - if (data.parent) - data.parent.appendChild(data.el); - $(el).removeData('blockUI.history'); - } + // don't bother unbinding if there is nothing to unbind + if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) + return; + + $el.data('blockUI.isBlocked', b); + + // don't bind events when overlay is not in use or if bindEvents is false + if (!full || !opts.bindEvents || (b && !opts.showOverlay)) + return; + + // bind anchors and inputs for mouse and key events + var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove'; + if (b) + $(document).bind(events, opts, handler); + else + $(document).unbind(events, handler); - if (typeof opts.onUnblock == 'function') - opts.onUnblock(el,opts); -}; - -// bind/unbind the handler -function bind(b, el, opts) { - var full = el == window, $el = $(el); - - // don't bother unbinding if there is nothing to unbind - if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) - return; - if (!full) - $el.data('blockUI.isBlocked', b); - - // don't bind events when overlay is not in use or if bindEvents is false - if (!opts.bindEvents || (b && !opts.showOverlay)) - return; - - // bind anchors and inputs for mouse and key events - var events = 'mousedown mouseup keydown keypress'; - b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler); - -// former impl... -// var $e = $('a,:input'); -// b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); -}; - -// event handler to suppress keyboard/mouse events when blocking -function handler(e) { - // allow tab navigation (conditionally) - if (e.keyCode && e.keyCode == 9) { - if (pageBlock && e.data.constrainTabKey) { - var els = pageBlockEls; - var fwd = !e.shiftKey && e.target === els[els.length-1]; - var back = e.shiftKey && e.target === els[0]; - if (fwd || back) { - setTimeout(function(){focus(back)},10); - return false; + // former impl... + // var $e = $('a,:input'); + // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); + } + + // event handler to suppress keyboard/mouse events when blocking + function handler(e) { + // allow tab navigation (conditionally) + if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) { + if (pageBlock && e.data.constrainTabKey) { + var els = pageBlockEls; + var fwd = !e.shiftKey && e.target === els[els.length-1]; + var back = e.shiftKey && e.target === els[0]; + if (fwd || back) { + setTimeout(function(){focus(back);},10); + return false; + } + } } + var opts = e.data; + var target = $(e.target); + if (target.hasClass('blockOverlay') && opts.onOverlayClick) + opts.onOverlayClick(e); + + // allow events within the message content + if (target.parents('div.' + opts.blockMsgClass).length > 0) + return true; + + // allow events for content that is not being blocked + return target.parents().children().filter('div.blockUI').length === 0; + } + + function focus(back) { + if (!pageBlockEls) + return; + var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; + if (e) + e.focus(); + } + + function center(el, x, y) { + var p = el.parentNode, s = el.style; + var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); + var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); + if (x) s.left = l > 0 ? (l+'px') : '0'; + if (y) s.top = t > 0 ? (t+'px') : '0'; } + + function sz(el, p) { + return parseInt($.css(el,p),10)||0; + } + } - var opts = e.data; - // allow events within the message content - if ($(e.target).parents('div.' + opts.blockMsgClass).length > 0) - return true; - - // allow events for content that is not being blocked - return $(e.target).parents().children().filter('div.blockUI').length == 0; -}; - -function focus(back) { - if (!pageBlockEls) - return; - var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; - if (e) - e.focus(); -}; - -function center(el, x, y) { - var p = el.parentNode, s = el.style; - var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); - var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); - if (x) s.left = l > 0 ? (l+'px') : '0'; - if (y) s.top = t > 0 ? (t+'px') : '0'; -}; - -function sz(el, p) { - return parseInt($.css(el,p))||0; -}; - -})(jQuery); + + + /*global define:true */ + if (typeof define === 'function' && define.amd && define.amd.jQuery) { + define(['jquery'], setup); + } else { + setup(jQuery); + } + +})(); From 5d1f4d0cdfac5120c93b6060f68422ce0b85301c Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:32:14 +0000 Subject: [PATCH 04/12] Swap to minified jquery.blockUI --- js/jquery.blockUI.js | 620 -------------------------------------- js/jquery.blockUI.min.js | 6 + php/tripit_list_trips.php | 2 +- 3 files changed, 7 insertions(+), 621 deletions(-) delete mode 100644 js/jquery.blockUI.js create mode 100644 js/jquery.blockUI.min.js diff --git a/js/jquery.blockUI.js b/js/jquery.blockUI.js deleted file mode 100644 index 90ce5d64..00000000 --- a/js/jquery.blockUI.js +++ /dev/null @@ -1,620 +0,0 @@ -/*! - * jQuery blockUI plugin - * Version 2.70.0-2014.11.23 - * Requires jQuery v1.7 or later - * - * Examples at: http://malsup.com/jquery/block/ - * Copyright (c) 2007-2013 M. Alsup - * Dual licensed under the MIT and GPL licenses: - * http://www.opensource.org/licenses/mit-license.php - * http://www.gnu.org/licenses/gpl.html - * - * Thanks to Amir-Hossein Sobhi for some excellent contributions! - */ - -;(function() { -/*jshint eqeqeq:false curly:false latedef:false */ -"use strict"; - - function setup($) { - $.fn._fadeIn = $.fn.fadeIn; - - var noOp = $.noop || function() {}; - - // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle - // confusing userAgent strings on Vista) - var msie = /MSIE/.test(navigator.userAgent); - var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent); - var mode = document.documentMode || 0; - var setExpr = $.isFunction( document.createElement('div').style.setExpression ); - - // global $ methods for blocking/unblocking the entire page - $.blockUI = function(opts) { install(window, opts); }; - $.unblockUI = function(opts) { remove(window, opts); }; - - // convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) - $.growlUI = function(title, message, timeout, onClose) { - var $m = $('
'); - if (title) $m.append('

'+title+'

'); - if (message) $m.append('

'+message+'

'); - if (timeout === undefined) timeout = 3000; - - // Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications - var callBlock = function(opts) { - opts = opts || {}; - - $.blockUI({ - message: $m, - fadeIn : typeof opts.fadeIn !== 'undefined' ? opts.fadeIn : 700, - fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000, - timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout, - centerY: false, - showOverlay: false, - onUnblock: onClose, - css: $.blockUI.defaults.growlCSS - }); - }; - - callBlock(); - var nonmousedOpacity = $m.css('opacity'); - $m.mouseover(function() { - callBlock({ - fadeIn: 0, - timeout: 30000 - }); - - var displayBlock = $('.blockMsg'); - displayBlock.stop(); // cancel fadeout if it has started - displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency - }).mouseout(function() { - $('.blockMsg').fadeOut(1000); - }); - // End konapun additions - }; - - // plugin method for blocking element content - $.fn.block = function(opts) { - if ( this[0] === window ) { - $.blockUI( opts ); - return this; - } - var fullOpts = $.extend({}, $.blockUI.defaults, opts || {}); - this.each(function() { - var $el = $(this); - if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked')) - return; - $el.unblock({ fadeOut: 0 }); - }); - - return this.each(function() { - if ($.css(this,'position') == 'static') { - this.style.position = 'relative'; - $(this).data('blockUI.static', true); - } - this.style.zoom = 1; // force 'hasLayout' in ie - install(this, opts); - }); - }; - - // plugin method for unblocking element content - $.fn.unblock = function(opts) { - if ( this[0] === window ) { - $.unblockUI( opts ); - return this; - } - return this.each(function() { - remove(this, opts); - }); - }; - - $.blockUI.version = 2.70; // 2nd generation blocking at no extra cost! - - // override these in your code to change the default behavior and style - $.blockUI.defaults = { - // message displayed when blocking (use null for no message) - message: '

Please wait...

', - - title: null, // title string; only used when theme == true - draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) - - theme: false, // set to true to use with jQuery UI themes - - // styles for the message when blocking; if you wish to disable - // these and use an external stylesheet then do this in your code: - // $.blockUI.defaults.css = {}; - css: { - padding: 0, - margin: 0, - width: '30%', - top: '40%', - left: '35%', - textAlign: 'center', - color: '#000', - border: '3px solid #aaa', - backgroundColor:'#fff', - cursor: 'wait' - }, - - // minimal style set used when themes are used - themedCSS: { - width: '30%', - top: '40%', - left: '35%' - }, - - // styles for the overlay - overlayCSS: { - backgroundColor: '#000', - opacity: 0.6, - cursor: 'wait' - }, - - // style to replace wait cursor before unblocking to correct issue - // of lingering wait cursor - cursorReset: 'default', - - // styles applied when using $.growlUI - growlCSS: { - width: '350px', - top: '10px', - left: '', - right: '10px', - border: 'none', - padding: '5px', - opacity: 0.6, - cursor: 'default', - color: '#fff', - backgroundColor: '#000', - '-webkit-border-radius':'10px', - '-moz-border-radius': '10px', - 'border-radius': '10px' - }, - - // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w - // (hat tip to Jorge H. N. de Vasconcelos) - /*jshint scripturl:true */ - iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', - - // force usage of iframe in non-IE browsers (handy for blocking applets) - forceIframe: false, - - // z-index for the blocking overlay - baseZ: 1000, - - // set these to true to have the message automatically centered - centerX: true, // <-- only effects element blocking (page block controlled via css above) - centerY: true, - - // allow body element to be stetched in ie6; this makes blocking look better - // on "short" pages. disable if you wish to prevent changes to the body height - allowBodyStretch: true, - - // enable if you want key and mouse events to be disabled for content that is blocked - bindEvents: true, - - // be default blockUI will supress tab navigation from leaving blocking content - // (if bindEvents is true) - constrainTabKey: true, - - // fadeIn time in millis; set to 0 to disable fadeIn on block - fadeIn: 200, - - // fadeOut time in millis; set to 0 to disable fadeOut on unblock - fadeOut: 400, - - // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock - timeout: 0, - - // disable if you don't want to show the overlay - showOverlay: true, - - // if true, focus will be placed in the first available input field when - // page blocking - focusInput: true, - - // elements that can receive focus - focusableElements: ':input:enabled:visible', - - // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) - // no longer needed in 2012 - // applyPlatformOpacityRules: true, - - // callback method invoked when fadeIn has completed and blocking message is visible - onBlock: null, - - // callback method invoked when unblocking has completed; the callback is - // passed the element that has been unblocked (which is the window object for page - // blocks) and the options that were passed to the unblock call: - // onUnblock(element, options) - onUnblock: null, - - // callback method invoked when the overlay area is clicked. - // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used. - onOverlayClick: null, - - // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 - quirksmodeOffsetHack: 4, - - // class name of the message block - blockMsgClass: 'blockMsg', - - // if it is already blocked, then ignore it (don't unblock and reblock) - ignoreIfBlocked: false - }; - - // private data and functions follow... - - var pageBlock = null; - var pageBlockEls = []; - - function install(el, opts) { - var css, themedCSS; - var full = (el == window); - var msg = (opts && opts.message !== undefined ? opts.message : undefined); - opts = $.extend({}, $.blockUI.defaults, opts || {}); - - if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked')) - return; - - opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); - css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); - if (opts.onOverlayClick) - opts.overlayCSS.cursor = 'pointer'; - - themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); - msg = msg === undefined ? opts.message : msg; - - // remove the current block (if there is one) - if (full && pageBlock) - remove(window, {fadeOut:0}); - - // if an existing element is being used as the blocking content then we capture - // its current place in the DOM (and current display style) so we can restore - // it when we unblock - if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { - var node = msg.jquery ? msg[0] : msg; - var data = {}; - $(el).data('blockUI.history', data); - data.el = node; - data.parent = node.parentNode; - data.display = node.style.display; - data.position = node.style.position; - if (data.parent) - data.parent.removeChild(node); - } - - $(el).data('blockUI.onUnblock', opts.onUnblock); - var z = opts.baseZ; - - // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; - // layer1 is the iframe layer which is used to supress bleed through of underlying content - // layer2 is the overlay layer which has opacity and a wait cursor (by default) - // layer3 is the message content that is displayed while blocking - var lyr1, lyr2, lyr3, s; - if (msie || opts.forceIframe) - lyr1 = $(''); - else - lyr1 = $(''); - - if (opts.theme) - lyr2 = $(''); - else - lyr2 = $(''); - - if (opts.theme && full) { - s = ''; - } - else if (opts.theme) { - s = ''; - } - else if (full) { - s = ''; - } - else { - s = ''; - } - lyr3 = $(s); - - // if we have a message, style it - if (msg) { - if (opts.theme) { - lyr3.css(themedCSS); - lyr3.addClass('ui-widget-content'); - } - else - lyr3.css(css); - } - - // style the overlay - if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/) - lyr2.css(opts.overlayCSS); - lyr2.css('position', full ? 'fixed' : 'absolute'); - - // make iframe layer transparent in IE - if (msie || opts.forceIframe) - lyr1.css('opacity',0.0); - - //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); - var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); - $.each(layers, function() { - this.appendTo($par); - }); - - if (opts.theme && opts.draggable && $.fn.draggable) { - lyr3.draggable({ - handle: '.ui-dialog-titlebar', - cancel: 'li' - }); - } - - // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) - var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0); - if (ie6 || expr) { - // give body 100% height - if (full && opts.allowBodyStretch && $.support.boxModel) - $('html,body').css('height','100%'); - - // fix ie6 issue when blocked element has a border width - if ((ie6 || !$.support.boxModel) && !full) { - var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); - var fixT = t ? '(0 - '+t+')' : 0; - var fixL = l ? '(0 - '+l+')' : 0; - } - - // simulate fixed position - $.each(layers, function(i,o) { - var s = o[0].style; - s.position = 'absolute'; - if (i < 2) { - if (full) - s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"'); - else - s.setExpression('height','this.parentNode.offsetHeight + "px"'); - if (full) - s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'); - else - s.setExpression('width','this.parentNode.offsetWidth + "px"'); - if (fixL) s.setExpression('left', fixL); - if (fixT) s.setExpression('top', fixT); - } - else if (opts.centerY) { - if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); - s.marginTop = 0; - } - else if (!opts.centerY && full) { - var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0; - var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; - s.setExpression('top',expression); - } - }); - } - - // show the message - if (msg) { - if (opts.theme) - lyr3.find('.ui-widget-content').append(msg); - else - lyr3.append(msg); - if (msg.jquery || msg.nodeType) - $(msg).show(); - } - - if ((msie || opts.forceIframe) && opts.showOverlay) - lyr1.show(); // opacity is zero - if (opts.fadeIn) { - var cb = opts.onBlock ? opts.onBlock : noOp; - var cb1 = (opts.showOverlay && !msg) ? cb : noOp; - var cb2 = msg ? cb : noOp; - if (opts.showOverlay) - lyr2._fadeIn(opts.fadeIn, cb1); - if (msg) - lyr3._fadeIn(opts.fadeIn, cb2); - } - else { - if (opts.showOverlay) - lyr2.show(); - if (msg) - lyr3.show(); - if (opts.onBlock) - opts.onBlock.bind(lyr3)(); - } - - // bind key and mouse events - bind(1, el, opts); - - if (full) { - pageBlock = lyr3[0]; - pageBlockEls = $(opts.focusableElements,pageBlock); - if (opts.focusInput) - setTimeout(focus, 20); - } - else - center(lyr3[0], opts.centerX, opts.centerY); - - if (opts.timeout) { - // auto-unblock - var to = setTimeout(function() { - if (full) - $.unblockUI(opts); - else - $(el).unblock(opts); - }, opts.timeout); - $(el).data('blockUI.timeout', to); - } - } - - // remove the block - function remove(el, opts) { - var count; - var full = (el == window); - var $el = $(el); - var data = $el.data('blockUI.history'); - var to = $el.data('blockUI.timeout'); - if (to) { - clearTimeout(to); - $el.removeData('blockUI.timeout'); - } - opts = $.extend({}, $.blockUI.defaults, opts || {}); - bind(0, el, opts); // unbind events - - if (opts.onUnblock === null) { - opts.onUnblock = $el.data('blockUI.onUnblock'); - $el.removeData('blockUI.onUnblock'); - } - - var els; - if (full) // crazy selector to handle odd field errors in ie6/7 - els = $('body').children().filter('.blockUI').add('body > .blockUI'); - else - els = $el.find('>.blockUI'); - - // fix cursor issue - if ( opts.cursorReset ) { - if ( els.length > 1 ) - els[1].style.cursor = opts.cursorReset; - if ( els.length > 2 ) - els[2].style.cursor = opts.cursorReset; - } - - if (full) - pageBlock = pageBlockEls = null; - - if (opts.fadeOut) { - count = els.length; - els.stop().fadeOut(opts.fadeOut, function() { - if ( --count === 0) - reset(els,data,opts,el); - }); - } - else - reset(els, data, opts, el); - } - - // move blocking element back into the DOM where it started - function reset(els,data,opts,el) { - var $el = $(el); - if ( $el.data('blockUI.isBlocked') ) - return; - - els.each(function(i,o) { - // remove via DOM calls so we don't lose event handlers - if (this.parentNode) - this.parentNode.removeChild(this); - }); - - if (data && data.el) { - data.el.style.display = data.display; - data.el.style.position = data.position; - data.el.style.cursor = 'default'; // #59 - if (data.parent) - data.parent.appendChild(data.el); - $el.removeData('blockUI.history'); - } - - if ($el.data('blockUI.static')) { - $el.css('position', 'static'); // #22 - } - - if (typeof opts.onUnblock == 'function') - opts.onUnblock(el,opts); - - // fix issue in Safari 6 where block artifacts remain until reflow - var body = $(document.body), w = body.width(), cssW = body[0].style.width; - body.width(w-1).width(w); - body[0].style.width = cssW; - } - - // bind/unbind the handler - function bind(b, el, opts) { - var full = el == window, $el = $(el); - - // don't bother unbinding if there is nothing to unbind - if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) - return; - - $el.data('blockUI.isBlocked', b); - - // don't bind events when overlay is not in use or if bindEvents is false - if (!full || !opts.bindEvents || (b && !opts.showOverlay)) - return; - - // bind anchors and inputs for mouse and key events - var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove'; - if (b) - $(document).bind(events, opts, handler); - else - $(document).unbind(events, handler); - - // former impl... - // var $e = $('a,:input'); - // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); - } - - // event handler to suppress keyboard/mouse events when blocking - function handler(e) { - // allow tab navigation (conditionally) - if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) { - if (pageBlock && e.data.constrainTabKey) { - var els = pageBlockEls; - var fwd = !e.shiftKey && e.target === els[els.length-1]; - var back = e.shiftKey && e.target === els[0]; - if (fwd || back) { - setTimeout(function(){focus(back);},10); - return false; - } - } - } - var opts = e.data; - var target = $(e.target); - if (target.hasClass('blockOverlay') && opts.onOverlayClick) - opts.onOverlayClick(e); - - // allow events within the message content - if (target.parents('div.' + opts.blockMsgClass).length > 0) - return true; - - // allow events for content that is not being blocked - return target.parents().children().filter('div.blockUI').length === 0; - } - - function focus(back) { - if (!pageBlockEls) - return; - var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; - if (e) - e.focus(); - } - - function center(el, x, y) { - var p = el.parentNode, s = el.style; - var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); - var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); - if (x) s.left = l > 0 ? (l+'px') : '0'; - if (y) s.top = t > 0 ? (t+'px') : '0'; - } - - function sz(el, p) { - return parseInt($.css(el,p),10)||0; - } - - } - - - /*global define:true */ - if (typeof define === 'function' && define.amd && define.amd.jQuery) { - define(['jquery'], setup); - } else { - setup(jQuery); - } - -})(); diff --git a/js/jquery.blockUI.min.js b/js/jquery.blockUI.min.js new file mode 100644 index 00000000..47ddda91 --- /dev/null +++ b/js/jquery.blockUI.min.js @@ -0,0 +1,6 @@ +/* +* jQuery BlockUI; v20141123 +* http://jquery.malsup.com/block/ +* Copyright (c) 2014 M. Alsup; Dual licensed: MIT/GPL +*/ +(function(){"use strict";function e(e){function o(o,i){var s,h,k=o==window,v=i&&void 0!==i.message?i.message:void 0;if(i=e.extend({},e.blockUI.defaults,i||{}),!i.ignoreIfBlocked||!e(o).data("blockUI.isBlocked")){if(i.overlayCSS=e.extend({},e.blockUI.defaults.overlayCSS,i.overlayCSS||{}),s=e.extend({},e.blockUI.defaults.css,i.css||{}),i.onOverlayClick&&(i.overlayCSS.cursor="pointer"),h=e.extend({},e.blockUI.defaults.themedCSS,i.themedCSS||{}),v=void 0===v?i.message:v,k&&b&&t(window,{fadeOut:0}),v&&"string"!=typeof v&&(v.parentNode||v.jquery)){var y=v.jquery?v[0]:v,m={};e(o).data("blockUI.history",m),m.el=y,m.parent=y.parentNode,m.display=y.style.display,m.position=y.style.position,m.parent&&m.parent.removeChild(y)}e(o).data("blockUI.onUnblock",i.onUnblock);var g,I,w,U,x=i.baseZ;g=r||i.forceIframe?e(''):e(''),I=i.theme?e(''):e(''),i.theme&&k?(U='"):i.theme?(U='"):U=k?'':'',w=e(U),v&&(i.theme?(w.css(h),w.addClass("ui-widget-content")):w.css(s)),i.theme||I.css(i.overlayCSS),I.css("position",k?"fixed":"absolute"),(r||i.forceIframe)&&g.css("opacity",0);var C=[g,I,w],S=k?e("body"):e(o);e.each(C,function(){this.appendTo(S)}),i.theme&&i.draggable&&e.fn.draggable&&w.draggable({handle:".ui-dialog-titlebar",cancel:"li"});var O=f&&(!e.support.boxModel||e("object,embed",k?null:o).length>0);if(u||O){if(k&&i.allowBodyStretch&&e.support.boxModel&&e("html,body").css("height","100%"),(u||!e.support.boxModel)&&!k)var E=d(o,"borderTopWidth"),T=d(o,"borderLeftWidth"),M=E?"(0 - "+E+")":0,B=T?"(0 - "+T+")":0;e.each(C,function(e,o){var t=o[0].style;if(t.position="absolute",2>e)k?t.setExpression("height","Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:"+i.quirksmodeOffsetHack+') + "px"'):t.setExpression("height",'this.parentNode.offsetHeight + "px"'),k?t.setExpression("width",'jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'):t.setExpression("width",'this.parentNode.offsetWidth + "px"'),B&&t.setExpression("left",B),M&&t.setExpression("top",M);else if(i.centerY)k&&t.setExpression("top",'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'),t.marginTop=0;else if(!i.centerY&&k){var n=i.css&&i.css.top?parseInt(i.css.top,10):0,s="((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "+n+') + "px"';t.setExpression("top",s)}})}if(v&&(i.theme?w.find(".ui-widget-content").append(v):w.append(v),(v.jquery||v.nodeType)&&e(v).show()),(r||i.forceIframe)&&i.showOverlay&&g.show(),i.fadeIn){var j=i.onBlock?i.onBlock:c,H=i.showOverlay&&!v?j:c,z=v?j:c;i.showOverlay&&I._fadeIn(i.fadeIn,H),v&&w._fadeIn(i.fadeIn,z)}else i.showOverlay&&I.show(),v&&w.show(),i.onBlock&&i.onBlock.bind(w)();if(n(1,o,i),k?(b=w[0],p=e(i.focusableElements,b),i.focusInput&&setTimeout(l,20)):a(w[0],i.centerX,i.centerY),i.timeout){var W=setTimeout(function(){k?e.unblockUI(i):e(o).unblock(i)},i.timeout);e(o).data("blockUI.timeout",W)}}}function t(o,t){var s,l=o==window,a=e(o),d=a.data("blockUI.history"),c=a.data("blockUI.timeout");c&&(clearTimeout(c),a.removeData("blockUI.timeout")),t=e.extend({},e.blockUI.defaults,t||{}),n(0,o,t),null===t.onUnblock&&(t.onUnblock=a.data("blockUI.onUnblock"),a.removeData("blockUI.onUnblock"));var r;r=l?e("body").children().filter(".blockUI").add("body > .blockUI"):a.find(">.blockUI"),t.cursorReset&&(r.length>1&&(r[1].style.cursor=t.cursorReset),r.length>2&&(r[2].style.cursor=t.cursorReset)),l&&(b=p=null),t.fadeOut?(s=r.length,r.stop().fadeOut(t.fadeOut,function(){0===--s&&i(r,d,t,o)})):i(r,d,t,o)}function i(o,t,i,n){var s=e(n);if(!s.data("blockUI.isBlocked")){o.each(function(){this.parentNode&&this.parentNode.removeChild(this)}),t&&t.el&&(t.el.style.display=t.display,t.el.style.position=t.position,t.el.style.cursor="default",t.parent&&t.parent.appendChild(t.el),s.removeData("blockUI.history")),s.data("blockUI.static")&&s.css("position","static"),"function"==typeof i.onUnblock&&i.onUnblock(n,i);var l=e(document.body),a=l.width(),d=l[0].style.width;l.width(a-1).width(a),l[0].style.width=d}}function n(o,t,i){var n=t==window,l=e(t);if((o||(!n||b)&&(n||l.data("blockUI.isBlocked")))&&(l.data("blockUI.isBlocked",o),n&&i.bindEvents&&(!o||i.showOverlay))){var a="mousedown mouseup keydown keypress keyup touchstart touchend touchmove";o?e(document).bind(a,i,s):e(document).unbind(a,s)}}function s(o){if("keydown"===o.type&&o.keyCode&&9==o.keyCode&&b&&o.data.constrainTabKey){var t=p,i=!o.shiftKey&&o.target===t[t.length-1],n=o.shiftKey&&o.target===t[0];if(i||n)return setTimeout(function(){l(n)},10),!1}var s=o.data,a=e(o.target);return a.hasClass("blockOverlay")&&s.onOverlayClick&&s.onOverlayClick(o),a.parents("div."+s.blockMsgClass).length>0?!0:0===a.parents().children().filter("div.blockUI").length}function l(e){if(p){var o=p[e===!0?p.length-1:0];o&&o.focus()}}function a(e,o,t){var i=e.parentNode,n=e.style,s=(i.offsetWidth-e.offsetWidth)/2-d(i,"borderLeftWidth"),l=(i.offsetHeight-e.offsetHeight)/2-d(i,"borderTopWidth");o&&(n.left=s>0?s+"px":"0"),t&&(n.top=l>0?l+"px":"0")}function d(o,t){return parseInt(e.css(o,t),10)||0}e.fn._fadeIn=e.fn.fadeIn;var c=e.noop||function(){},r=/MSIE/.test(navigator.userAgent),u=/MSIE 6.0/.test(navigator.userAgent)&&!/MSIE 8.0/.test(navigator.userAgent);document.documentMode||0;var f=e.isFunction(document.createElement("div").style.setExpression);e.blockUI=function(e){o(window,e)},e.unblockUI=function(e){t(window,e)},e.growlUI=function(o,t,i,n){var s=e('
');o&&s.append("

"+o+"

"),t&&s.append("

"+t+"

"),void 0===i&&(i=3e3);var l=function(o){o=o||{},e.blockUI({message:s,fadeIn:o.fadeIn!==void 0?o.fadeIn:700,fadeOut:o.fadeOut!==void 0?o.fadeOut:1e3,timeout:o.timeout!==void 0?o.timeout:i,centerY:!1,showOverlay:!1,onUnblock:n,css:e.blockUI.defaults.growlCSS})};l(),s.css("opacity"),s.mouseover(function(){l({fadeIn:0,timeout:3e4});var o=e(".blockMsg");o.stop(),o.fadeTo(300,1)}).mouseout(function(){e(".blockMsg").fadeOut(1e3)})},e.fn.block=function(t){if(this[0]===window)return e.blockUI(t),this;var i=e.extend({},e.blockUI.defaults,t||{});return this.each(function(){var o=e(this);i.ignoreIfBlocked&&o.data("blockUI.isBlocked")||o.unblock({fadeOut:0})}),this.each(function(){"static"==e.css(this,"position")&&(this.style.position="relative",e(this).data("blockUI.static",!0)),this.style.zoom=1,o(this,t)})},e.fn.unblock=function(o){return this[0]===window?(e.unblockUI(o),this):this.each(function(){t(this,o)})},e.blockUI.version=2.7,e.blockUI.defaults={message:"

Please wait...

",title:null,draggable:!0,theme:!1,css:{padding:0,margin:0,width:"30%",top:"40%",left:"35%",textAlign:"center",color:"#000",border:"3px solid #aaa",backgroundColor:"#fff",cursor:"wait"},themedCSS:{width:"30%",top:"40%",left:"35%"},overlayCSS:{backgroundColor:"#000",opacity:.6,cursor:"wait"},cursorReset:"default",growlCSS:{width:"350px",top:"10px",left:"",right:"10px",border:"none",padding:"5px",opacity:.6,cursor:"default",color:"#fff",backgroundColor:"#000","-webkit-border-radius":"10px","-moz-border-radius":"10px","border-radius":"10px"},iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank",forceIframe:!1,baseZ:1e3,centerX:!0,centerY:!0,allowBodyStretch:!0,bindEvents:!0,constrainTabKey:!0,fadeIn:200,fadeOut:400,timeout:0,showOverlay:!0,focusInput:!0,focusableElements:":input:enabled:visible",onBlock:null,onUnblock:null,onOverlayClick:null,quirksmodeOffsetHack:4,blockMsgClass:"blockMsg",ignoreIfBlocked:!1};var b=null,p=[]}"function"==typeof define&&define.amd&&define.amd.jQuery?define(["jquery"],e):e(jQuery)})(); diff --git a/php/tripit_list_trips.php b/php/tripit_list_trips.php index cbb67059..166e0753 100644 --- a/php/tripit_list_trips.php +++ b/php/tripit_list_trips.php @@ -531,7 +531,7 @@ function display_no_segments_message() { " type="text/css"> " type="text/css"> - + From 58f8627361523fb16d411505363c38f97901fd3c Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 13:01:34 +0000 Subject: [PATCH 05/12] Remove effects.js --- js/effects.js | 1123 ------------------------------------------------- 1 file changed, 1123 deletions(-) delete mode 100644 js/effects.js diff --git a/js/effects.js b/js/effects.js deleted file mode 100644 index 860ddc09..00000000 --- a/js/effects.js +++ /dev/null @@ -1,1123 +0,0 @@ -// script.aculo.us effects.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 - -// Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) -// Contributors: -// Justin Palmer (http://encytemedia.com/) -// Mark Pilgrim (http://diveintomark.org/) -// Martin Bialasinki -// -// script.aculo.us is freely distributable under the terms of an MIT-style license. -// For details, see the script.aculo.us web site: http://script.aculo.us/ - -// converts rgb() and #xxx to #xxxxxx format, -// returns self (or first argument) if not convertable -String.prototype.parseColor = function() { - var color = '#'; - if (this.slice(0,4) == 'rgb(') { - var cols = this.slice(4,this.length-1).split(','); - var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); - } else { - if (this.slice(0,1) == '#') { - if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); - if (this.length==7) color = this.toLowerCase(); - } - } - return (color.length==7 ? color : (arguments[0] || this)); -}; - -/*--------------------------------------------------------------------------*/ - -Element.collectTextNodes = function(element) { - return $A($(element).childNodes).collect( function(node) { - return (node.nodeType==3 ? node.nodeValue : - (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); - }).flatten().join(''); -}; - -Element.collectTextNodesIgnoreClass = function(element, className) { - return $A($(element).childNodes).collect( function(node) { - return (node.nodeType==3 ? node.nodeValue : - ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? - Element.collectTextNodesIgnoreClass(node, className) : '')); - }).flatten().join(''); -}; - -Element.setContentZoom = function(element, percent) { - element = $(element); - element.setStyle({fontSize: (percent/100) + 'em'}); - if (Prototype.Browser.WebKit) window.scrollBy(0,0); - return element; -}; - -Element.getInlineOpacity = function(element){ - return $(element).style.opacity || ''; -}; - -Element.forceRerendering = function(element) { - try { - element = $(element); - var n = document.createTextNode(' '); - element.appendChild(n); - element.removeChild(n); - } catch(e) { } -}; - -/*--------------------------------------------------------------------------*/ - -var Effect = { - _elementDoesNotExistError: { - name: 'ElementDoesNotExistError', - message: 'The specified DOM element does not exist, but is required for this effect to operate' - }, - Transitions: { - linear: Prototype.K, - sinoidal: function(pos) { - return (-Math.cos(pos*Math.PI)/2) + .5; - }, - reverse: function(pos) { - return 1-pos; - }, - flicker: function(pos) { - var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4; - return pos > 1 ? 1 : pos; - }, - wobble: function(pos) { - return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5; - }, - pulse: function(pos, pulses) { - return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5; - }, - spring: function(pos) { - return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); - }, - none: function(pos) { - return 0; - }, - full: function(pos) { - return 1; - } - }, - DefaultOptions: { - duration: 1.0, // seconds - fps: 100, // 100= assume 66fps max. - sync: false, // true for combining - from: 0.0, - to: 1.0, - delay: 0.0, - queue: 'parallel' - }, - tagifyText: function(element) { - var tagifyStyle = 'position:relative'; - if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; - - element = $(element); - $A(element.childNodes).each( function(child) { - if (child.nodeType==3) { - child.nodeValue.toArray().each( function(character) { - element.insertBefore( - new Element('span', {style: tagifyStyle}).update( - character == ' ' ? String.fromCharCode(160) : character), - child); - }); - Element.remove(child); - } - }); - }, - multiple: function(element, effect) { - var elements; - if (((typeof element == 'object') || - Object.isFunction(element)) && - (element.length)) - elements = element; - else - elements = $(element).childNodes; - - var options = Object.extend({ - speed: 0.1, - delay: 0.0 - }, arguments[2] || { }); - var masterDelay = options.delay; - - $A(elements).each( function(element, index) { - new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); - }); - }, - PAIRS: { - 'slide': ['SlideDown','SlideUp'], - 'blind': ['BlindDown','BlindUp'], - 'appear': ['Appear','Fade'] - }, - toggle: function(element, effect, options) { - element = $(element); - effect = (effect || 'appear').toLowerCase(); - - return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({ - queue: { position:'end', scope:(element.id || 'global'), limit: 1 } - }, options || {})); - } -}; - -Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; - -/* ------------- core effects ------------- */ - -Effect.ScopedQueue = Class.create(Enumerable, { - initialize: function() { - this.effects = []; - this.interval = null; - }, - _each: function(iterator) { - this.effects._each(iterator); - }, - add: function(effect) { - var timestamp = new Date().getTime(); - - var position = Object.isString(effect.options.queue) ? - effect.options.queue : effect.options.queue.position; - - switch(position) { - case 'front': - // move unstarted effects after this effect - this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { - e.startOn += effect.finishOn; - e.finishOn += effect.finishOn; - }); - break; - case 'with-last': - timestamp = this.effects.pluck('startOn').max() || timestamp; - break; - case 'end': - // start effect after last queued effect has finished - timestamp = this.effects.pluck('finishOn').max() || timestamp; - break; - } - - effect.startOn += timestamp; - effect.finishOn += timestamp; - - if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) - this.effects.push(effect); - - if (!this.interval) - this.interval = setInterval(this.loop.bind(this), 15); - }, - remove: function(effect) { - this.effects = this.effects.reject(function(e) { return e==effect }); - if (this.effects.length == 0) { - clearInterval(this.interval); - this.interval = null; - } - }, - loop: function() { - var timePos = new Date().getTime(); - for(var i=0, len=this.effects.length;i= this.startOn) { - if (timePos >= this.finishOn) { - this.render(1.0); - this.cancel(); - this.event('beforeFinish'); - if (this.finish) this.finish(); - this.event('afterFinish'); - return; - } - var pos = (timePos - this.startOn) / this.totalTime, - frame = (pos * this.totalFrames).round(); - if (frame > this.currentFrame) { - this.render(pos); - this.currentFrame = frame; - } - } - }, - cancel: function() { - if (!this.options.sync) - Effect.Queues.get(Object.isString(this.options.queue) ? - 'global' : this.options.queue.scope).remove(this); - this.state = 'finished'; - }, - event: function(eventName) { - if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); - if (this.options[eventName]) this.options[eventName](this); - }, - inspect: function() { - var data = $H(); - for(property in this) - if (!Object.isFunction(this[property])) data.set(property, this[property]); - return '#'; - } -}); - -Effect.Parallel = Class.create(Effect.Base, { - initialize: function(effects) { - this.effects = effects || []; - this.start(arguments[1]); - }, - update: function(position) { - this.effects.invoke('render', position); - }, - finish: function(position) { - this.effects.each( function(effect) { - effect.render(1.0); - effect.cancel(); - effect.event('beforeFinish'); - if (effect.finish) effect.finish(position); - effect.event('afterFinish'); - }); - } -}); - -Effect.Tween = Class.create(Effect.Base, { - initialize: function(object, from, to) { - object = Object.isString(object) ? $(object) : object; - var args = $A(arguments), method = args.last(), - options = args.length == 5 ? args[3] : null; - this.method = Object.isFunction(method) ? method.bind(object) : - Object.isFunction(object[method]) ? object[method].bind(object) : - function(value) { object[method] = value }; - this.start(Object.extend({ from: from, to: to }, options || { })); - }, - update: function(position) { - this.method(position); - } -}); - -Effect.Event = Class.create(Effect.Base, { - initialize: function() { - this.start(Object.extend({ duration: 0 }, arguments[0] || { })); - }, - update: Prototype.emptyFunction -}); - -Effect.Opacity = Class.create(Effect.Base, { - initialize: function(element) { - this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - // make this work on IE on elements without 'layout' - if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) - this.element.setStyle({zoom: 1}); - var options = Object.extend({ - from: this.element.getOpacity() || 0.0, - to: 1.0 - }, arguments[1] || { }); - this.start(options); - }, - update: function(position) { - this.element.setOpacity(position); - } -}); - -Effect.Move = Class.create(Effect.Base, { - initialize: function(element) { - this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ - x: 0, - y: 0, - mode: 'relative' - }, arguments[1] || { }); - this.start(options); - }, - setup: function() { - this.element.makePositioned(); - this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); - this.originalTop = parseFloat(this.element.getStyle('top') || '0'); - if (this.options.mode == 'absolute') { - this.options.x = this.options.x - this.originalLeft; - this.options.y = this.options.y - this.originalTop; - } - }, - update: function(position) { - this.element.setStyle({ - left: (this.options.x * position + this.originalLeft).round() + 'px', - top: (this.options.y * position + this.originalTop).round() + 'px' - }); - } -}); - -// for backwards compatibility -Effect.MoveBy = function(element, toTop, toLeft) { - return new Effect.Move(element, - Object.extend({ x: toLeft, y: toTop }, arguments[3] || { })); -}; - -Effect.Scale = Class.create(Effect.Base, { - initialize: function(element, percent) { - this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ - scaleX: true, - scaleY: true, - scaleContent: true, - scaleFromCenter: false, - scaleMode: 'box', // 'box' or 'contents' or { } with provided values - scaleFrom: 100.0, - scaleTo: percent - }, arguments[2] || { }); - this.start(options); - }, - setup: function() { - this.restoreAfterFinish = this.options.restoreAfterFinish || false; - this.elementPositioning = this.element.getStyle('position'); - - this.originalStyle = { }; - ['top','left','width','height','fontSize'].each( function(k) { - this.originalStyle[k] = this.element.style[k]; - }.bind(this)); - - this.originalTop = this.element.offsetTop; - this.originalLeft = this.element.offsetLeft; - - var fontSize = this.element.getStyle('font-size') || '100%'; - ['em','px','%','pt'].each( function(fontSizeType) { - if (fontSize.indexOf(fontSizeType)>0) { - this.fontSize = parseFloat(fontSize); - this.fontSizeType = fontSizeType; - } - }.bind(this)); - - this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; - - this.dims = null; - if (this.options.scaleMode=='box') - this.dims = [this.element.offsetHeight, this.element.offsetWidth]; - if (/^content/.test(this.options.scaleMode)) - this.dims = [this.element.scrollHeight, this.element.scrollWidth]; - if (!this.dims) - this.dims = [this.options.scaleMode.originalHeight, - this.options.scaleMode.originalWidth]; - }, - update: function(position) { - var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); - if (this.options.scaleContent && this.fontSize) - this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); - this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); - }, - finish: function(position) { - if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); - }, - setDimensions: function(height, width) { - var d = { }; - if (this.options.scaleX) d.width = width.round() + 'px'; - if (this.options.scaleY) d.height = height.round() + 'px'; - if (this.options.scaleFromCenter) { - var topd = (height - this.dims[0])/2; - var leftd = (width - this.dims[1])/2; - if (this.elementPositioning == 'absolute') { - if (this.options.scaleY) d.top = this.originalTop-topd + 'px'; - if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; - } else { - if (this.options.scaleY) d.top = -topd + 'px'; - if (this.options.scaleX) d.left = -leftd + 'px'; - } - } - this.element.setStyle(d); - } -}); - -Effect.Highlight = Class.create(Effect.Base, { - initialize: function(element) { - this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); - this.start(options); - }, - setup: function() { - // Prevent executing on elements not in the layout flow - if (this.element.getStyle('display')=='none') { this.cancel(); return; } - // Disable background image during the effect - this.oldStyle = { }; - if (!this.options.keepBackgroundImage) { - this.oldStyle.backgroundImage = this.element.getStyle('background-image'); - this.element.setStyle({backgroundImage: 'none'}); - } - if (!this.options.endcolor) - this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); - if (!this.options.restorecolor) - this.options.restorecolor = this.element.getStyle('background-color'); - // init color calculations - this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); - this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); - }, - update: function(position) { - this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ - return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) }); - }, - finish: function() { - this.element.setStyle(Object.extend(this.oldStyle, { - backgroundColor: this.options.restorecolor - })); - } -}); - -Effect.ScrollTo = function(element) { - var options = arguments[1] || { }, - scrollOffsets = document.viewport.getScrollOffsets(), - elementOffsets = $(element).cumulativeOffset(); - - if (options.offset) elementOffsets[1] += options.offset; - - return new Effect.Tween(null, - scrollOffsets.top, - elementOffsets[1], - options, - function(p){ scrollTo(scrollOffsets.left, p.round()); } - ); -}; - -/* ------------- combination effects ------------- */ - -Effect.Fade = function(element) { - element = $(element); - var oldOpacity = element.getInlineOpacity(); - var options = Object.extend({ - from: element.getOpacity() || 1.0, - to: 0.0, - afterFinishInternal: function(effect) { - if (effect.options.to!=0) return; - effect.element.hide().setStyle({opacity: oldOpacity}); - } - }, arguments[1] || { }); - return new Effect.Opacity(element,options); -}; - -Effect.Appear = function(element) { - element = $(element); - var options = Object.extend({ - from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), - to: 1.0, - // force Safari to render floated elements properly - afterFinishInternal: function(effect) { - effect.element.forceRerendering(); - }, - beforeSetup: function(effect) { - effect.element.setOpacity(effect.options.from).show(); - }}, arguments[1] || { }); - return new Effect.Opacity(element,options); -}; - -Effect.Puff = function(element) { - element = $(element); - var oldStyle = { - opacity: element.getInlineOpacity(), - position: element.getStyle('position'), - top: element.style.top, - left: element.style.left, - width: element.style.width, - height: element.style.height - }; - return new Effect.Parallel( - [ new Effect.Scale(element, 200, - { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), - new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], - Object.extend({ duration: 1.0, - beforeSetupInternal: function(effect) { - Position.absolutize(effect.effects[0].element); - }, - afterFinishInternal: function(effect) { - effect.effects[0].element.hide().setStyle(oldStyle); } - }, arguments[1] || { }) - ); -}; - -Effect.BlindUp = function(element) { - element = $(element); - element.makeClipping(); - return new Effect.Scale(element, 0, - Object.extend({ scaleContent: false, - scaleX: false, - restoreAfterFinish: true, - afterFinishInternal: function(effect) { - effect.element.hide().undoClipping(); - } - }, arguments[1] || { }) - ); -}; - -Effect.BlindDown = function(element) { - element = $(element); - var elementDimensions = element.getDimensions(); - return new Effect.Scale(element, 100, Object.extend({ - scaleContent: false, - scaleX: false, - scaleFrom: 0, - scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, - restoreAfterFinish: true, - afterSetup: function(effect) { - effect.element.makeClipping().setStyle({height: '0px'}).show(); - }, - afterFinishInternal: function(effect) { - effect.element.undoClipping(); - } - }, arguments[1] || { })); -}; - -Effect.SwitchOff = function(element) { - element = $(element); - var oldOpacity = element.getInlineOpacity(); - return new Effect.Appear(element, Object.extend({ - duration: 0.4, - from: 0, - transition: Effect.Transitions.flicker, - afterFinishInternal: function(effect) { - new Effect.Scale(effect.element, 1, { - duration: 0.3, scaleFromCenter: true, - scaleX: false, scaleContent: false, restoreAfterFinish: true, - beforeSetup: function(effect) { - effect.element.makePositioned().makeClipping(); - }, - afterFinishInternal: function(effect) { - effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); - } - }); - } - }, arguments[1] || { })); -}; - -Effect.DropOut = function(element) { - element = $(element); - var oldStyle = { - top: element.getStyle('top'), - left: element.getStyle('left'), - opacity: element.getInlineOpacity() }; - return new Effect.Parallel( - [ new Effect.Move(element, {x: 0, y: 100, sync: true }), - new Effect.Opacity(element, { sync: true, to: 0.0 }) ], - Object.extend( - { duration: 0.5, - beforeSetup: function(effect) { - effect.effects[0].element.makePositioned(); - }, - afterFinishInternal: function(effect) { - effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); - } - }, arguments[1] || { })); -}; - -Effect.Shake = function(element) { - element = $(element); - var options = Object.extend({ - distance: 20, - duration: 0.5 - }, arguments[1] || {}); - var distance = parseFloat(options.distance); - var split = parseFloat(options.duration) / 10.0; - var oldStyle = { - top: element.getStyle('top'), - left: element.getStyle('left') }; - return new Effect.Move(element, - { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) { - new Effect.Move(effect.element, - { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { - new Effect.Move(effect.element, - { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { - new Effect.Move(effect.element, - { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { - new Effect.Move(effect.element, - { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { - new Effect.Move(effect.element, - { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { - effect.element.undoPositioned().setStyle(oldStyle); - }}); }}); }}); }}); }}); }}); -}; - -Effect.SlideDown = function(element) { - element = $(element).cleanWhitespace(); - // SlideDown need to have the content of the element wrapped in a container element with fixed height! - var oldInnerBottom = element.down().getStyle('bottom'); - var elementDimensions = element.getDimensions(); - return new Effect.Scale(element, 100, Object.extend({ - scaleContent: false, - scaleX: false, - scaleFrom: window.opera ? 0 : 1, - scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, - restoreAfterFinish: true, - afterSetup: function(effect) { - effect.element.makePositioned(); - effect.element.down().makePositioned(); - if (window.opera) effect.element.setStyle({top: ''}); - effect.element.makeClipping().setStyle({height: '0px'}).show(); - }, - afterUpdateInternal: function(effect) { - effect.element.down().setStyle({bottom: - (effect.dims[0] - effect.element.clientHeight) + 'px' }); - }, - afterFinishInternal: function(effect) { - effect.element.undoClipping().undoPositioned(); - effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } - }, arguments[1] || { }) - ); -}; - -Effect.SlideUp = function(element) { - element = $(element).cleanWhitespace(); - var oldInnerBottom = element.down().getStyle('bottom'); - var elementDimensions = element.getDimensions(); - return new Effect.Scale(element, window.opera ? 0 : 1, - Object.extend({ scaleContent: false, - scaleX: false, - scaleMode: 'box', - scaleFrom: 100, - scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, - restoreAfterFinish: true, - afterSetup: function(effect) { - effect.element.makePositioned(); - effect.element.down().makePositioned(); - if (window.opera) effect.element.setStyle({top: ''}); - effect.element.makeClipping().show(); - }, - afterUpdateInternal: function(effect) { - effect.element.down().setStyle({bottom: - (effect.dims[0] - effect.element.clientHeight) + 'px' }); - }, - afterFinishInternal: function(effect) { - effect.element.hide().undoClipping().undoPositioned(); - effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); - } - }, arguments[1] || { }) - ); -}; - -// Bug in opera makes the TD containing this element expand for a instance after finish -Effect.Squish = function(element) { - return new Effect.Scale(element, window.opera ? 1 : 0, { - restoreAfterFinish: true, - beforeSetup: function(effect) { - effect.element.makeClipping(); - }, - afterFinishInternal: function(effect) { - effect.element.hide().undoClipping(); - } - }); -}; - -Effect.Grow = function(element) { - element = $(element); - var options = Object.extend({ - direction: 'center', - moveTransition: Effect.Transitions.sinoidal, - scaleTransition: Effect.Transitions.sinoidal, - opacityTransition: Effect.Transitions.full - }, arguments[1] || { }); - var oldStyle = { - top: element.style.top, - left: element.style.left, - height: element.style.height, - width: element.style.width, - opacity: element.getInlineOpacity() }; - - var dims = element.getDimensions(); - var initialMoveX, initialMoveY; - var moveX, moveY; - - switch (options.direction) { - case 'top-left': - initialMoveX = initialMoveY = moveX = moveY = 0; - break; - case 'top-right': - initialMoveX = dims.width; - initialMoveY = moveY = 0; - moveX = -dims.width; - break; - case 'bottom-left': - initialMoveX = moveX = 0; - initialMoveY = dims.height; - moveY = -dims.height; - break; - case 'bottom-right': - initialMoveX = dims.width; - initialMoveY = dims.height; - moveX = -dims.width; - moveY = -dims.height; - break; - case 'center': - initialMoveX = dims.width / 2; - initialMoveY = dims.height / 2; - moveX = -dims.width / 2; - moveY = -dims.height / 2; - break; - } - - return new Effect.Move(element, { - x: initialMoveX, - y: initialMoveY, - duration: 0.01, - beforeSetup: function(effect) { - effect.element.hide().makeClipping().makePositioned(); - }, - afterFinishInternal: function(effect) { - new Effect.Parallel( - [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), - new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), - new Effect.Scale(effect.element, 100, { - scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, - sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) - ], Object.extend({ - beforeSetup: function(effect) { - effect.effects[0].element.setStyle({height: '0px'}).show(); - }, - afterFinishInternal: function(effect) { - effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); - } - }, options) - ); - } - }); -}; - -Effect.Shrink = function(element) { - element = $(element); - var options = Object.extend({ - direction: 'center', - moveTransition: Effect.Transitions.sinoidal, - scaleTransition: Effect.Transitions.sinoidal, - opacityTransition: Effect.Transitions.none - }, arguments[1] || { }); - var oldStyle = { - top: element.style.top, - left: element.style.left, - height: element.style.height, - width: element.style.width, - opacity: element.getInlineOpacity() }; - - var dims = element.getDimensions(); - var moveX, moveY; - - switch (options.direction) { - case 'top-left': - moveX = moveY = 0; - break; - case 'top-right': - moveX = dims.width; - moveY = 0; - break; - case 'bottom-left': - moveX = 0; - moveY = dims.height; - break; - case 'bottom-right': - moveX = dims.width; - moveY = dims.height; - break; - case 'center': - moveX = dims.width / 2; - moveY = dims.height / 2; - break; - } - - return new Effect.Parallel( - [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), - new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), - new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) - ], Object.extend({ - beforeStartInternal: function(effect) { - effect.effects[0].element.makePositioned().makeClipping(); - }, - afterFinishInternal: function(effect) { - effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } - }, options) - ); -}; - -Effect.Pulsate = function(element) { - element = $(element); - var options = arguments[1] || { }, - oldOpacity = element.getInlineOpacity(), - transition = options.transition || Effect.Transitions.linear, - reverser = function(pos){ - return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5); - }; - - return new Effect.Opacity(element, - Object.extend(Object.extend({ duration: 2.0, from: 0, - afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } - }, options), {transition: reverser})); -}; - -Effect.Fold = function(element) { - element = $(element); - var oldStyle = { - top: element.style.top, - left: element.style.left, - width: element.style.width, - height: element.style.height }; - element.makeClipping(); - return new Effect.Scale(element, 5, Object.extend({ - scaleContent: false, - scaleX: false, - afterFinishInternal: function(effect) { - new Effect.Scale(element, 1, { - scaleContent: false, - scaleY: false, - afterFinishInternal: function(effect) { - effect.element.hide().undoClipping().setStyle(oldStyle); - } }); - }}, arguments[1] || { })); -}; - -Effect.Morph = Class.create(Effect.Base, { - initialize: function(element) { - this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ - style: { } - }, arguments[1] || { }); - - if (!Object.isString(options.style)) this.style = $H(options.style); - else { - if (options.style.include(':')) - this.style = options.style.parseStyle(); - else { - this.element.addClassName(options.style); - this.style = $H(this.element.getStyles()); - this.element.removeClassName(options.style); - var css = this.element.getStyles(); - this.style = this.style.reject(function(style) { - return style.value == css[style.key]; - }); - options.afterFinishInternal = function(effect) { - effect.element.addClassName(effect.options.style); - effect.transforms.each(function(transform) { - effect.element.style[transform.style] = ''; - }); - }; - } - } - this.start(options); - }, - - setup: function(){ - function parseColor(color){ - if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; - color = color.parseColor(); - return $R(0,2).map(function(i){ - return parseInt( color.slice(i*2+1,i*2+3), 16 ); - }); - } - this.transforms = this.style.map(function(pair){ - var property = pair[0], value = pair[1], unit = null; - - if (value.parseColor('#zzzzzz') != '#zzzzzz') { - value = value.parseColor(); - unit = 'color'; - } else if (property == 'opacity') { - value = parseFloat(value); - if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) - this.element.setStyle({zoom: 1}); - } else if (Element.CSS_LENGTH.test(value)) { - var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/); - value = parseFloat(components[1]); - unit = (components.length == 3) ? components[2] : null; - } - - var originalValue = this.element.getStyle(property); - return { - style: property.camelize(), - originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), - targetValue: unit=='color' ? parseColor(value) : value, - unit: unit - }; - }.bind(this)).reject(function(transform){ - return ( - (transform.originalValue == transform.targetValue) || - ( - transform.unit != 'color' && - (isNaN(transform.originalValue) || isNaN(transform.targetValue)) - ) - ); - }); - }, - update: function(position) { - var style = { }, transform, i = this.transforms.length; - while(i--) - style[(transform = this.transforms[i]).style] = - transform.unit=='color' ? '#'+ - (Math.round(transform.originalValue[0]+ - (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + - (Math.round(transform.originalValue[1]+ - (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() + - (Math.round(transform.originalValue[2]+ - (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : - (transform.originalValue + - (transform.targetValue - transform.originalValue) * position).toFixed(3) + - (transform.unit === null ? '' : transform.unit); - this.element.setStyle(style, true); - } -}); - -Effect.Transform = Class.create({ - initialize: function(tracks){ - this.tracks = []; - this.options = arguments[1] || { }; - this.addTracks(tracks); - }, - addTracks: function(tracks){ - tracks.each(function(track){ - track = $H(track); - var data = track.values().first(); - this.tracks.push($H({ - ids: track.keys().first(), - effect: Effect.Morph, - options: { style: data } - })); - }.bind(this)); - return this; - }, - play: function(){ - return new Effect.Parallel( - this.tracks.map(function(track){ - var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options'); - var elements = [$(ids) || $$(ids)].flatten(); - return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) }); - }).flatten(), - this.options - ); - } -}); - -Element.CSS_PROPERTIES = $w( - 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + - 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + - 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + - 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + - 'fontSize fontWeight height left letterSpacing lineHeight ' + - 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+ - 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + - 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + - 'right textIndent top width wordSpacing zIndex'); - -Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; - -String.__parseStyleElement = document.createElement('div'); -String.prototype.parseStyle = function(){ - var style, styleRules = $H(); - if (Prototype.Browser.WebKit) - style = new Element('div',{style:this}).style; - else { - String.__parseStyleElement.innerHTML = '
'; - style = String.__parseStyleElement.childNodes[0].style; - } - - Element.CSS_PROPERTIES.each(function(property){ - if (style[property]) styleRules.set(property, style[property]); - }); - - if (Prototype.Browser.IE && this.include('opacity')) - styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); - - return styleRules; -}; - -if (document.defaultView && document.defaultView.getComputedStyle) { - Element.getStyles = function(element) { - var css = document.defaultView.getComputedStyle($(element), null); - return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { - styles[property] = css[property]; - return styles; - }); - }; -} else { - Element.getStyles = function(element) { - element = $(element); - var css = element.currentStyle, styles; - styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) { - results[property] = css[property]; - return results; - }); - if (!styles.opacity) styles.opacity = element.getOpacity(); - return styles; - }; -} - -Effect.Methods = { - morph: function(element, style) { - element = $(element); - new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); - return element; - }, - visualEffect: function(element, effect, options) { - element = $(element); - var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); - new Effect[klass](element, options); - return element; - }, - highlight: function(element, options) { - element = $(element); - new Effect.Highlight(element, options); - return element; - } -}; - -$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ - 'pulsate shake puff squish switchOff dropOut').each( - function(effect) { - Effect.Methods[effect] = function(element, options){ - element = $(element); - Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); - return element; - }; - } -); - -$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( - function(f) { Effect.Methods[f] = Element[f]; } -); - -Element.addMethods(Effect.Methods); \ No newline at end of file From 8f22188a100fa0239a9b7ac407a974d8a3b35cc8 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 13:20:29 +0000 Subject: [PATCH 06/12] test/server/README.md: Fix syntax --- test/server/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/server/README.md b/test/server/README.md index 449e95fb..d1f3fb94 100644 --- a/test/server/README.md +++ b/test/server/README.md @@ -1,6 +1,6 @@ This test suite validates PHP calls and MySQL database content. -*** Instructions +### Instructions 0. Install Composer from https://getcomposer.org/download/ 1. `php composer.phar install` From 4ce988f6d3845db84961b60f8cf9dfcba01c6253 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 13:37:17 +0000 Subject: [PATCH 07/12] Turn sql/README into MD Remove export.sql, went away in 4ff8baf9d3daf43c8890cac9b08846a787fde420 --- sql/README | 23 ----------------------- sql/README.md | 13 +++++++++++++ 2 files changed, 13 insertions(+), 23 deletions(-) delete mode 100644 sql/README create mode 100644 sql/README.md diff --git a/sql/README b/sql/README deleted file mode 100644 index 7c2d50f6..00000000 --- a/sql/README +++ /dev/null @@ -1,23 +0,0 @@ -*** Tools for users - -create.sql - Create empty OpenFlights database schema -export.sql - Export airlines.dat, airports.dat and routes.dat from OpenFlights database -import-arm.sql - Import and sync a fresh copy of Airline Route Mapper (ARM) data -load-data.sql - Import airlines.dat, airports.dat and routes.dat into OpenFlights database -load-other-airport-dbs.sql - Import DAFIF and OurAirports, useful but not needed by site - -*** Site internal scripts - -elite-levels.sql - Generate table of elite users -merge-airports.sql - Called by data/merge-airports.sh for manual merging for duplicate ICAO codes -top10.sql - Generate nightly Top 10 lists (>data/top10.dat) -update-demo.sql - Update flights for "demo" user diff --git a/sql/README.md b/sql/README.md new file mode 100644 index 00000000..930cddf7 --- /dev/null +++ b/sql/README.md @@ -0,0 +1,13 @@ +### Tools for users + +- [`create.sql`](create.sql) - Create empty OpenFlights database schema +- [`import-arm.sql`](import-arm.sql) - Import and sync a fresh copy of Airline Route Mapper (ARM) data +- [`load-data.sql`](load-data.sql) - Import airlines.dat, airports.dat and routes.dat into OpenFlights database +- [`load-other-airport-dbs.sql`](load-other-airport-dbs.sql) - Import DAFIF and OurAirports, useful but not needed by site + +### Site internal scripts + +- [`elite-levels.sql`](elite-levels.sql) - Generate table of elite users +- [`merge-airports.sql`](merge-airports.sql) - Called by data/merge-airports.sh for manual merging for duplicate ICAO codes +- [`top10.sql`](top10.sql) - Generate nightly Top 10 lists (>data/top10.dat) +- [`update-demo.sql`](update-demo.sql) - Update flights for "demo" user From ed6ebf3e984afa7388d80d83f9fa9c8090e66ef2 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:04:50 +0000 Subject: [PATCH 08/12] Add prettier Pinned at ^2.8.8 due to version of npm in 22.04 (3.0.0+ doesn't work) --- .github/workflows/npm.yaml | 25 +++++++++++++++++++++++++ .gitignore | 3 ++- .prettierignore | 11 +++++++++++ .prettierrc.json | 1 + INSTALL | 4 ++++ package-lock.json | 35 +++++++++++++++++++++++++++++++++++ package.json | 9 +++++++++ 7 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/npm.yaml create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.github/workflows/npm.yaml b/.github/workflows/npm.yaml new file mode 100644 index 00000000..bf0f0012 --- /dev/null +++ b/.github/workflows/npm.yaml @@ -0,0 +1,25 @@ +name: NPM Actions + +#on: +# pull_request: +# branches: [master] +# push: + +jobs: + prettier: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + # Make sure the actual branch is checked out when running on pull requests + ref: ${{ github.head_ref }} + # This is important to fetch the changes to the previous commit + fetch-depth: 0 + + - name: Prettify code + uses: creyD/prettier_action@v4.3 + with: + dry: True + only_changed: True diff --git a/.gitignore b/.gitignore index bdaa9de5..4590c9a0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,9 +3,10 @@ composer.phar html/ad* html/analytics* import/ +node_modules/ php/config.php php/secrets.php vendor/* *.pyc .idea -.DS_Store \ No newline at end of file +.DS_Store diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..5c265a78 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,11 @@ +# Ignore artifacts: +build +coverage +# Ignore other files we don't want amending +vendor +composer.json +composer.lock +js/utilities.js +*.html +*.min.css +*.min.js diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1 @@ +{} diff --git a/INSTALL b/INSTALL index 6bf35363..4cce9c3c 100644 --- a/INSTALL +++ b/INSTALL @@ -37,6 +37,10 @@ sudo certbot --nginx -d [YOUR_DOMAIN] curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer sudo -u openflights php /usr/local/bin/composer install +# Set up npm packages if you're going to be developing OpenFlights +sudo apt-get install npm +sudo -u openflights npm install + # Generates locales for language support cd openflights find locale -name *utf8 -printf '%f ' | xargs sudo locale-gen diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..43fc365b --- /dev/null +++ b/package-lock.json @@ -0,0 +1,35 @@ +{ + "name": "openflights", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "devDependencies": { + "prettier": "^2.8.8" + } + }, + "node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + } + }, + "dependencies": { + "prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..f46dcc7c --- /dev/null +++ b/package.json @@ -0,0 +1,9 @@ +{ + "devDependencies": { + "prettier": "^2.8.8" + }, + "scripts": { + "lint": "prettier --check .", + "fix": "prettier --write ." + } +} From 6c4d3296b4fe64c927d83b995e538fdcd6507488 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 13:39:15 +0000 Subject: [PATCH 09/12] Run `npx prettier . --write` --- README.md | 1 + badge/README.md | 8 +- css/help.css | 2 +- css/tripit.css | 159 +- demo/README | 1 - js/alsearch.js | 328 +- js/apsearch.js | 644 ++-- js/greatcircle.js | 241 +- js/prototype.js | 6361 ++++++++++++++++++++------------------ js/settings.js | 223 +- js/trip.js | 66 +- js/tripit.js | 341 +- openflights.css | 43 +- openflights.js | 4059 ++++++++++++++---------- test/client/README | 5 +- test/server/README.md | 3 +- test/unit/README | 1 - test/unit/greatcircle.js | 2 +- 18 files changed, 7118 insertions(+), 5370 deletions(-) diff --git a/README.md b/README.md index 02fe2c35..983042c6 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Basically, though, it's your classic [LNMP](https://en.wikipedia.org/wiki/LAMP_% ## Tests Test coverage is woefully incomplete, but comes in three flavors: + - [`client`](test/client/): Client-side full-stack integration tests, require live DB & server - [`server`](test/server/): Server-side (PHP) integration tests, require a live database - [`unit`](test/unit/): Client-side JavaScript unit tests diff --git a/badge/README.md b/badge/README.md index 9253a44f..070281ca 100644 --- a/badge/README.md +++ b/badge/README.md @@ -1,4 +1,4 @@ -The Open Sans font is released under the [Open Font License 1.1](OFL.txt). - -* Project: https://fonts.google.com/specimen/Open+Sans -* Source: https://github.com/googlefonts/opensans +The Open Sans font is released under the [Open Font License 1.1](OFL.txt). + +- Project: https://fonts.google.com/specimen/Open+Sans +- Source: https://github.com/googlefonts/opensans diff --git a/css/help.css b/css/help.css index 63254abd..ce270b88 100644 --- a/css/help.css +++ b/css/help.css @@ -1,4 +1,4 @@ -table.time { +table.time { border-spacing: 1; } diff --git a/css/tripit.css b/css/tripit.css index 166a3827..8fd7219c 100644 --- a/css/tripit.css +++ b/css/tripit.css @@ -1,80 +1,79 @@ -/* TripIt Trip List */ -div.segment { - width: 850px; - overflow: auto; -} - -div.segment-left-cell { - width: 450px; - float: left; -} - -div.segment-right-cell { - width: 400px; - float: left; -} - -div.segment-none { - font-family: Calibri, Verdana, Arial, sans-serif; - font-size: 12pt; - color: #a1a1a1; - text-align: center; - margin: 15px 0; -} - -hr.segment-separator { - height: 1px; - background-color: #a1a1a1; - border: 1px; - clear: both; -} - -div.trip_header { - width: 850px; - overflow: auto; -} - -div.import_all { - float: right; - margin-top: 3px; -} - -/* TripIt Rendezvous */ -.loginSelector { - width: 200px; - height: 200px; - vertical-align: middle; -} - -.tripit_sprites_soc { - background: url("/img/tripit-sprites-social.png") no-repeat; - padding-left: 20px; -} - -.tripit_sprites_soc_fb { - background-position: 0 -2px; -} - -.tripit_sprites_soc_google { - background-position: 0 -80px; -} - -.tripit_sprites_soc_yahoo { - background-position: 0 -113px; -} - -.partnerLoginList { - text-align: left; - display: inline-block; - padding-top: 5px; - padding-bottom: 5px; -} - -.ui-button-text { - font-size: 12px; -} - -#loginPathPartnerHelp { - display: none; -} - +/* TripIt Trip List */ +div.segment { + width: 850px; + overflow: auto; +} + +div.segment-left-cell { + width: 450px; + float: left; +} + +div.segment-right-cell { + width: 400px; + float: left; +} + +div.segment-none { + font-family: Calibri, Verdana, Arial, sans-serif; + font-size: 12pt; + color: #a1a1a1; + text-align: center; + margin: 15px 0; +} + +hr.segment-separator { + height: 1px; + background-color: #a1a1a1; + border: 1px; + clear: both; +} + +div.trip_header { + width: 850px; + overflow: auto; +} + +div.import_all { + float: right; + margin-top: 3px; +} + +/* TripIt Rendezvous */ +.loginSelector { + width: 200px; + height: 200px; + vertical-align: middle; +} + +.tripit_sprites_soc { + background: url("/img/tripit-sprites-social.png") no-repeat; + padding-left: 20px; +} + +.tripit_sprites_soc_fb { + background-position: 0 -2px; +} + +.tripit_sprites_soc_google { + background-position: 0 -80px; +} + +.tripit_sprites_soc_yahoo { + background-position: 0 -113px; +} + +.partnerLoginList { + text-align: left; + display: inline-block; + padding-top: 5px; + padding-bottom: 5px; +} + +.ui-button-text { + font-size: 12px; +} + +#loginPathPartnerHelp { + display: none; +} diff --git a/demo/README b/demo/README index 9b002a19..e612b3f9 100644 --- a/demo/README +++ b/demo/README @@ -1,2 +1 @@ Various screenshots etc for promotional purposes. - diff --git a/js/alsearch.js b/js/alsearch.js index 53ecc0fa..1b596722 100644 --- a/js/alsearch.js +++ b/js/alsearch.js @@ -6,23 +6,23 @@ URL_ALSEARCH = "/php/alsearch.php"; var warning; var gt; -window.onload = function init(){ - gt = new Gettext({ 'domain' : 'messages' }); +window.onload = function init() { + gt = new Gettext({ domain: "messages" }); // ...?name=x&mode=y // 0 1 2 3 4 - var args = window.location.href.split('?'); - if(args[1]) { - keys = args[1].split('&'); - if(keys[0].split('=')[0] == "name") { - form = document.forms['searchform']; - form.name.value = unescape(keys[0].split('=')[1]); - selectInSelect(form.mode, keys[1].split('=')[1]); + var args = window.location.href.split("?"); + if (args[1]) { + keys = args[1].split("&"); + if (keys[0].split("=")[0] == "name") { + form = document.forms["searchform"]; + form.name.value = unescape(keys[0].split("=")[1]); + selectInSelect(form.mode, keys[1].split("=")[1]); selectInSelect(form.active, "Y"); changeMode(); } } -} +}; function doSearch(offset) { xmlhttpPost(URL_ALSEARCH, offset, "SEARCH"); @@ -43,9 +43,12 @@ function xmlhttpPost(strURL, offset, action) { else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } - self.xmlHttpReq.open('POST', strURL, true); - self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - self.xmlHttpReq.onreadystatechange = function() { + self.xmlHttpReq.open("POST", strURL, true); + self.xmlHttpReq.setRequestHeader( + "Content-Type", + "application/x-www-form-urlencoded" + ); + self.xmlHttpReq.onreadystatechange = function () { if (self.xmlHttpReq.readyState == 4) { if (strURL == URL_ALSEARCH) { if (action == "SEARCH") { @@ -56,10 +59,10 @@ function xmlhttpPost(strURL, offset, action) { } } } - } + }; var query = ""; - if(strURL == URL_ALSEARCH) { - var form = document.forms['searchform']; + if (strURL == URL_ALSEARCH) { + var form = document.forms["searchform"]; var name = form.name.value; var country = form.country[form.country.selectedIndex].text; var iata = form.iata.value; @@ -70,7 +73,7 @@ function xmlhttpPost(strURL, offset, action) { var active = form.active.value; var alid = form.alid.value; - if(iata != "" && iata.length != 2) { + if (iata != "" && iata.length != 2) { alert(gt.gettext("IATA codes must be exactly two letters.")); form.iata.focus(); return; @@ -78,7 +81,7 @@ function xmlhttpPost(strURL, offset, action) { iata = iata.toUpperCase(); form.iata.value = iata; } - if(icao != "" && icao.length != 3) { + if (icao != "" && icao.length != 3) { alert(gt.gettext("ICAO codes must be exactly three letters.")); form.icao.focus(); return; @@ -86,18 +89,22 @@ function xmlhttpPost(strURL, offset, action) { icao = icao.toUpperCase(); form.icao.value = icao; } - if(["XXX", "YYY", "ZZZ"].indexOf(icao) > -1) { + if (["XXX", "YYY", "ZZZ"].indexOf(icao) > -1) { alert(gt.gettext("Invalid ICAO code.")); form.iata.focus(); return; } - if(action == "RECORD") { - if(! parent.opener || ! parent.opener.addNewAirline) { - alert(gt.gettext("Sorry, you have to be logged into OpenFlights to use this.")); + if (action == "RECORD") { + if (!parent.opener || !parent.opener.addNewAirline) { + alert( + gt.gettext( + "Sorry, you have to be logged into OpenFlights to use this." + ) + ); return; } - if(name == "") { + if (name == "") { alert(gt.gettext("Please enter a name.")); form.name.focus(); return; @@ -106,50 +113,114 @@ function xmlhttpPost(strURL, offset, action) { form.name.value = name; } - if(country == "ALL") { + if (country == "ALL") { alert(gt.gettext("Please select a country.")); form.country.focus(); return; } - if(active == "") { - alert(gt.gettext("Please select Yes for airlines that are still operating, or No for inactive airlines.")); + if (active == "") { + alert( + gt.gettext( + "Please select Yes for airlines that are still operating, or No for inactive airlines." + ) + ); form.active.focus(); return; } - if(mode == "F") { - if (iata == "" && !confirm(gt.gettext("You have not entered an IATA/FAA code. Are you sure the airline does not have one and you wish to proceed?"))) { + if (mode == "F") { + if ( + iata == "" && + !confirm( + gt.gettext( + "You have not entered an IATA/FAA code. Are you sure the airline does not have one and you wish to proceed?" + ) + ) + ) { return; } - if (icao == "" && !confirm(gt.gettext("You have not entered an ICAO code. Are you sure the airline does not have one and you wish to proceed?"))) { + if ( + icao == "" && + !confirm( + gt.gettext( + "You have not entered an ICAO code. Are you sure the airline does not have one and you wish to proceed?" + ) + ) + ) { return; } } // Last check for new airlines only - if(alid == "") { - desc = name + ", " + country + - " (IATA: " + (iata == "" ? "N/A" : iata) + ", ICAO: " + (icao == "" ? "N/A" : icao) + ")"; - if (!confirm(Gettext.strargs(gt.gettext("Are you sure you want to add %1 as a new operator? Please double-check the name and any airline codes before confirming."), [desc]))) { - document.getElementById("miniresultbox").innerHTML = "" + gt.gettext("Cancelled.") + ""; + if (alid == "") { + desc = + name + + ", " + + country + + " (IATA: " + + (iata == "" ? "N/A" : iata) + + ", ICAO: " + + (icao == "" ? "N/A" : icao) + + ")"; + if ( + !confirm( + Gettext.strargs( + gt.gettext( + "Are you sure you want to add %1 as a new operator? Please double-check the name and any airline codes before confirming." + ), + [desc] + ) + ) + ) { + document.getElementById("miniresultbox").innerHTML = + "" + gt.gettext("Cancelled.") + ""; return; } } } - query = 'name=' + encodeURIComponent(name) + '&' + - 'alias=' + encodeURIComponent(alias) + '&' + - 'iata=' + encodeURIComponent(iata) + '&' + - 'icao=' + encodeURIComponent(icao) + '&' + - 'country=' + encodeURIComponent(country) + '&' + - 'callsign=' + encodeURIComponent(callsign) + '&' + - 'mode=' + encodeURIComponent(mode) + '&' + - 'active=' + encodeURIComponent(active) + '&' + - 'offset=' + offset + '&' + - 'iatafilter=' + form.iatafilter.checked + '&' + - 'alid=' + alid + '&' + - 'action=' + action; - document.getElementById("miniresultbox").innerHTML = "" + (action == "SEARCH" ? gt.gettext("Searching...") : gt.gettext("Recording...")) + ""; + query = + "name=" + + encodeURIComponent(name) + + "&" + + "alias=" + + encodeURIComponent(alias) + + "&" + + "iata=" + + encodeURIComponent(iata) + + "&" + + "icao=" + + encodeURIComponent(icao) + + "&" + + "country=" + + encodeURIComponent(country) + + "&" + + "callsign=" + + encodeURIComponent(callsign) + + "&" + + "mode=" + + encodeURIComponent(mode) + + "&" + + "active=" + + encodeURIComponent(active) + + "&" + + "offset=" + + offset + + "&" + + "iatafilter=" + + form.iatafilter.checked + + "&" + + "alid=" + + alid + + "&" + + "action=" + + action; + document.getElementById("miniresultbox").innerHTML = + "" + + (action == "SEARCH" + ? gt.gettext("Searching...") + : gt.gettext("Recording...")) + + ""; } self.xmlHttpReq.send(query); } @@ -164,35 +235,52 @@ function searchResult(str) { var disclaimer = ""; guest = !parent.opener || !parent.opener.addNewAirport; - if(warning) { - table += "" + warning + ""; + if (warning) { + table += + "" + + warning + + ""; warning = null; } - for(a in airlines) { + for (a in airlines) { var col = airlines[a].split(";"); // First line contains header info - if(a == 0) { + if (a == 0) { offset = parseInt(col[0]); max = col[1]; sql = col[2]; if (max == 0) { - table += "" + gt.gettext("No matches found.") + ""; + table += + "" + gt.gettext("No matches found.") + ""; break; } - table += "" + Gettext.strargs(gt.gettext("Results %1 to %2 of %3"), [offset + 1, Math.min(offset + 10, max), max]) + "
"; + table += + "" + + Gettext.strargs(gt.gettext("Results %1 to %2 of %3"), [ + offset + 1, + Math.min(offset + 10, max), + max, + ]) + + "
"; if (max > 10) { - table += ""; + table += ''; if (offset - 10 >= 0) { - table += ""; + table += + ''; } else { - table += ""; + table += ''; } if (offset + 10 < max) { - table += "\" onClick=\"doSearch(" + (offset + 10) + ")\">"; + table += + ''; } else { - table += "\" disabled>"; + table += ''; } table += ""; } @@ -202,32 +290,69 @@ function searchResult(str) { // Meat of the table var col = JSON.parse(airlines[a]); - if(a % 2 == 1) { + if (a % 2 == 1) { bgcolor = "#fff"; } else { bgcolor = "#ddd"; } - switch(col["al_uid"]) { - case "user": - bgcolor = "#fdd"; - disclaimer = "
" + gt.gettext("Operators in pink have been added by users of OpenFlights.") + ""; - break; + switch (col["al_uid"]) { + case "user": + bgcolor = "#fdd"; + disclaimer = + "
" + + gt.gettext( + "Operators in pink have been added by users of OpenFlights." + ) + + ""; + break; - case "own": - bgcolor = "#ddf"; - disclaimer = "
" + gt.gettext("Operators in blue have been added by you and can be edited.") + ""; - break; + case "own": + bgcolor = "#ddf"; + disclaimer = + "
" + + gt.gettext( + "Operators in blue have been added by you and can be edited." + ) + + ""; + break; } - table += "" + col["al_name"] + ""; + table += + "" + + col["al_name"] + + ""; // id = alid - table += ""; - if(col["al_uid"] == "own" || guest) { + table += + ""; + if (col["al_uid"] == "own" || guest) { if (col["al_uid"] == "own") { label = gt.gettext("Edit"); } else { label = gt.gettext("Load"); } - table += ""; + table += + ""; } table += ""; @@ -243,46 +368,49 @@ function loadAirline(data) { var b_back = document.getElementById("b_back"); var b_fwd = document.getElementById("b_fwd"); - if(b_back) b_back.disabled = true; - if(b_fwd) b_fwd.disabled = true; + if (b_back) b_back.disabled = true; + if (b_fwd) b_fwd.disabled = true; - var form = document.forms['searchform']; + var form = document.forms["searchform"]; form.name.value = col["name"]; - if(col["alias"] != "null") { + if (col["alias"] != "null") { form.alias.value = col["alias"]; } - if(col["iata"] != "null") { + if (col["iata"] != "null") { form.iata.value = col["iata"]; } - if(col["icao"] != "null") { + if (col["icao"] != "null") { form.icao.value = col["icao"]; } - if(col["callsign"] != "null") { + if (col["callsign"] != "null") { form.callsign.value = col["callsign"]; } form.mode.value = col["mode"]; country = col["country"]; var country_select = form.country; - for(index = 0; index < country_select.length; index++) { - if(country_select[index].value == country || country_select[index].text == country) { + for (index = 0; index < country_select.length; index++) { + if ( + country_select[index].value == country || + country_select[index].text == country + ) { country_select.selectedIndex = index; } } var active_select = form.active; - for(index = 0; index < active_select.length; index++) { - if(active_select[index].value == col["active"]) { + for (index = 0; index < active_select.length; index++) { + if (active_select[index].value == col["active"]) { active_select.selectedIndex = index; } } - if(col["alid"]) { + if (col["alid"]) { form.alid.value = col["alid"]; - document.getElementById('b_add').style.display = "none"; - document.getElementById('b_edit').style.display = "inline"; + document.getElementById("b_add").style.display = "none"; + document.getElementById("b_edit").style.display = "inline"; } else { form.alid.value = ""; - document.getElementById('b_add').style.display = "inline"; - document.getElementById('b_edit').style.display = "none"; + document.getElementById("b_add").style.display = "inline"; + document.getElementById("b_edit").style.display = "none"; } } @@ -290,17 +418,17 @@ function loadAirline(data) { function recordResult(str) { var col = str.split(";"); // Error? - if(col[0] != "1") { + if (col[0] != "1") { document.getElementById("miniresultbox").innerHTML = col[1]; } else { document.getElementById("miniresultbox").innerHTML = col[2]; // Select newly minted airline and return to main // 1;alid - var form = document.forms['searchform']; + var form = document.forms["searchform"]; name = form.name.value; mode = form.mode.value; - if(mode == "F") { + if (mode == "F") { var iata = form.iata.value; name += " (" + (iata != "" ? iata : form.icao.value) + ")"; } @@ -310,9 +438,9 @@ function recordResult(str) { // Enable IATA,ICAO,callsign only for flights function changeMode() { - var form = document.forms['searchform']; + var form = document.forms["searchform"]; var mode = form.mode.value; - disabled = (mode != "F"); + disabled = mode != "F"; form.iata.disabled = disabled; form.icao.disabled = disabled; form.callsign.disabled = disabled; @@ -321,7 +449,7 @@ function changeMode() { // Clear form -- everything *except* database function clearSearch() { - var form = document.forms['searchform']; + var form = document.forms["searchform"]; form.name.value = ""; form.country.selectedIndex = 0; form.active.selectedIndex = 0; @@ -337,8 +465,10 @@ function clearSearch() { // Airline selected, kick it back to main window and close this function selectAirline(data, name, mode) { - if(! parent.opener || ! parent.opener.addNewAirline) { - alert(gt.gettext("Sorry, you have to be logged into OpenFlights to do this.")); + if (!parent.opener || !parent.opener.addNewAirline) { + alert( + gt.gettext("Sorry, you have to be logged into OpenFlights to do this.") + ); } parent.opener.addNewAirline(data, unescape(name), mode); window.close(); @@ -346,5 +476,9 @@ function selectAirline(data, name, mode) { // A dupe from openflights.js... function help(context) { - window.open('/help/' + context + '.html', 'OpenFlights Help: ' + context, 'width=500,height=400,scrollbars=yes'); + window.open( + "/help/" + context + ".html", + "OpenFlights Help: " + context, + "width=500,height=400,scrollbars=yes" + ); } diff --git a/js/apsearch.js b/js/apsearch.js index ca37a636..73e5db5d 100644 --- a/js/apsearch.js +++ b/js/apsearch.js @@ -11,17 +11,17 @@ var warning; var gt; var query; -window.onload = function init(){ - gt = new Gettext({ 'domain' : 'messages' }); +window.onload = function init() { + gt = new Gettext({ domain: "messages" }); // ...?apid=code:apid:... - var args = window.location.href.split('?'); - if(args[1]) { - if(args[1].split('=')[0] == "apid") { - apid = args[1].split('=')[1]; + var args = window.location.href.split("?"); + if (args[1]) { + if (args[1].split("=")[0] == "apid") { + apid = args[1].split("=")[1]; xmlhttpPost(URL_APSEARCH, apid, "LOAD"); } } -} +}; function doSearch(offset) { xmlhttpPost(URL_APSEARCH, offset, "SEARCH"); @@ -46,29 +46,33 @@ function xmlhttpPost(strURL, offset, action) { else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } - self.xmlHttpReq.open('POST', strURL, true); - self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - self.xmlHttpReq.onreadystatechange = function() { - if (self.xmlHttpReq.readyState == 4) { - if (self.xmlHttpReq.status != 200) { - document.getElementById("miniresultbox").innerHTML = self.xmlHttpReq.statusText; - return; - } - if (strURL == URL_APSEARCH) { - if (action == "SEARCH") { - searchResult(self.xmlHttpReq.responseText); - } - if (action == "RECORD") { - recordResult(self.xmlHttpReq.responseText); - } - if (action == "LOAD") { - loadAirport(self.xmlHttpReq.responseText); - } - } + self.xmlHttpReq.open("POST", strURL, true); + self.xmlHttpReq.setRequestHeader( + "Content-Type", + "application/x-www-form-urlencoded" + ); + self.xmlHttpReq.onreadystatechange = function () { + if (self.xmlHttpReq.readyState == 4) { + if (self.xmlHttpReq.status != 200) { + document.getElementById("miniresultbox").innerHTML = + self.xmlHttpReq.statusText; + return; } - } - if(strURL == URL_APSEARCH) { - var form = document.forms['searchform']; + if (strURL == URL_APSEARCH) { + if (action == "SEARCH") { + searchResult(self.xmlHttpReq.responseText); + } + if (action == "RECORD") { + recordResult(self.xmlHttpReq.responseText); + } + if (action == "LOAD") { + loadAirport(self.xmlHttpReq.responseText); + } + } + } + }; + if (strURL == URL_APSEARCH) { + var form = document.forms["searchform"]; var db = form.db.value; var airport = form.airport.value; var city = form.city.value; @@ -80,10 +84,10 @@ function xmlhttpPost(strURL, offset, action) { var elevation = form.elevation.value; var tz = form.tz.value; var dst = form.dst.value; - var country = form.country[form.country.selectedIndex].text + var country = form.country[form.country.selectedIndex].text; var apid = form.apid.value; - if(iata != "" && iata.length != 3) { + if (iata != "" && iata.length != 3) { alert(gt.gettext("IATA/FAA codes must be exactly three letters.")); form.iata.focus(); return; @@ -91,12 +95,12 @@ function xmlhttpPost(strURL, offset, action) { iata = iata.toUpperCase(); form.iata.value = iata; } - if(["XXX", "YYY", "ZZZ"].indexOf(iata) > -1) { + if (["XXX", "YYY", "ZZZ"].indexOf(iata) > -1) { alert(gt.gettext("Invalid IATA code.")); form.iata.focus(); return; } - if(icao != "" && icao.length != 4) { + if (icao != "" && icao.length != 4) { alert(gt.gettext("ICAO codes must be exactly four letters.")); form.icao.focus(); return; @@ -105,166 +109,274 @@ function xmlhttpPost(strURL, offset, action) { form.icao.value = icao; } var re_alphanum = /^[-.\'a-zA-Z0-9 ]*$/; - if(! re_alphanum.test(airport) || ! re_alphanum.test(city)) { - alert(gt.gettext("Only the unaccented letters A-Z, the numbers 0-9, the punctuation marks -.' (dash, period, apostrophe) and spaces can be used in airport and city names.")); + if (!re_alphanum.test(airport) || !re_alphanum.test(city)) { + alert( + gt.gettext( + "Only the unaccented letters A-Z, the numbers 0-9, the punctuation marks -.' (dash, period, apostrophe) and spaces can be used in airport and city names." + ) + ); return; } - if(action == "SEARCH" && db == DB_DAFIF) { - if (city != "") { - warning = Gettext.strargs(gt.gettext("Ignoring city '%1', since the DAFIF database does not contain city information."), [city]); - city = ""; - } - if (iata != "") { - switch (code) { - case "US": - // do nothing - break; - - case "": - warning = Gettext.strargs(gt.gettext("Search for IATA/FAA code '%1' limited to United States airports, since DAFIF does not contain IATA codes for cities outside the US."), [iata]); - code = "US"; - break; - - default: - warning = Gettext.strargs(gt.gettext("Ignoring IATA code '%1', since DAFIF does not contain IATA codes for cities outside the United States."), [iata]); - iata = ""; - break; - } + if (action == "SEARCH" && db == DB_DAFIF) { + if (city != "") { + warning = Gettext.strargs( + gt.gettext( + "Ignoring city '%1', since the DAFIF database does not contain city information." + ), + [city] + ); + city = ""; + } + if (iata != "") { + switch (code) { + case "US": + // do nothing + break; + + case "": + warning = Gettext.strargs( + gt.gettext( + "Search for IATA/FAA code '%1' limited to United States airports, since DAFIF does not contain IATA codes for cities outside the US." + ), + [iata] + ); + code = "US"; + break; + + default: + warning = Gettext.strargs( + gt.gettext( + "Ignoring IATA code '%1', since DAFIF does not contain IATA codes for cities outside the United States." + ), + [iata] + ); + iata = ""; + break; } + } } - if(action == "LOAD") { + if (action == "LOAD") { apid = offset; // ugly hack! } - if(action == "RECORD") { - if(airport == "") { - alert(gt.gettext("Please enter an airport name.")); - form.airport.focus(); - return; + if (action == "RECORD") { + if (airport == "") { + alert(gt.gettext("Please enter an airport name.")); + form.airport.focus(); + return; } else { - airport = airport.substring(0, 1).toUpperCase() + airport.substring(1); - form.airport.value = airport; + airport = airport.substring(0, 1).toUpperCase() + airport.substring(1); + form.airport.value = airport; } - if(city == "") { - alert(gt.gettext("Please enter a city name.")); - form.city.focus(); - return; + if (city == "") { + alert(gt.gettext("Please enter a city name.")); + form.city.focus(); + return; } else { - city = city.substring(0, 1).toUpperCase() + city.substring(1); - form.city.value = city; + city = city.substring(0, 1).toUpperCase() + city.substring(1); + form.city.value = city; } - if(code == "") { - alert(gt.gettext("Please select a country.")); - form.country.focus(); - return; + if (code == "") { + alert(gt.gettext("Please select a country.")); + form.country.focus(); + return; } - if(x == "" || y == "" || elevation == "") { - alert(gt.gettext("Please enter latitude, longitude and elevation. Tip: Check if the OurAirport database already contains your airport, and \"Load\" the data from there.")); - form.x.focus(); - return; + if (x == "" || y == "" || elevation == "") { + alert( + gt.gettext( + 'Please enter latitude, longitude and elevation. Tip: Check if the OurAirport database already contains your airport, and "Load" the data from there.' + ) + ); + form.x.focus(); + return; } var re_dd = /^[-+]?\d*\.\d{3,}$/; - if(! re_dd.test(x) || ! re_dd.test(y)) { - alert(gt.gettext("Latitude and longitude must be given as decimal degrees, where negative numbers indicate 'south' and 'west' respectively, and with at least three digits of precision (after the decimal point). For example, San Francisco (SFO) is at latitude 37.6189(N), longitude -122.3748(W).")); - form.x.focus(); - return; + if (!re_dd.test(x) || !re_dd.test(y)) { + alert( + gt.gettext( + "Latitude and longitude must be given as decimal degrees, where negative numbers indicate 'south' and 'west' respectively, and with at least three digits of precision (after the decimal point). For example, San Francisco (SFO) is at latitude 37.6189(N), longitude -122.3748(W)." + ) + ); + form.x.focus(); + return; } - if(Math.abs(x) > 180) { - alert(gt.gettext("Longitude must be in the range -180 (west) to 180 (east) degrees.")); - form.x.focus(); - return; + if (Math.abs(x) > 180) { + alert( + gt.gettext( + "Longitude must be in the range -180 (west) to 180 (east) degrees." + ) + ); + form.x.focus(); + return; } - if(Math.abs(y) > 90) { - alert(gt.gettext("Latitude must be in the range 90 (north) to -90 (south) degrees.")); - form.y.focus(); - return; + if (Math.abs(y) > 90) { + alert( + gt.gettext( + "Latitude must be in the range 90 (north) to -90 (south) degrees." + ) + ); + form.y.focus(); + return; } - if(elevation < 0) { - alert(gt.gettext("Please enter a positive number for elevation.")); - form.elevation.focus(); - return; + if (elevation < 0) { + alert(gt.gettext("Please enter a positive number for elevation.")); + form.elevation.focus(); + return; } var re_tz = /^[-+]?\d*\.?\d*$/; - if(tz == "" || ! re_tz.test(tz) || Math.abs(tz) > 14) { - alert(gt.gettext("Please enter a timezone as an offset from UTC/GMT, eg. +8 for Singapore or -5 for New York. Use decimals for fractional time zones, eg. +5.75 for Nepal.")); - form.tz.focus(); - return; + if (tz == "" || !re_tz.test(tz) || Math.abs(tz) > 14) { + alert( + gt.gettext( + "Please enter a timezone as an offset from UTC/GMT, eg. +8 for Singapore or -5 for New York. Use decimals for fractional time zones, eg. +5.75 for Nepal." + ) + ); + form.tz.focus(); + return; } - if(dst == "U") { - if (!confirm(gt.gettext("You have not entered whether this airport follows Daylight Savings Time (DST). Leave it as Unknown?"))) { - form.dst.focus(); - return; - } + if (dst == "U") { + if ( + !confirm( + gt.gettext( + "You have not entered whether this airport follows Daylight Savings Time (DST). Leave it as Unknown?" + ) + ) + ) { + form.dst.focus(); + return; + } } - if(iata == "") { - if (!confirm(gt.gettext("You have not entered an IATA/FAA code. Are you sure the airport does not have one and you wish to proceed?"))) { - form.iata.focus(); - return; - } + if (iata == "") { + if ( + !confirm( + gt.gettext( + "You have not entered an IATA/FAA code. Are you sure the airport does not have one and you wish to proceed?" + ) + ) + ) { + form.iata.focus(); + return; + } } - if(icao == "") { - if (!confirm(gt.gettext("You have not entered an ICAO code. Are you sure the airport does not have one and you wish to proceed?"))) { - form.icao.focus(); - return; - } + if (icao == "") { + if ( + !confirm( + gt.gettext( + "You have not entered an ICAO code. Are you sure the airport does not have one and you wish to proceed?" + ) + ) + ) { + form.icao.focus(); + return; + } } // Last check for new airports only - if(apid == "") { - desc = airport + ", " + city + ", " + country + - " (IATA: " + (iata == "" ? "N/A" : iata) + ", ICAO: " + (icao == "" ? "N/A" : icao) + ")"; - quad = (parseFloat(y) < 0 ? "SOUTH" : "NORTH") + "-" + (parseFloat(x) < 0 ? "WEST" : "EAST"); - if (!confirm(Gettext.strargs(gt.gettext("Are you sure you want to add %1 as a new airport, located in the %2 quadrant of the world? Please double-check the name, airport codes and exact coordinates before confirming."), [desc, quad]))) { - getElement("miniresultbox").innerHTML = "" + gt.gettext("Cancelled.") + ""; - return; - } + if (apid == "") { + desc = + airport + + ", " + + city + + ", " + + country + + " (IATA: " + + (iata == "" ? "N/A" : iata) + + ", ICAO: " + + (icao == "" ? "N/A" : icao) + + ")"; + quad = + (parseFloat(y) < 0 ? "SOUTH" : "NORTH") + + "-" + + (parseFloat(x) < 0 ? "WEST" : "EAST"); + if ( + !confirm( + Gettext.strargs( + gt.gettext( + "Are you sure you want to add %1 as a new airport, located in the %2 quadrant of the world? Please double-check the name, airport codes and exact coordinates before confirming." + ), + [desc, quad] + ) + ) + ) { + getElement("miniresultbox").innerHTML = + "" + gt.gettext("Cancelled.") + ""; + return; + } } } // Build new query - if(action != "SEARCH" || - (action == "SEARCH" && offset == 0) - ) { - query = 'name=' + encodeURIComponent(airport) + '&' + - 'iata=' + encodeURIComponent(iata) + '&' + - 'icao=' + encodeURIComponent(icao) + '&' + - 'city=' + encodeURIComponent(city) + '&' + - 'country=' + encodeURIComponent(country) + '&' + - 'code=' + encodeURIComponent(code) + '&' + - 'x=' + x + '&' + - 'y=' + y + '&' + - 'elevation=' + elevation + '&' + - 'timezone=' + tz + '&' + - 'dst=' + dst + '&' + - 'db=' + encodeURIComponent(db) + '&' + - 'iatafilter=' + form.iatafilter.checked + '&' + - 'apid=' + apid + '&' + - 'action=' + action; + if (action != "SEARCH" || (action == "SEARCH" && offset == 0)) { + query = + "name=" + + encodeURIComponent(airport) + + "&" + + "iata=" + + encodeURIComponent(iata) + + "&" + + "icao=" + + encodeURIComponent(icao) + + "&" + + "city=" + + encodeURIComponent(city) + + "&" + + "country=" + + encodeURIComponent(country) + + "&" + + "code=" + + encodeURIComponent(code) + + "&" + + "x=" + + x + + "&" + + "y=" + + y + + "&" + + "elevation=" + + elevation + + "&" + + "timezone=" + + tz + + "&" + + "dst=" + + dst + + "&" + + "db=" + + encodeURIComponent(db) + + "&" + + "iatafilter=" + + form.iatafilter.checked + + "&" + + "apid=" + + apid + + "&" + + "action=" + + action; } } - getElement("miniresultbox").innerHTML = "" + gt.gettext(describe(action)) + ""; - self.xmlHttpReq.send(query + '&offset=' + offset); + getElement("miniresultbox").innerHTML = + "" + gt.gettext(describe(action)) + ""; + self.xmlHttpReq.send(query + "&offset=" + offset); } function describe(action) { - switch (action) { - case "SEARCH": - return "Searching..."; - case "LOAD": - return "Loading..."; - case "RECORD": - return "Recording..."; - } + switch (action) { + case "SEARCH": + return "Searching..."; + case "LOAD": + return "Loading..."; + case "RECORD": + return "Recording..."; + } } /* @@ -275,79 +387,149 @@ function searchResult(str) { var airports = json["airports"]; var table = ""; var offset, sql; - var db = document.forms['searchform'].db.value; + var db = document.forms["searchform"].db.value; var disclaimer = ""; - if(warning) { - table += ""; + if (warning) { + table += + ""; warning = null; } offset = json["offset"]; max = json["max"]; - if(max == 0) { - table += ""; } else { - table += ""; - if(max > 10) { - table += ""; + if (max > 10) { + table += '"; } table += ""; - for(a in airports) { - // Meat of the table + for (a in airports) { + // Meat of the table - var col = airports[a]; - if (a % 2 == 1) { - bgcolor = "#fff"; + var col = airports[a]; + if (a % 2 == 1) { + bgcolor = "#fff"; + } else { + bgcolor = "#ddd"; + } + switch (col["ap_uid"]) { + case "user": + bgcolor = "#fdd"; + disclaimer = + "
" + + gt.gettext( + "Airports in pink have been added by users of OpenFlights." + ) + + ""; + break; + + case "own": + bgcolor = "#ddf"; + disclaimer = + "
" + + gt.gettext( + "Airports in blue have been added by you and can be edited." + ) + + ""; + break; + } + table += + ""; + if (db == DB_OPENFLIGHTS && isEditMode()) { + // code:apid:x:y:tz:dst + id = + (col["iata"] != "" ? col["iata"] : col["icao"]) + + ":" + + col["apid"] + + ":" + + col["x"] + + ":" + + col["y"] + + ":" + + col["timezone"] + + ":" + + col["dst"]; + table += + ""; + } + if (db != DB_OPENFLIGHTS || col["ap_uid"] == "own" || !isEditMode()) { + if (col["ap_uid"] == "own" && db == DB_OPENFLIGHTS) { + label = gt.gettext("Edit"); } else { - bgcolor = "#ddd"; - } - switch (col["ap_uid"]) { - case "user": - bgcolor = "#fdd"; - disclaimer = "
" + gt.gettext("Airports in pink have been added by users of OpenFlights.") + ""; - break; - - case "own": - bgcolor = "#ddf"; - disclaimer = "
" + gt.gettext("Airports in blue have been added by you and can be edited.") + ""; - break; + label = gt.gettext("Load"); } - table += ""; - if (db == DB_OPENFLIGHTS && isEditMode()) { - // code:apid:x:y:tz:dst - id = (col["iata"] != "" ? col["iata"] : col["icao"]) + ":" + col["apid"] + ":" + col["x"] + ":" + col["y"] + - ":" + col["timezone"] + ":" + col["dst"]; - table += ""; - } - if (db != DB_OPENFLIGHTS || col["ap_uid"] == "own" || !isEditMode()) { - if (col["ap_uid"] == "own" && db == DB_OPENFLIGHTS) { - label = gt.gettext("Edit"); - } else { - label = gt.gettext("Load"); - } - table += ""; - } - table += ""; + table += + ""; + } + table += ""; } } table += "
" + warning + "
" + + warning + + "
" + gt.gettext("No matches found in this database.") + "
    "; - if(document.forms['searchform'].iatafilter.checked) { - table += "
  • " + gt.gettext("Try unchecking 'Show only major airports' and search again."); + if (max == 0) { + table += + "
" + + gt.gettext("No matches found in this database.") + + "
    "; + if (document.forms["searchform"].iatafilter.checked) { + table += + "
  • " + + gt.gettext( + "Try unchecking 'Show only major airports' and search again." + ); } - if(document.forms['searchform'].db.value != DB_OURAIRPORTS) { - table += "
  • " + gt.gettext("Switch to the OurAirports database and search again."); + if (document.forms["searchform"].db.value != DB_OURAIRPORTS) { + table += + "
  • " + + gt.gettext("Switch to the OurAirports database and search again."); } table += "
" + Gettext.strargs(gt.gettext("Results %1 to %2 of %3"), [offset+1, Math.min(offset+10, max), max]) + "
"; - if(offset - 10 >= 0) { - table += ""; + table += + "
" + + Gettext.strargs(gt.gettext("Results %1 to %2 of %3"), [ + offset + 1, + Math.min(offset + 10, max), + max, + ]) + + "
'; + if (offset - 10 >= 0) { + table += + ''; } else { - table += ""; + table += ''; } - if(offset + 10 < max) { - table += "\" onClick=\"doSearch(" + (offset+10) + ")\">"; + if (offset + 10 < max) { + table += + ''; } else { - table += "\" disabled>"; + table += ''; } table += "
" + + col["ap_name"] + + "
" + col["ap_name"] + "
"; @@ -358,13 +540,15 @@ function searchResult(str) { // Load data from search result into form function loadAirport(data) { var json = JSON.parse(data); - if(json["status"] != 1 || json["max"] == 0) { - getElement("miniresultbox").innerHTML = gt.gettext("No matches found in this database."); + if (json["status"] != 1 || json["max"] == 0) { + getElement("miniresultbox").innerHTML = gt.gettext( + "No matches found in this database." + ); return; } var col = json["airports"][0]; - var form = document.forms['searchform']; + var form = document.forms["searchform"]; form.airport.value = col["name"]; form.city.value = col["city"]; form.iata.value = col["iata"]; @@ -372,27 +556,30 @@ function loadAirport(data) { form.x.value = col["x"]; form.y.value = col["y"]; form.elevation.value = col["elevation"]; - if(col["timezone"]) { + if (col["timezone"]) { form.tz.value = col["timezone"]; } country = col["country"]; var country_select = form.country; - for(index = 0; index < country_select.length; index++) { - if(country_select[index].value == country || country_select[index].text == country) { + for (index = 0; index < country_select.length; index++) { + if ( + country_select[index].value == country || + country_select[index].text == country + ) { country_select.selectedIndex = index; } } var dst_select = form.dst; - for(index = 0; index < dst_select.length; index++) { + for (index = 0; index < dst_select.length; index++) { //alert(dst_select[index].value + "/" + col["dst"]); - if(dst_select[index].value == col["dst"]) { + if (dst_select[index].value == col["dst"]) { dst_select.selectedIndex = index; } } form.apid.value = col["apid"]; - getElement('b_add').style.display = "none"; - getElement('b_edit').style.display = "inline"; + getElement("b_add").style.display = "none"; + getElement("b_edit").style.display = "inline"; getElement("b_edit").disabled = true; getElement("miniresultbox").innerHTML = ""; } @@ -400,18 +587,25 @@ function loadAirport(data) { // Did we manage to record the airport? function recordResult(str) { var json = JSON.parse(str); - if(json["status"] == "1") { + if (json["status"] == "1") { alert(json["message"]); // Select newly minted airport and return to main - var form = document.forms['searchform']; + var form = document.forms["searchform"]; var iata = form.iata.value; - var country = form.country[form.country.selectedIndex].text + var country = form.country[form.country.selectedIndex].text; // code:apid:x:y - code = (iata != "" ? iata : form.icao.value); + code = iata != "" ? iata : form.icao.value; // city-airport (code), country data = code + ":" + json["apid"] + ":" + form.x.value + ":" + form.y.value; - name = form.city.value + "-" + form.airport.value + " (" + code + "), " + country; + name = + form.city.value + + "-" + + form.airport.value + + " (" + + code + + "), " + + country; selectAirport(data, name); } getElement("miniresultbox").innerHTML = json["message"]; @@ -419,8 +613,8 @@ function recordResult(str) { } function setEdited() { - if(isLoggedIn()) { - if(getElement("b_edit").style.display == "inline") { + if (isLoggedIn()) { + if (getElement("b_edit").style.display == "inline") { getElement("b_edit").disabled = false; } else { getElement("b_add").disabled = false; @@ -430,7 +624,7 @@ function setEdited() { // Clear form -- everything *except* database function clearSearch() { - var form = document.forms['searchform']; + var form = document.forms["searchform"]; form.airport.value = ""; form.city.value = ""; form.country.selectedIndex = 0; @@ -443,14 +637,14 @@ function clearSearch() { form.dst.selectedIndex = 0; form.apid.value = ""; form.iatafilter.checked = true; - getElement('b_add').style.display = "inline"; - getElement('b_add').disabled = true; - getElement('b_edit').style.display = "none"; + getElement("b_add").style.display = "inline"; + getElement("b_add").disabled = true; + getElement("b_edit").style.display = "none"; getElement("miniresultbox").innerHTML = ""; } function isLoggedIn() { - if(! parent.opener || ! parent.opener.addNewAirport) { + if (!parent.opener || !parent.opener.addNewAirport) { // If airport search was loaded without OpenFlights, we're not in edit mode return false; } else { @@ -474,5 +668,9 @@ function getElement(id) { // A dupe from openflights.js... function help(context) { - window.open('/help/' + context + '.html', 'OpenFlights Help: ' + context, 'width=500,height=400,scrollbars=yes'); + window.open( + "/help/" + context + ".html", + "OpenFlights Help: " + context, + "width=500,height=400,scrollbars=yes" + ); } diff --git a/js/greatcircle.js b/js/greatcircle.js index f362a56a..74274448 100644 --- a/js/greatcircle.js +++ b/js/greatcircle.js @@ -3,11 +3,11 @@ /** * Geo Constants */ -EARTH_RADIUS = 3958.75; // in miles +EARTH_RADIUS = 3958.75; // in miles EARTH_CIRCUMFERENCE = 24900; // in miles -MOON_DISTANCE = 238857; // in miles -MARS_DISTANCE = 34649589; // in miles -DEG2RAD = 0.01745329252; // factor to convert degrees to radians (PI/180) +MOON_DISTANCE = 238857; // in miles +MARS_DISTANCE = 34649589; // in miles +DEG2RAD = 0.01745329252; // factor to convert degrees to radians (PI/180) RAD2DEG = 57.29577951308; GC_STEP = 100; // draw segment every GC_STEP mi GC_MIN = 300; // trigger GC paths once distance is greater than this @@ -24,14 +24,14 @@ function gcDistance(lat1, lon1, lat2, lon2) { lon1 = lon1 * rad; lat2 = lat2 * rad; lon2 = lon2 * rad; - var d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + - Math.cos(lat1)*Math.cos(lat2) * - Math.cos(lon2-lon1)); + var d = Math.acos( + Math.sin(lat1) * Math.sin(lat2) + + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1) + ); if (d < 0) { d += Math.PI; } return Math.floor(d * EARTH_RADIUS); - } // Compute great circle bearing from point "from" towards point "to" @@ -41,21 +41,24 @@ function gcBearingTo(from, to) { var bearing; var adjust; - if( isValid(from) && isValid(to)) { - x[0] = from.x * DEG2RAD; y[0] = from.y * DEG2RAD; - x[1] = to.x * DEG2RAD; y[1] = to.y * DEG2RAD; + if (isValid(from) && isValid(to)) { + x[0] = from.x * DEG2RAD; + y[0] = from.y * DEG2RAD; + x[1] = to.x * DEG2RAD; + y[1] = to.y * DEG2RAD; var a = Math.cos(y[1]) * Math.sin(x[1] - x[0]); - var b = Math.cos(y[0]) * Math.sin(y[1]) - Math.sin(y[0]) - * Math.cos(y[1]) * Math.cos(x[1] - x[0]); + var b = + Math.cos(y[0]) * Math.sin(y[1]) - + Math.sin(y[0]) * Math.cos(y[1]) * Math.cos(x[1] - x[0]); - if((a == 0) && (b == 0)) { + if (a == 0 && b == 0) { bearing = 0; return bearing; } - if(b == 0) { - if(a < 0) { + if (b == 0) { + if (a < 0) { bearing = 270; } else { bearing = 90; @@ -63,27 +66,25 @@ function gcBearingTo(from, to) { return bearing; } - if(b < 0) { + if (b < 0) { adjust = Math.PI; } else { - if(a < 0) { + if (a < 0) { adjust = 2 * Math.PI; } else { adjust = 0; } } - bearing = (Math.atan(a/b) + adjust) * RAD2DEG; + bearing = (Math.atan(a / b) + adjust) * RAD2DEG; return bearing; - } else - return null; + } else return null; } - /** * Compute great circle waypoint "distance" miles away from "from" in direction "bearing" */ function gcWaypoint(from, distance, bearing) { - var wp = new OpenLayers.Geometry.Point( 0, 0 ); + var wp = new OpenLayers.Geometry.Point(0, 0); // Math.* trig functions require angles to be in radians var x = from.x * DEG2RAD; @@ -94,8 +95,13 @@ function gcWaypoint(from, distance, bearing) { var d = distance / EARTH_RADIUS; // Modified based on https://web.archive.org/web/20161209044600/http://williams.best.vwh.net/avform.htm - var lat = Math.asin( Math.sin(y) * Math.cos(d) + Math.cos(y) * Math.sin(d) * Math.cos(radBearing)); - var lon = Math.atan2( Math.sin(radBearing) * Math.sin(d) * Math.cos(y), Math.cos(d) - Math.sin(y) * Math.sin(lat)); + var lat = Math.asin( + Math.sin(y) * Math.cos(d) + Math.cos(y) * Math.sin(d) * Math.cos(radBearing) + ); + var lon = Math.atan2( + Math.sin(radBearing) * Math.sin(d) * Math.cos(y), + Math.cos(d) - Math.sin(y) * Math.sin(lat) + ); wp.x = (x + lon) * RAD2DEG; wp.y = lat * RAD2DEG; return wp; @@ -107,8 +113,8 @@ function gcWaypoint(from, distance, bearing) { */ function gcPath(startPoint, endPoint) { // Do we cross the dateline? If yes, then flip endPoint across it - if(Math.abs(startPoint.x-endPoint.x) > 180) { - if(startPoint.x < endPoint.x) { + if (Math.abs(startPoint.x - endPoint.x) > 180) { + if (startPoint.x < endPoint.x) { endPoint.x -= 360; } else { endPoint.x += 360; @@ -117,7 +123,7 @@ function gcPath(startPoint, endPoint) { // Compute distance between points var distance = gcDistance(startPoint.y, startPoint.x, endPoint.y, endPoint.x); - if(distance < GC_MIN) { + if (distance < GC_MIN) { // Short enough that we don't need to show curvature return [startPoint, endPoint]; } @@ -127,29 +133,32 @@ function gcPath(startPoint, endPoint) { var wayPoint = startPoint; var d = GC_STEP; var step = GC_STEP; - if(startPoint.x > -360 && startPoint.x < 360) { + if (startPoint.x > -360 && startPoint.x < 360) { pointList.push(startPoint); } - while(d < distance) { + while (d < distance) { var bearing = gcBearingTo(wayPoint, endPoint); // degrees, clockwise from 0 deg at north wayPoint = gcWaypoint(wayPoint, step, bearing); - if(wayPoint.x > -360 && wayPoint.x < 360) { + if (wayPoint.x > -360 && wayPoint.x < 360) { pointList.push(wayPoint); } else { - if((wayPoint.x < -360 && bearing > 180) || (wayPoint.x > 360 && bearing < 180)) { + if ( + (wayPoint.x < -360 && bearing > 180) || + (wayPoint.x > 360 && bearing < 180) + ) { break; // line's gone off the map, so stop rendering } } // Increase step resolution near the poles - if(Math.abs(wayPoint.y) > 60) { + if (Math.abs(wayPoint.y) > 60) { step = GC_STEP / 2; } else { step = GC_STEP; } d += step; } - if(endPoint.x > -360 && endPoint.x < 360) { + if (endPoint.x > -360 && endPoint.x < 360) { pointList.push(endPoint); } return pointList; @@ -157,21 +166,26 @@ function gcPath(startPoint, endPoint) { // Check if point is a point function isValid(point) { - return ((point.x != null) && (point.y != null) && (point.x != NaN) && (point.y != NaN)) + return point.x != null && point.y != null && point.x != NaN && point.y != NaN; } // Compute extent for visible data (-180 to 180) // Known bug: incorrectly draws whole map if flight lines span the meridian... function getVisibleDataExtent(layer) { var bounds = layer.getDataExtent(); - if(! bounds) { + if (!bounds) { return null; } - if(bounds.left < -180 && bounds.left > -360 && bounds.right > 180 && bounds.right < 360) { + if ( + bounds.left < -180 && + bounds.left > -360 && + bounds.right > 180 && + bounds.right < 360 + ) { // map spans the world, do nothing } else { - if(bounds.left < -180) bounds.left += 360; - if(bounds.right > 180) bounds.right -= 360; + if (bounds.left < -180) bounds.left += 360; + if (bounds.right > 180) bounds.right -= 360; } return bounds; } @@ -186,10 +200,10 @@ function changeLocale() { var locale = "lang=" + document.getElementById("locale").value; var re_lang = /lang=...../; var url = "http://" + location.host + location.pathname + location.search; // omit #anchor - if(re_lang.test(url)) { + if (re_lang.test(url)) { url = url.replace(re_lang, locale); } else { - if(url.indexOf("?") == -1) { + if (url.indexOf("?") == -1) { url = url + "?" + locale; } else { url = url + "&" + locale; @@ -201,53 +215,52 @@ function changeLocale() { // // Check if DST is active function checkDST(type, date, year) { - switch(type) { - case "E": - // Europe: Last Sunday in Mar to last Sunday in Oct - if (date >= getLastDay(year, 3, 0) && - date < getLastDay(year, 10, 0) - ) { - return true; - } - break; + switch (type) { + case "E": + // Europe: Last Sunday in Mar to last Sunday in Oct + if (date >= getLastDay(year, 3, 0) && date < getLastDay(year, 10, 0)) { + return true; + } + break; - case "A": - // US/Canada: 2nd Sunday in Mar to 1st Sunday in Nov - if (date >= getNthDay(year, 3, 2, 0) && + case "A": + // US/Canada: 2nd Sunday in Mar to 1st Sunday in Nov + if ( + date >= getNthDay(year, 3, 2, 0) && date < getNthDay(year, 11, 1, 0) - ) { - return true; - } - break; + ) { + return true; + } + break; - case "S": - // South America: Until 3rd Sunday in Mar or after 3nd Sunday in Oct - if (date < getNthDay(year, 3, 3, 0) || + case "S": + // South America: Until 3rd Sunday in Mar or after 3nd Sunday in Oct + if ( + date < getNthDay(year, 3, 3, 0) || date >= getNthDay(year, 10, 3, 0) - ) { - return true; - } - break; + ) { + return true; + } + break; - case "O": - // Australia: Until 1st Sunday in April or after 1st Sunday in Oct - if (date < getNthDay(year, 4, 1, 0) || + case "O": + // Australia: Until 1st Sunday in April or after 1st Sunday in Oct + if ( + date < getNthDay(year, 4, 1, 0) || date >= getNthDay(year, 10, 1, 0) - ) { - return true; - } - break; - - case "Z": - // New Zealand: Until 1st Sunday in April or after last Sunday in Sep - if (date < getNthDay(year, 4, 1, 0) || - date >= getLastDay(year, 9, 0) - ) { - return true; - } - break; + ) { + return true; + } + break; + + case "Z": + // New Zealand: Until 1st Sunday in April or after last Sunday in Sep + if (date < getNthDay(year, 4, 1, 0) || date >= getLastDay(year, 9, 0)) { + return true; + } + break; - default: + default: // cases U, N -- do nothing } return false; @@ -257,12 +270,12 @@ function checkDST(type, date, year) { // 'type' is 0 for Sun, 1 for Mon, etc function getNthDay(year, month, nth, type) { date = new Date(); - date.setFullYear(year, month-1, 1); // Date object months start from 0 + date.setFullYear(year, month - 1, 1); // Date object months start from 0 day = date.getDay(); - if(type >= day) { + if (type >= day) { nth--; } - date.setDate(date.getDate() + (7 - (day - type)) + ((nth-1) * 7)); + date.setDate(date.getDate() + (7 - (day - type)) + (nth - 1) * 7); return date; } @@ -270,7 +283,7 @@ function getNthDay(year, month, nth, type) { function getLastDay(year, month, type) { date = new Date(); date.setFullYear(year, month, 1); // Date object months start from 0, so this is +1 - date.setDate(date.getDate()-1); // last day of previous month + date.setDate(date.getDate() - 1); // last day of previous month date.setDate(date.getDate() - (date.getDay() - type)); return date; } @@ -284,25 +297,25 @@ function parseTimeString(time_str) { // Splice and dice apdata chunks // code:apid:x:y:tz:dst function getApid(element) { - return $(element + 'id').value.split(":")[1]; + return $(element + "id").value.split(":")[1]; } function getX(element) { - return $(element + 'id').value.split(":")[2]; + return $(element + "id").value.split(":")[2]; } function getY(element) { - return $(element + 'id').value.split(":")[3]; + return $(element + "id").value.split(":")[3]; } function getTZ(element) { - var tz = $(element + 'id').value.split(":")[4]; - if(!tz || tz == "") { + var tz = $(element + "id").value.split(":")[4]; + if (!tz || tz == "") { return 0; } else { return parseFloat(tz); } } function getDST(element) { - var dst = $(element + 'id').value.split(":")[5]; - if(!dst || dst == "") { + var dst = $(element + "id").value.split(":")[5]; + if (!dst || dst == "") { return "N"; } else { return dst; @@ -313,20 +326,40 @@ function getDST(element) { // If validity is not null, also return text description and validity period var eliteicons = [ - [ 'S', 'Silver Elite', '/img/silver-star.png' ], - [ 'G', 'Gold Elite', '/img/gold-star.png' ], - [ 'P', 'Platinum Elite', '/img/platinum-star.png' ], - [ 'X', 'Thank you for using OpenFlights — please donate!', '/img/icon-warning.png' ] + ["S", "Silver Elite", "/img/silver-star.png"], + ["G", "Gold Elite", "/img/gold-star.png"], + ["P", "Platinum Elite", "/img/platinum-star.png"], + [ + "X", + "Thank you for using OpenFlights — please donate!", + "/img/icon-warning.png", + ], ]; function getEliteIcon(e, validity) { - if(e && e != "") { - for(i = 0; i < eliteicons.length; i++) { - if(eliteicons[i][0] == e) { + if (e && e != "") { + for (i = 0; i < eliteicons.length; i++) { + if (eliteicons[i][0] == e) { if (validity) { - return "

" + eliteicons[i][1] + "
Valid until
" + validity + "
"; + return ( + "

" + + eliteicons[i][1] + + "
Valid until
" + + validity + + "
" + ); } else { - return ""; + return ( + "" + ); } } } @@ -336,12 +369,12 @@ function getEliteIcon(e, validity) { // Given element "select", select option matching "value", or #0 if not found function selectInSelect(select, value) { - if(!select) { + if (!select) { return; } select.selectedIndex = 0; // default to unselected - for(index = 0; index < select.length; index++) { - if(select[index].value == value) { + for (index = 0; index < select.length; index++) { + if (select[index].value == value) { select.selectedIndex = index; } } diff --git a/js/prototype.js b/js/prototype.js index 04a47793..b80e04ea 100644 --- a/js/prototype.js +++ b/js/prototype.js @@ -7,19 +7,19 @@ *--------------------------------------------------------------------------*/ var Prototype = { + Version: "1.7", - Version: '1.7', - - Browser: (function(){ + Browser: (function () { var ua = navigator.userAgent; - var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; + var isOpera = + Object.prototype.toString.call(window.opera) == "[object Opera]"; return { - IE: !!window.attachEvent && !isOpera, - Opera: isOpera, - WebKit: ua.indexOf('AppleWebKit/') > -1, - Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, - MobileSafari: /Apple.*Mobile/.test(ua) - } + IE: !!window.attachEvent && !isOpera, + Opera: isOpera, + WebKit: ua.indexOf("AppleWebKit/") > -1, + Gecko: ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1, + MobileSafari: /Apple.*Mobile/.test(ua), + }; })(), BrowserFeatures: { @@ -27,54 +27,54 @@ var Prototype = { SelectorsAPI: !!document.querySelector, - ElementExtensions: (function() { + ElementExtensions: (function () { var constructor = window.Element || window.HTMLElement; return !!(constructor && constructor.prototype); })(), - SpecificElementExtensions: (function() { - if (typeof window.HTMLDivElement !== 'undefined') - return true; + SpecificElementExtensions: (function () { + if (typeof window.HTMLDivElement !== "undefined") return true; - var div = document.createElement('div'), - form = document.createElement('form'), - isSupported = false; + var div = document.createElement("div"), + form = document.createElement("form"), + isSupported = false; - if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) { + if (div["__proto__"] && div["__proto__"] !== form["__proto__"]) { isSupported = true; } div = form = null; return isSupported; - })() + })(), }, - ScriptFragment: ']*>([\\S\\s]*?)<\/script>', + ScriptFragment: "]*>([\\S\\s]*?)", JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, - emptyFunction: function() { }, + emptyFunction: function () {}, - K: function(x) { return x } + K: function (x) { + return x; + }, }; if (Prototype.Browser.MobileSafari) Prototype.BrowserFeatures.SpecificElementExtensions = false; /* Based on Alex Arnell's inheritance implementation. */ -var Class = (function() { - - var IS_DONTENUM_BUGGY = (function(){ +var Class = (function () { + var IS_DONTENUM_BUGGY = (function () { for (var p in { toString: 1 }) { - if (p === 'toString') return false; + if (p === "toString") return false; } return true; })(); - function subclass() {}; + function subclass() {} function create() { - var parent = null, properties = $A(arguments); - if (Object.isFunction(properties[0])) - parent = properties.shift(); + var parent = null, + properties = $A(arguments); + if (Object.isFunction(properties[0])) parent = properties.shift(); function klass() { this.initialize.apply(this, arguments); @@ -86,7 +86,7 @@ var Class = (function() { if (parent) { subclass.prototype = parent.prototype; - klass.prototype = new subclass; + klass.prototype = new subclass(); parent.subclasses.push(klass); } @@ -101,8 +101,8 @@ var Class = (function() { } function addMethods(source) { - var ancestor = this.superclass && this.superclass.prototype, - properties = Object.keys(source); + var ancestor = this.superclass && this.superclass.prototype, + properties = Object.keys(source); if (IS_DONTENUM_BUGGY) { if (source.toString != Object.prototype.toString) @@ -112,12 +112,18 @@ var Class = (function() { } for (var i = 0, length = properties.length; i < length; i++) { - var property = properties[i], value = source[property]; - if (ancestor && Object.isFunction(value) && - value.argumentNames()[0] == "$super") { + var property = properties[i], + value = source[property]; + if ( + ancestor && + Object.isFunction(value) && + value.argumentNames()[0] == "$super" + ) { var method = value; - value = (function(m) { - return function() { return ancestor[m].apply(this, arguments); }; + value = (function (m) { + return function () { + return ancestor[m].apply(this, arguments); + }; })(property).wrap(method); value.valueOf = method.valueOf.bind(method); @@ -132,70 +138,74 @@ var Class = (function() { return { create: create, Methods: { - addMethods: addMethods - } + addMethods: addMethods, + }, }; })(); -(function() { - +(function () { var _toString = Object.prototype.toString, - NULL_TYPE = 'Null', - UNDEFINED_TYPE = 'Undefined', - BOOLEAN_TYPE = 'Boolean', - NUMBER_TYPE = 'Number', - STRING_TYPE = 'String', - OBJECT_TYPE = 'Object', - FUNCTION_CLASS = '[object Function]', - BOOLEAN_CLASS = '[object Boolean]', - NUMBER_CLASS = '[object Number]', - STRING_CLASS = '[object String]', - ARRAY_CLASS = '[object Array]', - DATE_CLASS = '[object Date]', - NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON && - typeof JSON.stringify === 'function' && - JSON.stringify(0) === '0' && - typeof JSON.stringify(Prototype.K) === 'undefined'; + NULL_TYPE = "Null", + UNDEFINED_TYPE = "Undefined", + BOOLEAN_TYPE = "Boolean", + NUMBER_TYPE = "Number", + STRING_TYPE = "String", + OBJECT_TYPE = "Object", + FUNCTION_CLASS = "[object Function]", + BOOLEAN_CLASS = "[object Boolean]", + NUMBER_CLASS = "[object Number]", + STRING_CLASS = "[object String]", + ARRAY_CLASS = "[object Array]", + DATE_CLASS = "[object Date]", + NATIVE_JSON_STRINGIFY_SUPPORT = + window.JSON && + typeof JSON.stringify === "function" && + JSON.stringify(0) === "0" && + typeof JSON.stringify(Prototype.K) === "undefined"; function Type(o) { - switch(o) { - case null: return NULL_TYPE; - case (void 0): return UNDEFINED_TYPE; + switch (o) { + case null: + return NULL_TYPE; + case void 0: + return UNDEFINED_TYPE; } var type = typeof o; - switch(type) { - case 'boolean': return BOOLEAN_TYPE; - case 'number': return NUMBER_TYPE; - case 'string': return STRING_TYPE; + switch (type) { + case "boolean": + return BOOLEAN_TYPE; + case "number": + return NUMBER_TYPE; + case "string": + return STRING_TYPE; } return OBJECT_TYPE; } function extend(destination, source) { - for (var property in source) - destination[property] = source[property]; + for (var property in source) destination[property] = source[property]; return destination; } function inspect(object) { try { - if (isUndefined(object)) return 'undefined'; - if (object === null) return 'null'; + if (isUndefined(object)) return "undefined"; + if (object === null) return "null"; return object.inspect ? object.inspect() : String(object); } catch (e) { - if (e instanceof RangeError) return '...'; + if (e instanceof RangeError) return "..."; throw e; } } function toJSON(value) { - return Str('', { '': value }, []); + return Str("", { "": value }, []); } function Str(key, holder, stack) { var value = holder[key], - type = typeof value; + type = typeof value; - if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') { + if (Type(value) === OBJECT_TYPE && typeof value.toJSON === "function") { value = value.toJSON(key); } @@ -209,21 +219,25 @@ var Class = (function() { } switch (value) { - case null: return 'null'; - case true: return 'true'; - case false: return 'false'; + case null: + return "null"; + case true: + return "true"; + case false: + return "false"; } type = typeof value; switch (type) { - case 'string': + case "string": return value.inspect(true); - case 'number': - return isFinite(value) ? String(value) : 'null'; - case 'object': - + case "number": + return isFinite(value) ? String(value) : "null"; + case "object": for (var i = 0, length = stack.length; i < length; i++) { - if (stack[i] === value) { throw new TypeError(); } + if (stack[i] === value) { + throw new TypeError(); + } } stack.push(value); @@ -231,18 +245,19 @@ var Class = (function() { if (_class === ARRAY_CLASS) { for (var i = 0, length = value.length; i < length; i++) { var str = Str(i, value, stack); - partial.push(typeof str === 'undefined' ? 'null' : str); + partial.push(typeof str === "undefined" ? "null" : str); } - partial = '[' + partial.join(',') + ']'; + partial = "[" + partial.join(",") + "]"; } else { var keys = Object.keys(value); for (var i = 0, length = keys.length; i < length; i++) { - var key = keys[i], str = Str(key, value, stack); + var key = keys[i], + str = Str(key, value, stack); if (typeof str !== "undefined") { - partial.push(key.inspect(true)+ ':' + str); - } + partial.push(key.inspect(true) + ":" + str); + } } - partial = '{' + partial.join(',') + '}'; + partial = "{" + partial.join(",") + "}"; } stack.pop(); return partial; @@ -262,7 +277,9 @@ var Class = (function() { } function keys(object) { - if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); } + if (Type(object) !== OBJECT_TYPE) { + throw new TypeError(); + } var results = []; for (var property in object) { if (object.hasOwnProperty(property)) { @@ -274,13 +291,12 @@ var Class = (function() { function values(object) { var results = []; - for (var property in object) - results.push(object[property]); + for (var property in object) results.push(object[property]); return results; } function clone(object) { - return extend({ }, object); + return extend({}, object); } function isElement(object) { @@ -291,8 +307,10 @@ var Class = (function() { return _toString.call(object) === ARRAY_CLASS; } - var hasNativeIsArray = (typeof Array.isArray == 'function') - && Array.isArray([]) && !Array.isArray({}); + var hasNativeIsArray = + typeof Array.isArray == "function" && + Array.isArray([]) && + !Array.isArray({}); if (hasNativeIsArray) { isArray = Array.isArray; @@ -323,145 +341,156 @@ var Class = (function() { } extend(Object, { - extend: extend, - inspect: inspect, - toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON, + extend: extend, + inspect: inspect, + toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON, toQueryString: toQueryString, - toHTML: toHTML, - keys: Object.keys || keys, - values: values, - clone: clone, - isElement: isElement, - isArray: isArray, - isHash: isHash, - isFunction: isFunction, - isString: isString, - isNumber: isNumber, - isDate: isDate, - isUndefined: isUndefined + toHTML: toHTML, + keys: Object.keys || keys, + values: values, + clone: clone, + isElement: isElement, + isArray: isArray, + isHash: isHash, + isFunction: isFunction, + isString: isString, + isNumber: isNumber, + isDate: isDate, + isUndefined: isUndefined, }); })(); -Object.extend(Function.prototype, (function() { - var slice = Array.prototype.slice; +Object.extend( + Function.prototype, + (function () { + var slice = Array.prototype.slice; + + function update(array, args) { + var arrayLength = array.length, + length = args.length; + while (length--) array[arrayLength + length] = args[length]; + return array; + } - function update(array, args) { - var arrayLength = array.length, length = args.length; - while (length--) array[arrayLength + length] = args[length]; - return array; - } + function merge(array, args) { + array = slice.call(array, 0); + return update(array, args); + } - function merge(array, args) { - array = slice.call(array, 0); - return update(array, args); - } + function argumentNames() { + var names = this.toString() + .match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] + .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, "") + .replace(/\s+/g, "") + .split(","); + return names.length == 1 && !names[0] ? [] : names; + } - function argumentNames() { - var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] - .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '') - .replace(/\s+/g, '').split(','); - return names.length == 1 && !names[0] ? [] : names; - } + function bind(context) { + if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; + var __method = this, + args = slice.call(arguments, 1); + return function () { + var a = merge(args, arguments); + return __method.apply(context, a); + }; + } - function bind(context) { - if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; - var __method = this, args = slice.call(arguments, 1); - return function() { - var a = merge(args, arguments); - return __method.apply(context, a); + function bindAsEventListener(context) { + var __method = this, + args = slice.call(arguments, 1); + return function (event) { + var a = update([event || window.event], args); + return __method.apply(context, a); + }; } - } - function bindAsEventListener(context) { - var __method = this, args = slice.call(arguments, 1); - return function(event) { - var a = update([event || window.event], args); - return __method.apply(context, a); + function curry() { + if (!arguments.length) return this; + var __method = this, + args = slice.call(arguments, 0); + return function () { + var a = merge(args, arguments); + return __method.apply(this, a); + }; } - } - function curry() { - if (!arguments.length) return this; - var __method = this, args = slice.call(arguments, 0); - return function() { - var a = merge(args, arguments); - return __method.apply(this, a); + function delay(timeout) { + var __method = this, + args = slice.call(arguments, 1); + timeout = timeout * 1000; + return window.setTimeout(function () { + return __method.apply(__method, args); + }, timeout); } - } - function delay(timeout) { - var __method = this, args = slice.call(arguments, 1); - timeout = timeout * 1000; - return window.setTimeout(function() { - return __method.apply(__method, args); - }, timeout); - } + function defer() { + var args = update([0.01], arguments); + return this.delay.apply(this, args); + } - function defer() { - var args = update([0.01], arguments); - return this.delay.apply(this, args); - } + function wrap(wrapper) { + var __method = this; + return function () { + var a = update([__method.bind(this)], arguments); + return wrapper.apply(this, a); + }; + } - function wrap(wrapper) { - var __method = this; - return function() { - var a = update([__method.bind(this)], arguments); - return wrapper.apply(this, a); + function methodize() { + if (this._methodized) return this._methodized; + var __method = this; + return (this._methodized = function () { + var a = update([this], arguments); + return __method.apply(null, a); + }); } - } - function methodize() { - if (this._methodized) return this._methodized; - var __method = this; - return this._methodized = function() { - var a = update([this], arguments); - return __method.apply(null, a); + return { + argumentNames: argumentNames, + bind: bind, + bindAsEventListener: bindAsEventListener, + curry: curry, + delay: delay, + defer: defer, + wrap: wrap, + methodize: methodize, }; - } - - return { - argumentNames: argumentNames, - bind: bind, - bindAsEventListener: bindAsEventListener, - curry: curry, - delay: delay, - defer: defer, - wrap: wrap, - methodize: methodize - } -})()); - - - -(function(proto) { - + })() +); +(function (proto) { function toISOString() { - return this.getUTCFullYear() + '-' + - (this.getUTCMonth() + 1).toPaddedString(2) + '-' + - this.getUTCDate().toPaddedString(2) + 'T' + - this.getUTCHours().toPaddedString(2) + ':' + - this.getUTCMinutes().toPaddedString(2) + ':' + - this.getUTCSeconds().toPaddedString(2) + 'Z'; + return ( + this.getUTCFullYear() + + "-" + + (this.getUTCMonth() + 1).toPaddedString(2) + + "-" + + this.getUTCDate().toPaddedString(2) + + "T" + + this.getUTCHours().toPaddedString(2) + + ":" + + this.getUTCMinutes().toPaddedString(2) + + ":" + + this.getUTCSeconds().toPaddedString(2) + + "Z" + ); } - function toJSON() { return this.toISOString(); } if (!proto.toISOString) proto.toISOString = toISOString; if (!proto.toJSON) proto.toJSON = toJSON; - })(Date.prototype); - RegExp.prototype.match = RegExp.prototype.test; -RegExp.escape = function(str) { - return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); +RegExp.escape = function (str) { + return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, "\\$1"); }; var PeriodicalExecuter = Class.create({ - initialize: function(callback, frequency) { + initialize: function (callback, frequency) { this.callback = callback; this.frequency = frequency; this.currentlyExecuting = false; @@ -469,338 +498,366 @@ var PeriodicalExecuter = Class.create({ this.registerCallback(); }, - registerCallback: function() { - this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + registerCallback: function () { + this.timer = setInterval( + this.onTimerEvent.bind(this), + this.frequency * 1000 + ); }, - execute: function() { + execute: function () { this.callback(this); }, - stop: function() { + stop: function () { if (!this.timer) return; clearInterval(this.timer); this.timer = null; }, - onTimerEvent: function() { + onTimerEvent: function () { if (!this.currentlyExecuting) { try { this.currentlyExecuting = true; this.execute(); this.currentlyExecuting = false; - } catch(e) { + } catch (e) { this.currentlyExecuting = false; throw e; } } - } + }, }); Object.extend(String, { - interpret: function(value) { - return value == null ? '' : String(value); + interpret: function (value) { + return value == null ? "" : String(value); }, specialChar: { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '\\': '\\\\' - } + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "\\": "\\\\", + }, }); -Object.extend(String.prototype, (function() { - var NATIVE_JSON_PARSE_SUPPORT = window.JSON && - typeof JSON.parse === 'function' && - JSON.parse('{"test": true}').test; - - function prepareReplacement(replacement) { - if (Object.isFunction(replacement)) return replacement; - var template = new Template(replacement); - return function(match) { return template.evaluate(match) }; - } +Object.extend( + String.prototype, + (function () { + var NATIVE_JSON_PARSE_SUPPORT = + window.JSON && + typeof JSON.parse === "function" && + JSON.parse('{"test": true}').test; + + function prepareReplacement(replacement) { + if (Object.isFunction(replacement)) return replacement; + var template = new Template(replacement); + return function (match) { + return template.evaluate(match); + }; + } - function gsub(pattern, replacement) { - var result = '', source = this, match; - replacement = prepareReplacement(replacement); + function gsub(pattern, replacement) { + var result = "", + source = this, + match; + replacement = prepareReplacement(replacement); - if (Object.isString(pattern)) - pattern = RegExp.escape(pattern); + if (Object.isString(pattern)) pattern = RegExp.escape(pattern); - if (!(pattern.length || pattern.source)) { - replacement = replacement(''); - return replacement + source.split('').join(replacement) + replacement; - } + if (!(pattern.length || pattern.source)) { + replacement = replacement(""); + return replacement + source.split("").join(replacement) + replacement; + } - while (source.length > 0) { - if (match = source.match(pattern)) { - result += source.slice(0, match.index); - result += String.interpret(replacement(match)); - source = source.slice(match.index + match[0].length); - } else { - result += source, source = ''; + while (source.length > 0) { + if ((match = source.match(pattern))) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + (result += source), (source = ""); + } } + return result; } - return result; - } - - function sub(pattern, replacement, count) { - replacement = prepareReplacement(replacement); - count = Object.isUndefined(count) ? 1 : count; - return this.gsub(pattern, function(match) { - if (--count < 0) return match[0]; - return replacement(match); - }); - } + function sub(pattern, replacement, count) { + replacement = prepareReplacement(replacement); + count = Object.isUndefined(count) ? 1 : count; - function scan(pattern, iterator) { - this.gsub(pattern, iterator); - return String(this); - } + return this.gsub(pattern, function (match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + } - function truncate(length, truncation) { - length = length || 30; - truncation = Object.isUndefined(truncation) ? '...' : truncation; - return this.length > length ? - this.slice(0, length - truncation.length) + truncation : String(this); - } + function scan(pattern, iterator) { + this.gsub(pattern, iterator); + return String(this); + } - function strip() { - return this.replace(/^\s+/, '').replace(/\s+$/, ''); - } + function truncate(length, truncation) { + length = length || 30; + truncation = Object.isUndefined(truncation) ? "..." : truncation; + return this.length > length + ? this.slice(0, length - truncation.length) + truncation + : String(this); + } - function stripTags() { - return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); - } + function strip() { + return this.replace(/^\s+/, "").replace(/\s+$/, ""); + } - function stripScripts() { - return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); - } + function stripTags() { + return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ""); + } - function extractScripts() { - var matchAll = new RegExp(Prototype.ScriptFragment, 'img'), - matchOne = new RegExp(Prototype.ScriptFragment, 'im'); - return (this.match(matchAll) || []).map(function(scriptTag) { - return (scriptTag.match(matchOne) || ['', ''])[1]; - }); - } + function stripScripts() { + return this.replace(new RegExp(Prototype.ScriptFragment, "img"), ""); + } - function evalScripts() { - return this.extractScripts().map(function(script) { return eval(script) }); - } + function extractScripts() { + var matchAll = new RegExp(Prototype.ScriptFragment, "img"), + matchOne = new RegExp(Prototype.ScriptFragment, "im"); + return (this.match(matchAll) || []).map(function (scriptTag) { + return (scriptTag.match(matchOne) || ["", ""])[1]; + }); + } - function escapeHTML() { - return this.replace(/&/g,'&').replace(//g,'>'); - } + function evalScripts() { + return this.extractScripts().map(function (script) { + return eval(script); + }); + } - function unescapeHTML() { - return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&'); - } + function escapeHTML() { + return this.replace(/&/g, "&") + .replace(//g, ">"); + } + function unescapeHTML() { + return this.stripTags() + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/&/g, "&"); + } - function toQueryParams(separator) { - var match = this.strip().match(/([^?#]*)(#.*)?$/); - if (!match) return { }; + function toQueryParams(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return {}; - return match[1].split(separator || '&').inject({ }, function(hash, pair) { - if ((pair = pair.split('='))[0]) { - var key = decodeURIComponent(pair.shift()), - value = pair.length > 1 ? pair.join('=') : pair[0]; + return match[1].split(separator || "&").inject({}, function (hash, pair) { + if ((pair = pair.split("="))[0]) { + var key = decodeURIComponent(pair.shift()), + value = pair.length > 1 ? pair.join("=") : pair[0]; - if (value != undefined) value = decodeURIComponent(value); + if (value != undefined) value = decodeURIComponent(value); - if (key in hash) { - if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; - hash[key].push(value); + if (key in hash) { + if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; + hash[key].push(value); + } else hash[key] = value; } - else hash[key] = value; - } - return hash; - }); - } - - function toArray() { - return this.split(''); - } + return hash; + }); + } - function succ() { - return this.slice(0, this.length - 1) + - String.fromCharCode(this.charCodeAt(this.length - 1) + 1); - } + function toArray() { + return this.split(""); + } - function times(count) { - return count < 1 ? '' : new Array(count + 1).join(this); - } + function succ() { + return ( + this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1) + ); + } - function camelize() { - return this.replace(/-+(.)?/g, function(match, chr) { - return chr ? chr.toUpperCase() : ''; - }); - } + function times(count) { + return count < 1 ? "" : new Array(count + 1).join(this); + } - function capitalize() { - return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); - } + function camelize() { + return this.replace(/-+(.)?/g, function (match, chr) { + return chr ? chr.toUpperCase() : ""; + }); + } - function underscore() { - return this.replace(/::/g, '/') - .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') - .replace(/([a-z\d])([A-Z])/g, '$1_$2') - .replace(/-/g, '_') - .toLowerCase(); - } + function capitalize() { + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + } - function dasherize() { - return this.replace(/_/g, '-'); - } + function underscore() { + return this.replace(/::/g, "/") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2") + .replace(/([a-z\d])([A-Z])/g, "$1_$2") + .replace(/-/g, "_") + .toLowerCase(); + } - function inspect(useDoubleQuotes) { - var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) { - if (character in String.specialChar) { - return String.specialChar[character]; - } - return '\\u00' + character.charCodeAt().toPaddedString(2, 16); - }); - if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; - return "'" + escapedString.replace(/'/g, '\\\'') + "'"; - } + function dasherize() { + return this.replace(/_/g, "-"); + } - function unfilterJSON(filter) { - return this.replace(filter || Prototype.JSONFilter, '$1'); - } + function inspect(useDoubleQuotes) { + var escapedString = this.replace(/[\x00-\x1f\\]/g, function (character) { + if (character in String.specialChar) { + return String.specialChar[character]; + } + return "\\u00" + character.charCodeAt().toPaddedString(2, 16); + }); + if (useDoubleQuotes) + return '"' + escapedString.replace(/"/g, '\\"') + '"'; + return "'" + escapedString.replace(/'/g, "\\'") + "'"; + } - function isJSON() { - var str = this; - if (str.blank()) return false; - str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); - str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); - str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); - return (/^[\],:{}\s]*$/).test(str); - } + function unfilterJSON(filter) { + return this.replace(filter || Prototype.JSONFilter, "$1"); + } - function evalJSON(sanitize) { - var json = this.unfilterJSON(), - cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - if (cx.test(json)) { - json = json.replace(cx, function (a) { - return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); + function isJSON() { + var str = this; + if (str.blank()) return false; + str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@"); + str = str.replace( + /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + "]" + ); + str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ""); + return /^[\],:{}\s]*$/.test(str); + } + + function evalJSON(sanitize) { + var json = this.unfilterJSON(), + cx = + /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; + if (cx.test(json)) { + json = json.replace(cx, function (a) { + return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + try { + if (!sanitize || json.isJSON()) return eval("(" + json + ")"); + } catch (e) {} + throw new SyntaxError("Badly formed JSON string: " + this.inspect()); } - try { - if (!sanitize || json.isJSON()) return eval('(' + json + ')'); - } catch (e) { } - throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); - } - function parseJSON() { - var json = this.unfilterJSON(); - return JSON.parse(json); - } + function parseJSON() { + var json = this.unfilterJSON(); + return JSON.parse(json); + } - function include(pattern) { - return this.indexOf(pattern) > -1; - } + function include(pattern) { + return this.indexOf(pattern) > -1; + } - function startsWith(pattern) { - return this.lastIndexOf(pattern, 0) === 0; - } + function startsWith(pattern) { + return this.lastIndexOf(pattern, 0) === 0; + } - function endsWith(pattern) { - var d = this.length - pattern.length; - return d >= 0 && this.indexOf(pattern, d) === d; - } + function endsWith(pattern) { + var d = this.length - pattern.length; + return d >= 0 && this.indexOf(pattern, d) === d; + } - function empty() { - return this == ''; - } + function empty() { + return this == ""; + } - function blank() { - return /^\s*$/.test(this); - } + function blank() { + return /^\s*$/.test(this); + } - function interpolate(object, pattern) { - return new Template(this, pattern).evaluate(object); - } + function interpolate(object, pattern) { + return new Template(this, pattern).evaluate(object); + } - return { - gsub: gsub, - sub: sub, - scan: scan, - truncate: truncate, - strip: String.prototype.trim || strip, - stripTags: stripTags, - stripScripts: stripScripts, - extractScripts: extractScripts, - evalScripts: evalScripts, - escapeHTML: escapeHTML, - unescapeHTML: unescapeHTML, - toQueryParams: toQueryParams, - parseQuery: toQueryParams, - toArray: toArray, - succ: succ, - times: times, - camelize: camelize, - capitalize: capitalize, - underscore: underscore, - dasherize: dasherize, - inspect: inspect, - unfilterJSON: unfilterJSON, - isJSON: isJSON, - evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON, - include: include, - startsWith: startsWith, - endsWith: endsWith, - empty: empty, - blank: blank, - interpolate: interpolate - }; -})()); + return { + gsub: gsub, + sub: sub, + scan: scan, + truncate: truncate, + strip: String.prototype.trim || strip, + stripTags: stripTags, + stripScripts: stripScripts, + extractScripts: extractScripts, + evalScripts: evalScripts, + escapeHTML: escapeHTML, + unescapeHTML: unescapeHTML, + toQueryParams: toQueryParams, + parseQuery: toQueryParams, + toArray: toArray, + succ: succ, + times: times, + camelize: camelize, + capitalize: capitalize, + underscore: underscore, + dasherize: dasherize, + inspect: inspect, + unfilterJSON: unfilterJSON, + isJSON: isJSON, + evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON, + include: include, + startsWith: startsWith, + endsWith: endsWith, + empty: empty, + blank: blank, + interpolate: interpolate, + }; + })() +); var Template = Class.create({ - initialize: function(template, pattern) { + initialize: function (template, pattern) { this.template = template.toString(); this.pattern = pattern || Template.Pattern; }, - evaluate: function(object) { + evaluate: function (object) { if (object && Object.isFunction(object.toTemplateReplacements)) object = object.toTemplateReplacements(); - return this.template.gsub(this.pattern, function(match) { - if (object == null) return (match[1] + ''); + return this.template.gsub(this.pattern, function (match) { + if (object == null) return match[1] + ""; - var before = match[1] || ''; - if (before == '\\') return match[2]; + var before = match[1] || ""; + if (before == "\\") return match[2]; - var ctx = object, expr = match[3], - pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; + var ctx = object, + expr = match[3], + pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; match = pattern.exec(expr); if (match == null) return before; while (match != null) { - var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1]; + var comp = match[1].startsWith("[") + ? match[2].replace(/\\\\]/g, "]") + : match[1]; ctx = ctx[comp]; - if (null == ctx || '' == match[3]) break; - expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); + if (null == ctx || "" == match[3]) break; + expr = expr.substring( + "[" == match[3] ? match[1].length : match[0].length + ); match = pattern.exec(expr); } return before + String.interpret(ctx); }); - } + }, }); Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; -var $break = { }; +var $break = {}; -var Enumerable = (function() { +var Enumerable = (function () { function each(iterator, context) { var index = 0; try { - this._each(function(value) { + this._each(function (value) { iterator.call(context, value, index++); }); } catch (e) { @@ -810,17 +867,19 @@ var Enumerable = (function() { } function eachSlice(number, iterator, context) { - var index = -number, slices = [], array = this.toArray(); + var index = -number, + slices = [], + array = this.toArray(); if (number < 1) return array; while ((index += number) < array.length) - slices.push(array.slice(index, index+number)); + slices.push(array.slice(index, index + number)); return slices.collect(iterator, context); } function all(iterator, context) { iterator = iterator || Prototype.K; var result = true; - this.each(function(value, index) { + this.each(function (value, index) { result = result && !!iterator.call(context, value, index); if (!result) throw $break; }); @@ -830,9 +889,8 @@ var Enumerable = (function() { function any(iterator, context) { iterator = iterator || Prototype.K; var result = false; - this.each(function(value, index) { - if (result = !!iterator.call(context, value, index)) - throw $break; + this.each(function (value, index) { + if ((result = !!iterator.call(context, value, index))) throw $break; }); return result; } @@ -840,7 +898,7 @@ var Enumerable = (function() { function collect(iterator, context) { iterator = iterator || Prototype.K; var results = []; - this.each(function(value, index) { + this.each(function (value, index) { results.push(iterator.call(context, value, index)); }); return results; @@ -848,7 +906,7 @@ var Enumerable = (function() { function detect(iterator, context) { var result; - this.each(function(value, index) { + this.each(function (value, index) { if (iterator.call(context, value, index)) { result = value; throw $break; @@ -859,9 +917,8 @@ var Enumerable = (function() { function findAll(iterator, context) { var results = []; - this.each(function(value, index) { - if (iterator.call(context, value, index)) - results.push(value); + this.each(function (value, index) { + if (iterator.call(context, value, index)) results.push(value); }); return results; } @@ -870,10 +927,9 @@ var Enumerable = (function() { iterator = iterator || Prototype.K; var results = []; - if (Object.isString(filter)) - filter = new RegExp(RegExp.escape(filter)); + if (Object.isString(filter)) filter = new RegExp(RegExp.escape(filter)); - this.each(function(value, index) { + this.each(function (value, index) { if (filter.match(value)) results.push(iterator.call(context, value, index)); }); @@ -885,7 +941,7 @@ var Enumerable = (function() { if (this.indexOf(object) != -1) return true; var found = false; - this.each(function(value) { + this.each(function (value) { if (value == object) { found = true; throw $break; @@ -896,14 +952,14 @@ var Enumerable = (function() { function inGroupsOf(number, fillWith) { fillWith = Object.isUndefined(fillWith) ? null : fillWith; - return this.eachSlice(number, function(slice) { - while(slice.length < number) slice.push(fillWith); + return this.eachSlice(number, function (slice) { + while (slice.length < number) slice.push(fillWith); return slice; }); } function inject(memo, iterator, context) { - this.each(function(value, index) { + this.each(function (value, index) { memo = iterator.call(context, memo, value, index); }); return memo; @@ -911,7 +967,7 @@ var Enumerable = (function() { function invoke(method) { var args = $A(arguments).slice(1); - return this.map(function(value) { + return this.map(function (value) { return value[method].apply(value, args); }); } @@ -919,10 +975,9 @@ var Enumerable = (function() { function max(iterator, context) { iterator = iterator || Prototype.K; var result; - this.each(function(value, index) { + this.each(function (value, index) { value = iterator.call(context, value, index); - if (result == null || value >= result) - result = value; + if (result == null || value >= result) result = value; }); return result; } @@ -930,27 +985,26 @@ var Enumerable = (function() { function min(iterator, context) { iterator = iterator || Prototype.K; var result; - this.each(function(value, index) { + this.each(function (value, index) { value = iterator.call(context, value, index); - if (result == null || value < result) - result = value; + if (result == null || value < result) result = value; }); return result; } function partition(iterator, context) { iterator = iterator || Prototype.K; - var trues = [], falses = []; - this.each(function(value, index) { - (iterator.call(context, value, index) ? - trues : falses).push(value); + var trues = [], + falses = []; + this.each(function (value, index) { + (iterator.call(context, value, index) ? trues : falses).push(value); }); return [trues, falses]; } function pluck(property) { var results = []; - this.each(function(value) { + this.each(function (value) { results.push(value[property]); }); return results; @@ -958,23 +1012,25 @@ var Enumerable = (function() { function reject(iterator, context) { var results = []; - this.each(function(value, index) { - if (!iterator.call(context, value, index)) - results.push(value); + this.each(function (value, index) { + if (!iterator.call(context, value, index)) results.push(value); }); return results; } function sortBy(iterator, context) { - return this.map(function(value, index) { + return this.map(function (value, index) { return { value: value, - criteria: iterator.call(context, value, index) + criteria: iterator.call(context, value, index), }; - }).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }).pluck('value'); + }) + .sort(function (left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }) + .pluck("value"); } function toArray() { @@ -982,12 +1038,12 @@ var Enumerable = (function() { } function zip() { - var iterator = Prototype.K, args = $A(arguments); - if (Object.isFunction(args.last())) - iterator = args.pop(); + var iterator = Prototype.K, + args = $A(arguments); + if (Object.isFunction(args.last())) iterator = args.pop(); var collections = [this].concat(args).map($A); - return this.map(function(value, index) { + return this.map(function (value, index) { return iterator(collections.pluck(index)); }); } @@ -997,60 +1053,52 @@ var Enumerable = (function() { } function inspect() { - return '#'; + return "#"; } - - - - - - - - return { - each: each, - eachSlice: eachSlice, - all: all, - every: all, - any: any, - some: any, - collect: collect, - map: collect, - detect: detect, - findAll: findAll, - select: findAll, - filter: findAll, - grep: grep, - include: include, - member: include, + each: each, + eachSlice: eachSlice, + all: all, + every: all, + any: any, + some: any, + collect: collect, + map: collect, + detect: detect, + findAll: findAll, + select: findAll, + filter: findAll, + grep: grep, + include: include, + member: include, inGroupsOf: inGroupsOf, - inject: inject, - invoke: invoke, - max: max, - min: min, - partition: partition, - pluck: pluck, - reject: reject, - sortBy: sortBy, - toArray: toArray, - entries: toArray, - zip: zip, - size: size, - inspect: inspect, - find: detect + inject: inject, + invoke: invoke, + max: max, + min: min, + partition: partition, + pluck: pluck, + reject: reject, + sortBy: sortBy, + toArray: toArray, + entries: toArray, + zip: zip, + size: size, + inspect: inspect, + find: detect, }; })(); function $A(iterable) { if (!iterable) return []; - if ('toArray' in Object(iterable)) return iterable.toArray(); - var length = iterable.length || 0, results = new Array(length); + if ("toArray" in Object(iterable)) return iterable.toArray(); + var length = iterable.length || 0, + results = new Array(length); while (length--) results[length] = iterable[length]; return results; } - function $w(string) { if (!Object.isString(string)) return []; string = string.strip(); @@ -1059,11 +1107,10 @@ function $w(string) { Array.from = $A; - -(function() { +(function () { var arrayProto = Array.prototype, - slice = arrayProto.slice, - _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available + slice = arrayProto.slice, + _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available function each(iterator, context) { for (var i = 0, length = this.length >>> 0; i < length; i++) { @@ -1086,15 +1133,14 @@ Array.from = $A; } function compact() { - return this.select(function(value) { + return this.select(function (value) { return value != null; }); } function flatten() { - return this.inject([], function(array, value) { - if (Object.isArray(value)) - return array.concat(value.flatten()); + return this.inject([], function (array, value) { + if (Object.isArray(value)) return array.concat(value.flatten()); array.push(value); return array; }); @@ -1102,7 +1148,7 @@ Array.from = $A; function without() { var values = slice.call(arguments, 0); - return this.select(function(value) { + return this.select(function (value) { return !values.include(value); }); } @@ -1112,20 +1158,24 @@ Array.from = $A; } function uniq(sorted) { - return this.inject([], function(array, value, index) { - if (0 == index || (sorted ? array.last() != value : !array.include(value))) + return this.inject([], function (array, value, index) { + if ( + 0 == index || + (sorted ? array.last() != value : !array.include(value)) + ) array.push(value); return array; }); } function intersect(array) { - return this.uniq().findAll(function(item) { - return array.detect(function(value) { return item === value }); + return this.uniq().findAll(function (item) { + return array.detect(function (value) { + return item === value; + }); }); } - function clone() { return slice.call(this, 0); } @@ -1135,29 +1185,29 @@ Array.from = $A; } function inspect() { - return '[' + this.map(Object.inspect).join(', ') + ']'; + return "[" + this.map(Object.inspect).join(", ") + "]"; } function indexOf(item, i) { i || (i = 0); var length = this.length; if (i < 0) i = length + i; - for (; i < length; i++) - if (this[i] === item) return i; + for (; i < length; i++) if (this[i] === item) return i; return -1; } function lastIndexOf(item, i) { i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; var n = this.slice(0, i).reverse().indexOf(item); - return (n < 0) ? n : i - n - 1; + return n < 0 ? n : i - n - 1; } function concat() { - var array = slice.call(this, 0), item; + var array = slice.call(this, 0), + item; for (var i = 0, length = arguments.length; i < length; i++) { item = arguments[i]; - if (Object.isArray(item) && !('callee' in item)) { + if (Object.isArray(item) && !("callee" in item)) { for (var j = 0, arrayLength = item.length; j < arrayLength; j++) array.push(item[j]); } else { @@ -1169,29 +1219,28 @@ Array.from = $A; Object.extend(arrayProto, Enumerable); - if (!arrayProto._reverse) - arrayProto._reverse = arrayProto.reverse; + if (!arrayProto._reverse) arrayProto._reverse = arrayProto.reverse; Object.extend(arrayProto, { - _each: _each, - clear: clear, - first: first, - last: last, - compact: compact, - flatten: flatten, - without: without, - reverse: reverse, - uniq: uniq, + _each: _each, + clear: clear, + first: first, + last: last, + compact: compact, + flatten: flatten, + without: without, + reverse: reverse, + uniq: uniq, intersect: intersect, - clone: clone, - toArray: clone, - size: size, - inspect: inspect + clone: clone, + toArray: clone, + size: size, + inspect: inspect, }); - var CONCAT_ARGUMENTS_BUGGY = (function() { + var CONCAT_ARGUMENTS_BUGGY = (function () { return [].concat(arguments)[0][0] !== 1; - })(1,2) + })(1, 2); if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat; @@ -1200,212 +1249,220 @@ Array.from = $A; })(); function $H(object) { return new Hash(object); -}; - -var Hash = Class.create(Enumerable, (function() { - function initialize(object) { - this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); - } - +} - function _each(iterator) { - for (var key in this._object) { - var value = this._object[key], pair = [key, value]; - pair.key = key; - pair.value = value; - iterator(pair); +var Hash = Class.create( + Enumerable, + (function () { + function initialize(object) { + this._object = Object.isHash(object) + ? object.toObject() + : Object.clone(object); + } + + function _each(iterator) { + for (var key in this._object) { + var value = this._object[key], + pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } } - } - - function set(key, value) { - return this._object[key] = value; - } - - function get(key) { - if (this._object[key] !== Object.prototype[key]) - return this._object[key]; - } - function unset(key) { - var value = this._object[key]; - delete this._object[key]; - return value; - } + function set(key, value) { + return (this._object[key] = value); + } - function toObject() { - return Object.clone(this._object); - } + function get(key) { + if (this._object[key] !== Object.prototype[key]) return this._object[key]; + } + function unset(key) { + var value = this._object[key]; + delete this._object[key]; + return value; + } + function toObject() { + return Object.clone(this._object); + } - function keys() { - return this.pluck('key'); - } + function keys() { + return this.pluck("key"); + } - function values() { - return this.pluck('value'); - } + function values() { + return this.pluck("value"); + } - function index(value) { - var match = this.detect(function(pair) { - return pair.value === value; - }); - return match && match.key; - } + function index(value) { + var match = this.detect(function (pair) { + return pair.value === value; + }); + return match && match.key; + } - function merge(object) { - return this.clone().update(object); - } + function merge(object) { + return this.clone().update(object); + } - function update(object) { - return new Hash(object).inject(this, function(result, pair) { - result.set(pair.key, pair.value); - return result; - }); - } + function update(object) { + return new Hash(object).inject(this, function (result, pair) { + result.set(pair.key, pair.value); + return result; + }); + } - function toQueryPair(key, value) { - if (Object.isUndefined(value)) return key; - return key + '=' + encodeURIComponent(String.interpret(value)); - } + function toQueryPair(key, value) { + if (Object.isUndefined(value)) return key; + return key + "=" + encodeURIComponent(String.interpret(value)); + } - function toQueryString() { - return this.inject([], function(results, pair) { - var key = encodeURIComponent(pair.key), values = pair.value; + function toQueryString() { + return this.inject([], function (results, pair) { + var key = encodeURIComponent(pair.key), + values = pair.value; - if (values && typeof values == 'object') { - if (Object.isArray(values)) { - var queryValues = []; - for (var i = 0, len = values.length, value; i < len; i++) { - value = values[i]; - queryValues.push(toQueryPair(key, value)); + if (values && typeof values == "object") { + if (Object.isArray(values)) { + var queryValues = []; + for (var i = 0, len = values.length, value; i < len; i++) { + value = values[i]; + queryValues.push(toQueryPair(key, value)); + } + return results.concat(queryValues); } - return results.concat(queryValues); - } - } else results.push(toQueryPair(key, values)); - return results; - }).join('&'); - } + } else results.push(toQueryPair(key, values)); + return results; + }).join("&"); + } - function inspect() { - return '#'; - } + function inspect() { + return ( + "#" + ); + } - function clone() { - return new Hash(this); - } + function clone() { + return new Hash(this); + } - return { - initialize: initialize, - _each: _each, - set: set, - get: get, - unset: unset, - toObject: toObject, - toTemplateReplacements: toObject, - keys: keys, - values: values, - index: index, - merge: merge, - update: update, - toQueryString: toQueryString, - inspect: inspect, - toJSON: toObject, - clone: clone - }; -})()); + return { + initialize: initialize, + _each: _each, + set: set, + get: get, + unset: unset, + toObject: toObject, + toTemplateReplacements: toObject, + keys: keys, + values: values, + index: index, + merge: merge, + update: update, + toQueryString: toQueryString, + inspect: inspect, + toJSON: toObject, + clone: clone, + }; + })() +); Hash.from = $H; -Object.extend(Number.prototype, (function() { - function toColorPart() { - return this.toPaddedString(2, 16); - } +Object.extend( + Number.prototype, + (function () { + function toColorPart() { + return this.toPaddedString(2, 16); + } - function succ() { - return this + 1; - } + function succ() { + return this + 1; + } - function times(iterator, context) { - $R(0, this, true).each(iterator, context); - return this; - } + function times(iterator, context) { + $R(0, this, true).each(iterator, context); + return this; + } - function toPaddedString(length, radix) { - var string = this.toString(radix || 10); - return '0'.times(length - string.length) + string; - } + function toPaddedString(length, radix) { + var string = this.toString(radix || 10); + return "0".times(length - string.length) + string; + } - function abs() { - return Math.abs(this); - } + function abs() { + return Math.abs(this); + } - function round() { - return Math.round(this); - } + function round() { + return Math.round(this); + } - function ceil() { - return Math.ceil(this); - } + function ceil() { + return Math.ceil(this); + } - function floor() { - return Math.floor(this); - } + function floor() { + return Math.floor(this); + } - return { - toColorPart: toColorPart, - succ: succ, - times: times, - toPaddedString: toPaddedString, - abs: abs, - round: round, - ceil: ceil, - floor: floor - }; -})()); + return { + toColorPart: toColorPart, + succ: succ, + times: times, + toPaddedString: toPaddedString, + abs: abs, + round: round, + ceil: ceil, + floor: floor, + }; + })() +); function $R(start, end, exclusive) { return new ObjectRange(start, end, exclusive); } -var ObjectRange = Class.create(Enumerable, (function() { - function initialize(start, end, exclusive) { - this.start = start; - this.end = end; - this.exclusive = exclusive; - } - - function _each(iterator) { - var value = this.start; - while (this.include(value)) { - iterator(value); - value = value.succ(); +var ObjectRange = Class.create( + Enumerable, + (function () { + function initialize(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; } - } - function include(value) { - if (value < this.start) - return false; - if (this.exclusive) - return value < this.end; - return value <= this.end; - } + function _each(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + } - return { - initialize: initialize, - _each: _each, - include: include - }; -})()); + function include(value) { + if (value < this.start) return false; + if (this.exclusive) return value < this.end; + return value <= this.end; + } + return { + initialize: initialize, + _each: _each, + include: include, + }; + })() +); - -var Abstract = { }; - +var Abstract = {}; var Try = { - these: function() { + these: function () { var returnValue; for (var i = 0, length = arguments.length; i < length; i++) { @@ -1413,100 +1470,111 @@ var Try = { try { returnValue = lambda(); break; - } catch (e) { } + } catch (e) {} } return returnValue; - } + }, }; var Ajax = { - getTransport: function() { - return Try.these( - function() {return new XMLHttpRequest()}, - function() {return new ActiveXObject('Msxml2.XMLHTTP')}, - function() {return new ActiveXObject('Microsoft.XMLHTTP')} - ) || false; + getTransport: function () { + return ( + Try.these( + function () { + return new XMLHttpRequest(); + }, + function () { + return new ActiveXObject("Msxml2.XMLHTTP"); + }, + function () { + return new ActiveXObject("Microsoft.XMLHTTP"); + } + ) || false + ); }, - activeRequestCount: 0 + activeRequestCount: 0, }; Ajax.Responders = { responders: [], - _each: function(iterator) { + _each: function (iterator) { this.responders._each(iterator); }, - register: function(responder) { - if (!this.include(responder)) - this.responders.push(responder); + register: function (responder) { + if (!this.include(responder)) this.responders.push(responder); }, - unregister: function(responder) { + unregister: function (responder) { this.responders = this.responders.without(responder); }, - dispatch: function(callback, request, transport, json) { - this.each(function(responder) { + dispatch: function (callback, request, transport, json) { + this.each(function (responder) { if (Object.isFunction(responder[callback])) { try { responder[callback].apply(responder, [request, transport, json]); - } catch (e) { } + } catch (e) {} } }); - } + }, }; Object.extend(Ajax.Responders, Enumerable); Ajax.Responders.register({ - onCreate: function() { Ajax.activeRequestCount++ }, - onComplete: function() { Ajax.activeRequestCount-- } + onCreate: function () { + Ajax.activeRequestCount++; + }, + onComplete: function () { + Ajax.activeRequestCount--; + }, }); Ajax.Base = Class.create({ - initialize: function(options) { + initialize: function (options) { this.options = { - method: 'post', + method: "post", asynchronous: true, - contentType: 'application/x-www-form-urlencoded', - encoding: 'UTF-8', - parameters: '', - evalJSON: true, - evalJS: true + contentType: "application/x-www-form-urlencoded", + encoding: "UTF-8", + parameters: "", + evalJSON: true, + evalJS: true, }; - Object.extend(this.options, options || { }); + Object.extend(this.options, options || {}); this.options.method = this.options.method.toLowerCase(); if (Object.isHash(this.options.parameters)) this.options.parameters = this.options.parameters.toObject(); - } + }, }); Ajax.Request = Class.create(Ajax.Base, { _complete: false, - initialize: function($super, url, options) { + initialize: function ($super, url, options) { $super(options); this.transport = Ajax.getTransport(); this.request(url); }, - request: function(url) { + request: function (url) { this.url = url; this.method = this.options.method; - var params = Object.isString(this.options.parameters) ? - this.options.parameters : - Object.toQueryString(this.options.parameters); + var params = Object.isString(this.options.parameters) + ? this.options.parameters + : Object.toQueryString(this.options.parameters); - if (!['get', 'post'].include(this.method)) { - params += (params ? '&' : '') + "_method=" + this.method; - this.method = 'post'; + if (!["get", "post"].include(this.method)) { + params += (params ? "&" : "") + "_method=" + this.method; + this.method = "post"; } - if (params && this.method === 'get') { - this.url += (this.url.include('?') ? '&' : '?') + params; + if (params && this.method === "get") { + this.url += (this.url.include("?") ? "&" : "?") + params; } this.parameters = params.toQueryParams(); @@ -1514,321 +1582,367 @@ Ajax.Request = Class.create(Ajax.Base, { try { var response = new Ajax.Response(this); if (this.options.onCreate) this.options.onCreate(response); - Ajax.Responders.dispatch('onCreate', this, response); + Ajax.Responders.dispatch("onCreate", this, response); - this.transport.open(this.method.toUpperCase(), this.url, - this.options.asynchronous); + this.transport.open( + this.method.toUpperCase(), + this.url, + this.options.asynchronous + ); - if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); + if (this.options.asynchronous) + this.respondToReadyState.bind(this).defer(1); this.transport.onreadystatechange = this.onStateChange.bind(this); this.setRequestHeaders(); - this.body = this.method == 'post' ? (this.options.postBody || params) : null; + this.body = + this.method == "post" ? this.options.postBody || params : null; this.transport.send(this.body); /* Force Firefox to handle ready state 4 for synchronous requests */ if (!this.options.asynchronous && this.transport.overrideMimeType) this.onStateChange(); - - } - catch (e) { + } catch (e) { this.dispatchException(e); } }, - onStateChange: function() { + onStateChange: function () { var readyState = this.transport.readyState; - if (readyState > 1 && !((readyState == 4) && this._complete)) + if (readyState > 1 && !(readyState == 4 && this._complete)) this.respondToReadyState(this.transport.readyState); }, - setRequestHeaders: function() { + setRequestHeaders: function () { var headers = { - 'X-Requested-With': 'XMLHttpRequest', - 'X-Prototype-Version': Prototype.Version, - 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + "X-Requested-With": "XMLHttpRequest", + "X-Prototype-Version": Prototype.Version, + Accept: "text/javascript, text/html, application/xml, text/xml, */*", }; - if (this.method == 'post') { - headers['Content-type'] = this.options.contentType + - (this.options.encoding ? '; charset=' + this.options.encoding : ''); + if (this.method == "post") { + headers["Content-type"] = + this.options.contentType + + (this.options.encoding ? "; charset=" + this.options.encoding : ""); /* Force "Connection: close" for older Mozilla browsers to work * around a bug where XMLHttpRequest sends an incorrect * Content-length header. See Mozilla Bugzilla #246651. */ - if (this.transport.overrideMimeType && - (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) - headers['Connection'] = 'close'; + if ( + this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0, 2005])[1] < 2005 + ) + headers["Connection"] = "close"; } - if (typeof this.options.requestHeaders == 'object') { + if (typeof this.options.requestHeaders == "object") { var extras = this.options.requestHeaders; if (Object.isFunction(extras.push)) for (var i = 0, length = extras.length; i < length; i += 2) - headers[extras[i]] = extras[i+1]; + headers[extras[i]] = extras[i + 1]; else - $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + $H(extras).each(function (pair) { + headers[pair.key] = pair.value; + }); } for (var name in headers) this.transport.setRequestHeader(name, headers[name]); }, - success: function() { + success: function () { var status = this.getStatus(); return !status || (status >= 200 && status < 300) || status == 304; }, - getStatus: function() { + getStatus: function () { try { if (this.transport.status === 1223) return 204; return this.transport.status || 0; - } catch (e) { return 0 } + } catch (e) { + return 0; + } }, - respondToReadyState: function(readyState) { - var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); + respondToReadyState: function (readyState) { + var state = Ajax.Request.Events[readyState], + response = new Ajax.Response(this); - if (state == 'Complete') { + if (state == "Complete") { try { this._complete = true; - (this.options['on' + response.status] - || this.options['on' + (this.success() ? 'Success' : 'Failure')] - || Prototype.emptyFunction)(response, response.headerJSON); + ( + this.options["on" + response.status] || + this.options["on" + (this.success() ? "Success" : "Failure")] || + Prototype.emptyFunction + )(response, response.headerJSON); } catch (e) { this.dispatchException(e); } - var contentType = response.getHeader('Content-type'); - if (this.options.evalJS == 'force' - || (this.options.evalJS && this.isSameOrigin() && contentType - && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) + var contentType = response.getHeader("Content-type"); + if ( + this.options.evalJS == "force" || + (this.options.evalJS && + this.isSameOrigin() && + contentType && + contentType.match( + /^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i + )) + ) this.evalResponse(); } try { - (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); - Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); + (this.options["on" + state] || Prototype.emptyFunction)( + response, + response.headerJSON + ); + Ajax.Responders.dispatch( + "on" + state, + this, + response, + response.headerJSON + ); } catch (e) { this.dispatchException(e); } - if (state == 'Complete') { + if (state == "Complete") { this.transport.onreadystatechange = Prototype.emptyFunction; } }, - isSameOrigin: function() { + isSameOrigin: function () { var m = this.url.match(/^\s*https?:\/\/[^\/]*/); - return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({ - protocol: location.protocol, - domain: document.domain, - port: location.port ? ':' + location.port : '' - })); + return ( + !m || + m[0] == + "#{protocol}//#{domain}#{port}".interpolate({ + protocol: location.protocol, + domain: document.domain, + port: location.port ? ":" + location.port : "", + }) + ); }, - getHeader: function(name) { + getHeader: function (name) { try { return this.transport.getResponseHeader(name) || null; - } catch (e) { return null; } + } catch (e) { + return null; + } }, - evalResponse: function() { + evalResponse: function () { try { - return eval((this.transport.responseText || '').unfilterJSON()); + return eval((this.transport.responseText || "").unfilterJSON()); } catch (e) { this.dispatchException(e); } }, - dispatchException: function(exception) { + dispatchException: function (exception) { (this.options.onException || Prototype.emptyFunction)(this, exception); - Ajax.Responders.dispatch('onException', this, exception); - } + Ajax.Responders.dispatch("onException", this, exception); + }, }); -Ajax.Request.Events = - ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; - - - - - - - +Ajax.Request.Events = [ + "Uninitialized", + "Loading", + "Loaded", + "Interactive", + "Complete", +]; Ajax.Response = Class.create({ - initialize: function(request){ + initialize: function (request) { this.request = request; - var transport = this.transport = request.transport, - readyState = this.readyState = transport.readyState; + var transport = (this.transport = request.transport), + readyState = (this.readyState = transport.readyState); if ((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { - this.status = this.getStatus(); - this.statusText = this.getStatusText(); + this.status = this.getStatus(); + this.statusText = this.getStatusText(); this.responseText = String.interpret(transport.responseText); - this.headerJSON = this._getHeaderJSON(); + this.headerJSON = this._getHeaderJSON(); } if (readyState == 4) { var xml = transport.responseXML; - this.responseXML = Object.isUndefined(xml) ? null : xml; + this.responseXML = Object.isUndefined(xml) ? null : xml; this.responseJSON = this._getResponseJSON(); } }, - status: 0, + status: 0, - statusText: '', + statusText: "", getStatus: Ajax.Request.prototype.getStatus, - getStatusText: function() { + getStatusText: function () { try { - return this.transport.statusText || ''; - } catch (e) { return '' } + return this.transport.statusText || ""; + } catch (e) { + return ""; + } }, getHeader: Ajax.Request.prototype.getHeader, - getAllHeaders: function() { + getAllHeaders: function () { try { return this.getAllResponseHeaders(); - } catch (e) { return null } + } catch (e) { + return null; + } }, - getResponseHeader: function(name) { + getResponseHeader: function (name) { return this.transport.getResponseHeader(name); }, - getAllResponseHeaders: function() { + getAllResponseHeaders: function () { return this.transport.getAllResponseHeaders(); }, - _getHeaderJSON: function() { - var json = this.getHeader('X-JSON'); + _getHeaderJSON: function () { + var json = this.getHeader("X-JSON"); if (!json) return null; json = decodeURIComponent(escape(json)); try { - return json.evalJSON(this.request.options.sanitizeJSON || - !this.request.isSameOrigin()); + return json.evalJSON( + this.request.options.sanitizeJSON || !this.request.isSameOrigin() + ); } catch (e) { this.request.dispatchException(e); } }, - _getResponseJSON: function() { + _getResponseJSON: function () { var options = this.request.options; - if (!options.evalJSON || (options.evalJSON != 'force' && - !(this.getHeader('Content-type') || '').include('application/json')) || - this.responseText.blank()) - return null; + if ( + !options.evalJSON || + (options.evalJSON != "force" && + !(this.getHeader("Content-type") || "").include("application/json")) || + this.responseText.blank() + ) + return null; try { - return this.responseText.evalJSON(options.sanitizeJSON || - !this.request.isSameOrigin()); + return this.responseText.evalJSON( + options.sanitizeJSON || !this.request.isSameOrigin() + ); } catch (e) { this.request.dispatchException(e); } - } + }, }); Ajax.Updater = Class.create(Ajax.Request, { - initialize: function($super, container, url, options) { + initialize: function ($super, container, url, options) { this.container = { - success: (container.success || container), - failure: (container.failure || (container.success ? null : container)) + success: container.success || container, + failure: container.failure || (container.success ? null : container), }; options = Object.clone(options); var onComplete = options.onComplete; - options.onComplete = (function(response, json) { + options.onComplete = function (response, json) { this.updateContent(response.responseText); if (Object.isFunction(onComplete)) onComplete(response, json); - }).bind(this); + }.bind(this); $super(url, options); }, - updateContent: function(responseText) { - var receiver = this.container[this.success() ? 'success' : 'failure'], - options = this.options; + updateContent: function (responseText) { + var receiver = this.container[this.success() ? "success" : "failure"], + options = this.options; if (!options.evalScripts) responseText = responseText.stripScripts(); - if (receiver = $(receiver)) { + if ((receiver = $(receiver))) { if (options.insertion) { if (Object.isString(options.insertion)) { - var insertion = { }; insertion[options.insertion] = responseText; + var insertion = {}; + insertion[options.insertion] = responseText; receiver.insert(insertion); - } - else options.insertion(receiver, responseText); - } - else receiver.update(responseText); + } else options.insertion(receiver, responseText); + } else receiver.update(responseText); } - } + }, }); Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { - initialize: function($super, container, url, options) { + initialize: function ($super, container, url, options) { $super(options); this.onComplete = this.options.onComplete; - this.frequency = (this.options.frequency || 2); - this.decay = (this.options.decay || 1); + this.frequency = this.options.frequency || 2; + this.decay = this.options.decay || 1; - this.updater = { }; + this.updater = {}; this.container = container; this.url = url; this.start(); }, - start: function() { + start: function () { this.options.onComplete = this.updateComplete.bind(this); this.onTimerEvent(); }, - stop: function() { + stop: function () { this.updater.options.onComplete = undefined; clearTimeout(this.timer); (this.onComplete || Prototype.emptyFunction).apply(this, arguments); }, - updateComplete: function(response) { + updateComplete: function (response) { if (this.options.decay) { - this.decay = (response.responseText == this.lastText ? - this.decay * this.options.decay : 1); + this.decay = + response.responseText == this.lastText + ? this.decay * this.options.decay + : 1; this.lastText = response.responseText; } - this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); + this.timer = this.onTimerEvent + .bind(this) + .delay(this.decay * this.frequency); }, - onTimerEvent: function() { + onTimerEvent: function () { this.updater = new Ajax.Updater(this.container, this.url, this.options); - } + }, }); - function $(element) { if (arguments.length > 1) { for (var i = 0, elements = [], length = arguments.length; i < length; i++) elements.push($(arguments[i])); return elements; } - if (Object.isString(element)) - element = document.getElementById(element); + if (Object.isString(element)) element = document.getElementById(element); return Element.extend(element); } if (Prototype.BrowserFeatures.XPath) { - document._getElementsByXPath = function(expression, parentElement) { + document._getElementsByXPath = function (expression, parentElement) { var results = []; - var query = document.evaluate(expression, $(parentElement) || document, - null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + var query = document.evaluate( + expression, + $(parentElement) || document, + null, + XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, + null + ); for (var i = 0, length = query.snapshotLength; i < length; i++) results.push(Element.extend(query.snapshotItem(i))); return results; @@ -1837,7 +1951,7 @@ if (Prototype.BrowserFeatures.XPath) { /*--------------------------------------------------------------------------*/ -if (!Node) var Node = { }; +if (!Node) var Node = {}; if (!Node.ELEMENT_NODE) { Object.extend(Node, { @@ -1852,102 +1966,102 @@ if (!Node.ELEMENT_NODE) { DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, - NOTATION_NODE: 12 + NOTATION_NODE: 12, }); } - - -(function(global) { +(function (global) { function shouldUseCache(tagName, attributes) { - if (tagName === 'select') return false; - if ('type' in attributes) return false; + if (tagName === "select") return false; + if ("type" in attributes) return false; return true; } - var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){ + var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function () { try { var el = document.createElement(''); - return el.tagName.toLowerCase() === 'input' && el.name === 'x'; - } - catch(err) { + return el.tagName.toLowerCase() === "input" && el.name === "x"; + } catch (err) { return false; } })(); var element = global.Element; - global.Element = function(tagName, attributes) { - attributes = attributes || { }; + global.Element = function (tagName, attributes) { + attributes = attributes || {}; tagName = tagName.toLowerCase(); var cache = Element.cache; if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) { - tagName = '<' + tagName + ' name="' + attributes.name + '">'; + tagName = "<" + tagName + ' name="' + attributes.name + '">'; delete attributes.name; - return Element.writeAttribute(document.createElement(tagName), attributes); + return Element.writeAttribute( + document.createElement(tagName), + attributes + ); } - if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); + if (!cache[tagName]) + cache[tagName] = Element.extend(document.createElement(tagName)); - var node = shouldUseCache(tagName, attributes) ? - cache[tagName].cloneNode(false) : document.createElement(tagName); + var node = shouldUseCache(tagName, attributes) + ? cache[tagName].cloneNode(false) + : document.createElement(tagName); return Element.writeAttribute(node, attributes); }; - Object.extend(global.Element, element || { }); + Object.extend(global.Element, element || {}); if (element) global.Element.prototype = element.prototype; - })(this); Element.idCounter = 1; -Element.cache = { }; +Element.cache = {}; -Element._purgeElement = function(element) { +Element._purgeElement = function (element) { var uid = element._prototypeUID; if (uid) { Element.stopObserving(element); element._prototypeUID = void 0; delete Element.Storage[uid]; } -} +}; Element.Methods = { - visible: function(element) { - return $(element).style.display != 'none'; + visible: function (element) { + return $(element).style.display != "none"; }, - toggle: function(element) { + toggle: function (element) { element = $(element); - Element[Element.visible(element) ? 'hide' : 'show'](element); + Element[Element.visible(element) ? "hide" : "show"](element); return element; }, - hide: function(element) { + hide: function (element) { element = $(element); - element.style.display = 'none'; + element.style.display = "none"; return element; }, - show: function(element) { + show: function (element) { element = $(element); - element.style.display = ''; + element.style.display = ""; return element; }, - remove: function(element) { + remove: function (element) { element = $(element); element.parentNode.removeChild(element); return element; }, - update: (function(){ - - var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){ + update: (function () { + var SELECT_ELEMENT_INNERHTML_BUGGY = (function () { var el = document.createElement("select"), - isBuggy = true; - el.innerHTML = ""; + isBuggy = true; + el.innerHTML = ''; if (el.options && el.options[0]) { isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION"; } @@ -1955,7 +2069,7 @@ Element.Methods = { return isBuggy; })(); - var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){ + var TABLE_ELEMENT_INNERHTML_BUGGY = (function () { try { var el = document.createElement("table"); if (el && el.tBodies) { @@ -1969,28 +2083,30 @@ Element.Methods = { } })(); - var LINK_ELEMENT_INNERHTML_BUGGY = (function() { + var LINK_ELEMENT_INNERHTML_BUGGY = (function () { try { - var el = document.createElement('div'); + var el = document.createElement("div"); el.innerHTML = ""; - var isBuggy = (el.childNodes.length === 0); + var isBuggy = el.childNodes.length === 0; el = null; return isBuggy; - } catch(e) { + } catch (e) { return true; } })(); - var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY || - TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY; + var ANY_INNERHTML_BUGGY = + SELECT_ELEMENT_INNERHTML_BUGGY || + TABLE_ELEMENT_INNERHTML_BUGGY || + LINK_ELEMENT_INNERHTML_BUGGY; var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () { var s = document.createElement("script"), - isBuggy = false; + isBuggy = false; try { s.appendChild(document.createTextNode("")); - isBuggy = !s.firstChild || - s.firstChild && s.firstChild.nodeType !== 3; + isBuggy = + !s.firstChild || (s.firstChild && s.firstChild.nodeType !== 3); } catch (e) { isBuggy = true; } @@ -1998,26 +2114,23 @@ Element.Methods = { return isBuggy; })(); - function update(element, content) { element = $(element); var purgeElement = Element._purgeElement; - var descendants = element.getElementsByTagName('*'), - i = descendants.length; + var descendants = element.getElementsByTagName("*"), + i = descendants.length; while (i--) purgeElement(descendants[i]); - if (content && content.toElement) - content = content.toElement(); + if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) - return element.update().insert(content); + if (Object.isElement(content)) return element.update().insert(content); content = Object.toHTML(content); var tagName = element.tagName.toUpperCase(); - if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) { + if (tagName === "SCRIPT" && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) { element.text = content; return element; } @@ -2027,22 +2140,32 @@ Element.Methods = { while (element.firstChild) { element.removeChild(element.firstChild); } - Element._getContentFromAnonymousElement(tagName, content.stripScripts()) - .each(function(node) { - element.appendChild(node) - }); - } else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf(' -1) { + Element._getContentFromAnonymousElement( + tagName, + content.stripScripts() + ).each(function (node) { + element.appendChild(node); + }); + } else if ( + LINK_ELEMENT_INNERHTML_BUGGY && + Object.isString(content) && + content.indexOf(" -1 + ) { while (element.firstChild) { element.removeChild(element.firstChild); } - var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true); - nodes.each(function(node) { element.appendChild(node) }); - } - else { + var nodes = Element._getContentFromAnonymousElement( + tagName, + content.stripScripts(), + true + ); + nodes.each(function (node) { + element.appendChild(node); + }); + } else { element.innerHTML = content.stripScripts(); } - } - else { + } else { element.innerHTML = content.stripScripts(); } @@ -2053,7 +2176,7 @@ Element.Methods = { return update; })(), - replace: function(element, content) { + replace: function (element, content) { element = $(element); if (content && content.toElement) content = content.toElement(); else if (!Object.isElement(content)) { @@ -2067,17 +2190,21 @@ Element.Methods = { return element; }, - insert: function(element, insertions) { + insert: function (element, insertions) { element = $(element); - if (Object.isString(insertions) || Object.isNumber(insertions) || - Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) - insertions = {bottom:insertions}; + if ( + Object.isString(insertions) || + Object.isNumber(insertions) || + Object.isElement(insertions) || + (insertions && (insertions.toElement || insertions.toHTML)) + ) + insertions = { bottom: insertions }; var content, insert, tagName, childNodes; for (var position in insertions) { - content = insertions[position]; + content = insertions[position]; position = position.toLowerCase(); insert = Element._insertionTranslations[position]; @@ -2089,12 +2216,18 @@ Element.Methods = { content = Object.toHTML(content); - tagName = ((position == 'before' || position == 'after') - ? element.parentNode : element).tagName.toUpperCase(); + tagName = ( + position == "before" || position == "after" + ? element.parentNode + : element + ).tagName.toUpperCase(); - childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + childNodes = Element._getContentFromAnonymousElement( + tagName, + content.stripScripts() + ); - if (position == 'top' || position == 'after') childNodes.reverse(); + if (position == "top" || position == "after") childNodes.reverse(); childNodes.each(insert.curry(element)); content.evalScripts.bind(content).defer(); @@ -2103,61 +2236,59 @@ Element.Methods = { return element; }, - wrap: function(element, wrapper, attributes) { + wrap: function (element, wrapper, attributes) { element = $(element); - if (Object.isElement(wrapper)) - $(wrapper).writeAttribute(attributes || { }); - else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes); - else wrapper = new Element('div', wrapper); - if (element.parentNode) - element.parentNode.replaceChild(wrapper, element); + if (Object.isElement(wrapper)) $(wrapper).writeAttribute(attributes || {}); + else if (Object.isString(wrapper)) + wrapper = new Element(wrapper, attributes); + else wrapper = new Element("div", wrapper); + if (element.parentNode) element.parentNode.replaceChild(wrapper, element); wrapper.appendChild(element); return wrapper; }, - inspect: function(element) { + inspect: function (element) { element = $(element); - var result = '<' + element.tagName.toLowerCase(); - $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var result = "<" + element.tagName.toLowerCase(); + $H({ id: "id", className: "class" }).each(function (pair) { var property = pair.first(), - attribute = pair.last(), - value = (element[property] || '').toString(); - if (value) result += ' ' + attribute + '=' + value.inspect(true); + attribute = pair.last(), + value = (element[property] || "").toString(); + if (value) result += " " + attribute + "=" + value.inspect(true); }); - return result + '>'; + return result + ">"; }, - recursivelyCollect: function(element, property, maximumLength) { + recursivelyCollect: function (element, property, maximumLength) { element = $(element); maximumLength = maximumLength || -1; var elements = []; - while (element = element[property]) { - if (element.nodeType == 1) - elements.push(Element.extend(element)); - if (elements.length == maximumLength) - break; + while ((element = element[property])) { + if (element.nodeType == 1) elements.push(Element.extend(element)); + if (elements.length == maximumLength) break; } return elements; }, - ancestors: function(element) { - return Element.recursivelyCollect(element, 'parentNode'); + ancestors: function (element) { + return Element.recursivelyCollect(element, "parentNode"); }, - descendants: function(element) { + descendants: function (element) { return Element.select(element, "*"); }, - firstDescendant: function(element) { + firstDescendant: function (element) { element = $(element).firstChild; while (element && element.nodeType != 1) element = element.nextSibling; return $(element); }, - immediateDescendants: function(element) { - var results = [], child = $(element).firstChild; + immediateDescendants: function (element) { + var results = [], + child = $(element).firstChild; while (child) { if (child.nodeType === 1) { results.push(Element.extend(child)); @@ -2167,57 +2298,64 @@ Element.Methods = { return results; }, - previousSiblings: function(element, maximumLength) { - return Element.recursivelyCollect(element, 'previousSibling'); + previousSiblings: function (element, maximumLength) { + return Element.recursivelyCollect(element, "previousSibling"); }, - nextSiblings: function(element) { - return Element.recursivelyCollect(element, 'nextSibling'); + nextSiblings: function (element) { + return Element.recursivelyCollect(element, "nextSibling"); }, - siblings: function(element) { + siblings: function (element) { element = $(element); - return Element.previousSiblings(element).reverse() + return Element.previousSiblings(element) + .reverse() .concat(Element.nextSiblings(element)); }, - match: function(element, selector) { + match: function (element, selector) { element = $(element); if (Object.isString(selector)) return Prototype.Selector.match(element, selector); return selector.match(element); }, - up: function(element, expression, index) { + up: function (element, expression, index) { element = $(element); if (arguments.length == 1) return $(element.parentNode); var ancestors = Element.ancestors(element); - return Object.isNumber(expression) ? ancestors[expression] : - Prototype.Selector.find(ancestors, expression, index); + return Object.isNumber(expression) + ? ancestors[expression] + : Prototype.Selector.find(ancestors, expression, index); }, - down: function(element, expression, index) { + down: function (element, expression, index) { element = $(element); if (arguments.length == 1) return Element.firstDescendant(element); - return Object.isNumber(expression) ? Element.descendants(element)[expression] : - Element.select(element, expression)[index || 0]; + return Object.isNumber(expression) + ? Element.descendants(element)[expression] + : Element.select(element, expression)[index || 0]; }, - previous: function(element, expression, index) { + previous: function (element, expression, index) { element = $(element); - if (Object.isNumber(expression)) index = expression, expression = false; + if (Object.isNumber(expression)) (index = expression), (expression = false); if (!Object.isNumber(index)) index = 0; if (expression) { - return Prototype.Selector.find(element.previousSiblings(), expression, index); + return Prototype.Selector.find( + element.previousSiblings(), + expression, + index + ); } else { return element.recursivelyCollect("previousSibling", index + 1)[index]; } }, - next: function(element, expression, index) { + next: function (element, expression, index) { element = $(element); - if (Object.isNumber(expression)) index = expression, expression = false; + if (Object.isNumber(expression)) (index = expression), (expression = false); if (!Object.isNumber(index)) index = 0; if (expression) { @@ -2228,102 +2366,112 @@ Element.Methods = { } }, - - select: function(element) { + select: function (element) { element = $(element); - var expressions = Array.prototype.slice.call(arguments, 1).join(', '); + var expressions = Array.prototype.slice.call(arguments, 1).join(", "); return Prototype.Selector.select(expressions, element); }, - adjacent: function(element) { + adjacent: function (element) { element = $(element); - var expressions = Array.prototype.slice.call(arguments, 1).join(', '); - return Prototype.Selector.select(expressions, element.parentNode).without(element); + var expressions = Array.prototype.slice.call(arguments, 1).join(", "); + return Prototype.Selector.select(expressions, element.parentNode).without( + element + ); }, - identify: function(element) { + identify: function (element) { element = $(element); - var id = Element.readAttribute(element, 'id'); + var id = Element.readAttribute(element, "id"); if (id) return id; - do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id)); - Element.writeAttribute(element, 'id', id); + do { + id = "anonymous_element_" + Element.idCounter++; + } while ($(id)); + Element.writeAttribute(element, "id", id); return id; }, - readAttribute: function(element, name) { + readAttribute: function (element, name) { element = $(element); if (Prototype.Browser.IE) { var t = Element._attributeTranslations.read; if (t.values[name]) return t.values[name](element, name); if (t.names[name]) name = t.names[name]; - if (name.include(':')) { - return (!element.attributes || !element.attributes[name]) ? null : - element.attributes[name].value; + if (name.include(":")) { + return !element.attributes || !element.attributes[name] + ? null + : element.attributes[name].value; } } return element.getAttribute(name); }, - writeAttribute: function(element, name, value) { + writeAttribute: function (element, name, value) { element = $(element); - var attributes = { }, t = Element._attributeTranslations.write; + var attributes = {}, + t = Element._attributeTranslations.write; - if (typeof name == 'object') attributes = name; + if (typeof name == "object") attributes = name; else attributes[name] = Object.isUndefined(value) ? true : value; for (var attr in attributes) { name = t.names[attr] || attr; value = attributes[attr]; if (t.values[attr]) name = t.values[attr](element, value); - if (value === false || value === null) - element.removeAttribute(name); - else if (value === true) - element.setAttribute(name, name); + if (value === false || value === null) element.removeAttribute(name); + else if (value === true) element.setAttribute(name, name); else element.setAttribute(name, value); } return element; }, - getHeight: function(element) { + getHeight: function (element) { return Element.getDimensions(element).height; }, - getWidth: function(element) { + getWidth: function (element) { return Element.getDimensions(element).width; }, - classNames: function(element) { + classNames: function (element) { return new Element.ClassNames(element); }, - hasClassName: function(element, className) { + hasClassName: function (element, className) { if (!(element = $(element))) return; var elementClassName = element.className; - return (elementClassName.length > 0 && (elementClassName == className || - new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); + return ( + elementClassName.length > 0 && + (elementClassName == className || + new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)) + ); }, - addClassName: function(element, className) { + addClassName: function (element, className) { if (!(element = $(element))) return; if (!Element.hasClassName(element, className)) - element.className += (element.className ? ' ' : '') + className; + element.className += (element.className ? " " : "") + className; return element; }, - removeClassName: function(element, className) { + removeClassName: function (element, className) { if (!(element = $(element))) return; - element.className = element.className.replace( - new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip(); + element.className = element.className + .replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " ") + .strip(); return element; }, - toggleClassName: function(element, className) { + toggleClassName: function (element, className) { if (!(element = $(element))) return; - return Element[Element.hasClassName(element, className) ? - 'removeClassName' : 'addClassName'](element, className); + return Element[ + Element.hasClassName(element, className) + ? "removeClassName" + : "addClassName" + ](element, className); }, - cleanWhitespace: function(element) { + cleanWhitespace: function (element) { element = $(element); var node = element.firstChild; while (node) { @@ -2335,12 +2483,12 @@ Element.Methods = { return element; }, - empty: function(element) { + empty: function (element) { return $(element).innerHTML.blank(); }, - descendantOf: function(element, ancestor) { - element = $(element), ancestor = $(ancestor); + descendantOf: function (element, ancestor) { + (element = $(element)), (ancestor = $(ancestor)); if (element.compareDocumentPosition) return (element.compareDocumentPosition(ancestor) & 8) === 8; @@ -2348,66 +2496,71 @@ Element.Methods = { if (ancestor.contains) return ancestor.contains(element) && ancestor !== element; - while (element = element.parentNode) - if (element == ancestor) return true; + while ((element = element.parentNode)) if (element == ancestor) return true; return false; }, - scrollTo: function(element) { + scrollTo: function (element) { element = $(element); var pos = Element.cumulativeOffset(element); window.scrollTo(pos[0], pos[1]); return element; }, - getStyle: function(element, style) { + getStyle: function (element, style) { element = $(element); - style = style == 'float' ? 'cssFloat' : style.camelize(); + style = style == "float" ? "cssFloat" : style.camelize(); var value = element.style[style]; - if (!value || value == 'auto') { + if (!value || value == "auto") { var css = document.defaultView.getComputedStyle(element, null); value = css ? css[style] : null; } - if (style == 'opacity') return value ? parseFloat(value) : 1.0; - return value == 'auto' ? null : value; + if (style == "opacity") return value ? parseFloat(value) : 1.0; + return value == "auto" ? null : value; }, - getOpacity: function(element) { - return $(element).getStyle('opacity'); + getOpacity: function (element) { + return $(element).getStyle("opacity"); }, - setStyle: function(element, styles) { + setStyle: function (element, styles) { element = $(element); - var elementStyle = element.style, match; + var elementStyle = element.style, + match; if (Object.isString(styles)) { - element.style.cssText += ';' + styles; - return styles.include('opacity') ? - element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; + element.style.cssText += ";" + styles; + return styles.include("opacity") + ? element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) + : element; } for (var property in styles) - if (property == 'opacity') element.setOpacity(styles[property]); + if (property == "opacity") element.setOpacity(styles[property]); else - elementStyle[(property == 'float' || property == 'cssFloat') ? - (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') : - property] = styles[property]; + elementStyle[ + property == "float" || property == "cssFloat" + ? Object.isUndefined(elementStyle.styleFloat) + ? "cssFloat" + : "styleFloat" + : property + ] = styles[property]; return element; }, - setOpacity: function(element, value) { + setOpacity: function (element, value) { element = $(element); - element.style.opacity = (value == 1 || value === '') ? '' : - (value < 0.00001) ? 0 : value; + element.style.opacity = + value == 1 || value === "" ? "" : value < 0.00001 ? 0 : value; return element; }, - makePositioned: function(element) { + makePositioned: function (element) { element = $(element); - var pos = Element.getStyle(element, 'position'); - if (pos == 'static' || !pos) { + var pos = Element.getStyle(element, "position"); + if (pos == "static" || !pos) { element._madePositioned = true; - element.style.position = 'relative'; + element.style.position = "relative"; if (Prototype.Browser.Opera) { element.style.top = 0; element.style.left = 0; @@ -2416,7 +2569,7 @@ Element.Methods = { return element; }, - undoPositioned: function(element) { + undoPositioned: function (element) { element = $(element); if (element._madePositioned) { element._madePositioned = undefined; @@ -2424,44 +2577,50 @@ Element.Methods = { element.style.top = element.style.left = element.style.bottom = - element.style.right = ''; + element.style.right = + ""; } return element; }, - makeClipping: function(element) { + makeClipping: function (element) { element = $(element); if (element._overflow) return element; - element._overflow = Element.getStyle(element, 'overflow') || 'auto'; - if (element._overflow !== 'hidden') - element.style.overflow = 'hidden'; + element._overflow = Element.getStyle(element, "overflow") || "auto"; + if (element._overflow !== "hidden") element.style.overflow = "hidden"; return element; }, - undoClipping: function(element) { + undoClipping: function (element) { element = $(element); if (!element._overflow) return element; - element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element.style.overflow = + element._overflow == "auto" ? "" : element._overflow; element._overflow = null; return element; }, - clonePosition: function(element, source) { - var options = Object.extend({ - setLeft: true, - setTop: true, - setWidth: true, - setHeight: true, - offsetTop: 0, - offsetLeft: 0 - }, arguments[2] || { }); + clonePosition: function (element, source) { + var options = Object.extend( + { + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0, + }, + arguments[2] || {} + ); source = $(source); - var p = Element.viewportOffset(source), delta = [0, 0], parent = null; + var p = Element.viewportOffset(source), + delta = [0, 0], + parent = null; element = $(element); - if (Element.getStyle(element, 'position') == 'absolute') { + if (Element.getStyle(element, "position") == "absolute") { parent = Element.getOffsetParent(element); delta = Element.viewportOffset(parent); } @@ -2471,132 +2630,156 @@ Element.Methods = { delta[1] -= document.body.offsetTop; } - if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; - if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; - if (options.setWidth) element.style.width = source.offsetWidth + 'px'; - if (options.setHeight) element.style.height = source.offsetHeight + 'px'; + if (options.setLeft) + element.style.left = p[0] - delta[0] + options.offsetLeft + "px"; + if (options.setTop) + element.style.top = p[1] - delta[1] + options.offsetTop + "px"; + if (options.setWidth) element.style.width = source.offsetWidth + "px"; + if (options.setHeight) element.style.height = source.offsetHeight + "px"; return element; - } + }, }; Object.extend(Element.Methods, { getElementsBySelector: Element.Methods.select, - childElements: Element.Methods.immediateDescendants + childElements: Element.Methods.immediateDescendants, }); Element._attributeTranslations = { write: { names: { - className: 'class', - htmlFor: 'for' + className: "class", + htmlFor: "for", }, - values: { } - } + values: {}, + }, }; if (Prototype.Browser.Opera) { - Element.Methods.getStyle = Element.Methods.getStyle.wrap( - function(proceed, element, style) { - switch (style) { - case 'height': case 'width': - if (!Element.visible(element)) return null; - - var dim = parseInt(proceed(element, style), 10); - - if (dim !== element['offset' + style.capitalize()]) - return dim + 'px'; - - var properties; - if (style === 'height') { - properties = ['border-top-width', 'padding-top', - 'padding-bottom', 'border-bottom-width']; - } - else { - properties = ['border-left-width', 'padding-left', - 'padding-right', 'border-right-width']; - } - return properties.inject(dim, function(memo, property) { + Element.Methods.getStyle = Element.Methods.getStyle.wrap(function ( + proceed, + element, + style + ) { + switch (style) { + case "height": + case "width": + if (!Element.visible(element)) return null; + + var dim = parseInt(proceed(element, style), 10); + + if (dim !== element["offset" + style.capitalize()]) return dim + "px"; + + var properties; + if (style === "height") { + properties = [ + "border-top-width", + "padding-top", + "padding-bottom", + "border-bottom-width", + ]; + } else { + properties = [ + "border-left-width", + "padding-left", + "padding-right", + "border-right-width", + ]; + } + return ( + properties.inject(dim, function (memo, property) { var val = proceed(element, property); return val === null ? memo : memo - parseInt(val, 10); - }) + 'px'; - default: return proceed(element, style); - } - } - ); - - Element.Methods.readAttribute = Element.Methods.readAttribute.wrap( - function(proceed, element, attribute) { - if (attribute === 'title') return element.title; - return proceed(element, attribute); + }) + "px" + ); + default: + return proceed(element, style); } - ); -} + }); -else if (Prototype.Browser.IE) { - Element.Methods.getStyle = function(element, style) { + Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(function ( + proceed, + element, + attribute + ) { + if (attribute === "title") return element.title; + return proceed(element, attribute); + }); +} else if (Prototype.Browser.IE) { + Element.Methods.getStyle = function (element, style) { element = $(element); - style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); + style = + style == "float" || style == "cssFloat" ? "styleFloat" : style.camelize(); var value = element.style[style]; if (!value && element.currentStyle) value = element.currentStyle[style]; - if (style == 'opacity') { - if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if (style == "opacity") { + if ( + (value = (element.getStyle("filter") || "").match( + /alpha\(opacity=(.*)\)/ + )) + ) if (value[1]) return parseFloat(value[1]) / 100; return 1.0; } - if (value == 'auto') { - if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none')) - return element['offset' + style.capitalize()] + 'px'; + if (value == "auto") { + if ( + (style == "width" || style == "height") && + element.getStyle("display") != "none" + ) + return element["offset" + style.capitalize()] + "px"; return null; } return value; }; - Element.Methods.setOpacity = function(element, value) { - function stripAlpha(filter){ - return filter.replace(/alpha\([^\)]*\)/gi,''); + Element.Methods.setOpacity = function (element, value) { + function stripAlpha(filter) { + return filter.replace(/alpha\([^\)]*\)/gi, ""); } element = $(element); var currentStyle = element.currentStyle; - if ((currentStyle && !currentStyle.hasLayout) || - (!currentStyle && element.style.zoom == 'normal')) - element.style.zoom = 1; - - var filter = element.getStyle('filter'), style = element.style; - if (value == 1 || value === '') { - (filter = stripAlpha(filter)) ? - style.filter = filter : style.removeAttribute('filter'); + if ( + (currentStyle && !currentStyle.hasLayout) || + (!currentStyle && element.style.zoom == "normal") + ) + element.style.zoom = 1; + + var filter = element.getStyle("filter"), + style = element.style; + if (value == 1 || value === "") { + (filter = stripAlpha(filter)) + ? (style.filter = filter) + : style.removeAttribute("filter"); return element; } else if (value < 0.00001) value = 0; - style.filter = stripAlpha(filter) + - 'alpha(opacity=' + (value * 100) + ')'; + style.filter = stripAlpha(filter) + "alpha(opacity=" + value * 100 + ")"; return element; }; - Element._attributeTranslations = (function(){ - - var classProp = 'className', - forProp = 'for', - el = document.createElement('div'); + Element._attributeTranslations = (function () { + var classProp = "className", + forProp = "for", + el = document.createElement("div"); - el.setAttribute(classProp, 'x'); + el.setAttribute(classProp, "x"); - if (el.className !== 'x') { - el.setAttribute('class', 'x'); - if (el.className === 'x') { - classProp = 'class'; + if (el.className !== "x") { + el.setAttribute("class", "x"); + if (el.className === "x") { + classProp = "class"; } } el = null; - el = document.createElement('label'); - el.setAttribute(forProp, 'x'); - if (el.htmlFor !== 'x') { - el.setAttribute('htmlFor', 'x'); - if (el.htmlFor === 'x') { - forProp = 'htmlFor'; + el = document.createElement("label"); + el.setAttribute(forProp, "x"); + if (el.htmlFor !== "x") { + el.setAttribute("htmlFor", "x"); + if (el.htmlFor === "x") { + forProp = "htmlFor"; } } el = null; @@ -2604,40 +2787,39 @@ else if (Prototype.Browser.IE) { return { read: { names: { - 'class': classProp, - 'className': classProp, - 'for': forProp, - 'htmlFor': forProp + class: classProp, + className: classProp, + for: forProp, + htmlFor: forProp, }, values: { - _getAttr: function(element, attribute) { + _getAttr: function (element, attribute) { return element.getAttribute(attribute); }, - _getAttr2: function(element, attribute) { + _getAttr2: function (element, attribute) { return element.getAttribute(attribute, 2); }, - _getAttrNode: function(element, attribute) { + _getAttrNode: function (element, attribute) { var node = element.getAttributeNode(attribute); return node ? node.value : ""; }, - _getEv: (function(){ - - var el = document.createElement('div'), f; + _getEv: (function () { + var el = document.createElement("div"), + f; el.onclick = Prototype.emptyFunction; - var value = el.getAttribute('onclick'); + var value = el.getAttribute("onclick"); - if (String(value).indexOf('{') > -1) { - f = function(element, attribute) { + if (String(value).indexOf("{") > -1) { + f = function (element, attribute) { attribute = element.getAttribute(attribute); if (!attribute) return null; attribute = attribute.toString(); - attribute = attribute.split('{')[1]; - attribute = attribute.split('}')[0]; + attribute = attribute.split("{")[1]; + attribute = attribute.split("}")[0]; return attribute.strip(); }; - } - else if (value === '') { - f = function(element, attribute) { + } else if (value === "") { + f = function (element, attribute) { attribute = element.getAttribute(attribute); if (!attribute) return null; return attribute.strip(); @@ -2646,126 +2828,131 @@ else if (Prototype.Browser.IE) { el = null; return f; })(), - _flag: function(element, attribute) { + _flag: function (element, attribute) { return $(element).hasAttribute(attribute) ? attribute : null; }, - style: function(element) { + style: function (element) { return element.style.cssText.toLowerCase(); }, - title: function(element) { + title: function (element) { return element.title; - } - } - } - } + }, + }, + }, + }; })(); Element._attributeTranslations.write = { - names: Object.extend({ - cellpadding: 'cellPadding', - cellspacing: 'cellSpacing' - }, Element._attributeTranslations.read.names), + names: Object.extend( + { + cellpadding: "cellPadding", + cellspacing: "cellSpacing", + }, + Element._attributeTranslations.read.names + ), values: { - checked: function(element, value) { + checked: function (element, value) { element.checked = !!value; }, - style: function(element, value) { - element.style.cssText = value ? value : ''; - } - } + style: function (element, value) { + element.style.cssText = value ? value : ""; + }, + }, }; Element._attributeTranslations.has = {}; - $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' + - 'encType maxLength readOnly longDesc frameBorder').each(function(attr) { + $w( + "colSpan rowSpan vAlign dateTime accessKey tabIndex " + + "encType maxLength readOnly longDesc frameBorder" + ).each(function (attr) { Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; Element._attributeTranslations.has[attr.toLowerCase()] = attr; }); - (function(v) { + (function (v) { Object.extend(v, { - href: v._getAttr2, - src: v._getAttr2, - type: v._getAttr, - action: v._getAttrNode, - disabled: v._flag, - checked: v._flag, - readonly: v._flag, - multiple: v._flag, - onload: v._getEv, - onunload: v._getEv, - onclick: v._getEv, - ondblclick: v._getEv, + href: v._getAttr2, + src: v._getAttr2, + type: v._getAttr, + action: v._getAttrNode, + disabled: v._flag, + checked: v._flag, + readonly: v._flag, + multiple: v._flag, + onload: v._getEv, + onunload: v._getEv, + onclick: v._getEv, + ondblclick: v._getEv, onmousedown: v._getEv, - onmouseup: v._getEv, + onmouseup: v._getEv, onmouseover: v._getEv, onmousemove: v._getEv, - onmouseout: v._getEv, - onfocus: v._getEv, - onblur: v._getEv, - onkeypress: v._getEv, - onkeydown: v._getEv, - onkeyup: v._getEv, - onsubmit: v._getEv, - onreset: v._getEv, - onselect: v._getEv, - onchange: v._getEv + onmouseout: v._getEv, + onfocus: v._getEv, + onblur: v._getEv, + onkeypress: v._getEv, + onkeydown: v._getEv, + onkeyup: v._getEv, + onsubmit: v._getEv, + onreset: v._getEv, + onselect: v._getEv, + onchange: v._getEv, }); })(Element._attributeTranslations.read.values); if (Prototype.BrowserFeatures.ElementExtensions) { - (function() { + (function () { function _descendants(element) { - var nodes = element.getElementsByTagName('*'), results = []; - for (var i = 0, node; node = nodes[i]; i++) - if (node.tagName !== "!") // Filter out comment nodes. + var nodes = element.getElementsByTagName("*"), + results = []; + for (var i = 0, node; (node = nodes[i]); i++) + if (node.tagName !== "!") + // Filter out comment nodes. results.push(node); return results; } - Element.Methods.down = function(element, expression, index) { + Element.Methods.down = function (element, expression, index) { element = $(element); if (arguments.length == 1) return element.firstDescendant(); - return Object.isNumber(expression) ? _descendants(element)[expression] : - Element.select(element, expression)[index || 0]; - } + return Object.isNumber(expression) + ? _descendants(element)[expression] + : Element.select(element, expression)[index || 0]; + }; })(); } - -} - -else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { - Element.Methods.setOpacity = function(element, value) { +} else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { + Element.Methods.setOpacity = function (element, value) { element = $(element); - element.style.opacity = (value == 1) ? 0.999999 : - (value === '') ? '' : (value < 0.00001) ? 0 : value; + element.style.opacity = + value == 1 ? 0.999999 : value === "" ? "" : value < 0.00001 ? 0 : value; return element; }; -} - -else if (Prototype.Browser.WebKit) { - Element.Methods.setOpacity = function(element, value) { +} else if (Prototype.Browser.WebKit) { + Element.Methods.setOpacity = function (element, value) { element = $(element); - element.style.opacity = (value == 1 || value === '') ? '' : - (value < 0.00001) ? 0 : value; + element.style.opacity = + value == 1 || value === "" ? "" : value < 0.00001 ? 0 : value; if (value == 1) - if (element.tagName.toUpperCase() == 'IMG' && element.width) { - element.width++; element.width--; - } else try { - var n = document.createTextNode(' '); - element.appendChild(n); - element.removeChild(n); - } catch (e) { } + if (element.tagName.toUpperCase() == "IMG" && element.width) { + element.width++; + element.width--; + } else + try { + var n = document.createTextNode(" "); + element.appendChild(n); + element.removeChild(n); + } catch (e) {} return element; }; } -if ('outerHTML' in document.documentElement) { - Element.Methods.replace = function(element, content) { +if ("outerHTML" in document.documentElement) { + Element.Methods.replace = function (element, content) { element = $(element); if (content && content.toElement) content = content.toElement(); @@ -2775,120 +2962,123 @@ if ('outerHTML' in document.documentElement) { } content = Object.toHTML(content); - var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); + var parent = element.parentNode, + tagName = parent.tagName.toUpperCase(); if (Element._insertionTranslations.tags[tagName]) { var nextSibling = element.next(), - fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + fragments = Element._getContentFromAnonymousElement( + tagName, + content.stripScripts() + ); parent.removeChild(element); if (nextSibling) - fragments.each(function(node) { parent.insertBefore(node, nextSibling) }); + fragments.each(function (node) { + parent.insertBefore(node, nextSibling); + }); else - fragments.each(function(node) { parent.appendChild(node) }); - } - else element.outerHTML = content.stripScripts(); + fragments.each(function (node) { + parent.appendChild(node); + }); + } else element.outerHTML = content.stripScripts(); content.evalScripts.bind(content).defer(); return element; }; } -Element._returnOffset = function(l, t) { +Element._returnOffset = function (l, t) { var result = [l, t]; result.left = l; result.top = t; return result; }; -Element._getContentFromAnonymousElement = function(tagName, html, force) { - var div = new Element('div'), - t = Element._insertionTranslations.tags[tagName]; +Element._getContentFromAnonymousElement = function (tagName, html, force) { + var div = new Element("div"), + t = Element._insertionTranslations.tags[tagName]; var workaround = false; if (t) workaround = true; else if (force) { workaround = true; - t = ['', '', 0]; + t = ["", "", 0]; } if (workaround) { - div.innerHTML = ' ' + t[0] + html + t[1]; + div.innerHTML = " " + t[0] + html + t[1]; div.removeChild(div.firstChild); for (var i = t[2]; i--; ) { div = div.firstChild; } - } - else { + } else { div.innerHTML = html; } return $A(div.childNodes); }; Element._insertionTranslations = { - before: function(element, node) { + before: function (element, node) { element.parentNode.insertBefore(node, element); }, - top: function(element, node) { + top: function (element, node) { element.insertBefore(node, element.firstChild); }, - bottom: function(element, node) { + bottom: function (element, node) { element.appendChild(node); }, - after: function(element, node) { + after: function (element, node) { element.parentNode.insertBefore(node, element.nextSibling); }, tags: { - TABLE: ['', '
', 1], - TBODY: ['', '
', 2], - TR: ['', '
', 3], - TD: ['
', '
', 4], - SELECT: ['', 1] - } + TABLE: ["", "
", 1], + TBODY: ["", "
", 2], + TR: ["", "
", 3], + TD: ["
", "
", 4], + SELECT: ["", 1], + }, }; -(function() { +(function () { var tags = Element._insertionTranslations.tags; Object.extend(tags, { THEAD: tags.TBODY, TFOOT: tags.TBODY, - TH: tags.TD + TH: tags.TD, }); })(); Element.Methods.Simulated = { - hasAttribute: function(element, attribute) { + hasAttribute: function (element, attribute) { attribute = Element._attributeTranslations.has[attribute] || attribute; var node = $(element).getAttributeNode(attribute); return !!(node && node.specified); - } + }, }; -Element.Methods.ByTag = { }; +Element.Methods.ByTag = {}; Object.extend(Element, Element.Methods); -(function(div) { - - if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) { - window.HTMLElement = { }; - window.HTMLElement.prototype = div['__proto__']; +(function (div) { + if (!Prototype.BrowserFeatures.ElementExtensions && div["__proto__"]) { + window.HTMLElement = {}; + window.HTMLElement.prototype = div["__proto__"]; Prototype.BrowserFeatures.ElementExtensions = true; } div = null; +})(document.createElement("div")); -})(document.createElement('div')); - -Element.extend = (function() { - +Element.extend = (function () { function checkDeficiency(tagName) { - if (typeof window.Element != 'undefined') { + if (typeof window.Element != "undefined") { var proto = window.Element.prototype; if (proto) { - var id = '_' + (Math.random()+'').slice(2), - el = document.createElement(tagName); - proto[id] = 'x'; - var isBuggy = (el[id] !== 'x'); + var id = "_" + (Math.random() + "").slice(2), + el = document.createElement(tagName); + proto[id] = "x"; + var isBuggy = el[id] !== "x"; delete proto[id]; el = null; return isBuggy; @@ -2905,75 +3095,83 @@ Element.extend = (function() { } } - var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object'); + var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency("object"); if (Prototype.BrowserFeatures.SpecificElementExtensions) { if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) { - return function(element) { - if (element && typeof element._extendedByPrototype == 'undefined') { + return function (element) { + if (element && typeof element._extendedByPrototype == "undefined") { var t = element.tagName; - if (t && (/^(?:object|applet|embed)$/i.test(t))) { + if (t && /^(?:object|applet|embed)$/i.test(t)) { extendElementWith(element, Element.Methods); extendElementWith(element, Element.Methods.Simulated); extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]); } } return element; - } + }; } return Prototype.K; } - var Methods = { }, ByTag = Element.Methods.ByTag; + var Methods = {}, + ByTag = Element.Methods.ByTag; - var extend = Object.extend(function(element) { - if (!element || typeof element._extendedByPrototype != 'undefined' || - element.nodeType != 1 || element == window) return element; + var extend = Object.extend( + function (element) { + if ( + !element || + typeof element._extendedByPrototype != "undefined" || + element.nodeType != 1 || + element == window + ) + return element; - var methods = Object.clone(Methods), + var methods = Object.clone(Methods), tagName = element.tagName.toUpperCase(); - if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); + if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); - extendElementWith(element, methods); + extendElementWith(element, methods); - element._extendedByPrototype = Prototype.emptyFunction; - return element; - - }, { - refresh: function() { - if (!Prototype.BrowserFeatures.ElementExtensions) { - Object.extend(Methods, Element.Methods); - Object.extend(Methods, Element.Methods.Simulated); - } + element._extendedByPrototype = Prototype.emptyFunction; + return element; + }, + { + refresh: function () { + if (!Prototype.BrowserFeatures.ElementExtensions) { + Object.extend(Methods, Element.Methods); + Object.extend(Methods, Element.Methods.Simulated); + } + }, } - }); + ); extend.refresh(); return extend; })(); if (document.documentElement.hasAttribute) { - Element.hasAttribute = function(element, attribute) { + Element.hasAttribute = function (element, attribute) { return element.hasAttribute(attribute); }; -} -else { +} else { Element.hasAttribute = Element.Methods.Simulated.hasAttribute; } -Element.addMethods = function(methods) { - var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; +Element.addMethods = function (methods) { + var F = Prototype.BrowserFeatures, + T = Element.Methods.ByTag; if (!methods) { Object.extend(Form, Form.Methods); Object.extend(Form.Element, Form.Element.Methods); Object.extend(Element.Methods.ByTag, { - "FORM": Object.clone(Form.Methods), - "INPUT": Object.clone(Form.Element.Methods), - "SELECT": Object.clone(Form.Element.Methods), - "TEXTAREA": Object.clone(Form.Element.Methods), - "BUTTON": Object.clone(Form.Element.Methods) + FORM: Object.clone(Form.Methods), + INPUT: Object.clone(Form.Element.Methods), + SELECT: Object.clone(Form.Element.Methods), + TEXTAREA: Object.clone(Form.Element.Methods), + BUTTON: Object.clone(Form.Element.Methods), }); } @@ -2982,7 +3180,7 @@ Element.addMethods = function(methods) { methods = arguments[1]; } - if (!tagName) Object.extend(Element.Methods, methods || { }); + if (!tagName) Object.extend(Element.Methods, methods || {}); else { if (Object.isArray(tagName)) tagName.each(extend); else extend(tagName); @@ -2990,8 +3188,7 @@ Element.addMethods = function(methods) { function extend(tagName) { tagName = tagName.toUpperCase(); - if (!Element.Methods.ByTag[tagName]) - Element.Methods.ByTag[tagName] = { }; + if (!Element.Methods.ByTag[tagName]) Element.Methods.ByTag[tagName] = {}; Object.extend(Element.Methods.ByTag[tagName], methods); } @@ -3008,32 +3205,54 @@ Element.addMethods = function(methods) { function findDOMClass(tagName) { var klass; var trans = { - "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", - "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", - "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", - "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", - "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": - "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": - "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": - "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": - "FrameSet", "IFRAME": "IFrame" + OPTGROUP: "OptGroup", + TEXTAREA: "TextArea", + P: "Paragraph", + FIELDSET: "FieldSet", + UL: "UList", + OL: "OList", + DL: "DList", + DIR: "Directory", + H1: "Heading", + H2: "Heading", + H3: "Heading", + H4: "Heading", + H5: "Heading", + H6: "Heading", + Q: "Quote", + INS: "Mod", + DEL: "Mod", + A: "Anchor", + IMG: "Image", + CAPTION: "TableCaption", + COL: "TableCol", + COLGROUP: "TableCol", + THEAD: "TableSection", + TFOOT: "TableSection", + TBODY: "TableSection", + TR: "TableRow", + TH: "TableCell", + TD: "TableCell", + FRAMESET: "FrameSet", + IFRAME: "IFrame", }; - if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; + if (trans[tagName]) klass = "HTML" + trans[tagName] + "Element"; if (window[klass]) return window[klass]; - klass = 'HTML' + tagName + 'Element'; + klass = "HTML" + tagName + "Element"; if (window[klass]) return window[klass]; - klass = 'HTML' + tagName.capitalize() + 'Element'; + klass = "HTML" + tagName.capitalize() + "Element"; if (window[klass]) return window[klass]; var element = document.createElement(tagName), - proto = element['__proto__'] || element.constructor.prototype; + proto = element["__proto__"] || element.constructor.prototype; element = null; return proto; } - var elementPrototype = window.HTMLElement ? HTMLElement.prototype : - Element.prototype; + var elementPrototype = window.HTMLElement + ? HTMLElement.prototype + : Element.prototype; if (F.ElementExtensions) { copy(Element.Methods, elementPrototype); @@ -3052,29 +3271,34 @@ Element.addMethods = function(methods) { delete Element.ByTag; if (Element.extend.refresh) Element.extend.refresh(); - Element.cache = { }; + Element.cache = {}; }; - document.viewport = { - - getDimensions: function() { + getDimensions: function () { return { width: this.getWidth(), height: this.getHeight() }; }, - getScrollOffsets: function() { + getScrollOffsets: function () { return Element._returnOffset( - window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, - window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); - } + window.pageXOffset || + document.documentElement.scrollLeft || + document.body.scrollLeft, + window.pageYOffset || + document.documentElement.scrollTop || + document.body.scrollTop + ); + }, }; -(function(viewport) { - var B = Prototype.Browser, doc = document, element, property = {}; +(function (viewport) { + var B = Prototype.Browser, + doc = document, + element, + property = {}; function getRootElement() { - if (B.WebKit && !doc.evaluate) - return document; + if (B.WebKit && !doc.evaluate) return document; if (B.Opera && window.parseFloat(window.opera.version()) < 9.5) return document.body; @@ -3085,24 +3309,25 @@ document.viewport = { function define(D) { if (!element) element = getRootElement(); - property[D] = 'client' + D; + property[D] = "client" + D; - viewport['get' + D] = function() { return element[property[D]] }; - return viewport['get' + D](); + viewport["get" + D] = function () { + return element[property[D]]; + }; + return viewport["get" + D](); } - viewport.getWidth = define.curry('Width'); + viewport.getWidth = define.curry("Width"); - viewport.getHeight = define.curry('Height'); + viewport.getHeight = define.curry("Height"); })(document.viewport); - Element.Storage = { - UID: 1 + UID: 1, }; Element.addMethods({ - getStorage: function(element) { + getStorage: function (element) { if (!(element = $(element))) return; var uid; @@ -3114,13 +3339,12 @@ Element.addMethods({ uid = element._prototypeUID; } - if (!Element.Storage[uid]) - Element.Storage[uid] = $H(); + if (!Element.Storage[uid]) Element.Storage[uid] = $H(); return Element.Storage[uid]; }, - store: function(element, key, value) { + store: function (element, key, value) { if (!(element = $(element))) return; if (arguments.length === 2) { @@ -3132,9 +3356,10 @@ Element.addMethods({ return element; }, - retrieve: function(element, key, defaultValue) { + retrieve: function (element, key, defaultValue) { if (!(element = $(element))) return; - var hash = Element.getStorage(element), value = hash.get(key); + var hash = Element.getStorage(element), + value = hash.get(key); if (Object.isUndefined(value)) { hash.set(key, defaultValue); @@ -3144,13 +3369,13 @@ Element.addMethods({ return value; }, - clone: function(element, deep) { + clone: function (element, deep) { if (!(element = $(element))) return; var clone = element.cloneNode(deep); clone._prototypeUID = void 0; if (deep) { - var descendants = Element.select(clone, '*'), - i = descendants.length; + var descendants = Element.select(clone, "*"), + i = descendants.length; while (i--) { descendants[i]._prototypeUID = void 0; } @@ -3158,27 +3383,26 @@ Element.addMethods({ return Element.extend(clone); }, - purge: function(element) { + purge: function (element) { if (!(element = $(element))) return; var purgeElement = Element._purgeElement; purgeElement(element); - var descendants = element.getElementsByTagName('*'), - i = descendants.length; + var descendants = element.getElementsByTagName("*"), + i = descendants.length; while (i--) purgeElement(descendants[i]); return null; - } + }, }); -(function() { - +(function () { function toDecimal(pctString) { var match = pctString.match(/^(\d+)%?$/i); if (!match) return null; - return (Number(match[1]) / 100); + return Number(match[1]) / 100; } function getPixelValue(value, property, context) { @@ -3192,14 +3416,21 @@ Element.addMethods({ return null; } - if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) { + if (/^(?:-)?\d+(\.\d+)?(px)?$/i.test(value)) { return window.parseFloat(value); } - var isPercentage = value.include('%'), isViewport = (context === document.viewport); + var isPercentage = value.include("%"), + isViewport = context === document.viewport; - if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) { - var style = element.style.left, rStyle = element.runtimeStyle.left; + if ( + /\d/.test(value) && + element && + element.runtimeStyle && + !(isPercentage && isViewport) + ) { + var style = element.style.left, + rStyle = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; element.style.left = value || 0; value = element.style.pixelLeft; @@ -3213,13 +3444,17 @@ Element.addMethods({ context = context || element.parentNode; var decimal = toDecimal(value); var whole = null; - var position = element.getStyle('position'); + var position = element.getStyle("position"); - var isHorizontal = property.include('left') || property.include('right') || - property.include('width'); + var isHorizontal = + property.include("left") || + property.include("right") || + property.include("width"); - var isVertical = property.include('top') || property.include('bottom') || - property.include('height'); + var isVertical = + property.include("top") || + property.include("bottom") || + property.include("height"); if (context === document.viewport) { if (isHorizontal) { @@ -3229,30 +3464,30 @@ Element.addMethods({ } } else { if (isHorizontal) { - whole = $(context).measure('width'); + whole = $(context).measure("width"); } else if (isVertical) { - whole = $(context).measure('height'); + whole = $(context).measure("height"); } } - return (whole === null) ? 0 : whole * decimal; + return whole === null ? 0 : whole * decimal; } return 0; } function toCSSPixels(number) { - if (Object.isString(number) && number.endsWith('px')) { + if (Object.isString(number) && number.endsWith("px")) { return number; } - return number + 'px'; + return number + "px"; } function isDisplayed(element) { var originalElement = element; while (element && element.parentNode) { - var display = element.getStyle('display'); - if (display === 'none') { + var display = element.getStyle("display"); + if (display === "none") { return false; } element = $(element.parentNode); @@ -3261,8 +3496,8 @@ Element.addMethods({ } var hasLayout = Prototype.K; - if ('currentStyle' in document.documentElement) { - hasLayout = function(element) { + if ("currentStyle" in document.documentElement) { + hasLayout = function (element) { if (!element.currentStyle.hasLayout) { element.style.zoom = 1; } @@ -3271,42 +3506,42 @@ Element.addMethods({ } function cssNameFor(key) { - if (key.include('border')) key = key + '-width'; + if (key.include("border")) key = key + "-width"; return key.camelize(); } Element.Layout = Class.create(Hash, { - initialize: function($super, element, preCompute) { + initialize: function ($super, element, preCompute) { $super(); this.element = $(element); - Element.Layout.PROPERTIES.each( function(property) { + Element.Layout.PROPERTIES.each(function (property) { this._set(property, null); }, this); if (preCompute) { this._preComputing = true; this._begin(); - Element.Layout.PROPERTIES.each( this._compute, this ); + Element.Layout.PROPERTIES.each(this._compute, this); this._end(); this._preComputing = false; } }, - _set: function(property, value) { + _set: function (property, value) { return Hash.prototype.set.call(this, property, value); }, - set: function(property, value) { + set: function (property, value) { throw "Properties of Element.Layout are read-only."; }, - get: function($super, property) { + get: function ($super, property) { var value = $super(property); return value === null ? this._compute(property) : value; }, - _begin: function() { + _begin: function () { if (this._prepared) return; var element = this.element; @@ -3316,78 +3551,85 @@ Element.addMethods({ } var originalStyles = { - position: element.style.position || '', - width: element.style.width || '', - visibility: element.style.visibility || '', - display: element.style.display || '' + position: element.style.position || "", + width: element.style.width || "", + visibility: element.style.visibility || "", + display: element.style.display || "", }; - element.store('prototype_original_styles', originalStyles); + element.store("prototype_original_styles", originalStyles); - var position = element.getStyle('position'), - width = element.getStyle('width'); + var position = element.getStyle("position"), + width = element.getStyle("width"); if (width === "0px" || width === null) { - element.style.display = 'block'; - width = element.getStyle('width'); + element.style.display = "block"; + width = element.getStyle("width"); } - var context = (position === 'fixed') ? document.viewport : - element.parentNode; + var context = + position === "fixed" ? document.viewport : element.parentNode; element.setStyle({ - position: 'absolute', - visibility: 'hidden', - display: 'block' + position: "absolute", + visibility: "hidden", + display: "block", }); - var positionedWidth = element.getStyle('width'); + var positionedWidth = element.getStyle("width"); var newWidth; - if (width && (positionedWidth === width)) { - newWidth = getPixelValue(element, 'width', context); - } else if (position === 'absolute' || position === 'fixed') { - newWidth = getPixelValue(element, 'width', context); + if (width && positionedWidth === width) { + newWidth = getPixelValue(element, "width", context); + } else if (position === "absolute" || position === "fixed") { + newWidth = getPixelValue(element, "width", context); } else { - var parent = element.parentNode, pLayout = $(parent).getLayout(); - - newWidth = pLayout.get('width') - - this.get('margin-left') - - this.get('border-left') - - this.get('padding-left') - - this.get('padding-right') - - this.get('border-right') - - this.get('margin-right'); + var parent = element.parentNode, + pLayout = $(parent).getLayout(); + + newWidth = + pLayout.get("width") - + this.get("margin-left") - + this.get("border-left") - + this.get("padding-left") - + this.get("padding-right") - + this.get("border-right") - + this.get("margin-right"); } - element.setStyle({ width: newWidth + 'px' }); + element.setStyle({ width: newWidth + "px" }); this._prepared = true; }, - _end: function() { + _end: function () { var element = this.element; - var originalStyles = element.retrieve('prototype_original_styles'); - element.store('prototype_original_styles', null); + var originalStyles = element.retrieve("prototype_original_styles"); + element.store("prototype_original_styles", null); element.setStyle(originalStyles); this._prepared = false; }, - _compute: function(property) { + _compute: function (property) { var COMPUTATIONS = Element.Layout.COMPUTATIONS; if (!(property in COMPUTATIONS)) { throw "Property not found."; } - return this._set(property, COMPUTATIONS[property].call(this, this.element)); + return this._set( + property, + COMPUTATIONS[property].call(this, this.element) + ); }, - toObject: function() { + toObject: function () { var args = $A(arguments); - var keys = (args.length === 0) ? Element.Layout.PROPERTIES : - args.join(' ').split(' '); + var keys = + args.length === 0 + ? Element.Layout.PROPERTIES + : args.join(" ").split(" "); var obj = {}; - keys.each( function(key) { + keys.each(function (key) { if (!Element.Layout.PROPERTIES.include(key)) return; var value = this.get(key); if (value != null) obj[key] = value; @@ -3395,255 +3637,258 @@ Element.addMethods({ return obj; }, - toHash: function() { + toHash: function () { var obj = this.toObject.apply(this, arguments); return new Hash(obj); }, - toCSS: function() { + toCSS: function () { var args = $A(arguments); - var keys = (args.length === 0) ? Element.Layout.PROPERTIES : - args.join(' ').split(' '); + var keys = + args.length === 0 + ? Element.Layout.PROPERTIES + : args.join(" ").split(" "); var css = {}; - keys.each( function(key) { + keys.each(function (key) { if (!Element.Layout.PROPERTIES.include(key)) return; if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return; var value = this.get(key); - if (value != null) css[cssNameFor(key)] = value + 'px'; + if (value != null) css[cssNameFor(key)] = value + "px"; }, this); return css; }, - inspect: function() { + inspect: function () { return "#"; - } + }, }); Object.extend(Element.Layout, { - PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'), + PROPERTIES: $w( + "height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height" + ), - COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'), + COMPOSITE_PROPERTIES: $w( + "padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height" + ), COMPUTATIONS: { - 'height': function(element) { + height: function (element) { if (!this._preComputing) this._begin(); - var bHeight = this.get('border-box-height'); + var bHeight = this.get("border-box-height"); if (bHeight <= 0) { if (!this._preComputing) this._end(); return 0; } - var bTop = this.get('border-top'), - bBottom = this.get('border-bottom'); + var bTop = this.get("border-top"), + bBottom = this.get("border-bottom"); - var pTop = this.get('padding-top'), - pBottom = this.get('padding-bottom'); + var pTop = this.get("padding-top"), + pBottom = this.get("padding-bottom"); if (!this._preComputing) this._end(); return bHeight - bTop - bBottom - pTop - pBottom; }, - 'width': function(element) { + width: function (element) { if (!this._preComputing) this._begin(); - var bWidth = this.get('border-box-width'); + var bWidth = this.get("border-box-width"); if (bWidth <= 0) { if (!this._preComputing) this._end(); return 0; } - var bLeft = this.get('border-left'), - bRight = this.get('border-right'); + var bLeft = this.get("border-left"), + bRight = this.get("border-right"); - var pLeft = this.get('padding-left'), - pRight = this.get('padding-right'); + var pLeft = this.get("padding-left"), + pRight = this.get("padding-right"); if (!this._preComputing) this._end(); return bWidth - bLeft - bRight - pLeft - pRight; }, - 'padding-box-height': function(element) { - var height = this.get('height'), - pTop = this.get('padding-top'), - pBottom = this.get('padding-bottom'); + "padding-box-height": function (element) { + var height = this.get("height"), + pTop = this.get("padding-top"), + pBottom = this.get("padding-bottom"); return height + pTop + pBottom; }, - 'padding-box-width': function(element) { - var width = this.get('width'), - pLeft = this.get('padding-left'), - pRight = this.get('padding-right'); + "padding-box-width": function (element) { + var width = this.get("width"), + pLeft = this.get("padding-left"), + pRight = this.get("padding-right"); return width + pLeft + pRight; }, - 'border-box-height': function(element) { + "border-box-height": function (element) { if (!this._preComputing) this._begin(); var height = element.offsetHeight; if (!this._preComputing) this._end(); return height; }, - 'border-box-width': function(element) { + "border-box-width": function (element) { if (!this._preComputing) this._begin(); var width = element.offsetWidth; if (!this._preComputing) this._end(); return width; }, - 'margin-box-height': function(element) { - var bHeight = this.get('border-box-height'), - mTop = this.get('margin-top'), - mBottom = this.get('margin-bottom'); + "margin-box-height": function (element) { + var bHeight = this.get("border-box-height"), + mTop = this.get("margin-top"), + mBottom = this.get("margin-bottom"); if (bHeight <= 0) return 0; return bHeight + mTop + mBottom; }, - 'margin-box-width': function(element) { - var bWidth = this.get('border-box-width'), - mLeft = this.get('margin-left'), - mRight = this.get('margin-right'); + "margin-box-width": function (element) { + var bWidth = this.get("border-box-width"), + mLeft = this.get("margin-left"), + mRight = this.get("margin-right"); if (bWidth <= 0) return 0; return bWidth + mLeft + mRight; }, - 'top': function(element) { + top: function (element) { var offset = element.positionedOffset(); return offset.top; }, - 'bottom': function(element) { + bottom: function (element) { var offset = element.positionedOffset(), - parent = element.getOffsetParent(), - pHeight = parent.measure('height'); + parent = element.getOffsetParent(), + pHeight = parent.measure("height"); - var mHeight = this.get('border-box-height'); + var mHeight = this.get("border-box-height"); return pHeight - mHeight - offset.top; }, - 'left': function(element) { + left: function (element) { var offset = element.positionedOffset(); return offset.left; }, - 'right': function(element) { + right: function (element) { var offset = element.positionedOffset(), - parent = element.getOffsetParent(), - pWidth = parent.measure('width'); + parent = element.getOffsetParent(), + pWidth = parent.measure("width"); - var mWidth = this.get('border-box-width'); + var mWidth = this.get("border-box-width"); return pWidth - mWidth - offset.left; }, - 'padding-top': function(element) { - return getPixelValue(element, 'paddingTop'); + "padding-top": function (element) { + return getPixelValue(element, "paddingTop"); }, - 'padding-bottom': function(element) { - return getPixelValue(element, 'paddingBottom'); + "padding-bottom": function (element) { + return getPixelValue(element, "paddingBottom"); }, - 'padding-left': function(element) { - return getPixelValue(element, 'paddingLeft'); + "padding-left": function (element) { + return getPixelValue(element, "paddingLeft"); }, - 'padding-right': function(element) { - return getPixelValue(element, 'paddingRight'); + "padding-right": function (element) { + return getPixelValue(element, "paddingRight"); }, - 'border-top': function(element) { - return getPixelValue(element, 'borderTopWidth'); + "border-top": function (element) { + return getPixelValue(element, "borderTopWidth"); }, - 'border-bottom': function(element) { - return getPixelValue(element, 'borderBottomWidth'); + "border-bottom": function (element) { + return getPixelValue(element, "borderBottomWidth"); }, - 'border-left': function(element) { - return getPixelValue(element, 'borderLeftWidth'); + "border-left": function (element) { + return getPixelValue(element, "borderLeftWidth"); }, - 'border-right': function(element) { - return getPixelValue(element, 'borderRightWidth'); + "border-right": function (element) { + return getPixelValue(element, "borderRightWidth"); }, - 'margin-top': function(element) { - return getPixelValue(element, 'marginTop'); + "margin-top": function (element) { + return getPixelValue(element, "marginTop"); }, - 'margin-bottom': function(element) { - return getPixelValue(element, 'marginBottom'); + "margin-bottom": function (element) { + return getPixelValue(element, "marginBottom"); }, - 'margin-left': function(element) { - return getPixelValue(element, 'marginLeft'); + "margin-left": function (element) { + return getPixelValue(element, "marginLeft"); }, - 'margin-right': function(element) { - return getPixelValue(element, 'marginRight'); - } - } + "margin-right": function (element) { + return getPixelValue(element, "marginRight"); + }, + }, }); - if ('getBoundingClientRect' in document.documentElement) { + if ("getBoundingClientRect" in document.documentElement) { Object.extend(Element.Layout.COMPUTATIONS, { - 'right': function(element) { + right: function (element) { var parent = hasLayout(element.getOffsetParent()); var rect = element.getBoundingClientRect(), - pRect = parent.getBoundingClientRect(); + pRect = parent.getBoundingClientRect(); return (pRect.right - rect.right).round(); }, - 'bottom': function(element) { + bottom: function (element) { var parent = hasLayout(element.getOffsetParent()); var rect = element.getBoundingClientRect(), - pRect = parent.getBoundingClientRect(); + pRect = parent.getBoundingClientRect(); return (pRect.bottom - rect.bottom).round(); - } + }, }); } Element.Offset = Class.create({ - initialize: function(left, top) { + initialize: function (left, top) { this.left = left.round(); - this.top = top.round(); + this.top = top.round(); this[0] = this.left; this[1] = this.top; }, - relativeTo: function(offset) { - return new Element.Offset( - this.left - offset.left, - this.top - offset.top - ); + relativeTo: function (offset) { + return new Element.Offset(this.left - offset.left, this.top - offset.top); }, - inspect: function() { + inspect: function () { return "#".interpolate(this); }, - toString: function() { + toString: function () { return "[#{left}, #{top}]".interpolate(this); }, - toArray: function() { + toArray: function () { return [this.left, this.top]; - } + }, }); function getLayout(element, preCompute) { @@ -3656,32 +3901,31 @@ Element.addMethods({ function getDimensions(element) { element = $(element); - var display = Element.getStyle(element, 'display'); + var display = Element.getStyle(element, "display"); - if (display && display !== 'none') { + if (display && display !== "none") { return { width: element.offsetWidth, height: element.offsetHeight }; } var style = element.style; var originalStyles = { visibility: style.visibility, - position: style.position, - display: style.display + position: style.position, + display: style.display, }; var newStyles = { - visibility: 'hidden', - display: 'block' + visibility: "hidden", + display: "block", }; - if (originalStyles.position !== 'fixed') - newStyles.position = 'absolute'; + if (originalStyles.position !== "fixed") newStyles.position = "absolute"; Element.setStyle(element, newStyles); var dimensions = { - width: element.offsetWidth, - height: element.offsetHeight + width: element.offsetWidth, + height: element.offsetHeight, }; Element.setStyle(element, originalStyles); @@ -3692,14 +3936,19 @@ Element.addMethods({ function getOffsetParent(element) { element = $(element); - if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) + if ( + isDocument(element) || + isDetached(element) || + isBody(element) || + isHtml(element) + ) return $(document.body); - var isInline = (Element.getStyle(element, 'display') === 'inline'); + var isInline = Element.getStyle(element, "display") === "inline"; if (!isInline && element.offsetParent) return $(element.offsetParent); while ((element = element.parentNode) && element !== document.body) { - if (Element.getStyle(element, 'position') !== 'static') { + if (Element.getStyle(element, "position") !== "static") { return isHtml(element) ? $(document.body) : $(element); } } @@ -3707,13 +3956,13 @@ Element.addMethods({ return $(document.body); } - function cumulativeOffset(element) { element = $(element); - var valueT = 0, valueL = 0; + var valueT = 0, + valueL = 0; if (element.parentNode) { do { - valueT += element.offsetTop || 0; + valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); @@ -3726,28 +3975,30 @@ Element.addMethods({ var layout = element.getLayout(); - var valueT = 0, valueL = 0; + var valueT = 0, + valueL = 0; do { - valueT += element.offsetTop || 0; + valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; if (element) { if (isBody(element)) break; - var p = Element.getStyle(element, 'position'); - if (p !== 'static') break; + var p = Element.getStyle(element, "position"); + if (p !== "static") break; } } while (element); - valueL -= layout.get('margin-top'); - valueT -= layout.get('margin-left'); + valueL -= layout.get("margin-top"); + valueT -= layout.get("margin-left"); return new Element.Offset(valueL, valueT); } function cumulativeScrollOffset(element) { - var valueT = 0, valueL = 0; + var valueT = 0, + valueL = 0; do { - valueT += element.scrollTop || 0; + valueT += element.scrollTop || 0; valueL += element.scrollLeft || 0; element = element.parentNode; } while (element); @@ -3756,53 +4007,58 @@ Element.addMethods({ function viewportOffset(forElement) { element = $(element); - var valueT = 0, valueL = 0, docBody = document.body; + var valueT = 0, + valueL = 0, + docBody = document.body; var element = forElement; do { - valueT += element.offsetTop || 0; + valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; - if (element.offsetParent == docBody && - Element.getStyle(element, 'position') == 'absolute') break; - } while (element = element.offsetParent); + if ( + element.offsetParent == docBody && + Element.getStyle(element, "position") == "absolute" + ) + break; + } while ((element = element.offsetParent)); element = forElement; do { if (element != docBody) { - valueT -= element.scrollTop || 0; + valueT -= element.scrollTop || 0; valueL -= element.scrollLeft || 0; } - } while (element = element.parentNode); + } while ((element = element.parentNode)); return new Element.Offset(valueL, valueT); } function absolutize(element) { element = $(element); - if (Element.getStyle(element, 'position') === 'absolute') { + if (Element.getStyle(element, "position") === "absolute") { return element; } var offsetParent = getOffsetParent(element); var eOffset = element.viewportOffset(), - pOffset = offsetParent.viewportOffset(); + pOffset = offsetParent.viewportOffset(); var offset = eOffset.relativeTo(pOffset); var layout = element.getLayout(); - element.store('prototype_absolutize_original_styles', { - left: element.getStyle('left'), - top: element.getStyle('top'), - width: element.getStyle('width'), - height: element.getStyle('height') + element.store("prototype_absolutize_original_styles", { + left: element.getStyle("left"), + top: element.getStyle("top"), + width: element.getStyle("width"), + height: element.getStyle("height"), }); element.setStyle({ - position: 'absolute', - top: offset.top + 'px', - left: offset.left + 'px', - width: layout.get('width') + 'px', - height: layout.get('height') + 'px' + position: "absolute", + top: offset.top + "px", + left: offset.left + "px", + width: layout.get("width") + "px", + height: layout.get("height") + "px", }); return element; @@ -3810,59 +4066,64 @@ Element.addMethods({ function relativize(element) { element = $(element); - if (Element.getStyle(element, 'position') === 'relative') { + if (Element.getStyle(element, "position") === "relative") { return element; } - var originalStyles = - element.retrieve('prototype_absolutize_original_styles'); + var originalStyles = element.retrieve( + "prototype_absolutize_original_styles" + ); if (originalStyles) element.setStyle(originalStyles); return element; } if (Prototype.Browser.IE) { - getOffsetParent = getOffsetParent.wrap( - function(proceed, element) { - element = $(element); + getOffsetParent = getOffsetParent.wrap(function (proceed, element) { + element = $(element); - if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) - return $(document.body); + if ( + isDocument(element) || + isDetached(element) || + isBody(element) || + isHtml(element) + ) + return $(document.body); - var position = element.getStyle('position'); - if (position !== 'static') return proceed(element); + var position = element.getStyle("position"); + if (position !== "static") return proceed(element); - element.setStyle({ position: 'relative' }); - var value = proceed(element); - element.setStyle({ position: position }); - return value; - } - ); + element.setStyle({ position: "relative" }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + }); - positionedOffset = positionedOffset.wrap(function(proceed, element) { + positionedOffset = positionedOffset.wrap(function (proceed, element) { element = $(element); if (!element.parentNode) return new Element.Offset(0, 0); - var position = element.getStyle('position'); - if (position !== 'static') return proceed(element); + var position = element.getStyle("position"); + if (position !== "static") return proceed(element); var offsetParent = element.getOffsetParent(); - if (offsetParent && offsetParent.getStyle('position') === 'fixed') + if (offsetParent && offsetParent.getStyle("position") === "fixed") hasLayout(offsetParent); - element.setStyle({ position: 'relative' }); + element.setStyle({ position: "relative" }); var value = proceed(element); element.setStyle({ position: position }); return value; }); } else if (Prototype.Browser.Webkit) { - cumulativeOffset = function(element) { + cumulativeOffset = function (element) { element = $(element); - var valueT = 0, valueL = 0; + var valueT = 0, + valueL = 0; do { - valueT += element.offsetTop || 0; + valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; if (element.offsetParent == document.body) - if (Element.getStyle(element, 'position') == 'absolute') break; + if (Element.getStyle(element, "position") == "absolute") break; element = element.offsetParent; } while (element); @@ -3871,26 +4132,25 @@ Element.addMethods({ }; } - Element.addMethods({ - getLayout: getLayout, - measure: measure, - getDimensions: getDimensions, - getOffsetParent: getOffsetParent, - cumulativeOffset: cumulativeOffset, - positionedOffset: positionedOffset, + getLayout: getLayout, + measure: measure, + getDimensions: getDimensions, + getOffsetParent: getOffsetParent, + cumulativeOffset: cumulativeOffset, + positionedOffset: positionedOffset, cumulativeScrollOffset: cumulativeScrollOffset, - viewportOffset: viewportOffset, - absolutize: absolutize, - relativize: relativize + viewportOffset: viewportOffset, + absolutize: absolutize, + relativize: relativize, }); function isBody(element) { - return element.nodeName.toUpperCase() === 'BODY'; + return element.nodeName.toUpperCase() === "BODY"; } function isHtml(element) { - return element.nodeName.toUpperCase() === 'HTML'; + return element.nodeName.toUpperCase() === "HTML"; } function isDocument(element) { @@ -3898,1049 +4158,1147 @@ Element.addMethods({ } function isDetached(element) { - return element !== document.body && - !Element.descendantOf(element, document.body); + return ( + element !== document.body && !Element.descendantOf(element, document.body) + ); } - if ('getBoundingClientRect' in document.documentElement) { + if ("getBoundingClientRect" in document.documentElement) { Element.addMethods({ - viewportOffset: function(element) { + viewportOffset: function (element) { element = $(element); if (isDetached(element)) return new Element.Offset(0, 0); - var rect = element.getBoundingClientRect(), - docEl = document.documentElement; - return new Element.Offset(rect.left - docEl.clientLeft, - rect.top - docEl.clientTop); - } - }); - } -})(); -window.$$ = function() { - var expression = $A(arguments).join(', '); - return Prototype.Selector.select(expression, document); -}; + var rect = element.getBoundingClientRect(), + docEl = document.documentElement; + return new Element.Offset( + rect.left - docEl.clientLeft, + rect.top - docEl.clientTop + ); + }, + }); + } +})(); +window.$$ = function () { + var expression = $A(arguments).join(", "); + return Prototype.Selector.select(expression, document); +}; + +Prototype.Selector = (function () { + function select() { + throw new Error('Method "Prototype.Selector.select" must be defined.'); + } + + function match() { + throw new Error('Method "Prototype.Selector.match" must be defined.'); + } + + function find(elements, expression, index) { + index = index || 0; + var match = Prototype.Selector.match, + length = elements.length, + matchIndex = 0, + i; + + for (i = 0; i < length; i++) { + if (match(elements[i], expression) && index == matchIndex++) { + return Element.extend(elements[i]); + } + } + } + + function extendElements(elements) { + for (var i = 0, length = elements.length; i < length; i++) { + Element.extend(elements[i]); + } + return elements; + } + + var K = Prototype.K; + + return { + select: select, + match: match, + find: find, + extendElements: Element.extend === K ? K : extendElements, + extendElement: Element.extend, + }; +})(); +/*! + * Sizzle CSS Selector Engine - v1.0 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function () { + var chunker = + /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true; + + [0, 0].sort(function () { + baseHasDuplicate = false; + return 0; + }); + + var Sizzle = function (selector, context, results, seed) { + results = results || []; + var origContext = (context = context || document); + + if (context.nodeType !== 1 && context.nodeType !== 9) { + return []; + } + + if (!selector || typeof selector !== "string") { + return results; + } + + var parts = [], + m, + set, + checkSet, + check, + mode, + extra, + prune = true, + contextXML = isXML(context), + soFar = selector; + + while ((chunker.exec(""), (m = chunker.exec(soFar))) !== null) { + soFar = m[3]; + + parts.push(m[1]); + + if (m[2]) { + extra = m[3]; + break; + } + } + + if (parts.length > 1 && origPOS.exec(selector)) { + if (parts.length === 2 && Expr.relative[parts[0]]) { + set = posProcess(parts[0] + parts[1], context); + } else { + set = Expr.relative[parts[0]] + ? [context] + : Sizzle(parts.shift(), context); + + while (parts.length) { + selector = parts.shift(); + + if (Expr.relative[selector]) selector += parts.shift(); + + set = posProcess(selector, set); + } + } + } else { + if ( + !seed && + parts.length > 1 && + context.nodeType === 9 && + !contextXML && + Expr.match.ID.test(parts[0]) && + !Expr.match.ID.test(parts[parts.length - 1]) + ) { + var ret = Sizzle.find(parts.shift(), context, contextXML); + context = ret.expr ? Sizzle.filter(ret.expr, ret.set)[0] : ret.set[0]; + } + + if (context) { + var ret = seed + ? { expr: parts.pop(), set: makeArray(seed) } + : Sizzle.find( + parts.pop(), + parts.length === 1 && + (parts[0] === "~" || parts[0] === "+") && + context.parentNode + ? context.parentNode + : context, + contextXML + ); + set = ret.expr ? Sizzle.filter(ret.expr, ret.set) : ret.set; + + if (parts.length > 0) { + checkSet = makeArray(set); + } else { + prune = false; + } + + while (parts.length) { + var cur = parts.pop(), + pop = cur; + + if (!Expr.relative[cur]) { + cur = ""; + } else { + pop = parts.pop(); + } + + if (pop == null) { + pop = context; + } + + Expr.relative[cur](checkSet, pop, contextXML); + } + } else { + checkSet = parts = []; + } + } + + if (!checkSet) { + checkSet = set; + } + + if (!checkSet) { + throw "Syntax error, unrecognized expression: " + (cur || selector); + } + + if (toString.call(checkSet) === "[object Array]") { + if (!prune) { + results.push.apply(results, checkSet); + } else if (context && context.nodeType === 1) { + for (var i = 0; checkSet[i] != null; i++) { + if ( + checkSet[i] && + (checkSet[i] === true || + (checkSet[i].nodeType === 1 && contains(context, checkSet[i]))) + ) { + results.push(set[i]); + } + } + } else { + for (var i = 0; checkSet[i] != null; i++) { + if (checkSet[i] && checkSet[i].nodeType === 1) { + results.push(set[i]); + } + } + } + } else { + makeArray(checkSet, results); + } + + if (extra) { + Sizzle(extra, origContext, results, seed); + Sizzle.uniqueSort(results); + } + + return results; + }; + + Sizzle.uniqueSort = function (results) { + if (sortOrder) { + hasDuplicate = baseHasDuplicate; + results.sort(sortOrder); + + if (hasDuplicate) { + for (var i = 1; i < results.length; i++) { + if (results[i] === results[i - 1]) { + results.splice(i--, 1); + } + } + } + } + + return results; + }; + + Sizzle.matches = function (expr, set) { + return Sizzle(expr, null, null, set); + }; + + Sizzle.find = function (expr, context, isXML) { + var set, match; + + if (!expr) { + return []; + } + + for (var i = 0, l = Expr.order.length; i < l; i++) { + var type = Expr.order[i], + match; + + if ((match = Expr.leftMatch[type].exec(expr))) { + var left = match[1]; + match.splice(1, 1); + + if (left.substr(left.length - 1) !== "\\") { + match[1] = (match[1] || "").replace(/\\/g, ""); + set = Expr.find[type](match, context, isXML); + if (set != null) { + expr = expr.replace(Expr.match[type], ""); + break; + } + } + } + } + + if (!set) { + set = context.getElementsByTagName("*"); + } + + return { set: set, expr: expr }; + }; + + Sizzle.filter = function (expr, set, inplace, not) { + var old = expr, + result = [], + curLoop = set, + match, + anyFound, + isXMLFilter = set && set[0] && isXML(set[0]); + + while (expr && set.length) { + for (var type in Expr.filter) { + if ((match = Expr.match[type].exec(expr)) != null) { + var filter = Expr.filter[type], + found, + item; + anyFound = false; + + if (curLoop == result) { + result = []; + } + + if (Expr.preFilter[type]) { + match = Expr.preFilter[type]( + match, + curLoop, + inplace, + result, + not, + isXMLFilter + ); + + if (!match) { + anyFound = found = true; + } else if (match === true) { + continue; + } + } + + if (match) { + for (var i = 0; (item = curLoop[i]) != null; i++) { + if (item) { + found = filter(item, match, i, curLoop); + var pass = not ^ !!found; + + if (inplace && found != null) { + if (pass) { + anyFound = true; + } else { + curLoop[i] = false; + } + } else if (pass) { + result.push(item); + anyFound = true; + } + } + } + } + + if (found !== undefined) { + if (!inplace) { + curLoop = result; + } + + expr = expr.replace(Expr.match[type], ""); + + if (!anyFound) { + return []; + } + + break; + } + } + } + + if (expr == old) { + if (anyFound == null) { + throw "Syntax error, unrecognized expression: " + expr; + } else { + break; + } + } + + old = expr; + } + + return curLoop; + }; + + var Expr = (Sizzle.selectors = { + order: ["ID", "NAME", "TAG"], + match: { + ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, + PSEUDO: + /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/, + }, + leftMatch: {}, + attrMap: { + class: "className", + for: "htmlFor", + }, + attrHandle: { + href: function (elem) { + return elem.getAttribute("href"); + }, + }, + relative: { + "+": function (checkSet, part, isXML) { + var isPartStr = typeof part === "string", + isTag = isPartStr && !/\W/.test(part), + isPartStrNotTag = isPartStr && !isTag; + + if (isTag && !isXML) { + part = part.toUpperCase(); + } + + for (var i = 0, l = checkSet.length, elem; i < l; i++) { + if ((elem = checkSet[i])) { + while ((elem = elem.previousSibling) && elem.nodeType !== 1) {} + + checkSet[i] = + isPartStrNotTag || (elem && elem.nodeName === part) + ? elem || false + : elem === part; + } + } + + if (isPartStrNotTag) { + Sizzle.filter(part, checkSet, true); + } + }, + ">": function (checkSet, part, isXML) { + var isPartStr = typeof part === "string"; + + if (isPartStr && !/\W/.test(part)) { + part = isXML ? part : part.toUpperCase(); + + for (var i = 0, l = checkSet.length; i < l; i++) { + var elem = checkSet[i]; + if (elem) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName === part ? parent : false; + } + } + } else { + for (var i = 0, l = checkSet.length; i < l; i++) { + var elem = checkSet[i]; + if (elem) { + checkSet[i] = isPartStr + ? elem.parentNode + : elem.parentNode === part; + } + } + + if (isPartStr) { + Sizzle.filter(part, checkSet, true); + } + } + }, + "": function (checkSet, part, isXML) { + var doneName = done++, + checkFn = dirCheck; + + if (!/\W/.test(part)) { + var nodeCheck = (part = isXML ? part : part.toUpperCase()); + checkFn = dirNodeCheck; + } + + checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); + }, + "~": function (checkSet, part, isXML) { + var doneName = done++, + checkFn = dirCheck; + + if (typeof part === "string" && !/\W/.test(part)) { + var nodeCheck = (part = isXML ? part : part.toUpperCase()); + checkFn = dirNodeCheck; + } + + checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); + }, + }, + find: { + ID: function (match, context, isXML) { + if (typeof context.getElementById !== "undefined" && !isXML) { + var m = context.getElementById(match[1]); + return m ? [m] : []; + } + }, + NAME: function (match, context, isXML) { + if (typeof context.getElementsByName !== "undefined") { + var ret = [], + results = context.getElementsByName(match[1]); + + for (var i = 0, l = results.length; i < l; i++) { + if (results[i].getAttribute("name") === match[1]) { + ret.push(results[i]); + } + } + + return ret.length === 0 ? null : ret; + } + }, + TAG: function (match, context) { + return context.getElementsByTagName(match[1]); + }, + }, + preFilter: { + CLASS: function (match, curLoop, inplace, result, not, isXML) { + match = " " + match[1].replace(/\\/g, "") + " "; + + if (isXML) { + return match; + } + + for (var i = 0, elem; (elem = curLoop[i]) != null; i++) { + if (elem) { + if ( + not ^ + (elem.className && + (" " + elem.className + " ").indexOf(match) >= 0) + ) { + if (!inplace) result.push(elem); + } else if (inplace) { + curLoop[i] = false; + } + } + } + + return false; + }, + ID: function (match) { + return match[1].replace(/\\/g, ""); + }, + TAG: function (match, curLoop) { + for (var i = 0; curLoop[i] === false; i++) {} + return curLoop[i] && isXML(curLoop[i]) + ? match[1] + : match[1].toUpperCase(); + }, + CHILD: function (match) { + if (match[1] == "nth") { + var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( + (match[2] == "even" && "2n") || + (match[2] == "odd" && "2n+1") || + (!/\D/.test(match[2]) && "0n+" + match[2]) || + match[2] + ); + + match[2] = test[1] + (test[2] || 1) - 0; + match[3] = test[3] - 0; + } + + match[0] = done++; + + return match; + }, + ATTR: function (match, curLoop, inplace, result, not, isXML) { + var name = match[1].replace(/\\/g, ""); + + if (!isXML && Expr.attrMap[name]) { + match[1] = Expr.attrMap[name]; + } + + if (match[2] === "~=") { + match[4] = " " + match[4] + " "; + } + + return match; + }, + PSEUDO: function (match, curLoop, inplace, result, not) { + if (match[1] === "not") { + if ( + (chunker.exec(match[3]) || "").length > 1 || + /^\w/.test(match[3]) + ) { + match[3] = Sizzle(match[3], null, null, curLoop); + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + if (!inplace) { + result.push.apply(result, ret); + } + return false; + } + } else if ( + Expr.match.POS.test(match[0]) || + Expr.match.CHILD.test(match[0]) + ) { + return true; + } + + return match; + }, + POS: function (match) { + match.unshift(true); + return match; + }, + }, + filters: { + enabled: function (elem) { + return elem.disabled === false && elem.type !== "hidden"; + }, + disabled: function (elem) { + return elem.disabled === true; + }, + checked: function (elem) { + return elem.checked === true; + }, + selected: function (elem) { + elem.parentNode.selectedIndex; + return elem.selected === true; + }, + parent: function (elem) { + return !!elem.firstChild; + }, + empty: function (elem) { + return !elem.firstChild; + }, + has: function (elem, i, match) { + return !!Sizzle(match[3], elem).length; + }, + header: function (elem) { + return /h\d/i.test(elem.nodeName); + }, + text: function (elem) { + return "text" === elem.type; + }, + radio: function (elem) { + return "radio" === elem.type; + }, + checkbox: function (elem) { + return "checkbox" === elem.type; + }, + file: function (elem) { + return "file" === elem.type; + }, + password: function (elem) { + return "password" === elem.type; + }, + submit: function (elem) { + return "submit" === elem.type; + }, + image: function (elem) { + return "image" === elem.type; + }, + reset: function (elem) { + return "reset" === elem.type; + }, + button: function (elem) { + return ( + "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON" + ); + }, + input: function (elem) { + return /input|select|textarea|button/i.test(elem.nodeName); + }, + }, + setFilters: { + first: function (elem, i) { + return i === 0; + }, + last: function (elem, i, match, array) { + return i === array.length - 1; + }, + even: function (elem, i) { + return i % 2 === 0; + }, + odd: function (elem, i) { + return i % 2 === 1; + }, + lt: function (elem, i, match) { + return i < match[3] - 0; + }, + gt: function (elem, i, match) { + return i > match[3] - 0; + }, + nth: function (elem, i, match) { + return match[3] - 0 == i; + }, + eq: function (elem, i, match) { + return match[3] - 0 == i; + }, + }, + filter: { + PSEUDO: function (elem, match, i, array) { + var name = match[1], + filter = Expr.filters[name]; + + if (filter) { + return filter(elem, i, match, array); + } else if (name === "contains") { + return ( + (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0 + ); + } else if (name === "not") { + var not = match[3]; + + for (var i = 0, l = not.length; i < l; i++) { + if (not[i] === elem) { + return false; + } + } + + return true; + } + }, + CHILD: function (elem, match) { + var type = match[1], + node = elem; + switch (type) { + case "only": + case "first": + while ((node = node.previousSibling)) { + if (node.nodeType === 1) return false; + } + if (type == "first") return true; + node = elem; + case "last": + while ((node = node.nextSibling)) { + if (node.nodeType === 1) return false; + } + return true; + case "nth": + var first = match[2], + last = match[3]; -Prototype.Selector = (function() { + if (first == 1 && last == 0) { + return true; + } - function select() { - throw new Error('Method "Prototype.Selector.select" must be defined.'); - } + var doneName = match[0], + parent = elem.parentNode; + + if (parent && (parent.sizcache !== doneName || !elem.nodeIndex)) { + var count = 0; + for (node = parent.firstChild; node; node = node.nextSibling) { + if (node.nodeType === 1) { + node.nodeIndex = ++count; + } + } + parent.sizcache = doneName; + } - function match() { - throw new Error('Method "Prototype.Selector.match" must be defined.'); - } + var diff = elem.nodeIndex - last; + if (first == 0) { + return diff == 0; + } else { + return diff % first == 0 && diff / first >= 0; + } + } + }, + ID: function (elem, match) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + TAG: function (elem, match) { + return ( + (match === "*" && elem.nodeType === 1) || elem.nodeName === match + ); + }, + CLASS: function (elem, match) { + return ( + (" " + (elem.className || elem.getAttribute("class")) + " ").indexOf( + match + ) > -1 + ); + }, + ATTR: function (elem, match) { + var name = match[1], + result = Expr.attrHandle[name] + ? Expr.attrHandle[name](elem) + : elem[name] != null + ? elem[name] + : elem.getAttribute(name), + value = result + "", + type = match[2], + check = match[4]; + + return result == null + ? type === "!=" + : type === "=" + ? value === check + : type === "*=" + ? value.indexOf(check) >= 0 + : type === "~=" + ? (" " + value + " ").indexOf(check) >= 0 + : !check + ? value && result !== false + : type === "!=" + ? value != check + : type === "^=" + ? value.indexOf(check) === 0 + : type === "$=" + ? value.substr(value.length - check.length) === check + : type === "|=" + ? value === check || value.substr(0, check.length + 1) === check + "-" + : false; + }, + POS: function (elem, match, i, array) { + var name = match[2], + filter = Expr.setFilters[name]; - function find(elements, expression, index) { - index = index || 0; - var match = Prototype.Selector.match, length = elements.length, matchIndex = 0, i; + if (filter) { + return filter(elem, i, match, array); + } + }, + }, + }); - for (i = 0; i < length; i++) { - if (match(elements[i], expression) && index == matchIndex++) { - return Element.extend(elements[i]); - } - } - } + var origPOS = Expr.match.POS; - function extendElements(elements) { - for (var i = 0, length = elements.length; i < length; i++) { - Element.extend(elements[i]); - } - return elements; + for (var type in Expr.match) { + Expr.match[type] = new RegExp( + Expr.match[type].source + /(?![^\[]*\])(?![^\(]*\))/.source + ); + Expr.leftMatch[type] = new RegExp( + /(^(?:.|\r|\n)*?)/.source + Expr.match[type].source + ); } + var makeArray = function (array, results) { + array = Array.prototype.slice.call(array, 0); - var K = Prototype.K; + if (results) { + results.push.apply(results, array); + return results; + } - return { - select: select, - match: match, - find: find, - extendElements: (Element.extend === K) ? K : extendElements, - extendElement: Element.extend + return array; }; -})(); -/*! - * Sizzle CSS Selector Engine - v1.0 - * Copyright 2009, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true; - -[0, 0].sort(function(){ - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function(selector, context, results, seed) { - results = results || []; - var origContext = context = context || document; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context), - soFar = selector; - - while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) - selector += parts.shift(); - - set = posProcess( selector, set ); - } - } - } else { - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - var ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; - } - - if ( context ) { - var ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray(set); - } else { - prune = false; - } - - while ( parts.length ) { - var cur = parts.pop(), pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - throw "Syntax error, unrecognized expression: " + (cur || selector); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - } else if ( context && context.nodeType === 1 ) { - for ( var i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - } else { - for ( var i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function(results){ - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort(sortOrder); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[i-1] ) { - results.splice(i--, 1); - } - } - } - } - - return results; -}; - -Sizzle.matches = function(expr, set){ - return Sizzle(expr, null, null, set); -}; -Sizzle.find = function(expr, context, isXML){ - var set, match; + try { + Array.prototype.slice.call(document.documentElement.childNodes, 0); + } catch (e) { + makeArray = function (array, results) { + var ret = results || []; - if ( !expr ) { - return []; - } + if (toString.call(array) === "[object Array]") { + Array.prototype.push.apply(ret, array); + } else { + if (typeof array.length === "number") { + for (var i = 0, l = array.length; i < l; i++) { + ret.push(array[i]); + } + } else { + for (var i = 0; array[i]; i++) { + ret.push(array[i]); + } + } + } - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var type = Expr.order[i], match; + return ret; + }; + } - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice(1,1); + var sortOrder; - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace(/\\/g, ""); - set = Expr.find[ type ]( match, context, isXML ); - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } + if (document.documentElement.compareDocumentPosition) { + sortOrder = function (a, b) { + if (!a.compareDocumentPosition || !b.compareDocumentPosition) { + if (a == b) { + hasDuplicate = true; + } + return 0; + } - if ( !set ) { - set = context.getElementsByTagName("*"); - } + var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; + if (ret === 0) { + hasDuplicate = true; + } + return ret; + }; + } else if ("sourceIndex" in document.documentElement) { + sortOrder = function (a, b) { + if (!a.sourceIndex || !b.sourceIndex) { + if (a == b) { + hasDuplicate = true; + } + return 0; + } - return {set: set, expr: expr}; -}; + var ret = a.sourceIndex - b.sourceIndex; + if (ret === 0) { + hasDuplicate = true; + } + return ret; + }; + } else if (document.createRange) { + sortOrder = function (a, b) { + if (!a.ownerDocument || !b.ownerDocument) { + if (a == b) { + hasDuplicate = true; + } + return 0; + } -Sizzle.filter = function(expr, set, inplace, not){ - var old = expr, result = [], curLoop = set, match, anyFound, - isXMLFilter = set && set[0] && isXML(set[0]); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.match[ type ].exec( expr )) != null ) { - var filter = Expr.filter[ type ], found, item; - anyFound = false; - - if ( curLoop == result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - } else { - curLoop[i] = false; - } - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - if ( expr == old ) { - if ( anyFound == null ) { - throw "Syntax error, unrecognized expression: " + expr; - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; + var aRange = a.ownerDocument.createRange(), + bRange = b.ownerDocument.createRange(); + aRange.setStart(a, 0); + aRange.setEnd(a, 0); + bRange.setStart(b, 0); + bRange.setEnd(b, 0); + var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); + if (ret === 0) { + hasDuplicate = true; + } + return ret; + }; + } -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - match: { - ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ - }, - leftMatch: {}, - attrMap: { - "class": "className", - "for": "htmlFor" - }, - attrHandle: { - href: function(elem){ - return elem.getAttribute("href"); - } - }, - relative: { - "+": function(checkSet, part, isXML){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !/\W/.test(part), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag && !isXML ) { - part = part.toUpperCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - ">": function(checkSet, part, isXML){ - var isPartStr = typeof part === "string"; - - if ( isPartStr && !/\W/.test(part) ) { - part = isXML ? part : part.toUpperCase(); - - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName === part ? parent : false; - } - } - } else { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - "": function(checkSet, part, isXML){ - var doneName = done++, checkFn = dirCheck; - - if ( !/\W/.test(part) ) { - var nodeCheck = part = isXML ? part : part.toUpperCase(); - checkFn = dirNodeCheck; - } - - checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); - }, - "~": function(checkSet, part, isXML){ - var doneName = done++, checkFn = dirCheck; - - if ( typeof part === "string" && !/\W/.test(part) ) { - var nodeCheck = part = isXML ? part : part.toUpperCase(); - checkFn = dirNodeCheck; - } - - checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); - } - }, - find: { - ID: function(match, context, isXML){ - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - return m ? [m] : []; - } - }, - NAME: function(match, context, isXML){ - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], results = context.getElementsByName(match[1]); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - TAG: function(match, context){ - return context.getElementsByTagName(match[1]); - } - }, - preFilter: { - CLASS: function(match, curLoop, inplace, result, not, isXML){ - match = " " + match[1].replace(/\\/g, "") + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) { - if ( !inplace ) - result.push( elem ); - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - ID: function(match){ - return match[1].replace(/\\/g, ""); - }, - TAG: function(match, curLoop){ - for ( var i = 0; curLoop[i] === false; i++ ){} - return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); - }, - CHILD: function(match){ - if ( match[1] == "nth" ) { - var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( - match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - - match[0] = done++; - - return match; - }, - ATTR: function(match, curLoop, inplace, result, not, isXML){ - var name = match[1].replace(/\\/g, ""); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - PSEUDO: function(match, curLoop, inplace, result, not){ - if ( match[1] === "not" ) { - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - if ( !inplace ) { - result.push.apply( result, ret ); - } - return false; - } - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - POS: function(match){ - match.unshift( true ); - return match; - } - }, - filters: { - enabled: function(elem){ - return elem.disabled === false && elem.type !== "hidden"; - }, - disabled: function(elem){ - return elem.disabled === true; - }, - checked: function(elem){ - return elem.checked === true; - }, - selected: function(elem){ - elem.parentNode.selectedIndex; - return elem.selected === true; - }, - parent: function(elem){ - return !!elem.firstChild; - }, - empty: function(elem){ - return !elem.firstChild; - }, - has: function(elem, i, match){ - return !!Sizzle( match[3], elem ).length; - }, - header: function(elem){ - return /h\d/i.test( elem.nodeName ); - }, - text: function(elem){ - return "text" === elem.type; - }, - radio: function(elem){ - return "radio" === elem.type; - }, - checkbox: function(elem){ - return "checkbox" === elem.type; - }, - file: function(elem){ - return "file" === elem.type; - }, - password: function(elem){ - return "password" === elem.type; - }, - submit: function(elem){ - return "submit" === elem.type; - }, - image: function(elem){ - return "image" === elem.type; - }, - reset: function(elem){ - return "reset" === elem.type; - }, - button: function(elem){ - return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; - }, - input: function(elem){ - return /input|select|textarea|button/i.test(elem.nodeName); - } - }, - setFilters: { - first: function(elem, i){ - return i === 0; - }, - last: function(elem, i, match, array){ - return i === array.length - 1; - }, - even: function(elem, i){ - return i % 2 === 0; - }, - odd: function(elem, i){ - return i % 2 === 1; - }, - lt: function(elem, i, match){ - return i < match[3] - 0; - }, - gt: function(elem, i, match){ - return i > match[3] - 0; - }, - nth: function(elem, i, match){ - return match[3] - 0 == i; - }, - eq: function(elem, i, match){ - return match[3] - 0 == i; - } - }, - filter: { - PSEUDO: function(elem, match, i, array){ - var name = match[1], filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0; - } else if ( name === "not" ) { - var not = match[3]; - - for ( var i = 0, l = not.length; i < l; i++ ) { - if ( not[i] === elem ) { - return false; - } - } - - return true; - } - }, - CHILD: function(elem, match){ - var type = match[1], node = elem; - switch (type) { - case 'only': - case 'first': - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) return false; - } - if ( type == 'first') return true; - node = elem; - case 'last': - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) return false; - } - return true; - case 'nth': - var first = match[2], last = match[3]; - - if ( first == 1 && last == 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - if ( first == 0 ) { - return diff == 0; - } else { - return ( diff % first == 0 && diff / first >= 0 ); - } - } - }, - ID: function(elem, match){ - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - TAG: function(elem, match){ - return (match === "*" && elem.nodeType === 1) || elem.nodeName === match; - }, - CLASS: function(elem, match){ - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - ATTR: function(elem, match){ - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value != check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - POS: function(elem, match, i, array){ - var name = match[2], filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; + (function () { + var form = document.createElement("div"), + id = "script" + new Date().getTime(); + form.innerHTML = ""; + + var root = document.documentElement; + root.insertBefore(form, root.firstChild); + + if (!!document.getElementById(id)) { + Expr.find.ID = function (match, context, isXML) { + if (typeof context.getElementById !== "undefined" && !isXML) { + var m = context.getElementById(match[1]); + return m + ? m.id === match[1] || + (typeof m.getAttributeNode !== "undefined" && + m.getAttributeNode("id").nodeValue === match[1]) + ? [m] + : undefined + : []; + } + }; -var origPOS = Expr.match.POS; + Expr.filter.ID = function (elem, match) { + var node = + typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source ); -} + root.removeChild(form); + root = form = null; // release memory in IE + })(); -var makeArray = function(array, results) { - array = Array.prototype.slice.call( array, 0 ); + (function () { + var div = document.createElement("div"); + div.appendChild(document.createComment("")); - if ( results ) { - results.push.apply( results, array ); - return results; - } + if (div.getElementsByTagName("*").length > 0) { + Expr.find.TAG = function (match, context) { + var results = context.getElementsByTagName(match[1]); - return array; -}; + if (match[1] === "*") { + var tmp = []; -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 ); - -} catch(e){ - makeArray = function(array, results) { - var ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - } else { - if ( typeof array.length === "number" ) { - for ( var i = 0, l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - } else { - for ( var i = 0; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} + for (var i = 0; results[i]; i++) { + if (results[i].nodeType === 1) { + tmp.push(results[i]); + } + } -var sortOrder; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - if ( a == b ) { - hasDuplicate = true; - } - return 0; - } - - var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; - if ( ret === 0 ) { - hasDuplicate = true; - } - return ret; - }; -} else if ( "sourceIndex" in document.documentElement ) { - sortOrder = function( a, b ) { - if ( !a.sourceIndex || !b.sourceIndex ) { - if ( a == b ) { - hasDuplicate = true; - } - return 0; - } - - var ret = a.sourceIndex - b.sourceIndex; - if ( ret === 0 ) { - hasDuplicate = true; - } - return ret; - }; -} else if ( document.createRange ) { - sortOrder = function( a, b ) { - if ( !a.ownerDocument || !b.ownerDocument ) { - if ( a == b ) { - hasDuplicate = true; - } - return 0; - } - - var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); - aRange.setStart(a, 0); - aRange.setEnd(a, 0); - bRange.setStart(b, 0); - bRange.setEnd(b, 0); - var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); - if ( ret === 0 ) { - hasDuplicate = true; - } - return ret; - }; -} + results = tmp; + } -(function(){ - var form = document.createElement("div"), - id = "script" + (new Date).getTime(); - form.innerHTML = ""; - - var root = document.documentElement; - root.insertBefore( form, root.firstChild ); - - if ( !!document.getElementById( id ) ) { - Expr.find.ID = function(match, context, isXML){ - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; - } - }; - - Expr.filter.ID = function(elem, match){ - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - root = form = null; // release memory in IE -})(); + return results; + }; + } -(function(){ + div.innerHTML = ""; + if ( + div.firstChild && + typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" + ) { + Expr.attrHandle.href = function (elem) { + return elem.getAttribute("href", 2); + }; + } - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); + div = null; // release memory in IE + })(); - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function(match, context){ - var results = context.getElementsByTagName(match[1]); + if (document.querySelectorAll) + (function () { + var oldSizzle = Sizzle, + div = document.createElement("div"); + div.innerHTML = "

"; - if ( match[1] === "*" ) { - var tmp = []; + if (div.querySelectorAll && div.querySelectorAll(".TEST").length === 0) { + return; + } - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } + Sizzle = function (query, context, extra, seed) { + context = context || document; - results = tmp; - } + if (!seed && context.nodeType === 9 && !isXML(context)) { + try { + return makeArray(context.querySelectorAll(query), extra); + } catch (e) {} + } - return results; - }; - } + return oldSizzle(query, context, extra, seed); + }; - div.innerHTML = ""; - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - Expr.attrHandle.href = function(elem){ - return elem.getAttribute("href", 2); - }; - } + for (var prop in oldSizzle) { + Sizzle[prop] = oldSizzle[prop]; + } - div = null; // release memory in IE -})(); + div = null; // release memory in IE + })(); -if ( document.querySelectorAll ) (function(){ - var oldSizzle = Sizzle, div = document.createElement("div"); - div.innerHTML = "

"; + if ( + document.getElementsByClassName && + document.documentElement.getElementsByClassName + ) + (function () { + var div = document.createElement("div"); + div.innerHTML = "
"; - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } + if (div.getElementsByClassName("e").length === 0) return; - Sizzle = function(query, context, extra, seed){ - context = context || document; + div.lastChild.className = "e"; - if ( !seed && context.nodeType === 9 && !isXML(context) ) { - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(e){} - } + if (div.getElementsByClassName("e").length === 1) return; - return oldSizzle(query, context, extra, seed); - }; + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function (match, context, isXML) { + if (typeof context.getElementsByClassName !== "undefined" && !isXML) { + return context.getElementsByClassName(match[1]); + } + }; - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } + div = null; // release memory in IE + })(); - div = null; // release memory in IE -})(); + function dirNodeCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) { + var sibDir = dir == "previousSibling" && !isXML; + for (var i = 0, l = checkSet.length; i < l; i++) { + var elem = checkSet[i]; + if (elem) { + if (sibDir && elem.nodeType === 1) { + elem.sizcache = doneName; + elem.sizset = i; + } + elem = elem[dir]; + var match = false; -if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){ - var div = document.createElement("div"); - div.innerHTML = "
"; + while (elem) { + if (elem.sizcache === doneName) { + match = checkSet[elem.sizset]; + break; + } - if ( div.getElementsByClassName("e").length === 0 ) - return; + if (elem.nodeType === 1 && !isXML) { + elem.sizcache = doneName; + elem.sizset = i; + } - div.lastChild.className = "e"; + if (elem.nodeName === cur) { + match = elem; + break; + } - if ( div.getElementsByClassName("e").length === 1 ) - return; + elem = elem[dir]; + } - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function(match, context, isXML) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; + checkSet[i] = match; + } + } + } - div = null; // release memory in IE -})(); + function dirCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) { + var sibDir = dir == "previousSibling" && !isXML; + for (var i = 0, l = checkSet.length; i < l; i++) { + var elem = checkSet[i]; + if (elem) { + if (sibDir && elem.nodeType === 1) { + elem.sizcache = doneName; + elem.sizset = i; + } + elem = elem[dir]; + var match = false; -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - var sibDir = dir == "previousSibling" && !isXML; - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - if ( sibDir && elem.nodeType === 1 ){ - elem.sizcache = doneName; - elem.sizset = i; - } - elem = elem[dir]; - var match = false; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} + while (elem) { + if (elem.sizcache === doneName) { + match = checkSet[elem.sizset]; + break; + } -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - var sibDir = dir == "previousSibling" && !isXML; - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - if ( elem ) { - if ( sibDir && elem.nodeType === 1 ) { - elem.sizcache = doneName; - elem.sizset = i; - } - elem = elem[dir]; - var match = false; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} + if (elem.nodeType === 1) { + if (!isXML) { + elem.sizcache = doneName; + elem.sizset = i; + } + if (typeof cur !== "string") { + if (elem === cur) { + match = true; + break; + } + } else if (Sizzle.filter(cur, [elem]).length > 0) { + match = elem; + break; + } + } -var contains = document.compareDocumentPosition ? function(a, b){ - return a.compareDocumentPosition(b) & 16; -} : function(a, b){ - return a !== b && (a.contains ? a.contains(b) : true); -}; + elem = elem[dir]; + } -var isXML = function(elem){ - return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || - !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML"; -}; + checkSet[i] = match; + } + } + } -var posProcess = function(selector, context){ - var tmpSet = [], later = "", match, - root = context.nodeType ? [context] : context; + var contains = document.compareDocumentPosition + ? function (a, b) { + return a.compareDocumentPosition(b) & 16; + } + : function (a, b) { + return a !== b && (a.contains ? a.contains(b) : true); + }; - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } + var isXML = function (elem) { + return ( + (elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML") || + (!!elem.ownerDocument && + elem.ownerDocument.documentElement.nodeName !== "HTML") + ); + }; - selector = Expr.relative[selector] ? selector + "*" : selector; + var posProcess = function (selector, context) { + var tmpSet = [], + later = "", + match, + root = context.nodeType ? [context] : context; - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } + while ((match = Expr.match.PSEUDO.exec(selector))) { + later += match[0]; + selector = selector.replace(Expr.match.PSEUDO, ""); + } - return Sizzle.filter( later, tmpSet ); -}; + selector = Expr.relative[selector] ? selector + "*" : selector; + for (var i = 0, l = root.length; i < l; i++) { + Sizzle(selector, root[i], tmpSet); + } -window.Sizzle = Sizzle; + return Sizzle.filter(later, tmpSet); + }; + window.Sizzle = Sizzle; })(); Prototype._original_property = window.Sizzle; -;(function(engine) { +(function (engine) { var extendElements = Prototype.Selector.extendElements; function select(selector, scope) { @@ -4960,20 +5318,25 @@ window.Sizzle = Prototype._original_property; delete Prototype._original_property; var Form = { - reset: function(form) { + reset: function (form) { form = $(form); form.reset(); return form; }, - serializeElements: function(elements, options) { - if (typeof options != 'object') options = { hash: !!options }; + serializeElements: function (elements, options) { + if (typeof options != "object") options = { hash: !!options }; else if (Object.isUndefined(options.hash)) options.hash = true; - var key, value, submitted = false, submit = options.submit, accumulator, initial; + var key, + value, + submitted = false, + submit = options.submit, + accumulator, + initial; if (options.hash) { initial = {}; - accumulator = function(result, key, value) { + accumulator = function (result, key, value) { if (key in result) { if (!Object.isArray(result[key])) result[key] = [result[key]]; result[key].push(value); @@ -4981,52 +5344,70 @@ var Form = { return result; }; } else { - initial = ''; - accumulator = function(result, key, value) { - return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value); - } + initial = ""; + accumulator = function (result, key, value) { + return ( + result + + (result ? "&" : "") + + encodeURIComponent(key) + + "=" + + encodeURIComponent(value) + ); + }; } - return elements.inject(initial, function(result, element) { + return elements.inject(initial, function (result, element) { if (!element.disabled && element.name) { - key = element.name; value = $(element).getValue(); - if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted && - submit !== false && (!submit || key == submit) && (submitted = true)))) { + key = element.name; + value = $(element).getValue(); + if ( + value != null && + element.type != "file" && + (element.type != "submit" || + (!submitted && + submit !== false && + (!submit || key == submit) && + (submitted = true))) + ) { result = accumulator(result, key, value); } } return result; }); - } + }, }; Form.Methods = { - serialize: function(form, options) { + serialize: function (form, options) { return Form.serializeElements(Form.getElements(form), options); }, - getElements: function(form) { - var elements = $(form).getElementsByTagName('*'), - element, - arr = [ ], - serializers = Form.Element.Serializers; - for (var i = 0; element = elements[i]; i++) { + getElements: function (form) { + var elements = $(form).getElementsByTagName("*"), + element, + arr = [], + serializers = Form.Element.Serializers; + for (var i = 0; (element = elements[i]); i++) { arr.push(element); } - return arr.inject([], function(elements, child) { + return arr.inject([], function (elements, child) { if (serializers[child.tagName.toLowerCase()]) elements.push(Element.extend(child)); return elements; - }) + }); }, - getInputs: function(form, typeName, name) { + getInputs: function (form, typeName, name) { form = $(form); - var inputs = form.getElementsByTagName('input'); + var inputs = form.getElementsByTagName("input"); if (!typeName && !name) return $A(inputs).map(Element.extend); - for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + for ( + var i = 0, matchingInputs = [], length = inputs.length; + i < length; + i++ + ) { var input = inputs[i]; if ((typeName && input.type != typeName) || (name && input.name != name)) continue; @@ -5036,42 +5417,52 @@ Form.Methods = { return matchingInputs; }, - disable: function(form) { + disable: function (form) { form = $(form); - Form.getElements(form).invoke('disable'); + Form.getElements(form).invoke("disable"); return form; }, - enable: function(form) { + enable: function (form) { form = $(form); - Form.getElements(form).invoke('enable'); + Form.getElements(form).invoke("enable"); return form; }, - findFirstElement: function(form) { - var elements = $(form).getElements().findAll(function(element) { - return 'hidden' != element.type && !element.disabled; - }); - var firstByIndex = elements.findAll(function(element) { - return element.hasAttribute('tabIndex') && element.tabIndex >= 0; - }).sortBy(function(element) { return element.tabIndex }).first(); - - return firstByIndex ? firstByIndex : elements.find(function(element) { - return /^(?:input|select|textarea)$/i.test(element.tagName); - }); + findFirstElement: function (form) { + var elements = $(form) + .getElements() + .findAll(function (element) { + return "hidden" != element.type && !element.disabled; + }); + var firstByIndex = elements + .findAll(function (element) { + return element.hasAttribute("tabIndex") && element.tabIndex >= 0; + }) + .sortBy(function (element) { + return element.tabIndex; + }) + .first(); + + return firstByIndex + ? firstByIndex + : elements.find(function (element) { + return /^(?:input|select|textarea)$/i.test(element.tagName); + }); }, - focusFirstElement: function(form) { + focusFirstElement: function (form) { form = $(form); var element = form.findFirstElement(); if (element) element.activate(); return form; }, - request: function(form, options) { - form = $(form), options = Object.clone(options || { }); + request: function (form, options) { + (form = $(form)), (options = Object.clone(options || {})); - var params = options.parameters, action = form.readAttribute('action') || ''; + var params = options.parameters, + action = form.readAttribute("action") || ""; if (action.blank()) action = window.location.href; options.parameters = form.serialize(true); @@ -5080,87 +5471,88 @@ Form.Methods = { Object.extend(options.parameters, params); } - if (form.hasAttribute('method') && !options.method) + if (form.hasAttribute("method") && !options.method) options.method = form.method; return new Ajax.Request(action, options); - } + }, }; /*--------------------------------------------------------------------------*/ - Form.Element = { - focus: function(element) { + focus: function (element) { $(element).focus(); return element; }, - select: function(element) { + select: function (element) { $(element).select(); return element; - } + }, }; Form.Element.Methods = { - - serialize: function(element) { + serialize: function (element) { element = $(element); if (!element.disabled && element.name) { var value = element.getValue(); if (value != undefined) { - var pair = { }; + var pair = {}; pair[element.name] = value; return Object.toQueryString(pair); } } - return ''; + return ""; }, - getValue: function(element) { + getValue: function (element) { element = $(element); var method = element.tagName.toLowerCase(); return Form.Element.Serializers[method](element); }, - setValue: function(element, value) { + setValue: function (element, value) { element = $(element); var method = element.tagName.toLowerCase(); Form.Element.Serializers[method](element, value); return element; }, - clear: function(element) { - $(element).value = ''; + clear: function (element) { + $(element).value = ""; return element; }, - present: function(element) { - return $(element).value != ''; + present: function (element) { + return $(element).value != ""; }, - activate: function(element) { + activate: function (element) { element = $(element); try { element.focus(); - if (element.select && (element.tagName.toLowerCase() != 'input' || - !(/^(?:button|reset|submit)$/i.test(element.type)))) + if ( + element.select && + (element.tagName.toLowerCase() != "input" || + !/^(?:button|reset|submit)$/i.test(element.type)) + ) element.select(); - } catch (e) { } + } catch (e) {} return element; }, - disable: function(element) { + disable: function (element) { element = $(element); element.disabled = true; return element; }, - enable: function(element) { + enable: function (element) { element = $(element); element.disabled = false; return element; - } + }, }; /*--------------------------------------------------------------------------*/ @@ -5171,11 +5563,11 @@ var $F = Form.Element.Methods.getValue; /*--------------------------------------------------------------------------*/ -Form.Element.Serializers = (function() { +Form.Element.Serializers = (function () { function input(element, value) { switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': + case "checkbox": + case "radio": return inputSelector(element, value); default: return valueSelector(element, value); @@ -5195,9 +5587,11 @@ Form.Element.Serializers = (function() { function select(element, value) { if (Object.isUndefined(value)) - return (element.type === 'select-one' ? selectOne : selectMany)(element); + return (element.type === "select-one" ? selectOne : selectMany)(element); - var opt, currentValue, single = !Object.isArray(value); + var opt, + currentValue, + single = !Object.isArray(value); for (var i = 0, length = element.length; i < length; i++) { opt = element.options[i]; currentValue = this.optionValue(opt); @@ -5206,8 +5600,7 @@ Form.Element.Serializers = (function() { opt.selected = true; return; } - } - else opt.selected = value.include(currentValue); + } else opt.selected = value.include(currentValue); } } @@ -5217,7 +5610,8 @@ Form.Element.Serializers = (function() { } function selectMany(element) { - var values, length = element.length; + var values, + length = element.length; if (!length) return null; for (var i = 0, values = []; i < length; i++) { @@ -5228,68 +5622,69 @@ Form.Element.Serializers = (function() { } function optionValue(opt) { - return Element.hasAttribute(opt, 'value') ? opt.value : opt.text; + return Element.hasAttribute(opt, "value") ? opt.value : opt.text; } return { - input: input, + input: input, inputSelector: inputSelector, - textarea: valueSelector, - select: select, - selectOne: selectOne, - selectMany: selectMany, - optionValue: optionValue, - button: valueSelector + textarea: valueSelector, + select: select, + selectOne: selectOne, + selectMany: selectMany, + optionValue: optionValue, + button: valueSelector, }; })(); /*--------------------------------------------------------------------------*/ - Abstract.TimedObserver = Class.create(PeriodicalExecuter, { - initialize: function($super, element, frequency, callback) { + initialize: function ($super, element, frequency, callback) { $super(callback, frequency); - this.element = $(element); + this.element = $(element); this.lastValue = this.getValue(); }, - execute: function() { + execute: function () { var value = this.getValue(); - if (Object.isString(this.lastValue) && Object.isString(value) ? - this.lastValue != value : String(this.lastValue) != String(value)) { + if ( + Object.isString(this.lastValue) && Object.isString(value) + ? this.lastValue != value + : String(this.lastValue) != String(value) + ) { this.callback(this.element, value); this.lastValue = value; } - } + }, }); Form.Element.Observer = Class.create(Abstract.TimedObserver, { - getValue: function() { + getValue: function () { return Form.Element.getValue(this.element); - } + }, }); Form.Observer = Class.create(Abstract.TimedObserver, { - getValue: function() { + getValue: function () { return Form.serialize(this.element); - } + }, }); /*--------------------------------------------------------------------------*/ Abstract.EventObserver = Class.create({ - initialize: function(element, callback) { - this.element = $(element); + initialize: function (element, callback) { + this.element = $(element); this.callback = callback; this.lastValue = this.getValue(); - if (this.element.tagName.toLowerCase() == 'form') + if (this.element.tagName.toLowerCase() == "form") this.registerFormCallbacks(); - else - this.registerCallback(this.element); + else this.registerCallback(this.element); }, - onElementEvent: function() { + onElementEvent: function () { var value = this.getValue(); if (this.lastValue != value) { this.callback(this.element, value); @@ -5297,79 +5692,80 @@ Abstract.EventObserver = Class.create({ } }, - registerFormCallbacks: function() { + registerFormCallbacks: function () { Form.getElements(this.element).each(this.registerCallback, this); }, - registerCallback: function(element) { + registerCallback: function (element) { if (element.type) { switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': - Event.observe(element, 'click', this.onElementEvent.bind(this)); + case "checkbox": + case "radio": + Event.observe(element, "click", this.onElementEvent.bind(this)); break; default: - Event.observe(element, 'change', this.onElementEvent.bind(this)); + Event.observe(element, "change", this.onElementEvent.bind(this)); break; } } - } + }, }); Form.Element.EventObserver = Class.create(Abstract.EventObserver, { - getValue: function() { + getValue: function () { return Form.Element.getValue(this.element); - } + }, }); Form.EventObserver = Class.create(Abstract.EventObserver, { - getValue: function() { + getValue: function () { return Form.serialize(this.element); - } + }, }); -(function() { - +(function () { var Event = { KEY_BACKSPACE: 8, - KEY_TAB: 9, - KEY_RETURN: 13, - KEY_ESC: 27, - KEY_LEFT: 37, - KEY_UP: 38, - KEY_RIGHT: 39, - KEY_DOWN: 40, - KEY_DELETE: 46, - KEY_HOME: 36, - KEY_END: 35, - KEY_PAGEUP: 33, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, KEY_PAGEDOWN: 34, - KEY_INSERT: 45, + KEY_INSERT: 45, - cache: {} + cache: {}, }; var docEl = document.documentElement; - var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl - && 'onmouseleave' in docEl; - + var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = + "onmouseenter" in docEl && "onmouseleave" in docEl; - - var isIELegacyEvent = function(event) { return false; }; + var isIELegacyEvent = function (event) { + return false; + }; if (window.attachEvent) { if (window.addEventListener) { - isIELegacyEvent = function(event) { + isIELegacyEvent = function (event) { return !(event instanceof window.Event); }; } else { - isIELegacyEvent = function(event) { return true; }; + isIELegacyEvent = function (event) { + return true; + }; } } var _isButton; function _isButtonForDOMEvents(event, code) { - return event.which ? (event.which === code + 1) : (event.button === code); + return event.which ? event.which === code + 1 : event.button === code; } var legacyButtonMap = { 0: 1, 1: 4, 2: 2 }; @@ -5379,10 +5775,14 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { function _isButtonForWebKit(event, code) { switch (code) { - case 0: return event.which == 1 && !event.metaKey; - case 1: return event.which == 2 || (event.which == 1 && event.metaKey); - case 2: return event.which == 3; - default: return false; + case 0: + return event.which == 1 && !event.metaKey; + case 1: + return event.which == 2 || (event.which == 1 && event.metaKey); + case 2: + return event.which == 3; + default: + return false; } } @@ -5390,10 +5790,11 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { if (!window.addEventListener) { _isButton = _isButtonForLegacyEvents; } else { - _isButton = function(event, code) { - return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) : - _isButtonForDOMEvents(event, code); - } + _isButton = function (event, code) { + return isIELegacyEvent(event) + ? _isButtonForLegacyEvents(event, code) + : _isButtonForDOMEvents(event, code); + }; } } else if (Prototype.Browser.WebKit) { _isButton = _isButtonForWebKit; @@ -5401,27 +5802,37 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { _isButton = _isButtonForDOMEvents; } - function isLeftClick(event) { return _isButton(event, 0) } + function isLeftClick(event) { + return _isButton(event, 0); + } - function isMiddleClick(event) { return _isButton(event, 1) } + function isMiddleClick(event) { + return _isButton(event, 1); + } - function isRightClick(event) { return _isButton(event, 2) } + function isRightClick(event) { + return _isButton(event, 2); + } function element(event) { event = Event.extend(event); - var node = event.target, type = event.type, - currentTarget = event.currentTarget; + var node = event.target, + type = event.type, + currentTarget = event.currentTarget; if (currentTarget && currentTarget.tagName) { - if (type === 'load' || type === 'error' || - (type === 'click' && currentTarget.tagName.toLowerCase() === 'input' - && currentTarget.type === 'radio')) - node = currentTarget; + if ( + type === "load" || + type === "error" || + (type === "click" && + currentTarget.tagName.toLowerCase() === "input" && + currentTarget.type === "radio") + ) + node = currentTarget; } - if (node.nodeType == Node.TEXT_NODE) - node = node.parentNode; + if (node.nodeType == Node.TEXT_NODE) node = node.parentNode; return Element.extend(node); } @@ -5431,7 +5842,10 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { if (!expression) return element; while (element) { - if (Object.isElement(element) && Prototype.Selector.match(element, expression)) { + if ( + Object.isElement(element) && + Prototype.Selector.match(element, expression) + ) { return Element.extend(element); } element = element.parentNode; @@ -5444,23 +5858,28 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { function pointerX(event) { var docElement = document.documentElement, - body = document.body || { scrollLeft: 0 }; + body = document.body || { scrollLeft: 0 }; - return event.pageX || (event.clientX + - (docElement.scrollLeft || body.scrollLeft) - - (docElement.clientLeft || 0)); + return ( + event.pageX || + event.clientX + + (docElement.scrollLeft || body.scrollLeft) - + (docElement.clientLeft || 0) + ); } function pointerY(event) { var docElement = document.documentElement, - body = document.body || { scrollTop: 0 }; + body = document.body || { scrollTop: 0 }; - return event.pageY || (event.clientY + - (docElement.scrollTop || body.scrollTop) - - (docElement.clientTop || 0)); + return ( + event.pageY || + event.clientY + + (docElement.scrollTop || body.scrollTop) - + (docElement.clientTop || 0) + ); } - function stop(event) { Event.extend(event); event.preventDefault(); @@ -5469,23 +5888,22 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { event.stopped = true; } - Event.Methods = { - isLeftClick: isLeftClick, + isLeftClick: isLeftClick, isMiddleClick: isMiddleClick, - isRightClick: isRightClick, + isRightClick: isRightClick, - element: element, + element: element, findElement: findElement, - pointer: pointer, + pointer: pointer, pointerX: pointerX, pointerY: pointerY, - stop: stop + stop: stop, }; - var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { + var methods = Object.keys(Event.Methods).inject({}, function (m, name) { m[name] = Event.Methods[name].methodize(); return m; }); @@ -5494,12 +5912,12 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { function _relatedTarget(event) { var element; switch (event.type) { - case 'mouseover': - case 'mouseenter': + case "mouseover": + case "mouseenter": element = event.fromElement; break; - case 'mouseout': - case 'mouseleave': + case "mouseout": + case "mouseleave": element = event.toElement; break; default: @@ -5509,12 +5927,18 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { } var additionalMethods = { - stopPropagation: function() { this.cancelBubble = true }, - preventDefault: function() { this.returnValue = false }, - inspect: function() { return '[object Event]' } + stopPropagation: function () { + this.cancelBubble = true; + }, + preventDefault: function () { + this.returnValue = false; + }, + inspect: function () { + return "[object Event]"; + }, }; - Event.extend = function(event, element) { + Event.extend = function (event, element) { if (!event) return false; if (!isIELegacyEvent(event)) return event; @@ -5527,8 +5951,8 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { Object.extend(event, { target: event.srcElement || element, relatedTarget: _relatedTarget(event), - pageX: pointer.x, - pageY: pointer.y + pageX: pointer.x, + pageY: pointer.y, }); Object.extend(event, methods); @@ -5541,16 +5965,17 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { } if (window.addEventListener) { - Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__; + Event.prototype = + window.Event.prototype || document.createEvent("HTMLEvents").__proto__; Object.extend(Event.prototype, methods); } function _createResponder(element, eventName, handler) { - var registry = Element.retrieve(element, 'prototype_event_registry'); + var registry = Element.retrieve(element, "prototype_event_registry"); if (Object.isUndefined(registry)) { CACHE.push(element); - registry = Element.retrieve(element, 'prototype_event_registry', $H()); + registry = Element.retrieve(element, "prototype_event_registry", $H()); } var respondersForEvent = registry.get(eventName); @@ -5559,31 +5984,34 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { registry.set(eventName, respondersForEvent); } - if (respondersForEvent.pluck('handler').include(handler)) return false; + if (respondersForEvent.pluck("handler").include(handler)) return false; var responder; if (eventName.include(":")) { - responder = function(event) { - if (Object.isUndefined(event.eventName)) - return false; + responder = function (event) { + if (Object.isUndefined(event.eventName)) return false; - if (event.eventName !== eventName) - return false; + if (event.eventName !== eventName) return false; Event.extend(event, element); handler.call(element, event); }; } else { - if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED && - (eventName === "mouseenter" || eventName === "mouseleave")) { + if ( + !MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED && + (eventName === "mouseenter" || eventName === "mouseleave") + ) { if (eventName === "mouseenter" || eventName === "mouseleave") { - responder = function(event) { + responder = function (event) { Event.extend(event, element); var parent = event.relatedTarget; while (parent && parent !== element) { - try { parent = parent.parentNode; } - catch(e) { parent = element; } + try { + parent = parent.parentNode; + } catch (e) { + parent = element; + } } if (parent === element) return; @@ -5592,7 +6020,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { }; } } else { - responder = function(event) { + responder = function (event) { Event.extend(event, element); handler.call(element, event); }; @@ -5613,19 +6041,17 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { var CACHE = []; - if (Prototype.Browser.IE) - window.attachEvent('onunload', _destroyCache); + if (Prototype.Browser.IE) window.attachEvent("onunload", _destroyCache); if (Prototype.Browser.WebKit) - window.addEventListener('unload', Prototype.emptyFunction, false); - + window.addEventListener("unload", Prototype.emptyFunction, false); var _getDOMEventName = Prototype.K, - translations = { mouseenter: "mouseover", mouseleave: "mouseout" }; + translations = { mouseenter: "mouseover", mouseleave: "mouseout" }; if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) { - _getDOMEventName = function(eventName) { - return (translations[eventName] || eventName); + _getDOMEventName = function (eventName) { + return translations[eventName] || eventName; }; } @@ -5636,7 +6062,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { if (!responder) return element; - if (eventName.include(':')) { + if (eventName.include(":")) { if (element.addEventListener) element.addEventListener("dataavailable", responder, false); else { @@ -5648,8 +6074,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { if (element.addEventListener) element.addEventListener(actualEventName, responder, false); - else - element.attachEvent("on" + actualEventName, responder); + else element.attachEvent("on" + actualEventName, responder); } return element; @@ -5658,11 +6083,11 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { function stopObserving(element, eventName, handler) { element = $(element); - var registry = Element.retrieve(element, 'prototype_event_registry'); + var registry = Element.retrieve(element, "prototype_event_registry"); if (!registry) return element; if (!eventName) { - registry.each( function(pair) { + registry.each(function (pair) { var eventName = pair.key; stopObserving(element, eventName); }); @@ -5673,13 +6098,14 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { if (!responders) return element; if (!handler) { - responders.each(function(r) { + responders.each(function (r) { stopObserving(element, eventName, r.handler); }); return element; } - var i = responders.length, responder; + var i = responders.length, + responder; while (i--) { if (responders[i].handler === handler) { responder = responders[i]; @@ -5688,7 +6114,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { } if (!responder) return element; - if (eventName.include(':')) { + if (eventName.include(":")) { if (element.removeEventListener) element.removeEventListener("dataavailable", responder, false); else { @@ -5699,8 +6125,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { var actualEventName = _getDOMEventName(eventName); if (element.removeEventListener) element.removeEventListener(actualEventName, responder, false); - else - element.detachEvent('on' + actualEventName, responder); + else element.detachEvent("on" + actualEventName, responder); } registry.set(eventName, responders.without(responder)); @@ -5711,61 +6136,58 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { function fire(element, eventName, memo, bubble) { element = $(element); - if (Object.isUndefined(bubble)) - bubble = true; + if (Object.isUndefined(bubble)) bubble = true; if (element == document && document.createEvent && !element.dispatchEvent) element = document.documentElement; var event; if (document.createEvent) { - event = document.createEvent('HTMLEvents'); - event.initEvent('dataavailable', bubble, true); + event = document.createEvent("HTMLEvents"); + event.initEvent("dataavailable", bubble, true); } else { event = document.createEventObject(); - event.eventType = bubble ? 'ondataavailable' : 'onlosecapture'; + event.eventType = bubble ? "ondataavailable" : "onlosecapture"; } event.eventName = eventName; - event.memo = memo || { }; + event.memo = memo || {}; - if (document.createEvent) - element.dispatchEvent(event); - else - element.fireEvent(event.eventType, event); + if (document.createEvent) element.dispatchEvent(event); + else element.fireEvent(event.eventType, event); return Event.extend(event); } Event.Handler = Class.create({ - initialize: function(element, eventName, selector, callback) { - this.element = $(element); + initialize: function (element, eventName, selector, callback) { + this.element = $(element); this.eventName = eventName; - this.selector = selector; - this.callback = callback; - this.handler = this.handleEvent.bind(this); + this.selector = selector; + this.callback = callback; + this.handler = this.handleEvent.bind(this); }, - start: function() { + start: function () { Event.observe(this.element, this.eventName, this.handler); return this; }, - stop: function() { + stop: function () { Event.stopObserving(this.element, this.eventName, this.handler); return this; }, - handleEvent: function(event) { + handleEvent: function (event) { var element = Event.findElement(event, this.selector); if (element) this.callback.call(this.element, event, element); - } + }, }); function on(element, eventName, selector, callback) { element = $(element); if (Object.isFunction(selector) && Object.isUndefined(callback)) { - callback = selector, selector = null; + (callback = selector), (selector = null); } return new Event.Handler(element, eventName, selector, callback).start(); @@ -5774,39 +6196,39 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { Object.extend(Event, Event.Methods); Object.extend(Event, { - fire: fire, - observe: observe, + fire: fire, + observe: observe, stopObserving: stopObserving, - on: on + on: on, }); Element.addMethods({ - fire: fire, + fire: fire, - observe: observe, + observe: observe, stopObserving: stopObserving, - on: on + on: on, }); Object.extend(document, { - fire: fire.methodize(), + fire: fire.methodize(), - observe: observe.methodize(), + observe: observe.methodize(), stopObserving: stopObserving.methodize(), - on: on.methodize(), + on: on.methodize(), - loaded: false + loaded: false, }); if (window.Event) Object.extend(window.Event, Event); else window.Event = Event; })(); -(function() { +(function () { /* Support for the DOMContentLoaded event is based on work by Dan Webb, Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */ @@ -5816,19 +6238,20 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { if (document.loaded) return; if (timer) window.clearTimeout(timer); document.loaded = true; - document.fire('dom:loaded'); + document.fire("dom:loaded"); } function checkReadyState() { - if (document.readyState === 'complete') { - document.stopObserving('readystatechange', checkReadyState); + if (document.readyState === "complete") { + document.stopObserving("readystatechange", checkReadyState); fireContentLoadedEvent(); } } function pollDoScroll() { - try { document.documentElement.doScroll('left'); } - catch(e) { + try { + document.documentElement.doScroll("left"); + } catch (e) { timer = pollDoScroll.defer(); return; } @@ -5836,17 +6259,19 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { } if (document.addEventListener) { - document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false); + document.addEventListener( + "DOMContentLoaded", + fireContentLoadedEvent, + false + ); } else { - document.observe('readystatechange', checkReadyState); - if (window == top) - timer = pollDoScroll.defer(); + document.observe("readystatechange", checkReadyState); + if (window == top) timer = pollDoScroll.defer(); } - Event.observe(window, 'load', fireContentLoadedEvent); + Event.observe(window, "load", fireContentLoadedEvent); })(); - Element.addMethods(); /*------------------------------- DEPRECATED -------------------------------*/ @@ -5857,86 +6282,97 @@ var Toggle = { display: Element.toggle }; Element.Methods.childOf = Element.Methods.descendantOf; var Insertion = { - Before: function(element, content) { - return Element.insert(element, {before:content}); + Before: function (element, content) { + return Element.insert(element, { before: content }); }, - Top: function(element, content) { - return Element.insert(element, {top:content}); + Top: function (element, content) { + return Element.insert(element, { top: content }); }, - Bottom: function(element, content) { - return Element.insert(element, {bottom:content}); + Bottom: function (element, content) { + return Element.insert(element, { bottom: content }); }, - After: function(element, content) { - return Element.insert(element, {after:content}); - } + After: function (element, content) { + return Element.insert(element, { after: content }); + }, }; -var $continue = new Error('"throw $continue" is deprecated, use "return" instead'); +var $continue = new Error( + '"throw $continue" is deprecated, use "return" instead' +); var Position = { includeScrollOffsets: false, - prepare: function() { - this.deltaX = window.pageXOffset - || document.documentElement.scrollLeft - || document.body.scrollLeft - || 0; - this.deltaY = window.pageYOffset - || document.documentElement.scrollTop - || document.body.scrollTop - || 0; + prepare: function () { + this.deltaX = + window.pageXOffset || + document.documentElement.scrollLeft || + document.body.scrollLeft || + 0; + this.deltaY = + window.pageYOffset || + document.documentElement.scrollTop || + document.body.scrollTop || + 0; }, - within: function(element, x, y) { + within: function (element, x, y) { if (this.includeScrollOffsets) return this.withinIncludingScrolloffsets(element, x, y); this.xcomp = x; this.ycomp = y; this.offset = Element.cumulativeOffset(element); - return (y >= this.offset[1] && - y < this.offset[1] + element.offsetHeight && - x >= this.offset[0] && - x < this.offset[0] + element.offsetWidth); + return ( + y >= this.offset[1] && + y < this.offset[1] + element.offsetHeight && + x >= this.offset[0] && + x < this.offset[0] + element.offsetWidth + ); }, - withinIncludingScrolloffsets: function(element, x, y) { + withinIncludingScrolloffsets: function (element, x, y) { var offsetcache = Element.cumulativeScrollOffset(element); this.xcomp = x + offsetcache[0] - this.deltaX; this.ycomp = y + offsetcache[1] - this.deltaY; this.offset = Element.cumulativeOffset(element); - return (this.ycomp >= this.offset[1] && - this.ycomp < this.offset[1] + element.offsetHeight && - this.xcomp >= this.offset[0] && - this.xcomp < this.offset[0] + element.offsetWidth); + return ( + this.ycomp >= this.offset[1] && + this.ycomp < this.offset[1] + element.offsetHeight && + this.xcomp >= this.offset[0] && + this.xcomp < this.offset[0] + element.offsetWidth + ); }, - overlap: function(mode, element) { + overlap: function (mode, element) { if (!mode) return 0; - if (mode == 'vertical') - return ((this.offset[1] + element.offsetHeight) - this.ycomp) / - element.offsetHeight; - if (mode == 'horizontal') - return ((this.offset[0] + element.offsetWidth) - this.xcomp) / - element.offsetWidth; + if (mode == "vertical") + return ( + (this.offset[1] + element.offsetHeight - this.ycomp) / + element.offsetHeight + ); + if (mode == "horizontal") + return ( + (this.offset[0] + element.offsetWidth - this.xcomp) / + element.offsetWidth + ); }, - cumulativeOffset: Element.Methods.cumulativeOffset, positionedOffset: Element.Methods.positionedOffset, - absolutize: function(element) { + absolutize: function (element) { Position.prepare(); return Element.absolutize(element); }, - relativize: function(element) { + relativize: function (element) { Position.prepare(); return Element.relativize(element); }, @@ -5947,111 +6383,132 @@ var Position = { page: Element.Methods.viewportOffset, - clone: function(source, target, options) { - options = options || { }; + clone: function (source, target, options) { + options = options || {}; return Element.clonePosition(target, source, options); - } + }, }; /*--------------------------------------------------------------------------*/ -if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){ - function iter(name) { - return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]"; - } - - instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ? - function(element, className) { - className = className.toString().strip(); - var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className); - return cond ? document._getElementsByXPath('.//*' + cond, element) : []; - } : function(element, className) { - className = className.toString().strip(); - var elements = [], classNames = (/\s/.test(className) ? $w(className) : null); - if (!classNames && !className) return elements; - - var nodes = $(element).getElementsByTagName('*'); - className = ' ' + className + ' '; - - for (var i = 0, child, cn; child = nodes[i]; i++) { - if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) || - (classNames && classNames.all(function(name) { - return !name.toString().blank() && cn.include(' ' + name + ' '); - })))) - elements.push(Element.extend(child)); - } - return elements; - }; +if (!document.getElementsByClassName) + document.getElementsByClassName = (function (instanceMethods) { + function iter(name) { + return name.blank() + ? null + : "[contains(concat(' ', @class, ' '), ' " + name + " ')]"; + } + + instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath + ? function (element, className) { + className = className.toString().strip(); + var cond = /\s/.test(className) + ? $w(className).map(iter).join("") + : iter(className); + return cond + ? document._getElementsByXPath(".//*" + cond, element) + : []; + } + : function (element, className) { + className = className.toString().strip(); + var elements = [], + classNames = /\s/.test(className) ? $w(className) : null; + if (!classNames && !className) return elements; + + var nodes = $(element).getElementsByTagName("*"); + className = " " + className + " "; + + for (var i = 0, child, cn; (child = nodes[i]); i++) { + if ( + child.className && + (cn = " " + child.className + " ") && + (cn.include(className) || + (classNames && + classNames.all(function (name) { + return ( + !name.toString().blank() && cn.include(" " + name + " ") + ); + }))) + ) + elements.push(Element.extend(child)); + } + return elements; + }; - return function(className, parentElement) { - return $(parentElement || document.body).getElementsByClassName(className); - }; -}(Element.Methods); + return function (className, parentElement) { + return $(parentElement || document.body).getElementsByClassName( + className + ); + }; + })(Element.Methods); /*--------------------------------------------------------------------------*/ Element.ClassNames = Class.create(); Element.ClassNames.prototype = { - initialize: function(element) { + initialize: function (element) { this.element = $(element); }, - _each: function(iterator) { - this.element.className.split(/\s+/).select(function(name) { - return name.length > 0; - })._each(iterator); + _each: function (iterator) { + this.element.className + .split(/\s+/) + .select(function (name) { + return name.length > 0; + }) + ._each(iterator); }, - set: function(className) { + set: function (className) { this.element.className = className; }, - add: function(classNameToAdd) { + add: function (classNameToAdd) { if (this.include(classNameToAdd)) return; - this.set($A(this).concat(classNameToAdd).join(' ')); + this.set($A(this).concat(classNameToAdd).join(" ")); }, - remove: function(classNameToRemove) { + remove: function (classNameToRemove) { if (!this.include(classNameToRemove)) return; - this.set($A(this).without(classNameToRemove).join(' ')); + this.set($A(this).without(classNameToRemove).join(" ")); }, - toString: function() { - return $A(this).join(' '); - } + toString: function () { + return $A(this).join(" "); + }, }; Object.extend(Element.ClassNames.prototype, Enumerable); /*--------------------------------------------------------------------------*/ -(function() { +(function () { window.Selector = Class.create({ - initialize: function(expression) { + initialize: function (expression) { this.expression = expression.strip(); }, - findElements: function(rootElement) { + findElements: function (rootElement) { return Prototype.Selector.select(this.expression, rootElement); }, - match: function(element) { + match: function (element) { return Prototype.Selector.match(element, this.expression); }, - toString: function() { + toString: function () { return this.expression; }, - inspect: function() { + inspect: function () { return "#"; - } + }, }); Object.extend(Selector, { - matchElements: function(elements, expression) { + matchElements: function (elements, expression) { var match = Prototype.Selector.match, - results = []; + results = []; for (var i = 0, length = elements.length; i < length; i++) { var element = elements[i]; @@ -6062,20 +6519,24 @@ Object.extend(Element.ClassNames.prototype, Enumerable); return results; }, - findElement: function(elements, expression, index) { + findElement: function (elements, expression, index) { index = index || 0; - var matchIndex = 0, element; + var matchIndex = 0, + element; for (var i = 0, length = elements.length; i < length; i++) { element = elements[i]; - if (Prototype.Selector.match(element, expression) && index === matchIndex++) { + if ( + Prototype.Selector.match(element, expression) && + index === matchIndex++ + ) { return Element.extend(element); } } }, - findChildElements: function(element, expressions) { - var selector = expressions.toArray().join(', '); + findChildElements: function (element, expressions) { + var selector = expressions.toArray().join(", "); return Prototype.Selector.select(selector, element || document); - } + }, }); })(); diff --git a/js/settings.js b/js/settings.js index 85cc91aa..e3971610 100644 --- a/js/settings.js +++ b/js/settings.js @@ -3,24 +3,27 @@ */ var URL_SETTINGS = "/php/settings.php"; -var privacyList = [ 'N', 'Y', 'O' ]; +var privacyList = ["N", "Y", "O"]; -window.onload = function init(){ - gt = new Gettext({ 'domain' : 'messages' }); - if(window.location.href.indexOf("settings") != -1) { - var form = document.forms['signupform']; +window.onload = function init() { + gt = new Gettext({ domain: "messages" }); + if (window.location.href.indexOf("settings") != -1) { + var form = document.forms["signupform"]; var elite = form.elite.value; - document.getElementById('eliteicon').innerHTML = getEliteIcon(elite, form.validity.value); - if(elite == "G" || elite == "P") { + document.getElementById("eliteicon").innerHTML = getEliteIcon( + elite, + form.validity.value + ); + if (elite == "G" || elite == "P") { signupform.guestpw.disabled = false; - for (r=0; r < signupform.startpane.length; r++){ + for (r = 0; r < signupform.startpane.length; r++) { signupform.startpane[r].disabled = false; } } } else { // TODO document.forms['signupform'].username.value = parent.opener.document.forms['login'].name.value; } -} +}; function xmlhttpPost(strURL, type) { var xmlHttpReq = false; @@ -33,68 +36,99 @@ function xmlhttpPost(strURL, type) { else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } - self.xmlHttpReq.open('POST', strURL, true); - self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - self.xmlHttpReq.onreadystatechange = function() { + self.xmlHttpReq.open("POST", strURL, true); + self.xmlHttpReq.setRequestHeader( + "Content-Type", + "application/x-www-form-urlencoded" + ); + self.xmlHttpReq.onreadystatechange = function () { if (self.xmlHttpReq.readyState == 4 && strURL == URL_SETTINGS) { signup(self.xmlHttpReq.responseText); } - } + }; var query = ""; - if(strURL == URL_SETTINGS) { - var form = document.forms['signupform']; + if (strURL == URL_SETTINGS) { + var form = document.forms["signupform"]; var privacy, editor, units; - for (r=0; r < signupform.privacy.length; r++){ + for (r = 0; r < signupform.privacy.length; r++) { if (signupform.privacy[r].checked) { privacy = signupform.privacy[r].value; } } - for (r=0; r < signupform.editor.length; r++){ + for (r = 0; r < signupform.editor.length; r++) { if (signupform.editor[r].checked) { editor = signupform.editor[r].value; } } - for (r=0; r < signupform.units.length; r++){ + for (r = 0; r < signupform.units.length; r++) { if (signupform.units[r].checked) { units = signupform.units[r].value; } } - query = 'type=' + type + '&' + - 'pw=' + encodeURIComponent(hex_md5(form.pw1.value + form.username.value.toLowerCase())) + '&' + - 'email=' + encodeURIComponent(form.email.value) + '&' + - 'privacy=' + encodeURIComponent(privacy) + '&' + - 'editor=' + encodeURIComponent(editor) + '&' + - 'units=' + encodeURIComponent(units) + '&' + - 'locale=' + encodeURIComponent(form.locale.value); - switch(type) { - case 'NEW': - query += '&name=' + encodeURIComponent(form.username.value); - document.getElementById("miniresultbox").innerHTML = "" + gt.gettext("Creating account...") + ""; - break; + query = + "type=" + + type + + "&" + + "pw=" + + encodeURIComponent( + hex_md5(form.pw1.value + form.username.value.toLowerCase()) + ) + + "&" + + "email=" + + encodeURIComponent(form.email.value) + + "&" + + "privacy=" + + encodeURIComponent(privacy) + + "&" + + "editor=" + + encodeURIComponent(editor) + + "&" + + "units=" + + encodeURIComponent(units) + + "&" + + "locale=" + + encodeURIComponent(form.locale.value); + switch (type) { + case "NEW": + query += "&name=" + encodeURIComponent(form.username.value); + document.getElementById("miniresultbox").innerHTML = + "" + gt.gettext("Creating account...") + ""; + break; - case 'EDIT': - for (r=0; r < signupform.startpane.length; r++){ - if (signupform.startpane[r].checked) { - startpane = signupform.startpane[r].value; + case "EDIT": + for (r = 0; r < signupform.startpane.length; r++) { + if (signupform.startpane[r].checked) { + startpane = signupform.startpane[r].value; + } } - } - if(form.oldpw.value != "") { - query += '&oldpw=' + encodeURIComponent(hex_md5(form.oldpw.value + form.username.value.toLowerCase())); - // Legacy password for case-sensitive days of yore - query += '&oldlpw=' + encodeURIComponent(hex_md5(form.oldpw.value + form.username.value)); - } - if(form.guestpw.value != "") { - query += '&guestpw=' + encodeURIComponent(hex_md5(form.guestpw.value + form.username.value.toLowerCase())); - } - query += '&startpane=' + encodeURIComponent(startpane); - document.getElementById("miniresultbox").innerHTML = "" + gt.gettext("Saving changes...") + ""; - break; + if (form.oldpw.value != "") { + query += + "&oldpw=" + + encodeURIComponent( + hex_md5(form.oldpw.value + form.username.value.toLowerCase()) + ); + // Legacy password for case-sensitive days of yore + query += + "&oldlpw=" + + encodeURIComponent(hex_md5(form.oldpw.value + form.username.value)); + } + if (form.guestpw.value != "") { + query += + "&guestpw=" + + encodeURIComponent( + hex_md5(form.guestpw.value + form.username.value.toLowerCase()) + ); + } + query += "&startpane=" + encodeURIComponent(startpane); + document.getElementById("miniresultbox").innerHTML = + "" + gt.gettext("Saving changes...") + ""; + break; - case 'RESET': - case 'LOAD': - // do nothing - break; + case "RESET": + case "LOAD": + // do nothing + break; } } self.xmlHttpReq.send(query); @@ -102,58 +136,79 @@ function xmlhttpPost(strURL, type) { // Validate form function validate(type) { - var form = document.forms['signupform']; + var form = document.forms["signupform"]; var pw1 = form.pw1.value; var pw2 = form.pw2.value; var email = form.email.value; - if(type == 'RESET') { - if(! confirm(gt.gettext("This will PERMANENTLY delete ALL YOUR FLIGHTS. Have you exported a backup copy, and are you sure you want to do this?"))) { - document.getElementById("miniresultbox").innerHTML = "" + gt.gettext("Deletion cancelled.") + ""; + if (type == "RESET") { + if ( + !confirm( + gt.gettext( + "This will PERMANENTLY delete ALL YOUR FLIGHTS. Have you exported a backup copy, and are you sure you want to do this?" + ) + ) + ) { + document.getElementById("miniresultbox").innerHTML = + "" + gt.gettext("Deletion cancelled.") + ""; return; } } - if(type == 'NEW') { + if (type == "NEW") { var name = form.username.value; - if(name == "") { + if (name == "") { showError(gt.gettext("Please enter a username.")); form.username.focus(); return; } - if(pw1 == "") { + if (pw1 == "") { showError(gt.gettext("Please enter a password.")); form.pw1.focus(); return; } } - if(type == 'EDIT') { + if (type == "EDIT") { var oldpw = form.oldpw.value; - if(pw1 != "" && oldpw == "") { - showError(gt.gettext("Please enter your current password if you wish to change to a new password.")); + if (pw1 != "" && oldpw == "") { + showError( + gt.gettext( + "Please enter your current password if you wish to change to a new password." + ) + ); form.oldpw.focus(); return; } - if(pw1 == "" && oldpw != "") { - showError(gt.gettext("Please enter a new password, or clear current password if you do not wish to change it.")); + if (pw1 == "" && oldpw != "") { + showError( + gt.gettext( + "Please enter a new password, or clear current password if you do not wish to change it." + ) + ); form.pw1.focus(); return; } } - if(pw1 != pw2) { + if (pw1 != pw2) { showError(gt.gettext("Your passwords don't match, please try again.")); form.pw1.focus(); return; } - if(email != "" && ! /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(email)) { - showError(gt.gettext('Invalid e-mail address, it should be "user@example.domain"')); + if ( + email != "" && + !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(email) + ) { + showError( + gt.gettext('Invalid e-mail address, it should be "user@example.domain"') + ); form.email.focus(); return; } - document.getElementById("miniresultbox").innerHTML = "" + gt.gettext("Processing...") + ""; + document.getElementById("miniresultbox").innerHTML = + "" + gt.gettext("Processing...") + ""; xmlhttpPost(URL_SETTINGS, type); } @@ -165,49 +220,51 @@ function signup(str) { var message = str.split(";")[1]; // Operation successful - if(code.length == 1 && code != "0") { + if (code.length == 1 && code != "0") { document.getElementById("miniresultbox").innerHTML = message; // Whether signup, edit or reset, go back to main screen now - location.href = '/'; + location.href = "/"; } else { showError(message); } } function changeName() { - var name = document.forms['signupform'].username.value; + var name = document.forms["signupform"].username.value; var url = location.origin + "/user/" + encodeURIComponent(name); - document.getElementById('profileurl').innerHTML = gt.gettext("Profile address: ") + url; + document.getElementById("profileurl").innerHTML = + gt.gettext("Profile address: ") + url; } // Swap privacy panes function changePrivacy(type) { - for(p = 0; p < privacyList.length; p++) { - if(type == privacyList[p]) { + for (p = 0; p < privacyList.length; p++) { + if (type == privacyList[p]) { style = "inline"; } else { style = "none"; } - document.getElementById('privacy' + privacyList[p]).style.display = style; + document.getElementById("privacy" + privacyList[p]).style.display = style; } } // Swap editor panes function changeEditor(type) { - switch(type) { - case "B": - document.getElementById('detaileditor').style.display = "none"; - document.getElementById('basiceditor').style.display = "inline"; - break; - case "D": - document.getElementById('basiceditor').style.display = "none"; - document.getElementById('detaileditor').style.display = "inline"; - break; + switch (type) { + case "B": + document.getElementById("detaileditor").style.display = "none"; + document.getElementById("basiceditor").style.display = "inline"; + break; + case "D": + document.getElementById("basiceditor").style.display = "none"; + document.getElementById("detaileditor").style.display = "inline"; + break; } } function showError(err) { - document.getElementById("miniresultbox").innerHTML = "" + err + ""; + document.getElementById("miniresultbox").innerHTML = + "" + err + ""; location.hash = "top"; } diff --git a/js/trip.js b/js/trip.js index b8f63b86..8ad72146 100644 --- a/js/trip.js +++ b/js/trip.js @@ -5,9 +5,9 @@ var URL_TRIP = "/php/trip.php"; var trid = 0; var type = "NEW"; -window.onload = function init(){ - gt = new Gettext({ 'domain' : 'messages' }); -} +window.onload = function init() { + gt = new Gettext({ domain: "messages" }); +}; function xmlhttpPost(strURL, type) { var xmlHttpReq = false; @@ -20,32 +20,42 @@ function xmlhttpPost(strURL, type) { else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } - self.xmlHttpReq.open('POST', strURL, true); - self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - self.xmlHttpReq.onreadystatechange = function() { + self.xmlHttpReq.open("POST", strURL, true); + self.xmlHttpReq.setRequestHeader( + "Content-Type", + "application/x-www-form-urlencoded" + ); + self.xmlHttpReq.onreadystatechange = function () { if (self.xmlHttpReq.readyState == 4) { - - if(strURL == URL_TRIP) { + if (strURL == URL_TRIP) { editTrip(self.xmlHttpReq.responseText); } } - } + }; var query = ""; - if(strURL == URL_TRIP) { - var form = document.forms['tripform']; + if (strURL == URL_TRIP) { + var form = document.forms["tripform"]; var privacy; - for (r=0; r < tripform.privacy.length; r++){ + for (r = 0; r < tripform.privacy.length; r++) { if (tripform.privacy[r].checked) { privacy = tripform.privacy[r].value; } } - query = 'type=' + type + '&' + - 'name=' + encodeURIComponent(form.name.value) + '&' + - 'url=' + encodeURIComponent(form.url.value) + '&' + - 'privacy=' + encodeURIComponent(privacy); - if(type == 'EDIT' || type == 'DELETE') { - query += '&trid=' + form.trid.value; + query = + "type=" + + type + + "&" + + "name=" + + encodeURIComponent(form.name.value) + + "&" + + "url=" + + encodeURIComponent(form.url.value) + + "&" + + "privacy=" + + encodeURIComponent(privacy); + if (type == "EDIT" || type == "DELETE") { + query += "&trid=" + form.trid.value; } } self.xmlHttpReq.send(query); @@ -53,8 +63,8 @@ function xmlhttpPost(strURL, type) { // Validate form function validate(type) { - var form = document.forms['tripform']; - if(form.name.value == "") { + var form = document.forms["tripform"]; + if (form.name.value == "") { showError("Please enter a name for this trip."); return; } @@ -65,10 +75,15 @@ function validate(type) { // Delete trip? function deleteTrip() { - if(confirm("Are you sure you want to delete this trip? (Flights in this trip will NOT be deleted.)")) { + if ( + confirm( + "Are you sure you want to delete this trip? (Flights in this trip will NOT be deleted.)" + ) + ) { xmlhttpPost(URL_TRIP, "DELETE"); } else { - document.getElementById("miniresultbox").innerHTML = "Deleting trip cancelled."; + document.getElementById("miniresultbox").innerHTML = + "Deleting trip cancelled."; } } @@ -78,9 +93,9 @@ function editTrip(str) { var trid = str.split(";")[1]; var message = str.split(";")[2]; // Operation successful - if(code != "0") { + if (code != "0") { document.getElementById("miniresultbox").innerHTML = message; - var form = document.forms['tripform']; + var form = document.forms["tripform"]; parent.opener.newTrip(code, trid, form.name.value, form.url.value); window.close(); } else { @@ -89,5 +104,6 @@ function editTrip(str) { } function showError(err) { - document.getElementById("miniresultbox").innerHTML = "" + err + ""; + document.getElementById("miniresultbox").innerHTML = + "" + err + ""; } diff --git a/js/tripit.js b/js/tripit.js index 6f41f6d4..e841d4f1 100644 --- a/js/tripit.js +++ b/js/tripit.js @@ -1,160 +1,181 @@ -/** - * tripit.js - TripIt integration for OpenFlights - * Andrew Chen - achen.code on big-G's email service - */ - -// Constants used elsewhere in this file. -var CONST = { - DEBUG: false, - IMPORT_URL: "/php/submit.php", - // HARD_FAIL means "don't retry", whereas SOFT_FAIL means "try again later". - CODE_HARD_FAIL: -1, - CODE_ADDOK: 1 -}; - -/** - * Submit a segment import form - * @param segmentId TripIt segment ID to import - */ -function importFlight(segmentId) { - var form = $("#import" + segmentId); - if(form == null) { - // Shouldn't happen, but let's be defensive. - setStatus(segmentId, "Internal Error: Couldn't find segment " + segmentId); - return; - } - - // Serialize the form into a request. - var params = form.serialize(); - - if(CONST.DEBUG) { - console.log("importFlight: params=" + params); - } - - $.post(CONST.IMPORT_URL, params, importFlightComplete(segmentId)); -} - -/** - * Callback upon successful import. - * @param segmentId - */ -var importFlightComplete = function (segmentId) { - return function (data, responseText, jqXHR) { - var result = data.split(";"); - code = result[0]; - text = result[1]; - setStatus(segmentId, '' + text + ''); - - var showOverlay = false; - var overlayImage; - if (code == CONST.CODE_ADDOK) { - // Successful add; show checkmark. - showOverlay = true; - overlayImage = 'Checkmark_green.80px.png'; - } else if (code == CONST.CODE_HARD_FAIL) { - // Fatal error, don't try again. - showOverlay = true; - overlayImage = 'Red_X.64px.png'; - } - - if (showOverlay) { - $('#import' + segmentId + ' :input').attr("disabled", true); - $('#import' + segmentId).block({ - message:'', - css:{ - cursor:'default', - border:'none', - padding:'15px', - // Set this to #000 to add a dark box around the checkbox - backgroundColor:'transparent', - '-webkit-border-radius':'10px', - '-moz-border-radius':'10px', - // Set opacity to .5 or .6 if box enabled above. - opacity:1, - color:'#fff' - }, - overlayCSS:{ - height:$('#segment' + segmentId).height(), - cursor:'default' - } - }) - } - } -}; - -/** - * Shortcut for marking a segment as already imported when loading a TripIt list page. - * @param segmentId - */ -function markSegmentImported(segmentId) { - importFlightComplete(segmentId)(CONST.CODE_ADDOK + ";Segment already imported.", null, null); -} - -/** - * Shortcut for marking a segment as invalid for import. This shouldn't normally happen. - * @param segmentId - */ -function markSegmentInvalid(segmentId) { - importFlightComplete(segmentId)(CONST.CODE_HARD_FAIL + ";Insufficient data to import this segment.", null, null); -} - -/** - * Set the status field for a given segment to message. - * @param segmentId - * @param message - */ -function setStatus(segmentId, message) { - var statusSpan = document.getElementById("input_status" + segmentId); - if(statusSpan != null) { - statusSpan.innerHTML = message; - } -} - -/** - * Import multiple segments at once. Under the covers, this still calls {@link #importFlight}, - * so each segment will result in a call to the service to import. - * @param flights Array of flights to import. - */ -function importFlights(flights) { - for (var i = 0; i < flights.length; i++) { - importFlight(flights[i]); - } -} - -/** - * Add a button to the DOM to import all segments for a given trip id. - * @param importAllButtonValue Text for the Import All button. This should be localized. - * @param tripId ID of the trip. - * @param segments Array of segments to be imported when this button is clicked. - */ -function addImportAllButton(importAllButtonValue, tripId, segments) { - var importAllDiv = document.getElementById("import_all_" + tripId); - if (importAllDiv == null) { - console.log("Couldn't find div to insert Import All button for trip " + tripId); - return; - } - - importAllDiv.innerHTML = ''; -} - -/** - * Init method for the rendezvous instruction page. - */ -function rendezvousPageInit() { - $("#loginPathPartner").click(function () { - $("#loginPathSelection").hide(); - $("#loginPathPartnerHelp").show(); - } - ); - - $("#loginPathNative").click(function () { - window.location.href = "/php/tripit_rendezvous_start.php"; - }); -} - -/** - * Popup a window with TripIt's login page. This is used for rendezvous with partner logins. - */ -function openTripItLogin() { - window.open('https://www.tripit.com/account/login', 'TripItLogin', 'width=1000,height=550,scrollbars=yes'); -} +/** + * tripit.js - TripIt integration for OpenFlights + * Andrew Chen - achen.code on big-G's email service + */ + +// Constants used elsewhere in this file. +var CONST = { + DEBUG: false, + IMPORT_URL: "/php/submit.php", + // HARD_FAIL means "don't retry", whereas SOFT_FAIL means "try again later". + CODE_HARD_FAIL: -1, + CODE_ADDOK: 1, +}; + +/** + * Submit a segment import form + * @param segmentId TripIt segment ID to import + */ +function importFlight(segmentId) { + var form = $("#import" + segmentId); + if (form == null) { + // Shouldn't happen, but let's be defensive. + setStatus(segmentId, "Internal Error: Couldn't find segment " + segmentId); + return; + } + + // Serialize the form into a request. + var params = form.serialize(); + + if (CONST.DEBUG) { + console.log("importFlight: params=" + params); + } + + $.post(CONST.IMPORT_URL, params, importFlightComplete(segmentId)); +} + +/** + * Callback upon successful import. + * @param segmentId + */ +var importFlightComplete = function (segmentId) { + return function (data, responseText, jqXHR) { + var result = data.split(";"); + code = result[0]; + text = result[1]; + setStatus(segmentId, "" + text + ""); + + var showOverlay = false; + var overlayImage; + if (code == CONST.CODE_ADDOK) { + // Successful add; show checkmark. + showOverlay = true; + overlayImage = "Checkmark_green.80px.png"; + } else if (code == CONST.CODE_HARD_FAIL) { + // Fatal error, don't try again. + showOverlay = true; + overlayImage = "Red_X.64px.png"; + } + + if (showOverlay) { + $("#import" + segmentId + " :input").attr("disabled", true); + $("#import" + segmentId).block({ + message: + '', + css: { + cursor: "default", + border: "none", + padding: "15px", + // Set this to #000 to add a dark box around the checkbox + backgroundColor: "transparent", + "-webkit-border-radius": "10px", + "-moz-border-radius": "10px", + // Set opacity to .5 or .6 if box enabled above. + opacity: 1, + color: "#fff", + }, + overlayCSS: { + height: $("#segment" + segmentId).height(), + cursor: "default", + }, + }); + } + }; +}; + +/** + * Shortcut for marking a segment as already imported when loading a TripIt list page. + * @param segmentId + */ +function markSegmentImported(segmentId) { + importFlightComplete(segmentId)( + CONST.CODE_ADDOK + ";Segment already imported.", + null, + null + ); +} + +/** + * Shortcut for marking a segment as invalid for import. This shouldn't normally happen. + * @param segmentId + */ +function markSegmentInvalid(segmentId) { + importFlightComplete(segmentId)( + CONST.CODE_HARD_FAIL + ";Insufficient data to import this segment.", + null, + null + ); +} + +/** + * Set the status field for a given segment to message. + * @param segmentId + * @param message + */ +function setStatus(segmentId, message) { + var statusSpan = document.getElementById("input_status" + segmentId); + if (statusSpan != null) { + statusSpan.innerHTML = message; + } +} + +/** + * Import multiple segments at once. Under the covers, this still calls {@link #importFlight}, + * so each segment will result in a call to the service to import. + * @param flights Array of flights to import. + */ +function importFlights(flights) { + for (var i = 0; i < flights.length; i++) { + importFlight(flights[i]); + } +} + +/** + * Add a button to the DOM to import all segments for a given trip id. + * @param importAllButtonValue Text for the Import All button. This should be localized. + * @param tripId ID of the trip. + * @param segments Array of segments to be imported when this button is clicked. + */ +function addImportAllButton(importAllButtonValue, tripId, segments) { + var importAllDiv = document.getElementById("import_all_" + tripId); + if (importAllDiv == null) { + console.log( + "Couldn't find div to insert Import All button for trip " + tripId + ); + return; + } + + importAllDiv.innerHTML = + ''; +} + +/** + * Init method for the rendezvous instruction page. + */ +function rendezvousPageInit() { + $("#loginPathPartner").click(function () { + $("#loginPathSelection").hide(); + $("#loginPathPartnerHelp").show(); + }); + + $("#loginPathNative").click(function () { + window.location.href = "/php/tripit_rendezvous_start.php"; + }); +} + +/** + * Popup a window with TripIt's login page. This is used for rendezvous with partner logins. + */ +function openTripItLogin() { + window.open( + "https://www.tripit.com/account/login", + "TripItLogin", + "width=1000,height=550,scrollbars=yes" + ); +} diff --git a/openflights.css b/openflights.css index 7f046c58..71e190ca 100644 --- a/openflights.css +++ b/openflights.css @@ -107,7 +107,7 @@ div.layersDiv { font-size: 1em; z-index: 1000; padding: 5px 5px 5px 5px; - background-color: #00008B; + background-color: #00008b; -moz-border-radius: 1em 0 0 1em; } @@ -164,7 +164,7 @@ div.layersDiv { padding: 10px 10px 0px 10px; } -#contexthelp{ +#contexthelp { margin: 0px 0px 0px 0px; padding: 10px; } @@ -195,11 +195,23 @@ div.layersDiv { padding: 5px 10px; } -td.donate { padding: 10px; vertical-align: top; text-align: center; } -td.donate2 { padding: 10px; vertical-align: top; text-align: left; } +td.donate { + padding: 10px; + vertical-align: top; + text-align: center; +} +td.donate2 { + padding: 10px; + vertical-align: top; + text-align: left; +} /* Autocomplete styles */ -.autocomplete>div.selected,.autocomplete>div:hover:not(.group){background:#C6DEFF;cursor:pointer} +.autocomplete > div.selected, +.autocomplete > div:hover:not(.group) { + background: #c6deff; + cursor: pointer; +} /* Textbox hinting */ @@ -236,7 +248,8 @@ table.sortable { border: 1px solid #000; border-collapse: collapse; } -table.sortable th, table.sortable td { +table.sortable th, +table.sortable td { text-align: left; padding: 2px 4px 2px 4px; border-style: solid; @@ -263,8 +276,13 @@ table.sortable tr.sortbottom td { /* Misc styles */ -input:focus, textarea:focus { background-color: LightYellow; } -select.filter { width: 160px; } +input:focus, +textarea:focus { + background-color: LightYellow; +} +select.filter { + width: 160px; +} /* OpenLayers default stuff starts here */ @@ -303,7 +321,7 @@ div.olLayerDiv { .olControlScaleLineBottom { border: solid 2px black; border-bottom: none; - margin-top:-2px; + margin-top: -2px; text-align: center; } .olControlScaleLineTop { @@ -337,7 +355,7 @@ div.olControlMousePosition { .olControlOverviewMapElement { padding: 10px 18px 10px 10px; - background-color: #00008B; + background-color: #00008b; -moz-border-radius: 1em 0 0 0; } @@ -369,7 +387,7 @@ div.olControlMousePosition { float: left; width: 100%; overflow: auto; - font-size: 1.0em; + font-size: 1em; } .olLayerGeoRSSClose { float: right; @@ -405,7 +423,6 @@ div.olControlMousePosition { background-repeat: no-repeat; width: 24px; height: 24px; - } .olControlNavigationHistoryPreviousItemActive { background-position: 0px 0px; @@ -490,7 +507,7 @@ div.olControlMousePosition { border: 2px solid red; position: absolute; background-color: white; - opacity: 0.50; + opacity: 0.5; font-size: 1px; filter: alpha(opacity=50); } diff --git a/openflights.js b/openflights.js index 49b40b91..ebb9d455 100644 --- a/openflights.js +++ b/openflights.js @@ -4,32 +4,62 @@ */ // Core map features -var map, proj, drawControls, selectControl, selectedFeature, lineLayer, currentPopup; -var paneStack = [ "ad" ]; +var map, + proj, + drawControls, + selectControl, + selectedFeature, + lineLayer, + currentPopup; +var paneStack = ["ad"]; // User settings (defaults) -var privacy = "Y", flightTotal = 0, prefs_editor = "B", elite = ""; +var privacy = "Y", + flightTotal = 0, + prefs_editor = "B", + elite = ""; // Filter selections and currently chosen airport -var filter_user = 0, filter_trid = 0, filter_alid = 0, filter_year = 0, apid = 0; +var filter_user = 0, + filter_trid = 0, + filter_alid = 0, + filter_year = 0, + apid = 0; var tripname, tripurl; // Current list of flights -var fidList, fidPtr = 0, fid = 0; +var fidList, + fidPtr = 0, + fid = 0; // Query and description of current list var lastQuery, lastDesc; // Temporary variables for current flight being edited -var alid = 0, plane; -var logged_in = false, demo_mode = true, initializing = true; +var alid = 0, + plane; +var logged_in = false, + demo_mode = true, + initializing = true; var input_srcmarker, input_dstmarker, input_line, input_toggle, input_al_toggle; -var changed = false, majorEdit = false; +var changed = false, + majorEdit = false; // Some helpers for multiinput handling -var multiinput_order = [ "src_ap1", "dst_ap1", "dst_ap2", "dst_ap3", "dst_ap4" ]; -var multiinput_ids = [ "src_ap1id", "src_ap2id", "src_ap3id", "src_ap4id", - "dst_ap1id", "dst_ap2id", "dst_ap3id", "dst_ap4id", - "airline1id", "airline2id", "airline3id", "airline4id" ]; +var multiinput_order = ["src_ap1", "dst_ap1", "dst_ap2", "dst_ap3", "dst_ap4"]; +var multiinput_ids = [ + "src_ap1id", + "src_ap2id", + "src_ap3id", + "src_ap4id", + "dst_ap1id", + "dst_ap2id", + "dst_ap3id", + "dst_ap4id", + "airline1id", + "airline2id", + "airline3id", + "airline4id", +]; var multiinput_rows = 1; var URL_FLIGHTS = "/php/flights.php"; @@ -58,23 +88,43 @@ var COLOR_SHIP = "#00ccff"; //cyany blue var COLOR_HIGHLIGHT = "#007fff"; //deeper blue var airportMaxFlights = 0; -var airportIcons = [ [ '/img/icon_plane-13x13.png', 13 ], - [ '/img/icon_plane-15x15.png', 15 ], - [ '/img/icon_plane-17x17.png', 17 ], - [ '/img/icon_plane-19x19b.png', 19 ], - [ '/img/icon_plane-19x19b.png', 19 ], - [ '/img/icon_plane-19x19.png', 19 ] ]; +var airportIcons = [ + ["/img/icon_plane-13x13.png", 13], + ["/img/icon_plane-15x15.png", 15], + ["/img/icon_plane-17x17.png", 17], + ["/img/icon_plane-19x19b.png", 19], + ["/img/icon_plane-19x19b.png", 19], + ["/img/icon_plane-19x19.png", 19], +]; // Redefined with localized strings under init -var classes, seattypes, reasons, classes_short, reasons_short, modenames, modesegments, modeoperators, topmodes; -var modecolors = { "F":COLOR_NORMAL, "T":COLOR_TRAIN, "R":COLOR_ROAD, "S":COLOR_SHIP }; -var modeicons = { "F":'/img/icon_airline.png', "T": '/img/icon_train.png', - "R": '/img/icon_car.png', "S": '/img/icon_ship.png' }; -var modespeeds = { "F":500, "T":100, "R":60, "S":40 }; -var toplimits = { "10":"Top 10", "20":"Top 20", "50":"Top 50", "-1":"All" }; +var classes, + seattypes, + reasons, + classes_short, + reasons_short, + modenames, + modesegments, + modeoperators, + topmodes; +var modecolors = { + F: COLOR_NORMAL, + T: COLOR_TRAIN, + R: COLOR_ROAD, + S: COLOR_SHIP, +}; +var modeicons = { + F: "/img/icon_airline.png", + T: "/img/icon_train.png", + R: "/img/icon_car.png", + S: "/img/icon_ship.png", +}; +var modespeeds = { F: 500, T: 100, R: 60, S: 40 }; +var toplimits = { 10: "Top 10", 20: "Top 20", 50: "Top 50", "-1": "All" }; // Validate YYYY*MM*DD date; contains groups, leading zeroes not required for month, date) -var re_date = /^((19|20)\d\d)[- /.]?([1-9]|0[1-9]|1[012])[- /.]?([1-9]|0[1-9]|[12][0-9]|3[01])$/; +var re_date = + /^((19|20)\d\d)[- /.]?([1-9]|0[1-9]|1[012])[- /.]?([1-9]|0[1-9]|[12][0-9]|3[01])$/; // Validate numeric value var re_numeric = /^[0-9]*$/; @@ -83,217 +133,315 @@ OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3; OpenLayers.Util.onImageLoadErrorColor = "transparent"; // Init Google Charts -google.load('visualization', '1', {packages: ['corechart']}); +google.load("visualization", "1", { packages: ["corechart"] }); // Call init after google is done initing. google.setOnLoadCallback(init); -function init(){ - $("helplink").style.display = 'inline'; - gt = new Gettext({ 'domain' : 'messages' }); - - classes = {"Y": gt.gettext("Economy"), "P": gt.gettext("Prem.Eco"), "C":gt.gettext("Business"), "F":gt.gettext("First"), "": ""}; - seattypes = {"W":gt.gettext("Window"), "A":gt.gettext("Aisle"), "M":gt.gettext("Middle"), "": ""}; - reasons = {"B":gt.gettext("Work"), "L":gt.gettext("Leisure"), "C":gt.gettext("Crew"), "O": gt.gettext("Other"), "": ""}; - classes_short = {"Y":gt.gettext("Econ"), "P":gt.gettext("P.Eco"), "C":gt.gettext("Biz"), "F":gt.gettext("1st"), "": ""}; - reasons_short = {"B":gt.gettext("Work"), "L":gt.gettext("Leis."), "C":gt.gettext("Crew"), "O":gt.gettext("Other"), "": ""}; - modenames = { "F":gt.gettext("Flight"), "T":gt.gettext("Train"), "R":gt.gettext("Road"), "S":gt.gettext("Ship") }; - modesegments = { "F":gt.gettext("flight"), "T":gt.gettext("train"), "R":gt.gettext("road trip"), "S":gt.gettext("ship") }; - modeoperators = { "F":gt.gettext("airline"), "T":gt.gettext("railway"), "R":gt.gettext("road transport"), "S":gt.gettext("shipping") }; - topmodes = { "F":gt.gettext("Segments"), "D":gt.gettext("Mileage") }; - - var projectionName = "EPSG:4326"; // spherical Mercator +function init() { + $("helplink").style.display = "inline"; + gt = new Gettext({ domain: "messages" }); + + classes = { + Y: gt.gettext("Economy"), + P: gt.gettext("Prem.Eco"), + C: gt.gettext("Business"), + F: gt.gettext("First"), + "": "", + }; + seattypes = { + W: gt.gettext("Window"), + A: gt.gettext("Aisle"), + M: gt.gettext("Middle"), + "": "", + }; + reasons = { + B: gt.gettext("Work"), + L: gt.gettext("Leisure"), + C: gt.gettext("Crew"), + O: gt.gettext("Other"), + "": "", + }; + classes_short = { + Y: gt.gettext("Econ"), + P: gt.gettext("P.Eco"), + C: gt.gettext("Biz"), + F: gt.gettext("1st"), + "": "", + }; + reasons_short = { + B: gt.gettext("Work"), + L: gt.gettext("Leis."), + C: gt.gettext("Crew"), + O: gt.gettext("Other"), + "": "", + }; + modenames = { + F: gt.gettext("Flight"), + T: gt.gettext("Train"), + R: gt.gettext("Road"), + S: gt.gettext("Ship"), + }; + modesegments = { + F: gt.gettext("flight"), + T: gt.gettext("train"), + R: gt.gettext("road trip"), + S: gt.gettext("ship"), + }; + modeoperators = { + F: gt.gettext("airline"), + T: gt.gettext("railway"), + R: gt.gettext("road transport"), + S: gt.gettext("shipping"), + }; + topmodes = { F: gt.gettext("Segments"), D: gt.gettext("Mileage") }; + + var projectionName = "EPSG:4326"; // spherical Mercator proj = new OpenLayers.Projection(projectionName); - map = new OpenLayers.Map('map', { + map = new OpenLayers.Map("map", { center: new OpenLayers.LonLat(0, 1682837.6144925), controls: [ new OpenLayers.Control.PanZoom(), - new OpenLayers.Control.Navigation({'title': gt.gettext("Toggle pan and region select mode")}), - new OpenLayers.Control.LayerSwitcher({'ascending':false, 'title': gt.gettext('Switch map layers')}), + new OpenLayers.Control.Navigation({ + title: gt.gettext("Toggle pan and region select mode"), + }), + new OpenLayers.Control.LayerSwitcher({ + ascending: false, + title: gt.gettext("Switch map layers"), + }), new OpenLayers.Control.ScaleLine(), - new OpenLayers.Control.OverviewMap({'title': gt.gettext("Toggle overview map")}), - new OpenLayers.Control.Attribution() - ] }); + new OpenLayers.Control.OverviewMap({ + title: gt.gettext("Toggle overview map"), + }), + new OpenLayers.Control.Attribution(), + ], + }); // Horrible hack to stop OpenLayers 2 from showing ZL < 2 - map.events.register('zoomend', this, function (event) { - if(map.getZoom() < 2) { map.zoomTo(2); } + map.events.register("zoomend", this, function (event) { + if (map.getZoom() < 2) { + map.zoomTo(2); + } }); -var poliLayer = new OpenLayers.Layer.XYZ( + var poliLayer = new OpenLayers.Layer.XYZ( "Political", [ - "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", - "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", - "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", - "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png" - ], { - attribution: "Map tiles © CartoDB (CC BY 3.0), data © OSM (ODbL)", - sphericalMercator: true, - transitionEffect: 'resize', - wrapDateLine: true - }); - -var artLayer = new OpenLayers.Layer.XYZ( + "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", + "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", + "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", + "https://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/${z}/${x}/${y}.png", + ], + { + attribution: + "Map tiles © CartoDB (CC BY 3.0), data © OSM (ODbL)", + sphericalMercator: true, + transitionEffect: "resize", + wrapDateLine: true, + } + ); + + var artLayer = new OpenLayers.Layer.XYZ( "Artistic", - [ - "https://stamen-tiles.a.ssl.fastly.net/watercolor/${z}/${x}/${y}.jpg" - ], { - attribution: "Map tiles © Stamen (CC BY 3.0), data © OSM (CC BY SA)", - sphericalMercator: true, - transitionEffect: 'resize', - wrapDateLine: true - }); + ["https://stamen-tiles.a.ssl.fastly.net/watercolor/${z}/${x}/${y}.jpg"], + { + attribution: + "Map tiles © Stamen (CC BY 3.0), data © OSM (CC BY SA)", + sphericalMercator: true, + transitionEffect: "resize", + wrapDateLine: true, + } + ); artLayer.setVisibility(false); -var earthLayer = new OpenLayers.Layer.XYZ( + var earthLayer = new OpenLayers.Layer.XYZ( "Satellite", [ - "https://api.tiles.mapbox.com/v4/mapbox.satellite/${z}/${x}/${y}.png?access_token=pk.eyJ1IjoianBhdG9rYWwiLCJhIjoiY2lyNmFyZThqMDBiNWcybTFlOWdkZGk1MiJ9.6_VWU3skRwM68ASapMLIQg" - ], { - attribution: "Map tiles © Mapbox", - sphericalMercator: true, - transitionEffect: 'resize', - wrapDateLine: true - }); + "https://api.tiles.mapbox.com/v4/mapbox.satellite/${z}/${x}/${y}.png?access_token=pk.eyJ1IjoianBhdG9rYWwiLCJhIjoiY2lyNmFyZThqMDBiNWcybTFlOWdkZGk1MiJ9.6_VWU3skRwM68ASapMLIQg", + ], + { + attribution: + "Map tiles © Mapbox", + sphericalMercator: true, + transitionEffect: "resize", + wrapDateLine: true, + } + ); earthLayer.setVisibility(false); - lineLayer = new OpenLayers.Layer.Vector(gt.gettext("Flights"), - { projection: projectionName, - styleMap: new OpenLayers.StyleMap({ - strokeColor: "${color}", - strokeOpacity: 1, - strokeWidth: "${count}", - strokeDashstyle: "${stroke}" - }) - }); - - var style = new OpenLayers.Style({graphicTitle: "${name}", - externalGraphic: "${icon}", - graphicWidth: "${size}", - graphicHeight: "${size}", - graphicXOffset: "${offset}", - graphicYOffset: "${offset}", - graphicOpacity: "${opacity}", - pointerEvents: "visiblePainted", - label : "\xA0${code}", - fontColor: "#000000", - fontSize: "9px", - fontFamily: "Calibri, Verdana, Arial, sans-serif", - labelAlign: "lt", - fillColor: "black" - }, { context: { - name: function(feature) { - if(feature.cluster) { - // Last airport is always the largest - last = feature.cluster.length - 1; - if(feature.cluster[last].attributes.index > 2) { - // One airport is dominant, copy its attributes into cluster - feature.attributes.apid = feature.cluster[last].attributes.apid; - feature.attributes.coreid = feature.cluster[last].attributes.coreid; - feature.attributes.code = feature.cluster[last].attributes.code + "+"; - feature.attributes.desc = feature.cluster[last].attributes.desc; - feature.attributes.rdesc = feature.cluster[last].attributes.rdesc; - feature.attributes.icon = feature.cluster[last].attributes.icon; - feature.attributes.size = feature.cluster[last].attributes.size; - feature.attributes.offset = feature.cluster[last].attributes.offset; - feature.attributes.name = feature.cluster[last].attributes.name + " \u2295"; - } else { - // No dominant airport, show cluster icon with aggregate info - name = ""; - for(c = last; c >= 0; c--) { - if(c < last) name += ", "; - name += feature.cluster[c].attributes.code; - } - feature.attributes.icon = "/img/icon_cluster.png"; - feature.attributes.code = ""; - feature.attributes.size = clusterRadius(feature); - feature.attributes.offset = -clusterRadius(feature) / 2; - feature.attributes.name = name; - } - } - return feature.attributes.name; - }, - icon: function(feature) { return feature.attributes.icon; }, - size: function(feature) { return feature.attributes.size; }, - offset: function(feature) { return feature.attributes.offset; }, - opacity: function(feature) { - return feature.cluster ? 1 : feature.attributes.opacity; - }, - code: function(feature) { return feature.attributes.code; } - }}); + lineLayer = new OpenLayers.Layer.Vector(gt.gettext("Flights"), { + projection: projectionName, + styleMap: new OpenLayers.StyleMap({ + strokeColor: "${color}", + strokeOpacity: 1, + strokeWidth: "${count}", + strokeDashstyle: "${stroke}", + }), + }); + + var style = new OpenLayers.Style( + { + graphicTitle: "${name}", + externalGraphic: "${icon}", + graphicWidth: "${size}", + graphicHeight: "${size}", + graphicXOffset: "${offset}", + graphicYOffset: "${offset}", + graphicOpacity: "${opacity}", + pointerEvents: "visiblePainted", + label: "\xA0${code}", + fontColor: "#000000", + fontSize: "9px", + fontFamily: "Calibri, Verdana, Arial, sans-serif", + labelAlign: "lt", + fillColor: "black", + }, + { + context: { + name: function (feature) { + if (feature.cluster) { + // Last airport is always the largest + last = feature.cluster.length - 1; + if (feature.cluster[last].attributes.index > 2) { + // One airport is dominant, copy its attributes into cluster + feature.attributes.apid = feature.cluster[last].attributes.apid; + feature.attributes.coreid = + feature.cluster[last].attributes.coreid; + feature.attributes.code = + feature.cluster[last].attributes.code + "+"; + feature.attributes.desc = feature.cluster[last].attributes.desc; + feature.attributes.rdesc = feature.cluster[last].attributes.rdesc; + feature.attributes.icon = feature.cluster[last].attributes.icon; + feature.attributes.size = feature.cluster[last].attributes.size; + feature.attributes.offset = + feature.cluster[last].attributes.offset; + feature.attributes.name = + feature.cluster[last].attributes.name + " \u2295"; + } else { + // No dominant airport, show cluster icon with aggregate info + name = ""; + for (c = last; c >= 0; c--) { + if (c < last) name += ", "; + name += feature.cluster[c].attributes.code; + } + feature.attributes.icon = "/img/icon_cluster.png"; + feature.attributes.code = ""; + feature.attributes.size = clusterRadius(feature); + feature.attributes.offset = -clusterRadius(feature) / 2; + feature.attributes.name = name; + } + } + return feature.attributes.name; + }, + icon: function (feature) { + return feature.attributes.icon; + }, + size: function (feature) { + return feature.attributes.size; + }, + offset: function (feature) { + return feature.attributes.offset; + }, + opacity: function (feature) { + return feature.cluster ? 1 : feature.attributes.opacity; + }, + code: function (feature) { + return feature.attributes.code; + }, + }, + } + ); var renderer = OpenLayers.Util.getParameters(window.location.href).renderer; - renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers; - var strategy = new OpenLayers.Strategy.Cluster({distance: 15, threshold: 3}); - airportLayer = new OpenLayers.Layer.Vector("Airports", - { projection: projectionName, - styleMap: new OpenLayers.StyleMap - ({'default': style, - 'select':{ - fillOpacity: 1.0, - pointerEvents: "visiblePainted", - label : "" - }}), - renderers: renderer, - strategies: [strategy]}); + renderer = renderer + ? [renderer] + : OpenLayers.Layer.Vector.prototype.renderers; + var strategy = new OpenLayers.Strategy.Cluster({ + distance: 15, + threshold: 3, + }); + airportLayer = new OpenLayers.Layer.Vector("Airports", { + projection: projectionName, + styleMap: new OpenLayers.StyleMap({ + default: style, + select: { + fillOpacity: 1.0, + pointerEvents: "visiblePainted", + label: "", + }, + }), + renderers: renderer, + strategies: [strategy], + }); map.addLayers([poliLayer, artLayer, earthLayer, lineLayer, airportLayer]); - selectControl = new OpenLayers.Control.SelectFeature(airportLayer, {onSelect: onAirportSelect, - onUnselect: onAirportUnselect}); + selectControl = new OpenLayers.Control.SelectFeature(airportLayer, { + onSelect: onAirportSelect, + onUnselect: onAirportUnselect, + }); map.addControl(selectControl); selectControl.activate(); // When using the earth map layer, change the font color from black to white, since the map is mostly dark colors. map.events.on({ - "changelayer":function () { - if(earthLayer.visibility) { + changelayer: function () { + if (earthLayer.visibility) { style.defaultStyle.fontColor = "#fff"; } else { style.defaultStyle.fontColor = "#000"; } - } + }, }); // Extract any arguments from URL var query; arguments = parseUrl(); - switch(arguments[0]) { - case "trip": - filter_trid = arguments[1]; - break; - case "user": - filter_user = arguments[1]; - break; - case "query": - case "airport": - case "airline": - query = arguments[1]; + switch (arguments[0]) { + case "trip": + filter_trid = arguments[1]; + break; + case "user": + filter_user = arguments[1]; + break; + case "query": + case "airport": + case "airline": + query = arguments[1]; } initHintTextboxes(); prepareAutocomplete("qs", { successCb: getQuickSearchId, - failureCb: (e) => undefined + failureCb: (e) => undefined, }); // Are we viewing another user's flights or trip? - if(filter_user != "0" || filter_trid != 0) { + if (filter_user != "0" || filter_trid != 0) { demo_mode = false; - $("loginstatus").style.display = 'inline'; - if(filter_trid != 0) { - $("filter_tripselect").style.display = 'none'; + $("loginstatus").style.display = "inline"; + if (filter_trid != 0) { + $("filter_tripselect").style.display = "none"; } } else { - $("news").style.display = 'inline'; - $("quicksearch").style.display = 'inline'; + $("news").style.display = "inline"; + $("quicksearch").style.display = "inline"; // Nope, set up hinting and autocompletes for editor - ac_airport = [ "src_ap", "src_ap1", "src_ap2", "src_ap3", "src_ap4", - "dst_ap", "dst_ap1", "dst_ap2", "dst_ap3", "dst_ap4" ]; - ac_airline = [ "airline", "airline1", "airline2", "airline3", "airline4" ]; - ac_plane = [ "plane" ]; + ac_airport = [ + "src_ap", + "src_ap1", + "src_ap2", + "src_ap3", + "src_ap4", + "dst_ap", + "dst_ap1", + "dst_ap2", + "dst_ap3", + "dst_ap4", + ]; + ac_airline = ["airline", "airline1", "airline2", "airline3", "airline4"]; + ac_plane = ["plane"]; for (const airportAutoCompInputId of ac_airport) { prepareAutocomplete(airportAutoCompInputId, { @@ -302,7 +450,7 @@ var earthLayer = new OpenLayers.Layer.XYZ( }, failureCb: (error) => { invalidateField(airportAutoCompInputId, true); - } + }, }); } @@ -310,7 +458,7 @@ var earthLayer = new OpenLayers.Layer.XYZ( prepareAutocomplete(airlineAutoCompInputId, { successCb: (item) => { getSelectedAlid(airlineAutoCompInputId, item.value); - } + }, }); } @@ -318,47 +466,47 @@ var earthLayer = new OpenLayers.Layer.XYZ( prepareAutocomplete(planeAutoCompInputId, { successCb: (item) => { getSelectedPlid(planeAutoCompInputId, item.value); - } + }, }); } // No idea why this is needed, but FF3 disables random buttons without it... - for(i=0;i 29) radius = 29; + if (radius > 29) radius = 29; return radius; } // Extract arguments from URL (/command/value, eg. /trip/123 or /user/foo) -function parseUrl() -{ +function parseUrl() { // http://foobar.com/name/xxx#blah *or* xxx?blah=blah // 0 1 2 3 4 3 4 var urlbits = window.location.href.split(/[\/#?]+/); - if(urlbits.length > 3) { + if (urlbits.length > 3) { return [urlbits[2], unescape(urlbits[3])]; - } else return [null,null]; + } else return [null, null]; } function projectedPoint(x, y) { @@ -376,29 +524,49 @@ function projectedLine(points) { // Draw a flight connecting (x1,y1)-(x2,y2) // Note: Values passed in *must already be parsed as floats* or very strange things happen function drawLine(x1, y1, x2, y2, count, distance, color, stroke) { - if(! color) { + if (!color) { color = COLOR_NORMAL; } - if(! stroke) { + if (!stroke) { stroke = "solid"; } // 1,2 flights as single pixel count = Math.floor(Math.sqrt(count) + 0.5); - var paths = [ gcPath(new OpenLayers.Geometry.Point(x1, y1), new OpenLayers.Geometry.Point(x2, y2)) ]; + var paths = [ + gcPath( + new OpenLayers.Geometry.Point(x1, y1), + new OpenLayers.Geometry.Point(x2, y2) + ), + ]; // Path is in or extends into east (+) half, so we have to make a -360 copy - if(x1 > 0 || x2 > 0) { - paths.push(gcPath(new OpenLayers.Geometry.Point(x1-360, y1), new OpenLayers.Geometry.Point(x2-360, y2))); + if (x1 > 0 || x2 > 0) { + paths.push( + gcPath( + new OpenLayers.Geometry.Point(x1 - 360, y1), + new OpenLayers.Geometry.Point(x2 - 360, y2) + ) + ); } // Path is in or extends into west (-) half, so we have to make a +360 copy - if(x1 < 0 || x2 < 0) { - paths.push(gcPath(new OpenLayers.Geometry.Point(x1+360, y1), new OpenLayers.Geometry.Point(x2+360, y2))); + if (x1 < 0 || x2 < 0) { + paths.push( + gcPath( + new OpenLayers.Geometry.Point(x1 + 360, y1), + new OpenLayers.Geometry.Point(x2 + 360, y2) + ) + ); } var features = []; - for(i = 0; i < paths.length; i++) { - features.push(new OpenLayers.Feature.Vector(projectedLine(paths[i]), - {count: count, color: color, stroke: stroke})); + for (i = 0; i < paths.length; i++) { + features.push( + new OpenLayers.Feature.Vector(projectedLine(paths[i]), { + count: count, + color: color, + stroke: stroke, + }) + ); } return features; } @@ -407,8 +575,7 @@ function drawLine(x1, y1, x2, y2, count, distance, color, stroke) { // `autocomplete.js` wrapper to encapsulate logic dealing with setting up the // autocomplete widgets and interacting with the autocomplete API endpoint. // -function prepareAutocomplete(inputId, {successCb, failureCb}) { - +function prepareAutocomplete(inputId, { successCb, failureCb }) { const inputElement = document.getElementById(inputId); autocomplete({ @@ -418,41 +585,43 @@ function prepareAutocomplete(inputId, {successCb, failureCb}) { fetch: (text, update) => { showLoadingAnimation(true); fetch(URL_GETCODE, { - method: 'POST', + method: "POST", headers: { - "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" + "Content-type": "application/x-www-form-urlencoded; charset=UTF-8", }, - body: encodeURI(`${inputId}=${text}`) - }).then((response) => { - if (response.status !== 200) { - throw new Error(response.status); - } - return response.text(); - }).then((text) => { - const responseXML = (new DOMParser()).parseFromString(text, "text/xml"); - - const suggestions = []; - const ul = responseXML.firstChild; - ul.childNodes.forEach((elem) => { - // Skip over newline text nodes - if (elem.nodeName === 'li') - suggestions.push({label: elem.firstChild.data, value: elem.id}) + body: encodeURI(`${inputId}=${text}`), + }) + .then((response) => { + if (response.status !== 200) { + throw new Error(response.status); + } + return response.text(); + }) + .then((text) => { + const responseXML = new DOMParser().parseFromString(text, "text/xml"); + + const suggestions = []; + const ul = responseXML.firstChild; + ul.childNodes.forEach((elem) => { + // Skip over newline text nodes + if (elem.nodeName === "li") + suggestions.push({ label: elem.firstChild.data, value: elem.id }); + }); + + update(suggestions); + }) + .catch((e) => { + if (failureCb) failureCb(e); + else invalidateField(inputId); + }) + .finally(() => { + showLoadingAnimation(false); }); - - update(suggestions); - }).catch((e) => { - if (failureCb) - failureCb(e); - else - invalidateField(inputId); - }).finally(() => { - showLoadingAnimation(false); - }); }, onSelect: (item) => { inputElement.value = item.label; successCb(item); - } + }, }); } @@ -462,7 +631,17 @@ function prepareAutocomplete(inputId, {successCb, failureCb}) { // // coreid -- apid of "core" airport at the center of a map of routes // -function drawAirport(airportLayer, apdata, name, city, country, count, formattedName, opacity, coreid) { +function drawAirport( + airportLayer, + apdata, + name, + city, + country, + count, + formattedName, + opacity, + coreid +) { var apcols = apdata.split(":"); var code = apcols[0]; var apid = apcols[1]; @@ -470,34 +649,59 @@ function drawAirport(airportLayer, apdata, name, city, country, count, formatted var y = apcols[3]; // Description - var desc = name + " (" + code + ")
" + city + ", " + country + "
Flights: " + count; - var rdesc = name + " (" + code + ")
" + city + ", " + country + ""; + var desc = + name + + " (" + + code + + ")
" + + city + + ", " + + country + + "
Flights: " + + count; + var rdesc = + name + + " (" + + code + + ")
" + + city + + ", " + + country + + ""; // Select icon based on number of flights (0...airportIcons.length-1) - var colorIndex = Math.floor((count / airportMaxFlights) * airportIcons.length) + 1; + var colorIndex = + Math.floor((count / airportMaxFlights) * airportIcons.length) + 1; // Two or less flights: smallest dot - if(count <= 2 || colorIndex < 0) { + if (count <= 2 || colorIndex < 0) { colorIndex = 0; } // More than two flights: at least 2nd smallest - if(count > 2) { + if (count > 2) { colorIndex = Math.max(1, colorIndex); } // Max out at top color // Core airport of route map always uses max color - if(colorIndex >= airportIcons.length || apid == coreid) { + if (colorIndex >= airportIcons.length || apid == coreid) { colorIndex = airportIcons.length - 1; } // This should never happen - if(! airportIcons[colorIndex]) { - $("news").style.display = 'inline'; - $("news").innerHTML = "ERROR: " + name + ":" + colorIndex + " of " + airportMaxFlights + ".i
Please hit CTRL-F5 to force refresh, and report this error if it does not go away."; + if (!airportIcons[colorIndex]) { + $("news").style.display = "inline"; + $("news").innerHTML = + "ERROR: " + + name + + ":" + + colorIndex + + " of " + + airportMaxFlights + + ".i
Please hit CTRL-F5 to force refresh, and report this error if it does not go away."; colorIndex = 0; return; } - var feature = new OpenLayers.Feature.Vector(projectedPoint(x,y)); + var feature = new OpenLayers.Feature.Vector(projectedPoint(x, y)); feature.attributes = { apid: apid, coreid: coreid, @@ -510,7 +714,7 @@ function drawAirport(airportLayer, apdata, name, city, country, count, formatted icon: airportIcons[colorIndex][0], size: airportIcons[colorIndex][1], index: count, - offset: Math.floor(-airportIcons[colorIndex][1]/2) + offset: Math.floor(-airportIcons[colorIndex][1] / 2), }; return feature; @@ -528,61 +732,112 @@ function onAirportSelect(airport) { rdesc = airport.attributes.rdesc; // Single airport? - if(!airport.cluster) { + if (!airport.cluster) { // Add toolbar to popup - desc = "" + - ""; - - if(coreid == 0) { + desc = + "" + + ""; + + if (coreid == 0) { // Detailed flights accessible only if... // 1. user is logged in, or // 2. system is in "demo mode", or // 3. privacy is set to (O)pen - if( logged_in || demo_mode || privacy == "O") { - // Get list of user flights - desc += " "; + if (logged_in || demo_mode || privacy == "O") { + // Get list of user flights + desc += + " "; } } else { - if(code.length == 3) { - // Get list of airport routes - if(coreid.startsWith("L")) { - idstring = coreid + "," + apid; - } else { - idstring = "R" + apid + "," + coreid; - } - desc += " "; + if (code.length == 3) { + // Get list of airport routes + if (coreid.startsWith("L")) { + idstring = coreid + "," + apid; + } else { + idstring = "R" + apid + "," + coreid; + } + desc += + " "; } } - if(code.length == 3) { + if (code.length == 3) { // IATA airport, we know its routes - desc += " "; + desc += + " "; } - desc += " "; - desc += "" + airport.attributes.desc.replace("Flights:", gt.gettext("Flights:")); + desc += + " "; + desc += + "" + + airport.attributes.desc.replace("Flights:", gt.gettext("Flights:")); } else { // Cluster, generate clickable list of members in reverse order (most flights first) desc = "" + gt.gettext("Airports") + "
"; edit = isEditMode() ? "true" : "false"; cmax = airport.cluster.length - 1; - for(c = cmax; c >= 0; c--) { - if(c < cmax) { - desc += ", "; - if((cmax-c) % 6 == 0) desc += "
"; + for (c = cmax; c >= 0; c--) { + if (c < cmax) { + desc += ", "; + if ((cmax - c) % 6 == 0) desc += "
"; } - desc += "" + airport.cluster[c].attributes.code + ""; + desc += + "" + + airport.cluster[c].attributes.code + + ""; } } - desc = " " + desc; + desc = + ' ' + + desc; closePopup(false); if (airport.popup == null) { - airport.popup = new OpenLayers.Popup.FramedCloud("airport", - airport.geometry.getBounds().getCenterLonLat(), - new OpenLayers.Size(200,80), - desc, null, false); - airport.popup.minSize = new OpenLayers.Size(200,80); + airport.popup = new OpenLayers.Popup.FramedCloud( + "airport", + airport.geometry.getBounds().getCenterLonLat(), + new OpenLayers.Size(200, 80), + desc, + null, + false + ); + airport.popup.minSize = new OpenLayers.Size(200, 80); airport.popup.overflow = "auto"; map.addPopup(airport.popup); @@ -591,17 +846,17 @@ function onAirportSelect(airport) { airport.popup.setContentHTML(desc); airport.popup.toggle(); } - if(airport.popup.visible()) { + if (airport.popup.visible()) { currentPopup = airport.popup; } else { closePane(); } // Show or hide toolbar when applicable - if($('popup' + apid)) { - if(isEditMode()) { - $('popup' + apid).style.visibility = "visible"; + if ($("popup" + apid)) { + if (isEditMode()) { + $("popup" + apid).style.visibility = "visible"; } else { - $('popup' + apid).style.visibility = "hidden"; + $("popup" + apid).style.visibility = "hidden"; } } } @@ -611,9 +866,9 @@ function onAirportUnselect(airport) { } function toggleControl(element) { - for(key in drawControls) { + for (key in drawControls) { var control = drawControls[key]; - if(element.value == key && element.checked) { + if (element.value == key && element.checked) { control.activate(); } else { control.deactivate(); @@ -627,7 +882,7 @@ function xmlhttpPost(strURL, id, param) { var self = this; var query = ""; - if(! initializing) closeNews(); + if (!initializing) closeNews(); // Mozilla/Safari if (window.XMLHttpRequest) { @@ -637,435 +892,534 @@ function xmlhttpPost(strURL, id, param) { else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } - self.xmlHttpReq.open('POST', strURL, true); - self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - self.xmlHttpReq.onreadystatechange = function() { + self.xmlHttpReq.open("POST", strURL, true); + self.xmlHttpReq.setRequestHeader( + "Content-Type", + "application/x-www-form-urlencoded" + ); + self.xmlHttpReq.onreadystatechange = function () { if (self.xmlHttpReq.readyState == 4) { - // Process results of query // First make sure session is still up // (note: sessionfree PHPs do not return this string) - if(self.xmlHttpReq.responseText.substring(0, 13) == "Not logged in") { - logout(self.xmlHttpReq.responseText); - return; - } - - if(strURL == URL_FLIGHTS) { - switch(param) { - case "COPY": - case "EDIT": - editFlight(self.xmlHttpReq.responseText, param); - break; - - case "RELOAD": - param = lastDesc; - // param contains previously escaped semi-random HTML title - // fallthru - - case "MAP": - default: - listFlights(self.xmlHttpReq.responseText, unescape(param), id); - break; - } - showLoadingAnimation(false); + if (self.xmlHttpReq.responseText.substring(0, 13) == "Not logged in") { + logout(self.xmlHttpReq.responseText); + return; } - if(strURL == URL_GETCODE) { - var cols = self.xmlHttpReq.responseText.split(";"); - switch(param) { - case 'qs': - var alid = cols[0]; - if(alid != "" && alid != 0) { - if(cols[0].indexOf(":") > 0) { - $('qsid').value = cols[0].split(":")[1]; // airport - } else { - $('qsid').value = "L" + cols[0]; // airline - } - $('qs').value = cols[1]; - $('qs').style.color = '#000000'; - $('qsgo').disabled = false; - $('qsgo').focus(); - } else { - $('qsid').value = 0; - $('qs').style.color = '#FF0000'; - $('qsgo').disabled = true; - } - break; - - case 'airline': - case 'airline1': - case 'airline2': - case 'airline3': - case 'airline4': - var alid = cols[0]; - if(alid != "" && alid != 0) { - $(param + 'id').value = cols[0]; - $(param).value = cols[1]; - $(param).style.color = '#000000'; - replicateSelection(param); - markAsChanged(true); // new airline, force refresh on save - } else { - $(param).style.color = '#FF0000'; - $(param + 'id').value = 0; - } - break; - - case 'src_ap': - case 'dst_ap': - case 'src_ap1': - case 'dst_ap1': - case 'src_ap2': - case 'dst_ap2': - case 'src_ap3': - case 'dst_ap3': - case 'src_ap4': - case 'dst_ap4': - var apdata = cols[0]; - var apid = apdata.split(":")[1]; - if(apid && apid != 0) { - $(param + 'id').value = apdata; - $(param).value = cols[1]; - $(param).style.color = '#000000'; - replicateSelection(param); - markAirport(param); // new airport, force refresh on save - markAsChanged(true); - } else { - invalidateField(param); - } - break; - } - } - if(strURL == URL_LOGIN) { - login(self.xmlHttpReq.responseText, param); - } - if(strURL == URL_LOGOUT) { - logout(self.xmlHttpReq.responseText); - } - if(strURL == URL_MAP || strURL == URL_ROUTES) { - var str = self.xmlHttpReq.responseText; - if(str.substring(0,6) == "Signup") { - window.location = "/html/settings?new=yes&vbulletin=true" - } - if(str.substring(0,5) == "Error") { - $("result").innerHTML = "

" + str.split(';')[1] + "


Home
"; + + if (strURL == URL_FLIGHTS) { + switch (param) { + case "COPY": + case "EDIT": + editFlight(self.xmlHttpReq.responseText, param); + break; + + case "RELOAD": + param = lastDesc; + // param contains previously escaped semi-random HTML title + // fallthru + + case "MAP": + default: + listFlights(self.xmlHttpReq.responseText, unescape(param), id); + break; + } showLoadingAnimation(false); - openPane("result"); - } else { - // Zoom map to fit when first loading another's flights/trip - updateMap(str, strURL); - if(! logged_in && ! demo_mode && initializing) { - closePane(); - var extent = airportLayer.getDataExtent(); - if(extent) map.zoomToExtent(extent); - } - if(strURL == URL_MAP) { - if(param) { - updateFilter(str); - } - $("maptitle").innerHTML = getMapTitle(true); - } else { - updateFilter(str); - closePopup(true); - $('qs').value = $('qs').hintText; - $('qs').style.color = '#888'; - $('qsid').value = 0; - $('qsgo').disabled = true; - if(filter_alid == 0) { - var extent = airportLayer.getDataExtent(); - if(extent) map.zoomToExtent(extent); - } - } - - // Map now completely drawn for the first time - if(initializing) { - initializing = false; - } - } - } - if(strURL == URL_STATS) { + } + if (strURL == URL_GETCODE) { + var cols = self.xmlHttpReq.responseText.split(";"); + switch (param) { + case "qs": + var alid = cols[0]; + if (alid != "" && alid != 0) { + if (cols[0].indexOf(":") > 0) { + $("qsid").value = cols[0].split(":")[1]; // airport + } else { + $("qsid").value = "L" + cols[0]; // airline + } + $("qs").value = cols[1]; + $("qs").style.color = "#000000"; + $("qsgo").disabled = false; + $("qsgo").focus(); + } else { + $("qsid").value = 0; + $("qs").style.color = "#FF0000"; + $("qsgo").disabled = true; + } + break; + + case "airline": + case "airline1": + case "airline2": + case "airline3": + case "airline4": + var alid = cols[0]; + if (alid != "" && alid != 0) { + $(param + "id").value = cols[0]; + $(param).value = cols[1]; + $(param).style.color = "#000000"; + replicateSelection(param); + markAsChanged(true); // new airline, force refresh on save + } else { + $(param).style.color = "#FF0000"; + $(param + "id").value = 0; + } + break; + + case "src_ap": + case "dst_ap": + case "src_ap1": + case "dst_ap1": + case "src_ap2": + case "dst_ap2": + case "src_ap3": + case "dst_ap3": + case "src_ap4": + case "dst_ap4": + var apdata = cols[0]; + var apid = apdata.split(":")[1]; + if (apid && apid != 0) { + $(param + "id").value = apdata; + $(param).value = cols[1]; + $(param).style.color = "#000000"; + replicateSelection(param); + markAirport(param); // new airport, force refresh on save + markAsChanged(true); + } else { + invalidateField(param); + } + break; + } + } + if (strURL == URL_LOGIN) { + login(self.xmlHttpReq.responseText, param); + } + if (strURL == URL_LOGOUT) { + logout(self.xmlHttpReq.responseText); + } + if (strURL == URL_MAP || strURL == URL_ROUTES) { + var str = self.xmlHttpReq.responseText; + if (str.substring(0, 6) == "Signup") { + window.location = "/html/settings?new=yes&vbulletin=true"; + } + if (str.substring(0, 5) == "Error") { + $("result").innerHTML = + "

" + + str.split(";")[1] + + "


Home
"; + showLoadingAnimation(false); + openPane("result"); + } else { + // Zoom map to fit when first loading another's flights/trip + updateMap(str, strURL); + if (!logged_in && !demo_mode && initializing) { + closePane(); + var extent = airportLayer.getDataExtent(); + if (extent) map.zoomToExtent(extent); + } + if (strURL == URL_MAP) { + if (param) { + updateFilter(str); + } + $("maptitle").innerHTML = getMapTitle(true); + } else { + updateFilter(str); + closePopup(true); + $("qs").value = $("qs").hintText; + $("qs").style.color = "#888"; + $("qsid").value = 0; + $("qsgo").disabled = true; + if (filter_alid == 0) { + var extent = airportLayer.getDataExtent(); + if (extent) map.zoomToExtent(extent); + } + } + + // Map now completely drawn for the first time + if (initializing) { + initializing = false; + } + } + } + if (strURL == URL_STATS) { showStats(self.xmlHttpReq.responseText); showLoadingAnimation(false); } - if(strURL == URL_TOP10) { + if (strURL == URL_TOP10) { showTop10(self.xmlHttpReq.responseText); showLoadingAnimation(false); } - if(strURL == URL_SUBMIT) { - var result = self.xmlHttpReq.responseText.split(";"); - code = result[0]; - text = result[1]; - if(getCurrentPane() == "multiinput") { - $("multiinput_status").innerHTML = '' + text + ''; - } else { - $("input_status").innerHTML = '' + text + ''; - } - setCommitAllowed(false); - - // Something went wrong, so we just abort - if(code == CODE_FAIL) { - return; - } - - // If flight was successfully deleted... - if(code == CODE_DELETEOK) { - - //... and we're in input mode, move to another flight - if(getCurrentPane() == "input") { - // Last flight deleted - if(fidList.length == 1) { - clearStack(); - } else { - // Remove current flight - fidList.splice(fidPtr, 1); - - // Edit next if you can - if(fidPtr < fidList.length) { - editPointer(0); - } else { - // Move back - editPointer(-1); - } - } - } else { - // Not in edit mode, so reload currently displayed list of flights - xmlhttpPost(URL_FLIGHTS, 0, "RELOAD"); - } - majorEdit = true; // trigger map refresh - } - - if(code == CODE_EDITOK || code == CODE_ADDOK) { - // If adding new flights (not editing), swap last destination to be new source and focus on date - if(getCurrentPane() == "input") { - if($("addflighttitle").style.display == 'inline') { - swapAirports(false); - document.forms['inputform'].seat.value = ""; - document.forms['inputform'].seat_type.selectedIndex = 0; - document.forms['inputform'].src_date.focus(); - } - } else { - clearInput(); // Always clear multiview - } - } - - // A change that affected the map was made, so redraw - if(majorEdit) { - if(code == CODE_DELETEOK) { - setTimeout('refresh(true)', 1000); // wait for earlier ops to complete... - } else { - refresh(true); // ...else do it right now - } - } else { - showLoadingAnimation(false); - } - majorEdit = false; + if (strURL == URL_SUBMIT) { + var result = self.xmlHttpReq.responseText.split(";"); + code = result[0]; + text = result[1]; + if (getCurrentPane() == "multiinput") { + $("multiinput_status").innerHTML = "" + text + ""; + } else { + $("input_status").innerHTML = "" + text + ""; + } + setCommitAllowed(false); + + // Something went wrong, so we just abort + if (code == CODE_FAIL) { + return; + } + + // If flight was successfully deleted... + if (code == CODE_DELETEOK) { + //... and we're in input mode, move to another flight + if (getCurrentPane() == "input") { + // Last flight deleted + if (fidList.length == 1) { + clearStack(); + } else { + // Remove current flight + fidList.splice(fidPtr, 1); + + // Edit next if you can + if (fidPtr < fidList.length) { + editPointer(0); + } else { + // Move back + editPointer(-1); + } + } + } else { + // Not in edit mode, so reload currently displayed list of flights + xmlhttpPost(URL_FLIGHTS, 0, "RELOAD"); + } + majorEdit = true; // trigger map refresh + } + + if (code == CODE_EDITOK || code == CODE_ADDOK) { + // If adding new flights (not editing), swap last destination to be new source and focus on date + if (getCurrentPane() == "input") { + if ($("addflighttitle").style.display == "inline") { + swapAirports(false); + document.forms["inputform"].seat.value = ""; + document.forms["inputform"].seat_type.selectedIndex = 0; + document.forms["inputform"].src_date.focus(); + } + } else { + clearInput(); // Always clear multiview + } + } + + // A change that affected the map was made, so redraw + if (majorEdit) { + if (code == CODE_DELETEOK) { + setTimeout("refresh(true)", 1000); // wait for earlier ops to complete... + } else { + refresh(true); // ...else do it right now + } + } else { + showLoadingAnimation(false); + } + majorEdit = false; } // end URL_SUBMIT } - } + }; // End result processing // Start query string generation - switch(strURL) { - - case URL_SUBMIT: - var inputform = document.forms['inputform']; - - // Deleting needs only the fid, and can be run without the inputform - if(param != "DELETE") { - if(getCurrentPane() == "multiinput") { - query = 'multi=' + multiinput_rows + '&'; - var indexes = []; - for(i = 1; i <= multiinput_rows; i++) { - indexes.push(i); - } - } else { - var indexes = [ "" ]; - } - for(i = 0; i < indexes.length; i++) { - var src_date = $('src_date' + indexes[i]).value; - if(! re_date.test(src_date)) { - alert(gt.gettext("Please enter a full date in year/month/date order, eg. 2008/10/30 for 30 October 2008. Valid formats include YYYY-MM-DD, YYYY/MM/DD, YYYY.MM.DD and YYYY MM DD.")); - $('src_date' + indexes[i]).focus(); - return; - } - var src_apid = getApid('src_ap' + indexes[i]); - if(! src_apid || src_apid == "0") { - alert(gt.gettext("Please enter a valid source airport.")); - $('src_ap' + indexes[i]).focus(); - return; - } - var dst_apid = getApid('dst_ap' + indexes[i]); - if(! dst_apid || dst_apid == "0") { - alert(gt.gettext("Please enter a valid destination airport.")); - $('dst_ap' + indexes[i]).focus(); - return; - } - var alid = $('airline' + indexes[i] + 'id').value; - var airline = $('airline' + indexes[i]).value.trim(); - if(! alid || alid == 0) { - if(airline == "" || airline == $('airline').hintText) { - alid = "-1"; // UNKNOWN - } else { - mode = getMode(); - if(confirm(Gettext.strargs(gt.gettext("'%1' not found in %2 database. Do you want to add it as a new %2 company?"), [airline, modeoperators[mode], modeoperators[mode]]))) { - popNewAirline('airline' + indexes[i], airline, mode); - } else { - $('airline' + indexes[i]).focus(); - } - return; - } - } - query +='alid' + indexes[i] + '=' + encodeURIComponent(alid) + '&' + - 'src_date' + indexes[i] + '=' + encodeURIComponent(src_date) + '&' + - 'src_apid' + indexes[i] + '=' + encodeURIComponent(src_apid) + '&' + - 'dst_apid' + indexes[i] + '=' + encodeURIComponent(dst_apid) + '&'; - } - if(getCurrentPane() == "input") { - src_time = $('src_time').value; - if(src_time != "" && src_time != "HH:MM") { - if(! RE_TIME.test(src_time)) { - alert(gt.gettext("Please enter times in 24-hour format with a colon between hour and minute, eg. 21:37 for 9:37 PM.")); - $('src_time').focus(); - return; - } - query += 'src_time=' + encodeURIComponent(src_time) + '&'; - } - - var type = inputform.seat_type.value; - if(type == "-") type = ""; - var myClass = radioValue(inputform.myClass); - var reason = radioValue(inputform.reason); - var plane = inputform.plane.value; - if(plane == gt.gettext("Enter plane model")) { - plane = ""; - } - var trid = 0; - if(inputform.trips) { - trid = inputform.trips[inputform.trips.selectedIndex].value.split(";")[0]; - } - if(trid == 0) trid = "NULL"; - var registration = inputform.registration.value; - var note = inputform.note.value; - var duration = $('duration').value; - if(! RE_TIME.test(duration)) { - alert(gt.gettext("Please enter flight duration as hours and minutes with a colon between hour and minute, eg. 5:37 for 5 hours, 37 minutes. You can blank the duration to have it recalculated automatically.")); - $('duration').focus(); - return; - } - var distance = $('distance').value; - if(! re_numeric.test(distance)) { - alert(gt.gettext("Please enter flight distance as miles, with no fractional parts. You can blank the distance to have it re-calculated automatically.")); - $('distance').focus(); - return; - } - var number = inputform.number.value; - var seat = inputform.seat.value; - var mode = inputform.mode.value; + switch (strURL) { + case URL_SUBMIT: + var inputform = document.forms["inputform"]; + + // Deleting needs only the fid, and can be run without the inputform + if (param != "DELETE") { + if (getCurrentPane() == "multiinput") { + query = "multi=" + multiinput_rows + "&"; + var indexes = []; + for (i = 1; i <= multiinput_rows; i++) { + indexes.push(i); + } + } else { + var indexes = [""]; + } + for (i = 0; i < indexes.length; i++) { + var src_date = $("src_date" + indexes[i]).value; + if (!re_date.test(src_date)) { + alert( + gt.gettext( + "Please enter a full date in year/month/date order, eg. 2008/10/30 for 30 October 2008. Valid formats include YYYY-MM-DD, YYYY/MM/DD, YYYY.MM.DD and YYYY MM DD." + ) + ); + $("src_date" + indexes[i]).focus(); + return; + } + var src_apid = getApid("src_ap" + indexes[i]); + if (!src_apid || src_apid == "0") { + alert(gt.gettext("Please enter a valid source airport.")); + $("src_ap" + indexes[i]).focus(); + return; + } + var dst_apid = getApid("dst_ap" + indexes[i]); + if (!dst_apid || dst_apid == "0") { + alert(gt.gettext("Please enter a valid destination airport.")); + $("dst_ap" + indexes[i]).focus(); + return; + } + var alid = $("airline" + indexes[i] + "id").value; + var airline = $("airline" + indexes[i]).value.trim(); + if (!alid || alid == 0) { + if (airline == "" || airline == $("airline").hintText) { + alid = "-1"; // UNKNOWN + } else { + mode = getMode(); + if ( + confirm( + Gettext.strargs( + gt.gettext( + "'%1' not found in %2 database. Do you want to add it as a new %2 company?" + ), + [airline, modeoperators[mode], modeoperators[mode]] + ) + ) + ) { + popNewAirline("airline" + indexes[i], airline, mode); + } else { + $("airline" + indexes[i]).focus(); + } + return; + } + } + query += + "alid" + + indexes[i] + + "=" + + encodeURIComponent(alid) + + "&" + + "src_date" + + indexes[i] + + "=" + + encodeURIComponent(src_date) + + "&" + + "src_apid" + + indexes[i] + + "=" + + encodeURIComponent(src_apid) + + "&" + + "dst_apid" + + indexes[i] + + "=" + + encodeURIComponent(dst_apid) + + "&"; + } + if (getCurrentPane() == "input") { + src_time = $("src_time").value; + if (src_time != "" && src_time != "HH:MM") { + if (!RE_TIME.test(src_time)) { + alert( + gt.gettext( + "Please enter times in 24-hour format with a colon between hour and minute, eg. 21:37 for 9:37 PM." + ) + ); + $("src_time").focus(); + return; + } + query += "src_time=" + encodeURIComponent(src_time) + "&"; + } + + var type = inputform.seat_type.value; + if (type == "-") type = ""; + var myClass = radioValue(inputform.myClass); + var reason = radioValue(inputform.reason); + var plane = inputform.plane.value; + if (plane == gt.gettext("Enter plane model")) { + plane = ""; + } + var trid = 0; + if (inputform.trips) { + trid = + inputform.trips[inputform.trips.selectedIndex].value.split( + ";" + )[0]; + } + if (trid == 0) trid = "NULL"; + var registration = inputform.registration.value; + var note = inputform.note.value; + var duration = $("duration").value; + if (!RE_TIME.test(duration)) { + alert( + gt.gettext( + "Please enter flight duration as hours and minutes with a colon between hour and minute, eg. 5:37 for 5 hours, 37 minutes. You can blank the duration to have it recalculated automatically." + ) + ); + $("duration").focus(); + return; + } + var distance = $("distance").value; + if (!re_numeric.test(distance)) { + alert( + gt.gettext( + "Please enter flight distance as miles, with no fractional parts. You can blank the distance to have it re-calculated automatically." + ) + ); + $("distance").focus(); + return; + } + var number = inputform.number.value; + var seat = inputform.seat.value; + var mode = inputform.mode.value; + } else { + var number = ""; + var seat = ""; + var type = ""; + var myClass = ""; + var reason = ""; + var plane = ""; + var trid = "NULL"; + var registration = ""; + var note = ""; + var duration = ""; + var distance = ""; + var mode = "F"; + } + } + query += + "duration=" + + encodeURIComponent(duration) + + "&" + + "distance=" + + encodeURIComponent(distance) + + "&" + + "number=" + + encodeURIComponent(number) + + "&" + + "seat=" + + encodeURIComponent(seat) + + "&" + + "type=" + + encodeURIComponent(type) + + "&" + + "class=" + + encodeURIComponent(myClass) + + "&" + + "reason=" + + encodeURIComponent(reason) + + "&" + + "registration=" + + encodeURIComponent(registration) + + "&" + + "note=" + + encodeURIComponent(note) + + "&" + + "plane=" + + encodeURIComponent(plane) + + "&" + + "trid=" + + encodeURIComponent(trid) + + "&" + + "mode=" + + encodeURIComponent(mode) + + "&" + + "fid=" + + encodeURIComponent(fid) + + "&" + + "param=" + + encodeURIComponent(param); + if (getCurrentPane() == "multiinput") { + $("multiinput_status").innerHTML = "Saving..."; } else { - var number = ""; - var seat = ""; - var type = ""; - var myClass = ""; - var reason = ""; - var plane = ""; - var trid = "NULL"; - var registration = ""; - var note = ""; - var duration = ""; - var distance = ""; - var mode = "F"; - } - } - query += 'duration=' + encodeURIComponent(duration) + '&' + - 'distance=' + encodeURIComponent(distance) + '&' + - 'number=' + encodeURIComponent(number) + '&' + - 'seat=' + encodeURIComponent(seat) + '&' + - 'type=' + encodeURIComponent(type) + '&' + - 'class=' + encodeURIComponent(myClass) + '&' + - 'reason=' + encodeURIComponent(reason) + '&' + - 'registration=' + encodeURIComponent(registration) + '&' + - 'note=' + encodeURIComponent(note) + '&' + - 'plane=' + encodeURIComponent(plane) + '&' + - 'trid=' + encodeURIComponent(trid) + '&' + - 'mode=' + encodeURIComponent(mode) + '&' + - 'fid=' + encodeURIComponent(fid) + '&' + - 'param=' + encodeURIComponent(param); - if(getCurrentPane() == "multiinput") { - $("multiinput_status").innerHTML = 'Saving...'; - } else { - $("input_status").innerHTML = 'Saving...'; - } - break; - - case URL_LOGIN: - showLoadingAnimation(true); - var name = document.forms['login'].name.value; - var pw = document.forms['login'].pw.value; - var challenge = document.forms['login'].challenge.value; - hash = hex_md5(challenge + hex_md5(pw + name.toLowerCase())); - legacy_hash = hex_md5(challenge + hex_md5(pw + name)); - query = 'name=' + encodeURIComponent(name) + '&pw=' + encodeURIComponent(hash) + '&lpw=' + encodeURIComponent(legacy_hash) + "&challenge=" + encodeURIComponent(challenge); - break; - - case URL_GETCODE: - query = encodeURIComponent(param) + '=' + encodeURIComponent(id) + '&quick=true&mode=' + getMode(); - break; - - case URL_LOGOUT: - // no parameters needed - break; - - case URL_FLIGHTS: - if(param == "RELOAD") { - query = lastQuery; + $("input_status").innerHTML = "Saving..."; + } break; - } - // ...else fallthru and generate new query - // URL_MAP, URL_ROUTES, URL_FLIGHTS, URL_STATS, URL_TOP10 - default: - showLoadingAnimation(true); - var form = document.forms['filterform']; - if(! initializing && form.Trips) { - filter_trid = form.Trips.value.split(";")[0]; - } - filter_alid = form.Airlines.value.split(";")[0]; - filter_year = form.Years.value; - query = 'user=' + encodeURIComponent(filter_user) + '&' + - 'trid=' + encodeURIComponent(filter_trid) + '&' + - 'alid=' + encodeURIComponent(filter_alid) + '&' + - 'year=' + encodeURIComponent(filter_year) + '&' + - 'param=' + encodeURIComponent(param); - guestpw = $('guestpw'); - if(guestpw) { - query += "&guestpw=" + hex_md5(guestpw.value + filter_user.toLowerCase()); - } - filter_extra_key = form.Extra.value; - if(filter_extra_key != "" && $('filter_extra_value')) { - filter_extra_value = $('filter_extra_value').value; - query += '&xkey=' + filter_extra_key + - '&xvalue=' + filter_extra_value; - } - if(strURL == URL_ROUTES) { - query += '&apid=' + encodeURIComponent(id); - } - if(strURL == URL_FLIGHTS) { - switch(param) { - case "EDIT": - case "COPY": - query += '&fid=' + encodeURIComponent(id); - break; + case URL_LOGIN: + showLoadingAnimation(true); + var name = document.forms["login"].name.value; + var pw = document.forms["login"].pw.value; + var challenge = document.forms["login"].challenge.value; + hash = hex_md5(challenge + hex_md5(pw + name.toLowerCase())); + legacy_hash = hex_md5(challenge + hex_md5(pw + name)); + query = + "name=" + + encodeURIComponent(name) + + "&pw=" + + encodeURIComponent(hash) + + "&lpw=" + + encodeURIComponent(legacy_hash) + + "&challenge=" + + encodeURIComponent(challenge); + break; - default: - query += '&id=' + encodeURIComponent(id); - lastQuery = query; - lastDesc = param; + case URL_GETCODE: + query = + encodeURIComponent(param) + + "=" + + encodeURIComponent(id) + + "&quick=true&mode=" + + getMode(); + break; + + case URL_LOGOUT: + // no parameters needed + break; + + case URL_FLIGHTS: + if (param == "RELOAD") { + query = lastQuery; + break; } - } - if(strURL == URL_TOP10) { - if(param) { - query += '&' + param; + // ...else fallthru and generate new query + + // URL_MAP, URL_ROUTES, URL_FLIGHTS, URL_STATS, URL_TOP10 + default: + showLoadingAnimation(true); + var form = document.forms["filterform"]; + if (!initializing && form.Trips) { + filter_trid = form.Trips.value.split(";")[0]; + } + filter_alid = form.Airlines.value.split(";")[0]; + filter_year = form.Years.value; + query = + "user=" + + encodeURIComponent(filter_user) + + "&" + + "trid=" + + encodeURIComponent(filter_trid) + + "&" + + "alid=" + + encodeURIComponent(filter_alid) + + "&" + + "year=" + + encodeURIComponent(filter_year) + + "&" + + "param=" + + encodeURIComponent(param); + guestpw = $("guestpw"); + if (guestpw) { + query += + "&guestpw=" + hex_md5(guestpw.value + filter_user.toLowerCase()); + } + filter_extra_key = form.Extra.value; + if (filter_extra_key != "" && $("filter_extra_value")) { + filter_extra_value = $("filter_extra_value").value; + query += "&xkey=" + filter_extra_key + "&xvalue=" + filter_extra_value; + } + if (strURL == URL_ROUTES) { + query += "&apid=" + encodeURIComponent(id); + } + if (strURL == URL_FLIGHTS) { + switch (param) { + case "EDIT": + case "COPY": + query += "&fid=" + encodeURIComponent(id); + break; + + default: + query += "&id=" + encodeURIComponent(id); + lastQuery = query; + lastDesc = param; + } + } + if (strURL == URL_TOP10) { + if (param) { + query += "&" + param; + } } - } } //alert(strURL + ":" + query); self.xmlHttpReq.send(query); @@ -1079,126 +1433,170 @@ function updateFilter(str) { var airlines = master[4]; var years = master[5]; - if(!trips || trips == "") { + if (!trips || trips == "") { $("filter_tripselect").innerHTML = " " + gt.gettext("No trips"); - $("input_trip_select").innerHTML = " " + gt.gettext("No trips. Add one? "); + $("input_trip_select").innerHTML = + " " + gt.gettext("No trips. Add one? "); } else { - var tripSelect = createSelect("Trips", gt.gettext("All trips"), filter_trid, trips.split("\t"), SELECT_MAXLEN, "refresh(true)"); + var tripSelect = createSelect( + "Trips", + gt.gettext("All trips"), + filter_trid, + trips.split("\t"), + SELECT_MAXLEN, + "refresh(true)" + ); $("filter_tripselect").innerHTML = tripSelect; - var editTripSelect = document.forms['inputform'].trips; - if(editTripSelect) { - + var editTripSelect = document.forms["inputform"].trips; + if (editTripSelect) { // New trip added, so now we need to figure out the newest (highest) trid to find it - if(editTripSelect.reselect) { - var newestId = 0; - var filterTripSelect = document.forms['filterform'].Trips; - for(i = 0; i < filterTripSelect.length; i++) { - id = filterTripSelect[i].value.split(";")[0]; - if(parseInt(id) > newestId) { - newestId = id; - selected = i; - } - } + if (editTripSelect.reselect) { + var newestId = 0; + var filterTripSelect = document.forms["filterform"].Trips; + for (i = 0; i < filterTripSelect.length; i++) { + id = filterTripSelect[i].value.split(";")[0]; + if (parseInt(id) > newestId) { + newestId = id; + selected = i; + } + } } else { - selected = editTripSelect.selectedIndex; + selected = editTripSelect.selectedIndex; } } else { selected = null; } - $("input_trip_select").innerHTML = - cloneSelect(document.forms['filterform'].Trips, "trips", "markAsChanged", selected); - document.forms['inputform'].trips[0].text = "Select trip"; - } - - var airlineSelect = createSelect("Airlines", gt.gettext("All carriers"), filter_alid, airlines.split("\t"), SELECT_MAXLEN, "refresh(true)"); + $("input_trip_select").innerHTML = cloneSelect( + document.forms["filterform"].Trips, + "trips", + "markAsChanged", + selected + ); + document.forms["inputform"].trips[0].text = "Select trip"; + } + + var airlineSelect = createSelect( + "Airlines", + gt.gettext("All carriers"), + filter_alid, + airlines.split("\t"), + SELECT_MAXLEN, + "refresh(true)" + ); $("filter_airlineselect").innerHTML = airlineSelect; - var yearSelect = createSelect("Years", gt.gettext("All"), filter_year, years.split("\t"), 20, "refresh(true)"); + var yearSelect = createSelect( + "Years", + gt.gettext("All"), + filter_year, + years.split("\t"), + 20, + "refresh(true)" + ); $("filter_yearselect").innerHTML = yearSelect; - } - // Generate title for current map function getMapTitle(closable) { - var form = document.forms['filterform']; + var form = document.forms["filterform"]; var text = ""; var alid = form.Airlines.value.split(";")[0]; var airline = form.Airlines.value.split(";")[1]; var year = form.Years.value; var trid = 0; - if(form.Trips) { + if (form.Trips) { trid = form.Trips[form.Trips.selectedIndex].value.split(";")[0]; } // Logged in users - if(logged_in) { - switch(filter_trid) { - case 0: - case "0": - // do nothing - break; - case "null": - text = gt.gettext("Unassigned flights"); - break; - default: - text = tripname + " \u2197"; - break; + if (logged_in) { + switch (filter_trid) { + case 0: + case "0": + // do nothing + break; + case "null": + text = gt.gettext("Unassigned flights"); + break; + default: + text = tripname + ' \u2197'; + break; } - if(alid != "0") { - if(text != "") text += ", "; + if (alid != "0") { + if (text != "") text += ", "; text += airline + " " + getAirlineMapIcon(alid); } - if(year != "0") { - if(text != "") text += ", "; + if (year != "0") { + if (text != "") text += ", "; text += year; } - } else { // Demo mode - if(demo_mode) { - if(alid != "0") { - text = Gettext.strargs(gt.gettext("Recent flights on %1"), [airline]) + " " + getAirlineMapIcon(alid); + if (demo_mode) { + if (alid != "0") { + text = + Gettext.strargs(gt.gettext("Recent flights on %1"), [airline]) + + " " + + getAirlineMapIcon(alid); } else { - text = gt.gettext("Recently added flights"); + text = gt.gettext("Recently added flights"); } - } else { // Viewing another's profile - if(trid != "0") { - text = tripname + " \u2197"; + if (trid != "0") { + text = tripname + ' \u2197'; } else { - if(alid != "0") { - if(year != "0") { - text = Gettext.strargs(gt.gettext("%1's flights on %2 in %3"), [filter_user, airline, year]); - } else { - text = Gettext.strargs(gt.gettext("%1's flights on %2"), [filter_user, airline]); - } - text += " " + getAirlineMapIcon(alid); - } else { - if(year != "0") { - text = Gettext.strargs(gt.gettext("%1's flights in %2"), [filter_user, year]); - } else { - text = Gettext.strargs(gt.gettext("%1's flights"), [filter_user]); - } - } - } - $("loginstatus").innerHTML = getEliteIcon(elite) + "" + text + - "
" + gt.gettext("Home") + "
"; + if (alid != "0") { + if (year != "0") { + text = Gettext.strargs(gt.gettext("%1's flights on %2 in %3"), [ + filter_user, + airline, + year, + ]); + } else { + text = Gettext.strargs(gt.gettext("%1's flights on %2"), [ + filter_user, + airline, + ]); + } + text += " " + getAirlineMapIcon(alid); + } else { + if (year != "0") { + text = Gettext.strargs(gt.gettext("%1's flights in %2"), [ + filter_user, + year, + ]); + } else { + text = Gettext.strargs(gt.gettext("%1's flights"), [filter_user]); + } + } + } + $("loginstatus").innerHTML = + getEliteIcon(elite) + + "" + + text + + "
" + + gt.gettext("Home") + + "
"; } } // Tack on the extra filter, if any filter_extra_key = form.Extra.value; - if(filter_extra_key != "" && $('filter_extra_value')) { - if(text != "") { + if (filter_extra_key != "" && $("filter_extra_value")) { + if (text != "") { text = text + ", "; } - text += form.Extra[form.Extra.selectedIndex].text + ' ' + $('filter_extra_value').value; + text += + form.Extra[form.Extra.selectedIndex].text + + " " + + $("filter_extra_value").value; } // Add X for easy filter removal (only for logged-in users with non-null titles) - if(closable && logged_in && text != "") { - text = " " + text; + if (closable && logged_in && text != "") { + text = + ' ' + + text; } return text; } @@ -1215,24 +1613,25 @@ function getMapTitle(closable) { * tabIndex: tabindex */ function createSelect(selectName, allopts, id, rows, maxlen, hook, tabIndex) { - var select = ""; } @@ -1243,29 +1642,35 @@ function createSelect(selectName, allopts, id, rows, maxlen, hook, tabIndex) { var name = col[1]; var url = col[2]; - if(rid == id) { + if (rid == id) { selected = " SELECTED"; // Special case: un-truncated trip name and URL - if(selectName == "Trips") { - tripname = name; - tripurl = url; + if (selectName == "Trips") { + tripname = name; + tripurl = url; } } else { selected = ""; } // ID;Full name - if(selectName != "Years") { + if (selectName != "Years") { rid = rid + ";" + name; } // Truncate display name if (maxlen && maxlen > 0 && name.length > maxlen) { // Three dots in a proportional font is about two chars... - name = name.substring(0,maxlen - 2) + "..."; + name = name.substring(0, maxlen - 2) + "..."; } - select += ""; + select += + '"; } - if(logged_in && selectName == "Trips") { - select += ""; + if (logged_in && selectName == "Trips") { + select += + ""; } select += ""; return select; @@ -1273,12 +1678,25 @@ function createSelect(selectName, allopts, id, rows, maxlen, hook, tabIndex) { // If current value is given, don't add "All" option function createSelectFromArray(selectName, opts, hook, current) { - var select = ""; + if (!current) select += ""; for (const r of Object.keys(opts)) { - console.log(r) - select += ""; + console.log(r); + select += + ""; } select += ""; return select; @@ -1287,30 +1705,31 @@ function createSelectFromArray(selectName, opts, hook, current) { // Create a copy of 'select', renamed (incl. hook) as 'name' // Note: *not* class="filter", so width is not limited function cloneSelect(oldSelect, name, hook, selected) { - var newSelect = ""; } - for(index = 0; index < oldSelect.length; index++) { + for (index = 0; index < oldSelect.length; index++) { id = oldSelect[index].value.split(";")[0]; text = oldSelect[index].value.split(";")[1]; - if(index == selected) { + if (index == selected) { selectedText = " SELECTED"; } else { selectedText = ""; } - if(id != "null") { // Skip "Not in trip" special option - newSelect += ""; + if (id != "null") { + // Skip "Not in trip" special option + newSelect += + '"; } } newSelect += ""; return newSelect; } - // Return value of currently selected radio button in this group function radioValue(radio) { - for (r=0; r < radio.length; r++){ + for (r = 0; r < radio.length; r++) { if (radio[r].checked) { return radio[r].value; } @@ -1323,13 +1742,13 @@ function clearMap() { lineLayer.destroyFeatures(); airportLayer.destroyFeatures(); var popups = map.popups; - for(p = 0; p < popups.length; p++) { + for (p = 0; p < popups.length; p++) { popups[p].destroy(); } } // Reinsert all flights, airports from database result -function updateMap(str, url){ +function updateMap(str, url) { lineLayer.destroyFeatures(); airportLayer.destroyFeatures(); lasturl = url; // used for refresh @@ -1342,53 +1761,73 @@ function updateMap(str, url){ var id = 0; var type = "M"; // map - if(url == URL_MAP) { + if (url == URL_MAP) { // User flight map var distance = col[1]; - if(! distance) distance = 0; + if (!distance) distance = 0; var duration = col[2]; // minutes - var days = Math.floor(col[2] / (60*24)); + var days = Math.floor(col[2] / (60 * 24)); var hours = Math.floor((col[2] / 60) % 24); var min = Math.floor(col[2] % 60); - if(min < 10) min = "0" + min; - - stats = col[0] + " " + gt.gettext("segments") + "
" + - distance + "
" + - days + " " + gt.gettext("days") + " " + hours + ":" + min; - $("stats_ajax").style.display = 'none'; + if (min < 10) min = "0" + min; + + stats = + col[0] + + " " + + gt.gettext("segments") + + "
" + + distance + + "
" + + days + + " " + + gt.gettext("days") + + " " + + hours + + ":" + + min; + $("stats_ajax").style.display = "none"; $("stats").innerHTML = stats; - $('statsbox').style.visibility = "visible"; + $("statsbox").style.visibility = "visible"; flightTotal = col[0]; privacy = col[3]; - if(! logged_in) { + if (!logged_in) { elite = col[4]; editor = col[6]; - document.forms['login'].challenge.value = col[7]; + document.forms["login"].challenge.value = col[7]; // Does user have a PHP session open? Log him in! // Simulate login.php: "1;name;editor;elite" - if(col[5] != "demo") { - if(flightTotal == "0") { - op = "NEWUSER"; - } else { - op = "REFRESH"; - } - login('{"status": 1, "name": "' + col[5] + '","editor": "' + col[6] + '","elite": "' + elite + '"}', op); + if (col[5] != "demo") { + if (flightTotal == "0") { + op = "NEWUSER"; + } else { + op = "REFRESH"; + } + login( + '{"status": 1, "name": "' + + col[5] + + '","editor": "' + + col[6] + + '","elite": "' + + elite + + '"}', + op + ); } } // Our PHP session has timed out, kick out the user - if(logged_in && col[5] == "demo") { + if (logged_in && col[5] == "demo") { logout(gt.gettext("Your session has timed out, please log in again.")); } } else { - // Route map - $('statsbox').style.visibility = "hidden"; + // Route map + $("statsbox").style.visibility = "hidden"; apid = col[0]; flightTotal = col[1]; desc = col[2]; - if(apid.startsWith("L")) { + if (apid.startsWith("L")) { type = "L"; coreid = apid; title = gt.gettext("List all routes on this airline"); @@ -1398,42 +1837,66 @@ function updateMap(str, url){ title = gt.gettext("List all routes from this airport"); } - var maptitle = " " + desc; - var form = document.forms['filterform']; + var maptitle = + ' ' + + desc; + var form = document.forms["filterform"]; filter_alid = form.Airlines.value.split(";")[0]; - maptitle += " "; - if(filter_alid != 0 && ! apid.startsWith("L")) { - maptitle += " on " + form.Airlines.value.split(";")[1] + " " + getAirlineMapIcon(filter_alid); + maptitle += + " "; + if (filter_alid != 0 && !apid.startsWith("L")) { + maptitle += + " on " + + form.Airlines.value.split(";")[1] + + " " + + getAirlineMapIcon(filter_alid); } maptitle = maptitle.replace("routes", gt.gettext("routes")); $("maptitle").innerHTML = maptitle; } // New user (or filter setting) with no flights? Then don't even try to draw - if(flightTotal != "0") { + if (flightTotal != "0") { var rows = flights.split("\t"); for (r = 0; r < rows.length; r++) { // apid1 0, x1 1, y1 2, apid2 3, x2 4, y2 5, count 6, distance 7, future 8, mode 9 var rCol = rows[r].split(";"); - if(rCol[8] == "Y") { - stroke = "dash"; + if (rCol[8] == "Y") { + stroke = "dash"; } else { - stroke = "solid"; + stroke = "solid"; } - if(url == URL_ROUTES) { - color = COLOR_ROUTE; + if (url == URL_ROUTES) { + color = COLOR_ROUTE; } else { - color = modecolors[rCol[9]]; - if(!color) color = COLOR_NORMAL; + color = modecolors[rCol[9]]; + if (!color) color = COLOR_NORMAL; } - lineLayer.addFeatures(drawLine(parseFloat(rCol[1]), parseFloat(rCol[2]), - parseFloat(rCol[4]), parseFloat(rCol[5]), - rCol[6], rCol[7], color, stroke)); + lineLayer.addFeatures( + drawLine( + parseFloat(rCol[1]), + parseFloat(rCol[2]), + parseFloat(rCol[4]), + parseFloat(rCol[5]), + rCol[6], + rCol[7], + color, + stroke + ) + ); } } // Route maps draw the core airport even if there are no routes - if(flightTotal != "0" || type == "R") { + if (flightTotal != "0" || type == "R") { var rows = airports.split("\t"); var airports = Array(); @@ -1442,36 +1905,47 @@ function updateMap(str, url){ for (r = 0; r < rows.length; r++) { var col = rows[r].split(";"); // 0 apdata, 1 name, 2 city, 3 country, 4 count, 5 formatted_name, 6 future - if(col[6] == "Y") { - opacity = 0.5; + if (col[6] == "Y") { + opacity = 0.5; } else { - opacity = 1; + opacity = 1; } - airports.push(drawAirport(airportLayer, col[0], col[1], col[2], col[3], col[4], col[5], opacity, apid)); + airports.push( + drawAirport( + airportLayer, + col[0], + col[1], + col[2], + col[3], + col[4], + col[5], + opacity, + apid + ) + ); } airportLayer.addFeatures(airports); } // Redraw selection markers if in input mode - if(getCurrentPane() == "input") { - if(input_srcmarker) markAirport("src_ap", true); - if(input_dstmarker) markAirport("dst_ap", true); + if (getCurrentPane() == "input") { + if (input_srcmarker) markAirport("src_ap", true); + if (input_dstmarker) markAirport("dst_ap", true); } showLoadingAnimation(false); - if(initializing) { - if(! logged_in && demo_mode) { - $("loginform").style.display = 'inline'; - } - $('statsbox').style.visibility = "visible"; - $('filter').style.visibility = "visible"; - if(logged_in || privacy == 'O') { - $('filter_extra_key').style.visibility = "visible"; + if (initializing) { + if (!logged_in && demo_mode) { + $("loginform").style.display = "inline"; + } + $("statsbox").style.visibility = "visible"; + $("filter").style.visibility = "visible"; + if (logged_in || privacy == "O") { + $("filter_extra_key").style.visibility = "visible"; } else { - $('filter_extra_key').style.visibility = "hidden"; + $("filter_extra_key").style.visibility = "hidden"; } } - } function startListFlights() { @@ -1481,37 +1955,83 @@ function startListFlights() { function listFlights(str, desc, id) { openPane("result"); fidList = new Array(); - var route = ! re_numeric.test(id); // ids starting with R are routes + var route = !re_numeric.test(id); // ids starting with R are routes var today = new Date().getTime(); - if(desc == "MAP") { + if (desc == "MAP") { desc = gt.gettext("Flights:") + " " + getMapTitle(false); } // IE string concat is painfully slow, so we use an array and join it instead var table = []; - table.push(" "); - if(str == "") { - table.push("" + gt.gettext("No flights found at this airport.") + "
"); + table.push( + ' ' + ); + if (str == "") { + table.push( + "" + + gt.gettext("No flights found at this airport.") + + "
" + ); } else { - if(desc) { + if (desc) { desc = desc.replace("Flights:", gt.gettext("Flights:")); desc = desc.replace("routes", gt.gettext("routes")); - desc = desc.replace(/\/g, " — ") + desc = desc.replace(/\/g, " — "); table.push(desc); - table.unshift("" + gt.gettext("Export") + " " + - "" + - "" + - "" + - ""); // place at front of array + table.unshift( + "" + + gt.gettext("Export") + + " " + + "" + + "" + + "" + + "" + ); // place at front of array } - table.push(""); - table.push(""); - if(!route) { - table.push(""); + table.push( + '
" + gt.gettext("From") + "" + gt.gettext("To") + "" + gt.gettext("Nr.") + "" + gt.gettext("Date") + "" + gt.gettext("Distance") + "" + gt.gettext("Time") + "" + gt.gettext("Vehicle") + "" + gt.gettext("Seat") + "" + gt.gettext("Class") + "" + gt.gettext("Reason") + "" + gt.gettext("Trip") + "
' + ); + table.push( + '" + ); + if (!route) { + table.push( + "" + ); } table.push(""); - if(logged_in) { - table.push(""); + if (logged_in) { + table.push('"); } table.push(""); @@ -1529,47 +2049,116 @@ function listFlights(str, desc, id) { var modename = modenames[col[21]]; // Date.parse() doesn't work on YYYY/MM/DD, so we chop it up and use Date.UTC instead (sigh) - if(Date.UTC(date.substring(0,4), date.substring(5,7) - 1, date.substring(8,10)) > today) { - date = "" + date + ""; + if ( + Date.UTC( + date.substring(0, 4), + date.substring(5, 7) - 1, + date.substring(8, 10) + ) > today + ) { + date = "" + date + ""; } // Prepend airline code to numeric/missing flight number - if(/^[0-9]*$/.test(code)) { - code = col[19] + code; + if (/^[0-9]*$/.test(code)) { + code = col[19] + code; } - if(col[14] != "") { - plane += " (" + col[14] + ")"; + if (col[14] != "") { + plane += " (" + col[14] + ")"; } - if(logged_in && trip != "") { - trip = "" + trip + ""; + if (logged_in && trip != "") { + trip = + '' + + trip + + ""; } - table.push("" + - "" + - "" + - "" + + '" + + '" + + ""); - if(!route) { - table.push(""); + table.push( + "" + ); + if (!route) { + table.push( + "" + ); } // Add an ellipsis to the note if we truncate it. var note = col[16]; - if(note.length > 15) { + if (note.length > 15) { note = note.substring(0, 15) + "…"; } table.push(""); - if(logged_in && !route) { - table.push(""); + if (logged_in && !route) { + table.push(""); } table.push(""); fidList.push(fid); @@ -1585,12 +2174,12 @@ function listFlights(str, desc, id) { // type: "backup" to export everything, "export" to export only current filter selection, "gcmap" to redirect to gcmap site // newWindow: true if we want target URL to open in a new window. function exportFlights(type, newWindow) { - if(type == "KML") { + if (type == "KML") { url = location.origin + "/php/kml.php?" + lastQuery; } else { url = location.origin + "/php/flights.php?" + lastQuery + "&export=" + type; } - if(newWindow) { + if (newWindow) { window.open(url, "openflights_export"); } else { location.href = url; @@ -1599,14 +2188,14 @@ function exportFlights(type, newWindow) { // The "Analyze" button (detailed stats) function showStats(str) { - if(str.substring(0,5) == "Error") { - $("result").innerHTML = str.split(';')[1]; + if (str.substring(0, 5) == "Error") { + $("result").innerHTML = str.split(";")[1]; openPane("result"); return; } openPane("result"); - if(str == "") { + if (str == "") { bigtable = "Statistics calculation failed!"; } else { var master = str.split("\n"); @@ -1619,71 +2208,159 @@ function showStats(str) { var modeData = master[6]; var classDataByDistance = master[7]; - bigtable = "
' + + gt.gettext("From") + + "" + + gt.gettext("To") + + "" + + gt.gettext("Nr.") + + "" + + gt.gettext("Date") + + '' + + gt.gettext("Distance") + + "" + + gt.gettext("Time") + + "" + + gt.gettext("Vehicle") + + "" + + gt.gettext("Seat") + + "" + + gt.gettext("Class") + + "" + + gt.gettext("Reason") + + "" + + gt.gettext("Trip") + + "" + gt.gettext("Note") + "" + gt.gettext("Action") + "' + gt.gettext("Action") + "
" + col[0] + "" + col[2] + ""); - if(route) { - table.push("" + code + ""); + table.push( + "
' + + col[0] + + "' + + col[2] + + "" + ); + if (route) { + table.push( + '' + + code + + "" + ); } else { - table.push(code); + table.push(code); } - table.push("" + date + "" + col[6] + "" + col[7] + "" + plane + "" + seat + - "" + classes[col[10]] + "" + reasons[col[11]] + - "" + trip + "" + + date + + "" + + col[6] + + "" + + col[7] + + "" + + plane + + "" + + seat + + "" + + classes[col[10]] + + "" + + reasons[col[11]] + + "" + + trip + + "" + note + ""); - table.push(""); - table.push(""); - table.push(""); - table.push(""); + table.push( + "" + ); + table.push( + "" + ); + table.push( + "" + ); + table.push("
"; + bigtable = + '
'; - table = ""; + table = '
'; table += ""; - table += ""; - table += ""; - table += ""; - table += ""; + table += + ""; + table += + ""; + table += + ""; + table += + ""; table += ""; var distance = parseInt(uniques["distance"]); table += ""; - table += ""; - table += ""; - table += ""; - table += ""; + table += + ""; + table += + ""; + table += + ""; + table += + ""; table += "
" + gt.gettext("Unique") + "
" + gt.gettext("Airports") + "" + uniques["num_airports"] + "
" + gt.gettext("Carriers") + "" + uniques["num_airlines"] + "
" + gt.gettext("Countries") + "" + uniques["num_countries"] + "
" + gt.gettext("Vehicles") + "" + uniques["num_planes"] + "
" + + gt.gettext("Airports") + + "" + + uniques["num_airports"] + + "
" + + gt.gettext("Carriers") + + "" + + uniques["num_airlines"] + + "
" + + gt.gettext("Countries") + + "" + + uniques["num_countries"] + + "
" + + gt.gettext("Vehicles") + + "" + + uniques["num_planes"] + + "
 
" + gt.gettext("Distance") + "
" + gt.gettext("Total flown") + "" + uniques["localedist"] + "
" + gt.gettext("Around the world") + "" + (distance / EARTH_CIRCUMFERENCE).toFixed(2) + "x
" + gt.gettext("To the Moon") + "" + (distance / MOON_DISTANCE).toFixed(3) + "x
" + gt.gettext("To Mars") + "" + (distance / MARS_DISTANCE).toFixed(4) + "x
" + + gt.gettext("Total flown") + + "" + + uniques["localedist"] + + "
" + + gt.gettext("Around the world") + + "" + + (distance / EARTH_CIRCUMFERENCE).toFixed(2) + + "x
" + + gt.gettext("To the Moon") + + "" + + (distance / MOON_DISTANCE).toFixed(3) + + "x
" + + gt.gettext("To Mars") + + "" + + (distance / MARS_DISTANCE).toFixed(4) + + "x
"; - bigtable += table + "
"; + bigtable += table + ''; - table = ""; - table += ""; + table = '
" + gt.gettext("Journey records") + "
'; + table += + ""; var rows = longshort.split(";"); for (r = 0; r < rows.length; r++) { var col = rows[r].split(","); // desc 0, distance 1, duration 2, s.iata 3, s.apid 4, d.iata 5, d.apid 6 - table += ""; + table += + ""; } - table += ""; + table += + ""; table += ""; table += ""; - table += ""; + table += + ""; var rows = extremes.split(":"); for (r = 0; r < rows.length; r++) { var col = rows[r].split(","); // 0 desc, 1 code, 2 apid, 3 x, 4 y lat = parseFloat(col[4]).toFixed(2); lon = parseFloat(col[3]).toFixed(2); - if(lat < 0) { - lat = -lat + "°S"; + if (lat < 0) { + lat = -lat + "°S"; } else { - lat += "°N"; + lat += "°N"; } - if(lon < 0) { - lon = -lon + "°W"; + if (lon < 0) { + lon = -lon + "°W"; } else { - lon += "°E"; + lon += "°E"; } - table += ""; + table += + ""; } table += "
" + gt.gettext("Journey records") + "
" + col[0] + "" + col[3] + "" + col[5] + ", " + col[1] + ", " + col[2] + "
" + + col[0] + + '' + + col[3] + + '' + + col[5] + + ", " + + col[1] + + ", " + + col[2] + + "
" + gt.gettext("Average") + "" + uniques["avg_distance"] + ", " + uniques["avg_duration"] + "
" + + gt.gettext("Average") + + "" + + uniques["avg_distance"] + + ", " + + uniques["avg_duration"] + + "
 
 
" + gt.gettext("Airport records") + "
" + gt.gettext("Airport records") + "
" + col[0] + "" + col[1] + " (" + lat + " " + lon + ")
" + + col[0] + + '' + + col[1] + + " (" + + lat + + " " + + lon + + ")
"; - bigtable += table + "
"; - - table = ""; - table += ""; + bigtable += table + '
" + gt.gettext("Class") + "" + gt.gettext("Reason") + "" + gt.gettext("Seats") + "
'; + + table = ''; + table += + ""; table += ""; - table += ""; - table += ""; - table += ""; + table += ''; + table += ''; + table += ''; table += ""; - table += ""; + table += + ""; table += ""; - table += ""; - table += ""; - table += ""; + table += ''; + table += ''; + table += ""; table += ""; table += "
" + + gt.gettext("Class") + + "" + + gt.gettext("Reason") + + "" + + gt.gettext("Seats") + + "
" + gt.gettext("Class by distance") + "" + gt.gettext("Mode") + "
" + + gt.gettext("Class by distance") + + "" + + gt.gettext("Mode") + + "
"; table += ""; @@ -1697,7 +2374,7 @@ function showStats(str) { $("result").innerHTML = bigtable; - if(str != "") { + if (str != "") { // First row of charts googleChart("chart_class", classData, classes_short); googleChart("chart_reason", reasonData, reasons_short); @@ -1715,16 +2392,16 @@ var GOOGLE_CHART_OPTIONS = { // Google seems to be adding a 10px highlights above/beloww the chart when moused over. // The actual chart height should be in chartArea[height] and the div height will be // chartHeight+20. A margin of 10 at the top will ensure the top highlight will show up. - chartArea: { left: 0, top: 10, width: '100%', height: '100' }, + chartArea: { left: 0, top: 10, width: "100%", height: "100" }, height: 120, width: 200, - legend: 'none', - pieSliceText: 'label' + legend: "none", + pieSliceText: "label", }; -var GOOGLE_CHART_TWO_COLORS = ['2A416A','B2C3DF']; -var GOOGLE_CHART_THREE_COLORS = ['2A416A','688BC3','B2C3DF']; -var GOOGLE_CHART_FOUR_COLORS = ['2A416A','39588E','688BC3','B2C3DF']; +var GOOGLE_CHART_TWO_COLORS = ["2A416A", "B2C3DF"]; +var GOOGLE_CHART_THREE_COLORS = ["2A416A", "688BC3", "B2C3DF"]; +var GOOGLE_CHART_FOUR_COLORS = ["2A416A", "39588E", "688BC3", "B2C3DF"]; // Generate a pie chart image via Google Charts API // targetdiv is the DIV where we should write out the chart @@ -1733,11 +2410,13 @@ var GOOGLE_CHART_FOUR_COLORS = ['2A416A','39588E','688BC3','B2C3DF']; // e.g. inputdata = F,1:C,2:F,3 // labeldata = {F: 'First', C: 'Biz', Y: 'Econ'} function googleChart(targetdiv, inputdata, labeldata) { - if(!inputdata) { return; } + if (!inputdata) { + return; + } var data = new google.visualization.DataTable(); - data.addColumn('string', 'Key'); - data.addColumn('number', 'Value'); + data.addColumn("string", "Key"); + data.addColumn("number", "Value"); var rows = inputdata.split(":"); for (r = 0; r < rows.length; r++) { @@ -1748,14 +2427,16 @@ function googleChart(targetdiv, inputdata, labeldata) { // Apply formatter to the "Value" column. var formatter = new google.visualization.NumberFormat({ - fractionDigits: 0 + fractionDigits: 0, }); formatter.format(data, 1); - var chart = new google.visualization.PieChart(document.getElementById(targetdiv)); - if(rows.length <= 2) { + var chart = new google.visualization.PieChart( + document.getElementById(targetdiv) + ); + if (rows.length <= 2) { GOOGLE_CHART_OPTIONS.colors = GOOGLE_CHART_TWO_COLORS; - } else if(rows.length <= 3) { + } else if (rows.length <= 3) { GOOGLE_CHART_OPTIONS.colors = GOOGLE_CHART_THREE_COLORS; } else { GOOGLE_CHART_OPTIONS.colors = GOOGLE_CHART_FOUR_COLORS; @@ -1773,15 +2454,15 @@ function showTop10(responseText) { return; } - if('error' in topData) { + if ("error" in topData) { $("result").innerHTML = topData.error; openPane("result"); return; } // Take note of existing settings, if any - var form = document.forms['top10form']; - if(form) { + var form = document.forms["top10form"]; + if (form) { mode = form.mode[form.mode.selectedIndex].value; limit = form.limit[form.limit.selectedIndex].value; } else { @@ -1789,41 +2470,79 @@ function showTop10(responseText) { limit = "10"; } - bigtable = "
"; + bigtable = + ""; - bigtable += ""; @@ -1833,16 +2552,15 @@ function showTop10(responseText) { } function updateTop10() { - const form = document.forms['top10form']; + const form = document.forms["top10form"]; const params = new URLSearchParams(); - if(form) { - params.set('mode', form.mode[form.mode.selectedIndex].value); + if (form) { + params.set("mode", form.mode[form.mode.selectedIndex].value); const limit = form.limit[form.limit.selectedIndex].value; - if (limit !== "-1") - params.set('limit', limit); + if (limit !== "-1") params.set("limit", limit); } else { - params.set('mode', 'F'); - params.set('limit', 10); + params.set("mode", "F"); + params.set("limit", 10); } xmlhttpPost(URL_TOP10, 0, params.toString()); } @@ -1850,10 +2568,16 @@ function updateTop10() { // Move "pointer" in flight list up or down one when user clicks prev, next function editPointer(offset) { var newPtr = fidPtr + offset; - if(newPtr >= 0 && newPtr < fidList.length) { - if(hasChanged()) { - if(!confirm(gt.gettext("Changes made to this flight have not been saved. OK to discard them?"))) { - return; + if (newPtr >= 0 && newPtr < fidList.length) { + if (hasChanged()) { + if ( + !confirm( + gt.gettext( + "Changes made to this flight have not been saved. OK to discard them?" + ) + ) + ) { + return; } } // Load new flight @@ -1864,8 +2588,8 @@ function editPointer(offset) { // Load up parameters of a given flight function preEditFlight(fid, idx) { fidPtr = idx; - $("b_prev").disabled = (fidPtr <= 0 ? true : false); - $("b_next").disabled = (fidPtr >= fidList.length - 1 ? true : false); + $("b_prev").disabled = fidPtr <= 0 ? true : false; + $("b_next").disabled = fidPtr >= fidList.length - 1 ? true : false; $("editflighttitle").innerHTML = gt.gettext("Loading..."); xmlhttpPost(URL_FLIGHTS, fid, "EDIT"); } @@ -1877,24 +2601,24 @@ function preCopyFlight(fid) { // Load existing flight data into input form function editFlight(str, param) { // Oops, no matches!? - if(str == "") { + if (str == "") { closeInput(); return; } - if(getCurrentPane() != "input") { + if (getCurrentPane() != "input") { // EDIT -> edit, COPY -> add openDetailedInput(param); } // src_iata 0, src_apid 1, dst_iata 2, dst_apid 3, flight code 4, date 5, distance 6, duration 7, seat 8, seat_type 9, class 10, reason 11, fid 12, plane 13, registration 14, alid 15, note 16, trid 17, plid 18, alcode 19, src_time 20, mode 21 var col = str.split("\t"); - var form = document.forms['inputform']; + var form = document.forms["inputform"]; form.number.value = col[4]; form.src_date.value = col[5]; - if(col[20] != "") { - $('src_time').style.color = '#000'; - form.src_time.value = col[20].substring(0,5); // HH:MM, drop seconds + if (col[20] != "") { + $("src_time").style.color = "#000"; + form.src_time.value = col[20].substring(0, 5); // HH:MM, drop seconds // dst_time calculated automatically } else { clearTimes(); @@ -1911,19 +2635,22 @@ function editFlight(str, param) { selectInSelect(inputform.mode, col[21]); changeMode(col[21]); - $("editflighttitle").innerHTML = Gettext.strargs(gt.gettext("Edit segment %1 of %2"), [fidPtr+1, fidList.length]); + $("editflighttitle").innerHTML = Gettext.strargs( + gt.gettext("Edit segment %1 of %2"), + [fidPtr + 1, fidList.length] + ); var myClass = inputform.myClass; - for(index = 0; index < myClass.length; index++) { - if(myClass[index].value == col[10]) { + for (index = 0; index < myClass.length; index++) { + if (myClass[index].value == col[10]) { myClass[index].checked = true; } else { myClass[index].checked = false; } } var reason = inputform.reason; - for(index = 0; index < reason.length; index++) { - if(reason[index].value == col[11]) { + for (index = 0; index < reason.length; index++) { + if (reason[index].value == col[11]) { reason[index].checked = true; } else { reason[index].checked = false; @@ -1931,30 +2658,30 @@ function editFlight(str, param) { } // Read these after selectAirport mucks up the dist/duration - $('distance').value = col[6]; - $('distance').style.color = '#000'; - $('duration').value = col[7]; - $('duration').style.color = '#000'; - calcDuration('DEPARTURE'); // figure out arrival time according to previous dist/dur + $("distance").value = col[6]; + $("distance").style.color = "#000"; + $("duration").value = col[7]; + $("duration").style.color = "#000"; + calcDuration("DEPARTURE"); // figure out arrival time according to previous dist/dur fid = col[12]; //stored until flight is saved or deleted - $('plane').value = col[13]; - $('planeid').value = col[18]; + $("plane").value = col[13]; + $("planeid").value = col[18]; form.registration.value = col[14]; alid = col[15]; - if(col[16] != "") { - $('note').style.color = '#000'; + if (col[16] != "") { + $("note").style.color = "#000"; form.note.value = col[16]; } else { - $('note').value = $('note').hintText; + $("note").value = $("note").hintText; } form.seat.value = col[8]; - $('src_ap').style.color = '#000000'; - $('dst_ap').style.color = '#000000'; - $('airline').style.color = '#000000'; - $('plane').style.color = '#000000'; + $("src_ap").style.color = "#000000"; + $("dst_ap").style.color = "#000000"; + $("airline").style.color = "#000000"; + $("plane").style.color = "#000000"; // Don't allow saving until something is changed setCommitAllowed(false); @@ -1963,28 +2690,28 @@ function editFlight(str, param) { // Select correct input editor function newFlight() { - switch(prefs_editor) { - case "D": - openDetailedInput("ADD"); - break; + switch (prefs_editor) { + case "D": + openDetailedInput("ADD"); + break; - default: - openBasicInput("ADD"); - break; + default: + openBasicInput("ADD"); + break; } } // User has edited a flight's contents // if major is true, force a redraw later function markAsChanged(major) { - if(major) { + if (major) { majorEdit = true; } - if(! changed) { + if (!changed) { changed = true; setCommitAllowed(true); - $("input_status").innerHTML = ''; - $("multiinput_status").innerHTML = ''; + $("input_status").innerHTML = ""; + $("multiinput_status").innerHTML = ""; } } @@ -1998,9 +2725,9 @@ function hasChanged() { // state={true,false} for enabled,disabled function setCommitAllowed(state) { state = !state; // enabled=true -> disabled=false - if(state) changed = false; // if no commit allowed, then no changes have been made + if (state) changed = false; // if no commit allowed, then no changes have been made - if(getCurrentPane() == "input") { + if (getCurrentPane() == "input") { $("b_add").disabled = state; $("b_save").disabled = state; } else { @@ -2019,50 +2746,53 @@ function saveFlight() { // Delete current flight (fid) function deleteFlight(id) { - if(id) { + if (id) { fid = id; } - if(confirm(gt.gettext("Are you sure you want to delete this flight?"))) { + if (confirm(gt.gettext("Are you sure you want to delete this flight?"))) { xmlhttpPost(URL_SUBMIT, false, "DELETE"); } else { - $("input_status").innerHTML = "" + gt.gettext("Deleting flight cancelled.") + ""; + $("input_status").innerHTML = + "" + gt.gettext("Deleting flight cancelled.") + ""; } } // Handle change of transportation mode // If 'mode' is supplied, force it function changeMode(mode) { - if(!mode) { - mode=document.forms['inputform'].mode.value; - } - $('icon_airline').src = modeicons[mode]; - $('icon_airline').title = Gettext.strargs(gt.gettext("Search for %1"), [modeoperators[mode]]); - calcDuration('AIRPORT'); // recompute duration estimate + if (!mode) { + mode = document.forms["inputform"].mode.value; + } + $("icon_airline").src = modeicons[mode]; + $("icon_airline").title = Gettext.strargs(gt.gettext("Search for %1"), [ + modeoperators[mode], + ]); + calcDuration("AIRPORT"); // recompute duration estimate markAsChanged(true); } // Handle the "add new airports" buttons function popNewAirport(type, apid) { - if(! apid) apid = 0; - url = '/html/apsearch'; - if(type) { + if (!apid) apid = 0; + url = "/html/apsearch"; + if (type) { input_toggle = type; apid = getApid(type); } - if(apid != 0) { + if (apid != 0) { url += "?apid=" + apid; } - window.open(url, 'Airport', 'width=580,height=580,scrollbars=yes'); + window.open(url, "Airport", "width=580,height=580,scrollbars=yes"); } // Read in newly added airport (from Airport Search) // (new for this map, that is, not necessarily DB) function addNewAirport(data, name) { var element = input_toggle; - if(input_toggle) { + if (input_toggle) { $(element).value = name; - $(element).style.color = '#000000'; - $(element + 'id').value = data; + $(element).style.color = "#000000"; + $(element + "id").value = data; replicateSelection(element); markAirport(element); markAsChanged(true); @@ -2071,14 +2801,14 @@ function addNewAirport(data, name) { // Handle the "add new airlines" buttons function popNewAirline(type, name, mode) { - if(type) { + if (type) { input_al_toggle = type; } - url = '/html/alsearch'; - if(name) { + url = "/html/alsearch"; + if (name) { url += "?name=" + encodeURIComponent(name) + "&mode=" + mode; } - window.open(url, 'Airline', 'width=580,height=580,scrollbars=yes'); + window.open(url, "Airline", "width=580,height=580,scrollbars=yes"); } // Read in newly added airline @@ -2088,16 +2818,16 @@ function addNewAirline(alid, name, mode) { selectInSelect(inputform.mode, mode); // Check if airline was listed already - if(selectAirline(alid, true)) { + if (selectAirline(alid, true)) { return; } // Nope, we need to add it to filter options - var al_select = document.forms['filterform'].Airlines; - var elOptNew = document.createElement('option'); + var al_select = document.forms["filterform"].Airlines; + var elOptNew = document.createElement("option"); if (name.length > SELECT_MAXLEN) { // Three dots in a proportional font is about two chars... - elOptNew.text = name.substring(0,SELECT_MAXLEN - 2) + "..."; + elOptNew.text = name.substring(0, SELECT_MAXLEN - 2) + "..."; } else { elOptNew.text = name; } @@ -2105,14 +2835,13 @@ function addNewAirline(alid, name, mode) { try { al_select.add(elOptNew, null); // standards compliant; doesn't work in IE - } - catch(ex) { + } catch (ex) { al_select.add(elOptNew); // IE only } // And finally the input form $(input_al_toggle).value = name; - $(input_al_toggle + 'id').value = alid; + $(input_al_toggle + "id").value = alid; $(input_al_toggle).style.color = "#000"; } @@ -2120,8 +2849,8 @@ function addNewAirline(alid, name, mode) { // Inject apid into hidden src/dst_apid field after new airport is selected, and draw on map // function getSelectedApid(inputElementId, apid) { - $(inputElementId).style.color = '#000000'; - $(inputElementId + 'id').value = apid; + $(inputElementId).style.color = "#000000"; + $(inputElementId + "id").value = apid; replicateSelection(inputElementId); markAirport(inputElementId); markAsChanged(true); // new airport, force refresh @@ -2131,14 +2860,14 @@ function getSelectedApid(inputElementId, apid) { // Inject alid into hidden alid field after new plane type is selected // function getSelectedAlid(inputElementId, alid) { - $(inputElementId).style.color = '#000000'; - $(inputElementId + 'id').value = alid; + $(inputElementId).style.color = "#000000"; + $(inputElementId + "id").value = alid; markAsChanged(true); // new airline, force refresh } function getSelectedPlid(inputElementId, plid) { - $(inputElementId).style.color = '#000000'; - $(inputElementId + 'id').value = plid; + $(inputElementId).style.color = "#000000"; + $(inputElementId + "id").value = plid; markAsChanged(true); // new plane, force refresh } @@ -2158,13 +2887,13 @@ function getQuickSearchId(item) { } else { id = `L${data}`; } - $('qsid').value = id; - $('qsgo').disabled = false; + $("qsid").value = id; + $("qsgo").disabled = false; } // Show map! function goQuickSearch() { - xmlhttpPost(URL_ROUTES, $('qsid').value); + xmlhttpPost(URL_ROUTES, $("qsid").value); } // @@ -2172,22 +2901,22 @@ function goQuickSearch() { // thisTrip can be "ADD" (new), "EDIT" (edit selected), or a numeric trip id (edit this) // function editTrip(thisTrip) { - var url = '/html/trip'; + var url = "/html/trip"; var trid = 0; - if(thisTrip == "ADD") { + if (thisTrip == "ADD") { // do nothing, we'll create a new trip } else { - if(thisTrip == "EDIT") { - var inputform = document.forms['inputform']; + if (thisTrip == "EDIT") { + var inputform = document.forms["inputform"]; trid = inputform.trips[inputform.trips.selectedIndex].value; } else { trid = thisTrip; } } - if(trid != 0) { + if (trid != 0) { url += "?trid=" + trid; } - window.open(url, 'TripEditor', 'width=500,height=280,scrollbars=yes'); + window.open(url, "TripEditor", "width=500,height=280,scrollbars=yes"); } // User has added, edited or deleted trip, so punch it in @@ -2195,30 +2924,31 @@ function newTrip(code, newTrid, name, url) { code = parseInt(code); // Trip deleted? Switch filter back to "all trips" view - if(code == CODE_DELETEOK) { - var tr_select = document.forms['filterform'].Trips; + if (code == CODE_DELETEOK) { + var tr_select = document.forms["filterform"].Trips; tr_select.selectedIndex = 0; } // This only applies when new trip is added in flight editor - var trips = document.forms['inputform'].trips; - if(!trips) { - $("input_trip_select").innerHTML = ""; - trips = document.forms['inputform'].trips; - } - if(trips) { - switch(code) { - case CODE_ADDOK: - trips.reselect = true; // means recalculate on refresh - break; - - case CODE_DELETEOK: - trips.selectedIndex = 0; - break; - - default: // EDIT - trips[trips.selectedIndex].text = name; - break; + var trips = document.forms["inputform"].trips; + if (!trips) { + $("input_trip_select").innerHTML = + ""; + trips = document.forms["inputform"].trips; + } + if (trips) { + switch (code) { + case CODE_ADDOK: + trips.reselect = true; // means recalculate on refresh + break; + + case CODE_DELETEOK: + trips.selectedIndex = 0; + break; + + default: // EDIT + trips[trips.selectedIndex].text = name; + break; } } // In all cases, refresh map @@ -2230,12 +2960,12 @@ function newTrip(code, newTrid, name, url) { // When user has manually entered an airport code, try to match it // "type" contains the element name function airportCodeToAirport(type) { - input_toggle = type; + input_toggle = type; markAsChanged(true); // Is it blank? - if($(type).value == "") { - $(type + 'id').value = 0; + if ($(type).value == "") { + $(type + "id").value = 0; return; } @@ -2243,11 +2973,11 @@ function airportCodeToAirport(type) { // TODO: Also match against marker.name var code = $(type).value.toUpperCase(); var found = false; - if(selectAirport(null, true, false, code)) { - if(type == 'qs') { - $('qsid').value = attrs.apid; - $('qsgo').disabled = false; - $('qsgo').focus(); + if (selectAirport(null, true, false, code)) { + if (type == "qs") { + $("qsid").value = attrs.apid; + $("qsgo").disabled = false; + $("qsgo").focus(); } } else { // If not found, dig up from DB @@ -2256,55 +2986,56 @@ function airportCodeToAirport(type) { } // User has entered invalid input: clear apid, turn field red (unless empty) and remove marker -function invalidateField(type, airport=false) { - if($(type).value != "" && $(type).value != $(type).hintText) { - $(type).style.color = '#FF0000'; +function invalidateField(type, airport = false) { + if ($(type).value != "" && $(type).value != $(type).hintText) { + $(type).style.color = "#FF0000"; } - $(type + 'id').value = 0; - if(airport) unmarkAirports(); + $(type + "id").value = 0; + if (airport) unmarkAirports(); } // When user has entered flight number, try to match it to airline // type: element invoked function flightNumberToAirline(type) { markAsChanged(); - if(type == "NUMBER") { + if (type == "NUMBER") { // This is a flight number - var flightNumber = document.forms['inputform'].number.value.toUpperCase(); - document.forms['inputform'].number.value = flightNumber; + var flightNumber = document.forms["inputform"].number.value.toUpperCase(); + document.forms["inputform"].number.value = flightNumber; // Ignore all-numeric flight numbers - if(re_numeric.test(flightNumber)) { + if (re_numeric.test(flightNumber)) { return; } // Does flight number start with IATA or ICAO code? - if(flightNumber.length >= 2) { + if (flightNumber.length >= 2) { var found = false; var re_iata = /^([a-zA-Z0-9][a-zA-Z0-9]$|[a-zA-Z0-9][a-zA-Z0-9][ 0-9])/; // XX or XX[ ]N... - var re_icao = /^([a-zA-Z][a-zA-Z][a-zA-Z]$|[a-zA-Z][a-zA-Z][a-zA-Z][ 0-9])/; // XXX or XXX[ ]N... - if(re_iata.test(flightNumber.substring(0,3))) { - var airlineCode = flightNumber.substring(0, 2); - } else if(re_icao.test(flightNumber.substring(0,4))) { - var airlineCode = flightNumber.substring(0, 3); + var re_icao = + /^([a-zA-Z][a-zA-Z][a-zA-Z]$|[a-zA-Z][a-zA-Z][a-zA-Z][ 0-9])/; // XXX or XXX[ ]N... + if (re_iata.test(flightNumber.substring(0, 3))) { + var airlineCode = flightNumber.substring(0, 2); + } else if (re_icao.test(flightNumber.substring(0, 4))) { + var airlineCode = flightNumber.substring(0, 3); } else { - // User has entered something weird, ignore it - return; + // User has entered something weird, ignore it + return; } type = "airline"; } } else { // This is a manually entered airline name // Is it blank? - if($(type).value == "") { - $(type + 'id').value = 0; + if ($(type).value == "") { + $(type + "id").value = 0; return; } airlineCode = $(type).value; } // We've found something that looks like an airline code, so overwrite it into AIRLINE field - if(airlineCode) { + if (airlineCode) { xmlhttpPost(URL_GETCODE, airlineCode, type); } } @@ -2316,123 +3047,126 @@ function flightNumberToAirline(type) { // param 'DURATION': duration changed by user, recompute time at destination // param 'DISTANCE': recalculate distance *only* if blanked function calcDuration(param) { - var days = 0, duration = 0; + var days = 0, + duration = 0; // Need both airports first - if($('src_apid').value == 0 || $('dst_apid').value == 0) return; - dst_time = $('dst_time').value.trim(); - if(dst_time == "" || dst_time == "HH:MM") { + if ($("src_apid").value == 0 || $("dst_apid").value == 0) return; + dst_time = $("dst_time").value.trim(); + if (dst_time == "" || dst_time == "HH:MM") { dst_time = 0; } - switch(param) { - case 'DISTANCE': - // Reestimate *only* if blanked - var distance = $('distance').value.trim(); - if(distance == "") { - var lon1 = getX('src_ap'); - var lat1 = getY('src_ap'); - var lon2 = getX('dst_ap'); - var lat2 = getY('dst_ap'); - $('distance').value = gcDistance(lat1, lon1, lat2, lon2); - $('distance').style.color = "#000"; - } else { - if(! re_numeric.test(distance)) { - $('distance').focus(); - $('distance').style.color = "#F00"; + switch (param) { + case "DISTANCE": + // Reestimate *only* if blanked + var distance = $("distance").value.trim(); + if (distance == "") { + var lon1 = getX("src_ap"); + var lat1 = getY("src_ap"); + var lon2 = getX("dst_ap"); + var lat2 = getY("dst_ap"); + $("distance").value = gcDistance(lat1, lon1, lat2, lon2); + $("distance").style.color = "#000"; } else { - $('distance').style.color = "#000"; + if (!re_numeric.test(distance)) { + $("distance").focus(); + $("distance").style.color = "#F00"; + } else { + $("distance").style.color = "#000"; + } + } + markAsChanged(); + return; // always terminate here + + case "ARRIVAL": + // User has changed arrival time: recompute duration + // User has blanked arrival time: recompute arrival time (using existing duration) + if (dst_time != 0) { + duration = 0; + break; } - } - markAsChanged(); - return; // always terminate here - - case 'ARRIVAL': - // User has changed arrival time: recompute duration - // User has blanked arrival time: recompute arrival time (using existing duration) - if(dst_time != 0) { - duration = 0; - break; - } // else fallthru - case 'DURATION': - case 'DEPARTURE': - // Recompute arrival time based on user-changed/previously calculated duration - // (if no duration is available, estimate it) - var duration = $('duration').value.trim(); - if(duration != "") { - if(! RE_TIME.test(duration)) { - $('duration').focus(); - $('duration').style.color = "#F00"; - return; - } - $('duration').style.color = "#000"; - duration = parseFloat(duration.split(":")[0]) + parseFloat(duration.split(":")[1] / 60); + case "DURATION": + case "DEPARTURE": + // Recompute arrival time based on user-changed/previously calculated duration + // (if no duration is available, estimate it) + var duration = $("duration").value.trim(); + if (duration != "") { + if (!RE_TIME.test(duration)) { + $("duration").focus(); + $("duration").style.color = "#F00"; + return; + } + $("duration").style.color = "#000"; + duration = + parseFloat(duration.split(":")[0]) + + parseFloat(duration.split(":")[1] / 60); + dst_time = 0; + break; + } + // else no duration known, estimate and reset + param = "AIRPORT"; + // fallthru + + case "AIRPORT": + // User has changed airport, estimate duration based on distance then (30 min plus 1 hr/500 mi) and + // compute time at destination + var distance = $("distance").value; + if (!re_numeric.test(distance)) { + $("distance").focus(); + $("distance").style.color = "#F00"; + return; + } + $("distance").style.color = "#000"; + duration = $("distance").value / modespeeds[getMode()] + 0.5; dst_time = 0; break; - } - // else no duration known, estimate and reset - param = 'AIRPORT'; - // fallthru - case 'AIRPORT': - // User has changed airport, estimate duration based on distance then (30 min plus 1 hr/500 mi) and - // compute time at destination - var distance = $('distance').value; - if(! re_numeric.test(distance)) { - $('distance').focus(); - $('distance').style.color = "#F00"; + default: + alert("Error: Unknown parameter '" + param + "' at calcDuration()"); return; - } - $('distance').style.color = "#000"; - duration = ($('distance').value / modespeeds[getMode()]) + 0.5; - dst_time = 0; - break; - - default: - alert("Error: Unknown parameter '" + param + "' at calcDuration()"); - return; } // Do we have a starting time? - src_time = $('src_time').value; - if(src_time != "" && src_time != "HH:MM") { + src_time = $("src_time").value; + if (src_time != "" && src_time != "HH:MM") { // We do! Does it make sense? - if(! RE_TIME.test(src_time)) { - $('src_time').focus(); - $('src_time').style.color = "#F00"; + if (!RE_TIME.test(src_time)) { + $("src_time").focus(); + $("src_time").style.color = "#F00"; return; } src_time = parseTimeString(src_time); // Do we have an arrival time? - if(dst_time != 0) { + if (dst_time != 0) { // Yes, validate it - if(! RE_TIME.test(dst_time)) { - $('dst_time').focus(); - $('dst_time').style.color = "#F00"; - return; + if (!RE_TIME.test(dst_time)) { + $("dst_time").focus(); + $("dst_time").style.color = "#F00"; + return; } // Case 3: Need to determine duration dst_time = parseTimeString(dst_time); - days = $('dst_days').value; - if(days != "") { - dst_time += parseInt($('dst_days').value) * 24; + days = $("dst_days").value; + if (days != "") { + dst_time += parseInt($("dst_days").value) * 24; } duration = 0; } // Get timezones - src_tz = getTZ('src_ap'); - dst_tz = getTZ('dst_ap'); - src_dst = getDST('src_ap'); - dst_dst = getDST('dst_ap'); + src_tz = getTZ("src_ap"); + dst_tz = getTZ("dst_ap"); + src_dst = getDST("src_ap"); + dst_dst = getDST("dst_ap"); // Verify if DST is active // 2008-01-26[0],2008[1],20[2],01[3],26[4] - src_date = re_date.exec($('src_date').value); - if(! src_date) { + src_date = re_date.exec($("src_date").value); + if (!src_date) { // Nonsensical date return; } @@ -2441,72 +3175,81 @@ function calcDuration(param) { src_day = src_date[4]; src_date = new Date(); src_date = src_date.setFullYear(src_year, src_month - 1, src_day); - if(checkDST(src_dst, src_date, src_year)) { + if (checkDST(src_dst, src_date, src_year)) { src_tz += 1; src_dst = "Y"; } - if(checkDST(dst_dst, src_date, src_year)) { + if (checkDST(dst_dst, src_date, src_year)) { dst_tz += 1; dst_dst = "Y"; } - $('icon_clock').title = - Gettext.strargs(gt.gettext("Departure UTC %1%2%3, Arrival UTC %4%5%6, Time difference %7 hours"), - [src_tz > 0 ? "+" : "", src_tz, src_dst == "Y" ? " (" + gt.gettext("DST") + ")" : "", - dst_tz > 0 ? "+" : "", dst_tz, dst_dst == "Y" ? " (" + gt.gettext("DST") + ")" : "", - dst_tz-src_tz]); + $("icon_clock").title = Gettext.strargs( + gt.gettext( + "Departure UTC %1%2%3, Arrival UTC %4%5%6, Time difference %7 hours" + ), + [ + src_tz > 0 ? "+" : "", + src_tz, + src_dst == "Y" ? " (" + gt.gettext("DST") + ")" : "", + dst_tz > 0 ? "+" : "", + dst_tz, + dst_dst == "Y" ? " (" + gt.gettext("DST") + ")" : "", + dst_tz - src_tz, + ] + ); // Case 2: Calculate arrival time from starting time and duration - if(dst_time == 0) { - dst_time = src_time + duration + (dst_tz-src_tz); + if (dst_time == 0) { + dst_time = src_time + duration + (dst_tz - src_tz); days = Math.floor(dst_time / 24); dst_time = dst_time % 24; - while(dst_time < 0) dst_time += 24; + while (dst_time < 0) dst_time += 24; hours = Math.floor(dst_time); - mins = Math.floor((dst_time-hours) * 60); - if(mins < 10) { - mins = "0" + mins + ""; - } - $('dst_time').value = hours + ":" + mins; - $('dst_time').style.color = '#000'; - if(days == 0) { - $('dst_days').value = ""; - $('dst_days').style.display = "none"; + mins = Math.floor((dst_time - hours) * 60); + if (mins < 10) { + mins = "0" + mins + ""; + } + $("dst_time").value = hours + ":" + mins; + $("dst_time").style.color = "#000"; + if (days == 0) { + $("dst_days").value = ""; + $("dst_days").style.display = "none"; } else { - if(days > 0) { - $('dst_days').value = Gettext.strargs(gt.gettext("+%1 day"), [days]); - } else { - $('dst_days').value = Gettext.strargs(gt.gettext("%1 day"), [days]); - } - $('dst_days').style.display = "inline"; + if (days > 0) { + $("dst_days").value = Gettext.strargs(gt.gettext("+%1 day"), [days]); + } else { + $("dst_days").value = Gettext.strargs(gt.gettext("%1 day"), [days]); + } + $("dst_days").style.display = "inline"; } } // Case 3: Calculate duration from arrival time and starting time - if(duration == 0) { - duration = (dst_time-src_time) - (dst_tz-src_tz); - if(duration < 0) duration += 24; + if (duration == 0) { + duration = dst_time - src_time - (dst_tz - src_tz); + if (duration < 0) duration += 24; } } else { // Case 1: Do nothing, just use estimated duration - $('icon_clock').title = gt.gettext("Flight departure and arrival times"); + $("icon_clock").title = gt.gettext("Flight departure and arrival times"); } - if(param == "AIRPORT" || param == "ARRIVAL") { + if (param == "AIRPORT" || param == "ARRIVAL") { // Convert duration back to clock time (sexagesimal) hours = Math.floor(duration); mins = Math.round((Math.abs(duration) % 1.0) * 60); - if(mins == 60) { + if (mins == 60) { mins = 0; hours++; } - if(mins < 10) { + if (mins < 10) { mins = "0" + mins + ""; } - if(hours < 10) { + if (hours < 10) { hours = "0" + hours + ""; } - $('duration').value = hours + ":" + mins; - $('duration').style.color = "#000"; + $("duration").value = hours + ":" + mins; + $("duration").style.color = "#000"; } markAsChanged(); } @@ -2515,63 +3258,63 @@ function calcDuration(param) { // Also calculates distance and duration (unless "quick" is true) // type: "src_ap" or "dst_ap" function markAirport(element, quick) { - if(element.startsWith("src_ap")) { - var icon = '/img/icon_plane-src.png'; + if (element.startsWith("src_ap")) { + var icon = "/img/icon_plane-src.png"; } else { - var icon = '/img/icon_plane-dst.png'; + var icon = "/img/icon_plane-dst.png"; } - if(getCurrentPane() == "multiinput") { + if (getCurrentPane() == "multiinput") { element = markingLimit(element); } - if(!element) return; // nothing to draw + if (!element) return; // nothing to draw - var data = $(element + 'id').value.split(":"); + var data = $(element + "id").value.split(":"); var iata = data[0]; var apid = data[1]; var x = data[2]; var y = data[3]; - if(apid > 0) { + if (apid > 0) { var point = projectedPoint(x, y); var marker = new OpenLayers.Feature.Vector(point); marker.attributes = { name: "", icon: icon, size: 17, - offset: -17/2, + offset: -17 / 2, opacity: 1, - code: data[0] + code: data[0], }; - airportLayer.addFeatures(marker, {silent: true}); + airportLayer.addFeatures(marker, { silent: true }); } - if(element.startsWith("src_ap")) { - if(input_srcmarker) { + if (element.startsWith("src_ap")) { + if (input_srcmarker) { airportLayer.removeFeatures([input_srcmarker]); } - if(apid > 0) { + if (apid > 0) { input_srcmarker = marker; - if(element == "src_ap") { - input_toggle = "dst_ap"; // single input + if (element == "src_ap") { + input_toggle = "dst_ap"; // single input } else { - var idx = multiinput_order.indexOf(element) + 1; - if(idx == multiinput_order.length) idx = 0; - input_toggle = multiinput_order[idx]; + var idx = multiinput_order.indexOf(element) + 1; + if (idx == multiinput_order.length) idx = 0; + input_toggle = multiinput_order[idx]; } } else { input_srcmarker = null; } } else { - if(input_dstmarker) { + if (input_dstmarker) { airportLayer.removeFeatures([input_dstmarker]); } - if(apid > 0) { + if (apid > 0) { input_dstmarker = marker; - if(element == "dst_ap") { - input_toggle = "src_ap"; // single input + if (element == "dst_ap") { + input_toggle = "src_ap"; // single input } else { - var idx = multiinput_order.indexOf(element) + 1; - if(idx == multiinput_order.length) idx = 0; - input_toggle = multiinput_order[idx]; + var idx = multiinput_order.indexOf(element) + 1; + if (idx == multiinput_order.length) idx = 0; + input_toggle = multiinput_order[idx]; } } else { input_dstmarker = null; @@ -2579,72 +3322,83 @@ function markAirport(element, quick) { } // Draw line and calculate distance and duration - if(! quick) { - if(input_line) { + if (!quick) { + if (input_line) { lineLayer.removeFeatures(input_line); input_line = null; } - if(input_dstmarker && input_srcmarker) { - if(getCurrentPane() == "input") { - - var lon1 = getX('src_ap'); - var lat1 = getY('src_ap'); - var lon2 = getX('dst_ap'); - var lat2 = getY('dst_ap'); - var distance = gcDistance(lat1, lon1, lat2, lon2); - input_line = drawLine(parseFloat(lon1), parseFloat(lat1), - parseFloat(lon2), parseFloat(lat2), - 4, distance, COLOR_HIGHLIGHT); + if (input_dstmarker && input_srcmarker) { + if (getCurrentPane() == "input") { + var lon1 = getX("src_ap"); + var lat1 = getY("src_ap"); + var lon2 = getX("dst_ap"); + var lat2 = getY("dst_ap"); + var distance = gcDistance(lat1, lon1, lat2, lon2); + input_line = drawLine( + parseFloat(lon1), + parseFloat(lat1), + parseFloat(lon2), + parseFloat(lat2), + 4, + distance, + COLOR_HIGHLIGHT + ); } else { - input_line = []; - for(i = 1; i <= multiinput_rows; i++) { - var src_ap = $('src_ap' + i + 'id').value; - var dst_ap = $('dst_ap' + i + 'id').value; - if(src_ap != 0 && dst_ap != 0) { - var src_ap_data = src_ap.split(":"); - var lon1 = src_ap_data[2]; - var lat1 = src_ap_data[3]; - var dst_ap_data = dst_ap.split(":"); - var lon2 = dst_ap_data[2]; - var lat2 = dst_ap_data[3]; - var distance = gcDistance(lat1, lon1, lat2, lon2); - line = drawLine(parseFloat(lon1), parseFloat(lat1), - parseFloat(lon2), parseFloat(lat2), - 4, distance, COLOR_HIGHLIGHT); - input_line = input_line.concat(line); - } else { - break; // stop drawing - } - } + input_line = []; + for (i = 1; i <= multiinput_rows; i++) { + var src_ap = $("src_ap" + i + "id").value; + var dst_ap = $("dst_ap" + i + "id").value; + if (src_ap != 0 && dst_ap != 0) { + var src_ap_data = src_ap.split(":"); + var lon1 = src_ap_data[2]; + var lat1 = src_ap_data[3]; + var dst_ap_data = dst_ap.split(":"); + var lon2 = dst_ap_data[2]; + var lat2 = dst_ap_data[3]; + var distance = gcDistance(lat1, lon1, lat2, lon2); + line = drawLine( + parseFloat(lon1), + parseFloat(lat1), + parseFloat(lon2), + parseFloat(lat2), + 4, + distance, + COLOR_HIGHLIGHT + ); + input_line = input_line.concat(line); + } else { + break; // stop drawing + } + } } lineLayer.addFeatures(input_line); - oldDist = $('distance').value; - $('distance').value = distance; - if(oldDist == "" && $('dst_time').value != $('dst_time').hintText) { - // user has already manually entered arrival time - calcDuration("ARRIVAL"); + oldDist = $("distance").value; + $("distance").value = distance; + if (oldDist == "" && $("dst_time").value != $("dst_time").hintText) { + // user has already manually entered arrival time + calcDuration("ARRIVAL"); } else { - // compute duration and arrival time - calcDuration("AIRPORT"); + // compute duration and arrival time + calcDuration("AIRPORT"); } } else { - $('distance').value = ""; - $('duration').value = ""; + $("distance").value = ""; + $("duration").value = ""; } } } // Remove input markers and flight lines function unmarkAirports() { - if(input_srcmarker) { + if (input_srcmarker) { airportLayer.removeFeatures([input_srcmarker]); input_srcmarker = null; } - if(input_dstmarker) { + if (input_dstmarker) { airportLayer.removeFeatures([input_dstmarker]); input_dstmarker = null; } - if(input_line) { + if (input_line) { lineLayer.removeFeatures(input_line); input_line = null; } @@ -2652,18 +3406,18 @@ function unmarkAirports() { // Find the highest valid (defined && non-zero apid) airport in multiinput function markingLimit(element) { - if(element.startsWith("src_ap")) { + if (element.startsWith("src_ap")) { return "src_ap1"; } - for(i = 1; i <= multiinput_rows; i++) { - var ap = $("dst_ap" + i + 'id').value; - if(!ap || ap == "" || ap == 0) { - i--; // this airport is no longer valid, so we use prev row as limit + for (i = 1; i <= multiinput_rows; i++) { + var ap = $("dst_ap" + i + "id").value; + if (!ap || ap == "" || ap == 0) { + i--; // this airport is no longer valid, so we use prev row as limit break; } } - if(i == 0) return null; // no valid airports - if(i > multiinput_rows) i = multiinput_rows; // otherwise it goes one over if all rows are valid + if (i == 0) return null; // no valid airports + if (i > multiinput_rows) i = multiinput_rows; // otherwise it goes one over if all rows are valid return "dst_ap" + i; } @@ -2671,34 +3425,34 @@ function markingLimit(element) { // If "true" (manual), swap both // If "false" (automatic), swap only top to bottom and restore top to original function swapAirports(manual) { - if(manual) { - srcName = $('src_ap').value; - srcData = $('src_apid').value; + if (manual) { + srcName = $("src_ap").value; + srcData = $("src_apid").value; } // Clear out times (makes no sense to swap them) clearTimes(); // Clone SRC from DST - $('src_ap').value = $('dst_ap').value; - $('src_apid').value = $('dst_apid').value; + $("src_ap").value = $("dst_ap").value; + $("src_apid").value = $("dst_apid").value; - if(manual) { + if (manual) { // Clone DST from SRC - $('dst_ap').value = srcName; - $('dst_apid').value = srcData; - if(srcName != "") { - $('dst_ap').style.color = "#000"; + $("dst_ap").value = srcName; + $("dst_apid").value = srcData; + if (srcName != "") { + $("dst_ap").style.color = "#000"; } } else { // Clear out DST - $('dst_ap').value = ""; - $('dst_apid').value = ""; + $("dst_ap").value = ""; + $("dst_apid").value = ""; } // Redraw markers and airline codes markAirport("src_ap", true); markAirport("dst_ap", true); - if(manual) { + if (manual) { markAsChanged(); } } @@ -2707,44 +3461,45 @@ function swapAirports(manual) { // "quick" is passed to markAirport function selectAirport(apid, select, quick, code) { var found = false; - for(var ap = 0; ap < airportLayer.features.length; ap++) { + for (var ap = 0; ap < airportLayer.features.length; ap++) { attrstack = new Array(); - if(airportLayer.features[ap].cluster) { - for(var c = 0; c < airportLayer.features[ap].cluster.length; c++) { - attrstack.push(airportLayer.features[ap].cluster[c].attributes); + if (airportLayer.features[ap].cluster) { + for (var c = 0; c < airportLayer.features[ap].cluster.length; c++) { + attrstack.push(airportLayer.features[ap].cluster[c].attributes); } } else { attrstack.push(airportLayer.features[ap].attributes); } - while(attrstack.length > 0) { + while (attrstack.length > 0) { attrs = attrstack.pop(); - if((apid && attrs.apid == apid) || - (code && attrs.code == code)) { - // If "select" is true, we select the airport into the input form instead of popping it up - if(select && isEditMode()) { - var element = input_toggle; - $(element).value = attrs.name; - $(element).style.color = "#000"; - $(element + 'id').value = attrs.apdata; - replicateSelection(element); - markAirport(element, quick); - markAsChanged(true); - closePopup(true); - } else { - if(airportLayer.features[ap].cluster) { - onAirportSelect(airportLayer.features[ap].cluster[attrstack.length]); - } else { - onAirportSelect(airportLayer.features[ap]); - } - } - found = true; - return found; + if ((apid && attrs.apid == apid) || (code && attrs.code == code)) { + // If "select" is true, we select the airport into the input form instead of popping it up + if (select && isEditMode()) { + var element = input_toggle; + $(element).value = attrs.name; + $(element).style.color = "#000"; + $(element + "id").value = attrs.apdata; + replicateSelection(element); + markAirport(element, quick); + markAsChanged(true); + closePopup(true); + } else { + if (airportLayer.features[ap].cluster) { + onAirportSelect( + airportLayer.features[ap].cluster[attrstack.length] + ); + } else { + onAirportSelect(airportLayer.features[ap]); + } + } + found = true; + return found; } } } // Search failed if (!quick && !code) { - if(confirm("This airport is currently filtered out. Clear filter?")) { + if (confirm("This airport is currently filtered out. Clear filter?")) { clearFilter(false); } } @@ -2753,74 +3508,74 @@ function selectAirport(apid, select, quick, code) { // Change number of rows displayed in multiinput function changeRows(type) { - switch(type) { - case "More": - if(multiinput_rows >= 3) { - $('b_more').disabled = true; - } - if(multiinput_rows == 1) { - $('b_less').disabled = false; - } - source = "dst_ap" + multiinput_rows; - multiinput_rows++; - var row = "row" + multiinput_rows; - $(row).style.display = ""; // resolves to "table-row" in FF and "block" in IE... - replicateSelection(source); - break; + switch (type) { + case "More": + if (multiinput_rows >= 3) { + $("b_more").disabled = true; + } + if (multiinput_rows == 1) { + $("b_less").disabled = false; + } + source = "dst_ap" + multiinput_rows; + multiinput_rows++; + var row = "row" + multiinput_rows; + $(row).style.display = ""; // resolves to "table-row" in FF and "block" in IE... + replicateSelection(source); + break; - case "Less": - if(multiinput_rows == 4) { - $('b_more').disabled = false; - } - if(multiinput_rows == 2) { - $('b_less').disabled = true; - } - $("row" + multiinput_rows).style.display = "none"; - multiinput_rows--; - break; + case "Less": + if (multiinput_rows == 4) { + $("b_more").disabled = false; + } + if (multiinput_rows == 2) { + $("b_less").disabled = true; + } + $("row" + multiinput_rows).style.display = "none"; + multiinput_rows--; + break; } - markAirport('dst_ap' + multiinput_rows); // redraw flight path + markAirport("dst_ap" + multiinput_rows); // redraw flight path } // In multiinput mode, copy entered airport/airline/date into next row (when empty) // Special argument "More" adds a row, "Less" removes one function replicateSelection(source) { - if(getCurrentPane() != "multiinput") return; - - switch(source) { - case "dst_ap1": - case "dst_ap2": - case "dst_ap3": - case "airline1": - case "airline2": - case "airline3": - // Check if the row we're trying to replicate to is active; if no, abort - idx = parseInt(source.charAt(source.length-1)) + 1; - row = "row" + idx; - if($(row).style.display == "none") return; - - target = "src_ap" + idx; - date_target = "src_date" + idx; - date_source = "src_date" + (idx - 1); - al_target = "airline" + idx; - al_source = "airline" + (idx - 1); - break; - - default: - return; // do nothing - } - if($(source + 'id').value != 0 && $(target + 'id').value == 0) { + if (getCurrentPane() != "multiinput") return; + + switch (source) { + case "dst_ap1": + case "dst_ap2": + case "dst_ap3": + case "airline1": + case "airline2": + case "airline3": + // Check if the row we're trying to replicate to is active; if no, abort + idx = parseInt(source.charAt(source.length - 1)) + 1; + row = "row" + idx; + if ($(row).style.display == "none") return; + + target = "src_ap" + idx; + date_target = "src_date" + idx; + date_source = "src_date" + (idx - 1); + al_target = "airline" + idx; + al_source = "airline" + (idx - 1); + break; + + default: + return; // do nothing + } + if ($(source + "id").value != 0 && $(target + "id").value == 0) { $(target).value = $(source).value; $(target).style.color = "#000"; - $(target + 'id').value = $(source + 'id').value; + $(target + "id").value = $(source + "id").value; } - if($(al_source + 'id').value != 0 && $(al_target + 'id').value == 0) { + if ($(al_source + "id").value != 0 && $(al_target + "id").value == 0) { $(al_target).value = $(al_source).value; $(al_target).style.color = "#000"; - $(al_target + 'id').value = $(al_source + 'id').value; + $(al_target + "id").value = $(al_source + "id").value; } - if($(date_target).value == "") { + if ($(date_target).value == "") { $(date_target).value = $(date_source).value; } } @@ -2829,15 +3584,15 @@ function replicateSelection(source) { // if edit is true, set it in editor, else set in map (filter) // return true if found, false if not function selectAirline(new_alid, edit) { - var al_select = document.forms['filterform'].Airlines; - for(index = 0; index < al_select.length; index++) { - if(al_select[index].value.split(";")[0] == new_alid) { - if(edit) { - $(input_al_toggle).value = al_select[index].value.split(";")[1]; - $(input_al_toggle).style.color = "#000"; - $(input_al_toggle + 'id').value = new_alid; + var al_select = document.forms["filterform"].Airlines; + for (index = 0; index < al_select.length; index++) { + if (al_select[index].value.split(";")[0] == new_alid) { + if (edit) { + $(input_al_toggle).value = al_select[index].value.split(";")[1]; + $(input_al_toggle).style.color = "#000"; + $(input_al_toggle + "id").value = new_alid; } else { - al_select.selectedIndex = index; + al_select.selectedIndex = index; } return true; } @@ -2846,7 +3601,13 @@ function selectAirline(new_alid, edit) { } function getAirlineMapIcon(alid) { - return ""; + return ( + "" + ); } // @@ -2862,21 +3623,25 @@ function showAirlineMap(alid) { // Context help // function help(context) { - window.open('/help/' + context, 'Help', 'width=500,height=400,scrollbars=yes'); + window.open( + "/help/" + context, + "Help", + "width=500,height=400,scrollbars=yes" + ); } // // Import flights // function openImport() { - window.open('/html/import', 'Import', 'width=900,height=600,scrollbars=yes'); + window.open("/html/import", "Import", "width=900,height=600,scrollbars=yes"); } // // Change settings // function settings() { - location.href = '/html/settings'; + location.href = "/html/settings"; } // @@ -2889,20 +3654,20 @@ function keyPress(e, element) { if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; - if(element == "login") { - if(e == "CHANGE") { - if(logged_in == "pending") return true; + if (element == "login") { + if (e == "CHANGE") { + if (logged_in == "pending") return true; } if (keycode == Event.KEY_RETURN) { logged_in = "pending"; xmlhttpPost("/php/login.php"); } } else { - if(keycode == Event.KEY_TAB) { + if (keycode == Event.KEY_TAB) { // Ignore fields that are already autocompleted - if($(element).value.length > 4) return; + if ($(element).value.length > 4) return; - switch(element) { + switch (element) { case "qs": case "src_ap": case "src_ap1": @@ -2939,108 +3704,128 @@ function keyPress(e, element) { // function login(str, param) { var result = JSON.parse(str); - var name = result['name']; - $("loginstatus").style.display = 'inline'; + var name = result["name"]; + $("loginstatus").style.display = "inline"; // Login successful - switch(result['status']) { - case 1: - prefs_editor = result['editor']; - elite = result['elite']; - logged_in = true; - $("loginform").style.display = 'none'; - $("langselect").style.display = 'none'; - $("controlpanel").style.display = 'inline'; - switch(param) { - case "REFRESH": - $("loginstatus").innerHTML = getEliteIcon(elite) + Gettext.strargs(gt.gettext("Logged in as %1"), [name]); - break; + switch (result["status"]) { + case 1: + prefs_editor = result["editor"]; + elite = result["elite"]; + logged_in = true; + $("loginform").style.display = "none"; + $("langselect").style.display = "none"; + $("controlpanel").style.display = "inline"; + switch (param) { + case "REFRESH": + $("loginstatus").innerHTML = + getEliteIcon(elite) + + Gettext.strargs(gt.gettext("Logged in as %1"), [name]); + break; - case "NEWUSER": - $("loginstatus").innerHTML = getEliteIcon(elite) + Gettext.strargs(gt.gettext("Welcome, %1 !"), [name]); - break; + case "NEWUSER": + $("loginstatus").innerHTML = + getEliteIcon(elite) + + Gettext.strargs(gt.gettext("Welcome, %1 !"), [name]); + break; - default: - $("stats").innerHTML = "" + gt.gettext("Loading") + ""; - $("stats_ajax").style.display = "inline"; - $("loginstatus").innerHTML = getEliteIcon(elite) + Gettext.strargs(gt.gettext("Hi, %1 !"), [name]); - break; - } + default: + $("stats").innerHTML = "" + gt.gettext("Loading") + ""; + $("stats_ajax").style.display = "inline"; + $("loginstatus").innerHTML = + getEliteIcon(elite) + + Gettext.strargs(gt.gettext("Hi, %1 !"), [name]); + break; + } - switch(elite) { - case "X": - $("news").style.display = 'inline'; - $("news").innerHTML = getEliteIcon("X") + - " " + - gt.gettext("Welcome back! We're delighted to see that you like OpenFlights.
Please donate and help keep the site running!"); - break; + switch (elite) { + case "X": + $("news").style.display = "inline"; + $("news").innerHTML = + getEliteIcon("X") + + " " + + gt.gettext( + "Welcome back! We're delighted to see that you like OpenFlights.
Please donate and help keep the site running!" + ); + break; - case "G": - case "P": - // Remove ad pane and manually force help to show - $(getCurrentPane()).style.display = 'none'; - $("help").style.display = 'inline'; - paneStack[0] = "help"; - break; - } + case "G": + case "P": + // Remove ad pane and manually force help to show + $(getCurrentPane()).style.display = "none"; + $("help").style.display = "inline"; + paneStack[0] = "help"; + break; + } - if(param == "NEWUSER") { - $("news").innerHTML = - " " + - Gettext.strargs(gt.gettext("Welcome to OpenFlights! Click on %1 to start adding flights, or on %2 to load in existing flights from sites like FlightMemory."), - [ "", - "" ]); - $("news").style.display = 'inline'; - } else { - closeNews(); - } + if (param == "NEWUSER") { + $("news").innerHTML = + " " + + Gettext.strargs( + gt.gettext( + "Welcome to OpenFlights! Click on %1 to start adding flights, or on %2 to load in existing flights from sites like FlightMemory." + ), + [ + "", + "", + ] + ); + $("news").style.display = "inline"; + } else { + closeNews(); + } - // in a NEWUSER or REFRESH, we've already drawn the map, so no need to redraw - if(!param) { - clearStack(); - clearMap(); - clearFilter(true); - } - break; + // in a NEWUSER or REFRESH, we've already drawn the map, so no need to redraw + if (!param) { + clearStack(); + clearMap(); + clearFilter(true); + } + break; - case 2: - // Successful but need to switch UI language, so reload, stripping out any "?lang" in the URL - $("loginstatus").innerHTML = "" + gt.gettext("Loading") + ""; - location.href = location.origin + location.pathname; - break; + case 2: + // Successful but need to switch UI language, so reload, stripping out any "?lang" in the URL + $("loginstatus").innerHTML = "" + gt.gettext("Loading") + ""; + location.href = location.origin + location.pathname; + break; - default: - // Login failed - logged_in = false; - $("loginstatus").innerHTML = "" + result['message'] + ""; - showLoadingAnimation(false); + default: + // Login failed + logged_in = false; + $("loginstatus").innerHTML = "" + result["message"] + ""; + showLoadingAnimation(false); } } function logout(str) { logged_in = false; - $("loginstatus").innerHTML = "" + gt.gettext("You have been logged out.") + ""; + $("loginstatus").innerHTML = + "" + gt.gettext("You have been logged out.") + ""; $("stats").innerHTML = "" + gt.gettext("Loading") + ""; - $("stats_ajax").style.display = 'inline'; - $("loginform").style.display = 'inline'; - $("langselect").style.display = 'block'; - $("controlpanel").style.display = 'none'; - $(getCurrentPane()).style.display = 'none'; - $("ad").style.display = 'inline'; + $("stats_ajax").style.display = "inline"; + $("loginform").style.display = "inline"; + $("langselect").style.display = "block"; + $("controlpanel").style.display = "none"; + $(getCurrentPane()).style.display = "none"; + $("ad").style.display = "inline"; paneStack[0] = "ad"; clearStack(); clearMap(); clearFilter(true); closeNews(); - document.forms['login'].name.value = ""; - document.forms['login'].pw.value = ""; - document.forms['login'].name.focus(); + document.forms["login"].name.value = ""; + document.forms["login"].pw.value = ""; + document.forms["login"].name.focus(); } // Get current transport mode function getMode() { - if(getCurrentPane() == "input") { - mode = document.forms['inputform'].mode.value; + if (getCurrentPane() == "input") { + mode = document.forms["inputform"].mode.value; } else { mode = "F"; } @@ -3051,31 +3836,31 @@ function getMode() { // Possible panes: 'ad', 'result', 'input', 'help' function getCurrentPane() { - return paneStack[paneStack.length-1]; + return paneStack[paneStack.length - 1]; } // Return true if we are in detailed or multi edit mode function isEditMode() { currentPane = getCurrentPane(); - return (currentPane == "input" || currentPane == "multiinput"); + return currentPane == "input" || currentPane == "multiinput"; } // Open a new pane // If the pane is open already, do nothing function openPane(newPane) { - if(paneStack.length > 0) { + if (paneStack.length > 0) { var currentPane = getCurrentPane(); - if(currentPane == newPane) return; - $(currentPane).style.display = 'none'; + if (currentPane == newPane) return; + $(currentPane).style.display = "none"; } - $(newPane).style.display = 'inline'; + $(newPane).style.display = "inline"; paneStack.push(newPane); } // Check if a named pane is already open, return index if yes function findPane(pane) { - for(i = 0; i < paneStack.length; i++) { - if(paneStack[i] == pane) { + for (i = 0; i < paneStack.length; i++) { + if (paneStack[i] == pane) { return i; } } @@ -3085,28 +3870,28 @@ function findPane(pane) { // Close current pane // If the current pane is the last one, do nothing function closePane() { - if(paneStack.length == 1) return; + if (paneStack.length == 1) return; - if(isEditMode()) { + if (isEditMode()) { unmarkAirports(); - $("newairport").style.display = 'none'; - $("qsmini").style.display = 'block'; + $("newairport").style.display = "none"; + $("qsmini").style.display = "block"; } var currentPane = paneStack.pop(); var lastPane = getCurrentPane(); - if(currentPane == "result") { + if (currentPane == "result") { apid = 0; } - $(currentPane).style.display = 'none'; - $(lastPane).style.display = 'inline'; + $(currentPane).style.display = "none"; + $(lastPane).style.display = "inline"; // If ad pane is now displayed, refresh it - if(paneStack.length == 1 && paneStack[0] == "ad") refreshAd(); + if (paneStack.length == 1 && paneStack[0] == "ad") refreshAd(); } // Clear all panes until the base pane (ad) function clearStack() { - while(paneStack.length > 1) { + while (paneStack.length > 1) { closePane(); } } @@ -3114,23 +3899,27 @@ function clearStack() { function openDetailedInput(param) { // Does the user already have an input pane open? p = findPane("input"); - if(!p) p = findPane("multiinput"); - if(p) { + if (!p) p = findPane("multiinput"); + if (p) { // Have they changed it, and do they want to throw away the changes? - if(hasChanged()) { - switch(param) { - case "ADD": - case "COPY": - msg = gt.gettext("You are already editing a flight. OK to discard your changes and add a new flight instead?"); - break; + if (hasChanged()) { + switch (param) { + case "ADD": + case "COPY": + msg = gt.gettext( + "You are already editing a flight. OK to discard your changes and add a new flight instead?" + ); + break; - break; - case "EDIT": - msg = gt.gettext("You are already editing a flight. OK to discard your changes and edit this flight instead?"); - break; + break; + case "EDIT": + msg = gt.gettext( + "You are already editing a flight. OK to discard your changes and edit this flight instead?" + ); + break; } - if(! confirm(msg)) { - return; + if (!confirm(msg)) { + return; } } $(paneStack[p]).style.display = "none"; @@ -3138,29 +3927,29 @@ function openDetailedInput(param) { } openPane("input"); - switch(param) { - case "ADD": - clearInput(); + switch (param) { + case "ADD": + clearInput(); // fall thru - case "COPY": - $("addflighttitle").style.display = 'inline'; - $("addflightbuttons").style.display = 'inline'; - $("editflighttitle").style.display = 'none'; - $("editflightbuttons").style.display = 'none'; - break; + case "COPY": + $("addflighttitle").style.display = "inline"; + $("addflightbuttons").style.display = "inline"; + $("editflighttitle").style.display = "none"; + $("editflightbuttons").style.display = "none"; + break; - case "EDIT": - $("addflighttitle").style.display = 'none'; - $("addflightbuttons").style.display = 'none'; - $("editflighttitle").style.display = 'inline'; - $("editflightbuttons").style.display = 'inline'; + case "EDIT": + $("addflighttitle").style.display = "none"; + $("addflightbuttons").style.display = "none"; + $("editflighttitle").style.display = "inline"; + $("editflightbuttons").style.display = "inline"; } input_toggle = "src_ap"; input_al_toggle = "airline"; - $("quicksearch").style.display = 'none'; - $("qsmini").style.display = 'none'; - $("newairport").style.display = 'inline'; + $("quicksearch").style.display = "none"; + $("qsmini").style.display = "none"; + $("newairport").style.display = "inline"; $("input_status").innerHTML = ""; } @@ -3168,12 +3957,18 @@ function openDetailedInput(param) { function openBasicInput(param) { // Does the user already have an input pane open? p = findPane("input"); - if(!p) p = findPane("multiinput"); - if(p) { + if (!p) p = findPane("multiinput"); + if (p) { // Have they changed it, and do they want to throw away the changes? - if(hasChanged()) { - if(! confirm(gt.gettext("You are already editing a flight. OK to discard your changes and add a new flight instead?"))) { - return; + if (hasChanged()) { + if ( + !confirm( + gt.gettext( + "You are already editing a flight. OK to discard your changes and add a new flight instead?" + ) + ) + ) { + return; } } $(paneStack[p]).style.display = "none"; @@ -3181,9 +3976,9 @@ function openBasicInput(param) { } openPane("multiinput"); - $("quicksearch").style.display = 'none'; - $("qsmini").style.display = 'none'; - $("newairport").style.display = 'inline'; + $("quicksearch").style.display = "none"; + $("qsmini").style.display = "none"; + $("newairport").style.display = "inline"; $("multiinput_status").innerHTML = ""; clearInput(); input_toggle = multiinput_order[0]; @@ -3191,8 +3986,14 @@ function openBasicInput(param) { } function closeInput() { - if(hasChanged()) { - if(!confirm(gt.gettext("Changes made to this flight have not been saved. OK to discard them?"))) { + if (hasChanged()) { + if ( + !confirm( + gt.gettext( + "Changes made to this flight have not been saved. OK to discard them?" + ) + ) + ) { return; } } @@ -3201,37 +4002,39 @@ function closeInput() { // Reload flights list if we were editing flights, or // user had a result pane open when he opened new flight editor - if(getCurrentPane() == "result" && - ($("editflighttitle").style.display == 'inline' || - $("addflighttitle").style.display == 'inline')) { + if ( + getCurrentPane() == "result" && + ($("editflighttitle").style.display == "inline" || + $("addflighttitle").style.display == "inline") + ) { xmlhttpPost(URL_FLIGHTS, 0, "RELOAD"); } } // Clear out (restore to defaults) the time indicators in the editor function clearTimes() { - $('src_time').value = $('src_time').hintText; - $('dst_time').value = $('dst_time').hintText; - $('dst_days').value = ""; - $('src_time').style.color = '#888'; - $('dst_time').style.color = '#888'; - $('dst_days').style.display = "none"; + $("src_time").value = $("src_time").hintText; + $("dst_time").value = $("dst_time").hintText; + $("dst_days").value = ""; + $("src_time").style.color = "#888"; + $("dst_time").style.color = "#888"; + $("dst_days").style.display = "none"; } // YYYY-MM-DD function todayString() { var today = new Date(); - var month = (today.getMonth() + 1) + ""; - if(month.length == 1) month = "0" + month; + var month = today.getMonth() + 1 + ""; + if (month.length == 1) month = "0" + month; var day = today.getDate() + ""; - if(day.length == 1) day = "0" + day; - return today.getFullYear()+ "-" + month + "-" + day; + if (day.length == 1) day = "0" + day; + return today.getFullYear() + "-" + month + "-" + day; } // Clear out (restore to defaults) the input box function clearInput() { resetHintTextboxes(); - if(getCurrentPane() == "input") { + if (getCurrentPane() == "input") { var form = document.forms["inputform"]; form.src_date.value = todayString(); form.src_date.focus(); @@ -3239,10 +4042,10 @@ function clearInput() { form.dst_apid.value = 0; form.dst_days.value = ""; clearTimes(); - $('duration').value = ""; - $('duration').style.color = "#000"; - $('distance').value = ""; - $('distance').style.color = "#000"; + $("duration").value = ""; + $("duration").style.color = "#000"; + $("distance").value = ""; + $("distance").style.color = "#000"; form.number.value = ""; form.airlineid.value = 0; form.seat.value = ""; @@ -3252,94 +4055,108 @@ function clearInput() { form.planeid.value = ""; form.registration.value = ""; form.note.value = ""; - if(form.trips) form.trips.selectedIndex = 0; + if (form.trips) form.trips.selectedIndex = 0; } else { var form = document.forms["multiinputform"]; - for(i = 0; i < multiinput_ids.length; i++) { + for (i = 0; i < multiinput_ids.length; i++) { $(multiinput_ids[i]).value = 0; } form.src_date1.value = todayString(); form.src_ap1.focus(); - form.src_ap1.style.color = '#000000'; + form.src_ap1.style.color = "#000000"; } unmarkAirports(); setCommitAllowed(false); } function showHelp() { - if(getCurrentPane() == "help") return; + if (getCurrentPane() == "help") return; openPane("help"); } function closePopup(unselect) { // close any previous popups - if(currentPopup && currentPopup != this.popup) { + if (currentPopup && currentPopup != this.popup) { currentPopup.hide(); currentPopup = null; } - if(unselect) { + if (unselect) { selectControl.unselectAll(); } } function closeNews() { - $("news").style.display = 'none'; + $("news").style.display = "none"; } function showLoadingAnimation(show) { - $("ajaxstatus").style.display = show ? 'inline' : 'none'; + $("ajaxstatus").style.display = show ? "inline" : "none"; } // user has selected a new field in the extra filter function setExtraFilter() { - var key = document.forms['filterform'].Extra.value; + var key = document.forms["filterform"].Extra.value; var span = ""; - switch(key) { - case "": // none (More...) - $('filter_extra_span').innerHTML = ""; - refresh(true); - return; + switch (key) { + case "": // none (More...) + $("filter_extra_span").innerHTML = ""; + refresh(true); + return; - case "class": - span = createSelectFromArray('filter_extra_value', classes, "refresh(true)"); - break; + case "class": + span = createSelectFromArray( + "filter_extra_value", + classes, + "refresh(true)" + ); + break; - case "distgt": - case "distlt": - span = " mi"; - break; + case "distgt": + case "distlt": + span = + " mi"; + break; - case "mode": - span = createSelectFromArray('filter_extra_value', modenames, "refresh(true)"); - break; + case "mode": + span = createSelectFromArray( + "filter_extra_value", + modenames, + "refresh(true)" + ); + break; - case "reason": - span = createSelectFromArray('filter_extra_value', reasons, "refresh(true)"); - break; + case "reason": + span = createSelectFromArray( + "filter_extra_value", + reasons, + "refresh(true)" + ); + break; - case "reg": - case "note": - span = ""; - break; + case "reg": + case "note": + span = + ""; + break; } - $('filter_extra_span').innerHTML = span; + $("filter_extra_span").innerHTML = span; } // refresh_all: false = only flights, true = reload everything function clearFilter(refresh_all) { - var form = document.forms['filterform']; + var form = document.forms["filterform"]; // Do not allow trip filter to be cleared if it's set in URL - if(form.Trips && parseUrl()[0] == "trip") { + if (form.Trips && parseUrl()[0] == "trip") { form.Trips.selectedIndex = 0; } form.Years.selectedIndex = 0; form.Extra.selectedIndex = 0; - $('filter_extra_span').innerHTML = ""; + $("filter_extra_span").innerHTML = ""; selectAirline(0); - if(refresh_all && lasturl == URL_ROUTES) { + if (refresh_all && lasturl == URL_ROUTES) { var extent = airportLayer.getDataExtent(); - if(extent) map.zoomToExtent(extent); + if (extent) map.zoomToExtent(extent); lasturl = URL_MAP; } refresh(refresh_all); @@ -3351,10 +4168,10 @@ function clearFilter(refresh_all) { // lasturl: either URL_MAP or URL_ROUTES (set in updateMap()) function refresh(init) { closePopup(); - if(typeof lasturl == "undefined") { + if (typeof lasturl == "undefined") { lasturl = URL_MAP; } - if(lasturl == URL_MAP) { + if (lasturl == URL_MAP) { apid = 0; } xmlhttpPost(lasturl, apid, init); @@ -3364,12 +4181,12 @@ function refresh(init) { * TODO: How to make the second ad refresh? */ function refreshAd() { - var d=$('ad'); - if(d){ - var s=d.getElementsByTagName('iframe'); - if(s && s.length){ - var src = (s[0].src.split(/&xtime=/))[0]; - s[0].src = src + '&xtime='+new Date().getTime(); + var d = $("ad"); + if (d) { + var s = d.getElementsByTagName("iframe"); + if (s && s.length) { + var src = s[0].src.split(/&xtime=/)[0]; + s[0].src = src + "&xtime=" + new Date().getTime(); } } return true; @@ -3378,5 +4195,3 @@ function refreshAd() { function of_debug(str) { $("maptitle").innerHTML = $("maptitle").innerHTML + "
" + str; } - - diff --git a/test/client/README b/test/client/README index f8877495..678d2f27 100644 --- a/test/client/README +++ b/test/client/README @@ -2,13 +2,12 @@ This test suite validates client-side (browser) behavior. Requirements: -* Selenium Server (2.0+ required for Firefox 4) +- Selenium Server (2.0+ required for Firefox 4) Install into directory '/openflights/test/selenium' -* A functional OpenFlights server and its test suite +- A functional OpenFlights server and its test suite Set up /openflights/test/server first (see its README) Testing: Run ./run-suite.sh and hope for the best! Test bootstrap logs into log/bootstrap.log, Selenium logs go into log/selenium.log. - diff --git a/test/server/README.md b/test/server/README.md index d1f3fb94..c3a48de9 100644 --- a/test/server/README.md +++ b/test/server/README.md @@ -6,8 +6,7 @@ This test suite validates PHP calls and MySQL database content. 1. `php composer.phar install` 2. Configure `config.php` 3. Run `php settings.php` to populate test user -4. Then run eg. `php login.php` to test login cases, *or* +4. Then run eg. `php login.php` to test login cases, _or_ 5. Load `/test/server/test_all.php` in a browser to test all. NOTE: Many cases are dependent on each other. Generally, run settings.php first, all cases afterward, and cleanup.php last. - diff --git a/test/unit/README b/test/unit/README index 41eeb77d..c65f2ad0 100644 --- a/test/unit/README +++ b/test/unit/README @@ -3,4 +3,3 @@ JavaScript unit tests implemented with JsTestDriver. - Start server with ./start_server.sh - Capture a browser as instructed - Run ./run_tests.sh - diff --git a/test/unit/greatcircle.js b/test/unit/greatcircle.js index 4af27bd6..24f63677 100644 --- a/test/unit/greatcircle.js +++ b/test/unit/greatcircle.js @@ -1,6 +1,6 @@ parseTimeStringTest = TestCase("parseTimeStringTest"); -parseTimeStringTest.prototype.testParseTimeString = function() { +parseTimeStringTest.prototype.testParseTimeString = function () { assertEquals(6.5, parseTimeString("06:30")); assertEquals(6.5, parseTimeString("6:30")); assertEquals(6.5, parseTimeString("0630")); From d02eb60da17b0a988406de8b13852682d6504cc6 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:46:15 +0000 Subject: [PATCH 10/12] Enable NPM related CI --- .github/workflows/npm.yaml | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/.github/workflows/npm.yaml b/.github/workflows/npm.yaml index bf0f0012..c90cd92d 100644 --- a/.github/workflows/npm.yaml +++ b/.github/workflows/npm.yaml @@ -1,8 +1,7 @@ name: NPM Actions -#on: -# pull_request: -# branches: [master] +on: + pull_request: # push: jobs: @@ -13,13 +12,12 @@ jobs: - name: Checkout uses: actions/checkout@v3 with: - # Make sure the actual branch is checked out when running on pull requests - ref: ${{ github.head_ref }} - # This is important to fetch the changes to the previous commit - fetch-depth: 0 + ref: ${{ github.event.pull_request.head.ref }} + repository: ${{ github.event.pull_request.head.repo.full_name }} - name: Prettify code uses: creyD/prettier_action@v4.3 with: dry: True only_changed: True + prettier_version: 2.8.8 From 79f751a37605f9bbbcd5622cb05f6b0eec7935ee Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 13:49:34 +0000 Subject: [PATCH 11/12] test: Move README files to MD --- test/client/{README => README.md} | 4 ++-- test/unit/README | 5 ----- test/unit/README.md | 5 +++++ 3 files changed, 7 insertions(+), 7 deletions(-) rename test/client/{README => README.md} (51%) delete mode 100644 test/unit/README create mode 100644 test/unit/README.md diff --git a/test/client/README b/test/client/README.md similarity index 51% rename from test/client/README rename to test/client/README.md index 678d2f27..01f8b07c 100644 --- a/test/client/README +++ b/test/client/README.md @@ -6,8 +6,8 @@ Requirements: Install into directory '/openflights/test/selenium' - A functional OpenFlights server and its test suite - Set up /openflights/test/server first (see its README) + Set up /openflights/test/server first (see its [README](../server/README.md)) Testing: -Run ./run-suite.sh and hope for the best! Test bootstrap logs into log/bootstrap.log, Selenium logs go into log/selenium.log. +Run [`./run-suite.sh`](run-suite.sh) and hope for the best! Test bootstrap logs into log/bootstrap.log, Selenium logs go into log/selenium.log. diff --git a/test/unit/README b/test/unit/README deleted file mode 100644 index c65f2ad0..00000000 --- a/test/unit/README +++ /dev/null @@ -1,5 +0,0 @@ -JavaScript unit tests implemented with JsTestDriver. - -- Start server with ./start_server.sh -- Capture a browser as instructed -- Run ./run_tests.sh diff --git a/test/unit/README.md b/test/unit/README.md new file mode 100644 index 00000000..d2954acf --- /dev/null +++ b/test/unit/README.md @@ -0,0 +1,5 @@ +JavaScript unit tests implemented with JsTestDriver. + +- Start server with (`./start_server.sh`)[start_server.sh] +- Capture a browser as instructed +- Run (`./run_tests.sh`)[run_tests.sh] From 65a1a8970c0932dd2f850eb95a90c36a02886b58 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 13:56:14 +0000 Subject: [PATCH 12/12] alsearch.php: Fix double space in --- html/alsearch.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html/alsearch.php b/html/alsearch.php index e4456f2f..7d8819e7 100644 --- a/html/alsearch.php +++ b/html/alsearch.php @@ -10,7 +10,7 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> -<title>OpenFlights: <?php echo _("Airline search") ?> + OpenFlights: <?php echo _("Airline search") ?>
"; table = "
" + gt.gettext("Show...") + "
"; - table += createSelectFromArray('limit', toplimits, "updateTop10()", limit) + "
"; + table += + createSelectFromArray("limit", toplimits, "updateTop10()", limit) + "
"; table += gt.gettext("Sort by...") + "
"; - table += createSelectFromArray('mode', topmodes, "updateTop10()", mode) + "
"; + table += + createSelectFromArray("mode", topmodes, "updateTop10()", mode) + "
"; bigtable += table + "
"; + bigtable += + ""; table = ""; for (const route of topData.routes) { - table += "" + - ""; + table += + "" + + ""; } table += "
" + gt.gettext("Routes") + "
" + route.src_code + "↔" + - "" + route.dst_code + "" + route.count + "
" + + route.src_code + + "↔" + + "" + + route.dst_code + + "" + + route.count + + "
"; - bigtable += table + "
"; + bigtable += + table + ""; table = ""; for (const airport of topData.airports) { - desc = airport.name.substring(0,20) + " (" + airport.code + ")"; - table += ""; + desc = airport.name.substring(0, 20) + " (" + airport.code + ")"; + table += + ""; } table += "
" + gt.gettext("Airports") + "
" + desc + "" + airport.count + "
" + + desc + + "" + + airport.count + + "
"; - bigtable += table + "
"; + bigtable += + table + + ""; table = ""; for (const airline of topData.airlines) { - table += ""; + table += + ""; } table += "
" + gt.gettext("Airlines") + "
" + airline.name + "" + airline.count + "
" + + airline.name + + "" + + airline.count + + "
"; - bigtable += table + "
"; + bigtable += + table + ""; table = ""; for (const plane of topData.planes) { - table += ""; + table += + ""; } table += "
" + gt.gettext("Planes") + "
" + plane.name + "" + plane.count + "
" + + plane.name + + "" + + plane.count + + "
"; bigtable += table + "