From dce38c9bd2b6813ae6ab0dede47372c4f0b38a24 Mon Sep 17 00:00:00 2001 From: Sam Reed Date: Mon, 10 Jul 2023 12:35:30 +0000 Subject: [PATCH] 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/effects.js | 1616 ++++++---- js/greatcircle.js | 241 +- js/prototype.js | 6361 ++++++++++++++++++++------------------ js/settings.js | 223 +- js/trip.js | 66 +- js/tripit.js | 341 +- js/utilities.js | 925 +++--- openflights.css | 43 +- openflights.js | 4059 ++++++++++++++---------- sql/README | 22 +- test/client/README | 5 +- test/server/README.md | 5 +- test/unit/README | 1 - test/unit/greatcircle.js | 2 +- 21 files changed, 8613 insertions(+), 6440 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/effects.js b/js/effects.js index 860ddc09..09c47ded 100644 --- a/js/effects.js +++ b/js/effects.js @@ -11,150 +11,181 @@ // 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); +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(); + 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)); + 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.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.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.setContentZoom = function (element, percent) { element = $(element); - element.setStyle({fontSize: (percent/100) + 'em'}); - if (Prototype.Browser.WebKit) window.scrollBy(0,0); + 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.getInlineOpacity = function (element) { + return $(element).style.opacity || ""; }; -Element.forceRerendering = function(element) { +Element.forceRerendering = function (element) { try { element = $(element); - var n = document.createTextNode(' '); + var n = document.createTextNode(" "); element.appendChild(n); element.removeChild(n); - } catch(e) { } + } catch (e) {} }; /*--------------------------------------------------------------------------*/ var Effect = { _elementDoesNotExistError: { - name: 'ElementDoesNotExistError', - message: 'The specified DOM element does not exist, but is required for this effect to operate' + 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; + sinoidal: function (pos) { + return -Math.cos(pos * Math.PI) / 2 + 0.5; }, - reverse: function(pos) { - return 1-pos; + reverse: function (pos) { + return 1 - pos; }, - flicker: function(pos) { - var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4; + flicker: function (pos) { + var pos = -Math.cos(pos * Math.PI) / 4 + 0.75 + Math.random() / 4; return pos > 1 ? 1 : pos; }, - wobble: function(pos) { - return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5; + wobble: function (pos) { + return -Math.cos(pos * Math.PI * (9 * pos)) / 2 + 0.5; }, - pulse: function(pos, pulses) { - return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5; + pulse: function (pos, pulses) { + return -Math.cos(pos * ((pulses || 5) - 0.5) * 2 * Math.PI) / 2 + 0.5; }, - spring: function(pos) { - return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); + spring: function (pos) { + return 1 - Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6); }, - none: function(pos) { + none: function (pos) { return 0; }, - full: function(pos) { + 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' + 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'; + 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) { + $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); + new Element("span", { style: tagifyStyle }).update( + character == " " ? String.fromCharCode(160) : character + ), + child + ); }); Element.remove(child); } }); }, - multiple: function(element, effect) { + multiple: function (element, effect) { var elements; - if (((typeof element == 'object') || - Object.isFunction(element)) && - (element.length)) + if ( + (typeof element == "object" || Object.isFunction(element)) && + element.length + ) elements = element; - else - elements = $(element).childNodes; + else elements = $(element).childNodes; - var options = Object.extend({ - speed: 0.1, - delay: 0.0 - }, arguments[2] || { }); + 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 })); + $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'] + slide: ["SlideDown", "SlideUp"], + blind: ["BlindDown", "BlindUp"], + appear: ["Appear", "Fade"], }, - toggle: function(element, effect, options) { + 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 = (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; @@ -162,632 +193,846 @@ Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; /* ------------- core effects ------------- */ Effect.ScopedQueue = Class.create(Enumerable, { - initialize: function() { - this.effects = []; + initialize: function () { + this.effects = []; this.interval = null; }, - _each: function(iterator) { + _each: function (iterator) { this.effects._each(iterator); }, - add: function(effect) { + add: function (effect) { var timestamp = new Date().getTime(); - var position = Object.isString(effect.options.queue) ? - effect.options.queue : effect.options.queue.position; + var position = Object.isString(effect.options.queue) + ? effect.options.queue + : effect.options.queue.position; - switch(position) { - case 'front': + 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; + 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; + case "with-last": + timestamp = this.effects.pluck("startOn").max() || timestamp; break; - case 'end': + case "end": // start effect after last queued effect has finished - timestamp = this.effects.pluck('finishOn').max() || timestamp; + timestamp = this.effects.pluck("finishOn").max() || timestamp; break; } - effect.startOn += timestamp; + effect.startOn += timestamp; effect.finishOn += timestamp; - if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + 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); + if (!this.interval) this.interval = setInterval(this.loop.bind(this), 15); }, - remove: function(effect) { - this.effects = this.effects.reject(function(e) { return e==effect }); + 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() { + 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'); + this.event("beforeFinish"); if (this.finish) this.finish(); - this.event('afterFinish'); + this.event("afterFinish"); return; } - var pos = (timePos - this.startOn) / this.totalTime, - frame = (pos * this.totalFrames).round(); + var pos = (timePos - this.startOn) / this.totalTime, + frame = (pos * this.totalFrames).round(); if (frame > this.currentFrame) { this.render(pos); this.currentFrame = frame; } } }, - cancel: function() { + cancel: function () { if (!this.options.sync) - Effect.Queues.get(Object.isString(this.options.queue) ? - 'global' : this.options.queue.scope).remove(this); - this.state = 'finished'; + 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); + event: function (eventName) { + if (this.options[eventName + "Internal"]) + this.options[eventName + "Internal"](this); if (this.options[eventName]) this.options[eventName](this); }, - inspect: function() { + inspect: function () { var data = $H(); - for(property in this) - if (!Object.isFunction(this[property])) data.set(property, this[property]); - return '#'; - } + for (property in this) + if (!Object.isFunction(this[property])) + data.set(property, this[property]); + return ( + "#" + ); + }, }); Effect.Parallel = Class.create(Effect.Base, { - initialize: function(effects) { + initialize: function (effects) { this.effects = effects || []; this.start(arguments[1]); }, - update: function(position) { - this.effects.invoke('render', position); + update: function (position) { + this.effects.invoke("render", position); }, - finish: function(position) { - this.effects.each( function(effect) { + finish: function (position) { + this.effects.each(function (effect) { effect.render(1.0); effect.cancel(); - effect.event('beforeFinish'); + effect.event("beforeFinish"); if (effect.finish) effect.finish(position); - effect.event('afterFinish'); + effect.event("afterFinish"); }); - } + }, }); Effect.Tween = Class.create(Effect.Base, { - initialize: function(object, from, to) { + initialize: function (object, from, to) { object = Object.isString(object) ? $(object) : object; - var args = $A(arguments), method = args.last(), + 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 || { })); + 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) { + update: function (position) { this.method(position); - } + }, }); Effect.Event = Class.create(Effect.Base, { - initialize: function() { - this.start(Object.extend({ duration: 0 }, arguments[0] || { })); + initialize: function () { + this.start(Object.extend({ duration: 0 }, arguments[0] || {})); }, - update: Prototype.emptyFunction + update: Prototype.emptyFunction, }); Effect.Opacity = Class.create(Effect.Base, { - initialize: function(element) { + initialize: function (element) { this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); + 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] || { }); + 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) { + update: function (position) { this.element.setOpacity(position); - } + }, }); Effect.Move = Class.create(Effect.Base, { - initialize: function(element) { + initialize: function (element) { this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ - x: 0, - y: 0, - mode: 'relative' - }, arguments[1] || { }); + if (!this.element) throw Effect._elementDoesNotExistError; + var options = Object.extend( + { + x: 0, + y: 0, + mode: "relative", + }, + arguments[1] || {} + ); this.start(options); }, - setup: function() { + 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.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) { + update: function (position) { this.element.setStyle({ - left: (this.options.x * position + this.originalLeft).round() + 'px', - top: (this.options.y * position + this.originalTop).round() + 'px' + 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.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) { + 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] || { }); + 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() { + setup: function () { this.restoreAfterFinish = this.options.restoreAfterFinish || false; - this.elementPositioning = this.element.getStyle('position'); + 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.originalStyle = {}; + ["top", "left", "width", "height", "fontSize"].each( + function (k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this) + ); - this.originalTop = this.element.offsetTop; + 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)); + 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.factor = (this.options.scaleTo - this.options.scaleFrom) / 100; this.dims = null; - if (this.options.scaleMode=='box') + 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]; + this.dims = [ + this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth, + ]; }, - update: function(position) { - var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + 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); + this.element.setStyle({ + fontSize: this.fontSize * currentScale + this.fontSizeType, + }); + this.setDimensions( + this.dims[0] * currentScale, + this.dims[1] * currentScale + ); }, - finish: function(position) { + 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'; + 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'; + 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'; + 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) { + initialize: function (element) { this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); + if (!this.element) throw Effect._elementDoesNotExistError; + var options = Object.extend({ startcolor: "#ffff99" }, arguments[1] || {}); this.start(options); }, - setup: function() { + setup: function () { // Prevent executing on elements not in the layout flow - if (this.element.getStyle('display')=='none') { this.cancel(); return; } + if (this.element.getStyle("display") == "none") { + this.cancel(); + return; + } // Disable background image during the effect - this.oldStyle = { }; + this.oldStyle = {}; if (!this.options.keepBackgroundImage) { - this.oldStyle.backgroundImage = this.element.getStyle('background-image'); - this.element.setStyle({backgroundImage: 'none'}); + 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'); + this.options.endcolor = this.element + .getStyle("background-color") + .parseColor("#ffffff"); if (!this.options.restorecolor) - this.options.restorecolor = this.element.getStyle('background-color'); + 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)); + 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) + ), + }); }, - 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, + }) + ); }, - 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(); +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, + return new Effect.Tween( + null, scrollOffsets.top, elementOffsets[1], options, - function(p){ scrollTo(scrollOffsets.left, p.round()); } + function (p) { + scrollTo(scrollOffsets.left, p.round()); + } ); }; /* ------------- combination effects ------------- */ -Effect.Fade = function(element) { +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); + 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) { +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); + 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) { +Effect.Puff = function (element) { element = $(element); var oldStyle = { opacity: element.getInlineOpacity(), - position: element.getStyle('position'), - top: element.style.top, + position: element.getStyle("position"), + top: element.style.top, left: element.style.left, width: element.style.width, - height: element.style.height + 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); + [ + 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); + }, }, - afterFinishInternal: function(effect) { - effect.effects[0].element.hide().setStyle(oldStyle); } - }, arguments[1] || { }) - ); + arguments[1] || {} + ) + ); }; -Effect.BlindUp = function(element) { +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] || { }) + 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) { +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] || { })); + 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) { +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(); + 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 }); + }, + }); }, - afterFinishInternal: function(effect) { - effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); - } - }); - } - }, arguments[1] || { })); + }, + arguments[1] || {} + ) + ); }; -Effect.DropOut = function(element) { +Effect.DropOut = function (element) { element = $(element); var oldStyle = { - top: element.getStyle('top'), - left: element.getStyle('left'), - opacity: element.getInlineOpacity() }; + 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 }) ], + [ + 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) { + { + duration: 0.5, + beforeSetup: function (effect) { effect.effects[0].element.makePositioned(); }, - afterFinishInternal: function(effect) { + afterFinishInternal: function (effect) { effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); - } - }, arguments[1] || { })); + }, + }, + arguments[1] || {} + ) + ); }; -Effect.Shake = function(element) { +Effect.Shake = function (element) { element = $(element); - var options = Object.extend({ - distance: 20, - duration: 0.5 - }, arguments[1] || {}); + 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); - }}); }}); }}); }}); }}); }}); + 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) { +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 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] || { }) + 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) { +Effect.SlideUp = function (element) { element = $(element).cleanWhitespace(); - var oldInnerBottom = element.down().getStyle('bottom'); + 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] || { }) + 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) { +Effect.Squish = function (element) { return new Effect.Scale(element, window.opera ? 1 : 0, { restoreAfterFinish: true, - beforeSetup: function(effect) { + beforeSetup: function (effect) { effect.element.makeClipping(); }, - afterFinishInternal: function(effect) { + afterFinishInternal: function (effect) { effect.element.hide().undoClipping(); - } + }, }); }; -Effect.Grow = function(element) { +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 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() }; + opacity: element.getInlineOpacity(), + }; var dims = element.getDimensions(); var initialMoveX, initialMoveY; var moveX, moveY; switch (options.direction) { - case 'top-left': + case "top-left": initialMoveX = initialMoveY = moveX = moveY = 0; break; - case 'top-right': + case "top-right": initialMoveX = dims.width; initialMoveY = moveY = 0; moveX = -dims.width; break; - case 'bottom-left': + case "bottom-left": initialMoveX = moveX = 0; initialMoveY = dims.height; moveY = -dims.height; break; - case 'bottom-right': + case "bottom-right": initialMoveX = dims.width; initialMoveY = dims.height; moveX = -dims.width; moveY = -dims.height; break; - case 'center': + case "center": initialMoveX = dims.width / 2; initialMoveY = dims.height / 2; moveX = -dims.width / 2; @@ -799,143 +1044,225 @@ Effect.Grow = function(element) { x: initialMoveX, y: initialMoveY, duration: 0.01, - beforeSetup: function(effect) { + beforeSetup: function (effect) { effect.element.hide().makeClipping().makePositioned(); }, - afterFinishInternal: function(effect) { + 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.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) + 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) { +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 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() }; + opacity: element.getInlineOpacity(), + }; var dims = element.getDimensions(); var moveX, moveY; switch (options.direction) { - case 'top-left': + case "top-left": moveX = moveY = 0; break; - case 'top-right': + case "top-right": moveX = dims.width; moveY = 0; break; - case 'bottom-left': + case "bottom-left": moveX = 0; moveY = dims.height; break; - case 'bottom-right': + case "bottom-right": moveX = dims.width; moveY = dims.height; break; - case 'center': + 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) + [ + 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) { +Effect.Pulsate = function (element) { element = $(element); - var options = arguments[1] || { }, + 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); + reverser = function (pos) { + return ( + 1 - + transition( + -Math.cos(pos * (options.pulses || 5) * 2 * Math.PI) / 2 + 0.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})); + 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) { +Effect.Fold = function (element) { element = $(element); var oldStyle = { top: element.style.top, left: element.style.left, width: element.style.width, - height: element.style.height }; + 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] || { })); + 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) { + initialize: function (element) { this.element = $(element); - if (!this.element) throw(Effect._elementDoesNotExistError); - var options = Object.extend({ - style: { } - }, arguments[1] || { }); + 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(); + 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) { + this.style = this.style.reject(function (style) { return style.value == css[style.key]; }); - options.afterFinishInternal = function(effect) { + options.afterFinishInternal = function (effect) { effect.element.addClassName(effect.options.style); - effect.transforms.each(function(transform) { - effect.element.style[transform.style] = ''; + effect.transforms.each(function (transform) { + effect.element.style[transform.style] = ""; }); }; } @@ -943,141 +1270,175 @@ Effect.Morph = Class.create(Effect.Base, { this.start(options); }, - setup: function(){ - function parseColor(color){ - if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; + 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 ); + 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)) - ) - ); - }); + 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--) + 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); + 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] || { }; + 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)); + 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(){ + 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.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'); + "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(); +String.__parseStyleElement = document.createElement("div"); +String.prototype.parseStyle = function () { + var style, + styleRules = $H(); if (Prototype.Browser.WebKit) - style = new Element('div',{style:this}).style; + style = new Element("div", { style: this }).style; else { String.__parseStyleElement.innerHTML = '
'; style = String.__parseStyleElement.childNodes[0].style; } - Element.CSS_PROPERTIES.each(function(property){ + 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]); + 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) { + Element.getStyles = function (element) { var css = document.defaultView.getComputedStyle($(element), null); - return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { + return Element.CSS_PROPERTIES.inject({}, function (styles, property) { styles[property] = css[property]; return styles; }); }; } else { - Element.getStyles = function(element) { + Element.getStyles = function (element) { element = $(element); - var css = element.currentStyle, styles; - styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) { + var css = element.currentStyle, + styles; + styles = Element.CSS_PROPERTIES.inject({}, function (results, property) { results[property] = css[property]; return results; }); @@ -1087,37 +1448,46 @@ if (document.defaultView && document.defaultView.getComputedStyle) { } Effect.Methods = { - morph: function(element, style) { + morph: function (element, style) { element = $(element); - new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); + new Effect.Morph( + element, + Object.extend({ style: style }, arguments[2] || {}) + ); return element; }, - visualEffect: function(element, effect, options) { + visualEffect: function (element, effect, options) { element = $(element); - var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); + var s = effect.dasherize().camelize(), + klass = s.charAt(0).toUpperCase() + s.substring(1); new Effect[klass](element, options); return element; }, - highlight: function(element, options) { + 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( + "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]; } -); +$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 +Element.addMethods(Effect.Methods); 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/js/utilities.js b/js/utilities.js index 2ab6fa5c..1e92ec6c 100644 --- a/js/utilities.js +++ b/js/utilities.js @@ -10,22 +10,23 @@ var miniHintClass = "miniTextbox"; var miniHintActiveClass = "miniTextboxActive"; // define a custom method on the string class to trim leading and training spaces -String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; +String.prototype.trim = function () { + return this.replace(/^\s+|\s+$/g, ""); +}; function initHintTextboxes() { - var inputs = document.getElementsByTagName('input'); - for (i=0; i 0) { - if (t.tHead && t.tHead.rows.length > 0) { - var firstRow = t.tHead.rows[t.tHead.rows.length-1]; - thead = true; - } else { - var firstRow = t.rows[0]; - } - } - if (!firstRow) return; - - // We have a first row: assume it's the header, and make its contents clickable links - for (var i=0;i'+txt+' ↓'; - } - } - if (alternate_row_colors) { - alternate(t); - } + if (t.rows && t.rows.length > 0) { + if (t.tHead && t.tHead.rows.length > 0) { + var firstRow = t.tHead.rows[t.tHead.rows.length - 1]; + thead = true; + } else { + var firstRow = t.rows[0]; + } + } + if (!firstRow) return; + + // We have a first row: assume it's the header, and make its contents clickable links + for (var i = 0; i < firstRow.cells.length; i++) { + var cell = firstRow.cells[i]; + var txt = ts_getInnerText(cell); + if ( + cell.className != "unsortable" && + cell.className.indexOf("unsortable") == -1 + ) { + cell.innerHTML = + '' + + txt + + ' ↓'; + } + } + if (alternate_row_colors) { + alternate(t); + } } function ts_getInnerText(el) { - if (typeof el == "string") return el; - if (typeof el == "undefined") { return el }; - if (el.innerText) return el.innerText; //Not needed but it is faster - var str = ""; - - var cs = el.childNodes; - var l = cs.length; - for (var i = 0; i < l; i++) { - switch (cs[i].nodeType) { - case 1: //ELEMENT_NODE - str += ts_getInnerText(cs[i]); - break; - case 3: //TEXT_NODE - str += cs[i].nodeValue; - break; - } - } - return str; + if (typeof el == "string") return el; + if (typeof el == "undefined") { + return el; + } + if (el.innerText) return el.innerText; //Not needed but it is faster + var str = ""; + + var cs = el.childNodes; + var l = cs.length; + for (var i = 0; i < l; i++) { + switch (cs[i].nodeType) { + case 1: //ELEMENT_NODE + str += ts_getInnerText(cs[i]); + break; + case 3: //TEXT_NODE + str += cs[i].nodeValue; + break; + } + } + return str; } function ts_resortTable(lnk, clid) { - var span; - for (var ci=0;ci'; - newRows.reverse(); - span.setAttribute('sortdir','up'); - } else { - ARROW = ' ↑'; - span.setAttribute('sortdir','down'); - } - // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones - // don't do sortbottom rows - for (i=0; i'; - } - } - } - span.innerHTML = ARROW; - alternate(t); + var span; + for (var ci = 0; ci < lnk.childNodes.length; ci++) { + if ( + lnk.childNodes[ci].tagName && + lnk.childNodes[ci].tagName.toLowerCase() == "span" + ) + span = lnk.childNodes[ci]; + } + var spantext = ts_getInnerText(span); + var td = lnk.parentNode; + var column = clid || td.cellIndex; + var t = getParent(td, "TABLE"); + // Work out a type for the column + if (t.rows.length <= 1) return; + var itm = ""; + var i = 1; + while (itm == "" && i < t.tBodies[0].rows.length) { + var itm = ts_getInnerText(t.tBodies[0].rows[i].cells[column]); + itm = trim(itm); + if (itm.substr(0, 4) == ""; + table += + "" + + gt.gettext("Class by distance") + + "" + + gt.gettext("Mode") + + ""; table += ""; - table += "
"; - table += "
"; - table += ""; + table += '
'; + table += '
'; + table += ""; table += ""; table += ""; 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/sql/README b/sql/README index 7c2d50f6..0339e882 100644 --- a/sql/README +++ b/sql/README @@ -1,23 +1,23 @@ -*** Tools for users +\*\*\* Tools for users create.sql - Create empty OpenFlights database schema +Create empty OpenFlights database schema export.sql - Export airlines.dat, airports.dat and routes.dat from OpenFlights database +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 +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 +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 +Import DAFIF and OurAirports, useful but not needed by site -*** Site internal scripts +\*\*\* Site internal scripts elite-levels.sql - Generate table of elite users +Generate table of elite users merge-airports.sql - Called by data/merge-airports.sh for manual merging for duplicate ICAO codes +Called by data/merge-airports.sh for manual merging for duplicate ICAO codes top10.sql - Generate nightly Top 10 lists (>data/top10.dat) +Generate nightly Top 10 lists (>data/top10.dat) update-demo.sql - Update flights for "demo" user +Update flights for "demo" user 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 449e95fb..8f41499c 100644 --- a/test/server/README.md +++ b/test/server/README.md @@ -1,13 +1,12 @@ 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` 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"));
"; 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 + "