From 46bc6e545a17e77202aaf01ec0cd8d5a46567525 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 25 Aug 2015 08:08:24 -0300 Subject: Move main pfSense content to src/ --- src/usr/local/www/javascript/autosuggest.js | 337 ++ src/usr/local/www/javascript/base64.js | 142 + .../www/javascript/carp_status/carp_status.js | 5 + .../local/www/javascript/chosen/chosen-sprite.png | Bin 0 -> 1866 bytes src/usr/local/www/javascript/chosen/chosen.css | 317 + .../local/www/javascript/chosen/chosen.jquery.js | 755 +++ .../www/javascript/chosen/chosen.jquery.min.js | 9 + .../local/www/javascript/chosen/chosen.proto.js | 765 +++ .../www/javascript/chosen/chosen.proto.min.js | 9 + .../javascript/chosen/coffee/chosen.jquery.coffee | 633 ++ .../javascript/chosen/coffee/chosen.proto.coffee | 629 ++ .../www/javascript/datepicker/css/datepicker.css | 178 + .../local/www/javascript/datepicker/js/blank.html | 6 + .../www/javascript/datepicker/js/datepicker.js | 1111 ++++ .../www/javascript/datepicker/media/bg_header.jpg | Bin 0 -> 1792 bytes .../www/javascript/datepicker/media/bullet1.gif | Bin 0 -> 55 bytes .../www/javascript/datepicker/media/bullet2.gif | Bin 0 -> 262 bytes .../local/www/javascript/datepicker/media/cal.gif | Bin 0 -> 127 bytes .../datepicker/media/gradient-e5e5e5-ffffff.gif | Bin 0 -> 526 bytes src/usr/local/www/javascript/domTT/LICENSE | 202 + src/usr/local/www/javascript/domTT/behaviour.js | 254 + src/usr/local/www/javascript/domTT/domLib.js | 706 +++ src/usr/local/www/javascript/domTT/domTT.js | 1132 ++++ src/usr/local/www/javascript/domTT/fadomatic.js | 180 + src/usr/local/www/javascript/filter_log.js | 168 + src/usr/local/www/javascript/firebug-lite.js | 1000 ++++ .../javascript/firewall_nat_edit/autosuggest.js | 337 ++ .../javascript/firewall_nat_edit/disablekeys.js | 6 + .../firewall_nat_edit/firewall_nat_edit.js | 203 + .../javascript/firewall_nat_edit/suggestions.js | 33 + .../javascript/firewall_rules_edit/autosuggest.js | 337 ++ .../javascript/firewall_rules_edit/disablekeys.js | 6 + .../firewall_rules_edit/firewall_rules_edit.js | 237 + .../javascript/firewall_rules_edit/suggestions.js | 33 + .../javascript/firewall_shaper_edit/autosuggest.js | 337 ++ .../javascript/firewall_shaper_edit/disablekeys.js | 6 + .../firewall_shaper_edit/firewall_shaper_edit.js | 37 + .../javascript/firewall_shaper_edit/suggestions.js | 33 + src/usr/local/www/javascript/global.js | 43 + src/usr/local/www/javascript/index/ajax.js | 196 + .../javascript/interfaces_ppps_edit/ppps_edit.js | 253 + src/usr/local/www/javascript/jquery-1.11.1.min.js | 4 + .../www/javascript/jquery-migrate-1.2.1.min.js | 2 + .../css/jquery-ui-timepicker-addon.css | 7 + .../js/jquery-ui-timepicker-addon.js | 1326 +++++ src/usr/local/www/javascript/jquery.ipv4v6ify.js | 140 + .../ui-bg_diagonals-thick_18_b81900_40x40.png | Bin 0 -> 260 bytes .../ui-bg_diagonals-thick_20_666666_40x40.png | Bin 0 -> 251 bytes .../jquery/images/ui-bg_flat_0_aaaaaa_40x100.png | Bin 0 -> 180 bytes .../jquery/images/ui-bg_flat_0_eeeeee_40x100.png | Bin 0 -> 180 bytes .../jquery/images/ui-bg_flat_10_000000_40x100.png | Bin 0 -> 178 bytes .../jquery/images/ui-bg_flat_55_c0402a_40x100.png | Bin 0 -> 213 bytes .../jquery/images/ui-bg_flat_55_eeeeee_40x100.png | Bin 0 -> 180 bytes .../jquery/images/ui-bg_glass_100_f6f6f6_1x400.png | Bin 0 -> 104 bytes .../jquery/images/ui-bg_glass_100_f8f8f8_1x400.png | Bin 0 -> 105 bytes .../jquery/images/ui-bg_glass_100_fdf5ce_1x400.png | Bin 0 -> 125 bytes .../jquery/images/ui-bg_glass_35_dddddd_1x400.png | Bin 0 -> 109 bytes .../jquery/images/ui-bg_glass_60_eeeeee_1x400.png | Bin 0 -> 110 bytes .../jquery/images/ui-bg_glass_65_ffffff_1x400.png | Bin 0 -> 105 bytes .../images/ui-bg_gloss-wave_35_f6a828_500x100.png | Bin 0 -> 3762 bytes .../ui-bg_highlight-soft_100_eeeeee_1x100.png | Bin 0 -> 90 bytes .../ui-bg_highlight-soft_75_ffe45c_1x100.png | Bin 0 -> 129 bytes .../images/ui-bg_inset-hard_75_999999_1x100.png | Bin 0 -> 114 bytes .../images/ui-bg_inset-soft_50_c9c9c9_1x100.png | Bin 0 -> 96 bytes .../jquery/images/ui-icons_222222_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_228ef1_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_3383bb_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_454545_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_70b2e1_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_999999_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_ef8c08_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_fbc856_256x240.png | Bin 0 -> 5355 bytes .../jquery/images/ui-icons_ffd27a_256x240.png | Bin 0 -> 4369 bytes .../jquery/images/ui-icons_ffffff_256x240.png | Bin 0 -> 4369 bytes .../www/javascript/jquery/jquery-ui-1.11.1.min.js | 13 + .../www/javascript/load_balancer_pool_edit/pool.js | 191 + .../load_balancer_relay_protocol_edit.js | 56 + src/usr/local/www/javascript/niftyjsCode.js | 174 + .../javascript/numericupdown/css/numericupdown.css | 40 + .../www/javascript/numericupdown/images/down.gif | Bin 0 -> 60 bytes .../www/javascript/numericupdown/images/up.gif | Bin 0 -> 60 bytes .../javascript/numericupdown/js/numericupdown.js | 287 + src/usr/local/www/javascript/pi.js | 682 +++ src/usr/local/www/javascript/row_helper.js | 97 + src/usr/local/www/javascript/row_helper_dynamic.js | 98 + src/usr/local/www/javascript/row_toggle.js | 66 + .../local/www/javascript/scriptaculous/builder.js | 136 + .../local/www/javascript/scriptaculous/controls.js | 965 ++++ .../local/www/javascript/scriptaculous/dragdrop.js | 974 ++++ .../local/www/javascript/scriptaculous/effects.js | 1123 ++++ .../www/javascript/scriptaculous/prototype.js | 6079 ++++++++++++++++++++ .../www/javascript/scriptaculous/scriptaculous.js | 68 + .../local/www/javascript/scriptaculous/slider.js | 275 + .../local/www/javascript/scriptaculous/sound.js | 59 + .../local/www/javascript/scriptaculous/unittest.js | 568 ++ src/usr/local/www/javascript/sorttable.js | 584 ++ src/usr/local/www/javascript/suggestions.js | 33 + src/usr/local/www/javascript/ticker.js | 73 + src/usr/local/www/javascript/wizard/autosuggest.js | 337 ++ src/usr/local/www/javascript/wizard/disablekeys.js | 6 + src/usr/local/www/javascript/wizard/suggestions.js | 33 + 101 files changed, 25131 insertions(+) create mode 100644 src/usr/local/www/javascript/autosuggest.js create mode 100644 src/usr/local/www/javascript/base64.js create mode 100644 src/usr/local/www/javascript/carp_status/carp_status.js create mode 100644 src/usr/local/www/javascript/chosen/chosen-sprite.png create mode 100644 src/usr/local/www/javascript/chosen/chosen.css create mode 100644 src/usr/local/www/javascript/chosen/chosen.jquery.js create mode 100644 src/usr/local/www/javascript/chosen/chosen.jquery.min.js create mode 100644 src/usr/local/www/javascript/chosen/chosen.proto.js create mode 100644 src/usr/local/www/javascript/chosen/chosen.proto.min.js create mode 100644 src/usr/local/www/javascript/chosen/coffee/chosen.jquery.coffee create mode 100644 src/usr/local/www/javascript/chosen/coffee/chosen.proto.coffee create mode 100644 src/usr/local/www/javascript/datepicker/css/datepicker.css create mode 100644 src/usr/local/www/javascript/datepicker/js/blank.html create mode 100644 src/usr/local/www/javascript/datepicker/js/datepicker.js create mode 100755 src/usr/local/www/javascript/datepicker/media/bg_header.jpg create mode 100755 src/usr/local/www/javascript/datepicker/media/bullet1.gif create mode 100755 src/usr/local/www/javascript/datepicker/media/bullet2.gif create mode 100755 src/usr/local/www/javascript/datepicker/media/cal.gif create mode 100755 src/usr/local/www/javascript/datepicker/media/gradient-e5e5e5-ffffff.gif create mode 100644 src/usr/local/www/javascript/domTT/LICENSE create mode 100644 src/usr/local/www/javascript/domTT/behaviour.js create mode 100644 src/usr/local/www/javascript/domTT/domLib.js create mode 100644 src/usr/local/www/javascript/domTT/domTT.js create mode 100644 src/usr/local/www/javascript/domTT/fadomatic.js create mode 100644 src/usr/local/www/javascript/filter_log.js create mode 100644 src/usr/local/www/javascript/firebug-lite.js create mode 100644 src/usr/local/www/javascript/firewall_nat_edit/autosuggest.js create mode 100644 src/usr/local/www/javascript/firewall_nat_edit/disablekeys.js create mode 100644 src/usr/local/www/javascript/firewall_nat_edit/firewall_nat_edit.js create mode 100644 src/usr/local/www/javascript/firewall_nat_edit/suggestions.js create mode 100644 src/usr/local/www/javascript/firewall_rules_edit/autosuggest.js create mode 100644 src/usr/local/www/javascript/firewall_rules_edit/disablekeys.js create mode 100644 src/usr/local/www/javascript/firewall_rules_edit/firewall_rules_edit.js create mode 100644 src/usr/local/www/javascript/firewall_rules_edit/suggestions.js create mode 100644 src/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js create mode 100644 src/usr/local/www/javascript/firewall_shaper_edit/disablekeys.js create mode 100644 src/usr/local/www/javascript/firewall_shaper_edit/firewall_shaper_edit.js create mode 100644 src/usr/local/www/javascript/firewall_shaper_edit/suggestions.js create mode 100644 src/usr/local/www/javascript/global.js create mode 100644 src/usr/local/www/javascript/index/ajax.js create mode 100644 src/usr/local/www/javascript/interfaces_ppps_edit/ppps_edit.js create mode 100644 src/usr/local/www/javascript/jquery-1.11.1.min.js create mode 100644 src/usr/local/www/javascript/jquery-migrate-1.2.1.min.js create mode 100644 src/usr/local/www/javascript/jquery-ui-timepicker-addon/css/jquery-ui-timepicker-addon.css create mode 100644 src/usr/local/www/javascript/jquery-ui-timepicker-addon/js/jquery-ui-timepicker-addon.js create mode 100755 src/usr/local/www/javascript/jquery.ipv4v6ify.js create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_diagonals-thick_18_b81900_40x40.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_diagonals-thick_20_666666_40x40.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_flat_10_000000_40x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_glass_100_f6f6f6_1x400.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_glass_100_fdf5ce_1x400.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_glass_65_ffffff_1x400.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_gloss-wave_35_f6a828_500x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_highlight-soft_100_eeeeee_1x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_highlight-soft_75_ffe45c_1x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_222222_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_228ef1_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_3383bb_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_454545_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_70b2e1_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_999999_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_ef8c08_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_fbc856_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_ffd27a_256x240.png create mode 100755 src/usr/local/www/javascript/jquery/images/ui-icons_ffffff_256x240.png create mode 100644 src/usr/local/www/javascript/jquery/jquery-ui-1.11.1.min.js create mode 100644 src/usr/local/www/javascript/load_balancer_pool_edit/pool.js create mode 100644 src/usr/local/www/javascript/load_balancer_relay_protocol_edit/load_balancer_relay_protocol_edit.js create mode 100644 src/usr/local/www/javascript/niftyjsCode.js create mode 100644 src/usr/local/www/javascript/numericupdown/css/numericupdown.css create mode 100755 src/usr/local/www/javascript/numericupdown/images/down.gif create mode 100755 src/usr/local/www/javascript/numericupdown/images/up.gif create mode 100644 src/usr/local/www/javascript/numericupdown/js/numericupdown.js create mode 100644 src/usr/local/www/javascript/pi.js create mode 100644 src/usr/local/www/javascript/row_helper.js create mode 100644 src/usr/local/www/javascript/row_helper_dynamic.js create mode 100644 src/usr/local/www/javascript/row_toggle.js create mode 100644 src/usr/local/www/javascript/scriptaculous/builder.js create mode 100644 src/usr/local/www/javascript/scriptaculous/controls.js create mode 100644 src/usr/local/www/javascript/scriptaculous/dragdrop.js create mode 100644 src/usr/local/www/javascript/scriptaculous/effects.js create mode 100644 src/usr/local/www/javascript/scriptaculous/prototype.js create mode 100644 src/usr/local/www/javascript/scriptaculous/scriptaculous.js create mode 100644 src/usr/local/www/javascript/scriptaculous/slider.js create mode 100644 src/usr/local/www/javascript/scriptaculous/sound.js create mode 100644 src/usr/local/www/javascript/scriptaculous/unittest.js create mode 100644 src/usr/local/www/javascript/sorttable.js create mode 100644 src/usr/local/www/javascript/suggestions.js create mode 100644 src/usr/local/www/javascript/ticker.js create mode 100644 src/usr/local/www/javascript/wizard/autosuggest.js create mode 100644 src/usr/local/www/javascript/wizard/disablekeys.js create mode 100644 src/usr/local/www/javascript/wizard/suggestions.js (limited to 'src/usr/local/www/javascript') diff --git a/src/usr/local/www/javascript/autosuggest.js b/src/usr/local/www/javascript/autosuggest.js new file mode 100644 index 0000000..d9b5ac0 --- /dev/null +++ b/src/usr/local/www/javascript/autosuggest.js @@ -0,0 +1,337 @@ + +/** + * An autosuggest textbox control. + * @class + * @scope public + */ +function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, + oProvider /*:SuggestionProvider*/) { + + /** + * The currently selected suggestions. + * @scope private + */ + this.cur /*:int*/ = -1; + + /** + * The dropdown list layer. + * @scope private + */ + this.layer = null; + + /** + * Suggestion provider for the autosuggest feature. + * @scope private. + */ + this.provider /*:SuggestionProvider*/ = oProvider; + + /** + * The textbox to capture. + * @scope private + */ + this.textbox /*:HTMLInputElement*/ = oTextbox; + + //initialize the control + this.init(); + +} + +/** + * Autosuggests one or more suggestions for what the user has typed. + * If no suggestions are passed in, then no autosuggest occurs. + * @scope private + * @param aSuggestions An array of suggestion strings. + * @param bTypeAhead If the control should provide a type ahead suggestion. + */ +AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/, + bTypeAhead /*:boolean*/) { + + //make sure there's at least one suggestion + if (aSuggestions.length > 0) { + if (bTypeAhead) { + this.typeAhead(aSuggestions[0]); + } + + this.showSuggestions(aSuggestions); + } else { + this.hideSuggestions(); + } +}; + +/** + * Creates the dropdown layer to display multiple suggestions. + * @scope private + */ +AutoSuggestControl.prototype.createDropDown = function () { + + var oThis = this; + + //create the layer and assign styles + this.layer = document.createElement("div"); + this.layer.className = "suggestions"; + this.layer.style.visibility = "hidden"; + this.layer.style.width = this.textbox.offsetWidth; + + //when the user clicks on the a suggestion, get the text (innerHTML) + //and place it into a textbox + this.layer.onmousedown = + this.layer.onmouseup = + this.layer.onmouseover = function (oEvent) { + oEvent = oEvent || window.event; + oTarget = oEvent.target || oEvent.srcElement; + + if (oEvent.type == "mousedown") { + oThis.textbox.value = oTarget.firstChild.nodeValue; + oThis.hideSuggestions(); + } else if (oEvent.type == "mouseover") { + oThis.highlightSuggestion(oTarget); + } else { + oThis.textbox.focus(); + } + }; + + + document.body.appendChild(this.layer); +}; + +/** + * Gets the left coordinate of the textbox. + * @scope private + * @return The left coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getLeft = function () /*:int*/ { + + var oNode = this.textbox; + var iLeft = 0; + + while(oNode.tagName != "BODY") { + iLeft += oNode.offsetLeft; + oNode = oNode.offsetParent; + } + + return iLeft; +}; + +/** + * Gets the top coordinate of the textbox. + * @scope private + * @return The top coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getTop = function () /*:int*/ { + + var oNode = this.textbox; + var iTop = 0; + + while(oNode.tagName != "BODY") { + iTop += oNode.offsetTop; + oNode = oNode.offsetParent; + } + + return iTop; +}; + +/** + * Handles three keydown events. + * @scope private + * @param oEvent The event object for the keydown event. + */ +AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) { + + switch(oEvent.keyCode) { + case 38: //up arrow + this.previousSuggestion(); + break; + case 40: //down arrow + this.nextSuggestion(); + break; + case 13: //enter + this.hideSuggestions(); + break; + } + +}; + +/** + * Handles keyup events. + * @scope private + * @param oEvent The event object for the keyup event. + */ +AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) { + + var iKeyCode = oEvent.keyCode; + + //for backspace (8) and delete (46), shows suggestions without typeahead + if (iKeyCode == 8 || iKeyCode == 46) { + this.provider.requestSuggestions(this, false); + + //make sure not to interfere with non-character keys + } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) { + //ignore + } else { + //request suggestions from the suggestion provider with typeahead + this.provider.requestSuggestions(this, true); + } +}; + +/** + * Hides the suggestion dropdown. + * @scope private + */ +AutoSuggestControl.prototype.hideSuggestions = function () { + this.layer.style.visibility = "hidden"; +}; + +/** + * Highlights the given node in the suggestions dropdown. + * @scope private + * @param oSuggestionNode The node representing a suggestion in the dropdown. + */ +AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) { + + for (var i=0; i < this.layer.childNodes.length; i++) { + var oNode = this.layer.childNodes[i]; + if (oNode == oSuggestionNode) { + oNode.className = "current"; + } else if (oNode.className == "current") { + oNode.className = ""; + } + } +}; + +/** + * Initializes the textbox with event handlers for + * auto suggest functionality. + * @scope private + */ +AutoSuggestControl.prototype.init = function () { + + //save a reference to this object + var oThis = this; + + //assign the onkeyup event handler + this.textbox.onkeyup = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyUp() method with the event object + oThis.handleKeyUp(oEvent); + }; + + //assign onkeydown event handler + this.textbox.onkeydown = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyDown() method with the event object + oThis.handleKeyDown(oEvent); + }; + + //assign onblur event handler (hides suggestions) + this.textbox.onblur = function () { + oThis.hideSuggestions(); + }; + + //create the suggestions dropdown + this.createDropDown(); +}; + +/** + * Highlights the next suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.nextSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) { + var oNode = cSuggestionNodes[++this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Highlights the previous suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.previousSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur > 0) { + var oNode = cSuggestionNodes[--this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Selects a range of text in the textbox. + * @scope public + * @param iStart The start index (base 0) of the selection. + * @param iLength The number of characters to select. + */ +AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) { + + //use text ranges for Internet Explorer + if (this.textbox.createTextRange) { + var oRange = this.textbox.createTextRange(); + oRange.moveStart("character", iStart); + oRange.moveEnd("character", iLength - this.textbox.value.length); + oRange.select(); + + //use setSelectionRange() for Mozilla + } else if (this.textbox.setSelectionRange) { + this.textbox.setSelectionRange(iStart, iLength); + } + + //set focus back to the textbox + this.textbox.focus(); +}; + +/** + * Builds the suggestion layer contents, moves it into position, + * and displays the layer. + * @scope private + * @param aSuggestions An array of suggestions for the control. + */ +AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) { + + var oDiv = null; + this.layer.innerHTML = ""; //clear contents of the layer + + for (var i=0; i < aSuggestions.length; i++) { + oDiv = document.createElement("div"); + oDiv.appendChild(document.createTextNode(aSuggestions[i])); + this.layer.appendChild(oDiv); + } + + this.layer.style.left = this.getLeft() + "px"; + this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; + this.layer.style.visibility = "visible"; + +}; + +/** + * Inserts a suggestion into the textbox, highlighting the + * suggested part of the text. + * @scope private + * @param sSuggestion The suggestion for the textbox. + */ +AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) { + + //check for support of typeahead functionality + if (this.textbox.createTextRange || this.textbox.setSelectionRange){ + var iLen = this.textbox.value.length; + this.textbox.value = sSuggestion; + this.selectRange(iLen, sSuggestion.length); + } +}; + diff --git a/src/usr/local/www/javascript/base64.js b/src/usr/local/www/javascript/base64.js new file mode 100644 index 0000000..48d5f33 --- /dev/null +++ b/src/usr/local/www/javascript/base64.js @@ -0,0 +1,142 @@ +/** + * + * Base64 encode / decode + * http://www.webtoolkit.info/ + * http://www.webtoolkit.info/licence + **/ + +var Base64 = { + + // private property + _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + + // public method for encoding + encode : function (input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = Base64._utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + output = output + + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + + } + + return output; + }, + + // public method for decoding + decode : function (input) { + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; + + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + + while (i < input.length) { + + enc1 = this._keyStr.indexOf(input.charAt(i++)); + enc2 = this._keyStr.indexOf(input.charAt(i++)); + enc3 = this._keyStr.indexOf(input.charAt(i++)); + enc4 = this._keyStr.indexOf(input.charAt(i++)); + + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + + output = output + String.fromCharCode(chr1); + + if (enc3 != 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 != 64) { + output = output + String.fromCharCode(chr3); + } + + } + + output = Base64._utf8_decode(output); + + return output; + + }, + + // private method for UTF-8 encoding + _utf8_encode : function (string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; + }, + + // private method for UTF-8 decoding + _utf8_decode : function (utftext) { + var string = ""; + var i = 0; + var c = c1 = c2 = 0; + + while ( i < utftext.length ) { + + c = utftext.charCodeAt(i); + + if (c < 128) { + string += String.fromCharCode(c); + i++; + } + else if((c > 191) && (c < 224)) { + c2 = utftext.charCodeAt(i+1); + string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } + else { + c2 = utftext.charCodeAt(i+1); + c3 = utftext.charCodeAt(i+2); + string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + + } + + return string; + } + +}; \ No newline at end of file diff --git a/src/usr/local/www/javascript/carp_status/carp_status.js b/src/usr/local/www/javascript/carp_status/carp_status.js new file mode 100644 index 0000000..c14201d --- /dev/null +++ b/src/usr/local/www/javascript/carp_status/carp_status.js @@ -0,0 +1,5 @@ + +window.onLoad = function () { + NiftyCheck(); + Rounded("div#mainlevel","all","#FFF","#eeeeee","smooth"); +}; diff --git a/src/usr/local/www/javascript/chosen/chosen-sprite.png b/src/usr/local/www/javascript/chosen/chosen-sprite.png new file mode 100644 index 0000000..6ec9bbf Binary files /dev/null and b/src/usr/local/www/javascript/chosen/chosen-sprite.png differ diff --git a/src/usr/local/www/javascript/chosen/chosen.css b/src/usr/local/www/javascript/chosen/chosen.css new file mode 100644 index 0000000..d2b1eb4 --- /dev/null +++ b/src/usr/local/www/javascript/chosen/chosen.css @@ -0,0 +1,317 @@ +div.chzn-container { + font-size: 13px; + position: relative; +} + +div.chzn-container input { + background: #fff; + background: -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); + background: -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); + background: -o-linear-gradient(bottom, white 85%, #eeeeee 99%); + border: 1px solid #aaa; + font-family: sans-serif; + font-size: 1em; + margin: 0px; + padding: 4px 5px; + outline: none; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + -khtml-border-radius: 3px; + border-radius: 3px; +} +div.chzn-container textarea:focus { + border-color: #058cf5; + -moz-box-shadow: 0px 0px 3px #aaa; + -webkit-box-shadow: 0px 0px 3px #aaa; + box-shadow: 0px 0px 3px #aaa; +} + + +div.chzn-container div.chzn-drop { + background: #FFF; + border: 1px solid #aaa; + border-width: 0 1px 1px; + left: 0; + position: absolute; + top: 29px; + -webkit-box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.15); + -moz-box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.15); + box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.15); + z-index: 20; +} +div.chzn-container-single div.chzn-drop { + -moz-border-radius: 0 0 4px 4px; + -webkit-border-radius: 0 0 4px 4px; + -o-border-radius: 0 0 4px 4px; + -ms-border-radius: 0 0 4px 4px; + -khtml-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} + + +/* SINGLE */ +div.chzn-container a.chzn-single { + background: #FFF; + background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white)); + background-image: -moz-linear-gradient(center bottom, #eeeeee 0%, white 50%); + background-image: -o-linear-gradient(bottom, #eeeeee 0%, white 50%); + border: 1px solid #aaa; + display: block; + overflow: hidden; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -o-border-radius: 4px; + -ms-border-radius: 4px; + -khtml-border-radius: 4px; + border-radius: 4px; + height: 25px; + color: #444; + line-height: 26px; + padding: 0px 0px 0px 8px; + position: relative; + text-decoration: none; + z-index: 19; + white-space: nowrap; +} +div.chzn-container a.chzn-single span { + display: block; + margin-right: 26px; + overflow: hidden; + text-overflow: ellipsis; +} +div.chzn-container a.chzn-single div { + -moz-border-radius-topright: 4px; + -webkit-border-top-right-radius: 4px; + -o-border-top-right-radius: 4px; + -ms-border-top-right-radius: 4px; + -khtml-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -moz-border-radius-bottomright: 4px; + -webkit-border-bottom-right-radius: 4px; + -o-border-bottom-right-radius: 4px; + -ms-border-bottom-right-radius: 4px; + -khtml-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + background: #ccc; + background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #ccc), color-stop(0.6, #eee)); + background-image: -moz-linear-gradient(center bottom, #ccc 0%, #eee 60%); + background-image: -o-linear-gradient(bottom, #ccc 0%, #eee 60%); + border-left: 1px solid #aaa; + display: block; + height: 100%; + position: absolute; + right: 0; + top: 0; + width: 18px; +} +div.chzn-container a.chzn-single div b { + background: url('chosen-sprite.png') no-repeat 0 1px; + display: block; + width: 100%; + height: 100%; +} +div.chzn-container div.chzn-search { + padding: 3px 4px; + margin: 0px; + white-space: nowrap; +} +div.chzn-container div.chzn-search input { + background: url('chosen-sprite.png') no-repeat 97% -35px, #ffffff; + background: url('chosen-sprite.png') no-repeat 97% -35px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); + background: url('chosen-sprite.png') no-repeat 97% -35px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); + background: url('chosen-sprite.png') no-repeat 97% -35px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); + -moz-border-radius: 0px; + -webkit-border-radius: 0px; + -o-border-radius: 0px; + -ms-border-radius: 0px; + -khtml-border-radius: 0px; + border-radius: 0px; + margin: 1px 0; + outline: 0; +} + + +/* Multi */ +div.chzn-container ul.chzn-choices { + background: #fff; + background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); + background-image: -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); + background-image: -o-linear-gradient(bottom, white 85%, #eeeeee 99%); + margin: 0; + cursor: text; + border: 1px solid #aaa; + overflow: hidden; + height: auto !important; + height: 1%; + padding: 0; + position: relative; +} +div.chzn-container ul.chzn-choices:focus { + border-color: #058cf5; + -moz-box-shadow: 0px 0px 5px #999; + -webkit-box-shadow: 0px 0px 5px #999; + box-shadow: 0px 0px 5px #999; +} +div.chzn-container ul.chzn-choices li { + float: left; + list-style-type: none; + margin: 0px; +} +div.chzn-container ul.chzn-choices li.search-field { + margin: 0px; + white-space: nowrap; + padding: 0px; +} +div.chzn-container ul.chzn-choices li.search-field input { + color: #666; + background: transparent !important; + border: 0px !important; + padding: 5px; + margin: 1px 0; + outline: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +div.chzn-container ul.chzn-choices li.search-field input.default { + color: #999; +} +div.chzn-container ul.chzn-choices li.search-choice { + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; + background: #e4e4e4; + background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #e4e4e4), color-stop(0.7, #eeeeee)); + background-image: -moz-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); + background-image: -o-linear-gradient(bottom, #e4e4e4 0%, #eeeeee 70%); + color: #333; + border: 1px solid #b4b4b4; + line-height: 13px; + padding: 3px 19px 3px 6px; + position: relative; + margin: 3px 0px 3px 5px; +} +div.chzn-container ul.chzn-choices li.search-choice span { + cursor: default; +} +div.chzn-container ul.chzn-choices li.search-choice.search-choice-focus { + background: #d4d4d4; +} +div.chzn-container ul.chzn-choices li.search-choice a.search-choice-close { + position: absolute; + right: 5px; + top: 6px; + display: block; + width: 8px; + height: 9px; + font-size: 1px; + background: url(chosen-sprite.png) right top no-repeat; +} +div.chzn-container ul.chzn-choices li.search-choice a.search-choice-close:hover { + background-position: right -9px; +} +div.chzn-container ul.chzn-choices li.search-choice.search-choice-focus a.search-choice-close { + background-position: right -9px; +} + + +/* Results */ +div.chzn-container ul.chzn-results { + margin: 0 4px 4px 0; + max-height: 190px; + padding: 0 0 0 4px; + position: relative; + overflow-x: hidden; + overflow-y: auto; + z-index: 20; +} +div.chzn-container-multi ul.chzn-results { + margin: -1px 0 0; + padding: 0; +} +div.chzn-container-multi ul.chzn-results li { + border-left: 0px !important; + border-right: 0px !important; +} +div.chzn-container ul.chzn-results li { + line-height: 80%; + padding: 7px 7px 8px; + z-index: 22; + margin: 0; + list-style-type: none; +} +div.chzn-container ul.chzn-results li.active-result { + cursor: pointer; +} +div.chzn-container ul.chzn-results li em { + font-style: normal; + background: #FEFFDC; +} +div.chzn-container ul.chzn-results li.highlighted { + background: #3875d7; + color: #fff; +} +div.chzn-container ul.chzn-results li.highlighted em { + background: transparent; +} +div.chzn-container ul.chzn-results li.no-results { + background: #F4F4F4; +} +div.chzn-container ul.chzn-results li.group-result { + cursor: default; + color: #999; + font-weight: bold; +} +div.chzn-container ul.chzn-results li.group-option { + padding-left: 20px; +} + +div.chzn-container-multi div.chzn-drop li.result-selected { + display: none; +} + + + +/* Active */ +div.chzn-container-active a.chzn-single { + -webkit-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); + box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); + border: 1px solid #5897fb; +} +div.chzn-container-active a.chzn-single-with-drop { + border: 1px solid #aaa; + border-width: 1px 1px 1px; + -moz-box-shadow: 0px 1px 0px #FFF inset; + -webkit-box-shadow: 0px 1px 0px #FFF inset; + box-shadow: 0px 1px 0px #FFF inset; + background: #EEE; + background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, white), color-stop(0.5, #eeeeee)); + background-image: -moz-linear-gradient(center bottom, white 0%, #eeeeee 50%); + background-image: -o-linear-gradient(bottom, white 0%, #eeeeee 50%); + -webkit-border-bottom-left-radius: 0px; + -webkit-border-bottom-right-radius: 0px; + -moz-border-radius-bottomleft: 0px; + -moz-border-radius-bottomright: 0px; + border-bottom-left-radius: 0px; + border-bottom-right-radius: 0px; +} +div.chzn-container-active a.chzn-single-with-drop div { + background: transparent; + border-left: none; +} +div.chzn-container-active a.chzn-single-with-drop div b { + background-position: -18px 1px; +} +div.chzn-container-active ul.chzn-choices { + z-index: 21; + -webkit-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); + box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); + border: 1px solid #5897fb; +} +div.chzn-container-active ul.chzn-choices input { + color: #111 !important; +} diff --git a/src/usr/local/www/javascript/chosen/chosen.jquery.js b/src/usr/local/www/javascript/chosen/chosen.jquery.js new file mode 100644 index 0000000..21e822a --- /dev/null +++ b/src/usr/local/www/javascript/chosen/chosen.jquery.js @@ -0,0 +1,755 @@ +(function() { + /* + Chosen, a Select Box Enhancer for jQuery and Protoype + by Patrick Filler for Harvest, http://getharvest.com + + Available for use under the MIT License, http://en.wikipedia.org/wiki/MIT_License + + Copyright (c) 2011 by Harvest + */ var $, Chosen, SelectParser, get_side_border_padding, root; + var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + root = typeof exports !== "undefined" && exports !== null ? exports : this; + $ = jQuery; + $.fn.extend({ + chosen: function(data, options) { + return $(this).each(function(input_field) { + if (!($(this)).hasClass("chzn-done")) { + return new Chosen(this, data, options); + } + }); + } + }); + Chosen = (function() { + function Chosen(elmn) { + this.set_default_values(); + this.form_field = elmn; + this.form_field_jq = $(this.form_field); + this.is_multiple = this.form_field.multiple; + this.default_text_default = this.form_field.multiple ? "Select Some Options" : "Select an Option"; + this.set_up_html(); + this.register_observers(); + this.form_field_jq.addClass("chzn-done"); + } + Chosen.prototype.set_default_values = function() { + this.click_test_action = __bind(function(evt) { + return this.test_active_click(evt); + }, this); + this.active_field = false; + this.mouse_on_container = false; + this.results_showing = false; + this.result_highlighted = null; + this.result_single_selected = null; + return this.choices = 0; + }; + Chosen.prototype.set_up_html = function() { + var container_div, dd_top, dd_width, sf_width; + this.container_id = this.form_field.id + "_chzn"; + this.f_width = this.form_field_jq.width(); + this.default_text = this.form_field_jq.attr('title') ? this.form_field_jq.attr('title') : this.default_text_default; + container_div = $("
", { + id: this.container_id, + "class": 'chzn-container', + style: 'width: ' + this.f_width + 'px;' + }); + if (this.is_multiple) { + container_div.html('
    '); + } else { + container_div.html('' + this.default_text + '
      '); + } + this.form_field_jq.hide().after(container_div); + this.container = $('#' + this.container_id); + this.container.addClass("chzn-container-" + (this.is_multiple ? "multi" : "single")); + this.dropdown = this.container.find('div.chzn-drop').first(); + dd_top = this.container.height(); + dd_width = this.f_width - get_side_border_padding(this.dropdown); + this.dropdown.css({ + "width": dd_width + "px", + "top": dd_top + "px" + }); + this.search_field = this.container.find('input').first(); + this.search_results = this.container.find('ul.chzn-results').first(); + this.search_field_scale(); + this.search_no_results = this.container.find('li.no-results').first(); + if (this.is_multiple) { + this.search_choices = this.container.find('ul.chzn-choices').first(); + this.search_container = this.container.find('li.search-field').first(); + } else { + this.search_container = this.container.find('div.chzn-search').first(); + this.selected_item = this.container.find('.chzn-single').first(); + sf_width = dd_width - get_side_border_padding(this.search_container) - get_side_border_padding(this.search_field); + this.search_field.css({ + "width": sf_width + "px" + }); + } + this.results_build(); + return this.set_tab_index(); + }; + Chosen.prototype.register_observers = function() { + this.container.click(__bind(function(evt) { + return this.container_click(evt); + }, this)); + this.container.mouseenter(__bind(function(evt) { + return this.mouse_enter(evt); + }, this)); + this.container.mouseleave(__bind(function(evt) { + return this.mouse_leave(evt); + }, this)); + this.search_results.click(__bind(function(evt) { + return this.search_results_click(evt); + }, this)); + this.search_results.mouseover(__bind(function(evt) { + return this.search_results_mouseover(evt); + }, this)); + this.search_results.mouseout(__bind(function(evt) { + return this.search_results_mouseout(evt); + }, this)); + this.form_field_jq.bind("liszt:updated", __bind(function(evt) { + return this.results_update_field(evt); + }, this)); + this.search_field.blur(__bind(function(evt) { + return this.input_blur(evt); + }, this)); + this.search_field.keyup(__bind(function(evt) { + return this.keyup_checker(evt); + }, this)); + this.search_field.keydown(__bind(function(evt) { + return this.keydown_checker(evt); + }, this)); + if (this.is_multiple) { + this.search_choices.click(__bind(function(evt) { + return this.choices_click(evt); + }, this)); + return this.search_field.focus(__bind(function(evt) { + return this.input_focus(evt); + }, this)); + } else { + return this.selected_item.focus(__bind(function(evt) { + return this.activate_field(evt); + }, this)); + } + }; + Chosen.prototype.container_click = function(evt) { + if (evt && evt.type === "click") { + evt.stopPropagation(); + } + if (!this.pending_destroy_click) { + if (!this.active_field) { + if (this.is_multiple) { + this.search_field.val(""); + } + $(document).click(this.click_test_action); + this.results_show(); + } else if (!this.is_multiple && evt && ($(evt.target) === this.selected_item || $(evt.target).parents("a.chzn-single").length)) { + evt.preventDefault(); + this.results_toggle(); + } + return this.activate_field(); + } else { + return this.pending_destroy_click = false; + } + }; + Chosen.prototype.mouse_enter = function() { + return this.mouse_on_container = true; + }; + Chosen.prototype.mouse_leave = function() { + return this.mouse_on_container = false; + }; + Chosen.prototype.input_focus = function(evt) { + if (!this.active_field) { + return setTimeout((__bind(function() { + return this.container_click(); + }, this)), 50); + } + }; + Chosen.prototype.input_blur = function(evt) { + if (!this.mouse_on_container) { + this.active_field = false; + return setTimeout((__bind(function() { + return this.blur_test(); + }, this)), 100); + } + }; + Chosen.prototype.blur_test = function(evt) { + if (!this.active_field && this.container.hasClass("chzn-container-active")) { + return this.close_field(); + } + }; + Chosen.prototype.close_field = function() { + $(document).unbind("click", this.click_test_action); + if (!this.is_multiple) { + this.selected_item.attr("tabindex", this.search_field.attr("tabindex")); + this.search_field.attr("tabindex", -1); + } + this.active_field = false; + this.results_hide(); + this.container.removeClass("chzn-container-active"); + this.winnow_results_clear(); + this.clear_backstroke(); + this.show_search_field_default(); + return this.search_field_scale(); + }; + Chosen.prototype.activate_field = function() { + if (!this.is_multiple && !this.active_field) { + this.search_field.attr("tabindex", this.selected_item.attr("tabindex")); + this.selected_item.attr("tabindex", -1); + } + this.container.addClass("chzn-container-active"); + this.active_field = true; + this.search_field.val(this.search_field.val()); + return this.search_field.focus(); + }; + Chosen.prototype.test_active_click = function(evt) { + if ($(evt.target).parents('#' + this.container.id).length) { + return this.active_field = true; + } else { + return this.close_field(); + } + }; + Chosen.prototype.results_build = function() { + var content, data, startTime, _i, _len, _ref; + startTime = new Date(); + this.parsing = true; + this.results_data = SelectParser.select_to_array(this.form_field); + if (this.is_multiple && this.choices > 0) { + this.search_choices.find("li.search-choice").remove(); + this.choices = 0; + } else if (!this.is_multiple) { + this.selected_item.find("span").text(this.default_text); + } + content = ''; + _ref = this.results_data; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + data = _ref[_i]; + if (data.group) { + content += this.result_add_group(data); + } else if (!data.empty) { + content += this.result_add_option(data); + if (data.selected && this.is_multiple) { + this.choice_build(data); + } else if (data.selected && !this.is_multiple) { + this.selected_item.find("span").text(data.text); + } + } + } + this.show_search_field_default(); + this.search_field_scale(); + this.search_results.html(content); + return this.parsing = false; + }; + Chosen.prototype.result_add_group = function(group) { + if (!group.disabled) { + group.dom_id = this.form_field.id + "chzn_g_" + group.array_index; + return '
    • ' + $("
      ").text(group.label).html() + '
    • '; + } else { + return ""; + } + }; + Chosen.prototype.result_add_option = function(option) { + var classes; + if (!option.disabled) { + option.dom_id = this.form_field.id + "chzn_o_" + option.array_index; + classes = option.selected && this.is_multiple ? [] : ["active-result"]; + if (option.selected) { + classes.push("result-selected"); + } + if (option.group_array_index != null) { + classes.push("group-option"); + } + return '
    • ' + $("
      ").text(option.text).html() + '
    • '; + } else { + return ""; + } + }; + Chosen.prototype.results_update_field = function() { + this.result_clear_highlight(); + this.result_single_selected = null; + return this.results_build(); + }; + Chosen.prototype.result_do_highlight = function(el) { + var high_bottom, high_top, maxHeight, visible_bottom, visible_top; + if (el.length) { + this.result_clear_highlight(); + this.result_highlight = el; + this.result_highlight.addClass("highlighted"); + maxHeight = parseInt(this.search_results.css("maxHeight"), 10); + visible_top = this.search_results.scrollTop(); + visible_bottom = maxHeight + visible_top; + high_top = this.result_highlight.position().top + this.search_results.scrollTop(); + high_bottom = high_top + this.result_highlight.outerHeight(); + if (high_bottom >= visible_bottom) { + return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0); + } else if (high_top < visible_top) { + return this.search_results.scrollTop(high_top); + } + } + }; + Chosen.prototype.result_clear_highlight = function() { + if (this.result_highlight) { + this.result_highlight.removeClass("highlighted"); + } + return this.result_highlight = null; + }; + Chosen.prototype.results_toggle = function() { + if (this.results_showing) { + return this.results_hide(); + } else { + return this.results_show(); + } + }; + Chosen.prototype.results_show = function() { + var dd_top; + if (!this.is_multiple) { + this.selected_item.addClass("chzn-single-with-drop"); + if (this.result_single_selected) { + this.result_do_highlight(this.result_single_selected); + } + } + dd_top = this.is_multiple ? this.container.height() : this.container.height() - 1; + this.dropdown.css({ + "top": dd_top + "px", + "left": 0 + }); + this.results_showing = true; + this.search_field.focus(); + this.search_field.val(this.search_field.val()); + return this.winnow_results(); + }; + Chosen.prototype.results_hide = function() { + if (!this.is_multiple) { + this.selected_item.removeClass("chzn-single-with-drop"); + } + this.result_clear_highlight(); + this.dropdown.css({ + "left": "-9000px" + }); + return this.results_showing = false; + }; + Chosen.prototype.set_tab_index = function(el) { + var ti; + if (this.form_field_jq.attr("tabindex")) { + ti = this.form_field_jq.attr("tabindex"); + this.form_field_jq.attr("tabindex", -1); + if (this.is_multiple) { + return this.search_field.attr("tabindex", ti); + } else { + this.selected_item.attr("tabindex", ti); + return this.search_field.attr("tabindex", -1); + } + } + }; + Chosen.prototype.show_search_field_default = function() { + if (this.is_multiple && this.choices < 1 && !this.active_field) { + this.search_field.val(this.default_text); + return this.search_field.addClass("default"); + } else { + this.search_field.val(""); + return this.search_field.removeClass("default"); + } + }; + Chosen.prototype.search_results_click = function(evt) { + var target; + target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); + if (target.length) { + this.result_highlight = target; + return this.result_select(); + } + }; + Chosen.prototype.search_results_mouseover = function(evt) { + var target; + target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); + if (target) { + return this.result_do_highlight(target); + } + }; + Chosen.prototype.search_results_mouseout = function(evt) { + if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) { + return this.result_clear_highlight(); + } + }; + Chosen.prototype.choices_click = function(evt) { + evt.preventDefault(); + if (this.active_field && !($(evt.target).hasClass("search-choice" || $(evt.target).parents('.search-choice').first)) && !this.results_showing) { + return this.results_show(); + } + }; + Chosen.prototype.choice_build = function(item) { + var choice_id, link; + choice_id = this.form_field.id + "_chzn_c_" + item.array_index; + this.choices += 1; + this.search_container.before('
    • ' + item.text + '
    • '); + link = $('#' + choice_id).find("a").first(); + return link.click(__bind(function(evt) { + return this.choice_destroy_link_click(evt); + }, this)); + }; + Chosen.prototype.choice_destroy_link_click = function(evt) { + evt.preventDefault(); + this.pending_destroy_click = true; + return this.choice_destroy($(evt.target)); + }; + Chosen.prototype.choice_destroy = function(link) { + this.choices -= 1; + this.show_search_field_default(); + if (this.is_multiple && this.choices > 0 && this.search_field.val().length < 1) { + this.results_hide(); + } + this.result_deselect(link.attr("rel")); + return link.parents('li').first().remove(); + }; + Chosen.prototype.result_select = function() { + var high, high_id, item, position; + if (this.result_highlight) { + high = this.result_highlight; + high_id = high.attr("id"); + this.result_clear_highlight(); + high.addClass("result-selected"); + if (this.is_multiple) { + this.result_deactivate(high); + } else { + this.result_single_selected = high; + } + position = high_id.substr(high_id.lastIndexOf("_") + 1); + item = this.results_data[position]; + item.selected = true; + this.form_field.options[item.options_index].selected = true; + if (this.is_multiple) { + this.choice_build(item); + } else { + this.selected_item.find("span").first().text(item.text); + } + this.results_hide(); + this.search_field.val(""); + this.form_field_jq.trigger("change"); + return this.search_field_scale(); + } + }; + Chosen.prototype.result_activate = function(el) { + return el.addClass("active-result").show(); + }; + Chosen.prototype.result_deactivate = function(el) { + return el.removeClass("active-result").hide(); + }; + Chosen.prototype.result_deselect = function(pos) { + var result, result_data; + result_data = this.results_data[pos]; + result_data.selected = false; + this.form_field.options[result_data.options_index].selected = false; + result = $("#" + this.form_field.id + "chzn_o_" + pos); + result.removeClass("result-selected").addClass("active-result").show(); + this.result_clear_highlight(); + this.winnow_results(); + this.form_field_jq.trigger("change"); + return this.search_field_scale(); + }; + Chosen.prototype.results_search = function(evt) { + if (this.results_showing) { + return this.winnow_results(); + } else { + return this.results_show(); + } + }; + Chosen.prototype.winnow_results = function() { + var found, option, part, parts, regex, result_id, results, searchText, startTime, startpos, text, zregex, _i, _j, _len, _len2, _ref; + startTime = new Date(); + this.no_results_clear(); + results = 0; + searchText = this.search_field.val() === this.default_text ? "" : $.trim(this.search_field.val()); + regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'); + zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'); + _ref = this.results_data; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + option = _ref[_i]; + if (!option.disabled && !option.empty) { + if (option.group) { + $('#' + option.dom_id).hide(); + } else if (!(this.is_multiple && option.selected)) { + found = false; + result_id = option.dom_id; + if (regex.test(option.text)) { + found = true; + results += 1; + } else if (option.text.indexOf(" ") >= 0 || option.text.indexOf("[") === 0) { + parts = option.text.replace(/\[|\]/g, "").split(" "); + if (parts.length) { + for (_j = 0, _len2 = parts.length; _j < _len2; _j++) { + part = parts[_j]; + if (regex.test(part)) { + found = true; + results += 1; + } + } + } + } + if (found) { + if (searchText.length) { + startpos = option.text.search(zregex); + text = option.text.substr(0, startpos + searchText.length) + '' + option.text.substr(startpos + searchText.length); + text = text.substr(0, startpos) + '' + text.substr(startpos); + } else { + text = option.text; + } + if ($("#" + result_id).html !== text) { + $("#" + result_id).html(text); + } + this.result_activate($("#" + result_id)); + if (option.group_array_index != null) { + $("#" + this.results_data[option.group_array_index].dom_id).show(); + } + } else { + if (this.result_highlight && result_id === this.result_highlight.attr('id')) { + this.result_clear_highlight(); + } + this.result_deactivate($("#" + result_id)); + } + } + } + } + if (results < 1 && searchText.length) { + return this.no_results(searchText); + } else { + return this.winnow_results_set_highlight(); + } + }; + Chosen.prototype.winnow_results_clear = function() { + var li, lis, _i, _len, _results; + this.search_field.val(""); + lis = this.search_results.find("li"); + _results = []; + for (_i = 0, _len = lis.length; _i < _len; _i++) { + li = lis[_i]; + li = $(li); + _results.push(li.hasClass("group-result") ? li.show() : !this.is_multiple || !li.hasClass("result-selected") ? this.result_activate(li) : void 0); + } + return _results; + }; + Chosen.prototype.winnow_results_set_highlight = function() { + var do_high; + if (!this.result_highlight) { + do_high = this.search_results.find(".active-result").first(); + if (do_high) { + return this.result_do_highlight(do_high); + } + } + }; + Chosen.prototype.no_results = function(terms) { + var no_results_html; + no_results_html = $('
    • No results match ""
    • '); + no_results_html.find("span").first().text(terms); + return this.search_results.append(no_results_html); + }; + Chosen.prototype.no_results_clear = function() { + return this.search_results.find(".no-results").remove(); + }; + Chosen.prototype.keydown_arrow = function() { + var first_active, next_sib; + if (!this.result_highlight) { + first_active = this.search_results.find("li.active-result").first(); + if (first_active) { + this.result_do_highlight($(first_active)); + } + } else if (this.results_showing) { + next_sib = this.result_highlight.nextAll("li.active-result").first(); + if (next_sib) { + this.result_do_highlight(next_sib); + } + } + if (!this.results_showing) { + return this.results_show(); + } + }; + Chosen.prototype.keyup_arrow = function() { + var prev_sibs; + if (!this.results_showing && !this.is_multiple) { + return this.results_show(); + } else if (this.result_highlight) { + prev_sibs = this.result_highlight.prevAll("li.active-result"); + if (prev_sibs.length) { + return this.result_do_highlight(prev_sibs.first()); + } else { + if (this.choices > 0) { + this.results_hide(); + } + return this.result_clear_highlight(); + } + } + }; + Chosen.prototype.keydown_backstroke = function() { + if (this.pending_backstroke) { + this.choice_destroy(this.pending_backstroke.find("a").first()); + return this.clear_backstroke(); + } else { + this.pending_backstroke = this.search_container.siblings("li.search-choice").last(); + return this.pending_backstroke.addClass("search-choice-focus"); + } + }; + Chosen.prototype.clear_backstroke = function() { + if (this.pending_backstroke) { + this.pending_backstroke.removeClass("search-choice-focus"); + } + return this.pending_backstroke = null; + }; + Chosen.prototype.keyup_checker = function(evt) { + var stroke, _ref; + stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; + this.search_field_scale(); + switch (stroke) { + case 8: + if (this.is_multiple && this.backstroke_length < 1 && this.choices > 0) { + return this.keydown_backstroke(); + } else if (!this.pending_backstroke) { + this.result_clear_highlight(); + return this.results_search(); + } + break; + case 13: + evt.preventDefault(); + if (this.results_showing) { + return this.result_select(); + } + break; + case 27: + if (this.results_showing) { + return this.results_hide(); + } + break; + case 9: + case 38: + case 40: + case 16: + break; + default: + return this.results_search(); + } + }; + Chosen.prototype.keydown_checker = function(evt) { + var stroke, _ref; + stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; + this.search_field_scale(); + if (stroke !== 8 && this.pending_backstroke) { + this.clear_backstroke(); + } + switch (stroke) { + case 8: + this.backstroke_length = this.search_field.val().length; + break; + case 9: + this.mouse_on_container = false; + break; + case 13: + evt.preventDefault(); + break; + case 38: + evt.preventDefault(); + this.keyup_arrow(); + break; + case 40: + this.keydown_arrow(); + break; + } + }; + Chosen.prototype.search_field_scale = function() { + var dd_top, div, h, style, style_block, styles, w, _i, _len; + if (this.is_multiple) { + h = 0; + w = 0; + style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; + styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; + for (_i = 0, _len = styles.length; _i < _len; _i++) { + style = styles[_i]; + style_block += style + ":" + this.search_field.css(style) + ";"; + } + div = $('
      ', { + 'style': style_block + }); + div.text(this.search_field.val()); + $('body').append(div); + w = div.width() + 25; + div.remove(); + if (w > this.f_width - 10) { + w = this.f_width - 10; + } + this.search_field.css({ + 'width': w + 'px' + }); + dd_top = this.container.height(); + return this.dropdown.css({ + "top": dd_top + "px" + }); + } + }; + return Chosen; + })(); + get_side_border_padding = function(elmt) { + var side_border_padding; + return side_border_padding = elmt.outerWidth() - elmt.width(); + }; + root.get_side_border_padding = get_side_border_padding; + SelectParser = (function() { + function SelectParser() { + this.options_index = 0; + this.parsed = []; + } + SelectParser.prototype.add_node = function(child) { + if (child.nodeName === "OPTGROUP") { + return this.add_group(child); + } else { + return this.add_option(child); + } + }; + SelectParser.prototype.add_group = function(group) { + var group_position, option, _i, _len, _ref, _results; + group_position = this.parsed.length; + this.parsed.push({ + array_index: group_position, + group: true, + label: group.label, + children: 0, + disabled: group.disabled + }); + _ref = group.childNodes; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + option = _ref[_i]; + _results.push(this.add_option(option, group_position, group.disabled)); + } + return _results; + }; + SelectParser.prototype.add_option = function(option, group_position, group_disabled) { + if (option.nodeName === "OPTION") { + if (option.text !== "") { + if (group_position != null) { + this.parsed[group_position].children += 1; + } + this.parsed.push({ + array_index: this.parsed.length, + options_index: this.options_index, + value: option.value, + text: option.text, + selected: option.selected, + disabled: group_disabled === true ? group_disabled : option.disabled, + group_array_index: group_position + }); + } else { + this.parsed.push({ + array_index: this.parsed.length, + options_index: this.options_index, + empty: true + }); + } + return this.options_index += 1; + } + }; + return SelectParser; + })(); + SelectParser.select_to_array = function(select) { + var child, parser, _i, _len, _ref; + parser = new SelectParser(); + _ref = select.childNodes; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + child = _ref[_i]; + parser.add_node(child); + } + return parser.parsed; + }; + root.SelectParser = SelectParser; +}).call(this); diff --git a/src/usr/local/www/javascript/chosen/chosen.jquery.min.js b/src/usr/local/www/javascript/chosen/chosen.jquery.min.js new file mode 100644 index 0000000..ae69f22 --- /dev/null +++ b/src/usr/local/www/javascript/chosen/chosen.jquery.min.js @@ -0,0 +1,9 @@ +/* +Chosen, a Select Box Enhancer for jQuery and Protoype +by Patrick Filler for Harvest, http://getharvest.com + +Available for use under the MIT License, http://en.wikipedia.org/wiki/MIT_License + +Copyright (c) 2011 by Harvest +*/ +(function(){var $,Chosen,SelectParser,get_side_border_padding,root;var __bind=function(fn,me){return function(){return fn.apply(me,arguments);};};root=typeof exports!=="undefined"&&exports!==null?exports:this;$=jQuery;$.fn.extend({chosen:function(data,options){return $(this).each(function(input_field){if(!($(this)).hasClass("chzn-done")){return new Chosen(this,data,options);}});}});Chosen=(function(){function Chosen(elmn){this.set_default_values();this.form_field=elmn;this.form_field_jq=$(this.form_field);this.is_multiple=this.form_field.multiple;this.default_text_default=this.form_field.multiple?"Select Some Options":"Select an Option";this.set_up_html();this.register_observers();this.form_field_jq.addClass("chzn-done");}Chosen.prototype.set_default_values=function(){this.click_test_action=__bind(function(evt){return this.test_active_click(evt);},this);this.active_field=false;this.mouse_on_container=false;this.results_showing=false;this.result_highlighted=null;this.result_single_selected=null;return this.choices=0;};Chosen.prototype.set_up_html=function(){var container_div,dd_top,dd_width,sf_width;this.container_id=this.form_field.id+"_chzn";this.f_width=this.form_field_jq.width();this.default_text=this.form_field_jq.attr("title")?this.form_field_jq.attr("title"):this.default_text_default;container_div=$("
      ",{id:this.container_id,"class":"chzn-container",style:"width: "+this.f_width+"px;"});if(this.is_multiple){container_div.html('
        ');}else{container_div.html(''+this.default_text+'
          ');}this.form_field_jq.hide().after(container_div);this.container=$("#"+this.container_id);this.container.addClass("chzn-container-"+(this.is_multiple?"multi":"single"));this.dropdown=this.container.find("div.chzn-drop").first();dd_top=this.container.height();dd_width=this.f_width-get_side_border_padding(this.dropdown);this.dropdown.css({width:dd_width+"px",top:dd_top+"px"});this.search_field=this.container.find("input").first();this.search_results=this.container.find("ul.chzn-results").first();this.search_field_scale();this.search_no_results=this.container.find("li.no-results").first();if(this.is_multiple){this.search_choices=this.container.find("ul.chzn-choices").first();this.search_container=this.container.find("li.search-field").first();}else{this.search_container=this.container.find("div.chzn-search").first();this.selected_item=this.container.find(".chzn-single").first();sf_width=dd_width-get_side_border_padding(this.search_container)-get_side_border_padding(this.search_field);this.search_field.css({width:sf_width+"px"});}this.results_build();return this.set_tab_index();};Chosen.prototype.register_observers=function(){this.container.click(__bind(function(evt){return this.container_click(evt);},this));this.container.mouseenter(__bind(function(evt){return this.mouse_enter(evt);},this));this.container.mouseleave(__bind(function(evt){return this.mouse_leave(evt);},this));this.search_results.click(__bind(function(evt){return this.search_results_click(evt);},this));this.search_results.mouseover(__bind(function(evt){return this.search_results_mouseover(evt);},this));this.search_results.mouseout(__bind(function(evt){return this.search_results_mouseout(evt);},this));this.form_field_jq.bind("liszt:updated",__bind(function(evt){return this.results_update_field(evt);},this));this.search_field.blur(__bind(function(evt){return this.input_blur(evt);},this));this.search_field.keyup(__bind(function(evt){return this.keyup_checker(evt);},this));this.search_field.keydown(__bind(function(evt){return this.keydown_checker(evt);},this));if(this.is_multiple){this.search_choices.click(__bind(function(evt){return this.choices_click(evt);},this));return this.search_field.focus(__bind(function(evt){return this.input_focus(evt);},this));}else{return this.selected_item.focus(__bind(function(evt){return this.activate_field(evt);},this));}};Chosen.prototype.container_click=function(evt){if(evt&&evt.type==="click"){evt.stopPropagation();}if(!this.pending_destroy_click){if(!this.active_field){if(this.is_multiple){this.search_field.val("");}$(document).click(this.click_test_action);this.results_show();}else{if(!this.is_multiple&&evt&&($(evt.target)===this.selected_item||$(evt.target).parents("a.chzn-single").length)){evt.preventDefault();this.results_toggle();}}return this.activate_field();}else{return this.pending_destroy_click=false;}};Chosen.prototype.mouse_enter=function(){return this.mouse_on_container=true;};Chosen.prototype.mouse_leave=function(){return this.mouse_on_container=false;};Chosen.prototype.input_focus=function(evt){if(!this.active_field){return setTimeout((__bind(function(){return this.container_click();},this)),50);}};Chosen.prototype.input_blur=function(evt){if(!this.mouse_on_container){this.active_field=false;return setTimeout((__bind(function(){return this.blur_test();},this)),100);}};Chosen.prototype.blur_test=function(evt){if(!this.active_field&&this.container.hasClass("chzn-container-active")){return this.close_field();}};Chosen.prototype.close_field=function(){$(document).unbind("click",this.click_test_action);if(!this.is_multiple){this.selected_item.attr("tabindex",this.search_field.attr("tabindex"));this.search_field.attr("tabindex",-1);}this.active_field=false;this.results_hide();this.container.removeClass("chzn-container-active");this.winnow_results_clear();this.clear_backstroke();this.show_search_field_default();return this.search_field_scale();};Chosen.prototype.activate_field=function(){if(!this.is_multiple&&!this.active_field){this.search_field.attr("tabindex",this.selected_item.attr("tabindex"));this.selected_item.attr("tabindex",-1);}this.container.addClass("chzn-container-active");this.active_field=true;this.search_field.val(this.search_field.val());return this.search_field.focus();};Chosen.prototype.test_active_click=function(evt){if($(evt.target).parents("#"+this.container.id).length){return this.active_field=true;}else{return this.close_field();}};Chosen.prototype.results_build=function(){var content,data,startTime,_i,_len,_ref;startTime=new Date();this.parsing=true;this.results_data=SelectParser.select_to_array(this.form_field);if(this.is_multiple&&this.choices>0){this.search_choices.find("li.search-choice").remove();this.choices=0;}else{if(!this.is_multiple){this.selected_item.find("span").text(this.default_text);}}content="";_ref=this.results_data;for(_i=0,_len=_ref.length;_i<_len;_i++){data=_ref[_i];if(data.group){content+=this.result_add_group(data);}else{if(!data.empty){content+=this.result_add_option(data);if(data.selected&&this.is_multiple){this.choice_build(data);}else{if(data.selected&&!this.is_multiple){this.selected_item.find("span").text(data.text);}}}}}this.show_search_field_default();this.search_field_scale();this.search_results.html(content);return this.parsing=false;};Chosen.prototype.result_add_group=function(group){if(!group.disabled){group.dom_id=this.form_field.id+"chzn_g_"+group.array_index;return'
        • '+$("
          ").text(group.label).html()+"
        • ";}else{return"";}};Chosen.prototype.result_add_option=function(option){var classes;if(!option.disabled){option.dom_id=this.form_field.id+"chzn_o_"+option.array_index;classes=option.selected&&this.is_multiple?[]:["active-result"];if(option.selected){classes.push("result-selected");}if(option.group_array_index!=null){classes.push("group-option");}return'
        • '+$("
          ").text(option.text).html()+"
        • ";}else{return"";}};Chosen.prototype.results_update_field=function(){this.result_clear_highlight();this.result_single_selected=null;return this.results_build();};Chosen.prototype.result_do_highlight=function(el){var high_bottom,high_top,maxHeight,visible_bottom,visible_top;if(el.length){this.result_clear_highlight();this.result_highlight=el;this.result_highlight.addClass("highlighted");maxHeight=parseInt(this.search_results.css("maxHeight"),10);visible_top=this.search_results.scrollTop();visible_bottom=maxHeight+visible_top;high_top=this.result_highlight.position().top+this.search_results.scrollTop();high_bottom=high_top+this.result_highlight.outerHeight();if(high_bottom>=visible_bottom){return this.search_results.scrollTop((high_bottom-maxHeight)>0?high_bottom-maxHeight:0);}else{if(high_top'+item.text+'');link=$("#"+choice_id).find("a").first();return link.click(__bind(function(evt){return this.choice_destroy_link_click(evt);},this));};Chosen.prototype.choice_destroy_link_click=function(evt){evt.preventDefault();this.pending_destroy_click=true;return this.choice_destroy($(evt.target));};Chosen.prototype.choice_destroy=function(link){this.choices-=1;this.show_search_field_default();if(this.is_multiple&&this.choices>0&&this.search_field.val().length<1){this.results_hide();}this.result_deselect(link.attr("rel"));return link.parents("li").first().remove();};Chosen.prototype.result_select=function(){var high,high_id,item,position;if(this.result_highlight){high=this.result_highlight;high_id=high.attr("id");this.result_clear_highlight();high.addClass("result-selected");if(this.is_multiple){this.result_deactivate(high);}else{this.result_single_selected=high;}position=high_id.substr(high_id.lastIndexOf("_")+1);item=this.results_data[position];item.selected=true;this.form_field.options[item.options_index].selected=true;if(this.is_multiple){this.choice_build(item);}else{this.selected_item.find("span").first().text(item.text);}this.results_hide();this.search_field.val("");this.form_field_jq.trigger("change");return this.search_field_scale();}};Chosen.prototype.result_activate=function(el){return el.addClass("active-result").show();};Chosen.prototype.result_deactivate=function(el){return el.removeClass("active-result").hide();};Chosen.prototype.result_deselect=function(pos){var result,result_data;result_data=this.results_data[pos];result_data.selected=false;this.form_field.options[result_data.options_index].selected=false;result=$("#"+this.form_field.id+"chzn_o_"+pos);result.removeClass("result-selected").addClass("active-result").show();this.result_clear_highlight();this.winnow_results();this.form_field_jq.trigger("change");return this.search_field_scale();};Chosen.prototype.results_search=function(evt){if(this.results_showing){return this.winnow_results();}else{return this.results_show();}};Chosen.prototype.winnow_results=function(){var found,option,part,parts,regex,result_id,results,searchText,startTime,startpos,text,zregex,_i,_j,_len,_len2,_ref;startTime=new Date();this.no_results_clear();results=0;searchText=this.search_field.val()===this.default_text?"":$.trim(this.search_field.val());regex=new RegExp("^"+searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i");zregex=new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i");_ref=this.results_data;for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];if(!option.disabled&&!option.empty){if(option.group){$("#"+option.dom_id).hide();}else{if(!(this.is_multiple&&option.selected)){found=false;result_id=option.dom_id;if(regex.test(option.text)){found=true;results+=1;}else{if(option.text.indexOf(" ")>=0||option.text.indexOf("[")===0){parts=option.text.replace(/\[|\]/g,"").split(" ");if(parts.length){for(_j=0,_len2=parts.length;_j<_len2;_j++){part=parts[_j];if(regex.test(part)){found=true;results+=1;}}}}}if(found){if(searchText.length){startpos=option.text.search(zregex);text=option.text.substr(0,startpos+searchText.length)+"
          "+option.text.substr(startpos+searchText.length);text=text.substr(0,startpos)+""+text.substr(startpos);}else{text=option.text;}if($("#"+result_id).html!==text){$("#"+result_id).html(text);}this.result_activate($("#"+result_id));if(option.group_array_index!=null){$("#"+this.results_data[option.group_array_index].dom_id).show();}}else{if(this.result_highlight&&result_id===this.result_highlight.attr("id")){this.result_clear_highlight();}this.result_deactivate($("#"+result_id));}}}}}if(results<1&&searchText.length){return this.no_results(searchText);}else{return this.winnow_results_set_highlight();}};Chosen.prototype.winnow_results_clear=function(){var li,lis,_i,_len,_results;this.search_field.val("");lis=this.search_results.find("li");_results=[];for(_i=0,_len=lis.length;_i<_len;_i++){li=lis[_i];li=$(li);_results.push(li.hasClass("group-result")?li.show():!this.is_multiple||!li.hasClass("result-selected")?this.result_activate(li):void 0);}return _results;};Chosen.prototype.winnow_results_set_highlight=function(){var do_high;if(!this.result_highlight){do_high=this.search_results.find(".active-result").first();if(do_high){return this.result_do_highlight(do_high);}}};Chosen.prototype.no_results=function(terms){var no_results_html;no_results_html=$('
        • No results match ""
        • ');no_results_html.find("span").first().text(terms);return this.search_results.append(no_results_html);};Chosen.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove();};Chosen.prototype.keydown_arrow=function(){var first_active,next_sib;if(!this.result_highlight){first_active=this.search_results.find("li.active-result").first();if(first_active){this.result_do_highlight($(first_active));}}else{if(this.results_showing){next_sib=this.result_highlight.nextAll("li.active-result").first();if(next_sib){this.result_do_highlight(next_sib);}}}if(!this.results_showing){return this.results_show();}};Chosen.prototype.keyup_arrow=function(){var prev_sibs;if(!this.results_showing&&!this.is_multiple){return this.results_show();}else{if(this.result_highlight){prev_sibs=this.result_highlight.prevAll("li.active-result");if(prev_sibs.length){return this.result_do_highlight(prev_sibs.first());}else{if(this.choices>0){this.results_hide();}return this.result_clear_highlight();}}}};Chosen.prototype.keydown_backstroke=function(){if(this.pending_backstroke){this.choice_destroy(this.pending_backstroke.find("a").first());return this.clear_backstroke();}else{this.pending_backstroke=this.search_container.siblings("li.search-choice").last();return this.pending_backstroke.addClass("search-choice-focus");}};Chosen.prototype.clear_backstroke=function(){if(this.pending_backstroke){this.pending_backstroke.removeClass("search-choice-focus");}return this.pending_backstroke=null;};Chosen.prototype.keyup_checker=function(evt){var stroke,_ref;stroke=(_ref=evt.which)!=null?_ref:evt.keyCode;this.search_field_scale();switch(stroke){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices>0){return this.keydown_backstroke();}else{if(!this.pending_backstroke){this.result_clear_highlight();return this.results_search();}}break;case 13:evt.preventDefault();if(this.results_showing){return this.result_select();}break;case 27:if(this.results_showing){return this.results_hide();}break;case 9:case 38:case 40:case 16:break;default:return this.results_search();}};Chosen.prototype.keydown_checker=function(evt){var stroke,_ref;stroke=(_ref=evt.which)!=null?_ref:evt.keyCode;this.search_field_scale();if(stroke!==8&&this.pending_backstroke){this.clear_backstroke();}switch(stroke){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.mouse_on_container=false;break;case 13:evt.preventDefault();break;case 38:evt.preventDefault();this.keyup_arrow();break;case 40:this.keydown_arrow();break;}};Chosen.prototype.search_field_scale=function(){var dd_top,div,h,style,style_block,styles,w,_i,_len;if(this.is_multiple){h=0;w=0;style_block="position:absolute; left: -1000px; top: -1000px; display:none;";styles=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"];for(_i=0,_len=styles.length;_i<_len;_i++){style=styles[_i];style_block+=style+":"+this.search_field.css(style)+";";}div=$("
          ",{style:style_block});div.text(this.search_field.val());$("body").append(div);w=div.width()+25;div.remove();if(w>this.f_width-10){w=this.f_width-10;}this.search_field.css({width:w+"px"});dd_top=this.container.height();return this.dropdown.css({top:dd_top+"px"});}};return Chosen;})();get_side_border_padding=function(elmt){var side_border_padding;return side_border_padding=elmt.outerWidth()-elmt.width();};root.get_side_border_padding=get_side_border_padding;SelectParser=(function(){function SelectParser(){this.options_index=0;this.parsed=[];}SelectParser.prototype.add_node=function(child){if(child.nodeName==="OPTGROUP"){return this.add_group(child);}else{return this.add_option(child);}};SelectParser.prototype.add_group=function(group){var group_position,option,_i,_len,_ref,_results;group_position=this.parsed.length;this.parsed.push({array_index:group_position,group:true,label:group.label,children:0,disabled:group.disabled});_ref=group.childNodes;_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];_results.push(this.add_option(option,group_position,group.disabled));}return _results;};SelectParser.prototype.add_option=function(option,group_position,group_disabled){if(option.nodeName==="OPTION"){if(option.text!==""){if(group_position!=null){this.parsed[group_position].children+=1;}this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:option.value,text:option.text,selected:option.selected,disabled:group_disabled===true?group_disabled:option.disabled,group_array_index:group_position});}else{this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:true});}return this.options_index+=1;}};return SelectParser;})();SelectParser.select_to_array=function(select){var child,parser,_i,_len,_ref;parser=new SelectParser();_ref=select.childNodes;for(_i=0,_len=_ref.length;_i<_len;_i++){child=_ref[_i];parser.add_node(child);}return parser.parsed;};root.SelectParser=SelectParser;}).call(this); \ No newline at end of file diff --git a/src/usr/local/www/javascript/chosen/chosen.proto.js b/src/usr/local/www/javascript/chosen/chosen.proto.js new file mode 100644 index 0000000..e3c0fbd --- /dev/null +++ b/src/usr/local/www/javascript/chosen/chosen.proto.js @@ -0,0 +1,765 @@ +(function() { + /* + Chosen, a Select Box Enhancer for jQuery and Protoype + by Patrick Filler for Harvest, http://getharvest.com + + Available for use under the MIT License, http://en.wikipedia.org/wiki/MIT_License + + Copyright (c) 2011 by Harvest + */ var Chosen, SelectParser, get_side_border_padding, root; + var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + root = typeof exports !== "undefined" && exports !== null ? exports : this; + Chosen = (function() { + function Chosen(elmn) { + this.set_default_values(); + this.form_field = elmn; + this.is_multiple = this.form_field.multiple; + this.default_text_default = this.form_field.multiple ? "Select Some Options" : "Select an Option"; + this.set_up_html(); + this.register_observers(); + } + Chosen.prototype.set_default_values = function() { + this.click_test_action = __bind(function(evt) { + return this.test_active_click(evt); + }, this); + this.active_field = false; + this.mouse_on_container = false; + this.results_showing = false; + this.result_highlighted = null; + this.result_single_selected = null; + this.choices = 0; + this.single_temp = new Template('#{default}
            '); + this.multi_temp = new Template('
              '); + this.choice_temp = new Template('
            • #{choice}
            • '); + return this.no_results_temp = new Template('
            • No results match "#{terms}"
            • '); + }; + Chosen.prototype.set_up_html = function() { + var base_template, container_props, dd_top, dd_width, sf_width; + this.container_id = this.form_field.id + "_chzn"; + this.f_width = this.form_field.getStyle("width") ? parseInt(this.form_field.getStyle("width"), 10) : this.form_field.getWidth(); + container_props = { + 'id': this.container_id, + 'class': 'chzn-container', + 'style': 'width: ' + this.f_width + 'px' + }; + this.default_text = this.form_field.readAttribute('title') ? this.form_field.readAttribute('title') : this.default_text_default; + base_template = this.is_multiple ? new Element('div', container_props).update(this.multi_temp.evaluate({ + "default": this.default_text + })) : new Element('div', container_props).update(this.single_temp.evaluate({ + "default": this.default_text + })); + this.form_field.hide().insert({ + after: base_template + }); + this.container = $(this.container_id); + this.container.addClassName("chzn-container-" + (this.is_multiple ? "multi" : "single")); + this.dropdown = this.container.down('div.chzn-drop'); + dd_top = this.container.getHeight(); + dd_width = this.f_width - get_side_border_padding(this.dropdown); + this.dropdown.setStyle({ + "width": dd_width + "px", + "top": dd_top + "px" + }); + this.search_field = this.container.down('input'); + this.search_results = this.container.down('ul.chzn-results'); + this.search_field_scale(); + this.search_no_results = this.container.down('li.no-results'); + if (this.is_multiple) { + this.search_choices = this.container.down('ul.chzn-choices'); + this.search_container = this.container.down('li.search-field'); + } else { + this.search_container = this.container.down('div.chzn-search'); + this.selected_item = this.container.down('.chzn-single'); + sf_width = dd_width - get_side_border_padding(this.search_container) - get_side_border_padding(this.search_field); + this.search_field.setStyle({ + "width": sf_width + "px" + }); + } + this.results_build(); + return this.set_tab_index(); + }; + Chosen.prototype.register_observers = function() { + this.container.observe("click", __bind(function(evt) { + return this.container_click(evt); + }, this)); + this.container.observe("mouseenter", __bind(function(evt) { + return this.mouse_enter(evt); + }, this)); + this.container.observe("mouseleave", __bind(function(evt) { + return this.mouse_leave(evt); + }, this)); + this.search_results.observe("click", __bind(function(evt) { + return this.search_results_click(evt); + }, this)); + this.search_results.observe("mouseover", __bind(function(evt) { + return this.search_results_mouseover(evt); + }, this)); + this.search_results.observe("mouseout", __bind(function(evt) { + return this.search_results_mouseout(evt); + }, this)); + this.form_field.observe("liszt:updated", __bind(function(evt) { + return this.results_update_field(evt); + }, this)); + this.search_field.observe("blur", __bind(function(evt) { + return this.input_blur(evt); + }, this)); + this.search_field.observe("keyup", __bind(function(evt) { + return this.keyup_checker(evt); + }, this)); + this.search_field.observe("keydown", __bind(function(evt) { + return this.keydown_checker(evt); + }, this)); + if (this.is_multiple) { + this.search_choices.observe("click", __bind(function(evt) { + return this.choices_click(evt); + }, this)); + return this.search_field.observe("focus", __bind(function(evt) { + return this.input_focus(evt); + }, this)); + } else { + return this.selected_item.observe("focus", __bind(function(evt) { + return this.activate_field(evt); + }, this)); + } + }; + Chosen.prototype.container_click = function(evt) { + if (evt && evt.type === "click") { + evt.stop(); + } + if (!this.pending_destroy_click) { + if (!this.active_field) { + if (this.is_multiple) { + this.search_field.clear(); + } + document.observe("click", this.click_test_action); + this.results_show(); + } else if (!this.is_multiple && evt && (evt.target === this.selected_item || evt.target.up("a.chzn-single"))) { + this.results_toggle(); + } + return this.activate_field(); + } else { + return this.pending_destroy_click = false; + } + }; + Chosen.prototype.mouse_enter = function() { + return this.mouse_on_container = true; + }; + Chosen.prototype.mouse_leave = function() { + return this.mouse_on_container = false; + }; + Chosen.prototype.input_focus = function(evt) { + if (!this.active_field) { + return setTimeout(this.container_click.bind(this), 50); + } + }; + Chosen.prototype.input_blur = function(evt) { + if (!this.mouse_on_container) { + this.active_field = false; + return setTimeout(this.blur_test.bind(this), 100); + } + }; + Chosen.prototype.blur_test = function(evt) { + if (!this.active_field && this.container.hasClassName("chzn-container-active")) { + return this.close_field(); + } + }; + Chosen.prototype.close_field = function() { + document.stopObserving("click", this.click_test_action); + if (!this.is_multiple) { + this.selected_item.tabIndex = this.search_field.tabIndex; + this.search_field.tabIndex = -1; + } + this.active_field = false; + this.results_hide(); + this.container.removeClassName("chzn-container-active"); + this.winnow_results_clear(); + this.clear_backstroke(); + this.show_search_field_default(); + return this.search_field_scale(); + }; + Chosen.prototype.activate_field = function() { + if (!this.is_multiple && !this.active_field) { + this.search_field.tabIndex = this.selected_item.tabIndex; + this.selected_item.tabIndex = -1; + } + this.container.addClassName("chzn-container-active"); + this.active_field = true; + this.search_field.value = this.search_field.value; + return this.search_field.focus(); + }; + Chosen.prototype.test_active_click = function(evt) { + if (evt.target.up('#' + this.container.id)) { + return this.active_field = true; + } else { + return this.close_field(); + } + }; + Chosen.prototype.results_build = function() { + var content, data, startTime, _i, _len, _ref; + startTime = new Date(); + this.parsing = true; + this.results_data = SelectParser.select_to_array(this.form_field); + if (this.is_multiple && this.choices > 0) { + this.search_choices.select("li.search-choice").invoke("remove"); + this.choices = 0; + } else if (!this.is_multiple) { + this.selected_item.down("span").update(this.default_text); + } + content = ''; + _ref = this.results_data; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + data = _ref[_i]; + if (data.group) { + content += this.result_add_group(data); + } else if (!data.empty) { + content += this.result_add_option(data); + if (data.selected && this.is_multiple) { + this.choice_build(data); + } else if (data.selected && !this.is_multiple) { + this.selected_item.down("span").update(data.text); + } + } + } + this.show_search_field_default(); + this.search_field_scale(); + this.search_results.update(content); + return this.parsing = false; + }; + Chosen.prototype.result_add_group = function(group) { + if (!group.disabled) { + group.dom_id = this.form_field.id + "chzn_g_" + group.array_index; + return '
            • ' + group.label.escapeHTML() + '
            • '; + } else { + return ""; + } + }; + Chosen.prototype.result_add_option = function(option) { + var classes; + if (!option.disabled) { + option.dom_id = this.form_field.id + "chzn_o_" + option.array_index; + classes = option.selected && this.is_multiple ? [] : ["active-result"]; + if (option.selected) { + classes.push("result-selected"); + } + if (option.group_array_index != null) { + classes.push("group-option"); + } + return '
            • ' + option.text.escapeHTML() + '
            • '; + } else { + return ""; + } + }; + Chosen.prototype.results_update_field = function() { + this.result_clear_highlight(); + this.result_single_selected = null; + return this.results_build(); + }; + Chosen.prototype.result_do_highlight = function(el) { + var high_bottom, high_top, maxHeight, visible_bottom, visible_top; + this.result_clear_highlight(); + this.result_highlight = el; + this.result_highlight.addClassName("highlighted"); + maxHeight = parseInt(this.search_results.getStyle('maxHeight'), 10); + visible_top = this.search_results.scrollTop; + visible_bottom = maxHeight + visible_top; + high_top = this.result_highlight.positionedOffset().top; + high_bottom = high_top + this.result_highlight.getHeight(); + if (high_bottom >= visible_bottom) { + return this.search_results.scrollTop = (high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0; + } else if (high_top < visible_top) { + return this.search_results.scrollTop = high_top; + } + }; + Chosen.prototype.result_clear_highlight = function() { + if (this.result_highlight) { + this.result_highlight.removeClassName('highlighted'); + } + return this.result_highlight = null; + }; + Chosen.prototype.results_toggle = function() { + if (this.results_showing) { + return this.results_hide(); + } else { + return this.results_show(); + } + }; + Chosen.prototype.results_show = function() { + var dd_top; + if (!this.is_multiple) { + this.selected_item.addClassName('chzn-single-with-drop'); + if (this.result_single_selected) { + this.result_do_highlight(this.result_single_selected); + } + } + dd_top = this.is_multiple ? this.container.getHeight() : this.container.getHeight() - 1; + this.dropdown.setStyle({ + "top": dd_top + "px", + "left": 0 + }); + this.results_showing = true; + this.search_field.focus(); + this.search_field.value = this.search_field.value; + return this.winnow_results(); + }; + Chosen.prototype.results_hide = function() { + if (!this.is_multiple) { + this.selected_item.removeClassName('chzn-single-with-drop'); + } + this.result_clear_highlight(); + this.dropdown.setStyle({ + "left": "-9000px" + }); + return this.results_showing = false; + }; + Chosen.prototype.set_tab_index = function(el) { + var ti; + if (this.form_field.tabIndex) { + ti = this.form_field.tabIndex; + this.form_field.tabIndex = -1; + if (this.is_multiple) { + return this.search_field.tabIndex = ti; + } else { + this.selected_item.tabIndex = ti; + return this.search_field.tabIndex = -1; + } + } + }; + Chosen.prototype.show_search_field_default = function() { + if (this.is_multiple && this.choices < 1 && !this.active_field) { + this.search_field.value = this.default_text; + return this.search_field.addClassName("default"); + } else { + this.search_field.value = ""; + return this.search_field.removeClassName("default"); + } + }; + Chosen.prototype.search_results_click = function(evt) { + var target; + target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result"); + if (target) { + this.result_highlight = target; + return this.result_select(); + } + }; + Chosen.prototype.search_results_mouseover = function(evt) { + var target; + target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result"); + if (target) { + return this.result_do_highlight(target); + } + }; + Chosen.prototype.search_results_mouseout = function(evt) { + if (evt.target.hasClassName('active-result') || evt.target.up('.active-result')) { + return this.result_clear_highlight(); + } + }; + Chosen.prototype.choices_click = function(evt) { + evt.preventDefault(); + if (this.active_field && !(evt.target.hasClassName('search-choice') || evt.target.up('.search-choice')) && !this.results_showing) { + return this.results_show(); + } + }; + Chosen.prototype.choice_build = function(item) { + var choice_id, link; + choice_id = this.form_field.id + "_chzn_c_" + item.array_index; + this.choices += 1; + this.search_container.insert({ + before: this.choice_temp.evaluate({ + "id": choice_id, + "choice": item.text, + "position": item.array_index + }) + }); + link = $(choice_id).down('a'); + return link.observe("click", __bind(function(evt) { + return this.choice_destroy_link_click(evt); + }, this)); + }; + Chosen.prototype.choice_destroy_link_click = function(evt) { + evt.preventDefault(); + this.pending_destroy_click = true; + return this.choice_destroy(evt.target); + }; + Chosen.prototype.choice_destroy = function(link) { + this.choices -= 1; + this.show_search_field_default(); + if (this.is_multiple && this.choices > 0 && this.search_field.value.length < 1) { + this.results_hide(); + } + this.result_deselect(link.readAttribute("rel")); + return link.up('li').remove(); + }; + Chosen.prototype.result_select = function() { + var high, item, position; + if (this.result_highlight) { + high = this.result_highlight; + this.result_clear_highlight(); + high.addClassName("result-selected"); + if (this.is_multiple) { + this.result_deactivate(high); + } else { + this.result_single_selected = high; + } + position = high.id.substr(high.id.lastIndexOf("_") + 1); + item = this.results_data[position]; + item.selected = true; + this.form_field.options[item.options_index].selected = true; + if (this.is_multiple) { + this.choice_build(item); + } else { + this.selected_item.down("span").update(item.text); + } + this.results_hide(); + this.search_field.value = ""; + if (typeof Event.simulate === 'function') { + this.form_field.simulate("change"); + } + return this.search_field_scale(); + } + }; + Chosen.prototype.result_activate = function(el) { + return el.addClassName("active-result").show(); + }; + Chosen.prototype.result_deactivate = function(el) { + return el.removeClassName("active-result").hide(); + }; + Chosen.prototype.result_deselect = function(pos) { + var result, result_data; + result_data = this.results_data[pos]; + result_data.selected = false; + this.form_field.options[result_data.options_index].selected = false; + result = $(this.form_field.id + "chzn_o_" + pos); + result.removeClassName("result-selected").addClassName("active-result").show(); + this.result_clear_highlight(); + this.winnow_results(); + if (typeof Event.simulate === 'function') { + this.form_field.simulate("change"); + } + return this.search_field_scale(); + }; + Chosen.prototype.results_search = function(evt) { + if (this.results_showing) { + return this.winnow_results(); + } else { + return this.results_show(); + } + }; + Chosen.prototype.winnow_results = function() { + var found, option, part, parts, regex, result_id, results, searchText, startTime, startpos, text, zregex, _i, _j, _len, _len2, _ref; + startTime = new Date(); + this.no_results_clear(); + results = 0; + searchText = this.search_field.value === this.default_text ? "" : this.search_field.value.strip(); + regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'); + zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'); + _ref = this.results_data; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + option = _ref[_i]; + if (!option.disabled && !option.empty) { + if (option.group) { + $(option.dom_id).hide(); + } else if (!(this.is_multiple && option.selected)) { + found = false; + result_id = option.dom_id; + if (regex.test(option.text)) { + found = true; + results += 1; + } else if (option.text.indexOf(" ") >= 0 || option.text.indexOf("[") === 0) { + parts = option.text.replace(/\[|\]/g, "").split(" "); + if (parts.length) { + for (_j = 0, _len2 = parts.length; _j < _len2; _j++) { + part = parts[_j]; + if (regex.test(part)) { + found = true; + results += 1; + } + } + } + } + if (found) { + if (searchText.length) { + startpos = option.text.search(zregex); + text = option.text.substr(0, startpos + searchText.length) + '
              ' + option.text.substr(startpos + searchText.length); + text = text.substr(0, startpos) + '' + text.substr(startpos); + } else { + text = option.text; + } + if ($(result_id).innerHTML !== text) { + $(result_id).update(text); + } + this.result_activate($(result_id)); + if (option.group_array_index != null) { + $(this.results_data[option.group_array_index].dom_id).show(); + } + } else { + if ($(result_id) === this.result_highlight) { + this.result_clear_highlight(); + } + this.result_deactivate($(result_id)); + } + } + } + } + if (results < 1 && searchText.length) { + return this.no_results(searchText); + } else { + return this.winnow_results_set_highlight(); + } + }; + Chosen.prototype.winnow_results_clear = function() { + var li, lis, _i, _len, _results; + this.search_field.clear(); + lis = this.search_results.select("li"); + _results = []; + for (_i = 0, _len = lis.length; _i < _len; _i++) { + li = lis[_i]; + _results.push(li.hasClassName("group-result") ? li.show() : !this.is_multiple || !li.hasClassName("result-selected") ? this.result_activate(li) : void 0); + } + return _results; + }; + Chosen.prototype.winnow_results_set_highlight = function() { + var do_high; + if (!this.result_highlight) { + do_high = this.search_results.down(".active-result"); + if (do_high) { + return this.result_do_highlight(do_high); + } + } + }; + Chosen.prototype.no_results = function(terms) { + return this.search_results.insert(this.no_results_temp.evaluate({ + "terms": terms.escapeHTML() + })); + }; + Chosen.prototype.no_results_clear = function() { + var nr, _results; + nr = null; + _results = []; + while (nr = this.search_results.down(".no-results")) { + _results.push(nr.remove()); + } + return _results; + }; + Chosen.prototype.keydown_arrow = function() { + var actives, nexts, sibs; + actives = this.search_results.select("li.active-result"); + if (actives.length) { + if (!this.result_highlight) { + this.result_do_highlight(actives.first()); + } else if (this.results_showing) { + sibs = this.result_highlight.nextSiblings(); + nexts = sibs.intersect(actives); + if (nexts.length) { + this.result_do_highlight(nexts.first()); + } + } + if (!this.results_showing) { + return this.results_show(); + } + } + }; + Chosen.prototype.keyup_arrow = function() { + var actives, prevs, sibs; + if (!this.results_showing && !this.is_multiple) { + return this.results_show(); + } else if (this.result_highlight) { + sibs = this.result_highlight.previousSiblings(); + actives = this.search_results.select("li.active-result"); + prevs = sibs.intersect(actives); + if (prevs.length) { + return this.result_do_highlight(prevs.first()); + } else { + if (this.choices > 0) { + this.results_hide(); + } + return this.result_clear_highlight(); + } + } + }; + Chosen.prototype.keydown_backstroke = function() { + if (this.pending_backstroke) { + this.choice_destroy(this.pending_backstroke.down("a")); + return this.clear_backstroke(); + } else { + this.pending_backstroke = this.search_container.siblings("li.search-choice").last(); + return this.pending_backstroke.addClassName("search-choice-focus"); + } + }; + Chosen.prototype.clear_backstroke = function() { + if (this.pending_backstroke) { + this.pending_backstroke.removeClassName("search-choice-focus"); + } + return this.pending_backstroke = null; + }; + Chosen.prototype.keyup_checker = function(evt) { + var stroke, _ref; + stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; + this.search_field_scale(); + switch (stroke) { + case 8: + if (this.is_multiple && this.backstroke_length < 1 && this.choices > 0) { + return this.keydown_backstroke(); + } else if (!this.pending_backstroke) { + this.result_clear_highlight(); + return this.results_search(); + } + break; + case 13: + evt.preventDefault(); + if (this.results_showing) { + return this.result_select(); + } + break; + case 27: + if (this.results_showing) { + return this.results_hide(); + } + break; + case 9: + case 38: + case 40: + case 16: + break; + default: + return this.results_search(); + } + }; + Chosen.prototype.keydown_checker = function(evt) { + var stroke, _ref; + stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; + this.search_field_scale(); + if (stroke !== 8 && this.pending_backstroke) { + this.clear_backstroke(); + } + switch (stroke) { + case 8: + return this.backstroke_length = this.search_field.value.length; + case 9: + return this.mouse_on_container = false; + case 13: + return evt.preventDefault(); + case 38: + evt.preventDefault(); + return this.keyup_arrow(); + case 40: + return this.keydown_arrow(); + } + }; + Chosen.prototype.search_field_scale = function() { + var dd_top, div, h, style, style_block, styles, w, _i, _len; + if (this.is_multiple) { + h = 0; + w = 0; + style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; + styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; + for (_i = 0, _len = styles.length; _i < _len; _i++) { + style = styles[_i]; + style_block += style + ":" + this.search_field.getStyle(style) + ";"; + } + div = new Element('div', { + 'style': style_block + }).update(this.search_field.value); + document.body.appendChild(div); + w = Element.measure(div, 'width') + 25; + div.remove(); + if (w > this.f_width - 10) { + w = this.f_width - 10; + } + this.search_field.setStyle({ + 'width': w + 'px' + }); + dd_top = this.container.getHeight(); + return this.dropdown.setStyle({ + "top": dd_top + "px" + }); + } + }; + return Chosen; + })(); + root.Chosen = Chosen; + document.observe('dom:loaded', function(evt) { + var select, selects, _i, _len, _results; + selects = $$(".chzn-select"); + _results = []; + for (_i = 0, _len = selects.length; _i < _len; _i++) { + select = selects[_i]; + _results.push(new Chosen(select)); + } + return _results; + }); + get_side_border_padding = function(elmt) { + var layout, side_border_padding; + layout = new Element.Layout(elmt); + return side_border_padding = layout.get("border-left") + layout.get("border-right") + layout.get("padding-left") + layout.get("padding-right"); + }; + root.get_side_border_padding = get_side_border_padding; + root = typeof exports !== "undefined" && exports !== null ? exports : this; + SelectParser = (function() { + function SelectParser() { + this.options_index = 0; + this.parsed = []; + } + SelectParser.prototype.add_node = function(child) { + if (child.nodeName === "OPTGROUP") { + return this.add_group(child); + } else { + return this.add_option(child); + } + }; + SelectParser.prototype.add_group = function(group) { + var group_position, option, _i, _len, _ref, _results; + group_position = this.parsed.length; + this.parsed.push({ + array_index: group_position, + group: true, + label: group.label, + children: 0, + disabled: group.disabled + }); + _ref = group.childNodes; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + option = _ref[_i]; + _results.push(this.add_option(option, group_position, group.disabled)); + } + return _results; + }; + SelectParser.prototype.add_option = function(option, group_position, group_disabled) { + if (option.nodeName === "OPTION") { + if (option.text !== "") { + if (group_position != null) { + this.parsed[group_position].children += 1; + } + this.parsed.push({ + array_index: this.parsed.length, + options_index: this.options_index, + value: option.value, + text: option.text, + selected: option.selected, + disabled: group_disabled === true ? group_disabled : option.disabled, + group_array_index: group_position + }); + } else { + this.parsed.push({ + array_index: this.parsed.length, + options_index: this.options_index, + empty: true + }); + } + return this.options_index += 1; + } + }; + return SelectParser; + })(); + SelectParser.select_to_array = function(select) { + var child, parser, _i, _len, _ref; + parser = new SelectParser(); + _ref = select.childNodes; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + child = _ref[_i]; + parser.add_node(child); + } + return parser.parsed; + }; + root.SelectParser = SelectParser; +}).call(this); diff --git a/src/usr/local/www/javascript/chosen/chosen.proto.min.js b/src/usr/local/www/javascript/chosen/chosen.proto.min.js new file mode 100644 index 0000000..79109c5 --- /dev/null +++ b/src/usr/local/www/javascript/chosen/chosen.proto.min.js @@ -0,0 +1,9 @@ +/* +Chosen, a Select Box Enhancer for jQuery and Protoype +by Patrick Filler for Harvest, http://getharvest.com + +Available for use under the MIT License, http://en.wikipedia.org/wiki/MIT_License + +Copyright (c) 2011 by Harvest +*/ +(function(){var Chosen,SelectParser,get_side_border_padding,root;var __bind=function(fn,me){return function(){return fn.apply(me,arguments);};};root=typeof exports!=="undefined"&&exports!==null?exports:this;Chosen=(function(){function Chosen(elmn){this.set_default_values();this.form_field=elmn;this.is_multiple=this.form_field.multiple;this.default_text_default=this.form_field.multiple?"Select Some Options":"Select an Option";this.set_up_html();this.register_observers();}Chosen.prototype.set_default_values=function(){this.click_test_action=__bind(function(evt){return this.test_active_click(evt);},this);this.active_field=false;this.mouse_on_container=false;this.results_showing=false;this.result_highlighted=null;this.result_single_selected=null;this.choices=0;this.single_temp=new Template('#{default}
                ');this.multi_temp=new Template('
                  ');this.choice_temp=new Template('
                • #{choice}
                • ');return this.no_results_temp=new Template('
                • No results match "#{terms}"
                • ');};Chosen.prototype.set_up_html=function(){var base_template,container_props,dd_top,dd_width,sf_width;this.container_id=this.form_field.id+"_chzn";this.f_width=this.form_field.getStyle("width")?parseInt(this.form_field.getStyle("width"),10):this.form_field.getWidth();container_props={id:this.container_id,"class":"chzn-container",style:"width: "+this.f_width+"px"};this.default_text=this.form_field.readAttribute("title")?this.form_field.readAttribute("title"):this.default_text_default;base_template=this.is_multiple?new Element("div",container_props).update(this.multi_temp.evaluate({"default":this.default_text})):new Element("div",container_props).update(this.single_temp.evaluate({"default":this.default_text}));this.form_field.hide().insert({after:base_template});this.container=$(this.container_id);this.container.addClassName("chzn-container-"+(this.is_multiple?"multi":"single"));this.dropdown=this.container.down("div.chzn-drop");dd_top=this.container.getHeight();dd_width=this.f_width-get_side_border_padding(this.dropdown);this.dropdown.setStyle({width:dd_width+"px",top:dd_top+"px"});this.search_field=this.container.down("input");this.search_results=this.container.down("ul.chzn-results");this.search_field_scale();this.search_no_results=this.container.down("li.no-results");if(this.is_multiple){this.search_choices=this.container.down("ul.chzn-choices");this.search_container=this.container.down("li.search-field");}else{this.search_container=this.container.down("div.chzn-search");this.selected_item=this.container.down(".chzn-single");sf_width=dd_width-get_side_border_padding(this.search_container)-get_side_border_padding(this.search_field);this.search_field.setStyle({width:sf_width+"px"});}this.results_build();return this.set_tab_index();};Chosen.prototype.register_observers=function(){this.container.observe("click",__bind(function(evt){return this.container_click(evt);},this));this.container.observe("mouseenter",__bind(function(evt){return this.mouse_enter(evt);},this));this.container.observe("mouseleave",__bind(function(evt){return this.mouse_leave(evt);},this));this.search_results.observe("click",__bind(function(evt){return this.search_results_click(evt);},this));this.search_results.observe("mouseover",__bind(function(evt){return this.search_results_mouseover(evt);},this));this.search_results.observe("mouseout",__bind(function(evt){return this.search_results_mouseout(evt);},this));this.form_field.observe("liszt:updated",__bind(function(evt){return this.results_update_field(evt);},this));this.search_field.observe("blur",__bind(function(evt){return this.input_blur(evt);},this));this.search_field.observe("keyup",__bind(function(evt){return this.keyup_checker(evt);},this));this.search_field.observe("keydown",__bind(function(evt){return this.keydown_checker(evt);},this));if(this.is_multiple){this.search_choices.observe("click",__bind(function(evt){return this.choices_click(evt);},this));return this.search_field.observe("focus",__bind(function(evt){return this.input_focus(evt);},this));}else{return this.selected_item.observe("focus",__bind(function(evt){return this.activate_field(evt);},this));}};Chosen.prototype.container_click=function(evt){if(evt&&evt.type==="click"){evt.stop();}if(!this.pending_destroy_click){if(!this.active_field){if(this.is_multiple){this.search_field.clear();}document.observe("click",this.click_test_action);this.results_show();}else{if(!this.is_multiple&&evt&&(evt.target===this.selected_item||evt.target.up("a.chzn-single"))){this.results_toggle();}}return this.activate_field();}else{return this.pending_destroy_click=false;}};Chosen.prototype.mouse_enter=function(){return this.mouse_on_container=true;};Chosen.prototype.mouse_leave=function(){return this.mouse_on_container=false;};Chosen.prototype.input_focus=function(evt){if(!this.active_field){return setTimeout(this.container_click.bind(this),50);}};Chosen.prototype.input_blur=function(evt){if(!this.mouse_on_container){this.active_field=false;return setTimeout(this.blur_test.bind(this),100);}};Chosen.prototype.blur_test=function(evt){if(!this.active_field&&this.container.hasClassName("chzn-container-active")){return this.close_field();}};Chosen.prototype.close_field=function(){document.stopObserving("click",this.click_test_action);if(!this.is_multiple){this.selected_item.tabIndex=this.search_field.tabIndex;this.search_field.tabIndex=-1;}this.active_field=false;this.results_hide();this.container.removeClassName("chzn-container-active");this.winnow_results_clear();this.clear_backstroke();this.show_search_field_default();return this.search_field_scale();};Chosen.prototype.activate_field=function(){if(!this.is_multiple&&!this.active_field){this.search_field.tabIndex=this.selected_item.tabIndex;this.selected_item.tabIndex=-1;}this.container.addClassName("chzn-container-active");this.active_field=true;this.search_field.value=this.search_field.value;return this.search_field.focus();};Chosen.prototype.test_active_click=function(evt){if(evt.target.up("#"+this.container.id)){return this.active_field=true;}else{return this.close_field();}};Chosen.prototype.results_build=function(){var content,data,startTime,_i,_len,_ref;startTime=new Date();this.parsing=true;this.results_data=SelectParser.select_to_array(this.form_field);if(this.is_multiple&&this.choices>0){this.search_choices.select("li.search-choice").invoke("remove");this.choices=0;}else{if(!this.is_multiple){this.selected_item.down("span").update(this.default_text);}}content="";_ref=this.results_data;for(_i=0,_len=_ref.length;_i<_len;_i++){data=_ref[_i];if(data.group){content+=this.result_add_group(data);}else{if(!data.empty){content+=this.result_add_option(data);if(data.selected&&this.is_multiple){this.choice_build(data);}else{if(data.selected&&!this.is_multiple){this.selected_item.down("span").update(data.text);}}}}}this.show_search_field_default();this.search_field_scale();this.search_results.update(content);return this.parsing=false;};Chosen.prototype.result_add_group=function(group){if(!group.disabled){group.dom_id=this.form_field.id+"chzn_g_"+group.array_index;return'
                • '+group.label.escapeHTML()+"
                • ";}else{return"";}};Chosen.prototype.result_add_option=function(option){var classes;if(!option.disabled){option.dom_id=this.form_field.id+"chzn_o_"+option.array_index;classes=option.selected&&this.is_multiple?[]:["active-result"];if(option.selected){classes.push("result-selected");}if(option.group_array_index!=null){classes.push("group-option");}return'
                • '+option.text.escapeHTML()+"
                • ";}else{return"";}};Chosen.prototype.results_update_field=function(){this.result_clear_highlight();this.result_single_selected=null;return this.results_build();};Chosen.prototype.result_do_highlight=function(el){var high_bottom,high_top,maxHeight,visible_bottom,visible_top;this.result_clear_highlight();this.result_highlight=el;this.result_highlight.addClassName("highlighted");maxHeight=parseInt(this.search_results.getStyle("maxHeight"),10);visible_top=this.search_results.scrollTop;visible_bottom=maxHeight+visible_top;high_top=this.result_highlight.positionedOffset().top;high_bottom=high_top+this.result_highlight.getHeight();if(high_bottom>=visible_bottom){return this.search_results.scrollTop=(high_bottom-maxHeight)>0?high_bottom-maxHeight:0;}else{if(high_top0&&this.search_field.value.length<1){this.results_hide();}this.result_deselect(link.readAttribute("rel"));return link.up("li").remove();};Chosen.prototype.result_select=function(){var high,item,position;if(this.result_highlight){high=this.result_highlight;this.result_clear_highlight();high.addClassName("result-selected");if(this.is_multiple){this.result_deactivate(high);}else{this.result_single_selected=high;}position=high.id.substr(high.id.lastIndexOf("_")+1);item=this.results_data[position];item.selected=true;this.form_field.options[item.options_index].selected=true;if(this.is_multiple){this.choice_build(item);}else{this.selected_item.down("span").update(item.text);}this.results_hide();this.search_field.value="";if(typeof Event.simulate==="function"){this.form_field.simulate("change");}return this.search_field_scale();}};Chosen.prototype.result_activate=function(el){return el.addClassName("active-result").show();};Chosen.prototype.result_deactivate=function(el){return el.removeClassName("active-result").hide();};Chosen.prototype.result_deselect=function(pos){var result,result_data;result_data=this.results_data[pos];result_data.selected=false;this.form_field.options[result_data.options_index].selected=false;result=$(this.form_field.id+"chzn_o_"+pos);result.removeClassName("result-selected").addClassName("active-result").show();this.result_clear_highlight();this.winnow_results();if(typeof Event.simulate==="function"){this.form_field.simulate("change");}return this.search_field_scale();};Chosen.prototype.results_search=function(evt){if(this.results_showing){return this.winnow_results();}else{return this.results_show();}};Chosen.prototype.winnow_results=function(){var found,option,part,parts,regex,result_id,results,searchText,startTime,startpos,text,zregex,_i,_j,_len,_len2,_ref;startTime=new Date();this.no_results_clear();results=0;searchText=this.search_field.value===this.default_text?"":this.search_field.value.strip();regex=new RegExp("^"+searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i");zregex=new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i");_ref=this.results_data;for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];if(!option.disabled&&!option.empty){if(option.group){$(option.dom_id).hide();}else{if(!(this.is_multiple&&option.selected)){found=false;result_id=option.dom_id;if(regex.test(option.text)){found=true;results+=1;}else{if(option.text.indexOf(" ")>=0||option.text.indexOf("[")===0){parts=option.text.replace(/\[|\]/g,"").split(" ");if(parts.length){for(_j=0,_len2=parts.length;_j<_len2;_j++){part=parts[_j];if(regex.test(part)){found=true;results+=1;}}}}}if(found){if(searchText.length){startpos=option.text.search(zregex);text=option.text.substr(0,startpos+searchText.length)+"
                  "+option.text.substr(startpos+searchText.length);text=text.substr(0,startpos)+""+text.substr(startpos);}else{text=option.text;}if($(result_id).innerHTML!==text){$(result_id).update(text);}this.result_activate($(result_id));if(option.group_array_index!=null){$(this.results_data[option.group_array_index].dom_id).show();}}else{if($(result_id)===this.result_highlight){this.result_clear_highlight();}this.result_deactivate($(result_id));}}}}}if(results<1&&searchText.length){return this.no_results(searchText);}else{return this.winnow_results_set_highlight();}};Chosen.prototype.winnow_results_clear=function(){var li,lis,_i,_len,_results;this.search_field.clear();lis=this.search_results.select("li");_results=[];for(_i=0,_len=lis.length;_i<_len;_i++){li=lis[_i];_results.push(li.hasClassName("group-result")?li.show():!this.is_multiple||!li.hasClassName("result-selected")?this.result_activate(li):void 0);}return _results;};Chosen.prototype.winnow_results_set_highlight=function(){var do_high;if(!this.result_highlight){do_high=this.search_results.down(".active-result");if(do_high){return this.result_do_highlight(do_high);}}};Chosen.prototype.no_results=function(terms){return this.search_results.insert(this.no_results_temp.evaluate({terms:terms.escapeHTML()}));};Chosen.prototype.no_results_clear=function(){var nr,_results;nr=null;_results=[];while(nr=this.search_results.down(".no-results")){_results.push(nr.remove());}return _results;};Chosen.prototype.keydown_arrow=function(){var actives,nexts,sibs;actives=this.search_results.select("li.active-result");if(actives.length){if(!this.result_highlight){this.result_do_highlight(actives.first());}else{if(this.results_showing){sibs=this.result_highlight.nextSiblings();nexts=sibs.intersect(actives);if(nexts.length){this.result_do_highlight(nexts.first());}}}if(!this.results_showing){return this.results_show();}}};Chosen.prototype.keyup_arrow=function(){var actives,prevs,sibs;if(!this.results_showing&&!this.is_multiple){return this.results_show();}else{if(this.result_highlight){sibs=this.result_highlight.previousSiblings();actives=this.search_results.select("li.active-result");prevs=sibs.intersect(actives);if(prevs.length){return this.result_do_highlight(prevs.first());}else{if(this.choices>0){this.results_hide();}return this.result_clear_highlight();}}}};Chosen.prototype.keydown_backstroke=function(){if(this.pending_backstroke){this.choice_destroy(this.pending_backstroke.down("a"));return this.clear_backstroke();}else{this.pending_backstroke=this.search_container.siblings("li.search-choice").last();return this.pending_backstroke.addClassName("search-choice-focus");}};Chosen.prototype.clear_backstroke=function(){if(this.pending_backstroke){this.pending_backstroke.removeClassName("search-choice-focus");}return this.pending_backstroke=null;};Chosen.prototype.keyup_checker=function(evt){var stroke,_ref;stroke=(_ref=evt.which)!=null?_ref:evt.keyCode;this.search_field_scale();switch(stroke){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices>0){return this.keydown_backstroke();}else{if(!this.pending_backstroke){this.result_clear_highlight();return this.results_search();}}break;case 13:evt.preventDefault();if(this.results_showing){return this.result_select();}break;case 27:if(this.results_showing){return this.results_hide();}break;case 9:case 38:case 40:case 16:break;default:return this.results_search();}};Chosen.prototype.keydown_checker=function(evt){var stroke,_ref;stroke=(_ref=evt.which)!=null?_ref:evt.keyCode;this.search_field_scale();if(stroke!==8&&this.pending_backstroke){this.clear_backstroke();}switch(stroke){case 8:return this.backstroke_length=this.search_field.value.length;case 9:return this.mouse_on_container=false;case 13:return evt.preventDefault();case 38:evt.preventDefault();return this.keyup_arrow();case 40:return this.keydown_arrow();}};Chosen.prototype.search_field_scale=function(){var dd_top,div,h,style,style_block,styles,w,_i,_len;if(this.is_multiple){h=0;w=0;style_block="position:absolute; left: -1000px; top: -1000px; display:none;";styles=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"];for(_i=0,_len=styles.length;_i<_len;_i++){style=styles[_i];style_block+=style+":"+this.search_field.getStyle(style)+";";}div=new Element("div",{style:style_block}).update(this.search_field.value);document.body.appendChild(div);w=Element.measure(div,"width")+25;div.remove();if(w>this.f_width-10){w=this.f_width-10;}this.search_field.setStyle({width:w+"px"});dd_top=this.container.getHeight();return this.dropdown.setStyle({top:dd_top+"px"});}};return Chosen;})();root.Chosen=Chosen;document.observe("dom:loaded",function(evt){var select,selects,_i,_len,_results;selects=$$(".chzn-select");_results=[];for(_i=0,_len=selects.length;_i<_len;_i++){select=selects[_i];_results.push(new Chosen(select));}return _results;});get_side_border_padding=function(elmt){var layout,side_border_padding;layout=new Element.Layout(elmt);return side_border_padding=layout.get("border-left")+layout.get("border-right")+layout.get("padding-left")+layout.get("padding-right");};root.get_side_border_padding=get_side_border_padding;root=typeof exports!=="undefined"&&exports!==null?exports:this;SelectParser=(function(){function SelectParser(){this.options_index=0;this.parsed=[];}SelectParser.prototype.add_node=function(child){if(child.nodeName==="OPTGROUP"){return this.add_group(child);}else{return this.add_option(child);}};SelectParser.prototype.add_group=function(group){var group_position,option,_i,_len,_ref,_results;group_position=this.parsed.length;this.parsed.push({array_index:group_position,group:true,label:group.label,children:0,disabled:group.disabled});_ref=group.childNodes;_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];_results.push(this.add_option(option,group_position,group.disabled));}return _results;};SelectParser.prototype.add_option=function(option,group_position,group_disabled){if(option.nodeName==="OPTION"){if(option.text!==""){if(group_position!=null){this.parsed[group_position].children+=1;}this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:option.value,text:option.text,selected:option.selected,disabled:group_disabled===true?group_disabled:option.disabled,group_array_index:group_position});}else{this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:true});}return this.options_index+=1;}};return SelectParser;})();SelectParser.select_to_array=function(select){var child,parser,_i,_len,_ref;parser=new SelectParser();_ref=select.childNodes;for(_i=0,_len=_ref.length;_i<_len;_i++){child=_ref[_i];parser.add_node(child);}return parser.parsed;};root.SelectParser=SelectParser;}).call(this); \ No newline at end of file diff --git a/src/usr/local/www/javascript/chosen/coffee/chosen.jquery.coffee b/src/usr/local/www/javascript/chosen/coffee/chosen.jquery.coffee new file mode 100644 index 0000000..0d6596a --- /dev/null +++ b/src/usr/local/www/javascript/chosen/coffee/chosen.jquery.coffee @@ -0,0 +1,633 @@ +### +Chosen, a Select Box Enhancer for jQuery and Protoype +by Patrick Filler for Harvest, http://getharvest.com + +Available for use under the MIT License, http://en.wikipedia.org/wiki/MIT_License + +Copyright (c) 2011 by Harvest +### + +root = exports ? this +$ = jQuery + +$.fn.extend({ + chosen: (data, options) -> + $(this).each((input_field) -> + new Chosen(this, data, options) unless ($ this).hasClass "chzn-done" + ) +}) + +class Chosen + + constructor: (elmn) -> + this.set_default_values() + + @form_field = elmn + @form_field_jq = $ @form_field + @is_multiple = @form_field.multiple + + @default_text_default = if @form_field.multiple then "Select Some Options" else "Select an Option" + + this.set_up_html() + this.register_observers() + @form_field_jq.addClass "chzn-done" + + set_default_values: -> + + @click_test_action = (evt) => this.test_active_click(evt) + @active_field = false + @mouse_on_container = false + @results_showing = false + @result_highlighted = null + @result_single_selected = null + @choices = 0 + + set_up_html: -> + @container_id = @form_field.id + "_chzn" + + @f_width = @form_field_jq.width() + + @default_text = if @form_field_jq.attr 'title' then @form_field_jq.attr 'title' else @default_text_default + + container_div = ($ "
                  ", { + id: @container_id + class: 'chzn-container' + style: 'width: ' + (@f_width) + 'px;' #use parens around @f_width so coffeescript doesn't think + ' px' is a function parameter + }) + + if @is_multiple + container_div.html '
                    ' + else + container_div.html '' + @default_text + '
                      ' + + @form_field_jq.hide().after container_div + @container = ($ '#' + @container_id) + @container.addClass( "chzn-container-" + (if @is_multiple then "multi" else "single") ) + @dropdown = @container.find('div.chzn-drop').first() + + dd_top = @container.height() + dd_width = (@f_width - get_side_border_padding(@dropdown)) + + @dropdown.css({"width": dd_width + "px", "top": dd_top + "px"}) + + @search_field = @container.find('input').first() + @search_results = @container.find('ul.chzn-results').first() + this.search_field_scale() + + @search_no_results = @container.find('li.no-results').first() + + if @is_multiple + @search_choices = @container.find('ul.chzn-choices').first() + @search_container = @container.find('li.search-field').first() + else + @search_container = @container.find('div.chzn-search').first() + @selected_item = @container.find('.chzn-single').first() + sf_width = dd_width - get_side_border_padding(@search_container) - get_side_border_padding(@search_field) + @search_field.css( {"width" : sf_width + "px"} ) + + this.results_build() + this.set_tab_index() + + + register_observers: -> + @container.click (evt) => this.container_click(evt) + @container.mouseenter (evt) => this.mouse_enter(evt) + @container.mouseleave (evt) => this.mouse_leave(evt) + + @search_results.click (evt) => this.search_results_click(evt) + @search_results.mouseover (evt) => this.search_results_mouseover(evt) + @search_results.mouseout (evt) => this.search_results_mouseout(evt) + + @form_field_jq.bind "liszt:updated", (evt) => this.results_update_field(evt) + + @search_field.blur (evt) => this.input_blur(evt) + @search_field.keyup (evt) => this.keyup_checker(evt) + @search_field.keydown (evt) => this.keydown_checker(evt) + + if @is_multiple + @search_choices.click (evt) => this.choices_click(evt) + @search_field.focus (evt) => this.input_focus(evt) + else + @selected_item.focus (evt) => this.activate_field(evt) + + container_click: (evt) -> + if evt and evt.type is "click" + evt.stopPropagation() + if not @pending_destroy_click + if not @active_field + @search_field.val "" if @is_multiple + $(document).click @click_test_action + this.results_show() + else if not @is_multiple and evt and ($(evt.target) is @selected_item || $(evt.target).parents("a.chzn-single").length) + evt.preventDefault() + this.results_toggle() + + this.activate_field() + else + @pending_destroy_click = false + + mouse_enter: -> @mouse_on_container = true + mouse_leave: -> @mouse_on_container = false + + input_focus: (evt) -> + setTimeout (=> this.container_click()), 50 unless @active_field + + input_blur: (evt) -> + if not @mouse_on_container + @active_field = false + setTimeout (=> this.blur_test()), 100 + + blur_test: (evt) -> + this.close_field() if not @active_field and @container.hasClass "chzn-container-active" + + close_field: -> + $(document).unbind "click", @click_test_action + + if not @is_multiple + @selected_item.attr "tabindex", @search_field.attr("tabindex") + @search_field.attr "tabindex", -1 + + @active_field = false + this.results_hide() + + @container.removeClass "chzn-container-active" + this.winnow_results_clear() + this.clear_backstroke() + + this.show_search_field_default() + this.search_field_scale() + + activate_field: -> + if not @is_multiple and not @active_field + @search_field.attr "tabindex", (@selected_item.attr "tabindex") + @selected_item.attr "tabindex", -1 + + @container.addClass "chzn-container-active" + @active_field = true + + @search_field.val(@search_field.val()) + @search_field.focus() + + + test_active_click: (evt) -> + if $(evt.target).parents('#' + @container.id).length + @active_field = true + else + this.close_field() + + results_build: -> + startTime = new Date() + @parsing = true + @results_data = SelectParser.select_to_array @form_field + + if @is_multiple and @choices > 0 + @search_choices.find("li.search-choice").remove() + @choices = 0 + else if not @is_multiple + @selected_item.find("span").text @default_text + + content = '' + for data in @results_data + if data.group + content += this.result_add_group data + else if !data.empty + content += this.result_add_option data + if data.selected and @is_multiple + this.choice_build data + else if data.selected and not @is_multiple + @selected_item.find("span").text data.text + + this.show_search_field_default() + this.search_field_scale() + + @search_results.html content + @parsing = false + + + result_add_group: (group) -> + if not group.disabled + group.dom_id = @form_field.id + "chzn_g_" + group.array_index + '
                    • ' + $("
                      ").text(group.label).html() + '
                    • ' + else + "" + + result_add_option: (option) -> + if not option.disabled + option.dom_id = @form_field.id + "chzn_o_" + option.array_index + + classes = if option.selected and @is_multiple then [] else ["active-result"] + classes.push "result-selected" if option.selected + classes.push "group-option" if option.group_array_index? + + '
                    • ' + $("
                      ").text(option.text).html() + '
                    • ' + else + "" + + results_update_field: -> + this.result_clear_highlight() + @result_single_selected = null + this.results_build() + + result_do_highlight: (el) -> + if el.length + this.result_clear_highlight() + + @result_highlight = el + @result_highlight.addClass "highlighted" + + maxHeight = parseInt @search_results.css("maxHeight"), 10 + visible_top = @search_results.scrollTop() + visible_bottom = maxHeight + visible_top + + high_top = @result_highlight.position().top + @search_results.scrollTop() + high_bottom = high_top + @result_highlight.outerHeight() + + if high_bottom >= visible_bottom + @search_results.scrollTop if (high_bottom - maxHeight) > 0 then (high_bottom - maxHeight) else 0 + else if high_top < visible_top + @search_results.scrollTop high_top + + result_clear_highlight: -> + @result_highlight.removeClass "highlighted" if @result_highlight + @result_highlight = null + + results_toggle: -> + if @results_showing + this.results_hide() + else + this.results_show() + + results_show: -> + if not @is_multiple + @selected_item.addClass "chzn-single-with-drop" + if @result_single_selected + this.result_do_highlight( @result_single_selected ) + + dd_top = if @is_multiple then @container.height() else (@container.height() - 1) + @dropdown.css {"top": dd_top + "px", "left":0} + @results_showing = true + + @search_field.focus() + @search_field.val @search_field.val() + + this.winnow_results() + + results_hide: -> + @selected_item.removeClass "chzn-single-with-drop" unless @is_multiple + this.result_clear_highlight() + @dropdown.css {"left":"-9000px"} + @results_showing = false + + + set_tab_index: (el) -> + if @form_field_jq.attr "tabindex" + ti = @form_field_jq.attr "tabindex" + @form_field_jq.attr "tabindex", -1 + + if @is_multiple + @search_field.attr "tabindex", ti + else + @selected_item.attr "tabindex", ti + @search_field.attr "tabindex", -1 + + show_search_field_default: -> + if @is_multiple and @choices < 1 and not @active_field + @search_field.val(@default_text) + @search_field.addClass "default" + else + @search_field.val("") + @search_field.removeClass "default" + + search_results_click: (evt) -> + target = if $(evt.target).hasClass "active-result" then $(evt.target) else $(evt.target).parents(".active-result").first() + if target.length + @result_highlight = target + this.result_select() + + search_results_mouseover: (evt) -> + target = if $(evt.target).hasClass "active-result" then $(evt.target) else $(evt.target).parents(".active-result").first() + this.result_do_highlight( target ) if target + + search_results_mouseout: (evt) -> + this.result_clear_highlight() if $(evt.target).hasClass "active-result" or $(evt.target).parents('.active-result').first() + + + choices_click: (evt) -> + evt.preventDefault() + if( @active_field and not($(evt.target).hasClass "search-choice" or $(evt.target).parents('.search-choice').first) and not @results_showing ) + this.results_show() + + choice_build: (item) -> + choice_id = @form_field.id + "_chzn_c_" + item.array_index + @choices += 1 + @search_container.before '
                    • ' + item.text + '
                    • ' + link = $('#' + choice_id).find("a").first() + link.click (evt) => this.choice_destroy_link_click(evt) + + choice_destroy_link_click: (evt) -> + evt.preventDefault() + @pending_destroy_click = true + this.choice_destroy $(evt.target) + + choice_destroy: (link) -> + @choices -= 1 + this.show_search_field_default() + + this.results_hide() if @is_multiple and @choices > 0 and @search_field.val().length < 1 + + this.result_deselect (link.attr "rel") + link.parents('li').first().remove() + + result_select: -> + if @result_highlight + high = @result_highlight + high_id = high.attr "id" + + this.result_clear_highlight() + + high.addClass "result-selected" + + if @is_multiple + this.result_deactivate high + else + @result_single_selected = high + + position = high_id.substr(high_id.lastIndexOf("_") + 1 ) + item = @results_data[position] + item.selected = true + + @form_field.options[item.options_index].selected = true + + if @is_multiple + this.choice_build item + else + @selected_item.find("span").first().text item.text + + this.results_hide() + @search_field.val "" + + @form_field_jq.trigger "change" + this.search_field_scale() + + result_activate: (el) -> + el.addClass("active-result").show() + + result_deactivate: (el) -> + el.removeClass("active-result").hide() + + result_deselect: (pos) -> + result_data = @results_data[pos] + result_data.selected = false + + @form_field.options[result_data.options_index].selected = false + result = $("#" + @form_field.id + "chzn_o_" + pos) + result.removeClass("result-selected").addClass("active-result").show() + + this.result_clear_highlight() + this.winnow_results() + + @form_field_jq.trigger "change" + this.search_field_scale() + + results_search: (evt) -> + if @results_showing + this.winnow_results() + else + this.results_show() + + winnow_results: -> + startTime = new Date() + this.no_results_clear() + + results = 0 + + searchText = if @search_field.val() is @default_text then "" else $.trim @search_field.val() + regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i') + zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i') + + for option in @results_data + if not option.disabled and not option.empty + if option.group + $('#' + option.dom_id).hide() + else if not (@is_multiple and option.selected) + found = false + result_id = option.dom_id + + if regex.test option.text + found = true + results += 1 + else if option.text.indexOf(" ") >= 0 or option.text.indexOf("[") == 0 + #TODO: replace this substitution of /\[\]/ with a list of characters to skip. + parts = option.text.replace(/\[|\]/g, "").split(" ") + if parts.length + for part in parts + if regex.test part + found = true + results += 1 + + if found + if searchText.length + startpos = option.text.search zregex + text = option.text.substr(0, startpos + searchText.length) + '
                      ' + option.text.substr(startpos + searchText.length) + text = text.substr(0, startpos) + '' + text.substr(startpos) + else + text = option.text + + $("#" + result_id).html text if $("#" + result_id).html != text + + this.result_activate $("#" + result_id) + + $("#" + @results_data[option.group_array_index].dom_id).show() if option.group_array_index? + else + this.result_clear_highlight() if @result_highlight and result_id is @result_highlight.attr 'id' + this.result_deactivate $("#" + result_id) + + if results < 1 and searchText.length + this.no_results searchText + else + this.winnow_results_set_highlight() + + winnow_results_clear: -> + @search_field.val "" + lis = @search_results.find("li") + + for li in lis + li = $(li) + if li.hasClass "group-result" + li.show() + else if not @is_multiple or not li.hasClass "result-selected" + this.result_activate li + + winnow_results_set_highlight: -> + if not @result_highlight + do_high = @search_results.find(".active-result").first() + if(do_high) + this.result_do_highlight do_high + + no_results: (terms) -> + no_results_html = $('
                    • No results match ""
                    • ') + no_results_html.find("span").first().text(terms) + + @search_results.append no_results_html + + no_results_clear: -> + @search_results.find(".no-results").remove() + + keydown_arrow: -> + if not @result_highlight + first_active = @search_results.find("li.active-result").first() + this.result_do_highlight $(first_active) if first_active + else if @results_showing + next_sib = @result_highlight.nextAll("li.active-result").first() + this.result_do_highlight next_sib if next_sib + this.results_show() if not @results_showing + + keyup_arrow: -> + if not @results_showing and not @is_multiple + this.results_show() + else if @result_highlight + prev_sibs = @result_highlight.prevAll("li.active-result") + + if prev_sibs.length + this.result_do_highlight prev_sibs.first() + else + this.results_hide() if @choices > 0 + this.result_clear_highlight() + + keydown_backstroke: -> + if @pending_backstroke + this.choice_destroy @pending_backstroke.find("a").first() + this.clear_backstroke() + else + @pending_backstroke = @search_container.siblings("li.search-choice").last() + @pending_backstroke.addClass "search-choice-focus" + + clear_backstroke: -> + @pending_backstroke.removeClass "search-choice-focus" if @pending_backstroke + @pending_backstroke = null + + keyup_checker: (evt) -> + stroke = evt.which ? evt.keyCode + this.search_field_scale() + + switch stroke + when 8 + if @is_multiple and @backstroke_length < 1 and @choices > 0 + this.keydown_backstroke() + else if not @pending_backstroke + this.result_clear_highlight() + this.results_search() + when 13 + evt.preventDefault() + this.result_select() if this.results_showing + when 27 + this.results_hide() if @results_showing + when 9, 38, 40, 16 + # don't do anything on these keys + else this.results_search() + + + keydown_checker: (evt) -> + stroke = evt.which ? evt.keyCode + this.search_field_scale() + + this.clear_backstroke() if stroke != 8 and this.pending_backstroke + + switch stroke + when 8 + @backstroke_length = this.search_field.val().length + break + when 9 + @mouse_on_container = false + break + when 13 + evt.preventDefault() + break + when 38 + evt.preventDefault() + this.keyup_arrow() + break + when 40 + this.keydown_arrow() + break + + + search_field_scale: -> + if @is_multiple + h = 0 + w = 0 + + style_block = "position:absolute; left: -1000px; top: -1000px; display:none;" + styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'] + + for style in styles + style_block += style + ":" + @search_field.css(style) + ";" + + div = $('
                      ', { 'style' : style_block }) + div.text @search_field.val() + $('body').append div + + w = div.width() + 25 + div.remove() + + if( w > @f_width-10 ) + w = @f_width - 10 + + @search_field.css({'width': w + 'px'}) + + dd_top = @container.height() + @dropdown.css({"top": dd_top + "px"}) + +get_side_border_padding = (elmt) -> + side_border_padding = elmt.outerWidth() - elmt.width() + +root.get_side_border_padding = get_side_border_padding + +class SelectParser + + constructor: -> + @options_index = 0 + @parsed = [] + + add_node: (child) -> + if child.nodeName is "OPTGROUP" + this.add_group child + else + this.add_option child + + add_group: (group) -> + group_position = @parsed.length + @parsed.push + array_index: group_position + group: true + label: group.label + children: 0 + disabled: group.disabled + this.add_option( option, group_position, group.disabled ) for option in group.childNodes + + add_option: (option, group_position, group_disabled) -> + if option.nodeName is "OPTION" + if option.text != "" + if group_position? + @parsed[group_position].children += 1 + @parsed.push + array_index: @parsed.length + options_index: @options_index + value: option.value + text: option.text + selected: option.selected + disabled: if group_disabled is true then group_disabled else option.disabled + group_array_index: group_position + else + @parsed.push + array_index: @parsed.length + options_index: @options_index + empty: true + @options_index += 1 + +SelectParser.select_to_array = (select) -> + parser = new SelectParser() + parser.add_node( child ) for child in select.childNodes + parser.parsed + +root.SelectParser = SelectParser diff --git a/src/usr/local/www/javascript/chosen/coffee/chosen.proto.coffee b/src/usr/local/www/javascript/chosen/coffee/chosen.proto.coffee new file mode 100644 index 0000000..87a22b6 --- /dev/null +++ b/src/usr/local/www/javascript/chosen/coffee/chosen.proto.coffee @@ -0,0 +1,629 @@ +### +Chosen, a Select Box Enhancer for jQuery and Protoype +by Patrick Filler for Harvest, http://getharvest.com + +Available for use under the MIT License, http://en.wikipedia.org/wiki/MIT_License + +Copyright (c) 2011 by Harvest +### + +root = exports ? this + +class Chosen + + constructor: (elmn) -> + this.set_default_values() + + @form_field = elmn + @is_multiple = @form_field.multiple + + @default_text_default = if @form_field.multiple then "Select Some Options" else "Select an Option" + + this.set_up_html() + this.register_observers() + + + set_default_values: -> + + @click_test_action = (evt) => this.test_active_click(evt) + @active_field = false + @mouse_on_container = false + @results_showing = false + @result_highlighted = null + @result_single_selected = null + @choices = 0 + + # HTML Templates + @single_temp = new Template('#{default}
                        ') + @multi_temp = new Template('
                          ') + @choice_temp = new Template('
                        • #{choice}
                        • ') + @no_results_temp = new Template('
                        • No results match "#{terms}"
                        • ') + + + set_up_html: -> + @container_id = @form_field.id + "_chzn" + + @f_width = if @form_field.getStyle("width") then parseInt @form_field.getStyle("width"), 10 else @form_field.getWidth() + + container_props = + 'id': @container_id + 'class': 'chzn-container' + 'style': 'width: ' + (@f_width) + 'px' #use parens around @f_width so coffeescript doesn't think + ' px' is a function parameter + + @default_text = if @form_field.readAttribute 'title' then @form_field.readAttribute 'title' else @default_text_default + + base_template = if @is_multiple then new Element('div', container_props).update( @multi_temp.evaluate({ "default": @default_text}) ) else new Element('div', container_props).update( @single_temp.evaluate({ "default":@default_text }) ) + + @form_field.hide().insert({ after: base_template }) + @container = $(@container_id) + @container.addClassName( "chzn-container-" + (if @is_multiple then "multi" else "single") ) + @dropdown = @container.down('div.chzn-drop') + + dd_top = @container.getHeight() + dd_width = (@f_width - get_side_border_padding(@dropdown)) + + @dropdown.setStyle({"width": dd_width + "px", "top": dd_top + "px"}) + + @search_field = @container.down('input') + @search_results = @container.down('ul.chzn-results') + this.search_field_scale() + + @search_no_results = @container.down('li.no-results') + + if @is_multiple + @search_choices = @container.down('ul.chzn-choices') + @search_container = @container.down('li.search-field') + else + @search_container = @container.down('div.chzn-search') + @selected_item = @container.down('.chzn-single') + sf_width = dd_width - get_side_border_padding(@search_container) - get_side_border_padding(@search_field) + @search_field.setStyle( {"width" : sf_width + "px"} ) + + this.results_build() + this.set_tab_index() + + + register_observers: -> + @container.observe "click", (evt) => this.container_click(evt) + @container.observe "mouseenter", (evt) => this.mouse_enter(evt) + @container.observe "mouseleave", (evt) => this.mouse_leave(evt) + + @search_results.observe "click", (evt) => this.search_results_click(evt) + @search_results.observe "mouseover", (evt) => this.search_results_mouseover(evt) + @search_results.observe "mouseout", (evt) => this.search_results_mouseout(evt) + + @form_field.observe "liszt:updated", (evt) => this.results_update_field(evt) + + @search_field.observe "blur", (evt) => this.input_blur(evt) + @search_field.observe "keyup", (evt) => this.keyup_checker(evt) + @search_field.observe "keydown", (evt) => this.keydown_checker(evt) + + if @is_multiple + @search_choices.observe "click", (evt) => this.choices_click(evt) + @search_field.observe "focus", (evt) => this.input_focus(evt) + else + @selected_item.observe "focus", (evt) => this.activate_field(evt) + + + container_click: (evt) -> + if evt and evt.type is "click" + evt.stop() + if not @pending_destroy_click + if not @active_field + @search_field.clear() if @is_multiple + document.observe "click", @click_test_action + this.results_show() + else if not @is_multiple and evt and (evt.target is @selected_item || evt.target.up("a.chzn-single")) + this.results_toggle() + + this.activate_field() + else + @pending_destroy_click = false + + mouse_enter: -> @mouse_on_container = true + mouse_leave: -> @mouse_on_container = false + + input_focus: (evt) -> + setTimeout this.container_click.bind(this), 50 unless @active_field + + input_blur: (evt) -> + if not @mouse_on_container + @active_field = false + setTimeout this.blur_test.bind(this), 100 + + blur_test: (evt) -> + this.close_field() if not @active_field and @container.hasClassName("chzn-container-active") + + close_field: -> + document.stopObserving "click", @click_test_action + + if not @is_multiple + @selected_item.tabIndex = @search_field.tabIndex + @search_field.tabIndex = -1 + + @active_field = false + this.results_hide() + + @container.removeClassName "chzn-container-active" + this.winnow_results_clear() + this.clear_backstroke() + + this.show_search_field_default() + this.search_field_scale() + + activate_field: -> + if not @is_multiple and not @active_field + @search_field.tabIndex = @selected_item.tabIndex + @selected_item.tabIndex = -1 + + @container.addClassName "chzn-container-active" + @active_field = true + + @search_field.value = @search_field.value + @search_field.focus() + + + test_active_click: (evt) -> + if evt.target.up('#' + @container.id) + @active_field = true + else + this.close_field() + + results_build: -> + startTime = new Date() + @parsing = true + @results_data = SelectParser.select_to_array @form_field + + if @is_multiple and @choices > 0 + @search_choices.select("li.search-choice").invoke("remove") + @choices = 0 + else if not @is_multiple + @selected_item.down("span").update(@default_text) + + content = '' + for data in @results_data + if data.group + content += this.result_add_group data + else if !data.empty + content += this.result_add_option data + if data.selected and @is_multiple + this.choice_build data + else if data.selected and not @is_multiple + @selected_item.down("span").update( data.text ) + + this.show_search_field_default() + this.search_field_scale() + + @search_results.update content + @parsing = false + + + result_add_group: (group) -> + if not group.disabled + group.dom_id = @form_field.id + "chzn_g_" + group.array_index + '
                        • ' + group.label.escapeHTML() + '
                        • ' + else + "" + + result_add_option: (option) -> + if not option.disabled + option.dom_id = @form_field.id + "chzn_o_" + option.array_index + + classes = if option.selected and @is_multiple then [] else ["active-result"] + classes.push "result-selected" if option.selected + classes.push "group-option" if option.group_array_index? + + '
                        • ' + option.text.escapeHTML() + '
                        • ' + else + "" + + results_update_field: -> + this.result_clear_highlight() + @result_single_selected = null + this.results_build() + + result_do_highlight: (el) -> + this.result_clear_highlight() + + @result_highlight = el + @result_highlight.addClassName "highlighted" + + maxHeight = parseInt @search_results.getStyle('maxHeight'), 10 + visible_top = @search_results.scrollTop + visible_bottom = maxHeight + visible_top + + high_top = @result_highlight.positionedOffset().top + high_bottom = high_top + @result_highlight.getHeight() + + if high_bottom >= visible_bottom + @search_results.scrollTop = if (high_bottom - maxHeight) > 0 then (high_bottom - maxHeight) else 0 + else if high_top < visible_top + @search_results.scrollTop = high_top + + result_clear_highlight: -> + @result_highlight.removeClassName('highlighted') if @result_highlight + @result_highlight = null + + results_toggle: -> + if @results_showing + this.results_hide() + else + this.results_show() + + results_show: -> + if not @is_multiple + @selected_item.addClassName('chzn-single-with-drop') + if @result_single_selected + this.result_do_highlight( @result_single_selected ) + + dd_top = if @is_multiple then @container.getHeight() else (@container.getHeight() - 1) + @dropdown.setStyle {"top": dd_top + "px", "left":0} + @results_showing = true + + @search_field.focus() + @search_field.value = @search_field.value + + this.winnow_results() + + results_hide: -> + @selected_item.removeClassName('chzn-single-with-drop') unless @is_multiple + this.result_clear_highlight() + @dropdown.setStyle({"left":"-9000px"}) + @results_showing = false + + + set_tab_index: (el) -> + if @form_field.tabIndex + ti = @form_field.tabIndex + @form_field.tabIndex = -1 + + if @is_multiple + @search_field.tabIndex = ti + else + @selected_item.tabIndex = ti + @search_field.tabIndex = -1 + + show_search_field_default: -> + if @is_multiple and @choices < 1 and not @active_field + @search_field.value = @default_text + @search_field.addClassName "default" + else + @search_field.value = "" + @search_field.removeClassName "default" + + search_results_click: (evt) -> + target = if evt.target.hasClassName("active-result") then evt.target else evt.target.up(".active-result") + if target + @result_highlight = target + this.result_select() + + search_results_mouseover: (evt) -> + target = if evt.target.hasClassName("active-result") then evt.target else evt.target.up(".active-result") + this.result_do_highlight( target ) if target + + search_results_mouseout: (evt) -> + this.result_clear_highlight() if evt.target.hasClassName('active-result') or evt.target.up('.active-result') + + + choices_click: (evt) -> + evt.preventDefault() + if( @active_field and not(evt.target.hasClassName('search-choice') or evt.target.up('.search-choice')) and not @results_showing ) + this.results_show() + + choice_build: (item) -> + choice_id = @form_field.id + "_chzn_c_" + item.array_index + @choices += 1 + @search_container.insert { before: @choice_temp.evaluate({"id":choice_id, "choice":item.text, "position":item.array_index}) } + link = $(choice_id).down('a') + link.observe "click", (evt) => this.choice_destroy_link_click(evt) + + choice_destroy_link_click: (evt) -> + evt.preventDefault() + @pending_destroy_click = true + this.choice_destroy evt.target + + choice_destroy: (link) -> + @choices -= 1 + this.show_search_field_default() + + this.results_hide() if @is_multiple and @choices > 0 and @search_field.value.length < 1 + + this.result_deselect link.readAttribute("rel") + link.up('li').remove() + + result_select: -> + if @result_highlight + high = @result_highlight + this.result_clear_highlight() + + high.addClassName("result-selected") + + if @is_multiple + this.result_deactivate high + else + @result_single_selected = high + + position = high.id.substr(high.id.lastIndexOf("_") + 1 ) + item = @results_data[position] + item.selected = true + + @form_field.options[item.options_index].selected = true + + if @is_multiple + this.choice_build item + else + @selected_item.down("span").update(item.text) + + this.results_hide() + @search_field.value = "" + + @form_field.simulate("change") if typeof Event.simulate is 'function' + this.search_field_scale() + + result_activate: (el) -> + el.addClassName("active-result").show() + + result_deactivate: (el) -> + el.removeClassName("active-result").hide() + + result_deselect: (pos) -> + result_data = @results_data[pos] + result_data.selected = false + + @form_field.options[result_data.options_index].selected = false + result = $(@form_field.id + "chzn_o_" + pos) + result.removeClassName("result-selected").addClassName("active-result").show() + + this.result_clear_highlight() + this.winnow_results() + + @form_field.simulate("change") if typeof Event.simulate is 'function' + this.search_field_scale() + + results_search: (evt) -> + if @results_showing + this.winnow_results() + else + this.results_show() + + winnow_results: -> + startTime = new Date() + this.no_results_clear() + + results = 0 + + searchText = if @search_field.value is @default_text then "" else @search_field.value.strip() + regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i') + zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i') + + for option in @results_data + if not option.disabled and not option.empty + if option.group + $(option.dom_id).hide() + else if not (@is_multiple and option.selected) + found = false + result_id = option.dom_id + + if regex.test option.text + found = true + results += 1 + else if option.text.indexOf(" ") >= 0 or option.text.indexOf("[") == 0 + #TODO: replace this substitution of /\[\]/ with a list of characters to skip. + parts = option.text.replace(/\[|\]/g, "").split(" ") + if parts.length + for part in parts + if regex.test part + found = true + results += 1 + + if found + if searchText.length + startpos = option.text.search zregex + text = option.text.substr(0, startpos + searchText.length) + '
                          ' + option.text.substr(startpos + searchText.length) + text = text.substr(0, startpos) + '' + text.substr(startpos) + else + text = option.text + + $(result_id).update text if $(result_id).innerHTML != text + + this.result_activate $(result_id) + + $(@results_data[option.group_array_index].dom_id).show() if option.group_array_index? + else + this.result_clear_highlight() if $(result_id) is @result_highlight + this.result_deactivate $(result_id) + + if results < 1 and searchText.length + this.no_results(searchText) + else + this.winnow_results_set_highlight() + + winnow_results_clear: -> + @search_field.clear() + lis = @search_results.select("li") + + for li in lis + if li.hasClassName("group-result") + li.show() + else if not @is_multiple or not li.hasClassName("result-selected") + this.result_activate li + + winnow_results_set_highlight: -> + if not @result_highlight + do_high = @search_results.down(".active-result") + if(do_high) + this.result_do_highlight do_high + + no_results: (terms) -> + @search_results.insert @no_results_temp.evaluate({"terms":terms.escapeHTML()}) + + no_results_clear: -> + nr = null + nr.remove() while nr = @search_results.down(".no-results") + + + keydown_arrow: -> + actives = @search_results.select("li.active-result") + if actives.length + if not @result_highlight + this.result_do_highlight actives.first() + else if @results_showing + sibs = @result_highlight.nextSiblings() + nexts = sibs.intersect(actives) + this.result_do_highlight nexts.first() if nexts.length + this.results_show() if not @results_showing + + keyup_arrow: -> + if not @results_showing and not @is_multiple + this.results_show() + else if @result_highlight + sibs = @result_highlight.previousSiblings() + actives = @search_results.select("li.active-result") + prevs = sibs.intersect(actives) + + if prevs.length + this.result_do_highlight prevs.first() + else + this.results_hide() if @choices > 0 + this.result_clear_highlight() + + keydown_backstroke: -> + if @pending_backstroke + this.choice_destroy @pending_backstroke.down("a") + this.clear_backstroke() + else + @pending_backstroke = @search_container.siblings("li.search-choice").last() + @pending_backstroke.addClassName("search-choice-focus") + + clear_backstroke: -> + @pending_backstroke.removeClassName("search-choice-focus") if @pending_backstroke + @pending_backstroke = null + + keyup_checker: (evt) -> + stroke = evt.which ? evt.keyCode + this.search_field_scale() + + switch stroke + when 8 + if @is_multiple and @backstroke_length < 1 and @choices > 0 + this.keydown_backstroke() + else if not @pending_backstroke + this.result_clear_highlight() + this.results_search() + when 13 + evt.preventDefault() + this.result_select() if this.results_showing + when 27 + this.results_hide() if @results_showing + when 9, 38, 40, 16 + # don't do anything on these keys + else this.results_search() + + + keydown_checker: (evt) -> + stroke = evt.which ? evt.keyCode + this.search_field_scale() + + this.clear_backstroke() if stroke != 8 and this.pending_backstroke + + switch stroke + when 8 + @backstroke_length = this.search_field.value.length + when 9 + @mouse_on_container = false + when 13 + evt.preventDefault() + when 38 + evt.preventDefault() + this.keyup_arrow() + when 40 + this.keydown_arrow() + + + search_field_scale: -> + if @is_multiple + h = 0 + w = 0 + + style_block = "position:absolute; left: -1000px; top: -1000px; display:none;" + styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'] + + for style in styles + style_block += style + ":" + @search_field.getStyle(style) + ";" + + div = new Element('div', { 'style' : style_block }).update(@search_field.value) + document.body.appendChild(div) + + w = Element.measure(div, 'width') + 25 + div.remove() + + if( w > @f_width-10 ) + w = @f_width - 10 + + @search_field.setStyle({'width': w + 'px'}) + + dd_top = @container.getHeight() + @dropdown.setStyle({"top": dd_top + "px"}) + +root.Chosen = Chosen + +document.observe 'dom:loaded', (evt) -> + selects = $$(".chzn-select") + new Chosen select for select in selects + +get_side_border_padding = (elmt) -> + layout = new Element.Layout(elmt) + side_border_padding = layout.get("border-left") + layout.get("border-right") + layout.get("padding-left") + layout.get("padding-right") + +root.get_side_border_padding = get_side_border_padding + +root = exports ? this + +class SelectParser + + constructor: -> + @options_index = 0 + @parsed = [] + + add_node: (child) -> + if child.nodeName is "OPTGROUP" + this.add_group child + else + this.add_option child + + add_group: (group) -> + group_position = @parsed.length + @parsed.push + array_index: group_position + group: true + label: group.label + children: 0 + disabled: group.disabled + this.add_option( option, group_position, group.disabled ) for option in group.childNodes + + add_option: (option, group_position, group_disabled) -> + if option.nodeName is "OPTION" + if option.text != "" + if group_position? + @parsed[group_position].children += 1 + @parsed.push + array_index: @parsed.length + options_index: @options_index + value: option.value + text: option.text + selected: option.selected + disabled: if group_disabled is true then group_disabled else option.disabled + group_array_index: group_position + else + @parsed.push + array_index: @parsed.length + options_index: @options_index + empty: true + @options_index += 1 + +SelectParser.select_to_array = (select) -> + parser = new SelectParser() + parser.add_node( child ) for child in select.childNodes + parser.parsed + +root.SelectParser = SelectParser diff --git a/src/usr/local/www/javascript/datepicker/css/datepicker.css b/src/usr/local/www/javascript/datepicker/css/datepicker.css new file mode 100644 index 0000000..0773fa6 --- /dev/null +++ b/src/usr/local/www/javascript/datepicker/css/datepicker.css @@ -0,0 +1,178 @@ +/* This is a very basic stylesheet for the date-picker. Feel free to create your own. */ + +/* The wrapper div */ +.datePicker + { + position:absolute; + min-width:21em; + width:21em; + z-index:9999; + text-align:center; + font:900 0.8em/0.8em Verdana, Sans-Serif; + background:transparent; + } +/* + Quirksmode necessity + -------------------- + + If your HTML document renders in quirksmode (i.e. has no doctype declaration) + then uncomment the following CSS rule or the datePicker will be HUGE... + +.datePicker th, +.datePicker td + { + font-size:11px; + } +*/ +/* The iframe hack to cover selectlists in Internet Explorer <= v6 */ +.iehack + { + position:absolute; + background:#fff; + z-index:9998; + padding:0; + border:0; + display:none; + } +/* The button created beside each input */ +.date-picker-control + { + border:0 none; + padding:0; + margin-left:4px; + background:transparent url(../media/cal.gif) no-repeat 0 0; + width:16px; + height:16px; + margin-top:0; + vertical-align:top; + cursor:pointer; + } +/* The next & previous buttons */ +.datePicker th button + { + display:inline; + padding:0; + margin:0; + color:#000; + height:1em; + width:0.8em; + line-height:0.8em; + border-width:0; + font-family: georgia, times new roman, palatino, times, bookman, serif; + background:transparent; + font-weight:bold; + cursor:pointer; + } +.datePicker th button:active, +.datePicker th button:focus, +.date-picker-control:active, +.date-picker-control:focus + { + outline:none; + } +.datePicker th button.prev-but + { + text-align:left; + } +.datePicker th button.next-but + { + text-align:right; + } +/* The mon, tue, wed etc day buttons */ +.datePicker th button.fd-day-header + { + text-align:center; + margin:0 auto; + font:900 1em Verdana, Sans-Serif; + height:auto; + width:auto; + text-decoration:none; + line-height:1.4em; + } +/* The table */ +.datePicker table + { + position:relative; + margin:0; + padding:0; + border:1px solid #ccc; + background:#fff url(../media/gradient-e5e5e5-ffffff.gif) repeat-x 0 -20px; + text-align:center; + width:100%; + } +.datePicker table tfoot td + { + background:#fff url(../media/gradient-e5e5e5-ffffff.gif) repeat-x 0 -40px; + } +/* Common TD & TH styling */ +.datePicker table td + { + border: 1px solid #ccc; + padding:0.6em 0.5em 0.5em 0.5em; + /* Opera requires a line-height bigger than 1em in order to redraw properly */ + line-height:1.2em; + cursor:default; + background:#fff url(../media/gradient-e5e5e5-ffffff.gif) repeat-x 0 -50px; + } +.datePicker table th + { + border:0 none; + padding:0; + line-height:1em; + font-weight:bold; + color:#222; + text-align:center; + } +/* The "mon tue wed etc" day header button styles */ +.datePicker table th.date-picker-day-header + { + text-transform:lowercase; + cursor:help; + } +/* The "todays date" style */ +.datePicker table td.date-picker-today + { + background:#fff url(../media/bullet2.gif) no-repeat 0 0; + color:rgb(100,100,100) !important; + } +/* The "selected date" style */ +.datePicker table td.date-picker-selected-date + { + color:#333 !important; + border-color:#333 !important; + } +/* the "highlight days" style */ +td.date-picker-highlight + { + color:#a86666; + } +/* The date "out of range" style */ +.datePicker table td.out-of-range + { + color:#ccc !important; + font-style:oblique; + background:transparent !important; + cursor:default !important; + } +/* The "disabled days" style */ +.datePicker table td.day-disabled + { + color:#aaa !important; + background:transparent !important; + cursor:default !important; + } +/* The "active cursor" style */ +.datePicker table td#date-picker-hover + { + background:#fff url(../media/bg_header.jpg) no-repeat 0 0; + cursor:pointer; + border-color:rgb(100,130,170); + color:rgb(100,130,170); + } +/* Remove the images for Internet Explorer <= v6 using the "* html" hack */ +* html .datePicker table td.date-picker-selected, +* html .datePicker table td.date-picker-hover, +* html .datePicker table td + { + background-image:none; + } diff --git a/src/usr/local/www/javascript/datepicker/js/blank.html b/src/usr/local/www/javascript/datepicker/js/blank.html new file mode 100644 index 0000000..53a7f24 --- /dev/null +++ b/src/usr/local/www/javascript/datepicker/js/blank.html @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/usr/local/www/javascript/datepicker/js/datepicker.js b/src/usr/local/www/javascript/datepicker/js/datepicker.js new file mode 100644 index 0000000..3d6dbd3 --- /dev/null +++ b/src/usr/local/www/javascript/datepicker/js/datepicker.js @@ -0,0 +1,1111 @@ +/* + DatePicker v2.5 by frequency-decoder.com (2006/12/01) + + Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/) + + Please credit frequency-decoder in any derivative work - thanks. + + You are free: + + * to copy, distribute, display, and perform the work + * to make derivative works + * to make commercial use of the work + + Under the following conditions: + + by Attribution. + -------------- + You must attribute the work in the manner specified by the author or licensor. + + sa + -- + Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. + + * For any reuse or distribution, you must make clear to others the license terms of this work. + * Any of these conditions can be waived if you get permission from the copyright holder. +*/ +var datePickerController; + +(function() { + +datePicker.isSupported = typeof document.createElement != "undefined" && + typeof document.documentElement != "undefined" && + typeof document.documentElement.offsetWidth == "number"; + +// Detect the users language +datePicker.languageinfo = navigator.language ? navigator.language : navigator.userLanguage; +datePicker.languageinfo = datePicker.languageinfo ? datePicker.languageinfo.toLowerCase().replace(/-[a-z]+$/, "") : 'en'; + +if(datePicker.languageinfo != 'en') { + // Load the appropriate language file + var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script'); + var loc = ""; + + for(var i = 0, scriptFile; scriptFile = scriptFiles[i]; i++) { + if(scriptFile.src && scriptFile.src.match(/datepicker/)) { + loc = scriptFile.src.replace("datepicker", "lang/" + datePicker.languageinfo); + break; + }; + }; + + if(loc != "") { + var script = document.createElement('script'); + script.type = "text/javascript"; + script.src = loc; + // Hopefully this allows a UTF-8 js file to be imported into a non-UTF HTML document + script.setAttribute("charset", "utf-8"); + document.getElementsByTagName('head')[0].appendChild(script); + }; +}; + +// Defaults for the language should the locale file not load +datePicker.months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"]; +datePicker.fullDay = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday"]; +datePicker.titles = [ + "Previous month", + "Next month", + "Previous year", + "Next year"]; +datePicker.daysPerMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; + +datePicker.getDaysPerMonth = function (nMonth, nYear) { + nMonth = (nMonth + 12) % 12; + var res = datePicker.daysPerMonth[nMonth]; + if(((0 == (nYear%4)) && ((0 != (nYear%100)) || (0 == (nYear%400)))) && nMonth == 1) { + res = 29; + }; + return res; +}; + +function datePicker(options) { + + this.defaults = {}; + + for(opt in options) { + this[opt] = this.defaults[opt] = options[opt]; + }; + + this.date = new Date(); + this.yearinc = 1; + this.timer = null; + this.pause = 1000; + this.timerSet = false; + this.opacity = 0; + this.opacityTo = 0; + this.fadeTimer = null; + this.interval = new Date(); + this.firstDayOfWeek = this.defaults.firstDayOfWeek = 0; + this.dateSet = null; + this.visible = false; + this.div; + this.table; + + var o = this; + + o.reset = function() { + for(def in o.defaults) { + o[def] = o.defaults[def]; + }; + }; + o.setOpacity = function(op) { + o.div.style.opacity = + op/100; + o.div.style.filter = 'alpha(opacity=' + op + ')'; + o.opacity = op; + }; + o.fade = function() { + + window.clearTimeout(o.fadeTimer); + var diff = Math.round(o.opacity + ((o.opacityTo - o.opacity) / 4)); + + o.setOpacity(diff); + + if(Math.abs(o.opacityTo - diff) > 3) { + o.fadeTimer = window.setTimeout(function () { o.fade(); }, 50); + } else { + o.setOpacity(o.opacityTo); + if(o.opacityTo == 0) o.div.style.display = "none"; + }; + }; + o.killEvent = function(e) { + if (e == null) e = document.parentWindow.event; + + if (e.stopPropagation) { + e.stopPropagation(); + e.preventDefault(); + } + /*@cc_on@*/ + /*@if(@_win32) + e.cancelBubble = true; + e.returnValue = false; + /*@end@*/ + return false; + }; + o.startTimer = function () { + if (o.timerSet) o.stopTimer(); + o.timer = window.setTimeout(function () { o.onTimer(); }, o.timerInc); + o.timerSet = true; + }; + o.stopTimer = function () { + if (o.timer != null) window.clearTimeout(o.timer); + o.timerSet = false; + }; + o.events = { + onkeydown: function (e) { + + if(!o.visible) return false; + + if (e == null) e = document.parentWindow.event; + var kc = e.keyCode ? e.keyCode : e.charCode; + + if ( kc == 13 ) { + // close with update + o.returnFormattedDate(); + o.hide(); + return o.killEvent(e); + } else if ( kc == 27 ) { + // close + o.hide(); + return o.killEvent(e); + } else if ( kc == 32 || kc == 0 ) { + // close + o.date = new Date( ); + o.updateTable(); + return o.killEvent(e); + }; + + // Internet Explorer fires the keydown event faster than the JavaScript engine can + // update the interface. The following attempts to fix this. + + /*@cc_on@*/ + /*@if(@_win32) + if(new Date().getTime() - o.interval.getTime() < 100) return o.killEvent(e); + o.interval = new Date(); + /*@end@*/ + + if ((kc > 49 && kc < 56) || (kc > 97 && kc < 104)) { + if (kc > 96) kc -= (96-48); + kc -= 49; + o.firstDayOfWeek = (o.firstDayOfWeek + kc) % 7; + o.updateTable(); + return o.killEvent(e); + }; + + if ( kc < 37 || kc > 40 ) return true; + + var d = new Date( o.date ).valueOf(); + + if ( kc == 37 ) { + // ctrl + left = previous month + if( e.ctrlKey ) { + d = new Date( o.date ); + d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() - 1,d.getFullYear())) ); // no need to catch dec -> jan for the year + d.setMonth( d.getMonth() - 1 ); + } else { + d -= 24 * 60 * 60 * 1000; + }; + } else if ( kc == 39 ) { + // ctrl + right = next month + if( e.ctrlKey ) { + d = new Date( o.date ); + d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() + 1,d.getFullYear())) ); // no need to catch dec -> jan for the year + d.setMonth( d.getMonth() + 1 ); + } else { + d += 24 * 60 * 60 * 1000; + }; + } else if ( kc == 38 ) { + // ctrl + up = next year + if( e.ctrlKey ) { + d = new Date( o.date ); + d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() + 1)) ); // no need to catch dec -> jan for the year + d.setFullYear( d.getFullYear() + 1 ); + } else { + d -= 7 * 24 * 60 * 60 * 1000; + }; + } else if ( kc == 40 ) { + // ctrl + down = prev year + if( e.ctrlKey ) { + d = new Date( o.date ); + d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() - 1)) ); // no need to catch dec -> jan for the year + d.setFullYear( d.getFullYear() - 1 ); + } else { + d += 7 * 24 * 60 * 60 * 1000; + }; + }; + + var tmpDate = new Date( d ); + if(!o.outOfRange(tmpDate)) { + o.date = tmpDate; + }; + + o.updateTable(); + + return o.killEvent(e); + }, + onmousedown: function(e) { + if ( e == null ) e = document.parentWindow.event; + var el = e.target != null ? e.target : e.srcElement; + + var found = false; + + while(el.parentNode) { + if(el.id && (el.id == "fd-"+o.id || el.id == "fd-but-"+o.id)) { + found = true; + break; + } + try { + el = el.parentNode; + } catch(err) { + break; + } + } + if(found) return true; + datePickerController.hideAll(); + }, + onmouseover: function(e) { + if(document.getElementById("date-picker-hover")) { + document.getElementById("date-picker-hover").id = ""; + }; + + this.id = "date-picker-hover"; + + o.date.setDate(this.firstChild.nodeValue); + }, + onclick: function (e) { + if(o.opacity != o.opacityTo) return false; + if ( e == null ) e = document.parentWindow.event; + var el = e.target != null ? e.target : e.srcElement; + while ( el.nodeType != 1 ) el = el.parentNode; + + var d = new Date( o.date ); + var n = Number( el.firstChild.data ); + + if(isNaN(n)) { return true; }; + + d.setDate( n ); + o.date = d; + + o.returnFormattedDate(); + o.hide(); + return o.killEvent(e); + }, + incDec:function(e) { + if(o.timerSet) { + o.stopTimer(); + }; + + datePickerController.addEvent(document, "mouseup", o.events.clearTimer); + + o.timerInc = 1000; + o.dayInc = arguments[1]; + o.yearInc = arguments[2]; + o.monthInc = arguments[3]; + o.onTimer(); + return o.killEvent(e); + }, + clearTimer:function() { + o.stopped = true; + o.timerInc = 1000; + o.yearInc = 0; + o.monthInc = 0; + o.dayInc = 0; + try { + datePickerController.removeEvent(document, "mouseup", o.events.clearTimer); + } catch(e) { }; + o.stopTimer(); + } + }; + o.onTimer = function() { + var d = new Date( o.date ); + + d.setDate( Math.min(d.getDate()+o.dayInc, datePicker.getDaysPerMonth(d.getMonth()+o.monthInc,d.getFullYear()+o.yearInc)) ); // no need to catch dec -> jan for the year + d.setMonth( d.getMonth() + o.monthInc ); + d.setFullYear( d.getFullYear() + o.yearInc ); + + o.date = d; + + if(o.timerInc > 50) { + o.timerInc = 50 + Math.round(((o.timerInc - 50) / 1.8)); + }; + o.startTimer(); + o.updateTable(); + }; + o.getElem = function() { + return document.getElementById(o.id.replace(/^fd-/, '')) || false; + }; + o.setRangeLow = function(range) { + if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = ''; + o.low = o.defaults.low = range; + }; + o.setRangeHigh = function(range) { + if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = ''; + o.high = o.defaults.high = range; + }; + o.setDisabledDays = function(dayArray) { + o.disableDays = o.defaults.disableDays = dayArray; + }; + o.setFirstDayOfWeek = function(e) { + if ( e == null ) e = document.parentWindow.event; + var elem = e.target != null ? e.target : e.srcElement; + + if(elem.tagName.toLowerCase() != "th") { + while(elem.tagName.toLowerCase() != "th") elem = elem.parentNode; + } + + var cnt = 0; + + while(elem.previousSibling) { + elem = elem.previousSibling; + if(elem.tagName.toLowerCase() == "th") cnt++; + } + + o.firstDayOfWeek = (o.firstDayOfWeek + cnt) % 7; + o.updateTable(); + + return o.killEvent(e); + }; + o.trueBody = function() { + return; + }; + o.resize = function() { + if(!o.created || !o.getElem()) return; + + o.div.style.visibility = "hidden"; + o.div.style.display = "block"; + + var osh = o.div.offsetHeight; + var osw = o.div.offsetWidth; + + o.div.style.visibility = "visible"; + o.div.style.display = "none"; + + var elem = document.getElementById('fd-but-' + o.id); + var pos = datePickerController.findPosition(elem); + var trueBody = (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body; + + if ( parseInt(trueBody.clientWidth+trueBody.scrollLeft) < parseInt(osw+pos[0])) { + o.div.style.left = Math.abs(parseInt((trueBody.clientWidth+trueBody.scrollLeft) - osw)) + "px"; + } else { + o.div.style.left = pos[0] + "px"; + }; + + if ( parseInt(trueBody.clientHeight+trueBody.scrollTop) < parseInt(osh+pos[1]+elem.offsetHeight+2)) { + o.div.style.top = Math.abs(parseInt(pos[1] - (osh + 2))) + "px"; + } else { + o.div.style.top = Math.abs(parseInt(pos[1] + elem.offsetHeight + 2)) + "px"; + }; + }; + o.equaliseDates = function() { + var clearDayFound = false; + var tmpDate; + for(var i = o.low; i <= o.high; i++) { + tmpDate = String(i); + if(!o.disableDays[new Date(tmpDate.substr(4,2) + '/' + tmpDate.substr(6,2) + '/' + tmpDate.substr(0,4)).getDay() - 1]) { + clearDayFound = true; + break; + }; + }; + if(!clearDayFound) o.disableDays = o.defaults.disableDays = [0,0,0,0,0,0,0]; + }; + o.outOfRange = function(tmpDate) { + if(!o.low && !o.high) return false; + + var level = false; + if(!tmpDate) { + level = true; + tmpDate = o.date; + }; + + var d = (tmpDate.getDate() < 10) ? "0" + tmpDate.getDate() : tmpDate.getDate(); + var m = ((tmpDate.getMonth() + 1) < 10) ? "0" + (tmpDate.getMonth() + 1) : tmpDate.getMonth() + 1; + var y = tmpDate.getFullYear(); + var dt = (y+' '+m+' '+d).replace(/ /g,''); + + if(o.low) { + if(parseInt(dt) < parseInt(o.low)) { + if(!level) return true; + o.date = new Date( o.low.substr(4,2) + '/' + o.low.substr(6,2) + '/' + o.low.substr(0,4) ); + return false; + }; + }; + if(o.high) { + if(parseInt(dt) > parseInt(o.high)) { + if(!level) return true; + o.date = new Date( o.high.substr(4,2) + '/' + o.high.substr(6,2) + '/' + o.high.substr(0,4) ); + }; + }; + return false; + }; + o.create = function() { + + /*@cc_on@*/ + /*@if(@_jscript_version <= 5.6) + if(!document.getElementById("iePopUpHack")) { + var loc = "./blank.html"; + var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script'); + for(var i = 0, scriptFile; scriptFile = scriptFiles[i]; i++) { + if(scriptFile.src && scriptFile.src.match(/datepicker.js$/)) { + loc = scriptFile.src.replace("datepicker.js", "blank.html"); + break; + }; + }; + + o.iePopUp = document.createElement('iframe'); + o.iePopUp.src = loc; + o.iePopUp.setAttribute('className','iehack'); + o.iePopUp.scrolling="no"; + o.iePopUp.frameBorder="0"; + o.iePopUp.name = o.iePopUp.id = "iePopUpHack"; + document.body.appendChild(o.iePopUp); + } else { + o.iePopUp = document.getElementById("iePopUpHack"); + }; + /*@end@*/ + + if(typeof(fdLocale) == "object" && o.locale) { + datePicker.titles = fdLocale.titles; + datePicker.months = fdLocale.months; + datePicker.fullDay = fdLocale.fullDay; + // Optional parameters + if(fdLocale.dayAbbr) datePicker.dayAbbr = fdLocale.dayAbbr; + if(fdLocale.firstDayOfWeek) o.firstDayOfWeek = o.defaults.firstDayOfWeek = fdLocale.firstDayOfWeek; + }; + + o.div = document.createElement('div'); + o.div.style.zIndex = 9999; + o.div.id = "fd-"+o.id; + var tableBody = document.createElement('tbody'); + var tableHead = document.createElement('thead'); + var nbsp = String.fromCharCode( 160 ); + + o.table = document.createElement('table'); + o.div.className = "datePicker"; + + var tr = document.createElement('tr'); + var th = document.createElement('th'); + + // previous year + var tmpelem = document.createElement('button'); + tmpelem.setAttribute("type", "button"); + tmpelem.className = "prev-but"; + tmpelem.appendChild(document.createTextNode('\u00AB')); + tmpelem.title = datePicker.titles[2]; + tmpelem.onmousedown = function(e) { this.blur(); o.events.incDec(e,0,-1,0); }; + tmpelem.onmouseup = o.events.clearTimer; + th.appendChild( tmpelem ); + + // previous month + var tmpelem = document.createElement('button'); + tmpelem.setAttribute("type", "button"); + tmpelem.className = "prev-but"; + tmpelem.appendChild(document.createTextNode("\u2039")); + tmpelem.title = datePicker.titles[0]; + tmpelem.onmousedown = function(e) { this.blur(); o.events.incDec(e,0,0,-1); }; + tmpelem.onmouseup = o.events.clearTimer; + th.appendChild( tmpelem ); + tr.appendChild( th ); + + // title bar + o.titleBar = document.createElement('th'); + + /*@cc_on + /*@if (@_win32) + o.titleBar.setAttribute('colSpan','5'); + @else @*/ + o.titleBar.setAttribute('colspan','5'); + /*@end + @*/ + + o.titleBar.setAttribute('text-align','center'); + tr.appendChild( o.titleBar ); + + th = document.createElement('th'); + + // next month + var tmpelem = document.createElement('button'); + tmpelem.setAttribute("type", "button"); + tmpelem.className = "next-but"; + tmpelem.appendChild(document.createTextNode('\u203A')); + tmpelem.title = datePicker.titles[1]; + tmpelem.onmousedown = function(e) { this.blur(); o.events.incDec(e,0,0,1); }; + tmpelem.onmouseup = o.events.clearTimer; + + th.appendChild( tmpelem ); + + // next year + var tmpelem = document.createElement('button'); + tmpelem.setAttribute("type", "button"); + tmpelem.className = "next-but"; + tmpelem.appendChild(document.createTextNode('\u00BB')); + tmpelem.title = datePicker.titles[3]; + tmpelem.onmousedown = function(e) { this.blur(); o.events.incDec(e,0,1,0); }; + tmpelem.onmouseup = o.events.clearTimer; + th.appendChild( tmpelem ); + + tr.appendChild( th ); + + tableHead.appendChild(tr); + + var row, col; + + for(var rows = 0; rows < 7; rows++) { + row = document.createElement('tr'); + for(var cols = 0; cols < 7; cols++) { + col = (rows == 0) ? document.createElement('th') : document.createElement('td'); + if(rows != 0) { + col.appendChild(document.createTextNode(nbsp)); + } else { + col.className = "date-picker-day-header"; + col.scope = "col"; + }; + + row.appendChild(col); + } + if(rows != 0) tableBody.appendChild(row); + else tableHead.appendChild(row); + }; + o.table.appendChild( tableHead ); + o.table.appendChild( tableBody ); + + o.div.appendChild( o.table ); + o.created = true; + + document.getElementsByTagName('body')[0].appendChild( o.div ); + }; + o.setDateFromInput = function() { + o.dateSet = null; + + var elem = o.getElem(); + if(!elem) return; + + var date = elem.value; + + var d,m,y,dt,dates; + + d = o.format.replace(/-/g,'').indexOf('d'); + m = o.format.replace(/-/g,'').indexOf('m'); + y = o.format.replace(/-/g,'').indexOf('y'); + + if(o.splitDate) { + dates = []; + + dates[m] = document.getElementById(o.id+'-mm').value; + if(dates[m] < 1 || dates[m] > 12) dates[m] = ""; + + dates[d] = document.getElementById(o.id+'-dd').value; + if(dates[d] < 1 || dates[d] > datePicker.daysPerMonth[dates[m]-1]) dates[d] = ""; + + dates[y] = date; + } else { + if(date.match(/^[0-9]{4}$/)) { + if(date > 1600 && date < 2030) { + o.date.setFullYear(date); + return; + }; + }; + + dates = date.split(o.divider); + + if(dates.length != 3) { + o.date = new Date(); + return; + }; + }; + + var check = new Date( dates[y] + "/" + dates[m] + "/" + dates[d] ); + if(check == 'Invalid Date' /*@cc_on@*/ /*@if(@_win32) || check == 'NaN' /*@end@*/) { + o.date = new Date(); + return; + }; + + o.date.setMonth(dates[m]-1); + o.date.setFullYear(dates[y]); + o.date.setDate(dates[d]); + + o.dateSet = new Date(o.date); + }; + o.returnFormattedDate = function() { + var elem = o.getElem(); + if(!elem) return; + + var d = (o.date.getDate() < 10) ? "0" + o.date.getDate() : o.date.getDate(); + var m = ((o.date.getMonth() + 1) < 10) ? "0" + (o.date.getMonth() + 1) : o.date.getMonth() + 1; + var yyyy = o.date.getFullYear(); + + var weekDay = ( o.date.getDay() + 6 ) % 7; + + if(!(o.disableDays[weekDay])) { + if(o.splitDate) { + document.getElementById(o.id+"-dd").value = d; + document.getElementById(o.id+"-mm").value = m; + elem.value = yyyy; + + document.getElementById(o.id+"-dd").focus(); + if(document.getElementById(o.id+"-dd").onchange) document.getElementById(o.id+"-dd").onchange(); + if(document.getElementById(o.id+"-mm").onchange) document.getElementById(o.id+"-mm").onchange(); + } else { + elem.value = o.format.replace('y',yyyy).replace('m',m).replace('d',d).replace(/-/g,o.divider); + elem.focus(); + }; + if(elem.onchange) elem.onchange(); + }; + }; + // Credit where credit's due: + + // Most of the logic for this method from the webfx date-picker + // http://webfx.eae.net/ + + o.updateTable = function() { + + if(document.getElementById("date-picker-hover")) { + document.getElementById("date-picker-hover").id = ""; + }; + + var i; + var str = ""; + var rows = 6; + var cols = 7; + var currentWeek = 0; + var nbsp = String.fromCharCode( 160 ); + + var cells = new Array( rows ); + + for ( i = 0; i < rows; i++ ) { + cells[i] = new Array( cols ); + }; + + o.outOfRange(); + + // Set the tmpDate to this month + var tmpDate = new Date( o.date.getFullYear(), o.date.getMonth(), 1 ); + var today = new Date(); + + // titleBar + var titleText = datePicker.months[o.date.getMonth()] + nbsp + o.date.getFullYear(); + while(o.titleBar.firstChild) o.titleBar.removeChild(o.titleBar.firstChild); + o.titleBar.appendChild(document.createTextNode(titleText)); + + for ( i = 1; i < 32; i++ ) { + + tmpDate.setDate( i ); + var weekDay = ( tmpDate.getDay() + 6 ) % 7; + var colIndex = ( (weekDay - o.firstDayOfWeek) + 7 ) % 7; + var cell = { text:"", className:"", id:"" }; + + if ( tmpDate.getMonth() == o.date.getMonth() ) { + + cells[currentWeek][colIndex] = { text:"", className:"", id:"" }; + + var isToday = tmpDate.getDate() == today.getDate() && + tmpDate.getMonth() == today.getMonth() && + tmpDate.getFullYear() == today.getFullYear(); + + if ( o.dateSet != null && o.dateSet.getDate() == tmpDate.getDate() && o.dateSet.getMonth() == tmpDate.getMonth() && o.dateSet.getFullYear() == tmpDate.getFullYear()) { + cells[currentWeek][colIndex].className = "date-picker-selected-date"; + }; + if ( o.date.getDate() == tmpDate.getDate() && o.date.getFullYear() == tmpDate.getFullYear()) { + cells[currentWeek][colIndex].id = "date-picker-hover"; + }; + + if(o.highlightDays[weekDay]) { + cells[currentWeek][colIndex].className += " date-picker-highlight"; + }; + if ( isToday ) { + cells[currentWeek][colIndex].className = "date-picker-today"; + }; + if(o.outOfRange(tmpDate)) { + cells[currentWeek][colIndex].className = "out-of-range"; + } else if(o.disableDays[weekDay]) { + cells[currentWeek][colIndex].className = "day-disabled"; + }; + cells[currentWeek][colIndex].text = tmpDate.getDate(); + if ( colIndex == 6 ) currentWeek++; + }; + }; + + // Table headers + var lnk, d; + var ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[1].getElementsByTagName('th'); + for ( var y = 0; y < 7; y++ ) { + d = (o.firstDayOfWeek + y) % 7; + + while(ths[y].firstChild) ths[y].removeChild(ths[y].firstChild); + + ths[y].title = datePicker.fullDay[d]; + + // Don't create a button for the first day header + if(y > 0) { + but = document.createElement("BUTTON"); + but.className = "fd-day-header"; + but.onclick = but.onkeypress = ths[y].onclick = o.setFirstDayOfWeek; + but.appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0))); + ths[y].appendChild(but); + but.title = datePicker.fullDay[d]; + } else { + ths[y].appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0))); + ths[y].onclick = null; + }; + }; + + + var trs = o.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'); + + var tmpCell; + + for ( var y = 0; y < rows; y++ ) { + var tds = trs[y].getElementsByTagName('td'); + for (var x = 0; x < cols; x++) { + tmpCell = tds[x]; + + while(tmpCell.firstChild) tmpCell.removeChild(tmpCell.firstChild); + + if ( typeof cells[y][x] != "undefined" ) { + tmpCell.className = cells[y][x].className; + tmpCell.id = cells[y][x].id; + + tmpCell.appendChild(document.createTextNode(cells[y][x].text)); + + if(cells[y][x].className != "out-of-range") { + tmpCell.onmouseover = o.events.onmouseover; + tmpCell.onclick = cells[y][x].className == "day-disabled" ? o.killEvent : o.events.onclick; + tmpCell.title = datePicker.months[o.date.getMonth()] + nbsp + cells[y][x].text + "," + nbsp + o.date.getFullYear(); + } else { + tmpCell.onmouseover = null; + tmpCell.onclick = o.killEvent; + tmpCell.title = ""; + }; + } else { + tmpCell.className = ""; + tmpCell.id = ""; + tmpCell.onmouseover = null; + tmpCell.onclick = function(e) { return o.killEvent(e); }; + tmpCell.appendChild(document.createTextNode(nbsp)); + tmpCell.title = ""; + }; + }; + }; + }; + o.init = function() { + if(o.low && o.high && (o.high - o.low < 7)) { + o.equaliseDates(); + }; + o.resize(); + o.setDateFromInput(); + o.fade(); + o.ieHack(true); + }; + o.ieHack = function(cleanup) { + // IE hack + if(o.iePopUp) { + o.iePopUp.style.display = "block"; + o.iePopUp.style.top = (o.div.offsetTop + 2) + "px"; + o.iePopUp.style.left = o.div.offsetLeft + "px"; + o.iePopUp.style.width = o.div.clientWidth + "px"; + o.iePopUp.style.height = (o.div.clientHeight - 2) + "px"; + if(cleanup) o.iePopUp.style.display = "none"; + } + }; + o.show = function() { + var elem = o.getElem(); + if(!elem || o.visible || elem.disabled) return; + + o.reset(); + o.setDateFromInput(); + o.updateTable(); + o.resize(); + o.ieHack(false); + + datePickerController.addEvent(document, "mousedown", o.events.onmousedown); + datePickerController.addEvent(document, "keypress", o.events.onkeydown); + + // Internet Explorer requires the keydown event in order to catch arrow keys + + /*@cc_on@*/ + /*@if(@_win32) + datePickerController.removeEvent(document, "keypress", o.events.onkeydown); + datePickerController.addEvent(document, "keydown", o.events.onkeydown); + /*@end@*/ + + o.opacityTo = 90; + o.div.style.display = "block"; + o.ieHack(false); + o.fade(); + o.visible = true; + + }; + o.hide = function() { + try { + datePickerController.removeEvent(document, "mousedown", o.events.onmousedown); + datePickerController.removeEvent(document, "keypress", o.events.onkeydown); + datePickerController.removeEvent(document, "keydown", o.events.onkeydown); + } catch(e) { + + }; + if(o.iePopUp) { + o.iePopUp.style.display = "none"; + }; + o.opacityTo = 0; + o.fade(); + o.visible = false; + }; + o.create(); + o.init(); +}; + +datePickerController = { + datePickers: {}, + addEvent: function(obj, type, fn, tmp) { + tmp || (tmp = true); + if( obj.attachEvent ) { + obj["e"+type+fn] = fn; + obj[type+fn] = function(){obj["e"+type+fn]( window.event );}; + obj.attachEvent( "on"+type, obj[type+fn] ); + } else { + obj.addEventListener( type, fn, true ); + }; + }, + removeEvent: function(obj, type, fn, tmp) { + tmp || (tmp = true); + if( obj.detachEvent ) { + obj.detachEvent( "on"+type, obj[type+fn] ); + obj[type+fn] = null; + } else { + obj.removeEventListener( type, fn, true ); + }; + }, + findPosition: function(obj) { + var curleft = 0; + var curtop = 0; + var orig = obj; + + if(obj.offsetParent) { + while(obj.offsetParent) { + curleft += obj.offsetLeft; + curtop += obj.offsetTop; + obj = obj.offsetParent; + }; + } else if (obj.x) { + curleft += obj.x; + curtop += obj.y; + }; + return [ curleft, curtop ]; + }, + hideAll: function(exception) { + for(dp in datePickerController.datePickers) { + if(exception && exception == datePickerController.datePickers[dp].id) continue; + datePickerController.datePickers[dp].hide(); + }; + }, + cleanUp: function() { + var dp; + for(dp in datePickerController.datePickers) { + if(!document.getElementById(datePickerController.datePickers[dp].id)) { + dpElem = document.getElementById("fd-"+datePickerController.datePickers[dp].id); + if(dpElem) { + dpElem.parentNode.removeChild(dpElem); + }; + datePickerController.datePickers[dp] = null; + delete datePickerController.datePickers[dp]; + }; + }; + }, + dateFormat: function(dateIn, favourMDY) { + var dateTest = [ + { regExp:/^(0[1-9]|[12][0-9]|3[01])([- \/.])(0[1-9]|1[012])([- \/.])(\d\d?\d\d)$/, d:1, m:3, y:5 }, // dmy + { regExp:/^(0[1-9]|1[012])([- \/.])(0[1-9]|[12][0-9]|3[01])([- \/.])(\d\d?\d\d)$/, d:3, m:1, y:5 }, // mdy + { regExp:/^(\d\d?\d\d)([- \/.])(0[1-9]|1[012])([- \/.])(0[1-9]|[12][0-9]|3[01])$/, d:5, m:3, y:1 } // ymd + ]; + + var start; + var cnt = 0; + + while(cnt < 3) { + start = (cnt + (favourMDY ? 4 : 3)) % 3; + + if(dateIn.match(dateTest[start].regExp)) { + res = dateIn.match(dateTest[start].regExp); + y = res[dateTest[start].y]; + m = res[dateTest[start].m]; + d = res[dateTest[start].d]; + if(m.length == 1) m = "0" + m; + if(d.length == 1) d = "0" + d; + if(y.length != 4) y = (parseInt(y) < 50) ? '20' + y : '19' + y; + + return y+m+d; + }; + + cnt++; + }; + + return 0; + }, + create: function() { + if(!datePicker.isSupported) return; + + datePickerController.cleanUp(); + + var inputs = document.getElementsByTagName('input'); + + var regExp1 = /disable-days-([1-7]){1,6}/g; // the days to disable + var regExp3 = /highlight-days-([1-7]){1,7}/g; // the days to highlight in red + var regExp4 = /range-low-([0-9\-]){10}/g; // the lowest selectable date + var regExp5 = /range-high-([0-9\-]){10}/g; // the highest selectable date + var regExp6 = /format-([dmy\-]{5})/g; // the input/output date format + var regExp7 = /divider-(dot|slash|space|dash)/g; // the character used to divide the date + var regExp8 = /no-locale/g; // do not attempt to detect the browser language + + for(var i=0, inp; inp = inputs[i]; i++) { + if(inp.className && (inp.className.search(regExp6) != -1 || inp.className.search(/split-date/) != -1) && inp.type == "text" && inp.name) { + + if(!inp.id) { + // Internet explorer requires you to give each input a unique ID attribute. + if(document.getElementById(inp.name)) continue; + inp.id = inp.name; + }; + + var options = { + id:inp.id, + low:"", + high:"", + divider:"/", + format:"d-m-y", + highlightDays:[0,0,0,0,0,1,1], + disableDays:[0,0,0,0,0,0,0], + locale:inp.className.search(regExp8) == -1, + splitDate:0 + }; + + // Split the date into three parts ? + if(inp.className.search(/split-date/) != -1) { + if(document.getElementById(inp.id+'-dd') && document.getElementById(inp.id+'-mm') && document.getElementById(inp.id+'-dd').tagName.toLowerCase() == "input" && document.getElementById(inp.id+'-mm').tagName.toLowerCase() == "input") { + options.splitDate = 1; + }; + }; + + // Date format(variations of d-m-y) + if(inp.className.search(regExp6) != -1) { + options.format = inp.className.match(regExp6)[0].replace('format-',''); + }; + + // What divider to use, a "/", "-", "." or " " + if(inp.className.search(regExp7) != -1) { + var divider = inp.className.match(regExp7)[0].replace('divider-',''); + switch(divider.toLowerCase()) { + case "dot": + options.divider = "."; + break; + case "space": + options.divider = " "; + break; + case "dash": + options.divider = "-"; + break; + default: + options.divider = "/"; + }; + }; + + // The days to highlight + if(inp.className.search(regExp3) != -1) { + var tmp = inp.className.match(regExp3)[0].replace(/highlight-days-/, ''); + options.highlightDays = [0,0,0,0,0,0,0]; + for(var j = 0; j < tmp.length; j++) { + options.highlightDays[tmp.charAt(j) - 1] = 1; + }; + }; + + // The days to disable + if(inp.className.search(regExp1) != -1) { + var tmp = inp.className.match(regExp1)[0].replace(/disable-days-/, ''); + options.disableDays = [0,0,0,0,0,0,0]; + for(var j = 0; j < tmp.length; j++) { + options.disableDays[tmp.charAt(j) - 1] = 1; + }; + }; + + // The lower limit + if(inp.className.search(regExp4) != -1) { + options.low = datePickerController.dateFormat(inp.className.match(regExp4)[0].replace(/range-low-/, ''), options.format.charAt(0) == "m"); + if(options.low == 0) { + options.low = ''; + }; + }; + + // The higher limit + if(inp.className.search(regExp5) != -1) { + options.high = datePickerController.dateFormat(inp.className.match(regExp5)[0].replace(/range-high-/, ''), options.format.charAt(0) == "m"); + if(options.high == 0) { + options.high = ''; + }; + }; + + // Datepicker is already created so reset it's defaults + if(document.getElementById('fd-'+inp.id)) { + for(var opt in options) { + datePickerController.datePickers[inp.id].defaults[opt] = options[opt]; + }; + }; + + // Create the button (if needs be) + if(!document.getElementById("fd-but-" + inp.id)) { + var but = document.createElement('button'); + but.setAttribute("type", "button"); + but.className = "date-picker-control"; + + but.id = "fd-but-" + inp.id; + but.appendChild(document.createTextNode(String.fromCharCode( 160 ))); + + if(inp.nextSibling) { + inp.parentNode.insertBefore(but, inp.nextSibling); + } else { + inp.parentNode.appendChild(but); + }; + + } else { + var but = document.getElementById("fd-but-" + inp.id); + }; + + // Add button events + but.onclick = but.onpress = function() { + var inpId = this.id.replace('fd-but-',''); + + datePickerController.hideAll(inpId); + if(inpId in datePickerController.datePickers && !datePickerController.datePickers[inpId].visible) { + datePickerController.datePickers[inpId].show(); + }; + return false; + }; + + // Create the datePicker (if needs be) + if(!document.getElementById('fd-'+inp.id)) { + datePickerController.datePickers[inp.id] = new datePicker(options); + }; + }; + }; + } + +}; + + +})(); + +datePickerController.addEvent(window, 'load', datePickerController.create); + diff --git a/src/usr/local/www/javascript/datepicker/media/bg_header.jpg b/src/usr/local/www/javascript/datepicker/media/bg_header.jpg new file mode 100755 index 0000000..10dbd74 Binary files /dev/null and b/src/usr/local/www/javascript/datepicker/media/bg_header.jpg differ diff --git a/src/usr/local/www/javascript/datepicker/media/bullet1.gif b/src/usr/local/www/javascript/datepicker/media/bullet1.gif new file mode 100755 index 0000000..ae352c2 Binary files /dev/null and b/src/usr/local/www/javascript/datepicker/media/bullet1.gif differ diff --git a/src/usr/local/www/javascript/datepicker/media/bullet2.gif b/src/usr/local/www/javascript/datepicker/media/bullet2.gif new file mode 100755 index 0000000..04b293d Binary files /dev/null and b/src/usr/local/www/javascript/datepicker/media/bullet2.gif differ diff --git a/src/usr/local/www/javascript/datepicker/media/cal.gif b/src/usr/local/www/javascript/datepicker/media/cal.gif new file mode 100755 index 0000000..8526cf5 Binary files /dev/null and b/src/usr/local/www/javascript/datepicker/media/cal.gif differ diff --git a/src/usr/local/www/javascript/datepicker/media/gradient-e5e5e5-ffffff.gif b/src/usr/local/www/javascript/datepicker/media/gradient-e5e5e5-ffffff.gif new file mode 100755 index 0000000..72a0d3e Binary files /dev/null and b/src/usr/local/www/javascript/datepicker/media/gradient-e5e5e5-ffffff.gif differ diff --git a/src/usr/local/www/javascript/domTT/LICENSE b/src/usr/local/www/javascript/domTT/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/src/usr/local/www/javascript/domTT/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/usr/local/www/javascript/domTT/behaviour.js b/src/usr/local/www/javascript/domTT/behaviour.js new file mode 100644 index 0000000..21b28d7 --- /dev/null +++ b/src/usr/local/www/javascript/domTT/behaviour.js @@ -0,0 +1,254 @@ +/* + Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work + of Simon Willison (see comments by Simon below). + + Description: + + Uses css selectors to apply javascript behaviours to enable + unobtrusive javascript in html documents. + + Usage: + + var myrules = { + 'b.someclass' : function(element){ + element.onclick = function(){ + alert(this.innerHTML); + } + }, + '#someid u' : function(element){ + element.onmouseover = function(){ + this.innerHTML = "BLAH!"; + } + } + }; + + Behaviour.register(myrules); + + // Call Behaviour.apply() to re-apply the rules (if you + // update the dom, etc). + + License: + + This file is entirely BSD licensed. + + More information: + + http://ripcord.co.nz/behaviour/ + +*/ + +var Behaviour = { + list : new Array, + + register : function(sheet){ + Behaviour.list.push(sheet); + }, + + start : function(){ + Behaviour.addLoadEvent(function(){ + Behaviour.apply(); + }); + }, + + apply : function(){ + for (h=0;sheet=Behaviour.list[h];h++){ + for (selector in sheet){ + list = document.getElementsBySelector(selector); + + if (!list){ + continue; + } + + for (i=0;element=list[i];i++){ + sheet[selector](element); + } + } + } + }, + + addLoadEvent : function(func){ + var oldonload = window.onload; + + if (typeof window.onload != 'function') { + window.onload = func; + } else { + window.onload = function() { + oldonload(); + func(); + }; + } + } +}; + +Behaviour.start(); + +/* + The following code is Copyright (C) Simon Willison 2004. + + document.getElementsBySelector(selector) + - returns an array of element objects from the current document + matching the CSS selector. Selectors can contain element names, + class names and ids and can be nested. For example: + + elements = document.getElementsBySelect('div#main p a.external') + + Will return an array of all 'a' elements with 'external' in their + class attribute that are contained inside 'p' elements that are + contained inside the 'div' element which has id="main" + + New in version 0.4: Support for CSS2 and CSS3 attribute selectors: + See http://www.w3.org/TR/css3-selectors/#attribute-selectors + + Version 0.4 - Simon Willison, March 25th 2003 + -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows + -- Opera 7 fails +*/ + +function getAllChildren(e) { + // Returns all children of element. Workaround required for IE5/Windows. Ugh. + return e.all ? e.all : e.getElementsByTagName('*'); +} + +document.getElementsBySelector = function(selector) { + // Attempt to fail gracefully in lesser browsers + if (!document.getElementsByTagName) { + return new Array(); + } + // Split selector in to tokens + var tokens = selector.split(' '); + var currentContext = new Array(document); + for (var i = 0; i < tokens.length; i++) { + token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,''); + if (token.indexOf('#') > -1) { + // Token is an ID selector + var bits = token.split('#'); + var tagName = bits[0]; + var id = bits[1]; + var element = document.getElementById(id); + if (tagName && element.nodeName.toLowerCase() != tagName) { + // tag with that ID not found, return false + return new Array(); + } + // Set currentContext to contain just this element + currentContext = new Array(element); + continue; // Skip to next token + } + if (token.indexOf('.') > -1) { + // Token contains a class selector + var bits = token.split('.'); + var tagName = bits[0]; + var className = bits[1]; + if (!tagName) { + tagName = '*'; + } + // Get elements matching tag, filter them for class selector + var found = new Array; + var foundCount = 0; + for (var h = 0; h < currentContext.length; h++) { + var elements; + if (tagName == '*') { + elements = getAllChildren(currentContext[h]); + } else { + elements = currentContext[h].getElementsByTagName(tagName); + } + for (var j = 0; j < elements.length; j++) { + found[foundCount++] = elements[j]; + } + } + currentContext = new Array; + var currentContextIndex = 0; + for (var k = 0; k < found.length; k++) { + if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) { + currentContext[currentContextIndex++] = found[k]; + } + } + continue; // Skip to next token + } + // Code to deal with attribute selectors + if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) { + var tagName = RegExp.$1; + var attrName = RegExp.$2; + var attrOperator = RegExp.$3; + var attrValue = RegExp.$4; + if (!tagName) { + tagName = '*'; + } + // Grab all of the tagName elements within current context + var found = new Array; + var foundCount = 0; + for (var h = 0; h < currentContext.length; h++) { + var elements; + if (tagName == '*') { + elements = getAllChildren(currentContext[h]); + } else { + elements = currentContext[h].getElementsByTagName(tagName); + } + for (var j = 0; j < elements.length; j++) { + found[foundCount++] = elements[j]; + } + } + currentContext = new Array; + var currentContextIndex = 0; + var checkFunction; // This function will be used to filter the elements + switch (attrOperator) { + case '=': // Equality + checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); }; + break; + case '~': // Match one of space separated words + checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); }; + break; + case '|': // Match start with value followed by optional hyphen + checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); }; + break; + case '^': // Match starts with value + checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); }; + break; + case '$': // Match ends with value - fails with "Warning" in Opera 7 + checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); }; + break; + case '*': // Match ends with value + checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); }; + break; + default : + // Just test for existence of attribute + checkFunction = function(e) { return e.getAttribute(attrName); }; + } + currentContext = new Array; + var currentContextIndex = 0; + for (var k = 0; k < found.length; k++) { + if (checkFunction(found[k])) { + currentContext[currentContextIndex++] = found[k]; + } + } + // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue); + continue; // Skip to next token + } + + if (!currentContext[0]){ + return; + } + + // If we get here, token is JUST an element (not a class or ID selector) + tagName = token; + var found = new Array; + var foundCount = 0; + for (var h = 0; h < currentContext.length; h++) { + var elements = currentContext[h].getElementsByTagName(tagName); + for (var j = 0; j < elements.length; j++) { + found[foundCount++] = elements[j]; + } + } + currentContext = found; + } + return currentContext; +} + +/* That revolting regular expression explained +/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ + \---/ \---/\-------------/ \-------/ + | | | | + | | | The value + | | ~,|,^,$,* or = + | Attribute + Tag +*/ diff --git a/src/usr/local/www/javascript/domTT/domLib.js b/src/usr/local/www/javascript/domTT/domLib.js new file mode 100644 index 0000000..9a51a34 --- /dev/null +++ b/src/usr/local/www/javascript/domTT/domLib.js @@ -0,0 +1,706 @@ +/** $Id: domLib.js 2321 2006-06-12 06:45:41Z dallen $ */ +// {{{ license + +/* + * Copyright 2002-2005 Dan Allen, Mojavelinux.com (dan.allen@mojavelinux.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// }}} +// {{{ intro + +/** + * Title: DOM Library Core + * Version: 0.70 + * + * Summary: + * A set of commonly used functions that make it easier to create javascript + * applications that rely on the DOM. + * + * Updated: 2005/05/17 + * + * Maintainer: Dan Allen + * Maintainer: Jason Rust + * + * License: Apache 2.0 + */ + +// }}} +// {{{ global constants (DO NOT EDIT) + +// -- Browser Detection -- +var domLib_userAgent = navigator.userAgent.toLowerCase(); +var domLib_isMac = navigator.appVersion.indexOf('Mac') != -1; +var domLib_isWin = domLib_userAgent.indexOf('windows') != -1; +// NOTE: could use window.opera for detecting Opera +var domLib_isOpera = domLib_userAgent.indexOf('opera') != -1; +var domLib_isOpera7up = domLib_userAgent.match(/opera.(7|8)/i); +var domLib_isSafari = domLib_userAgent.indexOf('safari') != -1; +var domLib_isKonq = domLib_userAgent.indexOf('konqueror') != -1; +// Both konqueror and safari use the khtml rendering engine +var domLib_isKHTML = (domLib_isKonq || domLib_isSafari || domLib_userAgent.indexOf('khtml') != -1); +var domLib_isIE = (!domLib_isKHTML && !domLib_isOpera && (domLib_userAgent.indexOf('msie 5') != -1 || domLib_userAgent.indexOf('msie 6') != -1 || domLib_userAgent.indexOf('msie 7') != -1 || domLib_userAgent.indexOf('msie 8') != -1)); +var domLib_isIE5up = domLib_isIE; +var domLib_isIE50 = (domLib_isIE && domLib_userAgent.indexOf('msie 5.0') != -1); +var domLib_isIE55 = (domLib_isIE && domLib_userAgent.indexOf('msie 5.5') != -1); +var domLib_isIE5 = (domLib_isIE50 || domLib_isIE55); +// safari and konq may use string "khtml, like gecko", so check for destinctive / +var domLib_isGecko = domLib_userAgent.indexOf('gecko/') != -1; +var domLib_isMacIE = (domLib_isIE && domLib_isMac); +var domLib_isIE55up = domLib_isIE5up && !domLib_isIE50 && !domLib_isMacIE; +var domLib_isIE6up = domLib_isIE55up && !domLib_isIE55; + +// -- Browser Abilities -- +var domLib_standardsMode = (document.compatMode && document.compatMode == 'CSS1Compat'); +var domLib_useLibrary = (domLib_isOpera7up || domLib_isKHTML || domLib_isIE5up || domLib_isGecko || domLib_isMacIE || document.defaultView); +// fixed in Konq3.2 +var domLib_hasBrokenTimeout = (domLib_isMacIE || (domLib_isKonq && domLib_userAgent.match(/konqueror\/3.([2-9])/) == null)); +var domLib_canFade = (domLib_isGecko || domLib_isIE || domLib_isSafari || domLib_isOpera); +var domLib_canDrawOverSelect = (domLib_isMac || domLib_isOpera || domLib_isGecko); +var domLib_canDrawOverFlash = (domLib_isMac || domLib_isWin); + +// -- Event Variables -- +var domLib_eventTarget = domLib_isIE ? 'srcElement' : 'currentTarget'; +var domLib_eventButton = domLib_isIE ? 'button' : 'which'; +var domLib_eventTo = domLib_isIE ? 'toElement' : 'relatedTarget'; +var domLib_stylePointer = domLib_isIE ? 'hand' : 'pointer'; +// NOTE: a bug exists in Opera that prevents maxWidth from being set to 'none', so we make it huge +var domLib_styleNoMaxWidth = domLib_isOpera ? '10000px' : 'none'; +var domLib_hidePosition = '-1000px'; +var domLib_scrollbarWidth = 14; +var domLib_autoId = 1; +var domLib_zIndex = 1010; + +// -- Detection -- +var domLib_collisionElements; +var domLib_collisionsCached = false; + +var domLib_timeoutStateId = 0; +var domLib_timeoutStates = new domTT_Hash(); + +// }}} +// {{{ DOM enhancements + +if (!document.ELEMENT_NODE) +{ + document.ELEMENT_NODE = 1; + document.ATTRIBUTE_NODE = 2; + document.TEXT_NODE = 3; + document.DOCUMENT_NODE = 9; + document.DOCUMENT_FRAGMENT_NODE = 11; +} + +function domLib_clone(obj) +{ + var copy = {}; + for (var i in obj) + { + var value = obj[i]; + try + { + if (value != null && typeof(value) == 'object' && value != window && !value.nodeType) + { + copy[i] = domLib_clone(value); + } + else + { + copy[i] = value; + } + } + catch(e) + { + copy[i] = value; + } + } + + return copy; +} + +// }}} +// {{{ class domTT_Hash() + +function domTT_Hash() +{ + this.length = 0; + this.numericLength = 0; + this.elementData = []; + for (var i = 0; i < arguments.length; i += 2) + { + if (typeof(arguments[i + 1]) != 'undefined') + { + this.elementData[arguments[i]] = arguments[i + 1]; + this.length++; + if (arguments[i] == parseInt(arguments[i])) + { + this.numericLength++; + } + } + } +} + +// using prototype as opposed to inner functions saves on memory +domTT_Hash.prototype.get = function(in_key) +{ + if (typeof(this.elementData[in_key]) != 'undefined') { + return this.elementData[in_key]; + } + + return null; +}; + +domTT_Hash.prototype.set = function(in_key, in_value) +{ + if (typeof(in_value) != 'undefined') + { + if (typeof(this.elementData[in_key]) == 'undefined') + { + this.length++; + if (in_key == parseInt(in_key)) + { + this.numericLength++; + } + } + + return this.elementData[in_key] = in_value; + } + + return false; +}; + +domTT_Hash.prototype.remove = function(in_key) +{ + var tmp_value; + if (typeof(this.elementData[in_key]) != 'undefined') + { + this.length--; + if (in_key == parseInt(in_key)) + { + this.numericLength--; + } + + tmp_value = this.elementData[in_key]; + delete this.elementData[in_key]; + } + + return tmp_value; +}; + +domTT_Hash.prototype.size = function() +{ + return this.length; +}; + +domTT_Hash.prototype.has = function(in_key) +{ + return typeof(this.elementData[in_key]) != 'undefined'; +}; + +domTT_Hash.prototype.find = function(in_obj) +{ + for (var tmp_key in this.elementData) + { + if (this.elementData[tmp_key] == in_obj) + { + return tmp_key; + } + } + + return null; +}; + +domTT_Hash.prototype.merge = function(in_hash) +{ + for (var tmp_key in in_hash.elementData) + { + if (typeof(this.elementData[tmp_key]) == 'undefined') + { + this.length++; + if (tmp_key == parseInt(tmp_key)) + { + this.numericLength++; + } + } + + this.elementData[tmp_key] = in_hash.elementData[tmp_key]; + } +}; + +domTT_Hash.prototype.compare = function(in_hash) +{ + if (this.length != in_hash.length) + { + return false; + } + + for (var tmp_key in this.elementData) + { + if (this.elementData[tmp_key] != in_hash.elementData[tmp_key]) + { + return false; + } + } + + return true; +}; + +// }}} +// {{{ domLib_isDescendantOf() + +function domLib_isDescendantOf(in_object, in_ancestor, in_bannedTags) +{ + if (in_object == null) + { + return false; + } + + if (in_object == in_ancestor) + { + return true; + } + + if (typeof(in_bannedTags) != 'undefined' && + (',' + in_bannedTags.join(',') + ',').indexOf(',' + in_object.tagName + ',') != -1) + { + return false; + } + + while (in_object != document.documentElement) + { + try + { + if ((tmp_object = in_object.offsetParent) && tmp_object == in_ancestor) + { + return true; + } + else if ((tmp_object = in_object.parentNode) == in_ancestor) + { + return true; + } + else + { + in_object = tmp_object; + } + } + // in case we get some wierd error, assume we left the building + catch(e) + { + return false; + } + } + + return false; +} + +// }}} +// {{{ domLib_detectCollisions() + +/** + * For any given target element, determine if elements on the page + * are colliding with it that do not obey the rules of z-index. + */ +function domLib_detectCollisions(in_object, in_recover, in_useCache) +{ + // the reason for the cache is that if the root menu is built before + // the page is done loading, then it might not find all the elements. + // so really the only time you don't use cache is when building the + // menu as part of the page load + if (!domLib_collisionsCached) + { + var tags = []; + + if (!domLib_canDrawOverFlash) + { + tags[tags.length] = 'object'; + } + + if (!domLib_canDrawOverSelect) + { + tags[tags.length] = 'select'; + } + + domLib_collisionElements = domLib_getElementsByTagNames(tags, true); + domLib_collisionsCached = in_useCache; + } + + // if we don't have a tip, then unhide selects + if (in_recover) + { + for (var cnt = 0; cnt < domLib_collisionElements.length; cnt++) + { + var thisElement = domLib_collisionElements[cnt]; + + if (!thisElement.hideList) + { + thisElement.hideList = new domTT_Hash(); + } + + thisElement.hideList.remove(in_object.id); + if (!thisElement.hideList.length) + { + domLib_collisionElements[cnt].style.visibility = 'visible'; + if (domLib_isKonq) + { + domLib_collisionElements[cnt].style.display = ''; + } + } + } + + return; + } + else if (domLib_collisionElements.length == 0) + { + return; + } + + // okay, we have a tip, so hunt and destroy + var objectOffsets = domLib_getOffsets(in_object); + + for (var cnt = 0; cnt < domLib_collisionElements.length; cnt++) + { + var thisElement = domLib_collisionElements[cnt]; + + // if collision element is in active element, move on + // WARNING: is this too costly? + if (domLib_isDescendantOf(thisElement, in_object)) + { + continue; + } + + // konqueror only has trouble with multirow selects + if (domLib_isKonq && + thisElement.tagName == 'SELECT' && + (thisElement.size <= 1 && !thisElement.multiple)) + { + continue; + } + + if (!thisElement.hideList) + { + thisElement.hideList = new domTT_Hash(); + } + + var selectOffsets = domLib_getOffsets(thisElement); + var center2centerDistance = Math.sqrt(Math.pow(selectOffsets.get('leftCenter') - objectOffsets.get('leftCenter'), 2) + Math.pow(selectOffsets.get('topCenter') - objectOffsets.get('topCenter'), 2)); + var radiusSum = selectOffsets.get('radius') + objectOffsets.get('radius'); + // the encompassing circles are overlapping, get in for a closer look + if (center2centerDistance < radiusSum) + { + // tip is left of select + if ((objectOffsets.get('leftCenter') <= selectOffsets.get('leftCenter') && objectOffsets.get('right') < selectOffsets.get('left')) || + // tip is right of select + (objectOffsets.get('leftCenter') > selectOffsets.get('leftCenter') && objectOffsets.get('left') > selectOffsets.get('right')) || + // tip is above select + (objectOffsets.get('topCenter') <= selectOffsets.get('topCenter') && objectOffsets.get('bottom') < selectOffsets.get('top')) || + // tip is below select + (objectOffsets.get('topCenter') > selectOffsets.get('topCenter') && objectOffsets.get('top') > selectOffsets.get('bottom'))) + { + thisElement.hideList.remove(in_object.id); + if (!thisElement.hideList.length) + { + thisElement.style.visibility = 'visible'; + if (domLib_isKonq) + { + thisElement.style.display = ''; + } + } + } + else + { + thisElement.hideList.set(in_object.id, true); + thisElement.style.visibility = 'hidden'; + if (domLib_isKonq) + { + thisElement.style.display = 'none'; + } + } + } + } +} + +// }}} +// {{{ domLib_getOffsets() + +function domLib_getOffsets(in_object, in_preserveScroll) +{ + if (typeof(in_preserveScroll) == 'undefined') { + in_preserveScroll = false; + } + + var originalObject = in_object; + var originalWidth = in_object.offsetWidth; + var originalHeight = in_object.offsetHeight; + var offsetLeft = 0; + var offsetTop = 0; + + while (in_object) + { + offsetLeft += in_object.offsetLeft; + offsetTop += in_object.offsetTop; + in_object = in_object.offsetParent; + // consider scroll offset of parent elements + if (in_object && !in_preserveScroll) + { + offsetLeft -= in_object.scrollLeft; + offsetTop -= in_object.scrollTop; + } + } + + // MacIE misreports the offsets (even with margin: 0 in body{}), still not perfect + if (domLib_isMacIE) { + offsetLeft += 10; + offsetTop += 10; + } + + return new domTT_Hash( + 'left', offsetLeft, + 'top', offsetTop, + 'right', offsetLeft + originalWidth, + 'bottom', offsetTop + originalHeight, + 'leftCenter', offsetLeft + originalWidth/2, + 'topCenter', offsetTop + originalHeight/2, + 'radius', Math.max(originalWidth, originalHeight) + ); +} + +// }}} +// {{{ domLib_setTimeout() + +function domLib_setTimeout(in_function, in_timeout, in_args) +{ + if (typeof(in_args) == 'undefined') + { + in_args = []; + } + + if (in_timeout == -1) + { + // timeout event is disabled + return 0; + } + else if (in_timeout == 0) + { + in_function(in_args); + return 0; + } + + // must make a copy of the arguments so that we release the reference + var args = domLib_clone(in_args); + + if (!domLib_hasBrokenTimeout) + { + return setTimeout(function() { in_function(args); }, in_timeout); + } + else + { + var id = domLib_timeoutStateId++; + var data = new domTT_Hash(); + data.set('function', in_function); + data.set('args', args); + domLib_timeoutStates.set(id, data); + + data.set('timeoutId', setTimeout('domLib_timeoutStates.get(' + id + ').get(\'function\')(domLib_timeoutStates.get(' + id + ').get(\'args\')); domLib_timeoutStates.remove(' + id + ');', in_timeout)); + return id; + } +} + +// }}} +// {{{ domLib_clearTimeout() + +function domLib_clearTimeout(in_id) +{ + if (!domLib_hasBrokenTimeout) + { + if (in_id > 0) { + clearTimeout(in_id); + } + } + else + { + if (domLib_timeoutStates.has(in_id)) + { + clearTimeout(domLib_timeoutStates.get(in_id).get('timeoutId')); + domLib_timeoutStates.remove(in_id); + } + } +} + +// }}} +// {{{ domLib_getEventPosition() + +function domLib_getEventPosition(in_eventObj) +{ + var eventPosition = new domTT_Hash('x', 0, 'y', 0, 'scrollX', 0, 'scrollY', 0); + + // IE varies depending on standard compliance mode + if (domLib_isIE) + { + var doc = (domLib_standardsMode ? document.documentElement : document.body); + // NOTE: events may fire before the body has been loaded + if (doc) + { + eventPosition.set('x', in_eventObj.clientX + doc.scrollLeft); + eventPosition.set('y', in_eventObj.clientY + doc.scrollTop); + eventPosition.set('scrollX', doc.scrollLeft); + eventPosition.set('scrollY', doc.scrollTop); + } + } + else + { + eventPosition.set('x', in_eventObj.pageX); + eventPosition.set('y', in_eventObj.pageY); + eventPosition.set('scrollX', in_eventObj.pageX - in_eventObj.clientX); + eventPosition.set('scrollY', in_eventObj.pageY - in_eventObj.clientY); + } + + return eventPosition; +} + +// }}} +// {{{ domLib_cancelBubble() + +function domLib_cancelBubble(in_event) +{ + var eventObj = in_event ? in_event : window.event; + eventObj.cancelBubble = true; +} + +// }}} +// {{{ domLib_getIFrameReference() + +function domLib_getIFrameReference(in_frame) +{ + if (domLib_isGecko || domLib_isIE) + { + return in_frame.frameElement; + } + else + { + // we could either do it this way or require an id on the frame + // equivalent to the name + var name = in_frame.name; + if (!name || !in_frame.parent) + { + return null; + } + + var candidates = in_frame.parent.document.getElementsByTagName('iframe'); + for (var i = 0; i < candidates.length; i++) + { + if (candidates[i].name == name) + { + return candidates[i]; + } + } + + return null; + } +} + +// }}} +// {{{ domLib_getElementsByClass() + +function domLib_getElementsByClass(in_class) +{ + var elements = domLib_isIE5 ? document.all : document.getElementsByTagName('*'); + var matches = []; + var cnt = 0; + for (var i = 0; i < elements.length; i++) + { + if ((" " + elements[i].className + " ").indexOf(" " + in_class + " ") != -1) + { + matches[cnt++] = elements[i]; + } + } + + return matches; +} + +// }}} +// {{{ domLib_getElementsByTagNames() + +function domLib_getElementsByTagNames(in_list, in_excludeHidden) +{ + var elements = []; + for (var i = 0; i < in_list.length; i++) + { + var matches = document.getElementsByTagName(in_list[i]); + for (var j = 0; j < matches.length; j++) + { + // skip objects that have nested embeds, or else we get "flashing" + if (matches[j].tagName == 'OBJECT' && domLib_isGecko) + { + var kids = matches[j].childNodes; + var skip = false; + for (var k = 0; k < kids.length; k++) + { + if (kids[k].tagName == 'EMBED') + { + skip = true; + break; + } + } + if (skip) continue; + } + + if (in_excludeHidden && domLib_getComputedStyle(matches[j], 'visibility') == 'hidden') + { + continue; + } + + elements[elements.length] = matches[j]; + } + } + + return elements; +} + +// }}} +// {{{ domLib_getComputedStyle() + +function domLib_getComputedStyle(in_obj, in_property) +{ + if (domLib_isIE) + { + var humpBackProp = in_property.replace(/-(.)/, function (a, b) { return b.toUpperCase(); }); + return eval('in_obj.currentStyle.' + humpBackProp); + } + // getComputedStyle() is broken in konqueror, so let's go for the style object + else if (domLib_isKonq) + { + //var humpBackProp = in_property.replace(/-(.)/, function (a, b) { return b.toUpperCase(); }); + return eval('in_obj.style.' + in_property); + } + else + { + return document.defaultView.getComputedStyle(in_obj, null).getPropertyValue(in_property); + } +} + +// }}} +// {{{ makeTrue() + +function makeTrue() +{ + return true; +} + +// }}} +// {{{ makeFalse() + +function makeFalse() +{ + return false; +} + +// }}} diff --git a/src/usr/local/www/javascript/domTT/domTT.js b/src/usr/local/www/javascript/domTT/domTT.js new file mode 100644 index 0000000..fc9bf6a --- /dev/null +++ b/src/usr/local/www/javascript/domTT/domTT.js @@ -0,0 +1,1132 @@ +/** $Id: domTT.js 2324 2006-06-12 07:06:39Z dallen $ */ +// {{{ license + +/* + * Copyright 2002-2005 Dan Allen, Mojavelinux.com (dan.allen@mojavelinux.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// }}} +// {{{ intro + +/** + * Title: DOM Tooltip Library + * Version: 0.7.3 + * + * Summary: + * Allows developers to add custom tooltips to the webpages. Tooltips are + * generated using the domTT_activate() function and customized by setting + * a handful of options. + * + * Maintainer: Dan Allen + * Contributors: + * Josh Gross + * Jason Rust + * + * License: Apache 2.0 + * However, if you use this library, you earn the position of official bug + * reporter :) Please post questions or problem reports to the newsgroup: + * + * http://groups-beta.google.com/group/dom-tooltip + * + * If you are doing this for commercial work, perhaps you could send me a few + * Starbucks Coffee gift dollars or PayPal bucks to encourage future + * developement (NOT REQUIRED). E-mail me for my snail mail address. + + * + * Homepage: http://www.mojavelinux.com/projects/domtooltip/ + * + * Newsgroup: http://groups-beta.google.com/group/dom-tooltip + * + * Freshmeat Project: http://freshmeat.net/projects/domtt/?topic_id=92 + * + * Updated: 2005/07/16 + * + * Supported Browsers: + * Mozilla (Gecko), IE 5.5+, IE on Mac, Safari, Konqueror, Opera 7 + * + * Usage: + * Please see the HOWTO documentation. +**/ + +// }}} +// {{{ settings (editable) + +// IE mouse events seem to be off by 2 pixels +var domTT_offsetX = (domLib_isIE ? -2 : 0); +var domTT_offsetY = (domLib_isIE ? 4 : 2); +var domTT_direction = 'southeast'; +var domTT_mouseHeight = domLib_isIE ? 13 : 19; +var domTT_closeLink = 'X'; +var domTT_closeAction = 'hide'; +var domTT_activateDelay = 500; +var domTT_maxWidth = false; +var domTT_styleClass = 'domTT'; +var domTT_fade = 'neither'; +var domTT_lifetime = 0; +var domTT_grid = 0; +var domTT_trailDelay = 200; +var domTT_useGlobalMousePosition = true; +var domTT_postponeActivation = false; +var domTT_tooltipIdPrefix = '[domTT]'; +var domTT_screenEdgeDetection = true; +var domTT_screenEdgePadding = 4; +var domTT_oneOnly = false; +var domTT_cloneNodes = false; +var domTT_detectCollisions = true; +var domTT_bannedTags = ['OPTION']; +var domTT_draggable = false; +if (typeof(domTT_dragEnabled) == 'undefined') +{ + domTT_dragEnabled = false; +} + +// }}} +// {{{ globals (DO NOT EDIT) + +var domTT_predefined = new domTT_Hash(); +// tooltips are keyed on both the tip id and the owner id, +// since events can originate on either object +var domTT_tooltips = new domTT_Hash(); +var domTT_lastOpened = 0; +var domTT_documentLoaded = false; +var domTT_mousePosition = null; + +// }}} +// {{{ document.onmousemove + +if (domLib_useLibrary && domTT_useGlobalMousePosition) +{ + document.onmousemove = function(in_event) + { + if (typeof(in_event) == 'undefined') { in_event = window.event; } + + domTT_mousePosition = domLib_getEventPosition(in_event); + if (domTT_dragEnabled && domTT_dragMouseDown) + { + domTT_dragUpdate(in_event); + } + }; +} + +// }}} +// {{{ domTT_activate() + +function domTT_activate(in_this, in_event) +{ + if (!domLib_useLibrary || (domTT_postponeActivation && !domTT_documentLoaded)) { return false; } + + // make sure in_event is set (for IE, some cases we have to use window.event) + if (typeof(in_event) == 'undefined') { in_event = window.event; } + + // don't allow tooltips on banned tags (such as OPTION) + if (in_event != null) { + var target = in_event.srcElement ? in_event.srcElement : in_event.target; + if (target != null && (',' + domTT_bannedTags.join(',') + ',').indexOf(',' + target.tagName + ',') != -1) + { + return false; + } + } + + var owner = document.body; + // we have an active event so get the owner + if (in_event != null && in_event.type.match(/key|mouse|click|contextmenu/i)) + { + // make sure we have nothing higher than the body element + if (in_this.nodeType && in_this.nodeType != document.DOCUMENT_NODE) + { + owner = in_this; + } + } + // non active event (make sure we were passed a string id) + else + { + if (typeof(in_this) != 'object' && !(owner = domTT_tooltips.get(in_this))) + { + // NOTE: two steps to avoid "flashing" in gecko + var embryo = document.createElement('div'); + owner = document.body.appendChild(embryo); + owner.style.display = 'none'; + owner.id = in_this; + } + } + + // make sure the owner has a unique id + if (!owner.id) + { + owner.id = '__autoId' + domLib_autoId++; + } + + // see if we should only be opening one tip at a time + // NOTE: this is not "perfect" yet since it really steps on any other + // tip working on fade out or delayed close, but it get's the job done + if (domTT_oneOnly && domTT_lastOpened) + { + domTT_deactivate(domTT_lastOpened); + } + + domTT_lastOpened = owner.id; + + var tooltip = domTT_tooltips.get(owner.id); + if (tooltip) + { + if (tooltip.get('eventType') != in_event.type) + { + if (tooltip.get('type') == 'greasy') + { + tooltip.set('closeAction', 'destroy'); + domTT_deactivate(owner.id); + } + else if (tooltip.get('status') != 'inactive') + { + return owner.id; + } + } + else + { + if (tooltip.get('status') == 'inactive') + { + tooltip.set('status', 'pending'); + tooltip.set('activateTimeout', domLib_setTimeout(domTT_runShow, tooltip.get('delay'), [owner.id, in_event])); + + return owner.id; + } + // either pending or active, let it be + else + { + return owner.id; + } + } + } + + // setup the default options hash + var options = new domTT_Hash( + 'caption', '', + 'content', '', + 'clearMouse', true, + 'closeAction', domTT_closeAction, + 'closeLink', domTT_closeLink, + 'delay', domTT_activateDelay, + 'direction', domTT_direction, + 'draggable', domTT_draggable, + 'fade', domTT_fade, + 'fadeMax', 100, + 'grid', domTT_grid, + 'id', domTT_tooltipIdPrefix + owner.id, + 'inframe', false, + 'lifetime', domTT_lifetime, + 'offsetX', domTT_offsetX, + 'offsetY', domTT_offsetY, + 'parent', document.body, + 'position', 'absolute', + 'styleClass', domTT_styleClass, + 'type', 'greasy', + 'trail', false, + 'lazy', false + ); + + // load in the options from the function call + for (var i = 2; i < arguments.length; i += 2) + { + // load in predefined + if (arguments[i] == 'predefined') + { + var predefinedOptions = domTT_predefined.get(arguments[i + 1]); + for (var j in predefinedOptions.elementData) + { + options.set(j, predefinedOptions.get(j)); + } + } + // set option + else + { + options.set(arguments[i], arguments[i + 1]); + } + } + + options.set('eventType', in_event != null ? in_event.type : null); + + // immediately set the status text if provided + if (options.has('statusText')) + { + try { window.status = options.get('statusText'); } catch(e) {} + } + + // if we didn't give content...assume we just wanted to change the status and return + if (!options.has('content') || options.get('content') == '' || options.get('content') == null) + { + if (typeof(owner.onmouseout) != 'function') + { + owner.onmouseout = function(in_event) { domTT_mouseout(this, in_event); }; + } + + return owner.id; + } + + options.set('owner', owner); + + domTT_create(options); + + // determine the show delay + options.set('delay', (in_event != null && in_event.type.match(/click|mousedown|contextmenu/i)) ? 0 : parseInt(options.get('delay'))); + domTT_tooltips.set(owner.id, options); + domTT_tooltips.set(options.get('id'), options); + options.set('status', 'pending'); + options.set('activateTimeout', domLib_setTimeout(domTT_runShow, options.get('delay'), [owner.id, in_event])); + + return owner.id; +} + +// }}} +// {{{ domTT_create() + +function domTT_create(in_options) +{ + var tipOwner = in_options.get('owner'); + var parentObj = in_options.get('parent'); + var parentDoc = parentObj.ownerDocument || parentObj.document; + + // create the tooltip and hide it + // NOTE: two steps to avoid "flashing" in gecko + var embryo = parentDoc.createElement('div'); + var tipObj = parentObj.appendChild(embryo); + tipObj.style.position = 'absolute'; + tipObj.style.left = '0px'; + tipObj.style.top = '0px'; + tipObj.style.visibility = 'hidden'; + tipObj.id = in_options.get('id'); + tipObj.className = in_options.get('styleClass'); + + var contentBlock; + var tableLayout = false; + + if (in_options.get('caption') || (in_options.get('type') == 'sticky' && in_options.get('caption') !== false)) + { + tableLayout = true; + // layout the tip with a hidden formatting table + var tipLayoutTable = tipObj.appendChild(parentDoc.createElement('table')); + tipLayoutTable.style.borderCollapse = 'collapse'; + if (domLib_isKHTML) + { + tipLayoutTable.cellSpacing = 0; + } + + var tipLayoutTbody = tipLayoutTable.appendChild(parentDoc.createElement('tbody')); + + var numCaptionCells = 0; + var captionRow = tipLayoutTbody.appendChild(parentDoc.createElement('tr')); + var captionCell = captionRow.appendChild(parentDoc.createElement('td')); + captionCell.style.padding = '0px'; + var caption = captionCell.appendChild(parentDoc.createElement('div')); + caption.className = 'caption'; + if (domLib_isIE50) + { + caption.style.height = '100%'; + } + + if (in_options.get('caption').nodeType) + { + caption.appendChild(domTT_cloneNodes ? in_options.get('caption').cloneNode(1) : in_options.get('caption')); + } + else + { + caption.innerHTML = in_options.get('caption'); + } + + if (in_options.get('type') == 'sticky') + { + var numCaptionCells = 2; + var closeLinkCell = captionRow.appendChild(parentDoc.createElement('td')); + closeLinkCell.style.padding = '0px'; + var closeLink = closeLinkCell.appendChild(parentDoc.createElement('div')); + closeLink.className = 'caption'; + if (domLib_isIE50) + { + closeLink.style.height = '100%'; + } + + closeLink.style.textAlign = 'right'; + closeLink.style.cursor = domLib_stylePointer; + // merge the styles of the two cells + closeLink.style.borderLeftWidth = caption.style.borderRightWidth = '0px'; + closeLink.style.paddingLeft = caption.style.paddingRight = '0px'; + closeLink.style.marginLeft = caption.style.marginRight = '0px'; + if (in_options.get('closeLink').nodeType) + { + closeLink.appendChild(in_options.get('closeLink').cloneNode(1)); + } + else + { + closeLink.innerHTML = in_options.get('closeLink'); + } + + closeLink.onclick = function() + { + domTT_deactivate(tipOwner.id); + }; + closeLink.onmousedown = function(in_event) + { + if (typeof(in_event) == 'undefined') { in_event = window.event; } + in_event.cancelBubble = true; + }; + // MacIE has to have a newline at the end and must be made with createTextNode() + if (domLib_isMacIE) + { + closeLinkCell.appendChild(parentDoc.createTextNode("\n")); + } + } + + // MacIE has to have a newline at the end and must be made with createTextNode() + if (domLib_isMacIE) + { + captionCell.appendChild(parentDoc.createTextNode("\n")); + } + + var contentRow = tipLayoutTbody.appendChild(parentDoc.createElement('tr')); + var contentCell = contentRow.appendChild(parentDoc.createElement('td')); + contentCell.style.padding = '0px'; + if (numCaptionCells) + { + if (domLib_isIE || domLib_isOpera) + { + contentCell.colSpan = numCaptionCells; + } + else + { + contentCell.setAttribute('colspan', numCaptionCells); + } + } + + contentBlock = contentCell.appendChild(parentDoc.createElement('div')); + if (domLib_isIE50) + { + contentBlock.style.height = '100%'; + } + } + else + { + contentBlock = tipObj.appendChild(parentDoc.createElement('div')); + } + + contentBlock.className = 'contents'; + + var content = in_options.get('content'); + // allow content has a function to return the actual content + if (typeof(content) == 'function') { + content = content(in_options.get('id')); + } + + if (content != null && content.nodeType) + { + contentBlock.appendChild(domTT_cloneNodes ? content.cloneNode(1) : content); + } + else + { + contentBlock.innerHTML = content; + } + + // adjust the width if specified + if (in_options.has('width')) + { + tipObj.style.width = parseInt(in_options.get('width')) + 'px'; + } + + // check if we are overridding the maxWidth + // if the browser supports maxWidth, the global setting will be ignored (assume stylesheet) + var maxWidth = domTT_maxWidth; + if (in_options.has('maxWidth')) + { + if ((maxWidth = in_options.get('maxWidth')) === false) + { + tipObj.style.maxWidth = domLib_styleNoMaxWidth; + } + else + { + maxWidth = parseInt(in_options.get('maxWidth')); + tipObj.style.maxWidth = maxWidth + 'px'; + } + } + + // HACK: fix lack of maxWidth in CSS for KHTML and IE + if (maxWidth !== false && (domLib_isIE || domLib_isKHTML) && tipObj.offsetWidth > maxWidth) + { + tipObj.style.width = maxWidth + 'px'; + } + + in_options.set('offsetWidth', tipObj.offsetWidth); + in_options.set('offsetHeight', tipObj.offsetHeight); + + // konqueror miscalcuates the width of the containing div when using the layout table based on the + // border size of the containing div + if (domLib_isKonq && tableLayout && !tipObj.style.width) + { + var left = document.defaultView.getComputedStyle(tipObj, '').getPropertyValue('border-left-width'); + var right = document.defaultView.getComputedStyle(tipObj, '').getPropertyValue('border-right-width'); + + left = left.substring(left.indexOf(':') + 2, left.indexOf(';')); + right = right.substring(right.indexOf(':') + 2, right.indexOf(';')); + var correction = 2 * ((left ? parseInt(left) : 0) + (right ? parseInt(right) : 0)); + tipObj.style.width = (tipObj.offsetWidth - correction) + 'px'; + } + + // if a width is not set on an absolutely positioned object, both IE and Opera + // will attempt to wrap when it spills outside of body...we cannot have that + if (domLib_isIE || domLib_isOpera) + { + if (!tipObj.style.width) + { + // HACK: the correction here is for a border + tipObj.style.width = (tipObj.offsetWidth - 2) + 'px'; + } + + // HACK: the correction here is for a border + tipObj.style.height = (tipObj.offsetHeight - 2) + 'px'; + } + + // store placement offsets from event position + var offsetX, offsetY; + + // tooltip floats + if (in_options.get('position') == 'absolute' && !(in_options.has('x') && in_options.has('y'))) + { + // determine the offset relative to the pointer + switch (in_options.get('direction')) + { + case 'northeast': + offsetX = in_options.get('offsetX'); + offsetY = 0 - tipObj.offsetHeight - in_options.get('offsetY'); + break; + case 'northwest': + offsetX = 0 - tipObj.offsetWidth - in_options.get('offsetX'); + offsetY = 0 - tipObj.offsetHeight - in_options.get('offsetY'); + break; + case 'north': + offsetX = 0 - parseInt(tipObj.offsetWidth/2); + offsetY = 0 - tipObj.offsetHeight - in_options.get('offsetY'); + break; + case 'southwest': + offsetX = 0 - tipObj.offsetWidth - in_options.get('offsetX'); + offsetY = in_options.get('offsetY'); + break; + case 'southeast': + offsetX = in_options.get('offsetX'); + offsetY = in_options.get('offsetY'); + break; + case 'south': + offsetX = 0 - parseInt(tipObj.offsetWidth/2); + offsetY = in_options.get('offsetY'); + break; + } + + // if we are in an iframe, get the offsets of the iframe in the parent document + if (in_options.get('inframe')) + { + var iframeObj = domLib_getIFrameReference(window); + if (iframeObj) + { + var frameOffsets = domLib_getOffsets(iframeObj); + offsetX += frameOffsets.get('left'); + offsetY += frameOffsets.get('top'); + } + } + } + // tooltip is fixed + else + { + offsetX = 0; + offsetY = 0; + in_options.set('trail', false); + } + + // set the direction-specific offsetX/Y + in_options.set('offsetX', offsetX); + in_options.set('offsetY', offsetY); + if (in_options.get('clearMouse') && in_options.get('direction').indexOf('south') != -1) + { + in_options.set('mouseOffset', domTT_mouseHeight); + } + else + { + in_options.set('mouseOffset', 0); + } + + if (domLib_canFade && typeof(Fadomatic) == 'function') + { + if (in_options.get('fade') != 'neither') + { + var fadeHandler = new Fadomatic(tipObj, 10, 0, 0, in_options.get('fadeMax')); + in_options.set('fadeHandler', fadeHandler); + } + } + else + { + in_options.set('fade', 'neither'); + } + + // setup mouse events + if (in_options.get('trail') && typeof(tipOwner.onmousemove) != 'function') + { + tipOwner.onmousemove = function(in_event) { domTT_mousemove(this, in_event); }; + } + + if (typeof(tipOwner.onmouseout) != 'function') + { + tipOwner.onmouseout = function(in_event) { domTT_mouseout(this, in_event); }; + } + + if (in_options.get('type') == 'sticky') + { + if (in_options.get('position') == 'absolute' && domTT_dragEnabled && in_options.get('draggable')) + { + if (domLib_isIE) + { + captionRow.onselectstart = function() { return false; }; + } + + // setup drag + captionRow.onmousedown = function(in_event) { domTT_dragStart(tipObj, in_event); }; + captionRow.onmousemove = function(in_event) { domTT_dragUpdate(in_event); }; + captionRow.onmouseup = function() { domTT_dragStop(); }; + } + } + else if (in_options.get('type') == 'velcro') + { + /* can use once we have deactivateDelay + tipObj.onmouseover = function(in_event) + { + if (typeof(in_event) == 'undefined') { in_event = window.event; } + var tooltip = domTT_tooltips.get(tipObj.id); + if (in_options.get('lifetime')) { + domLib_clearTimeout(in_options.get('lifetimeTimeout'); + } + }; + */ + tipObj.onmouseout = function(in_event) + { + if (typeof(in_event) == 'undefined') { in_event = window.event; } + if (!domLib_isDescendantOf(in_event[domLib_eventTo], tipObj, domTT_bannedTags)) { + domTT_deactivate(tipOwner.id); + } + }; + // NOTE: this might interfere with links in the tip + tipObj.onclick = function(in_event) + { + domTT_deactivate(tipOwner.id); + }; + } + + if (in_options.get('position') == 'relative') + { + tipObj.style.position = 'relative'; + } + + in_options.set('node', tipObj); + in_options.set('status', 'inactive'); +} + +// }}} +// {{{ domTT_show() + +// in_id is either tip id or the owner id +function domTT_show(in_id, in_event) +{ + + // should always find one since this call would be cancelled if tip was killed + var tooltip = domTT_tooltips.get(in_id); + var status = tooltip.get('status'); + var tipObj = tooltip.get('node'); + + if (tooltip.get('position') == 'absolute') + { + var mouseX, mouseY; + + if (tooltip.has('x') && tooltip.has('y')) + { + mouseX = tooltip.get('x'); + mouseY = tooltip.get('y'); + } + else if (!domTT_useGlobalMousePosition || domTT_mousePosition == null || status == 'active' || tooltip.get('delay') == 0) + { + var eventPosition = domLib_getEventPosition(in_event); + var eventX = eventPosition.get('x'); + var eventY = eventPosition.get('y'); + if (tooltip.get('inframe')) + { + eventX -= eventPosition.get('scrollX'); + eventY -= eventPosition.get('scrollY'); + } + + // only move tip along requested trail axis when updating position + if (status == 'active' && tooltip.get('trail') !== true) + { + var trail = tooltip.get('trail'); + if (trail == 'x') + { + mouseX = eventX; + mouseY = tooltip.get('mouseY'); + } + else if (trail == 'y') + { + mouseX = tooltip.get('mouseX'); + mouseY = eventY; + } + } + else + { + mouseX = eventX; + mouseY = eventY; + } + } + else + { + mouseX = domTT_mousePosition.get('x'); + mouseY = domTT_mousePosition.get('y'); + if (tooltip.get('inframe')) + { + mouseX -= domTT_mousePosition.get('scrollX'); + mouseY -= domTT_mousePosition.get('scrollY'); + } + } + + // we are using a grid for updates + if (tooltip.get('grid')) + { + // if this is not a mousemove event or it is a mousemove event on an active tip and + // the movement is bigger than the grid + if (in_event.type != 'mousemove' || (status == 'active' && (Math.abs(tooltip.get('lastX') - mouseX) > tooltip.get('grid') || Math.abs(tooltip.get('lastY') - mouseY) > tooltip.get('grid')))) + { + tooltip.set('lastX', mouseX); + tooltip.set('lastY', mouseY); + } + // did not satisfy the grid movement requirement + else + { + return false; + } + } + + // mouseX and mouseY store the last acknowleged mouse position, + // good for trailing on one axis + tooltip.set('mouseX', mouseX); + tooltip.set('mouseY', mouseY); + + var coordinates; + if (domTT_screenEdgeDetection) + { + coordinates = domTT_correctEdgeBleed( + tooltip.get('offsetWidth'), + tooltip.get('offsetHeight'), + mouseX, + mouseY, + tooltip.get('offsetX'), + tooltip.get('offsetY'), + tooltip.get('mouseOffset'), + tooltip.get('inframe') ? window.parent : window + ); + } + else + { + coordinates = { + 'x' : mouseX + tooltip.get('offsetX'), + 'y' : mouseY + tooltip.get('offsetY') + tooltip.get('mouseOffset') + }; + } + + // update the position + tipObj.style.left = coordinates.x + 'px'; + tipObj.style.top = coordinates.y + 'px'; + + // increase the tip zIndex so it goes over previously shown tips + tipObj.style.zIndex = domLib_zIndex++; + } + + // if tip is not active, active it now and check for a fade in + if (status == 'pending') + { + // unhide the tooltip + tooltip.set('status', 'active'); + tipObj.style.display = ''; + tipObj.style.visibility = 'visible'; + + var fade = tooltip.get('fade'); + if (fade != 'neither') + { + var fadeHandler = tooltip.get('fadeHandler'); + if (fade == 'out' || fade == 'both') + { + fadeHandler.haltFade(); + if (fade == 'out') + { + fadeHandler.halt(); + } + } + + if (fade == 'in' || fade == 'both') + { + fadeHandler.fadeIn(); + } + } + + if (tooltip.get('type') == 'greasy' && tooltip.get('lifetime') != 0) + { + tooltip.set('lifetimeTimeout', domLib_setTimeout(domTT_runDeactivate, tooltip.get('lifetime'), [tipObj.id])); + } + } + + if (tooltip.get('position') == 'absolute' && domTT_detectCollisions) + { + // utilize original collision element cache + domLib_detectCollisions(tipObj, false, true); + } +} + +// }}} +// {{{ domTT_close() + +// in_handle can either be an child object of the tip, the tip id or the owner id +function domTT_close(in_handle) +{ + var id; + if (typeof(in_handle) == 'object' && in_handle.nodeType) + { + var obj = in_handle; + while (!obj.id || !domTT_tooltips.get(obj.id)) + { + obj = obj.parentNode; + + if (obj.nodeType != document.ELEMENT_NODE) { return; } + } + + id = obj.id; + } + else + { + id = in_handle; + } + + domTT_deactivate(id); +} + +// }}} +// {{{ domTT_closeAll() + +// run through the tooltips and close them all +function domTT_closeAll() +{ + // NOTE: this will iterate 2x # of tooltips + for (var id in domTT_tooltips.elementData) { + domTT_close(id); + } +} + +// }}} +// {{{ domTT_deactivate() + +// in_id is either the tip id or the owner id +function domTT_deactivate(in_id) +{ + var tooltip = domTT_tooltips.get(in_id); + if (tooltip) + { + var status = tooltip.get('status'); + if (status == 'pending') + { + // cancel the creation of this tip if it is still pending + domLib_clearTimeout(tooltip.get('activateTimeout')); + tooltip.set('status', 'inactive'); + } + else if (status == 'active') + { + if (tooltip.get('lifetime')) + { + domLib_clearTimeout(tooltip.get('lifetimeTimeout')); + } + + var tipObj = tooltip.get('node'); + if (tooltip.get('closeAction') == 'hide') + { + var fade = tooltip.get('fade'); + if (fade != 'neither') + { + var fadeHandler = tooltip.get('fadeHandler'); + if (fade == 'out' || fade == 'both') + { + fadeHandler.fadeOut(); + } + else + { + fadeHandler.hide(); + } + } + else + { + tipObj.style.display = 'none'; + } + } + else + { + tooltip.get('parent').removeChild(tipObj); + domTT_tooltips.remove(tooltip.get('owner').id); + domTT_tooltips.remove(tooltip.get('id')); + } + + tooltip.set('status', 'inactive'); + if (domTT_detectCollisions) { + // unhide all of the selects that are owned by this object + // utilize original collision element cache + domLib_detectCollisions(tipObj, true, true); + } + } + } +} + +// }}} +// {{{ domTT_mouseout() + +function domTT_mouseout(in_owner, in_event) +{ + if (!domLib_useLibrary) { return false; } + + if (typeof(in_event) == 'undefined') { in_event = window.event; } + + var toChild = domLib_isDescendantOf(in_event[domLib_eventTo], in_owner, domTT_bannedTags); + var tooltip = domTT_tooltips.get(in_owner.id); + if (tooltip && (tooltip.get('type') == 'greasy' || tooltip.get('status') != 'active')) + { + // deactivate tip if exists and we moved away from the owner + if (!toChild) + { + domTT_deactivate(in_owner.id); + try { window.status = window.defaultStatus; } catch(e) {} + } + } + else if (!toChild) + { + try { window.status = window.defaultStatus; } catch(e) {} + } +} + +// }}} +// {{{ domTT_mousemove() + +function domTT_mousemove(in_owner, in_event) +{ + if (!domLib_useLibrary) { return false; } + + if (typeof(in_event) == 'undefined') { in_event = window.event; } + + var tooltip = domTT_tooltips.get(in_owner.id); + if (tooltip && tooltip.get('trail') && tooltip.get('status') == 'active') + { + // see if we are trailing lazy + if (tooltip.get('lazy')) + { + domLib_setTimeout(domTT_runShow, domTT_trailDelay, [in_owner.id, in_event]); + } + else + { + domTT_show(in_owner.id, in_event); + } + } +} + +// }}} +// {{{ domTT_addPredefined() + +function domTT_addPredefined(in_id) +{ + var options = new domTT_Hash(); + for (var i = 1; i < arguments.length; i += 2) + { + options.set(arguments[i], arguments[i + 1]); + } + + domTT_predefined.set(in_id, options); +} + +// }}} +// {{{ domTT_correctEdgeBleed() + +function domTT_correctEdgeBleed(in_width, in_height, in_x, in_y, in_offsetX, in_offsetY, in_mouseOffset, in_window) +{ + var win, doc; + var bleedRight, bleedBottom; + var pageHeight, pageWidth, pageYOffset, pageXOffset; + + var x = in_x + in_offsetX; + var y = in_y + in_offsetY + in_mouseOffset; + + win = (typeof(in_window) == 'undefined' ? window : in_window); + + // Gecko and IE swaps values of clientHeight, clientWidth properties when + // in standards compliance mode from documentElement to document.body + doc = ((domLib_standardsMode && (domLib_isIE || domLib_isGecko)) ? win.document.documentElement : win.document.body); + + // for IE in compliance mode + if (domLib_isIE) + { + pageHeight = doc.clientHeight; + pageWidth = doc.clientWidth; + pageYOffset = doc.scrollTop; + pageXOffset = doc.scrollLeft; + } + else + { + pageHeight = doc.clientHeight; + pageWidth = doc.clientWidth; + + if (domLib_isKHTML) + { + pageHeight = win.innerHeight; + } + + pageYOffset = win.pageYOffset; + pageXOffset = win.pageXOffset; + } + + // we are bleeding off the right, move tip over to stay on page + // logic: take x position, add width and subtract from effective page width + if ((bleedRight = (x - pageXOffset) + in_width - (pageWidth - domTT_screenEdgePadding)) > 0) + { + x -= bleedRight; + } + + // we are bleeding to the left, move tip over to stay on page + // if tip doesn't fit, we will go back to bleeding off the right + // logic: take x position and check if less than edge padding + if ((x - pageXOffset) < domTT_screenEdgePadding) + { + x = domTT_screenEdgePadding + pageXOffset; + } + + // if we are bleeding off the bottom, flip to north + // logic: take y position, add height and subtract from effective page height + if ((bleedBottom = (y - pageYOffset) + in_height - (pageHeight - domTT_screenEdgePadding)) > 0) + { + y = in_y - in_height - in_offsetY; + } + + // if we are bleeding off the top, flip to south + // if tip doesn't fit, we will go back to bleeding off the bottom + // logic: take y position and check if less than edge padding + if ((y - pageYOffset) < domTT_screenEdgePadding) + { + y = in_y + domTT_mouseHeight + in_offsetY; + } + + return {'x' : x, 'y' : y}; +} + +// }}} +// {{{ domTT_isActive() + +// in_id is either the tip id or the owner id +function domTT_isActive(in_id) +{ + var tooltip = domTT_tooltips.get(in_id); + if (!tooltip || tooltip.get('status') != 'active') + { + return false; + } + else + { + return true; + } +} + +// }}} +// {{{ domTT_runXXX() + +// All of these domMenu_runXXX() methods are used by the event handling sections to +// avoid the circular memory leaks caused by inner functions +function domTT_runDeactivate(args) { domTT_deactivate(args[0]); } +function domTT_runShow(args) { domTT_show(args[0], args[1]); } + +// }}} +// {{{ domTT_replaceTitles() + +function domTT_replaceTitles(in_decorator) +{ + var elements = domLib_getElementsByClass('tooltip'); + for (var i = 0; i < elements.length; i++) + { + if (elements[i].title) + { + var content; + if (typeof(in_decorator) == 'function') + { + content = in_decorator(elements[i]); + } + else + { + content = elements[i].title; + } + + content = content.replace(new RegExp('\'', 'g'), '\\\''); + elements[i].onmouseover = new Function('in_event', "domTT_activate(this, in_event, 'content', '" + content + "')"); + elements[i].title = ''; + } + } +} + +// }}} +// {{{ domTT_update() + +// Allow authors to update the contents of existing tips using the DOM +// Unfortunately, the tip must already exist, or else no work is done. +// TODO: make getting at content or caption cleaner +function domTT_update(handle, content, type) +{ + // type defaults to 'content', can also be 'caption' + if (typeof(type) == 'undefined') + { + type = 'content'; + } + + var tip = domTT_tooltips.get(handle); + if (!tip) + { + return; + } + + var tipObj = tip.get('node'); + var updateNode; + if (type == 'content') + { + //
                          ... + updateNode = tipObj.firstChild; + if (updateNode.className != 'contents') + { + // ...\s*$/g,rb={option:[1,""],legend:[1,"
                          ","
                          "],area:[1,"",""],param:[1,"",""],thead:[1,"
                          ... + updateNode = updateNode.firstChild.firstChild.nextSibling.firstChild.firstChild; + } + } + else + { + updateNode = tipObj.firstChild; + if (updateNode.className == 'contents') + { + // missing caption + return; + } + + // ' + data[i] + ''); + } + } + } else { + for (var i = rows.length - 1; i >= move; i--) { + jQuery(rows[i]).html(jQuery(rows[i - move]).html()); + } + + var tbody = jQuery('#filter-log-entries'); + for (var i = 0; i < data.length; i++) { + var rowIndex = move - 1 - i; + if (rowIndex >= 0) { + jQuery(rows[rowIndex]).html(data[i]); + } else { + jQuery(tbody).prepend('' + data[i] + ''); + } + } + } + + // Much easier to go through each of the rows once they've all be added. + rows = jQuery('#filter-log-entries>tr'); + for (var i = 0; i < rows.length; i++) { + rows[i].className = i % 2 == 0 ? 'listMRodd' : 'listMReven'; + } +} + +function toggle_pause() { + if(isPaused) { + isPaused = false; + fetch_new_rules(); + } else { + isPaused = true; + } +} +/* start local AJAX engine */ +if (typeof updateDelay != 'undefined') { + timer = setInterval('fetch_new_rules()', updateDelay); +} + +function toggleListDescriptions(){ + var ss = document.styleSheets; + for (var i=0; i + * v1.0 + * 04.11.2008, 8:25 PM ~ + * v1.0a + * 03.27.2008, 5:44 AM ~ 04.01.2008, 21:32 PM + * Azer Koçulu + */ + +var firebug = { + env:{ "cache":{}, "ctmp":[], "dIndex":"console", "init":false, "ml":false, "objCn":[] }, + init:function(){ + firebug.el = {}; // elements + firebug.el.content = {}; + with(firebug){ + + document.documentElement.childNodes[0].appendChild( + new pi.element("link").attribute.set("rel","stylesheet").attribute.set("href","http://firebuglite.appspot.com/firebug-lite.css").environment.getElement() + ); + + /* + * main interface + */ + el.main = new pi.element("DIV").attribute.set("id","Firebug").environment.addStyle({ "width":pi.util.GetWindowSize().width+"px" }).insert(document.body); + el.header = new pi.element("DIV").attribute.addClass("Header").insert(el.main); + el.left = {}; + el.left.container = new pi.element("DIV").attribute.addClass("Left").insert(el.main); + el.right = {}; + el.right.container = new pi.element("DIV").attribute.addClass("Right").insert(el.main); + el.main.child.add(new pi.element("DIV").environment.addStyle({ "clear":"both" })); + + /* + * buttons + */ + el.button = {}; + el.button.container = new pi.element("DIV").attribute.addClass("ButtonContainer").insert(el.header); + el.button.logo = new pi.element("A").attribute.set("title","Firebug Lite").attribute.set("target","_blank").attribute.set("href","http://getfirebug.com/lite.html").update(" ").attribute.addClass("Button Logo").insert(el.button.container); + el.button.inspect = new pi.element("A").attribute.addClass("Button").event.addListener("click",d.inspector.toggle).update("Inspect").insert(el.button.container); + el.button.maximize = new pi.element("A").attribute.addClass("Button Maximize").event.addListener("click",win.maximize).insert(el.button.container); + el.button.minimize = new pi.element("A").attribute.addClass("Button Minimize").event.addListener("click",win.minimize).insert(el.button.container); + el.button.close = new pi.element("A").attribute.addClass("Button Close").event.addListener("click",win.close).insert(el.button.container); + + if(pi.env.ie||pi.env.webkit){ + el.button.container.environment.addStyle({ "paddingTop":"12px" }); + } + + /* + * navigation + */ + el.nav = {}; + el.nav.container = new pi.element("DIV").attribute.addClass("Nav").insert(el.left.container); + el.nav.console = new pi.element("A").attribute.addClass("Tab Selected").event.addListener("click",d.navigate.curry(window,"console")).update("Console").insert(el.nav.container); + el.nav.html = new pi.element("A").attribute.addClass("Tab").update("HTML").event.addListener("click",d.navigate.curry(window,"html")).insert(el.nav.container); + el.nav.css = new pi.element("A").attribute.addClass("Tab").update("CSS").event.addListener("click",d.navigate.curry(window,"css")).insert(el.nav.container); + el.nav.scripts = new pi.element("A").attribute.addClass("Tab").update("Script").event.addListener("click",d.navigate.curry(window,"scripts")).insert(el.nav.container); + el.nav.dom = new pi.element("A").attribute.addClass("Tab").update("DOM").event.addListener("click",d.navigate.curry(window,"dom")).insert(el.nav.container); + el.nav.xhr = new pi.element("A").attribute.addClass("Tab").update("XHR").event.addListener("click",d.navigate.curry(window,"xhr")).insert(el.nav.container); + + /* + * inspector + */ + + el.borderInspector = new pi.element("DIV").attribute.set("id","FirebugBorderInspector").event.addListener("click",listen.inspector).insert(document.body); + el.bgInspector = new pi.element("DIV").attribute.set("id","FirebugBGInspector").insert(document.body); + + /* + * console + */ + el.left.console = {}; + el.left.console.container = new pi.element("DIV").attribute.addClass("Console").insert(el.left.container); + el.left.console.mlButton = new pi.element("A").attribute.addClass("MLButton").event.addListener("click",d.console.toggleML).insert(el.left.console.container); + el.left.console.monitor = new pi.element("DIV").insert( + new pi.element("DIV").attribute.addClass("Monitor").insert(el.left.console.container) + ); + el.left.console.container.child.add( + new pi.element("DIV").attribute.addClass("InputArrow").update(">>>") + ); + el.left.console.input = new pi.element("INPUT").attribute.set("type","text").attribute.addClass("Input").event.addListener("keydown",listen.consoleTextbox).insert( + new pi.element("DIV").attribute.addClass("InputContainer").insert(el.left.console.container) + ); + + el.right.console = {}; + el.right.console.container = new pi.element("DIV").attribute.addClass("Console Container").insert(el.right.container); + el.right.console.mlButton = new pi.element("A").attribute.addClass("MLButton CloseML").event.addListener("click",d.console.toggleML).insert(el.right.console.container); + el.right.console.input = new pi.element("TEXTAREA").attribute.addClass("Input").insert(el.right.console.container); + el.right.console.run = new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.runMultiline).update("Run").insert(el.right.console.container); + + el.right.console.clear = new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.right.console.input)).update("Clear").insert(el.right.console.container); + + el.button.console = {}; + el.button.console.container = new pi.element("DIV").attribute.addClass("ButtonSet").insert(el.button.container); + el.button.console.clear = new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.left.console.monitor)).update("Clear").insert(el.button.console.container); + + /* + * html + */ + + el.left.html = {}; + el.left.html.container = new pi.element("DIV").attribute.addClass("HTML").insert(el.left.container); + + el.right.html = {}; + el.right.html.container = new pi.element("DIV").attribute.addClass("HTML Container").insert(el.right.container); + + el.right.html.nav = {}; + el.right.html.nav.container = new pi.element("DIV").attribute.addClass("Nav").insert(el.right.html.container); + el.right.html.nav.computedStyle = new pi.element("A").attribute.addClass("Tab Selected").event.addListener("click",d.html.navigate.curry(firebug,"computedStyle")).update("Computed Style").insert(el.right.html.nav.container); + if(!pi.env.ie6) + el.right.html.nav.dom = new pi.element("A").attribute.addClass("Tab").event.addListener("click",d.html.navigate.curry(firebug,"dom")).update("DOM").insert(el.right.html.nav.container); + + el.right.html.content = new pi.element("DIV").attribute.addClass("Content").insert(el.right.html.container); + + el.button.html = {}; + el.button.html.container = new pi.element("DIV").attribute.addClass("ButtonSet HTML").insert(el.button.container); + + /* + * css + */ + + el.left.css = {}; + el.left.css.container = new pi.element("DIV").attribute.addClass("CSS").insert(el.left.container); + + el.right.css = {}; + el.right.css.container = new pi.element("DIV").attribute.addClass("CSS Container").insert(el.right.container); + + el.right.css.nav = {}; + el.right.css.nav.container = new pi.element("DIV").attribute.addClass("Nav").insert(el.right.css.container); + el.right.css.nav.runCSS = new pi.element("A").attribute.addClass("Tab Selected").update("Run CSS").insert(el.right.css.nav.container); + + el.right.css.mlButton = new pi.element("A").attribute.addClass("MLButton CloseML").event.addListener("click",d.console.toggleML).insert(el.right.css.container); + el.right.css.input = new pi.element("TEXTAREA").attribute.addClass("Input").insert(el.right.css.container); + el.right.css.run = new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.runCSS).update("Run").insert(el.right.css.container); + el.right.css.clear = new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.right.css.input)).update("Clear").insert(el.right.css.container); + + el.button.css = {}; + el.button.css.container = new pi.element("DIV").attribute.addClass("ButtonSet CSS").insert(el.button.container); + el.button.css.selectbox = new pi.element("SELECT").event.addListener("change",listen.cssSelectbox).insert(el.button.css.container); + + /* + * scripts + */ + + el.left.scripts = {}; + el.left.scripts.container = new pi.element("DIV").attribute.addClass("Scripts").insert(el.left.container); + + el.right.scripts = {}; + el.right.scripts.container = new pi.element("DIV").attribute.addClass("Scripts Container").insert(el.right.container); + + el.button.scripts = {}; + el.button.scripts.container = new pi.element("DIV").attribute.addClass("ButtonSet Scripts").insert(el.button.container); + el.button.scripts.selectbox = new pi.element("SELECT").event.addListener("change",listen.scriptsSelectbox).insert(el.button.scripts.container); + el.button.scripts.lineNumbers = new pi.element("A").attribute.addClass("Button").event.addListener("click",d.scripts.toggleLineNumbers).update("Show Line Numbers").insert(el.button.scripts.container); + + /* + * dom + */ + + el.left.dom = {}; + el.left.dom.container = new pi.element("DIV").attribute.addClass("DOM").insert(el.left.container); + + el.right.dom = {}; + el.right.dom.container = new pi.element("DIV").attribute.addClass("DOM Container").insert(el.right.container); + + el.button.dom = {}; + el.button.dom.container = new pi.element("DIV").attribute.addClass("ButtonSet DOM").insert(el.button.container); + el.button.dom.label = new pi.element("LABEL").update("Object Path:").insert(el.button.dom.container); + el.button.dom.textbox = new pi.element("INPUT").event.addListener("keydown",listen.domTextbox).update("window").insert(el.button.dom.container); + + /* + * str + */ + + el.left.str = {}; + el.left.str.container = new pi.element("DIV").attribute.addClass("STR").insert(el.left.container); + + el.right.str = {}; + el.right.str.container = new pi.element("DIV").attribute.addClass("STR").insert(el.left.container); + + el.button.str = {}; + el.button.str.container = new pi.element("DIV").attribute.addClass("ButtonSet XHR").insert(el.button.container); + el.button.str.watch = new pi.element("A").attribute.addClass("Button").event.addListener("click",d.navigate.curry(window,"xhr")).update("Back").insert(el.button.str.container); + + /* + * xhr + */ + + el.left.xhr = {}; + el.left.xhr.container = new pi.element("DIV").attribute.addClass("XHR").insert(el.left.container); + + el.right.xhr = {}; + el.right.xhr.container = new pi.element("DIV").attribute.addClass("XHR").insert(el.left.container); + + + el.button.xhr = {}; + el.button.xhr.container = new pi.element("DIV").attribute.addClass("ButtonSet XHR").insert(el.button.container); + el.button.xhr.label = new pi.element("LABEL").update("XHR Path:").insert(el.button.xhr.container); + el.button.xhr.textbox = new pi.element("INPUT").event.addListener("keydown",listen.xhrTextbox).insert(el.button.xhr.container); + el.button.xhr.watch = new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.addXhrObject).update("Watch").insert(el.button.xhr.container); + + // fix ie6 a:hover bug + if(pi.env.ie6) + { + var buttons = [ + el.button.inspect, + el.button.close, + el.button.inspect, + el.button.console.clear, + el.right.console.run, + el.right.console.clear, + el.right.css.run, + el.right.css.clear + ]; + for(var i=0; i>> console.dir("+_value+")"); + d.dom.open(_value,d.console.addLine()); + } + }, + addLine:function(){ + with (firebug) { + return new pi.element("DIV").attribute.addClass("Row").insert(el.left.console.monitor); + } + }, + openObject:function(_index){ + with (firebug) { + d.dom.open(env.objCn[_index], el.left.dom.container, pi.env.ie); + d.navigate("dom"); + } + }, + historyIndex:0, + history:[], + log:function(_values){ + with (firebug) { + if(env.init==false){ + env.ctmp.push(arguments); + return; + } + + var value = ""; + for(var i=0; i0?" ":"")+d.highlight(arguments[i],false,false,true); + } + + d.console.addLine().update(value); + d.console.scroll(); + + } + }, + print: function(_cmd,_text){ + with (firebug){ + d.console.addLine().attribute.addClass("Arrow").update(">>> "+_cmd); + d.console.addLine().update(d.highlight(_text,false,false,true)); + d.console.scroll(); + d.console.historyIndex = d.console.history.push(_cmd); + } + }, + run:function(cmd){ + with(firebug){ + if(cmd.length==0)return; + el.left.console.input.environment.getElement().value = ""; + try { + var result = eval.call(window,cmd); + d.console.print(cmd,result); + } catch(e){ + d.console.addLine().attribute.addClass("Arrow").update(">>> "+cmd); + if(!pi.env.ff){ + d.console.scroll(); + return d.console.addLine().attribute.addClass("Error").update("Error: "+(e.description||e),true); + } + if(e.fileName==null){ + d.console.addLine().attribute.addClass("Error").update("Error: "+e.message,true); + } + var fileName = e.fileName.split("\/").getLastItem(); + d.console.addLine().attribute.addClass("Error").update("Error: "+e.message+" ("+fileName+","+e.lineNumber+")",true); + d.console.scroll(); + } + d.console.scroll(); + } + }, + scroll:function(){ + with(firebug){ + el.left.console.monitor.environment.getElement().parentNode.scrollTop = Math.abs(el.left.console.monitor.environment.getSize().offsetHeight-200); + } + }, + toggleML:function(){ + with(firebug){ + var open = !env.ml; + env.ml = !env.ml; + d.navigateRightColumn("console",open); + el[open?"left":"right"].console.mlButton.environment.addStyle({ display:"none" }); + el[!open?"left":"right"].console.mlButton.environment.addStyle({ display:"block" }); + el.left.console.monitor.environment.addStyle({ "height":(open?233:210)+"px" }); + el.left.console.mlButton.attribute[(open?"add":"remove")+"Class"]("CloseML"); + } + } + }, + css:{ + index:-1, + open:function(_index){ + with (firebug) { + var item = document.styleSheets[_index]; + var uri = item.href; + if(uri.indexOf("http:\/\/")>-1&&getDomain(uri)!=document.domain){ + el.left.css.container.update("Access to restricted URI denied"); + return; + } + var rules = item[pi.env.ie ? "rules" : "cssRules"]; + var str = ""; + for (var i=0; i"; + for(var i=0; i<_css.length; i++){ + var item = _css[i]; + str += "
                          "+item.replace(/(.+\:)(.+)/,"$1$2;")+"
                          "; + } + str+="
                          }
                          "; + return str; + } + }, + refresh:function(){ + with(firebug){ + el.button.css.selectbox.update(""); + var collection = document.styleSheets; + for(var i=0; i-1){ + // NULL + if(_value==null){ + return "null"; + } + + // BOOLEAN & NUMBER + if (["boolean", "number"].indexOf(typeof _value) > -1) { + return "" + _value + ""; + } + + // FUNCTION + if(typeof _value=="function"){ + return "function()"; + } + + // STRING + return "\""+( !_inObject&&!_inArray?_value : _value.substring(0,35) ).replace(/\n/g,"\\n").replace(/\s/g," ").replace(/>/g,">").replace(/"; + } + // element + else if(isElement){ + if(_value.nodeType==3)return d.highlight(_value.nodeValue); + + if(_inArray||_inObject){ + var result = ""+_value.nodeName.toLowerCase(); + if(_value.getAttribute&&_value.getAttribute("id"))result += "#"+_value.getAttribute("id")+""; + var elClass = _value.getAttribute?_value.getAttribute(pi.env.ie?"className":"class"):""; + if(elClass)result += "."+elClass.split(" ")[0]+""; + return result+""; + } + + var result = "<"+_value.nodeName.toLowerCase()+""; + if(_value.attributes) + for(var i=0; i<_value.attributes.length; i++){ + var item = _value.attributes[i]; + if(pi.env.ie&&Boolean(item.nodeValue)==false)continue; + result += " "+item.nodeName+"=\""+item.nodeValue+"\""; + } + result += ">"; + return result; + } + // array & object + else if(isArray||["object","array"].indexOf(typeof _value)>-1){ + var result = ""; + if(isArray||_value instanceof Array){ + if(_inObject)return "["+_value.length+"]"; + result += "[ "; + + for(var i=0; i<_value.length; i++){ + if((_inObject||_inArray)&&pi.env.ie&&i>3)break; + result += (i > 0 ? ", " : "") + d.highlight(_value[i], false, true, true); + } + result += " ]"; + return result; + } + if(_inObject)return "Object"; + result += "Object"; + var i=0; + for(var key in _value){ + var value = _value[key]; + if((_inObject||_inArray)&&pi.env.ie&&i>3) + break; + result += " "+key+"="+d.highlight(value,true); + i++; + }; + result += ""; + return result; + } else { + if(_inObject) + return ""+_value+""; + return _value; + } + + } + }, + html:{ + nIndex:"computedStyle", + current:null, + highlight:function(_element,_clear,_event){ + with(firebug){ + if(_clear){ + el.bgInspector.environment.addStyle({ "display":"none" }); + return; + } + d.inspector.inspect(_element,true); + } + }, + inspect:function(_element){ + var el = _element, map = [], parent = _element; + while(parent){ + map.push(parent); + if(parent==document.body)break; + parent = parent.parentNode; + } + map = map.reverse(); + with(firebug){ + d.inspector.toggle(); + var parentLayer = el.left.html.container.child.get()[1].childNodes[1].pi; + for(var t=0; map[t];){ + if(t==map.length-1){ + + var link = parentLayer.environment.getElement().previousSibling.pi; + link.attribute.addClass("Selected"); + + if(d.html.current)d.html.current[1].attribute.removeClass("Selected"); + + d.html.current = [_element,link]; + + return t; + } + parentLayer = d.html.openHtmlTree(map[t],parentLayer,map[t+1]); + t++; + } + } + }, + navigate:function(_index,_element){ + with(firebug){ + el.right.html.nav[d.html.nIndex].attribute.removeClass("Selected"); + el.right.html.nav[_index].attribute.addClass("Selected"); + d.html.nIndex = _index; + d.html.openProperties(); + + } + }, + openHtmlTree:function(_element,_parent,_returnParentElementByElement,_event){ + with(firebug){ + var element = _element || document.documentElement, + parent = _parent || el.left.html.container, + returnParentEl = _returnParentElementByElement || null, + returnParentVal = null; + + if(parent!=el.left.html.container){ + var nodeLink = parent.environment.getParent().pi.child.get()[0].pi; + if(d.html.current)d.html.current[1].attribute.removeClass("Selected"); + nodeLink.attribute.addClass("Selected"); + + d.html.current = [_element,nodeLink]; + d.html.openProperties(); + } + + if(element.childNodes&&(element.childNodes.length==0||(element.childNodes.length==1&&element.childNodes[0].nodeType==3)))return; + parent.clean(); + + if(parent.opened&&Boolean(_returnParentElementByElement)==false){ + parent.opened = false; + parent.environment.getParent().pi.child.get()[0].pi.attribute.removeClass("Open"); + return; + } + if (parent != el.left.html.container) { + parent.environment.getParent().pi.child.get()[0].pi.attribute.addClass("Open"); + parent.opened = true; + + } + + for(var i=0; i")); + continue; + } + else if(item.childNodes&&item.childNodes.length==0)continue; + link.attribute.addClass("ParentLink"); + + } + return returnParentVal; + } + }, + openProperties:function(){ + with(firebug){ + + var index = d.html.nIndex; + var node = d.html.current[0]; + d.clean(el.right.html.content); + var str = ""; + switch(index){ + case "computedStyle": + var property = ["opacity","filter","azimuth","background","backgroundAttachment","backgroundColor","backgroundImage","backgroundPosition","backgroundRepeat","border","borderCollapse","borderColor","borderSpacing","borderStyle","borderTop","borderRight","borderBottom","borderLeft","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","borderTopStyle","borderRightStyle","borderBottomStyle","borderLeftStyle","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderWidth","bottom","captionSide","clear","clip","color","content","counterIncrement","counterReset","cue","cueAfter","cueBefore","cursor","direction","display","elevation","emptyCells","cssFloat","font","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","height","left","letterSpacing","lineHeight","listStyle","listStyleImage","listStylePosition","listStyleType","margin","marginTop","marginRight","marginBottom","marginLeft","markerOffset","marks","maxHeight","maxWidth","minHeight","minWidth","orphans","outline","outlineColor","outlineStyle","outlineWidth","overflow","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","page","pageBreakAfter","pageBreakBefore","pageBreakInside","pause","pauseAfter","pauseBefore","pitch","pitchRange","playDuring","position","quotes","richness","right","size","speak","speakHeader","speakNumeral","speakPunctuation","speechRate","stress","tableLayout","textAlign","textDecoration","textIndent","textShadow","textTransform","top","unicodeBidi","verticalAlign","visibility","voiceFamily","volume","whiteSpace","widows","width","wordSpacing","zIndex"].sort(); + var view = document.defaultView?document.defaultView.getComputedStyle(node,null):node.currentStyle; + for(var i=0; i
                          "+d.highlight(view[item])+"
                          "; + } + el.right.html.content.update(str); + break; + case "dom": + d.dom.open(node,el.right.html.content,pi.env.ie); + break; + } + } + } + }, + inspector:{ + enabled:false, + el:null, + inspect:function(_element,_bgInspector){ + var el = _element, top = el.offsetTop, left = el.offsetLeft, parent = _element.offsetParent; + while(Boolean(parent)&&parent!=document.firstChild){ + top += parent.offsetTop; + left += parent.offsetLeft; + parent = parent.offsetParent; + if(parent==document.body)break; + }; + + with(firebug){ + el[_bgInspector?"bgInspector":"borderInspector"].environment.addStyle({ + "width":_element.offsetWidth+"px", "height":_element.offsetHeight+"px", + "top":top-(_bgInspector?0:2)+"px", "left":left-(_bgInspector?0:2)+"px", + "display":"block" + }); + + if(!_bgInspector){ + d.inspector.el = _element; + } + }; + }, + toggle:function(){ + with (firebug) { + d.inspector.enabled = !d.inspector.enabled; + el.button.inspect.attribute[(d.inspector.enabled ? "add" : "remove") + "Class"]("Enabled"); + if(d.inspector.enabled==false){ + el.borderInspector.environment.addStyle({ "display":"none" }); + d.inspector.el = null; + } else if(pi.env.dIndex!="html") { + d.navigate("html"); + } + } + } + }, + scripts:{ + index:-1, + lineNumbers:false, + open:function(_index){ + with(firebug){ + d.scripts.index = _index; + el.left.scripts.container.update(""); + var script = document.getElementsByTagName("script")[_index],uri = script.src||document.location.href,source; + + if(uri.indexOf("http:\/\/")>-1&&getDomain(uri)!=document.domain){ + el.left.scripts.container.update("Access to restricted URI denied"); + return; + } + + if(uri!=document.location.href){ + source = env.cache[uri]||pi.xhr.get(uri).responseText; + env.cache[uri] = source; + } else + source = script.innerHTML; + source = source.replace(/\n|\t|<|>/g,function(_ch){ + return ({"<":"<",">":">","\t":"        ","\n":"
                          "})[_ch]; + }); + + if (!d.scripts.lineNumbers) + el.left.scripts.container.child.add( + new pi.element("DIV").attribute.addClass("CodeContainer").update(source) + ); + else { + source = source.split("
                          "); + for (var i = 0; i < source.length; i++) { + el.left.scripts.container.child.add(new pi.element("DIV").child.add(new pi.element("DIV").attribute.addClass("LineNumber").update(i + 1), new pi.element("DIV").attribute.addClass("Code").update(" " + source[i]), new pi.element("DIV").environment.addStyle({ + "clear": "both" + }))); + }; + }; + } + }, + toggleLineNumbers:function(){ + with(firebug){ + d.scripts.lineNumbers = !d.scripts.lineNumbers; + el.button.scripts.lineNumbers.attribute[(d.scripts.lineNumbers ? "add" : "remove") + "Class"]("Enabled"); + d.scripts.open( d.scripts.index ); + + } + }, + refresh:function(){ + with(firebug){ + el.button.scripts.selectbox.clean(); + var collection = document.getElementsByTagName("script"); + for(var i=0; i")) + } + } + }, + xhr:{ + objects:[], + addObject:function(){ + with(firebug){ + for(var i=0; i d.console.historyIndex ? + d.console.history[d.console.historyIndex] : + "" + ); + } + }, + cssSelectbox:function(){ + with(firebug){ + d.css.open(el.button.css.selectbox.environment.getElement().selectedIndex); + } + }, + domTextbox:function(_event){ + with(firebug){ + if(_event.keyCode==13){ + d.dom.open(eval(el.button.dom.textbox.environment.getElement().value),el.left.dom.container); + } + } + }, + inspector:function(){ + with(firebug){ + d.html.inspect(d.inspector.el); + } + }, + keyboard:function(_event){ + with(firebug){ + if(_event.keyCode==27&&d.inspector.enabled) + d.inspector.toggle(); + } + }, + mouse:function(_event){ + with(firebug){ + var target = _event[pi.env.ie?"srcElement":"target"]; + if( + d.inspector.enabled&& + target!=document.body&& + target!=document.firstChild&& + target!=document.childNodes[1]&& + target!=el.borderInspector.environment.getElement()&& + target!=el.main.environment.getElement()&& + target.offsetParent!=el.main.environment.getElement() + ) + d.inspector.inspect(target); + } + }, + runMultiline:function(){ + with(firebug){ + d.console.run.call(window,el.right.console.input.environment.getElement().value); + } + }, + runCSS:function(){ + with(firebug){ + var source = el.right.css.input.environment.getElement().value.replace(/\n|\t/g,"").split("}"); + for(var i=0; i0?collection[0]:document.body.appendChild( document.createElement("style") ); + if(!item.match(/.+\{.+\}/))continue; + if(pi.env.ie) + style.styleSheet.addRule(rule[0],rule[1]); + else + style.sheet.insertRule( rule, style.sheet.cssRules.length ); + } + } + }, + scriptsSelectbox:function(){ + with(firebug){ + d.scripts.open(parseInt(el.button.scripts.selectbox.environment.getElement().value)); + } + }, + xhrTextbox:function(_event){ + with(firebug){ + if(_event.keyCode==13){ + d.xhr.addObject.apply(window, el.button.xhr.textbox.environment.getElement().value.split(",")); + } + } + } + } +}; + +window.console = firebug.d.console; +pi.util.AddEvent(window,"resize",firebug.d.refreshSize); +pi.util.AddEvent(document,"mousemove",firebug.listen.mouse); +pi.util.AddEvent(document,"keydown",firebug.listen.keyboard); +pi.util.DOMContentLoaded.push(firebug.init); \ No newline at end of file diff --git a/src/usr/local/www/javascript/firewall_nat_edit/autosuggest.js b/src/usr/local/www/javascript/firewall_nat_edit/autosuggest.js new file mode 100644 index 0000000..d9b5ac0 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_nat_edit/autosuggest.js @@ -0,0 +1,337 @@ + +/** + * An autosuggest textbox control. + * @class + * @scope public + */ +function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, + oProvider /*:SuggestionProvider*/) { + + /** + * The currently selected suggestions. + * @scope private + */ + this.cur /*:int*/ = -1; + + /** + * The dropdown list layer. + * @scope private + */ + this.layer = null; + + /** + * Suggestion provider for the autosuggest feature. + * @scope private. + */ + this.provider /*:SuggestionProvider*/ = oProvider; + + /** + * The textbox to capture. + * @scope private + */ + this.textbox /*:HTMLInputElement*/ = oTextbox; + + //initialize the control + this.init(); + +} + +/** + * Autosuggests one or more suggestions for what the user has typed. + * If no suggestions are passed in, then no autosuggest occurs. + * @scope private + * @param aSuggestions An array of suggestion strings. + * @param bTypeAhead If the control should provide a type ahead suggestion. + */ +AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/, + bTypeAhead /*:boolean*/) { + + //make sure there's at least one suggestion + if (aSuggestions.length > 0) { + if (bTypeAhead) { + this.typeAhead(aSuggestions[0]); + } + + this.showSuggestions(aSuggestions); + } else { + this.hideSuggestions(); + } +}; + +/** + * Creates the dropdown layer to display multiple suggestions. + * @scope private + */ +AutoSuggestControl.prototype.createDropDown = function () { + + var oThis = this; + + //create the layer and assign styles + this.layer = document.createElement("div"); + this.layer.className = "suggestions"; + this.layer.style.visibility = "hidden"; + this.layer.style.width = this.textbox.offsetWidth; + + //when the user clicks on the a suggestion, get the text (innerHTML) + //and place it into a textbox + this.layer.onmousedown = + this.layer.onmouseup = + this.layer.onmouseover = function (oEvent) { + oEvent = oEvent || window.event; + oTarget = oEvent.target || oEvent.srcElement; + + if (oEvent.type == "mousedown") { + oThis.textbox.value = oTarget.firstChild.nodeValue; + oThis.hideSuggestions(); + } else if (oEvent.type == "mouseover") { + oThis.highlightSuggestion(oTarget); + } else { + oThis.textbox.focus(); + } + }; + + + document.body.appendChild(this.layer); +}; + +/** + * Gets the left coordinate of the textbox. + * @scope private + * @return The left coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getLeft = function () /*:int*/ { + + var oNode = this.textbox; + var iLeft = 0; + + while(oNode.tagName != "BODY") { + iLeft += oNode.offsetLeft; + oNode = oNode.offsetParent; + } + + return iLeft; +}; + +/** + * Gets the top coordinate of the textbox. + * @scope private + * @return The top coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getTop = function () /*:int*/ { + + var oNode = this.textbox; + var iTop = 0; + + while(oNode.tagName != "BODY") { + iTop += oNode.offsetTop; + oNode = oNode.offsetParent; + } + + return iTop; +}; + +/** + * Handles three keydown events. + * @scope private + * @param oEvent The event object for the keydown event. + */ +AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) { + + switch(oEvent.keyCode) { + case 38: //up arrow + this.previousSuggestion(); + break; + case 40: //down arrow + this.nextSuggestion(); + break; + case 13: //enter + this.hideSuggestions(); + break; + } + +}; + +/** + * Handles keyup events. + * @scope private + * @param oEvent The event object for the keyup event. + */ +AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) { + + var iKeyCode = oEvent.keyCode; + + //for backspace (8) and delete (46), shows suggestions without typeahead + if (iKeyCode == 8 || iKeyCode == 46) { + this.provider.requestSuggestions(this, false); + + //make sure not to interfere with non-character keys + } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) { + //ignore + } else { + //request suggestions from the suggestion provider with typeahead + this.provider.requestSuggestions(this, true); + } +}; + +/** + * Hides the suggestion dropdown. + * @scope private + */ +AutoSuggestControl.prototype.hideSuggestions = function () { + this.layer.style.visibility = "hidden"; +}; + +/** + * Highlights the given node in the suggestions dropdown. + * @scope private + * @param oSuggestionNode The node representing a suggestion in the dropdown. + */ +AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) { + + for (var i=0; i < this.layer.childNodes.length; i++) { + var oNode = this.layer.childNodes[i]; + if (oNode == oSuggestionNode) { + oNode.className = "current"; + } else if (oNode.className == "current") { + oNode.className = ""; + } + } +}; + +/** + * Initializes the textbox with event handlers for + * auto suggest functionality. + * @scope private + */ +AutoSuggestControl.prototype.init = function () { + + //save a reference to this object + var oThis = this; + + //assign the onkeyup event handler + this.textbox.onkeyup = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyUp() method with the event object + oThis.handleKeyUp(oEvent); + }; + + //assign onkeydown event handler + this.textbox.onkeydown = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyDown() method with the event object + oThis.handleKeyDown(oEvent); + }; + + //assign onblur event handler (hides suggestions) + this.textbox.onblur = function () { + oThis.hideSuggestions(); + }; + + //create the suggestions dropdown + this.createDropDown(); +}; + +/** + * Highlights the next suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.nextSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) { + var oNode = cSuggestionNodes[++this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Highlights the previous suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.previousSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur > 0) { + var oNode = cSuggestionNodes[--this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Selects a range of text in the textbox. + * @scope public + * @param iStart The start index (base 0) of the selection. + * @param iLength The number of characters to select. + */ +AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) { + + //use text ranges for Internet Explorer + if (this.textbox.createTextRange) { + var oRange = this.textbox.createTextRange(); + oRange.moveStart("character", iStart); + oRange.moveEnd("character", iLength - this.textbox.value.length); + oRange.select(); + + //use setSelectionRange() for Mozilla + } else if (this.textbox.setSelectionRange) { + this.textbox.setSelectionRange(iStart, iLength); + } + + //set focus back to the textbox + this.textbox.focus(); +}; + +/** + * Builds the suggestion layer contents, moves it into position, + * and displays the layer. + * @scope private + * @param aSuggestions An array of suggestions for the control. + */ +AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) { + + var oDiv = null; + this.layer.innerHTML = ""; //clear contents of the layer + + for (var i=0; i < aSuggestions.length; i++) { + oDiv = document.createElement("div"); + oDiv.appendChild(document.createTextNode(aSuggestions[i])); + this.layer.appendChild(oDiv); + } + + this.layer.style.left = this.getLeft() + "px"; + this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; + this.layer.style.visibility = "visible"; + +}; + +/** + * Inserts a suggestion into the textbox, highlighting the + * suggested part of the text. + * @scope private + * @param sSuggestion The suggestion for the textbox. + */ +AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) { + + //check for support of typeahead functionality + if (this.textbox.createTextRange || this.textbox.setSelectionRange){ + var iLen = this.textbox.value.length; + this.textbox.value = sSuggestion; + this.selectRange(iLen, sSuggestion.length); + } +}; + diff --git a/src/usr/local/www/javascript/firewall_nat_edit/disablekeys.js b/src/usr/local/www/javascript/firewall_nat_edit/disablekeys.js new file mode 100644 index 0000000..5d6c87a --- /dev/null +++ b/src/usr/local/www/javascript/firewall_nat_edit/disablekeys.js @@ -0,0 +1,6 @@ +function kH(e) { + var pK = document.all? window.event.keyCode:e.which; + return pK != 13; +} +document.onkeypress = kH; +if (document.layers) document.captureEvents(Event.KEYPRESS); \ No newline at end of file diff --git a/src/usr/local/www/javascript/firewall_nat_edit/firewall_nat_edit.js b/src/usr/local/www/javascript/firewall_nat_edit/firewall_nat_edit.js new file mode 100644 index 0000000..7007b40 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_nat_edit/firewall_nat_edit.js @@ -0,0 +1,203 @@ +//= 0 && document.iform.proto.selectedIndex <= 2) { + portsenabled = 1; + } else { + portsenabled = 0; + } + + if (portsenabled) { + document.getElementById("sprtable").style.display = showsource == 1 ? '':'none'; + document.getElementById("dprtr").style.display = ''; + document.getElementById("lprtr").style.display = document.iform.nordr.checked ? 'none' : ''; + } else { + document.getElementById("sprtable").style.display = 'none'; + document.getElementById("dprtr").style.display = 'none'; + document.getElementById("lprtr").style.display = 'none'; + document.getElementById("dstbeginport").selectedIndex = 0; + document.getElementById("dstbeginport_cust").value = ""; + document.getElementById("dstendport").selectedIndex = 0; + document.getElementById("dstendport_cust").value = ""; + document.getElementById("localbeginport").selectedIndex = 0; + document.getElementById("localbeginport_cust").value = ""; + } +} + +function typesel_change() { + switch (document.iform.srctype.selectedIndex) { + case 1: /* single */ + document.iform.src.disabled = 0; + document.iform.srcmask.value = ""; + document.iform.srcmask.disabled = 1; + break; + case 2: /* network */ + document.iform.src.disabled = 0; + document.iform.srcmask.disabled = 0; + break; + default: + document.iform.src.value = ""; + document.iform.src.disabled = 1; + document.iform.srcmask.value = ""; + document.iform.srcmask.disabled = 1; + break; + } + if( dstenabled ) + { + switch (document.iform.dsttype.selectedIndex) { + case 1: /* single */ + document.iform.dst.disabled = 0; + document.iform.dstmask.value = ""; + document.iform.dstmask.disabled = 1; + break; + case 2: /* network */ + document.iform.dst.disabled = 0; + document.iform.dstmask.disabled = 0; + break; + default: + document.iform.dst.value = ""; + document.iform.dst.disabled = 1; + document.iform.dstmask.value = ""; + document.iform.dstmask.disabled = 1; + break; + } + } +} + +function src_rep_change() { + document.iform.srcendport.selectedIndex = document.iform.srcbeginport.selectedIndex; +} + +function dst_rep_change() { + document.iform.dstendport.selectedIndex = document.iform.dstbeginport.selectedIndex; +} + +function dst_change( iface, old_iface, old_dst ) { + if ( ( old_dst == "" ) || ( old_iface.concat("ip") == old_dst ) ) { + document.iform.dsttype.value = iface.concat("ip"); + } +} +//]]> diff --git a/src/usr/local/www/javascript/firewall_nat_edit/suggestions.js b/src/usr/local/www/javascript/firewall_nat_edit/suggestions.js new file mode 100644 index 0000000..4d1e127 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_nat_edit/suggestions.js @@ -0,0 +1,33 @@ + +/** + * Provides suggestions for state names (USA). + * @class + * @scope public + */ +function StateSuggestions(text) { + this.states = text; +} + +/** + * Request suggestions for the given autosuggest control. + * @scope protected + * @param oAutoSuggestControl The autosuggest control to provide suggestions for. + */ +StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/, + bTypeAhead /*:boolean*/) { + var aSuggestions = []; + var sTextboxValue = oAutoSuggestControl.textbox.value; + + if (sTextboxValue.length > 0){ + + //search for matching states + for (var i=0; i < this.states.length; i++) { + if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) { + aSuggestions.push(this.states[i]); + } + } + } + + //provide suggestions to the control + oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead); +}; diff --git a/src/usr/local/www/javascript/firewall_rules_edit/autosuggest.js b/src/usr/local/www/javascript/firewall_rules_edit/autosuggest.js new file mode 100644 index 0000000..d9b5ac0 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_rules_edit/autosuggest.js @@ -0,0 +1,337 @@ + +/** + * An autosuggest textbox control. + * @class + * @scope public + */ +function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, + oProvider /*:SuggestionProvider*/) { + + /** + * The currently selected suggestions. + * @scope private + */ + this.cur /*:int*/ = -1; + + /** + * The dropdown list layer. + * @scope private + */ + this.layer = null; + + /** + * Suggestion provider for the autosuggest feature. + * @scope private. + */ + this.provider /*:SuggestionProvider*/ = oProvider; + + /** + * The textbox to capture. + * @scope private + */ + this.textbox /*:HTMLInputElement*/ = oTextbox; + + //initialize the control + this.init(); + +} + +/** + * Autosuggests one or more suggestions for what the user has typed. + * If no suggestions are passed in, then no autosuggest occurs. + * @scope private + * @param aSuggestions An array of suggestion strings. + * @param bTypeAhead If the control should provide a type ahead suggestion. + */ +AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/, + bTypeAhead /*:boolean*/) { + + //make sure there's at least one suggestion + if (aSuggestions.length > 0) { + if (bTypeAhead) { + this.typeAhead(aSuggestions[0]); + } + + this.showSuggestions(aSuggestions); + } else { + this.hideSuggestions(); + } +}; + +/** + * Creates the dropdown layer to display multiple suggestions. + * @scope private + */ +AutoSuggestControl.prototype.createDropDown = function () { + + var oThis = this; + + //create the layer and assign styles + this.layer = document.createElement("div"); + this.layer.className = "suggestions"; + this.layer.style.visibility = "hidden"; + this.layer.style.width = this.textbox.offsetWidth; + + //when the user clicks on the a suggestion, get the text (innerHTML) + //and place it into a textbox + this.layer.onmousedown = + this.layer.onmouseup = + this.layer.onmouseover = function (oEvent) { + oEvent = oEvent || window.event; + oTarget = oEvent.target || oEvent.srcElement; + + if (oEvent.type == "mousedown") { + oThis.textbox.value = oTarget.firstChild.nodeValue; + oThis.hideSuggestions(); + } else if (oEvent.type == "mouseover") { + oThis.highlightSuggestion(oTarget); + } else { + oThis.textbox.focus(); + } + }; + + + document.body.appendChild(this.layer); +}; + +/** + * Gets the left coordinate of the textbox. + * @scope private + * @return The left coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getLeft = function () /*:int*/ { + + var oNode = this.textbox; + var iLeft = 0; + + while(oNode.tagName != "BODY") { + iLeft += oNode.offsetLeft; + oNode = oNode.offsetParent; + } + + return iLeft; +}; + +/** + * Gets the top coordinate of the textbox. + * @scope private + * @return The top coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getTop = function () /*:int*/ { + + var oNode = this.textbox; + var iTop = 0; + + while(oNode.tagName != "BODY") { + iTop += oNode.offsetTop; + oNode = oNode.offsetParent; + } + + return iTop; +}; + +/** + * Handles three keydown events. + * @scope private + * @param oEvent The event object for the keydown event. + */ +AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) { + + switch(oEvent.keyCode) { + case 38: //up arrow + this.previousSuggestion(); + break; + case 40: //down arrow + this.nextSuggestion(); + break; + case 13: //enter + this.hideSuggestions(); + break; + } + +}; + +/** + * Handles keyup events. + * @scope private + * @param oEvent The event object for the keyup event. + */ +AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) { + + var iKeyCode = oEvent.keyCode; + + //for backspace (8) and delete (46), shows suggestions without typeahead + if (iKeyCode == 8 || iKeyCode == 46) { + this.provider.requestSuggestions(this, false); + + //make sure not to interfere with non-character keys + } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) { + //ignore + } else { + //request suggestions from the suggestion provider with typeahead + this.provider.requestSuggestions(this, true); + } +}; + +/** + * Hides the suggestion dropdown. + * @scope private + */ +AutoSuggestControl.prototype.hideSuggestions = function () { + this.layer.style.visibility = "hidden"; +}; + +/** + * Highlights the given node in the suggestions dropdown. + * @scope private + * @param oSuggestionNode The node representing a suggestion in the dropdown. + */ +AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) { + + for (var i=0; i < this.layer.childNodes.length; i++) { + var oNode = this.layer.childNodes[i]; + if (oNode == oSuggestionNode) { + oNode.className = "current"; + } else if (oNode.className == "current") { + oNode.className = ""; + } + } +}; + +/** + * Initializes the textbox with event handlers for + * auto suggest functionality. + * @scope private + */ +AutoSuggestControl.prototype.init = function () { + + //save a reference to this object + var oThis = this; + + //assign the onkeyup event handler + this.textbox.onkeyup = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyUp() method with the event object + oThis.handleKeyUp(oEvent); + }; + + //assign onkeydown event handler + this.textbox.onkeydown = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyDown() method with the event object + oThis.handleKeyDown(oEvent); + }; + + //assign onblur event handler (hides suggestions) + this.textbox.onblur = function () { + oThis.hideSuggestions(); + }; + + //create the suggestions dropdown + this.createDropDown(); +}; + +/** + * Highlights the next suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.nextSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) { + var oNode = cSuggestionNodes[++this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Highlights the previous suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.previousSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur > 0) { + var oNode = cSuggestionNodes[--this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Selects a range of text in the textbox. + * @scope public + * @param iStart The start index (base 0) of the selection. + * @param iLength The number of characters to select. + */ +AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) { + + //use text ranges for Internet Explorer + if (this.textbox.createTextRange) { + var oRange = this.textbox.createTextRange(); + oRange.moveStart("character", iStart); + oRange.moveEnd("character", iLength - this.textbox.value.length); + oRange.select(); + + //use setSelectionRange() for Mozilla + } else if (this.textbox.setSelectionRange) { + this.textbox.setSelectionRange(iStart, iLength); + } + + //set focus back to the textbox + this.textbox.focus(); +}; + +/** + * Builds the suggestion layer contents, moves it into position, + * and displays the layer. + * @scope private + * @param aSuggestions An array of suggestions for the control. + */ +AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) { + + var oDiv = null; + this.layer.innerHTML = ""; //clear contents of the layer + + for (var i=0; i < aSuggestions.length; i++) { + oDiv = document.createElement("div"); + oDiv.appendChild(document.createTextNode(aSuggestions[i])); + this.layer.appendChild(oDiv); + } + + this.layer.style.left = this.getLeft() + "px"; + this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; + this.layer.style.visibility = "visible"; + +}; + +/** + * Inserts a suggestion into the textbox, highlighting the + * suggested part of the text. + * @scope private + * @param sSuggestion The suggestion for the textbox. + */ +AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) { + + //check for support of typeahead functionality + if (this.textbox.createTextRange || this.textbox.setSelectionRange){ + var iLen = this.textbox.value.length; + this.textbox.value = sSuggestion; + this.selectRange(iLen, sSuggestion.length); + } +}; + diff --git a/src/usr/local/www/javascript/firewall_rules_edit/disablekeys.js b/src/usr/local/www/javascript/firewall_rules_edit/disablekeys.js new file mode 100644 index 0000000..5d6c87a --- /dev/null +++ b/src/usr/local/www/javascript/firewall_rules_edit/disablekeys.js @@ -0,0 +1,6 @@ +function kH(e) { + var pK = document.all? window.event.keyCode:e.which; + return pK != 13; +} +document.onkeypress = kH; +if (document.layers) document.captureEvents(Event.KEYPRESS); \ No newline at end of file diff --git a/src/usr/local/www/javascript/firewall_rules_edit/firewall_rules_edit.js b/src/usr/local/www/javascript/firewall_rules_edit/firewall_rules_edit.js new file mode 100644 index 0000000..de1ff0c --- /dev/null +++ b/src/usr/local/www/javascript/firewall_rules_edit/firewall_rules_edit.js @@ -0,0 +1,237 @@ +//= 0 && document.iform.proto.selectedIndex <= 2) { + document.getElementById("dprtr").style.display = ''; + if (editenabled) { + document.getElementById("showadvancedboxspr").style.display = 'table-row'; + } + } else { + document.getElementById("sprtable").style.display = 'none'; + document.getElementById("dprtr").style.display = 'none'; + document.getElementById("showadvancedboxspr").style.display = 'none'; + } +} + +function show_aodiv() { + document.getElementById("aoadv").innerHTML=''; + aodiv = document.getElementById('aodivmain'); + aodiv.style.display = "block"; +} + +function show_dsdiv() { + document.getElementById("dsadv").innerHTML=''; + dsdiv = document.getElementById('dsdivmain'); + dsdiv.style.display = "block"; +} + +function show_advanced_noxmlrpc() { + document.getElementById("showadvnoxmlrpcsyncbox").innerHTML=''; + aodiv = document.getElementById('shownoxmlrpcadv'); + aodiv.style.display = "block"; +} + +function show_advanced_vlanprio() { + document.getElementById("showadvvlanpriobox").innerHTML=''; + aodiv = document.getElementById('showvlanprioadv'); + aodiv.style.display = "block"; +} + +function show_advanced_schedule() { + document.getElementById("showadvschedulebox").innerHTML=''; + aodiv = document.getElementById('showscheduleadv'); + aodiv.style.display = "block"; +} + +function show_advanced_gateway() { + document.getElementById("showadvgatewaybox").innerHTML=''; + aodiv = document.getElementById('showgatewayadv'); + aodiv.style.display = "block"; +} + +function show_advanced_sourceos() { + document.getElementById("showadvsourceosbox").innerHTML=''; + aodiv = document.getElementById('showsourceosadv'); + aodiv.style.display = "block"; +} + +function show_advanced_ackqueue() { + document.getElementById("showadvackqueuebox").innerHTML=''; + aodiv = document.getElementById('showackqueueadv'); + aodiv.style.display = "block"; +} + +function show_advanced_inout() { + document.getElementById("showadvinoutbox").innerHTML=''; + aodiv = document.getElementById('showinoutadv'); + aodiv.style.display = "block"; +} + +function show_advanced_state() { + document.getElementById("showadvstatebox").innerHTML=''; + aodiv = document.getElementById('showstateadv'); + aodiv.style.display = "block"; +} + +function show_advanced_tcpflags() { + document.getElementById("showtcpflagsbox").innerHTML=''; + aodiv = document.getElementById('showtcpflagsadv'); + aodiv.style.display = "block"; +} + +function show_advanced_layer7() { + document.getElementById("showadvlayer7box").innerHTML=''; + aodiv = document.getElementById('showlayer7adv'); + aodiv.style.display = "block"; +} + +function src_rep_change() { + document.iform.srcendport.selectedIndex = document.iform.srcbeginport.selectedIndex; +} + +function dst_rep_change() { + document.iform.dstendport.selectedIndex = document.iform.dstbeginport.selectedIndex; +} + +function tcpflags_anyclick(obj) { + if (obj.checked) { + document.getElementById('tcpheader').style.display= 'none'; + } else { + document.getElementById('tcpheader').style.display= ""; + } +} +//]]> diff --git a/src/usr/local/www/javascript/firewall_rules_edit/suggestions.js b/src/usr/local/www/javascript/firewall_rules_edit/suggestions.js new file mode 100644 index 0000000..4d1e127 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_rules_edit/suggestions.js @@ -0,0 +1,33 @@ + +/** + * Provides suggestions for state names (USA). + * @class + * @scope public + */ +function StateSuggestions(text) { + this.states = text; +} + +/** + * Request suggestions for the given autosuggest control. + * @scope protected + * @param oAutoSuggestControl The autosuggest control to provide suggestions for. + */ +StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/, + bTypeAhead /*:boolean*/) { + var aSuggestions = []; + var sTextboxValue = oAutoSuggestControl.textbox.value; + + if (sTextboxValue.length > 0){ + + //search for matching states + for (var i=0; i < this.states.length; i++) { + if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) { + aSuggestions.push(this.states[i]); + } + } + } + + //provide suggestions to the control + oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead); +}; diff --git a/src/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js b/src/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js new file mode 100644 index 0000000..d9b5ac0 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js @@ -0,0 +1,337 @@ + +/** + * An autosuggest textbox control. + * @class + * @scope public + */ +function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, + oProvider /*:SuggestionProvider*/) { + + /** + * The currently selected suggestions. + * @scope private + */ + this.cur /*:int*/ = -1; + + /** + * The dropdown list layer. + * @scope private + */ + this.layer = null; + + /** + * Suggestion provider for the autosuggest feature. + * @scope private. + */ + this.provider /*:SuggestionProvider*/ = oProvider; + + /** + * The textbox to capture. + * @scope private + */ + this.textbox /*:HTMLInputElement*/ = oTextbox; + + //initialize the control + this.init(); + +} + +/** + * Autosuggests one or more suggestions for what the user has typed. + * If no suggestions are passed in, then no autosuggest occurs. + * @scope private + * @param aSuggestions An array of suggestion strings. + * @param bTypeAhead If the control should provide a type ahead suggestion. + */ +AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/, + bTypeAhead /*:boolean*/) { + + //make sure there's at least one suggestion + if (aSuggestions.length > 0) { + if (bTypeAhead) { + this.typeAhead(aSuggestions[0]); + } + + this.showSuggestions(aSuggestions); + } else { + this.hideSuggestions(); + } +}; + +/** + * Creates the dropdown layer to display multiple suggestions. + * @scope private + */ +AutoSuggestControl.prototype.createDropDown = function () { + + var oThis = this; + + //create the layer and assign styles + this.layer = document.createElement("div"); + this.layer.className = "suggestions"; + this.layer.style.visibility = "hidden"; + this.layer.style.width = this.textbox.offsetWidth; + + //when the user clicks on the a suggestion, get the text (innerHTML) + //and place it into a textbox + this.layer.onmousedown = + this.layer.onmouseup = + this.layer.onmouseover = function (oEvent) { + oEvent = oEvent || window.event; + oTarget = oEvent.target || oEvent.srcElement; + + if (oEvent.type == "mousedown") { + oThis.textbox.value = oTarget.firstChild.nodeValue; + oThis.hideSuggestions(); + } else if (oEvent.type == "mouseover") { + oThis.highlightSuggestion(oTarget); + } else { + oThis.textbox.focus(); + } + }; + + + document.body.appendChild(this.layer); +}; + +/** + * Gets the left coordinate of the textbox. + * @scope private + * @return The left coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getLeft = function () /*:int*/ { + + var oNode = this.textbox; + var iLeft = 0; + + while(oNode.tagName != "BODY") { + iLeft += oNode.offsetLeft; + oNode = oNode.offsetParent; + } + + return iLeft; +}; + +/** + * Gets the top coordinate of the textbox. + * @scope private + * @return The top coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getTop = function () /*:int*/ { + + var oNode = this.textbox; + var iTop = 0; + + while(oNode.tagName != "BODY") { + iTop += oNode.offsetTop; + oNode = oNode.offsetParent; + } + + return iTop; +}; + +/** + * Handles three keydown events. + * @scope private + * @param oEvent The event object for the keydown event. + */ +AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) { + + switch(oEvent.keyCode) { + case 38: //up arrow + this.previousSuggestion(); + break; + case 40: //down arrow + this.nextSuggestion(); + break; + case 13: //enter + this.hideSuggestions(); + break; + } + +}; + +/** + * Handles keyup events. + * @scope private + * @param oEvent The event object for the keyup event. + */ +AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) { + + var iKeyCode = oEvent.keyCode; + + //for backspace (8) and delete (46), shows suggestions without typeahead + if (iKeyCode == 8 || iKeyCode == 46) { + this.provider.requestSuggestions(this, false); + + //make sure not to interfere with non-character keys + } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) { + //ignore + } else { + //request suggestions from the suggestion provider with typeahead + this.provider.requestSuggestions(this, true); + } +}; + +/** + * Hides the suggestion dropdown. + * @scope private + */ +AutoSuggestControl.prototype.hideSuggestions = function () { + this.layer.style.visibility = "hidden"; +}; + +/** + * Highlights the given node in the suggestions dropdown. + * @scope private + * @param oSuggestionNode The node representing a suggestion in the dropdown. + */ +AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) { + + for (var i=0; i < this.layer.childNodes.length; i++) { + var oNode = this.layer.childNodes[i]; + if (oNode == oSuggestionNode) { + oNode.className = "current"; + } else if (oNode.className == "current") { + oNode.className = ""; + } + } +}; + +/** + * Initializes the textbox with event handlers for + * auto suggest functionality. + * @scope private + */ +AutoSuggestControl.prototype.init = function () { + + //save a reference to this object + var oThis = this; + + //assign the onkeyup event handler + this.textbox.onkeyup = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyUp() method with the event object + oThis.handleKeyUp(oEvent); + }; + + //assign onkeydown event handler + this.textbox.onkeydown = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyDown() method with the event object + oThis.handleKeyDown(oEvent); + }; + + //assign onblur event handler (hides suggestions) + this.textbox.onblur = function () { + oThis.hideSuggestions(); + }; + + //create the suggestions dropdown + this.createDropDown(); +}; + +/** + * Highlights the next suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.nextSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) { + var oNode = cSuggestionNodes[++this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Highlights the previous suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.previousSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur > 0) { + var oNode = cSuggestionNodes[--this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Selects a range of text in the textbox. + * @scope public + * @param iStart The start index (base 0) of the selection. + * @param iLength The number of characters to select. + */ +AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) { + + //use text ranges for Internet Explorer + if (this.textbox.createTextRange) { + var oRange = this.textbox.createTextRange(); + oRange.moveStart("character", iStart); + oRange.moveEnd("character", iLength - this.textbox.value.length); + oRange.select(); + + //use setSelectionRange() for Mozilla + } else if (this.textbox.setSelectionRange) { + this.textbox.setSelectionRange(iStart, iLength); + } + + //set focus back to the textbox + this.textbox.focus(); +}; + +/** + * Builds the suggestion layer contents, moves it into position, + * and displays the layer. + * @scope private + * @param aSuggestions An array of suggestions for the control. + */ +AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) { + + var oDiv = null; + this.layer.innerHTML = ""; //clear contents of the layer + + for (var i=0; i < aSuggestions.length; i++) { + oDiv = document.createElement("div"); + oDiv.appendChild(document.createTextNode(aSuggestions[i])); + this.layer.appendChild(oDiv); + } + + this.layer.style.left = this.getLeft() + "px"; + this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; + this.layer.style.visibility = "visible"; + +}; + +/** + * Inserts a suggestion into the textbox, highlighting the + * suggested part of the text. + * @scope private + * @param sSuggestion The suggestion for the textbox. + */ +AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) { + + //check for support of typeahead functionality + if (this.textbox.createTextRange || this.textbox.setSelectionRange){ + var iLen = this.textbox.value.length; + this.textbox.value = sSuggestion; + this.selectRange(iLen, sSuggestion.length); + } +}; + diff --git a/src/usr/local/www/javascript/firewall_shaper_edit/disablekeys.js b/src/usr/local/www/javascript/firewall_shaper_edit/disablekeys.js new file mode 100644 index 0000000..5d6c87a --- /dev/null +++ b/src/usr/local/www/javascript/firewall_shaper_edit/disablekeys.js @@ -0,0 +1,6 @@ +function kH(e) { + var pK = document.all? window.event.keyCode:e.which; + return pK != 13; +} +document.onkeypress = kH; +if (document.layers) document.captureEvents(Event.KEYPRESS); \ No newline at end of file diff --git a/src/usr/local/www/javascript/firewall_shaper_edit/firewall_shaper_edit.js b/src/usr/local/www/javascript/firewall_shaper_edit/firewall_shaper_edit.js new file mode 100644 index 0000000..b1b8df0 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_shaper_edit/firewall_shaper_edit.js @@ -0,0 +1,37 @@ +// \ No newline at end of file diff --git a/src/usr/local/www/javascript/firewall_shaper_edit/suggestions.js b/src/usr/local/www/javascript/firewall_shaper_edit/suggestions.js new file mode 100644 index 0000000..4d1e127 --- /dev/null +++ b/src/usr/local/www/javascript/firewall_shaper_edit/suggestions.js @@ -0,0 +1,33 @@ + +/** + * Provides suggestions for state names (USA). + * @class + * @scope public + */ +function StateSuggestions(text) { + this.states = text; +} + +/** + * Request suggestions for the given autosuggest control. + * @scope protected + * @param oAutoSuggestControl The autosuggest control to provide suggestions for. + */ +StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/, + bTypeAhead /*:boolean*/) { + var aSuggestions = []; + var sTextboxValue = oAutoSuggestControl.textbox.value; + + if (sTextboxValue.length > 0){ + + //search for matching states + for (var i=0; i < this.states.length; i++) { + if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) { + aSuggestions.push(this.states[i]); + } + } + } + + //provide suggestions to the control + oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead); +}; diff --git a/src/usr/local/www/javascript/global.js b/src/usr/local/www/javascript/global.js new file mode 100644 index 0000000..0b67f58 --- /dev/null +++ b/src/usr/local/www/javascript/global.js @@ -0,0 +1,43 @@ +var AjaxQueue = { + batchSize: 1, //No.of simultaneous AJAX requests allowed, Default : 1 + urlQueue: [], //Request URLs will be pushed into this array + elementsQueue: [], //Element IDs of elements to be updated on completion of a request + optionsQueue: [], //Request options will be pushed into this array + currentRequest: null, + setBatchSize: function(bSize){ //Method to set a different batch size. Recommended: Set batchSize before making requests + this.batchSize = bSize; + }, + push: function(url, options, elementID){ //Push the request in the queue. elementID is optional and required only for Ajax requests that updates the element + this.urlQueue.push(url); + this.optionsQueue.push(options); + if(elementID!=null){ + this.elementsQueue.push(elementID); + } else { + this.elementsQueue.push("NOTSPECIFIED"); + } + + this._processNext(); + }, + _processNext: function() { // Method for processing the requests in the queue. Private method. Don't call it explicitly + if(this.currentRequest == null && this.urlQueue.length > 0) // Check if the currently processing request count is less than batch size + { + // Call jQuery.ajax on the first item in the queue and remove it from the queue + AjaxQueue.currentRequest = jQuery.ajax(AjaxQueue.urlQueue.shift(), AjaxQueue.optionsQueue.shift()); + AjaxQueue.currentRequest.complete( function() { + //Call AjaxQueue._processNext on completion ( success / failure) of this AJAX request. + AjaxQueue.currentRequest = null; + AjaxQueue._processNext(); + }); + if(this.elementsQueue[0]=="NOTSPECIFIED") { //Check if an elementID was specified + // If no ElementID was specified remove the first item from the queue + var junk = AjaxQueue.elementsQueue.shift(); + } else { + // If ElementID was specified update the first item in the queue and remove it from the queue + AjaxQueue.currentRequest.success( function(data) { + jQuery(AjaxQueue.elementsQueue.shift()).html(data); + }); + } + } + } +}; + diff --git a/src/usr/local/www/javascript/index/ajax.js b/src/usr/local/www/javascript/index/ajax.js new file mode 100644 index 0000000..274b8c0 --- /dev/null +++ b/src/usr/local/www/javascript/index/ajax.js @@ -0,0 +1,196 @@ +/* Most widgets update their backend data every 10 seconds. 11 seconds + * will ensure that we update the GUI right after the stats are updated. + * Seconds * 1000 = value + */ +var Seconds = 11; +var update_interval = (Math.abs(Math.ceil(Seconds))-1)*1000 + 990; + +function updateMeters() { + url = '/getstats.php'; + + jQuery.ajax(url, { + type: 'get', + success: function(data) { + response = data || ""; + if (response != "") + stats(data); + } + }); + setTimer(); +} + +function setTimer() { + timeout = window.setTimeout('updateMeters()', update_interval); +} + +function stats(x) { + var values = x.split("|"); + if (jQuery.each(values,function(key,value){ + if (value == 'undefined' || value == null) + return true; + else + return false; + })) + + updateUptime(values[2]); + updateDateTime(values[5]); + updateCPU(values[0]); + updateMemory(values[1]); + updateState(values[3]); + updateTemp(values[4]); + updateInterfaceStats(values[6]); + updateInterfaces(values[7]); + updateGatewayStats(values[8]); + updateCpuFreq(values[9]); + updateLoadAverage(values[10]); + updateMbuf(values[11]); + updateMbufMeter(values[12]); + updateStateMeter(values[13]); +} + +function updateMemory(x) { + if(jQuery('#memusagemeter')) + jQuery("#memusagemeter").html(x + '%'); + if(jQuery('#memUsagePB')) + jQuery('#memUsagePB').progressbar( { value: parseInt(x) } ); +} + +function updateMbuf(x) { + if(jQuery('#mbuf')) + jQuery("#mbuf").html(x); +} + +function updateMbufMeter(x) { + if(jQuery('#mbufusagemeter')) + jQuery("#mbufusagemeter").html(x + '%'); + if(jQuery('#mbufPB')) + jQuery('#mbufPB').progressbar( { value: parseInt(x) } ); +} + +function updateCPU(x) { + if(jQuery('#cpumeter')) + jQuery("#cpumeter").html(x + '%'); + if(jQuery('#cpuPB')) + jQuery('#cpuPB').progressbar( { value: parseInt(x) } ); + /* Load CPU Graph widget if enabled */ + if(widgetActive('cpu_graphs')) { + GraphValue(graph[0], x); + } +} + +function updateTemp(x) { + if(jQuery("#tempmeter")) + jQuery("#tempmeter").html(x + '\u00B0' + 'C'); + if(jQuery('#tempPB')) + jQuery("#tempPB").progressbar( { value: parseInt(x) } ); +} + +function updateDateTime(x) { + if(jQuery('#datetime')) + jQuery("#datetime").html(x); +} + +function updateUptime(x) { + if(jQuery('#uptime')) + jQuery("#uptime").html(x); +} + +function updateState(x) { + if(jQuery('#pfstate')) + jQuery("#pfstate").html(x); +} + +function updateStateMeter(x) { + if(jQuery('#pfstateusagemeter')) + jQuery("#pfstateusagemeter").html(x + '%'); + if(jQuery('#statePB')) + jQuery('#statePB').progressbar( { value: parseInt(x) } ); +} + +function updateGatewayStats(x){ + if (widgetActive("gateways")){ + gateways_split = x.split(","); + for (var y=0; y'; + switch(details[1]) { + case "up": + jQuery('#' + details[0] + '-up').css("display","inline"); + jQuery('#' + details[0] + '-down').css("display","none"); + jQuery('#' + details[0] + '-block').css("display","none"); + jQuery('#' + details[0] + '-ip').html(ipv4_details); + jQuery('#' + details[0] + '-ipv6').html(details[3]); + jQuery('#' + details[0] + '-media').html(details[4]); + break; + case "down": + jQuery('#' + details[0] + '-down').css("display","inline"); + jQuery('#' + details[0] + '-up').css("display","none"); + jQuery('#' + details[0] + '-block').css("display","none"); + jQuery('#' + details[0] + '-ip').html(ipv4_details); + jQuery('#' + details[0] + '-ipv6').html(details[3]); + jQuery('#' + details[0] + '-media').html(details[4]); + break; + case "block": + jQuery('#' + details[0] + '-block').css("display","inline"); + jQuery('#' + details[0] + '-down').css("display","none"); + jQuery('#' + details[0] + '-up').css("display","none"); + break; + } + }); + } +} + +function widgetActive(x) { + var widget = jQuery('#' + x + '-container'); + if ((widget != null) && (widget.css('display') != null) && (widget.css('display') != "none")) + return true; + else + return false; +} + +/* start updater */ +jQuery(document).ready(function(){ + setTimer(); +}); + diff --git a/src/usr/local/www/javascript/interfaces_ppps_edit/ppps_edit.js b/src/usr/local/www/javascript/interfaces_ppps_edit/ppps_edit.js new file mode 100644 index 0000000..45b529b --- /dev/null +++ b/src/usr/local/www/javascript/interfaces_ppps_edit/ppps_edit.js @@ -0,0 +1,253 @@ +/*jslint white: true, sloppy: true, vars: true, eqeq: true */ +/*jslint browser: true, devel: true */ +/*global show_hide_linkfields, jQuery, country_list */ + +function update_select_list(new_options, select_list){ + var option_array = new_options.split("|"); + var i = 0; + var j; + select_list.length = 0; + for(j=0; j < option_array.length-1; j++){ + var option = option_array[j].split(","); + var selected = Boolean(parseInt(option[2], 10)); + select_list[j] = new Option(option[0], option[1], false, selected); + //for testing and debugging + //select_list.options[option_array.length-1+j] = new Option(option[2].toString() +" "+ selected.toString()); + //select_list.options[option_array.length-1+j] = new Option("Link Label: " + linklabel + " Label Text:" + label_text); + } + show_hide_linkfields(select_list); +} + +function show_advanced(hide){ + var select_list = document.iform["interfaces[]"].options; + var adv_rows = parseInt(jQuery('#adv_rows').html(), 10); + var adv_show = Boolean(parseInt(jQuery('#adv_show').html(), 10)); + var status = Boolean(parseInt(hide, 10)); + var j, advanced; + if (status){ + jQuery('#advanced_').hide(); + for(j=0; j < adv_rows; j++){ + advanced = "#advanced_" + j.toString(); + jQuery(advanced).show(); + } + jQuery('#adv_show').html("1"); + show_hide_linkfields(select_list); + } else { + jQuery('#advanced_').show(); + for(j=0; j < adv_rows; j++){ + advanced = "#advanced_" + j.toString(); + jQuery(advanced).hide(); + } + jQuery('#adv_show').html("0"); + show_hide_linkfields(select_list); + } +} + +function show_hide_linkfields(options){ + var i = 0; + var port_count = parseInt(jQuery('#port_count').html(), 10); + var adv_show = Boolean(parseInt(jQuery('#adv_show').html(), 10)); + var j, count, type, link, lnklabel, bw, bwlabel, mtu, mru, mrru, ipfields, gwfields, localip, + localiplabel, subnet, gateway, gatewaylabel; + for(j=0; j < port_count; j++){ + count = j.toString(); + type = jQuery('#type').val(); + link = "#link" + count; + lnklabel = "#linklabel" + count; + bw = "#bandwidth" + count; + bwlabel = "#bwlabel" + count; + mtu = "#mtu" + count; + mru = "#mru" + count; + mrru = "#mrru" + count; + ipfields = "#ip_fields" + count; + gwfields = "#gw_fields" + count; + localip = "#localip" + count; + localiplabel = "#localiplabel" + count; + subnet = "#subnet" + count; + gateway = "#gateway" + count; + gatewaylabel = "#gatewaylabel" + count; + + jQuery(ipfields + ',' + gwfields + ',' + link).hide(); + jQuery(subnet).prop('disabled',true); + + jQuery(bw).attr("name","bandwidth[]"); + jQuery(mtu).attr("name","mtu[]"); + jQuery(mru).attr("name","mru[]"); + jQuery(mrru).attr("name","mrru[]"); + jQuery(localip).attr("name","localip[]"); + jQuery(subnet).attr("name","subnet[]"); + jQuery(gateway).attr("name","gateway[]"); + + while(i < options.length){ + if (options[i].selected ){ + jQuery(lnklabel).html("Link Parameters (" + options[i].value + ")"); + jQuery(bwlabel).html("Bandwidth (" + options[i].value + ")"); + jQuery(bw).attr("name","bandwidth[" + options[i].value + "]"); + jQuery(mtu).attr("name","mtu[" + options[i].value + "]"); + jQuery(mru).attr("name","mru[" + options[i].value + "]"); + jQuery(mrru).attr("name","mrru[" + options[i].value + "]"); + jQuery(localiplabel).html("Local IP (" + options[i].value + ")"); + jQuery(gatewaylabel).html("Gateway (" + options[i].value + ")"); + jQuery(localip).attr("name","localip[" + options[i].value + "]"); + jQuery(subnet).attr("name","subnet[" + options[i].value + "]"); + jQuery(gateway).attr("name","gateway[" + options[i].value + "]"); + if (type == 'ppp' && adv_show){ + jQuery(ipfields + ',' + gwfields).show(); + } + if (type == 'pptp' || type == 'l2tp'){ + jQuery(subnet).prop("disabled",false); + jQuery(ipfields + ',' + gwfields).show(); + } + if (adv_show){ + jQuery(link).show(); + } + i++; + break; + } + i++; + } + } +} + + +function updateType(t){ + var serialports = jQuery('#serialports').html(); + var ports = jQuery('#ports').html(); + var select_list = document.iform["interfaces[]"].options; + jQuery('#adv_show').html("0"); + show_advanced('0'); + jQuery("#select").show(); + switch(t) { + case "select": + jQuery('#ppp,#pppoe,#ppp_provider,#phone_num,#apn_').hide(); + select_list.length = 0; + select_list[0] = new Option("Select Link Type First",""); + break; + case "ppp": + update_select_list(serialports, select_list); + jQuery('#select,#pppoe').hide(); + jQuery('#ppp_provider,#phone_num,#apn_').show(); + country_list(); + break; + case "pppoe": + update_select_list(ports, select_list); + jQuery('#select,#ppp,#ppp_provider,#phone_num,#apn_').hide(); + break; + case "l2tp": + case "pptp": + update_select_list(ports, select_list); + jQuery('#select,#ppp,#pppoe,#ppp_provider,#phone_num,#apn_').hide(); + break; + default: + select_list.length = 0; + select_list[0] = new Option("Select Link Type First",""); + break; + } + if (t == "pppoe" || t == "ppp"){ + jQuery("#" + t).show(); + } +} + +function show_reset_settings(reset_type) { + if (reset_type == 'preset') { + jQuery('#pppoepresetwrap').show(0); + jQuery('#pppoecustomwrap').hide(0); + } + else if (reset_type == 'custom') { + jQuery('#pppoecustomwrap').show(0); + jQuery('#pppoepresetwrap').hide(0); + } else { + jQuery('#pppoecustomwrap').hide(0); + jQuery('#pppoepresetwrap').hide(0); + } +} + +function country_list() { + jQuery('#country option').remove(); + jQuery('#provider option').remove(); + jQuery('#providerplan option').remove(); + jQuery('#country').append(new Option('', '')); + jQuery.ajax("getserviceproviders.php",{ + success: function(responseText) { + var responseTextArr = responseText.split("\n"); + var value, i, country; + responseTextArr.sort(); + for (i = 0; i < responseTextArr.length; i += 1) { + value = responseTextArr[i]; + if (/\S/.test(value)) { + country = value.split(":"); + jQuery('#country').append(new Option(country[0],country[1])); + } + } + } + }); + jQuery('#trcountry').css("display","table-row"); +} + +function providers_list() { + jQuery('#provider option').remove(); + jQuery('#providerplan option').remove(); + jQuery('#provider').append(new Option('', '')); + jQuery.ajax("getserviceproviders.php",{ + type: 'POST', + data: {country : jQuery('#country').val()}, + success: function(responseText) { + var responseTextArr = responseText.split("\n"); + var value, i; + responseTextArr.sort(); + for (i = 0; i < responseTextArr.length; i += 1) { + value = responseTextArr[i]; + if (/\S/.test(value)) { + jQuery('#provider').append(new Option(value, value)); + } + } + } + }); + jQuery('#trprovider').css("display","table-row"); + jQuery('#trproviderplan').css("display","none"); +} + +function providerplan_list() { + jQuery('#providerplan option').remove(); + jQuery('#providerplan').append( new Option('','') ); + jQuery.ajax("getserviceproviders.php",{ + type: 'POST', + data: {country : jQuery('#country').val(), provider : jQuery('#provider').val()}, + success: function(responseText) { + var responseTextArr = responseText.split("\n"); + var value, providerplan, i; + responseTextArr.sort(); + for (i = 0; i < responseTextArr.length; i += 1) { + value = responseTextArr[i]; + if (/\S/.test(value)) { + providerplan = value.split(":"); + jQuery('#providerplan').append(new Option(providerplan[0] + " - " + providerplan[1], + providerplan[1])); + } + } + } + }); + jQuery('#trproviderplan').css("display","table-row"); +} + +function prefill_provider() { + jQuery.ajax("getserviceproviders.php",{ + type: "POST", + data: {country : jQuery('#country').val(), provider : jQuery('#provider').val(), plan : jQuery('#providerplan').val()}, + success: function(responseXML) { + var xmldoc = responseXML; + var provider = xmldoc.getElementsByTagName('connection')[0]; + jQuery('#username').val(''); + jQuery('#password').val(''); + if(provider.getElementsByTagName('apn')[0].firstChild.data == "CDMA") { + jQuery('#phone').val('#777'); + jQuery('#apn').val(''); + } else { + jQuery('#phone').val('*99#'); + jQuery('#apn').val(provider.getElementsByTagName('apn')[0].firstChild.data); + } + jQuery('#username').val(provider.getElementsByTagName('username')[0].firstChild.data); + jQuery('#password').val(provider.getElementsByTagName('password')[0].firstChild.data); + } + }); +} diff --git a/src/usr/local/www/javascript/jquery-1.11.1.min.js b/src/usr/local/www/javascript/jquery-1.11.1.min.js new file mode 100644 index 0000000..ab28a24 --- /dev/null +++ b/src/usr/local/www/javascript/jquery-1.11.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
                          ",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; +if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
                          ... + updateNode = updateNode.firstChild.firstChild.firstChild.firstChild; + } + + // TODO: allow for a DOM node as content + updateNode.innerHTML = content; +} + +// }}} diff --git a/src/usr/local/www/javascript/domTT/fadomatic.js b/src/usr/local/www/javascript/domTT/fadomatic.js new file mode 100644 index 0000000..2c67d0b --- /dev/null +++ b/src/usr/local/www/javascript/domTT/fadomatic.js @@ -0,0 +1,180 @@ +/** $Id$ */ +// Title: Fadomatic +// Version: 1.2 +// Homepage: http://chimpen.com/fadomatic +// Author: Philip McCarthy + +// Fade interval in milliseconds +// Make this larger if you experience performance issues +Fadomatic.INTERVAL_MILLIS = 50; + +// Creates a fader +// element - The element to fade +// speed - The speed to fade at, from 0.0 to 100.0 +// initialOpacity (optional, default 100) - element's starting opacity, 0 to 100 +// minOpacity (optional, default 0) - element's minimum opacity, 0 to 100 +// maxOpacity (optional, default 0) - element's minimum opacity, 0 to 100 +function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity) { + this._element = element; + this._intervalId = null; + this._rate = rate; + this._isFadeOut = true; + + // Set initial opacity and bounds + // NB use 99 instead of 100 to avoid flicker at start of fade + this._minOpacity = 0; + this._maxOpacity = 99; + this._opacity = 99; + + if (typeof minOpacity != 'undefined') { + if (minOpacity < 0) { + this._minOpacity = 0; + } else if (minOpacity > 99) { + this._minOpacity = 99; + } else { + this._minOpacity = minOpacity; + } + } + + if (typeof maxOpacity != 'undefined') { + if (maxOpacity < 0) { + this._maxOpacity = 0; + } else if (maxOpacity > 99) { + this._maxOpacity = 99; + } else { + this._maxOpacity = maxOpacity; + } + + if (this._maxOpacity < this._minOpacity) { + this._maxOpacity = this._minOpacity; + } + } + + if (typeof initialOpacity != 'undefined') { + if (initialOpacity > this._maxOpacity) { + this._opacity = this._maxOpacity; + } else if (initialOpacity < this._minOpacity) { + this._opacity = this._minOpacity; + } else { + this._opacity = initialOpacity; + } + } + + // See if we're using W3C opacity, MSIE filter, or just + // toggling visiblity + if(typeof element.style.opacity != 'undefined') { + + this._updateOpacity = this._updateOpacityW3c; + + } else if(typeof element.style.filter != 'undefined') { + + // If there's not an alpha filter on the element already, + // add one + if (element.style.filter.indexOf("alpha") == -1) { + + // Attempt to preserve existing filters + var existingFilters=""; + if (element.style.filter) { + existingFilters = element.style.filter+" "; + } + element.style.filter = existingFilters+"alpha(opacity="+this._opacity+")"; + } + + this._updateOpacity = this._updateOpacityMSIE; + + } else { + + this._updateOpacity = this._updateVisibility; + } + + this._updateOpacity(); +} + +// Initiates a fade out +Fadomatic.prototype.fadeOut = function () { + this._isFadeOut = true; + this._beginFade(); +}; + +// Initiates a fade in +Fadomatic.prototype.fadeIn = function () { + this._isFadeOut = false; + this._beginFade(); +}; + +// Makes the element completely opaque, stops any fade in progress +Fadomatic.prototype.show = function () { + this.haltFade(); + this._opacity = this._maxOpacity; + this._updateOpacity(); +}; + +// Makes the element completely transparent, stops any fade in progress +Fadomatic.prototype.hide = function () { + this.haltFade(); + this._opacity = 0; + this._updateOpacity(); +}; + +// Halts any fade in progress +Fadomatic.prototype.haltFade = function () { + + clearInterval(this._intervalId); +}; + +// Resumes a fade where it was halted +Fadomatic.prototype.resumeFade = function () { + + this._beginFade(); +}; + +// Pseudo-private members + +Fadomatic.prototype._beginFade = function () { + + this.haltFade(); + var objref = this; + this._intervalId = setInterval(function() { objref._tickFade(); },Fadomatic.INTERVAL_MILLIS); +}; + +Fadomatic.prototype._tickFade = function () { + + if (this._isFadeOut) { + this._opacity -= this._rate; + if (this._opacity < this._minOpacity) { + this._opacity = this._minOpacity; + this.haltFade(); + } + } else { + this._opacity += this._rate; + if (this._opacity > this._maxOpacity ) { + this._opacity = this._maxOpacity; + this.haltFade(); + } + } + + this._updateOpacity(); +}; + +Fadomatic.prototype._updateVisibility = function () { + + if (this._opacity > 0) { + this._element.style.visibility = 'visible'; + } else { + this._element.style.visibility = 'hidden'; + } +}; + +Fadomatic.prototype._updateOpacityW3c = function () { + + this._element.style.opacity = this._opacity/100; + this._updateVisibility(); +}; + +Fadomatic.prototype._updateOpacityMSIE = function () { + + this._element.filters.alpha.opacity = this._opacity; + this._updateVisibility(); +}; + +Fadomatic.prototype._updateOpacity = null; diff --git a/src/usr/local/www/javascript/filter_log.js b/src/usr/local/www/javascript/filter_log.js new file mode 100644 index 0000000..66a7309 --- /dev/null +++ b/src/usr/local/www/javascript/filter_log.js @@ -0,0 +1,168 @@ +if (typeof getURL == 'undefined') { + getURL = function(url, callback) { + if (!url) + throw 'No URL for getURL'; + try { + if (typeof callback.operationComplete == 'function') + callback = callback.operationComplete; + } catch (e) {} + if (typeof callback != 'function') + throw 'No callback function for getURL'; + var http_request = null; + if (typeof XMLHttpRequest != 'undefined') { + http_request = new XMLHttpRequest(); + } + else if (typeof ActiveXObject != 'undefined') { + try { + http_request = new ActiveXObject('Msxml2.XMLHTTP'); + } catch (e) { + try { + http_request = new ActiveXObject('Microsoft.XMLHTTP'); + } catch (e) {} + } + } + if (!http_request) + throw 'Both getURL and XMLHttpRequest are undefined'; + http_request.onreadystatechange = function() { + if (http_request.readyState == 4) { + callback( { success : true, + content : http_request.responseText, + contentType : http_request.getResponseHeader("Content-Type") } ); + } + }; + http_request.open('GET', url, true); + http_request.send(null); + }; +} + +function outputrule(req) { + alert(req.content); +} +function fetch_new_rules() { + if(isPaused) + return; + if(isBusy) + return; + isBusy = true; + getURL('diag_logs_filter_dynamic.php?lastsawtime=' + lastsawtime, fetch_new_rules_callback); +} +function fetch_new_rules_callback(callback_data) { + if(isPaused) + return; + + var data_split; + var new_data_to_add = Array(); + var data = callback_data.content; + + data_split = data.split("\n"); + + for(var x=0; xtr'); + + // Number of rows to move by + var move = rows.length + data.length - nentries; + if (move < 0) + move = 0; + + if (isReverse == false) { + for (var i = move; i < rows.length; i++) { + jQuery(rows[i - move]).html(jQuery(rows[i]).html()); + } + + var tbody = jQuery('#filter-log-entries'); + for (var i = 0; i < data.length; i++) { + var rowIndex = rows.length - move + i; + if (rowIndex < rows.length) { + jQuery(rows[rowIndex]).html(data[i]); + } else { + jQuery(tbody).append('
                          a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/
                          ","
                          "],tr:[2,"","
                          "],col:[2,"","
                          "],td:[3,"","
                          "],_default:k.htmlSerialize?[0,"",""]:[1,"X
                          ","
                          "]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("'); + this.iefix = $(this.update.id+'_iefix'); + } + if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); + }, + + fixIEOverlapping: function() { + Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); + this.iefix.style.zIndex = 1; + this.update.style.zIndex = 2; + Element.show(this.iefix); + }, + + hide: function() { + this.stopIndicator(); + if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); + if(this.iefix) Element.hide(this.iefix); + }, + + startIndicator: function() { + if(this.options.indicator) Element.show(this.options.indicator); + }, + + stopIndicator: function() { + if(this.options.indicator) Element.hide(this.options.indicator); + }, + + onKeyPress: function(event) { + if(this.active) + switch(event.keyCode) { + case Event.KEY_TAB: + case Event.KEY_RETURN: + this.selectEntry(); + Event.stop(event); + case Event.KEY_ESC: + this.hide(); + this.active = false; + Event.stop(event); + return; + case Event.KEY_LEFT: + case Event.KEY_RIGHT: + return; + case Event.KEY_UP: + this.markPrevious(); + this.render(); + Event.stop(event); + return; + case Event.KEY_DOWN: + this.markNext(); + this.render(); + Event.stop(event); + return; + } + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; + + this.changed = true; + this.hasFocus = true; + + if(this.observer) clearTimeout(this.observer); + this.observer = + setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); + }, + + activate: function() { + this.changed = false; + this.hasFocus = true; + this.getUpdatedChoices(); + }, + + onHover: function(event) { + var element = Event.findElement(event, 'LI'); + if(this.index != element.autocompleteIndex) + { + this.index = element.autocompleteIndex; + this.render(); + } + Event.stop(event); + }, + + onClick: function(event) { + var element = Event.findElement(event, 'LI'); + this.index = element.autocompleteIndex; + this.selectEntry(); + this.hide(); + }, + + onBlur: function(event) { + // needed to make click events working + setTimeout(this.hide.bind(this), 250); + this.hasFocus = false; + this.active = false; + }, + + render: function() { + if(this.entryCount > 0) { + for (var i = 0; i < this.entryCount; i++) + this.index==i ? + Element.addClassName(this.getEntry(i),"selected") : + Element.removeClassName(this.getEntry(i),"selected"); + if(this.hasFocus) { + this.show(); + this.active = true; + } + } else { + this.active = false; + this.hide(); + } + }, + + markPrevious: function() { + if(this.index > 0) this.index--; + else this.index = this.entryCount-1; + this.getEntry(this.index).scrollIntoView(true); + }, + + markNext: function() { + if(this.index < this.entryCount-1) this.index++; + else this.index = 0; + this.getEntry(this.index).scrollIntoView(false); + }, + + getEntry: function(index) { + return this.update.firstChild.childNodes[index]; + }, + + getCurrentEntry: function() { + return this.getEntry(this.index); + }, + + selectEntry: function() { + this.active = false; + this.updateElement(this.getCurrentEntry()); + }, + + updateElement: function(selectedElement) { + if (this.options.updateElement) { + this.options.updateElement(selectedElement); + return; + } + var value = ''; + if (this.options.select) { + var nodes = $(selectedElement).select('.' + this.options.select) || []; + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); + } else + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); + + var bounds = this.getTokenBounds(); + if (bounds[0] != -1) { + var newValue = this.element.value.substr(0, bounds[0]); + var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/); + if (whitespace) + newValue += whitespace[0]; + this.element.value = newValue + value + this.element.value.substr(bounds[1]); + } else { + this.element.value = value; + } + this.oldElementValue = this.element.value; + this.element.focus(); + + if (this.options.afterUpdateElement) + this.options.afterUpdateElement(this.element, selectedElement); + }, + + updateChoices: function(choices) { + if(!this.changed && this.hasFocus) { + this.update.innerHTML = choices; + Element.cleanWhitespace(this.update); + Element.cleanWhitespace(this.update.down()); + + if(this.update.firstChild && this.update.down().childNodes) { + this.entryCount = + this.update.down().childNodes.length; + for (var i = 0; i < this.entryCount; i++) { + var entry = this.getEntry(i); + entry.autocompleteIndex = i; + this.addObservers(entry); + } + } else { + this.entryCount = 0; + } + + this.stopIndicator(); + this.index = 0; + + if(this.entryCount==1 && this.options.autoSelect) { + this.selectEntry(); + this.hide(); + } else { + this.render(); + } + } + }, + + addObservers: function(element) { + Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); + Event.observe(element, "click", this.onClick.bindAsEventListener(this)); + }, + + onObserverEvent: function() { + this.changed = false; + this.tokenBounds = null; + if(this.getToken().length>=this.options.minChars) { + this.getUpdatedChoices(); + } else { + this.active = false; + this.hide(); + } + this.oldElementValue = this.element.value; + }, + + getToken: function() { + var bounds = this.getTokenBounds(); + return this.element.value.substring(bounds[0], bounds[1]).strip(); + }, + + getTokenBounds: function() { + if (null != this.tokenBounds) return this.tokenBounds; + var value = this.element.value; + if (value.strip().empty()) return [-1, 0]; + var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue); + var offset = (diff == this.oldElementValue.length ? 1 : 0); + var prevTokenPos = -1, nextTokenPos = value.length; + var tp; + for (var index = 0, l = this.options.tokens.length; index < l; ++index) { + tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1); + if (tp > prevTokenPos) prevTokenPos = tp; + tp = value.indexOf(this.options.tokens[index], diff + offset); + if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp; + } + return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]); + } +}); + +Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) { + var boundary = Math.min(newS.length, oldS.length); + for (var index = 0; index < boundary; ++index) + if (newS[index] != oldS[index]) + return index; + return boundary; +}; + +Ajax.Autocompleter = Class.create(Autocompleter.Base, { + initialize: function(element, update, url, options) { + this.baseInitialize(element, update, options); + this.options.asynchronous = true; + this.options.onComplete = this.onComplete.bind(this); + this.options.defaultParams = this.options.parameters || null; + this.url = url; + }, + + getUpdatedChoices: function() { + this.startIndicator(); + + var entry = encodeURIComponent(this.options.paramName) + '=' + + encodeURIComponent(this.getToken()); + + this.options.parameters = this.options.callback ? + this.options.callback(this.element, entry) : entry; + + if(this.options.defaultParams) + this.options.parameters += '&' + this.options.defaultParams; + + new Ajax.Request(this.url, this.options); + }, + + onComplete: function(request) { + this.updateChoices(request.responseText); + } +}); + +// The local array autocompleter. Used when you'd prefer to +// inject an array of autocompletion options into the page, rather +// than sending out Ajax queries, which can be quite slow sometimes. +// +// The constructor takes four parameters. The first two are, as usual, +// the id of the monitored textbox, and id of the autocompletion menu. +// The third is the array you want to autocomplete from, and the fourth +// is the options block. +// +// Extra local autocompletion options: +// - choices - How many autocompletion choices to offer +// +// - partialSearch - If false, the autocompleter will match entered +// text only at the beginning of strings in the +// autocomplete array. Defaults to true, which will +// match text at the beginning of any *word* in the +// strings in the autocomplete array. If you want to +// search anywhere in the string, additionally set +// the option fullSearch to true (default: off). +// +// - fullSsearch - Search anywhere in autocomplete array strings. +// +// - partialChars - How many characters to enter before triggering +// a partial match (unlike minChars, which defines +// how many characters are required to do any match +// at all). Defaults to 2. +// +// - ignoreCase - Whether to ignore case when autocompleting. +// Defaults to true. +// +// It's possible to pass in a custom function as the 'selector' +// option, if you prefer to write your own autocompletion logic. +// In that case, the other options above will not apply unless +// you support them. + +Autocompleter.Local = Class.create(Autocompleter.Base, { + initialize: function(element, update, array, options) { + this.baseInitialize(element, update, options); + this.options.array = array; + }, + + getUpdatedChoices: function() { + this.updateChoices(this.options.selector(this)); + }, + + setOptions: function(options) { + this.options = Object.extend({ + choices: 10, + partialSearch: true, + partialChars: 2, + ignoreCase: true, + fullSearch: false, + selector: function(instance) { + var ret = []; // Beginning matches + var partial = []; // Inside matches + var entry = instance.getToken(); + var count = 0; + + for (var i = 0; i < instance.options.array.length && + ret.length < instance.options.choices ; i++) { + + var elem = instance.options.array[i]; + var foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase()) : + elem.indexOf(entry); + + while (foundPos != -1) { + if (foundPos == 0 && elem.length != entry.length) { + ret.push("
                        • " + elem.substr(0, entry.length) + "" + + elem.substr(entry.length) + "
                        • "); + break; + } else if (entry.length >= instance.options.partialChars && + instance.options.partialSearch && foundPos != -1) { + if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { + partial.push("
                        • " + elem.substr(0, foundPos) + "" + + elem.substr(foundPos, entry.length) + "" + elem.substr( + foundPos + entry.length) + "
                        • "); + break; + } + } + + foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : + elem.indexOf(entry, foundPos + 1); + + } + } + if (partial.length) + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)); + return "
                            " + ret.join('') + "
                          "; + } + }, options || { }); + } +}); + +// AJAX in-place editor and collection editor +// Full rewrite by Christophe Porteneuve (April 2007). + +// Use this if you notice weird scrolling problems on some browsers, +// the DOM might be a bit confused when this gets called so do this +// waits 1 ms (with setTimeout) until it does the activation +Field.scrollFreeActivate = function(field) { + setTimeout(function() { + Field.activate(field); + }, 1); +}; + +Ajax.InPlaceEditor = Class.create({ + initialize: function(element, url, options) { + this.url = url; + this.element = element = $(element); + this.prepareOptions(); + this._controls = { }; + arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!! + Object.extend(this.options, options || { }); + if (!this.options.formId && this.element.id) { + this.options.formId = this.element.id + '-inplaceeditor'; + if ($(this.options.formId)) + this.options.formId = ''; + } + if (this.options.externalControl) + this.options.externalControl = $(this.options.externalControl); + if (!this.options.externalControl) + this.options.externalControlOnly = false; + this._originalBackground = this.element.getStyle('background-color') || 'transparent'; + this.element.title = this.options.clickToEditText; + this._boundCancelHandler = this.handleFormCancellation.bind(this); + this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this); + this._boundFailureHandler = this.handleAJAXFailure.bind(this); + this._boundSubmitHandler = this.handleFormSubmission.bind(this); + this._boundWrapperHandler = this.wrapUp.bind(this); + this.registerListeners(); + }, + checkForEscapeOrReturn: function(e) { + if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return; + if (Event.KEY_ESC == e.keyCode) + this.handleFormCancellation(e); + else if (Event.KEY_RETURN == e.keyCode) + this.handleFormSubmission(e); + }, + createControl: function(mode, handler, extraClasses) { + var control = this.options[mode + 'Control']; + var text = this.options[mode + 'Text']; + if ('button' == control) { + var btn = document.createElement('input'); + btn.type = 'submit'; + btn.value = text; + btn.className = 'editor_' + mode + '_button'; + if ('cancel' == mode) + btn.onclick = this._boundCancelHandler; + this._form.appendChild(btn); + this._controls[mode] = btn; + } else if ('link' == control) { + var link = document.createElement('a'); + link.href = '#'; + link.appendChild(document.createTextNode(text)); + link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler; + link.className = 'editor_' + mode + '_link'; + if (extraClasses) + link.className += ' ' + extraClasses; + this._form.appendChild(link); + this._controls[mode] = link; + } + }, + createEditField: function() { + var text = (this.options.loadTextURL ? this.options.loadingText : this.getText()); + var fld; + if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) { + fld = document.createElement('input'); + fld.type = 'text'; + var size = this.options.size || this.options.cols || 0; + if (0 < size) fld.size = size; + } else { + fld = document.createElement('textarea'); + fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows); + fld.cols = this.options.cols || 40; + } + fld.name = this.options.paramName; + fld.value = text; // No HTML breaks conversion anymore + fld.className = 'editor_field'; + if (this.options.submitOnBlur) + fld.onblur = this._boundSubmitHandler; + this._controls.editor = fld; + if (this.options.loadTextURL) + this.loadExternalText(); + this._form.appendChild(this._controls.editor); + }, + createForm: function() { + var ipe = this; + function addText(mode, condition) { + var text = ipe.options['text' + mode + 'Controls']; + if (!text || condition === false) return; + ipe._form.appendChild(document.createTextNode(text)); + }; + this._form = $(document.createElement('form')); + this._form.id = this.options.formId; + this._form.addClassName(this.options.formClassName); + this._form.onsubmit = this._boundSubmitHandler; + this.createEditField(); + if ('textarea' == this._controls.editor.tagName.toLowerCase()) + this._form.appendChild(document.createElement('br')); + if (this.options.onFormCustomization) + this.options.onFormCustomization(this, this._form); + addText('Before', this.options.okControl || this.options.cancelControl); + this.createControl('ok', this._boundSubmitHandler); + addText('Between', this.options.okControl && this.options.cancelControl); + this.createControl('cancel', this._boundCancelHandler, 'editor_cancel'); + addText('After', this.options.okControl || this.options.cancelControl); + }, + destroy: function() { + if (this._oldInnerHTML) + this.element.innerHTML = this._oldInnerHTML; + this.leaveEditMode(); + this.unregisterListeners(); + }, + enterEditMode: function(e) { + if (this._saving || this._editing) return; + this._editing = true; + this.triggerCallback('onEnterEditMode'); + if (this.options.externalControl) + this.options.externalControl.hide(); + this.element.hide(); + this.createForm(); + this.element.parentNode.insertBefore(this._form, this.element); + if (!this.options.loadTextURL) + this.postProcessEditField(); + if (e) Event.stop(e); + }, + enterHover: function(e) { + if (this.options.hoverClassName) + this.element.addClassName(this.options.hoverClassName); + if (this._saving) return; + this.triggerCallback('onEnterHover'); + }, + getText: function() { + return this.element.innerHTML.unescapeHTML(); + }, + handleAJAXFailure: function(transport) { + this.triggerCallback('onFailure', transport); + if (this._oldInnerHTML) { + this.element.innerHTML = this._oldInnerHTML; + this._oldInnerHTML = null; + } + }, + handleFormCancellation: function(e) { + this.wrapUp(); + if (e) Event.stop(e); + }, + handleFormSubmission: function(e) { + var form = this._form; + var value = $F(this._controls.editor); + this.prepareSubmission(); + var params = this.options.callback(form, value) || ''; + if (Object.isString(params)) + params = params.toQueryParams(); + params.editorId = this.element.id; + if (this.options.htmlResponse) { + var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions); + Object.extend(options, { + parameters: params, + onComplete: this._boundWrapperHandler, + onFailure: this._boundFailureHandler + }); + new Ajax.Updater({ success: this.element }, this.url, options); + } else { + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: params, + onComplete: this._boundWrapperHandler, + onFailure: this._boundFailureHandler + }); + new Ajax.Request(this.url, options); + } + if (e) Event.stop(e); + }, + leaveEditMode: function() { + this.element.removeClassName(this.options.savingClassName); + this.removeForm(); + this.leaveHover(); + this.element.style.backgroundColor = this._originalBackground; + this.element.show(); + if (this.options.externalControl) + this.options.externalControl.show(); + this._saving = false; + this._editing = false; + this._oldInnerHTML = null; + this.triggerCallback('onLeaveEditMode'); + }, + leaveHover: function(e) { + if (this.options.hoverClassName) + this.element.removeClassName(this.options.hoverClassName); + if (this._saving) return; + this.triggerCallback('onLeaveHover'); + }, + loadExternalText: function() { + this._form.addClassName(this.options.loadingClassName); + this._controls.editor.disabled = true; + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + this._form.removeClassName(this.options.loadingClassName); + var text = transport.responseText; + if (this.options.stripLoadedTextTags) + text = text.stripTags(); + this._controls.editor.value = text; + this._controls.editor.disabled = false; + this.postProcessEditField(); + }.bind(this), + onFailure: this._boundFailureHandler + }); + new Ajax.Request(this.options.loadTextURL, options); + }, + postProcessEditField: function() { + var fpc = this.options.fieldPostCreation; + if (fpc) + $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate'](); + }, + prepareOptions: function() { + this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions); + Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks); + [this._extraDefaultOptions].flatten().compact().each(function(defs) { + Object.extend(this.options, defs); + }.bind(this)); + }, + prepareSubmission: function() { + this._saving = true; + this.removeForm(); + this.leaveHover(); + this.showSaving(); + }, + registerListeners: function() { + this._listeners = { }; + var listener; + $H(Ajax.InPlaceEditor.Listeners).each(function(pair) { + listener = this[pair.value].bind(this); + this._listeners[pair.key] = listener; + if (!this.options.externalControlOnly) + this.element.observe(pair.key, listener); + if (this.options.externalControl) + this.options.externalControl.observe(pair.key, listener); + }.bind(this)); + }, + removeForm: function() { + if (!this._form) return; + this._form.remove(); + this._form = null; + this._controls = { }; + }, + showSaving: function() { + this._oldInnerHTML = this.element.innerHTML; + this.element.innerHTML = this.options.savingText; + this.element.addClassName(this.options.savingClassName); + this.element.style.backgroundColor = this._originalBackground; + this.element.show(); + }, + triggerCallback: function(cbName, arg) { + if ('function' == typeof this.options[cbName]) { + this.options[cbName](this, arg); + } + }, + unregisterListeners: function() { + $H(this._listeners).each(function(pair) { + if (!this.options.externalControlOnly) + this.element.stopObserving(pair.key, pair.value); + if (this.options.externalControl) + this.options.externalControl.stopObserving(pair.key, pair.value); + }.bind(this)); + }, + wrapUp: function(transport) { + this.leaveEditMode(); + // Can't use triggerCallback due to backward compatibility: requires + // binding + direct element + this._boundComplete(transport, this.element); + } +}); + +Object.extend(Ajax.InPlaceEditor.prototype, { + dispose: Ajax.InPlaceEditor.prototype.destroy +}); + +Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { + initialize: function($super, element, url, options) { + this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions; + $super(element, url, options); + }, + + createEditField: function() { + var list = document.createElement('select'); + list.name = this.options.paramName; + list.size = 1; + this._controls.editor = list; + this._collection = this.options.collection || []; + if (this.options.loadCollectionURL) + this.loadCollection(); + else + this.checkForExternalText(); + this._form.appendChild(this._controls.editor); + }, + + loadCollection: function() { + this._form.addClassName(this.options.loadingClassName); + this.showLoadingText(this.options.loadingCollectionText); + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + var js = transport.responseText.strip(); + if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check + throw('Server returned an invalid collection representation.'); + this._collection = eval(js); + this.checkForExternalText(); + }.bind(this), + onFailure: this.onFailure + }); + new Ajax.Request(this.options.loadCollectionURL, options); + }, + + showLoadingText: function(text) { + this._controls.editor.disabled = true; + var tempOption = this._controls.editor.firstChild; + if (!tempOption) { + tempOption = document.createElement('option'); + tempOption.value = ''; + this._controls.editor.appendChild(tempOption); + tempOption.selected = true; + } + tempOption.update((text || '').stripScripts().stripTags()); + }, + + checkForExternalText: function() { + this._text = this.getText(); + if (this.options.loadTextURL) + this.loadExternalText(); + else + this.buildOptionList(); + }, + + loadExternalText: function() { + this.showLoadingText(this.options.loadingText); + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + this._text = transport.responseText.strip(); + this.buildOptionList(); + }.bind(this), + onFailure: this.onFailure + }); + new Ajax.Request(this.options.loadTextURL, options); + }, + + buildOptionList: function() { + this._form.removeClassName(this.options.loadingClassName); + this._collection = this._collection.map(function(entry) { + return 2 === entry.length ? entry : [entry, entry].flatten(); + }); + var marker = ('value' in this.options) ? this.options.value : this._text; + var textFound = this._collection.any(function(entry) { + return entry[0] == marker; + }.bind(this)); + this._controls.editor.update(''); + var option; + this._collection.each(function(entry, index) { + option = document.createElement('option'); + option.value = entry[0]; + option.selected = textFound ? entry[0] == marker : 0 == index; + option.appendChild(document.createTextNode(entry[1])); + this._controls.editor.appendChild(option); + }.bind(this)); + this._controls.editor.disabled = false; + Field.scrollFreeActivate(this._controls.editor); + } +}); + +//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! **** +//**** This only exists for a while, in order to let **** +//**** users adapt to the new API. Read up on the new **** +//**** API and convert your code to it ASAP! **** + +Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) { + if (!options) return; + function fallback(name, expr) { + if (name in options || expr === undefined) return; + options[name] = expr; + }; + fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' : + options.cancelLink == options.cancelButton == false ? false : undefined))); + fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' : + options.okLink == options.okButton == false ? false : undefined))); + fallback('highlightColor', options.highlightcolor); + fallback('highlightEndColor', options.highlightendcolor); +}; + +Object.extend(Ajax.InPlaceEditor, { + DefaultOptions: { + ajaxOptions: { }, + autoRows: 3, // Use when multi-line w/ rows == 1 + cancelControl: 'link', // 'link'|'button'|false + cancelText: 'cancel', + clickToEditText: 'Click to edit', + externalControl: null, // id|elt + externalControlOnly: false, + fieldPostCreation: 'activate', // 'activate'|'focus'|false + formClassName: 'inplaceeditor-form', + formId: null, // id|elt + highlightColor: '#ffff99', + highlightEndColor: '#ffffff', + hoverClassName: '', + htmlResponse: true, + loadingClassName: 'inplaceeditor-loading', + loadingText: 'Loading...', + okControl: 'button', // 'link'|'button'|false + okText: 'ok', + paramName: 'value', + rows: 1, // If 1 and multi-line, uses autoRows + savingClassName: 'inplaceeditor-saving', + savingText: 'Saving...', + size: 0, + stripLoadedTextTags: false, + submitOnBlur: false, + textAfterControls: '', + textBeforeControls: '', + textBetweenControls: '' + }, + DefaultCallbacks: { + callback: function(form) { + return Form.serialize(form); + }, + onComplete: function(transport, element) { + // For backward compatibility, this one is bound to the IPE, and passes + // the element directly. It was too often customized, so we don't break it. + new Effect.Highlight(element, { + startcolor: this.options.highlightColor, keepBackgroundImage: true }); + }, + onEnterEditMode: null, + onEnterHover: function(ipe) { + ipe.element.style.backgroundColor = ipe.options.highlightColor; + if (ipe._effect) + ipe._effect.cancel(); + }, + onFailure: function(transport, ipe) { + alert('Error communication with the server: ' + transport.responseText.stripTags()); + }, + onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls. + onLeaveEditMode: null, + onLeaveHover: function(ipe) { + ipe._effect = new Effect.Highlight(ipe.element, { + startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor, + restorecolor: ipe._originalBackground, keepBackgroundImage: true + }); + } + }, + Listeners: { + click: 'enterEditMode', + keydown: 'checkForEscapeOrReturn', + mouseover: 'enterHover', + mouseout: 'leaveHover' + } +}); + +Ajax.InPlaceCollectionEditor.DefaultOptions = { + loadingCollectionText: 'Loading options...' +}; + +// Delayed observer, like Form.Element.Observer, +// but waits for delay after last key input +// Ideal for live-search fields + +Form.Element.DelayedObserver = Class.create({ + initialize: function(element, delay, callback) { + this.delay = delay || 0.5; + this.element = $(element); + this.callback = callback; + this.timer = null; + this.lastValue = $F(this.element); + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); + }, + delayedListener: function(event) { + if(this.lastValue == $F(this.element)) return; + if(this.timer) clearTimeout(this.timer); + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); + this.lastValue = $F(this.element); + }, + onTimerEvent: function() { + this.timer = null; + this.callback(this.element, $F(this.element)); + } +}); \ No newline at end of file diff --git a/src/usr/local/www/javascript/scriptaculous/dragdrop.js b/src/usr/local/www/javascript/scriptaculous/dragdrop.js new file mode 100644 index 0000000..452601e --- /dev/null +++ b/src/usr/local/www/javascript/scriptaculous/dragdrop.js @@ -0,0 +1,974 @@ +// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 + +// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +if(Object.isUndefined(Effect)) + throw("dragdrop.js requires including script.aculo.us' effects.js library"); + +var Droppables = { + drops: [], + + remove: function(element) { + this.drops = this.drops.reject(function(d) { return d.element==$(element); }); + }, + + add: function(element) { + element = $(element); + var options = Object.extend({ + greedy: true, + hoverclass: null, + tree: false + }, arguments[1] || { }); + + // cache containers + if(options.containment) { + options._containers = []; + var containment = options.containment; + if(Object.isArray(containment)) { + containment.each( function(c) { options._containers.push($(c)); }); + } else { + options._containers.push($(containment)); + } + } + + if(options.accept) options.accept = [options.accept].flatten(); + + Element.makePositioned(element); // fix IE + options.element = element; + + this.drops.push(options); + }, + + findDeepestChild: function(drops) { + deepest = drops[0]; + + for (i = 1; i < drops.length; ++i) + if (Element.isParent(drops[i].element, deepest.element)) + deepest = drops[i]; + + return deepest; + }, + + isContained: function(element, drop) { + var containmentNode; + if(drop.tree) { + containmentNode = element.treeNode; + } else { + containmentNode = element.parentNode; + } + return drop._containers.detect(function(c) { return containmentNode == c; }); + }, + + isAffected: function(point, element, drop) { + return ( + (drop.element!=element) && + ((!drop._containers) || + this.isContained(element, drop)) && + ((!drop.accept) || + (Element.classNames(element).detect( + function(v) { return drop.accept.include(v); } ) )) && + Position.within(drop.element, point[0], point[1]) ); + }, + + deactivate: function(drop) { + if(drop.hoverclass) + Element.removeClassName(drop.element, drop.hoverclass); + this.last_active = null; + }, + + activate: function(drop) { + if(drop.hoverclass) + Element.addClassName(drop.element, drop.hoverclass); + this.last_active = drop; + }, + + show: function(point, element) { + if(!this.drops.length) return; + var drop, affected = []; + + this.drops.each( function(drop) { + if(Droppables.isAffected(point, element, drop)) + affected.push(drop); + }); + + if(affected.length>0) + drop = Droppables.findDeepestChild(affected); + + if(this.last_active && this.last_active != drop) this.deactivate(this.last_active); + if (drop) { + Position.within(drop.element, point[0], point[1]); + if(drop.onHover) + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); + + if (drop != this.last_active) Droppables.activate(drop); + } + }, + + fire: function(event, element) { + if(!this.last_active) return; + Position.prepare(); + + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) + if (this.last_active.onDrop) { + this.last_active.onDrop(element, this.last_active.element, event); + return true; + } + }, + + reset: function() { + if(this.last_active) + this.deactivate(this.last_active); + } +}; + +var Draggables = { + drags: [], + observers: [], + + register: function(draggable) { + if(this.drags.length == 0) { + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.updateDrag.bindAsEventListener(this); + this.eventKeypress = this.keyPress.bindAsEventListener(this); + + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + Event.observe(document, "keypress", this.eventKeypress); + } + this.drags.push(draggable); + }, + + unregister: function(draggable) { + this.drags = this.drags.reject(function(d) { return d==draggable; }); + if(this.drags.length == 0) { + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + Event.stopObserving(document, "keypress", this.eventKeypress); + } + }, + + activate: function(draggable) { + if(draggable.options.delay) { + this._timeout = setTimeout(function() { + Draggables._timeout = null; + window.focus(); + Draggables.activeDraggable = draggable; + }.bind(this), draggable.options.delay); + } else { + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari + this.activeDraggable = draggable; + } + }, + + deactivate: function() { + this.activeDraggable = null; + }, + + updateDrag: function(event) { + if(!this.activeDraggable) return; + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + // Mozilla-based browsers fire successive mousemove events with + // the same coordinates, prevent needless redrawing (moz bug?) + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; + this._lastPointer = pointer; + + this.activeDraggable.updateDrag(event, pointer); + }, + + endDrag: function(event) { + if(this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + } + if(!this.activeDraggable) return; + this._lastPointer = null; + this.activeDraggable.endDrag(event); + this.activeDraggable = null; + }, + + keyPress: function(event) { + if(this.activeDraggable) + this.activeDraggable.keyPress(event); + }, + + addObserver: function(observer) { + this.observers.push(observer); + this._cacheObserverCallbacks(); + }, + + removeObserver: function(element) { // element instead of observer fixes mem leaks + this.observers = this.observers.reject( function(o) { return o.element==element; }); + this._cacheObserverCallbacks(); + }, + + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' + if(this[eventName+'Count'] > 0) + this.observers.each( function(o) { + if(o[eventName]) o[eventName](eventName, draggable, event); + }); + if(draggable.options[eventName]) draggable.options[eventName](draggable, event); + }, + + _cacheObserverCallbacks: function() { + ['onStart','onEnd','onDrag'].each( function(eventName) { + Draggables[eventName+'Count'] = Draggables.observers.select( + function(o) { return o[eventName]; } + ).length; + }); + } +}; + +/*--------------------------------------------------------------------------*/ + +var Draggable = Class.create({ + initialize: function(element) { + var defaults = { + handle: false, + reverteffect: function(element, top_offset, left_offset) { + var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; + new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, + queue: {scope:'_draggable', position:'end'} + }); + }, + endeffect: function(element) { + var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, + queue: {scope:'_draggable', position:'end'}, + afterFinish: function(){ + Draggable._dragging[element] = false; + } + }); + }, + zindex: 1000, + revert: false, + quiet: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } + delay: 0 + }; + + if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) + Object.extend(defaults, { + starteffect: function(element) { + element._opacity = Element.getOpacity(element); + Draggable._dragging[element] = true; + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + } + }); + + var options = Object.extend(defaults, arguments[1] || { }); + + this.element = $(element); + + if(options.handle && Object.isString(options.handle)) + this.handle = this.element.down('.'+options.handle, 0); + + if(!this.handle) this.handle = $(options.handle); + if(!this.handle) this.handle = this.element; + + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { + options.scroll = $(options.scroll); + this._isScrollChild = Element.childOf(this.element, options.scroll); + } + + Element.makePositioned(this.element); // fix IE + + this.options = options; + this.dragging = false; + + this.eventMouseDown = this.initDrag.bindAsEventListener(this); + Event.observe(this.handle, "mousedown", this.eventMouseDown); + + Draggables.register(this); + }, + + destroy: function() { + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); + Draggables.unregister(this); + }, + + currentDelta: function() { + return([ + parseInt(Element.getStyle(this.element,'left') || '0'), + parseInt(Element.getStyle(this.element,'top') || '0')]); + }, + + initDrag: function(event) { + if(!Object.isUndefined(Draggable._dragging[this.element]) && + Draggable._dragging[this.element]) return; + if(Event.isLeftClick(event)) { + // abort on form elements, fixes a Firefox issue + var src = Event.element(event); + if((tag_name = src.tagName.toUpperCase()) && ( + tag_name=='input' || + tag_name=='select' || + tag_name=='option' || + tag_name=='button' || + tag_name=='textarea')) return; + + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var pos = this.element.cumulativeOffset(); + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]); }); + + Draggables.activate(this); + Event.stop(event); + } + }, + + startDrag: function(event) { + this.dragging = true; + if(!this.delta) + this.delta = this.currentDelta(); + + if(this.options.zindex) { + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); + this.element.style.zIndex = this.options.zindex; + } + + if(this.options.ghosting) { + this._clone = this.element.cloneNode(true); + this._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); + if (!this._originallyAbsolute) + Position.absolutize(this.element); + this.element.parentNode.insertBefore(this._clone, this.element); + } + + if(this.options.scroll) { + if (this.options.scroll == window) { + var where = this._getWindowScroll(this.options.scroll); + this.originalScrollLeft = where.left; + this.originalScrollTop = where.top; + } else { + this.originalScrollLeft = this.options.scroll.scrollLeft; + this.originalScrollTop = this.options.scroll.scrollTop; + } + } + + Draggables.notify('onStart', this, event); + + if(this.options.starteffect) this.options.starteffect(this.element); + }, + + updateDrag: function(event, pointer) { + if(!this.dragging) this.startDrag(event); + + if(!this.options.quiet){ + Position.prepare(); + Droppables.show(pointer, this.element); + } + + Draggables.notify('onDrag', this, event); + + this.draw(pointer); + if(this.options.change) this.options.change(this); + + if(this.options.scroll) { + this.stopScrolling(); + + var p; + if (this.options.scroll == window) { + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } + } else { + p = Position.page(this.options.scroll); + p[0] += this.options.scroll.scrollLeft + Position.deltaX; + p[1] += this.options.scroll.scrollTop + Position.deltaY; + p.push(p[0]+this.options.scroll.offsetWidth); + p.push(p[1]+this.options.scroll.offsetHeight); + } + var speed = [0,0]; + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); + this.startScrolling(speed); + } + + // fix AppleWebKit rendering + if(Prototype.Browser.WebKit) window.scrollBy(0,0); + + Event.stop(event); + }, + + finishDrag: function(event, success) { + this.dragging = false; + + if(this.options.quiet){ + Position.prepare(); + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + Droppables.show(pointer, this.element); + } + + if(this.options.ghosting) { + if (!this._originallyAbsolute) + Position.relativize(this.element); + delete this._originallyAbsolute; + Element.remove(this._clone); + this._clone = null; + } + + var dropped = false; + if(success) { + dropped = Droppables.fire(event, this.element); + if (!dropped) dropped = false; + } + if(dropped && this.options.onDropped) this.options.onDropped(this.element); + Draggables.notify('onEnd', this, event); + + var revert = this.options.revert; + if(revert && Object.isFunction(revert)) revert = revert(this.element); + + var d = this.currentDelta(); + if(revert && this.options.reverteffect) { + if (dropped == 0 || revert != 'failure') + this.options.reverteffect(this.element, + d[1]-this.delta[1], d[0]-this.delta[0]); + } else { + this.delta = d; + } + + if(this.options.zindex) + this.element.style.zIndex = this.originalZ; + + if(this.options.endeffect) + this.options.endeffect(this.element); + + Draggables.deactivate(this); + Droppables.reset(); + }, + + keyPress: function(event) { + if(event.keyCode!=Event.KEY_ESC) return; + this.finishDrag(event, false); + Event.stop(event); + }, + + endDrag: function(event) { + if(!this.dragging) return; + this.stopScrolling(); + this.finishDrag(event, true); + Event.stop(event); + }, + + draw: function(point) { + var pos = this.element.cumulativeOffset(); + if(this.options.ghosting) { + var r = Position.realOffset(this.element); + pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; + } + + var d = this.currentDelta(); + pos[0] -= d[0]; pos[1] -= d[1]; + + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; + } + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]); + }.bind(this)); + + if(this.options.snap) { + if(Object.isFunction(this.options.snap)) { + p = this.options.snap(p[0],p[1],this); + } else { + if(Object.isArray(this.options.snap)) { + p = p.map( function(v, i) { + return (v/this.options.snap[i]).round()*this.options.snap[i]; }.bind(this)); + } else { + p = p.map( function(v) { + return (v/this.options.snap).round()*this.options.snap; }.bind(this)); + } + }} + + var style = this.element.style; + if((!this.options.constraint) || (this.options.constraint=='horizontal')) + style.left = p[0] + "px"; + if((!this.options.constraint) || (this.options.constraint=='vertical')) + style.top = p[1] + "px"; + + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering + }, + + stopScrolling: function() { + if(this.scrollInterval) { + clearInterval(this.scrollInterval); + this.scrollInterval = null; + Draggables._lastScrollPointer = null; + } + }, + + startScrolling: function(speed) { + if(!(speed[0] || speed[1])) return; + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; + this.lastScrolled = new Date(); + this.scrollInterval = setInterval(this.scroll.bind(this), 10); + }, + + scroll: function() { + var current = new Date(); + var delta = current - this.lastScrolled; + this.lastScrolled = current; + if(this.options.scroll == window) { + with (this._getWindowScroll(this.options.scroll)) { + if (this.scrollSpeed[0] || this.scrollSpeed[1]) { + var d = delta / 1000; + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); + } + } + } else { + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; + } + + Position.prepare(); + Droppables.show(Draggables._lastPointer, this.element); + Draggables.notify('onDrag', this); + if (this._isScrollChild) { + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; + if (Draggables._lastScrollPointer[0] < 0) + Draggables._lastScrollPointer[0] = 0; + if (Draggables._lastScrollPointer[1] < 0) + Draggables._lastScrollPointer[1] = 0; + this.draw(Draggables._lastScrollPointer); + } + + if(this.options.change) this.options.change(this); + }, + + _getWindowScroll: function(w) { + var T, L, W, H; + with (w.document) { + if (w.document.documentElement && documentElement.scrollTop) { + T = documentElement.scrollTop; + L = documentElement.scrollLeft; + } else if (w.document.body) { + T = body.scrollTop; + L = body.scrollLeft; + } + if (w.innerWidth) { + W = w.innerWidth; + H = w.innerHeight; + } else if (w.document.documentElement && documentElement.clientWidth) { + W = documentElement.clientWidth; + H = documentElement.clientHeight; + } else { + W = body.offsetWidth; + H = body.offsetHeight; + } + } + return { top: T, left: L, width: W, height: H }; + } +}); + +Draggable._dragging = { }; + +/*--------------------------------------------------------------------------*/ + +var SortableObserver = Class.create({ + initialize: function(element, observer) { + this.element = $(element); + this.observer = observer; + this.lastValue = Sortable.serialize(this.element); + }, + + onStart: function() { + this.lastValue = Sortable.serialize(this.element); + }, + + onEnd: function() { + Sortable.unmark(); + if(this.lastValue != Sortable.serialize(this.element)) + this.observer(this.element); + } +}); + +var Sortable = { + SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, + + sortables: { }, + + _findRootElement: function(element) { + while (element.tagName.toUpperCase() != "BODY") { + if(element.id && Sortable.sortables[element.id]) return element; + element = element.parentNode; + } + }, + + options: function(element) { + element = Sortable._findRootElement($(element)); + if(!element) return; + return Sortable.sortables[element.id]; + }, + + destroy: function(element){ + element = $(element); + var s = Sortable.sortables[element.id]; + + if(s) { + Draggables.removeObserver(s.element); + s.droppables.each(function(d){ Droppables.remove(d); }); + s.draggables.invoke('destroy'); + + delete Sortable.sortables[s.element.id]; + } + }, + + create: function(element) { + element = $(element); + var options = Object.extend({ + element: element, + tag: 'li', // assumes li children, override with tag: 'tagname' + dropOnEmpty: false, + tree: false, + treeTag: 'ul', + overlap: 'vertical', // one of 'vertical', 'horizontal' + constraint: 'vertical', // one of 'vertical', 'horizontal', false + containment: element, // also takes array of elements (or id's); or false + handle: false, // or a CSS class + only: false, + delay: 0, + hoverclass: null, + ghosting: false, + quiet: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + format: this.SERIALIZE_RULE, + + // these take arrays of elements or ids and can be + // used for better initialization performance + elements: false, + handles: false, + + onChange: Prototype.emptyFunction, + onUpdate: Prototype.emptyFunction + }, arguments[1] || { }); + + // clear any old sortable with same element + this.destroy(element); + + // build options for the draggables + var options_for_draggable = { + revert: true, + quiet: options.quiet, + scroll: options.scroll, + scrollSpeed: options.scrollSpeed, + scrollSensitivity: options.scrollSensitivity, + delay: options.delay, + ghosting: options.ghosting, + constraint: options.constraint, + handle: options.handle }; + + if(options.starteffect) + options_for_draggable.starteffect = options.starteffect; + + if(options.reverteffect) + options_for_draggable.reverteffect = options.reverteffect; + else + if(options.ghosting) options_for_draggable.reverteffect = function(element) { + element.style.top = 0; + element.style.left = 0; + }; + + if(options.endeffect) + options_for_draggable.endeffect = options.endeffect; + + if(options.zindex) + options_for_draggable.zindex = options.zindex; + + // build options for the droppables + var options_for_droppable = { + overlap: options.overlap, + containment: options.containment, + tree: options.tree, + hoverclass: options.hoverclass, + onHover: Sortable.onHover + }; + + var options_for_tree = { + onHover: Sortable.onEmptyHover, + overlap: options.overlap, + containment: options.containment, + hoverclass: options.hoverclass + }; + + // fix for gecko engine + Element.cleanWhitespace(element); + + options.draggables = []; + options.droppables = []; + + // drop on empty handling + if(options.dropOnEmpty || options.tree) { + Droppables.add(element, options_for_tree); + options.droppables.push(element); + } + + (options.elements || this.findElements(element, options) || []).each( function(e,i) { + var handle = options.handles ? $(options.handles[i]) : + (options.handle ? $(e).select('.' + options.handle)[0] : e); + options.draggables.push( + new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); + Droppables.add(e, options_for_droppable); + if(options.tree) e.treeNode = element; + options.droppables.push(e); + }); + + if(options.tree) { + (Sortable.findTreeElements(element, options) || []).each( function(e) { + Droppables.add(e, options_for_tree); + e.treeNode = element; + options.droppables.push(e); + }); + } + + // keep reference + this.sortables[element.identify()] = options; + + // for onupdate + Draggables.addObserver(new SortableObserver(element, options.onUpdate)); + + }, + + // return all suitable-for-sortable elements in a guaranteed order + findElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.tag); + }, + + findTreeElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.treeTag); + }, + + onHover: function(element, dropon, overlap) { + if(Element.isParent(dropon, element)) return; + + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { + return; + } else if(overlap>0.5) { + Sortable.mark(dropon, 'before'); + if(dropon.previousSibling != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, dropon); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } else { + Sortable.mark(dropon, 'after'); + var nextElement = dropon.nextSibling || null; + if(nextElement != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, nextElement); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } + }, + + onEmptyHover: function(element, dropon, overlap) { + var oldParentNode = element.parentNode; + var droponOptions = Sortable.options(dropon); + + if(!Element.isParent(dropon, element)) { + var index; + + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); + var child = null; + + if(children) { + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); + + for (index = 0; index < children.length; index += 1) { + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { + offset -= Element.offsetSize (children[index], droponOptions.overlap); + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { + child = index + 1 < children.length ? children[index + 1] : null; + break; + } else { + child = children[index]; + break; + } + } + } + + dropon.insertBefore(element, child); + + Sortable.options(oldParentNode).onChange(element); + droponOptions.onChange(element); + } + }, + + unmark: function() { + if(Sortable._marker) Sortable._marker.hide(); + }, + + mark: function(dropon, position) { + // mark on ghosting only + var sortable = Sortable.options(dropon.parentNode); + if(sortable && !sortable.ghosting) return; + + if(!Sortable._marker) { + Sortable._marker = + ($('dropmarker') || Element.extend(document.createElement('DIV'))). + hide().addClassName('dropmarker').setStyle({position:'absolute'}); + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); + } + var offsets = dropon.cumulativeOffset(); + Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); + + if(position=='after') + if(sortable.overlap == 'horizontal') + Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); + else + Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); + + Sortable._marker.show(); + }, + + _tree: function(element, options, parent) { + var children = Sortable.findElements(element, options) || []; + + for (var i = 0; i < children.length; ++i) { + var match = children[i].id.match(options.format); + + if (!match) continue; + + var child = { + id: encodeURIComponent(match ? match[1] : null), + element: element, + parent: parent, + children: [], + position: parent.children.length, + container: $(children[i]).down(options.treeTag) + }; + + /* Get the element containing the children and recurse over it */ + if (child.container) + this._tree(child.container, options, child); + + parent.children.push (child); + } + + return parent; + }, + + tree: function(element) { + element = $(element); + var sortableOptions = this.options(element); + var options = Object.extend({ + tag: sortableOptions.tag, + treeTag: sortableOptions.treeTag, + only: sortableOptions.only, + name: element.id, + format: sortableOptions.format + }, arguments[1] || { }); + + var root = { + id: null, + parent: null, + children: [], + container: element, + position: 0 + }; + + return Sortable._tree(element, options, root); + }, + + /* Construct a [i] index for a particular node */ + _constructIndex: function(node) { + var index = ''; + do { + if (node.id) index = '[' + node.position + ']' + index; + } while ((node = node.parent) != null); + return index; + }, + + sequence: function(element) { + element = $(element); + var options = Object.extend(this.options(element), arguments[1] || { }); + + return $(this.findElements(element, options) || []).map( function(item) { + return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; + }); + }, + + setSequence: function(element, new_sequence) { + element = $(element); + var options = Object.extend(this.options(element), arguments[2] || { }); + + var nodeMap = { }; + this.findElements(element, options).each( function(n) { + if (n.id.match(options.format)) + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; + n.parentNode.removeChild(n); + }); + + new_sequence.each(function(ident) { + var n = nodeMap[ident]; + if (n) { + n[1].appendChild(n[0]); + delete nodeMap[ident]; + } + }); + }, + + serialize: function(element) { + element = $(element); + var options = Object.extend(Sortable.options(element), arguments[1] || { }); + var name = encodeURIComponent( + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); + + if (options.tree) { + return Sortable.tree(element, arguments[1]).children.map( function (item) { + return [name + Sortable._constructIndex(item) + "[id]=" + + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); + }).flatten().join('&'); + } else { + return Sortable.sequence(element, arguments[1]).map( function(item) { + return name + "[]=" + encodeURIComponent(item); + }).join('&'); + } + } +}; + +// Returns true if child is contained within element +Element.isParent = function(child, element) { + if (!child.parentNode || child == element) return false; + if (child.parentNode == element) return true; + return Element.isParent(child.parentNode, element); +}; + +Element.findChildren = function(element, only, recursive, tagName) { + if(!element.hasChildNodes()) return null; + tagName = tagName.toUpperCase(); + if(only) only = [only].flatten(); + var elements = []; + $A(element.childNodes).each( function(e) { + if(e.tagName && e.tagName.toUpperCase()==tagName && + (!only || (Element.classNames(e).detect(function(v) { return only.include(v); })))) + elements.push(e); + if(recursive) { + var grandchildren = Element.findChildren(e, only, recursive, tagName); + if(grandchildren) elements.push(grandchildren); + } + }); + + return (elements.length>0 ? elements.flatten() : []); +}; + +Element.offsetSize = function (element, type) { + return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; +}; \ No newline at end of file diff --git a/src/usr/local/www/javascript/scriptaculous/effects.js b/src/usr/local/www/javascript/scriptaculous/effects.js new file mode 100644 index 0000000..7d5192c --- /dev/null +++ b/src/usr/local/www/javascript/scriptaculous/effects.js @@ -0,0 +1,1123 @@ +// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 + +// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// Contributors: +// Justin Palmer (http://encytemedia.com/) +// Mark Pilgrim (http://diveintomark.org/) +// Martin Bialasinki +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { + var color = '#'; + if (this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart(); } while (++i<3); + } else { + if (this.slice(0,1) == '#') { + if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if (this.length==7) color = this.toLowerCase(); + } + } + return (color.length==7 ? color : (arguments[0] || this)); +}; + +/*--------------------------------------------------------------------------*/ + +Element.collectTextNodes = function(element) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); + }).flatten().join(''); +}; + +Element.collectTextNodesIgnoreClass = function(element, className) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + Element.collectTextNodesIgnoreClass(node, className) : '')); + }).flatten().join(''); +}; + +Element.setContentZoom = function(element, percent) { + element = $(element); + element.setStyle({fontSize: (percent/100) + 'em'}); + if (Prototype.Browser.WebKit) window.scrollBy(0,0); + return element; +}; + +Element.getInlineOpacity = function(element){ + return $(element).style.opacity || ''; +}; + +Element.forceRerendering = function(element) { + try { + element = $(element); + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch(e) { } +}; + +/*--------------------------------------------------------------------------*/ + +var Effect = { + _elementDoesNotExistError: { + name: 'ElementDoesNotExistError', + message: 'The specified DOM element does not exist, but is required for this effect to operate' + }, + Transitions: { + linear: Prototype.K, + sinoidal: function(pos) { + return (-Math.cos(pos*Math.PI)/2) + .5; + }, + reverse: function(pos) { + return 1-pos; + }, + flicker: function(pos) { + var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4; + return pos > 1 ? 1 : pos; + }, + wobble: function(pos) { + return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5; + }, + pulse: function(pos, pulses) { + return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5; + }, + spring: function(pos) { + return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); + }, + none: function(pos) { + return 0; + }, + full: function(pos) { + return 1; + } + }, + DefaultOptions: { + duration: 1.0, // seconds + fps: 100, // 100= assume 66fps max. + sync: false, // true for combining + from: 0.0, + to: 1.0, + delay: 0.0, + queue: 'parallel' + }, + tagifyText: function(element) { + var tagifyStyle = 'position:relative'; + if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; + + element = $(element); + $A(element.childNodes).each( function(child) { + if (child.nodeType==3) { + child.nodeValue.toArray().each( function(character) { + element.insertBefore( + new Element('span', {style: tagifyStyle}).update( + character == ' ' ? String.fromCharCode(160) : character), + child); + }); + Element.remove(child); + } + }); + }, + multiple: function(element, effect) { + var elements; + if (((typeof element == 'object') || + Object.isFunction(element)) && + (element.length)) + elements = element; + else + elements = $(element).childNodes; + + var options = Object.extend({ + speed: 0.1, + delay: 0.0 + }, arguments[2] || { }); + var masterDelay = options.delay; + + $A(elements).each( function(element, index) { + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); + }); + }, + PAIRS: { + 'slide': ['SlideDown','SlideUp'], + 'blind': ['BlindDown','BlindUp'], + 'appear': ['Appear','Fade'] + }, + toggle: function(element, effect, options) { + element = $(element); + effect = (effect || 'appear').toLowerCase(); + + return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({ + queue: { position:'end', scope:(element.id || 'global'), limit: 1 } + }, options || {})); + } +}; + +Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; + +/* ------------- core effects ------------- */ + +Effect.ScopedQueue = Class.create(Enumerable, { + initialize: function() { + this.effects = []; + this.interval = null; + }, + _each: function(iterator) { + this.effects._each(iterator); + }, + add: function(effect) { + var timestamp = new Date().getTime(); + + var position = Object.isString(effect.options.queue) ? + effect.options.queue : effect.options.queue.position; + + switch(position) { + case 'front': + // move unstarted effects after this effect + this.effects.findAll(function(e){ return e.state=='idle'; }).each( function(e) { + e.startOn += effect.finishOn; + e.finishOn += effect.finishOn; + }); + break; + case 'with-last': + timestamp = this.effects.pluck('startOn').max() || timestamp; + break; + case 'end': + // start effect after last queued effect has finished + timestamp = this.effects.pluck('finishOn').max() || timestamp; + break; + } + + effect.startOn += timestamp; + effect.finishOn += timestamp; + + if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + this.effects.push(effect); + + if (!this.interval) + this.interval = setInterval(this.loop.bind(this), 15); + }, + remove: function(effect) { + this.effects = this.effects.reject(function(e) { return e==effect; }); + if (this.effects.length == 0) { + clearInterval(this.interval); + this.interval = null; + } + }, + loop: function() { + var timePos = new Date().getTime(); + for(var i=0, len=this.effects.length;i= this.startOn) { + if (timePos >= this.finishOn) { + this.render(1.0); + this.cancel(); + this.event('beforeFinish'); + if (this.finish) this.finish(); + this.event('afterFinish'); + return; + } + var pos = (timePos - this.startOn) / this.totalTime, + frame = (pos * this.totalFrames).round(); + if (frame > this.currentFrame) { + this.render(pos); + this.currentFrame = frame; + } + } + }, + cancel: function() { + if (!this.options.sync) + Effect.Queues.get(Object.isString(this.options.queue) ? + 'global' : this.options.queue.scope).remove(this); + this.state = 'finished'; + }, + event: function(eventName) { + if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); + if (this.options[eventName]) this.options[eventName](this); + }, + inspect: function() { + var data = $H(); + for(property in this) + if (!Object.isFunction(this[property])) data.set(property, this[property]); + return '#'; + } +}); + +Effect.Parallel = Class.create(Effect.Base, { + initialize: function(effects) { + this.effects = effects || []; + this.start(arguments[1]); + }, + update: function(position) { + this.effects.invoke('render', position); + }, + finish: function(position) { + this.effects.each( function(effect) { + effect.render(1.0); + effect.cancel(); + effect.event('beforeFinish'); + if (effect.finish) effect.finish(position); + effect.event('afterFinish'); + }); + } +}); + +Effect.Tween = Class.create(Effect.Base, { + initialize: function(object, from, to) { + object = Object.isString(object) ? $(object) : object; + var args = $A(arguments), method = args.last(), + options = args.length == 5 ? args[3] : null; + this.method = Object.isFunction(method) ? method.bind(object) : + Object.isFunction(object[method]) ? object[method].bind(object) : + function(value) { object[method] = value; }; + this.start(Object.extend({ from: from, to: to }, options || { })); + }, + update: function(position) { + this.method(position); + } +}); + +Effect.Event = Class.create(Effect.Base, { + initialize: function() { + this.start(Object.extend({ duration: 0 }, arguments[0] || { })); + }, + update: Prototype.emptyFunction +}); + +Effect.Opacity = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + // make this work on IE on elements without 'layout' + if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + var options = Object.extend({ + from: this.element.getOpacity() || 0.0, + to: 1.0 + }, arguments[1] || { }); + this.start(options); + }, + update: function(position) { + this.element.setOpacity(position); + } +}); + +Effect.Move = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + x: 0, + y: 0, + mode: 'relative' + }, arguments[1] || { }); + this.start(options); + }, + setup: function() { + this.element.makePositioned(); + this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); + this.originalTop = parseFloat(this.element.getStyle('top') || '0'); + if (this.options.mode == 'absolute') { + this.options.x = this.options.x - this.originalLeft; + this.options.y = this.options.y - this.originalTop; + } + }, + update: function(position) { + this.element.setStyle({ + left: (this.options.x * position + this.originalLeft).round() + 'px', + top: (this.options.y * position + this.originalTop).round() + 'px' + }); + } +}); + +// for backwards compatibility +Effect.MoveBy = function(element, toTop, toLeft) { + return new Effect.Move(element, + Object.extend({ x: toLeft, y: toTop }, arguments[3] || { })); +}; + +Effect.Scale = Class.create(Effect.Base, { + initialize: function(element, percent) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + scaleX: true, + scaleY: true, + scaleContent: true, + scaleFromCenter: false, + scaleMode: 'box', // 'box' or 'contents' or { } with provided values + scaleFrom: 100.0, + scaleTo: percent + }, arguments[2] || { }); + this.start(options); + }, + setup: function() { + this.restoreAfterFinish = this.options.restoreAfterFinish || false; + this.elementPositioning = this.element.getStyle('position'); + + this.originalStyle = { }; + ['top','left','width','height','fontSize'].each( function(k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this)); + + this.originalTop = this.element.offsetTop; + this.originalLeft = this.element.offsetLeft; + + var fontSize = this.element.getStyle('font-size') || '100%'; + ['em','px','%','pt'].each( function(fontSizeType) { + if (fontSize.indexOf(fontSizeType)>0) { + this.fontSize = parseFloat(fontSize); + this.fontSizeType = fontSizeType; + } + }.bind(this)); + + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; + + this.dims = null; + if (this.options.scaleMode=='box') + this.dims = [this.element.offsetHeight, this.element.offsetWidth]; + if (/^content/.test(this.options.scaleMode)) + this.dims = [this.element.scrollHeight, this.element.scrollWidth]; + if (!this.dims) + this.dims = [this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth]; + }, + update: function(position) { + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + if (this.options.scaleContent && this.fontSize) + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); + }, + finish: function(position) { + if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); + }, + setDimensions: function(height, width) { + var d = { }; + if (this.options.scaleX) d.width = width.round() + 'px'; + if (this.options.scaleY) d.height = height.round() + 'px'; + if (this.options.scaleFromCenter) { + var topd = (height - this.dims[0])/2; + var leftd = (width - this.dims[1])/2; + if (this.elementPositioning == 'absolute') { + if (this.options.scaleY) d.top = this.originalTop-topd + 'px'; + if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; + } else { + if (this.options.scaleY) d.top = -topd + 'px'; + if (this.options.scaleX) d.left = -leftd + 'px'; + } + } + this.element.setStyle(d); + } +}); + +Effect.Highlight = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); + this.start(options); + }, + setup: function() { + // Prevent executing on elements not in the layout flow + if (this.element.getStyle('display')=='none') { this.cancel(); return; } + // Disable background image during the effect + this.oldStyle = { }; + if (!this.options.keepBackgroundImage) { + this.oldStyle.backgroundImage = this.element.getStyle('background-image'); + this.element.setStyle({backgroundImage: 'none'}); + } + if (!this.options.endcolor) + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); + if (!this.options.restorecolor) + this.options.restorecolor = this.element.getStyle('background-color'); + // init color calculations + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16); }.bind(this)); + this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]; }.bind(this)); + }, + update: function(position) { + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ + return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) }); + }, + finish: function() { + this.element.setStyle(Object.extend(this.oldStyle, { + backgroundColor: this.options.restorecolor + })); + } +}); + +Effect.ScrollTo = function(element) { + var options = arguments[1] || { }, + scrollOffsets = document.viewport.getScrollOffsets(), + elementOffsets = $(element).cumulativeOffset(); + + if (options.offset) elementOffsets[1] += options.offset; + + return new Effect.Tween(null, + scrollOffsets.top, + elementOffsets[1], + options, + function(p){ scrollTo(scrollOffsets.left, p.round()); } + ); +}; + +/* ------------- combination effects ------------- */ + +Effect.Fade = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + var options = Object.extend({ + from: element.getOpacity() || 1.0, + to: 0.0, + afterFinishInternal: function(effect) { + if (effect.options.to!=0) return; + effect.element.hide().setStyle({opacity: oldOpacity}); + } + }, arguments[1] || { }); + return new Effect.Opacity(element,options); +}; + +Effect.Appear = function(element) { + element = $(element); + var options = Object.extend({ + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), + to: 1.0, + // force Safari to render floated elements properly + afterFinishInternal: function(effect) { + effect.element.forceRerendering(); + }, + beforeSetup: function(effect) { + effect.element.setOpacity(effect.options.from).show(); + }}, arguments[1] || { }); + return new Effect.Opacity(element,options); +}; + +Effect.Puff = function(element) { + element = $(element); + var oldStyle = { + opacity: element.getInlineOpacity(), + position: element.getStyle('position'), + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height + }; + return new Effect.Parallel( + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, + beforeSetupInternal: function(effect) { + Position.absolutize(effect.effects[0].element); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().setStyle(oldStyle); } + }, arguments[1] || { }) + ); +}; + +Effect.BlindUp = function(element) { + element = $(element); + element.makeClipping(); + return new Effect.Scale(element, 0, + Object.extend({ scaleContent: false, + scaleX: false, + restoreAfterFinish: true, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }, arguments[1] || { }) + ); +}; + +Effect.BlindDown = function(element) { + element = $(element); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: 0, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + } + }, arguments[1] || { })); +}; + +Effect.SwitchOff = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + return new Effect.Appear(element, Object.extend({ + duration: 0.4, + from: 0, + transition: Effect.Transitions.flicker, + afterFinishInternal: function(effect) { + new Effect.Scale(effect.element, 1, { + duration: 0.3, scaleFromCenter: true, + scaleX: false, scaleContent: false, restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); + } + }); + } + }, arguments[1] || { })); +}; + +Effect.DropOut = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left'), + opacity: element.getInlineOpacity() }; + return new Effect.Parallel( + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 }) ], + Object.extend( + { duration: 0.5, + beforeSetup: function(effect) { + effect.effects[0].element.makePositioned(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); + } + }, arguments[1] || { })); +}; + +Effect.Shake = function(element) { + element = $(element); + var options = Object.extend({ + distance: 20, + duration: 0.5 + }, arguments[1] || {}); + var distance = parseFloat(options.distance); + var split = parseFloat(options.duration) / 10.0; + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left') }; + return new Effect.Move(element, + { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { + effect.element.undoPositioned().setStyle(oldStyle); + }}); }}); }}); }}); }}); }}); +}; + +Effect.SlideDown = function(element) { + element = $(element).cleanWhitespace(); + // SlideDown need to have the content of the element wrapped in a container element with fixed height! + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: window.opera ? 0 : 1, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if (window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || { }) + ); +}; + +Effect.SlideUp = function(element) { + element = $(element).cleanWhitespace(); + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, window.opera ? 0 : 1, + Object.extend({ scaleContent: false, + scaleX: false, + scaleMode: 'box', + scaleFrom: 100, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if (window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); + } + }, arguments[1] || { }) + ); +}; + +// Bug in opera makes the TD containing this element expand for a instance after finish +Effect.Squish = function(element) { + return new Effect.Scale(element, window.opera ? 1 : 0, { + restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }); +}; + +Effect.Grow = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.full + }, arguments[1] || { }); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var initialMoveX, initialMoveY; + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + initialMoveX = initialMoveY = moveX = moveY = 0; + break; + case 'top-right': + initialMoveX = dims.width; + initialMoveY = moveY = 0; + moveX = -dims.width; + break; + case 'bottom-left': + initialMoveX = moveX = 0; + initialMoveY = dims.height; + moveY = -dims.height; + break; + case 'bottom-right': + initialMoveX = dims.width; + initialMoveY = dims.height; + moveX = -dims.width; + moveY = -dims.height; + break; + case 'center': + initialMoveX = dims.width / 2; + initialMoveY = dims.height / 2; + moveX = -dims.width / 2; + moveY = -dims.height / 2; + break; + } + + return new Effect.Move(element, { + x: initialMoveX, + y: initialMoveY, + duration: 0.01, + beforeSetup: function(effect) { + effect.element.hide().makeClipping().makePositioned(); + }, + afterFinishInternal: function(effect) { + new Effect.Parallel( + [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), + new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), + new Effect.Scale(effect.element, 100, { + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) + ], Object.extend({ + beforeSetup: function(effect) { + effect.effects[0].element.setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); + } + }, options) + ); + } + }); +}; + +Effect.Shrink = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.none + }, arguments[1] || { }); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + moveX = moveY = 0; + break; + case 'top-right': + moveX = dims.width; + moveY = 0; + break; + case 'bottom-left': + moveX = 0; + moveY = dims.height; + break; + case 'bottom-right': + moveX = dims.width; + moveY = dims.height; + break; + case 'center': + moveX = dims.width / 2; + moveY = dims.height / 2; + break; + } + + return new Effect.Parallel( + [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), + new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), + new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) + ], Object.extend({ + beforeStartInternal: function(effect) { + effect.effects[0].element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } + }, options) + ); +}; + +Effect.Pulsate = function(element) { + element = $(element); + var options = arguments[1] || { }, + oldOpacity = element.getInlineOpacity(), + transition = options.transition || Effect.Transitions.linear, + reverser = function(pos){ + return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5); + }; + + return new Effect.Opacity(element, + Object.extend(Object.extend({ duration: 2.0, from: 0, + afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } + }, options), {transition: reverser})); +}; + +Effect.Fold = function(element) { + element = $(element); + var oldStyle = { + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height }; + element.makeClipping(); + return new Effect.Scale(element, 5, Object.extend({ + scaleContent: false, + scaleX: false, + afterFinishInternal: function(effect) { + new Effect.Scale(element, 1, { + scaleContent: false, + scaleY: false, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().setStyle(oldStyle); + } }); + }}, arguments[1] || { })); +}; + +Effect.Morph = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + style: { } + }, arguments[1] || { }); + + if (!Object.isString(options.style)) this.style = $H(options.style); + else { + if (options.style.include(':')) + this.style = options.style.parseStyle(); + else { + this.element.addClassName(options.style); + this.style = $H(this.element.getStyles()); + this.element.removeClassName(options.style); + var css = this.element.getStyles(); + this.style = this.style.reject(function(style) { + return style.value == css[style.key]; + }); + options.afterFinishInternal = function(effect) { + effect.element.addClassName(effect.options.style); + effect.transforms.each(function(transform) { + effect.element.style[transform.style] = ''; + }); + }; + } + } + this.start(options); + }, + + setup: function(){ + function parseColor(color){ + if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; + color = color.parseColor(); + return $R(0,2).map(function(i){ + return parseInt( color.slice(i*2+1,i*2+3), 16 ); + }); + } + this.transforms = this.style.map(function(pair){ + var property = pair[0], value = pair[1], unit = null; + + if (value.parseColor('#zzzzzz') != '#zzzzzz') { + value = value.parseColor(); + unit = 'color'; + } else if (property == 'opacity') { + value = parseFloat(value); + if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + } else if (Element.CSS_LENGTH.test(value)) { + var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/); + value = parseFloat(components[1]); + unit = (components.length == 3) ? components[2] : null; + } + + var originalValue = this.element.getStyle(property); + return { + style: property.camelize(), + originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), + targetValue: unit=='color' ? parseColor(value) : value, + unit: unit + }; + }.bind(this)).reject(function(transform){ + return ( + (transform.originalValue == transform.targetValue) || + ( + transform.unit != 'color' && + (isNaN(transform.originalValue) || isNaN(transform.targetValue)) + ) + ); + }); + }, + update: function(position) { + var style = { }, transform, i = this.transforms.length; + while(i--) + style[(transform = this.transforms[i]).style] = + transform.unit=='color' ? '#'+ + (Math.round(transform.originalValue[0]+ + (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + + (Math.round(transform.originalValue[1]+ + (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() + + (Math.round(transform.originalValue[2]+ + (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : + (transform.originalValue + + (transform.targetValue - transform.originalValue) * position).toFixed(3) + + (transform.unit === null ? '' : transform.unit); + this.element.setStyle(style, true); + } +}); + +Effect.Transform = Class.create({ + initialize: function(tracks){ + this.tracks = []; + this.options = arguments[1] || { }; + this.addTracks(tracks); + }, + addTracks: function(tracks){ + tracks.each(function(track){ + track = $H(track); + var data = track.values().first(); + this.tracks.push($H({ + ids: track.keys().first(), + effect: Effect.Morph, + options: { style: data } + })); + }.bind(this)); + return this; + }, + play: function(){ + return new Effect.Parallel( + this.tracks.map(function(track){ + var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options'); + var elements = [$(ids) || $$(ids)].flatten(); + return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)); }); + }).flatten(), + this.options + ); + } +}); + +Element.CSS_PROPERTIES = $w( + 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + + 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + + 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + + 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + + 'fontSize fontWeight height left letterSpacing lineHeight ' + + 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+ + 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + + 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + + 'right textIndent top width wordSpacing zIndex'); + +Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; + +String.__parseStyleElement = document.createElement('div'); +String.prototype.parseStyle = function(){ + var style, styleRules = $H(); + if (Prototype.Browser.WebKit) + style = new Element('div',{style:this}).style; + else { + String.__parseStyleElement.innerHTML = '
                          '; + style = String.__parseStyleElement.childNodes[0].style; + } + + Element.CSS_PROPERTIES.each(function(property){ + if (style[property]) styleRules.set(property, style[property]); + }); + + if (Prototype.Browser.IE && this.include('opacity')) + styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); + + return styleRules; +}; + +if (document.defaultView && document.defaultView.getComputedStyle) { + Element.getStyles = function(element) { + var css = document.defaultView.getComputedStyle($(element), null); + return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { + styles[property] = css[property]; + return styles; + }); + }; +} else { + Element.getStyles = function(element) { + element = $(element); + var css = element.currentStyle, styles; + styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) { + results[property] = css[property]; + return results; + }); + if (!styles.opacity) styles.opacity = element.getOpacity(); + return styles; + }; +} + +Effect.Methods = { + morph: function(element, style) { + element = $(element); + new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); + return element; + }, + visualEffect: function(element, effect, options) { + element = $(element); + var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); + new Effect[klass](element, options); + return element; + }, + highlight: function(element, options) { + element = $(element); + new Effect.Highlight(element, options); + return element; + } +}; + +$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ + 'pulsate shake puff squish switchOff dropOut').each( + function(effect) { + Effect.Methods[effect] = function(element, options){ + element = $(element); + Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); + return element; + }; + } +); + +$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( + function(f) { Effect.Methods[f] = Element[f]; } +); + +Element.addMethods(Effect.Methods); \ No newline at end of file diff --git a/src/usr/local/www/javascript/scriptaculous/prototype.js b/src/usr/local/www/javascript/scriptaculous/prototype.js new file mode 100644 index 0000000..9cb702c --- /dev/null +++ b/src/usr/local/www/javascript/scriptaculous/prototype.js @@ -0,0 +1,6079 @@ +/* Prototype JavaScript framework, version 1.7 + * (c) 2005-2010 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://www.prototypejs.org/ + * + *--------------------------------------------------------------------------*/ + +var Prototype = { + + Version: '1.7', + + Browser: (function(){ + var ua = navigator.userAgent; + 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) + }; + })(), + + BrowserFeatures: { + XPath: !!document.evaluate, + + SelectorsAPI: !!document.querySelector, + + ElementExtensions: (function() { + var constructor = window.Element || window.HTMLElement; + return !!(constructor && constructor.prototype); + })(), + SpecificElementExtensions: (function() { + if (typeof window.HTMLDivElement !== 'undefined') + return true; + + var div = document.createElement('div'), + form = document.createElement('form'), + isSupported = false; + + if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) { + isSupported = true; + } + + div = form = null; + + return isSupported; + })() + }, + + ScriptFragment: ']*>([\\S\\s]*?)<\/script>', + JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, + + emptyFunction: function() { }, + + K: function(x) { return x; } +}; + +if (Prototype.Browser.MobileSafari) + Prototype.BrowserFeatures.SpecificElementExtensions = false; + + +var Abstract = { }; + + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) { } + } + + return returnValue; + } +}; + +/* Based on Alex Arnell's inheritance implementation. */ + +var Class = (function() { + + var IS_DONTENUM_BUGGY = (function(){ + for (var p in { toString: 1 }) { + if (p === 'toString') return false; + } + return true; + })(); + + function subclass() {}; + function create() { + var parent = null, properties = $A(arguments); + if (Object.isFunction(properties[0])) + parent = properties.shift(); + + function klass() { + this.initialize.apply(this, arguments); + } + + Object.extend(klass, Class.Methods); + klass.superclass = parent; + klass.subclasses = []; + + if (parent) { + subclass.prototype = parent.prototype; + klass.prototype = new subclass; + parent.subclasses.push(klass); + } + + for (var i = 0, length = properties.length; i < length; i++) + klass.addMethods(properties[i]); + + if (!klass.prototype.initialize) + klass.prototype.initialize = Prototype.emptyFunction; + + klass.prototype.constructor = klass; + return klass; + } + + function addMethods(source) { + var ancestor = this.superclass && this.superclass.prototype, + properties = Object.keys(source); + + if (IS_DONTENUM_BUGGY) { + if (source.toString != Object.prototype.toString) + properties.push("toString"); + if (source.valueOf != Object.prototype.valueOf) + properties.push("valueOf"); + } + + 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 method = value; + value = (function(m) { + return function() { return ancestor[m].apply(this, arguments); }; + })(property).wrap(method); + + value.valueOf = method.valueOf.bind(method); + value.toString = method.toString.bind(method); + } + this.prototype[property] = value; + } + + return this; + } + + return { + create: create, + Methods: { + addMethods: addMethods + } + }; +})(); +(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'; + + function Type(o) { + 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; + } + return OBJECT_TYPE; + } + + function extend(destination, source) { + 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'; + return object.inspect ? object.inspect() : String(object); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + } + + function toJSON(value) { + return Str('', { '': value }, []); + } + + function Str(key, holder, stack) { + var value = holder[key], + type = typeof value; + + if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + + var _class = _toString.call(value); + + switch (_class) { + case NUMBER_CLASS: + case BOOLEAN_CLASS: + case STRING_CLASS: + value = value.valueOf(); + } + + switch (value) { + case null: return 'null'; + case true: return 'true'; + case false: return 'false'; + } + + type = typeof value; + switch (type) { + case 'string': + return value.inspect(true); + 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(); } + } + stack.push(value); + + var partial = []; + 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 = '[' + 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); + if (typeof str !== "undefined") { + partial.push(key.inspect(true)+ ':' + str); + } + } + partial = '{' + partial.join(',') + '}'; + } + stack.pop(); + return partial; + } + } + + function stringify(object) { + return JSON.stringify(object); + } + + function toQueryString(object) { + return $H(object).toQueryString(); + } + + function toHTML(object) { + return object && object.toHTML ? object.toHTML() : String.interpret(object); + } + + function keys(object) { + if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); } + var results = []; + for (var property in object) { + if (object.hasOwnProperty(property)) { + results.push(property); + } + } + return results; + } + + function values(object) { + var results = []; + for (var property in object) + results.push(object[property]); + return results; + } + + function clone(object) { + return extend({ }, object); + } + + function isElement(object) { + return !!(object && object.nodeType == 1); + } + + function isArray(object) { + return _toString.call(object) === ARRAY_CLASS; + } + + var hasNativeIsArray = (typeof Array.isArray == 'function') + && Array.isArray([]) && !Array.isArray({}); + + if (hasNativeIsArray) { + isArray = Array.isArray; + } + + function isHash(object) { + return object instanceof Hash; + } + + function isFunction(object) { + return _toString.call(object) === FUNCTION_CLASS; + } + + function isString(object) { + return _toString.call(object) === STRING_CLASS; + } + + function isNumber(object) { + return _toString.call(object) === NUMBER_CLASS; + } + + function isDate(object) { + return _toString.call(object) === DATE_CLASS; + } + + function isUndefined(object) { + return typeof object === "undefined"; + } + + extend(Object, { + 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 + }); +})(); +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 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 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 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 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 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 + }; +})()); + + + +(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'; + } + + + 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'); +}; +var PeriodicalExecuter = Class.create({ + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + execute: function() { + this.callback(this); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.execute(); + this.currentlyExecuting = false; + } catch(e) { + this.currentlyExecuting = false; + throw e; + } + } + } +}); +Object.extend(String, { + interpret: function(value) { + return value == null ? '' : String(value); + }, + specialChar: { + '\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); }; + } + + function gsub(pattern, replacement) { + var result = '', source = this, match; + replacement = prepareReplacement(replacement); + + if (Object.isString(pattern)) + pattern = RegExp.escape(pattern); + + 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 = ''; + } + } + 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 scan(pattern, iterator) { + this.gsub(pattern, iterator); + return String(this); + } + + 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 strip() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + } + + function stripTags() { + return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); + } + + function stripScripts() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + } + + 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 evalScripts() { + return this.extractScripts().map(function(script) { return eval(script); }); + } + + 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 { }; + + 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 (key in hash) { + if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; + hash[key].push(value); + } + else hash[key] = value; + } + return hash; + }); + } + + function toArray() { + return this.split(''); + } + + function succ() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + } + + function times(count) { + return count < 1 ? '' : new Array(count + 1).join(this); + } + + function camelize() { + return this.replace(/-+(.)?/g, function(match, chr) { + return chr ? chr.toUpperCase() : ''; + }); + } + + function capitalize() { + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + } + + 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 dasherize() { + return this.replace(/_/g, '-'); + } + + 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 unfilterJSON(filter) { + return this.replace(filter || Prototype.JSONFilter, '$1'); + } + + 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()); + } + + function parseJSON() { + var json = this.unfilterJSON(); + return JSON.parse(json); + } + + function include(pattern) { + return this.indexOf(pattern) > -1; + } + + 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 empty() { + return this == ''; + } + + function blank() { + return /^\s*$/.test(this); + } + + 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 + }; +})()); + +var Template = Class.create({ + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + 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] + ''); + + var before = match[1] || ''; + if (before == '\\') return match[2]; + + 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]; + ctx = ctx[comp]; + 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 Enumerable = (function() { + function each(iterator, context) { + var index = 0; + try { + this._each(function(value) { + iterator.call(context, value, index++); + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + } + + function eachSlice(number, iterator, context) { + var index = -number, slices = [], array = this.toArray(); + if (number < 1) return array; + while ((index += number) < array.length) + 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) { + result = result && !!iterator.call(context, value, index); + if (!result) throw $break; + }); + return result; + } + + 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; + }); + return result; + } + + function collect(iterator, context) { + iterator = iterator || Prototype.K; + var results = []; + this.each(function(value, index) { + results.push(iterator.call(context, value, index)); + }); + return results; + } + + function detect(iterator, context) { + var result; + this.each(function(value, index) { + if (iterator.call(context, value, index)) { + result = value; + throw $break; + } + }); + return result; + } + + function findAll(iterator, context) { + var results = []; + this.each(function(value, index) { + if (iterator.call(context, value, index)) + results.push(value); + }); + return results; + } + + function grep(filter, iterator, context) { + iterator = iterator || Prototype.K; + var results = []; + + if (Object.isString(filter)) + filter = new RegExp(RegExp.escape(filter)); + + this.each(function(value, index) { + if (filter.match(value)) + results.push(iterator.call(context, value, index)); + }); + return results; + } + + function include(object) { + if (Object.isFunction(this.indexOf)) + if (this.indexOf(object) != -1) return true; + + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + } + + function inGroupsOf(number, fillWith) { + fillWith = Object.isUndefined(fillWith) ? null : 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) { + memo = iterator.call(context, memo, value, index); + }); + return memo; + } + + function invoke(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + } + + function max(iterator, context) { + iterator = iterator || Prototype.K; + var result; + this.each(function(value, index) { + value = iterator.call(context, value, index); + if (result == null || value >= result) + result = value; + }); + return result; + } + + function min(iterator, context) { + iterator = iterator || Prototype.K; + var result; + this.each(function(value, index) { + value = iterator.call(context, value, index); + 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); + }); + return [trues, falses]; + } + + function pluck(property) { + var results = []; + this.each(function(value) { + results.push(value[property]); + }); + return results; + } + + function reject(iterator, context) { + var results = []; + 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 { + value: value, + 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'); + } + + function toArray() { + return this.map(); + } + + function zip() { + 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 iterator(collections.pluck(index)); + }); + } + + function size() { + return this.toArray().length; + } + + function inspect() { + 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, + 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 + }; +})(); + +function $A(iterable) { + if (!iterable) return []; + 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(); + return string ? string.split(/\s+/) : []; +} + +Array.from = $A; + + +(function() { + var arrayProto = Array.prototype, + 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++) { + if (i in this) iterator.call(context, this[i], i, this); + } + } + if (!_each) _each = each; + + function clear() { + this.length = 0; + return this; + } + + function first() { + return this[0]; + } + + function last() { + return this[this.length - 1]; + } + + function compact() { + 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()); + array.push(value); + return array; + }); + } + + function without() { + var values = slice.call(arguments, 0); + return this.select(function(value) { + return !values.include(value); + }); + } + + function reverse(inline) { + return (inline === false ? this.toArray() : this)._reverse(); + } + + function uniq(sorted) { + 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; }); + }); + } + + + function clone() { + return slice.call(this, 0); + } + + function size() { + return this.length; + } + + function inspect() { + 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; + 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; + } + + function concat() { + 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)) { + for (var j = 0, arrayLength = item.length; j < arrayLength; j++) + array.push(item[j]); + } else { + array.push(item); + } + } + return array; + } + + Object.extend(arrayProto, Enumerable); + + 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, + intersect: intersect, + clone: clone, + toArray: clone, + size: size, + inspect: inspect + }); + + var CONCAT_ARGUMENTS_BUGGY = (function() { + return [].concat(arguments)[0][0] !== 1; + })(1,2); + + if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat; + + if (!arrayProto.indexOf) arrayProto.indexOf = indexOf; + if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf; +})(); +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); + } + } + + 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 toObject() { + return Object.clone(this._object); + } + + + + function keys() { + return this.pluck('key'); + } + + function values() { + return this.pluck('value'); + } + + 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 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 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)); + } + return results.concat(queryValues); + } + } else results.push(toQueryPair(key, values)); + return results; + }).join('&'); + } + + function inspect() { + return '#'; + } + + 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 + }; +})()); + +Hash.from = $H; +Object.extend(Number.prototype, (function() { + function toColorPart() { + return this.toPaddedString(2, 16); + } + + function succ() { + return this + 1; + } + + 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 abs() { + return Math.abs(this); + } + + function round() { + return Math.round(this); + } + + function ceil() { + return Math.ceil(this); + } + + function floor() { + return Math.floor(this); + } + + 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(); + } + } + + 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 Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest();}, + function() {return new ActiveXObject('Msxml2.XMLHTTP');}, + function() {return new ActiveXObject('Microsoft.XMLHTTP');} + ) || false; + }, + + activeRequestCount: 0 +}; + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(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) { } + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { Ajax.activeRequestCount++; }, + onComplete: function() { Ajax.activeRequestCount--; } +}); +Ajax.Base = Class.create({ + initialize: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '', + evalJSON: true, + evalJS: true + }; + 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) { + $super(options); + this.transport = Ajax.getTransport(); + this.request(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); + + 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; + } + + this.parameters = params.toQueryParams(); + + try { + var response = new Ajax.Response(this); + if (this.options.onCreate) this.options.onCreate(response); + Ajax.Responders.dispatch('onCreate', this, response); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + 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.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) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + '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 : ''); + + /* 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 (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]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value; }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + var status = this.getStatus(); + return !status || (status >= 200 && status < 300) || status == 304; + }, + + getStatus: function() { + try { + if (this.transport.status === 1223) return 204; + return this.transport.status || 0; + } catch (e) { return 0; } + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); + + if (state == 'Complete') { + try { + this._complete = true; + (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))) + this.evalResponse(); + } + + try { + (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') { + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + 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 : '' + })); + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name) || null; + } catch (e) { return null; } + }, + + evalResponse: function() { + try { + return eval((this.transport.responseText || '').unfilterJSON()); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + + + + + + + + +Ajax.Response = Class.create({ + initialize: function(request){ + this.request = request; + 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.responseText = String.interpret(transport.responseText); + this.headerJSON = this._getHeaderJSON(); + } + + if (readyState == 4) { + var xml = transport.responseXML; + this.responseXML = Object.isUndefined(xml) ? null : xml; + this.responseJSON = this._getResponseJSON(); + } + }, + + status: 0, + + statusText: '', + + getStatus: Ajax.Request.prototype.getStatus, + + getStatusText: function() { + try { + return this.transport.statusText || ''; + } catch (e) { return ''; } + }, + + getHeader: Ajax.Request.prototype.getHeader, + + getAllHeaders: function() { + try { + return this.getAllResponseHeaders(); + } catch (e) { return null; } + }, + + getResponseHeader: function(name) { + return this.transport.getResponseHeader(name); + }, + + getAllResponseHeaders: function() { + return this.transport.getAllResponseHeaders(); + }, + + _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()); + } catch (e) { + this.request.dispatchException(e); + } + }, + + _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; + try { + 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) { + this.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) { + this.updateContent(response.responseText); + if (Object.isFunction(onComplete)) onComplete(response, json); + }).bind(this); + + $super(url, 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 (options.insertion) { + if (Object.isString(options.insertion)) { + var insertion = { }; insertion[options.insertion] = responseText; + receiver.insert(insertion); + } + else options.insertion(receiver, responseText); + } + else receiver.update(responseText); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { + 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.updater = { }; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(response) { + if (this.options.decay) { + 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); + }, + + 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); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + 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; + }; +} + +/*--------------------------------------------------------------------------*/ + +if (!Node) var Node = { }; + +if (!Node.ELEMENT_NODE) { + Object.extend(Node, { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }); +} + + + +(function(global) { + function shouldUseCache(tagName, attributes) { + if (tagName === 'select') return false; + if ('type' in attributes) return false; + return true; + } + + var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){ + try { + var el = document.createElement(''); + return el.tagName.toLowerCase() === 'input' && el.name === 'x'; + } + catch(err) { + return false; + } + })(); + + var element = global.Element; + + 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 + '">'; + delete attributes.name; + return Element.writeAttribute(document.createElement(tagName), attributes); + } + + if (!cache[tagName]) cache[tagName] = Element.extend(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 || { }); + if (element) global.Element.prototype = element.prototype; + +})(this); + +Element.idCounter = 1; +Element.cache = { }; + +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'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + hide: function(element) { + element = $(element); + element.style.display = 'none'; + return element; + }, + + show: function(element) { + element = $(element); + element.style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: (function(){ + + var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){ + var el = document.createElement("select"), + isBuggy = true; + el.innerHTML = ""; + if (el.options && el.options[0]) { + isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION"; + } + el = null; + return isBuggy; + })(); + + var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){ + try { + var el = document.createElement("table"); + if (el && el.tBodies) { + el.innerHTML = "
                          "; + var isBuggy = typeof el.tBodies[0] == "undefined"; + el = null; + return isBuggy; + } + } catch (e) { + return true; + } + })(); + + var LINK_ELEMENT_INNERHTML_BUGGY = (function() { + try { + var el = document.createElement('div'); + el.innerHTML = ""; + var isBuggy = (el.childNodes.length === 0); + el = null; + return isBuggy; + } catch(e) { + return true; + } + })(); + + 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; + try { + s.appendChild(document.createTextNode("")); + isBuggy = !s.firstChild || + s.firstChild && s.firstChild.nodeType !== 3; + } catch (e) { + isBuggy = true; + } + s = null; + return isBuggy; + })(); + + + function update(element, content) { + element = $(element); + var purgeElement = Element._purgeElement; + + var descendants = element.getElementsByTagName('*'), + i = descendants.length; + while (i--) purgeElement(descendants[i]); + + if (content && content.toElement) + content = content.toElement(); + + 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) { + element.text = content; + return element; + } + + if (ANY_INNERHTML_BUGGY) { + if (tagName in Element._insertionTranslations.tags) { + 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) { + while (element.firstChild) { + element.removeChild(element.firstChild); + } + var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true); + nodes.each(function(node) { element.appendChild(node); }); + } + else { + element.innerHTML = content.stripScripts(); + } + } + else { + element.innerHTML = content.stripScripts(); + } + + content.evalScripts.bind(content).defer(); + return element; + } + + return update; + })(), + + replace: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + else if (!Object.isElement(content)) { + content = Object.toHTML(content); + var range = element.ownerDocument.createRange(); + range.selectNode(element); + content.evalScripts.bind(content).defer(); + content = range.createContextualFragment(content.stripScripts()); + } + element.parentNode.replaceChild(content, element); + return element; + }, + + insert: function(element, insertions) { + element = $(element); + + 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]; + position = position.toLowerCase(); + insert = Element._insertionTranslations[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + insert(element, content); + continue; + } + + content = Object.toHTML(content); + + tagName = ((position == 'before' || position == 'after') + ? element.parentNode : element).tagName.toUpperCase(); + + childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + + if (position == 'top' || position == 'after') childNodes.reverse(); + childNodes.each(insert.curry(element)); + + content.evalScripts.bind(content).defer(); + } + + return element; + }, + + 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); + wrapper.appendChild(element); + return wrapper; + }, + + inspect: function(element) { + element = $(element); + 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); + }); + return result + '>'; + }, + + 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; + } + + return elements; + }, + + ancestors: function(element) { + return Element.recursivelyCollect(element, 'parentNode'); + }, + + descendants: function(element) { + return Element.select(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; + while (child) { + if (child.nodeType === 1) { + results.push(Element.extend(child)); + } + child = child.nextSibling; + } + return results; + }, + + previousSiblings: function(element, maximumLength) { + return Element.recursivelyCollect(element, 'previousSibling'); + }, + + nextSiblings: function(element) { + return Element.recursivelyCollect(element, 'nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return Element.previousSiblings(element).reverse() + .concat(Element.nextSiblings(element)); + }, + + 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) { + 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); + }, + + 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]; + }, + + previous: function(element, expression, index) { + element = $(element); + if (Object.isNumber(expression)) index = expression, expression = false; + if (!Object.isNumber(index)) index = 0; + + if (expression) { + return Prototype.Selector.find(element.previousSiblings(), expression, index); + } else { + return element.recursivelyCollect("previousSibling", index + 1)[index]; + } + }, + + next: function(element, expression, index) { + element = $(element); + if (Object.isNumber(expression)) index = expression, expression = false; + if (!Object.isNumber(index)) index = 0; + + if (expression) { + return Prototype.Selector.find(element.nextSiblings(), expression, index); + } else { + var maximumLength = Object.isNumber(index) ? index + 1 : 1; + return element.recursivelyCollect("nextSibling", index + 1)[index]; + } + }, + + + select: function(element) { + element = $(element); + var expressions = Array.prototype.slice.call(arguments, 1).join(', '); + return Prototype.Selector.select(expressions, element); + }, + + adjacent: function(element) { + element = $(element); + var expressions = Array.prototype.slice.call(arguments, 1).join(', '); + return Prototype.Selector.select(expressions, element.parentNode).without(element); + }, + + identify: function(element) { + element = $(element); + var id = Element.readAttribute(element, 'id'); + if (id) return id; + do { id = 'anonymous_element_' + Element.idCounter++; } while ($(id)); + Element.writeAttribute(element, 'id', id); + return id; + }, + + 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; + } + } + return element.getAttribute(name); + }, + + writeAttribute: function(element, name, value) { + element = $(element); + var attributes = { }, t = Element._attributeTranslations.write; + + 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); + else element.setAttribute(name, value); + } + return element; + }, + + getHeight: function(element) { + return Element.getDimensions(element).height; + }, + + getWidth: function(element) { + return Element.getDimensions(element).width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + 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))); + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + if (!Element.hasClassName(element, className)) + element.className += (element.className ? ' ' : '') + className; + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + element.className = element.className.replace( + new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip(); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + return Element[Element.hasClassName(element, className) ? + 'removeClassName' : 'addClassName'](element, className); + }, + + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.blank(); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + + if (element.compareDocumentPosition) + return (element.compareDocumentPosition(ancestor) & 8) === 8; + + if (ancestor.contains) + return ancestor.contains(element) && ancestor !== element; + + while (element = element.parentNode) + if (element == ancestor) return true; + + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = Element.cumulativeOffset(element); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + style = style == 'float' ? 'cssFloat' : style.camelize(); + var value = element.style[style]; + 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; + }, + + getOpacity: function(element) { + return $(element).getStyle('opacity'); + }, + + setStyle: function(element, styles) { + element = $(element); + 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; + } + for (var property in styles) + if (property == 'opacity') element.setOpacity(styles[property]); + else + elementStyle[(property == 'float' || property == 'cssFloat') ? + (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') : + property] = styles[property]; + + return element; + }, + + setOpacity: function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + return element; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + if (Prototype.Browser.Opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return 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'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + 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] || { }); + + source = $(source); + var p = Element.viewportOffset(source), delta = [0, 0], parent = null; + + element = $(element); + + if (Element.getStyle(element, 'position') == 'absolute') { + parent = Element.getOffsetParent(element); + delta = Element.viewportOffset(parent); + } + + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + 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'; + return element; + } +}; + +Object.extend(Element.Methods, { + getElementsBySelector: Element.Methods.select, + + childElements: Element.Methods.immediateDescendants +}); + +Element._attributeTranslations = { + write: { + names: { + className: 'class', + htmlFor: 'for' + }, + 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) { + 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); + } + ); +} + +else if (Prototype.Browser.IE) { + Element.Methods.getStyle = function(element, style) { + element = $(element); + 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 (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'; + return null; + } + return value; + }; + + 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'); + return element; + } else if (value < 0.00001) value = 0; + style.filter = stripAlpha(filter) + + 'alpha(opacity=' + (value * 100) + ')'; + return element; + }; + + Element._attributeTranslations = (function(){ + + var classProp = 'className', + forProp = 'for', + el = document.createElement('div'); + + el.setAttribute(classProp, 'x'); + + 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 = null; + + return { + read: { + names: { + 'class': classProp, + 'className': classProp, + 'for': forProp, + 'htmlFor': forProp + }, + values: { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute); + }, + _getAttr2: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + _getAttrNode: function(element, attribute) { + var node = element.getAttributeNode(attribute); + return node ? node.value : ""; + }, + _getEv: (function(){ + + var el = document.createElement('div'), f; + el.onclick = Prototype.emptyFunction; + var value = el.getAttribute('onclick'); + + 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]; + return attribute.strip(); + }; + } + else if (value === '') { + f = function(element, attribute) { + attribute = element.getAttribute(attribute); + if (!attribute) return null; + return attribute.strip(); + }; + } + el = null; + return f; + })(), + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + title: function(element) { + return element.title; + } + } + } + }; + })(); + + Element._attributeTranslations.write = { + names: Object.extend({ + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing' + }, Element._attributeTranslations.read.names), + values: { + checked: function(element, value) { + element.checked = !!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) { + Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; + Element._attributeTranslations.has[attr.toLowerCase()] = attr; + }); + + (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, + onmousedown: 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 + }); + })(Element._attributeTranslations.read.values); + + if (Prototype.BrowserFeatures.ElementExtensions) { + (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. + results.push(node); + return results; + } + + 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]; + }; + })(); + } + +} + +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; + return element; + }; +} + +else if (Prototype.Browser.WebKit) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + 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) { } + + return element; + }; +} + +if ('outerHTML' in document.documentElement) { + Element.Methods.replace = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + element.parentNode.replaceChild(content, element); + return element; + } + + content = Object.toHTML(content); + var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); + + if (Element._insertionTranslations.tags[tagName]) { + var nextSibling = element.next(), + fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + parent.removeChild(element); + if (nextSibling) + fragments.each(function(node) { parent.insertBefore(node, nextSibling); }); + else + fragments.each(function(node) { parent.appendChild(node); }); + } + else element.outerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +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]; + + var workaround = false; + if (t) workaround = true; + else if (force) { + workaround = true; + t = ['', '', 0]; + } + + if (workaround) { + div.innerHTML = ' ' + t[0] + html + t[1]; + div.removeChild(div.firstChild); + for (var i = t[2]; i--; ) { + div = div.firstChild; + } + } + else { + div.innerHTML = html; + } + return $A(div.childNodes); +}; + +Element._insertionTranslations = { + before: function(element, node) { + element.parentNode.insertBefore(node, element); + }, + top: function(element, node) { + element.insertBefore(node, element.firstChild); + }, + bottom: function(element, node) { + element.appendChild(node); + }, + after: function(element, node) { + element.parentNode.insertBefore(node, element.nextSibling); + }, + tags: { + TABLE: ['
                          test
                          ', '
                          ', 1], + TBODY: ['', '
                          ', 2], + TR: ['', '
                          ', 3], + TD: ['
                          ', '
                          ', 4], + SELECT: ['', 1] + } +}; + +(function() { + var tags = Element._insertionTranslations.tags; + Object.extend(tags, { + THEAD: tags.TBODY, + TFOOT: tags.TBODY, + TH: tags.TD + }); +})(); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + attribute = Element._attributeTranslations.has[attribute] || attribute; + var node = $(element).getAttributeNode(attribute); + return !!(node && node.specified); + } +}; + +Element.Methods.ByTag = { }; + +Object.extend(Element, Element.Methods); + +(function(div) { + + if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) { + window.HTMLElement = { }; + window.HTMLElement.prototype = div['__proto__']; + Prototype.BrowserFeatures.ElementExtensions = true; + } + + div = null; + +})(document.createElement('div')); + +Element.extend = (function() { + + function checkDeficiency(tagName) { + 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'); + delete proto[id]; + el = null; + return isBuggy; + } + } + return false; + } + + function extendElementWith(element, methods) { + for (var property in methods) { + var value = methods[property]; + if (Object.isFunction(value) && !(property in element)) + element[property] = value.methodize(); + } + } + + var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object'); + + if (Prototype.BrowserFeatures.SpecificElementExtensions) { + if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) { + return function(element) { + if (element && typeof element._extendedByPrototype == 'undefined') { + var t = element.tagName; + 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 extend = Object.extend(function(element) { + if (!element || typeof element._extendedByPrototype != 'undefined' || + element.nodeType != 1 || element == window) return element; + + var methods = Object.clone(Methods), + tagName = element.tagName.toUpperCase(); + + if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); + + 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); + } + } + }); + + extend.refresh(); + return extend; +})(); + +if (document.documentElement.hasAttribute) { + Element.hasAttribute = function(element, attribute) { + return element.hasAttribute(attribute); + }; +} +else { + Element.hasAttribute = Element.Methods.Simulated.hasAttribute; +} + +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) + }); + } + + if (arguments.length == 2) { + var tagName = methods; + methods = arguments[1]; + } + + if (!tagName) Object.extend(Element.Methods, methods || { }); + else { + if (Object.isArray(tagName)) tagName.each(extend); + else extend(tagName); + } + + function extend(tagName) { + tagName = tagName.toUpperCase(); + if (!Element.Methods.ByTag[tagName]) + Element.Methods.ByTag[tagName] = { }; + Object.extend(Element.Methods.ByTag[tagName], methods); + } + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + for (var property in methods) { + var value = methods[property]; + if (!Object.isFunction(value)) continue; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = value.methodize(); + } + } + + 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" + }; + if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName.capitalize() + 'Element'; + if (window[klass]) return window[klass]; + + var element = document.createElement(tagName), + proto = element['__proto__'] || element.constructor.prototype; + + element = null; + return proto; + } + + var elementPrototype = window.HTMLElement ? HTMLElement.prototype : + Element.prototype; + + if (F.ElementExtensions) { + copy(Element.Methods, elementPrototype); + copy(Element.Methods.Simulated, elementPrototype, true); + } + + if (F.SpecificElementExtensions) { + for (var tag in Element.Methods.ByTag) { + var klass = findDOMClass(tag); + if (Object.isUndefined(klass)) continue; + copy(T[tag], klass.prototype); + } + } + + Object.extend(Element, Element.Methods); + delete Element.ByTag; + + if (Element.extend.refresh) Element.extend.refresh(); + Element.cache = { }; +}; + + +document.viewport = { + + getDimensions: function() { + return { width: this.getWidth(), height: this.getHeight() }; + }, + + getScrollOffsets: function() { + return Element._returnOffset( + 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 getRootElement() { + if (B.WebKit && !doc.evaluate) + return document; + + if (B.Opera && window.parseFloat(window.opera.version()) < 9.5) + return document.body; + + return document.documentElement; + } + + function define(D) { + if (!element) element = getRootElement(); + + property[D] = 'client' + D; + + viewport['get' + D] = function() { return element[property[D]]; }; + return viewport['get' + D](); + } + + viewport.getWidth = define.curry('Width'); + + viewport.getHeight = define.curry('Height'); +})(document.viewport); + + +Element.Storage = { + UID: 1 +}; + +Element.addMethods({ + getStorage: function(element) { + if (!(element = $(element))) return; + + var uid; + if (element === window) { + uid = 0; + } else { + if (typeof element._prototypeUID === "undefined") + element._prototypeUID = Element.Storage.UID++; + uid = element._prototypeUID; + } + + if (!Element.Storage[uid]) + Element.Storage[uid] = $H(); + + return Element.Storage[uid]; + }, + + store: function(element, key, value) { + if (!(element = $(element))) return; + + if (arguments.length === 2) { + Element.getStorage(element).update(key); + } else { + Element.getStorage(element).set(key, value); + } + + return element; + }, + + retrieve: function(element, key, defaultValue) { + if (!(element = $(element))) return; + var hash = Element.getStorage(element), value = hash.get(key); + + if (Object.isUndefined(value)) { + hash.set(key, defaultValue); + value = defaultValue; + } + + return value; + }, + + 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; + while (i--) { + descendants[i]._prototypeUID = void 0; + } + } + return Element.extend(clone); + }, + + purge: function(element) { + if (!(element = $(element))) return; + var purgeElement = Element._purgeElement; + + purgeElement(element); + + var descendants = element.getElementsByTagName('*'), + i = descendants.length; + + while (i--) purgeElement(descendants[i]); + + return null; + } +}); + +(function() { + + function toDecimal(pctString) { + var match = pctString.match(/^(\d+)%?$/i); + if (!match) return null; + return (Number(match[1]) / 100); + } + + function getPixelValue(value, property, context) { + var element = null; + if (Object.isElement(value)) { + element = value; + value = element.getStyle(property); + } + + if (value === null) { + return null; + } + + if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) { + return window.parseFloat(value); + } + + 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; + element.runtimeStyle.left = element.currentStyle.left; + element.style.left = value || 0; + value = element.style.pixelLeft; + element.style.left = style; + element.runtimeStyle.left = rStyle; + + return value; + } + + if (element && isPercentage) { + context = context || element.parentNode; + var decimal = toDecimal(value); + var whole = null; + var position = element.getStyle('position'); + + var isHorizontal = property.include('left') || property.include('right') || + property.include('width'); + + var isVertical = property.include('top') || property.include('bottom') || + property.include('height'); + + if (context === document.viewport) { + if (isHorizontal) { + whole = document.viewport.getWidth(); + } else if (isVertical) { + whole = document.viewport.getHeight(); + } + } else { + if (isHorizontal) { + whole = $(context).measure('width'); + } else if (isVertical) { + whole = $(context).measure('height'); + } + } + + return (whole === null) ? 0 : whole * decimal; + } + + return 0; + } + + function toCSSPixels(number) { + if (Object.isString(number) && number.endsWith('px')) { + return number; + } + return number + 'px'; + } + + function isDisplayed(element) { + var originalElement = element; + while (element && element.parentNode) { + var display = element.getStyle('display'); + if (display === 'none') { + return false; + } + element = $(element.parentNode); + } + return true; + } + + var hasLayout = Prototype.K; + if ('currentStyle' in document.documentElement) { + hasLayout = function(element) { + if (!element.currentStyle.hasLayout) { + element.style.zoom = 1; + } + return element; + }; + } + + function cssNameFor(key) { + if (key.include('border')) key = key + '-width'; + return key.camelize(); + } + + Element.Layout = Class.create(Hash, { + initialize: function($super, element, preCompute) { + $super(); + this.element = $(element); + + 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 ); + this._end(); + this._preComputing = false; + } + }, + + _set: function(property, value) { + return Hash.prototype.set.call(this, property, value); + }, + + set: function(property, value) { + throw "Properties of Element.Layout are read-only."; + }, + + get: function($super, property) { + var value = $super(property); + return value === null ? this._compute(property) : value; + }, + + _begin: function() { + if (this._prepared) return; + + var element = this.element; + if (isDisplayed(element)) { + this._prepared = true; + return; + } + + var originalStyles = { + position: element.style.position || '', + width: element.style.width || '', + visibility: element.style.visibility || '', + display: element.style.display || '' + }; + + element.store('prototype_original_styles', originalStyles); + + var position = element.getStyle('position'), + width = element.getStyle('width'); + + if (width === "0px" || width === null) { + element.style.display = 'block'; + width = element.getStyle('width'); + } + + var context = (position === 'fixed') ? document.viewport : + element.parentNode; + + element.setStyle({ + position: 'absolute', + visibility: 'hidden', + display: 'block' + }); + + 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); + } 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'); + } + + element.setStyle({ width: newWidth + 'px' }); + + this._prepared = true; + }, + + _end: function() { + var element = this.element; + var originalStyles = element.retrieve('prototype_original_styles'); + element.store('prototype_original_styles', null); + element.setStyle(originalStyles); + this._prepared = false; + }, + + _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)); + }, + + toObject: function() { + var args = $A(arguments); + var keys = (args.length === 0) ? Element.Layout.PROPERTIES : + args.join(' ').split(' '); + var obj = {}; + keys.each( function(key) { + if (!Element.Layout.PROPERTIES.include(key)) return; + var value = this.get(key); + if (value != null) obj[key] = value; + }, this); + return obj; + }, + + toHash: function() { + var obj = this.toObject.apply(this, arguments); + return new Hash(obj); + }, + + toCSS: function() { + var args = $A(arguments); + var keys = (args.length === 0) ? Element.Layout.PROPERTIES : + args.join(' ').split(' '); + var css = {}; + + 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'; + }, this); + return css; + }, + + 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'), + + 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) { + if (!this._preComputing) this._begin(); + + 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 pTop = this.get('padding-top'), + pBottom = this.get('padding-bottom'); + + if (!this._preComputing) this._end(); + + return bHeight - bTop - bBottom - pTop - pBottom; + }, + + 'width': function(element) { + if (!this._preComputing) this._begin(); + + 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 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'); + + return height + pTop + pBottom; + }, + + '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) { + if (!this._preComputing) this._begin(); + var height = element.offsetHeight; + if (!this._preComputing) this._end(); + return height; + }, + + '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'); + + 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'); + + if (bWidth <= 0) return 0; + + return bWidth + mLeft + mRight; + }, + + 'top': function(element) { + var offset = element.positionedOffset(); + return offset.top; + }, + + 'bottom': function(element) { + var offset = element.positionedOffset(), + parent = element.getOffsetParent(), + pHeight = parent.measure('height'); + + var mHeight = this.get('border-box-height'); + + return pHeight - mHeight - offset.top; + }, + + 'left': function(element) { + var offset = element.positionedOffset(); + return offset.left; + }, + + 'right': function(element) { + var offset = element.positionedOffset(), + parent = element.getOffsetParent(), + pWidth = parent.measure('width'); + + var mWidth = this.get('border-box-width'); + + return pWidth - mWidth - offset.left; + }, + + 'padding-top': function(element) { + return getPixelValue(element, 'paddingTop'); + }, + + 'padding-bottom': function(element) { + return getPixelValue(element, 'paddingBottom'); + }, + + 'padding-left': function(element) { + return getPixelValue(element, 'paddingLeft'); + }, + + 'padding-right': function(element) { + return getPixelValue(element, 'paddingRight'); + }, + + 'border-top': function(element) { + return getPixelValue(element, 'borderTopWidth'); + }, + + 'border-bottom': function(element) { + return getPixelValue(element, 'borderBottomWidth'); + }, + + 'border-left': function(element) { + return getPixelValue(element, 'borderLeftWidth'); + }, + + 'border-right': function(element) { + return getPixelValue(element, 'borderRightWidth'); + }, + + 'margin-top': function(element) { + return getPixelValue(element, 'marginTop'); + }, + + 'margin-bottom': function(element) { + return getPixelValue(element, 'marginBottom'); + }, + + 'margin-left': function(element) { + return getPixelValue(element, 'marginLeft'); + }, + + 'margin-right': function(element) { + return getPixelValue(element, 'marginRight'); + } + } + }); + + if ('getBoundingClientRect' in document.documentElement) { + Object.extend(Element.Layout.COMPUTATIONS, { + 'right': function(element) { + var parent = hasLayout(element.getOffsetParent()); + var rect = element.getBoundingClientRect(), + pRect = parent.getBoundingClientRect(); + + return (pRect.right - rect.right).round(); + }, + + 'bottom': function(element) { + var parent = hasLayout(element.getOffsetParent()); + var rect = element.getBoundingClientRect(), + pRect = parent.getBoundingClientRect(); + + return (pRect.bottom - rect.bottom).round(); + } + }); + } + + Element.Offset = Class.create({ + initialize: function(left, top) { + this.left = left.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 + ); + }, + + inspect: function() { + return "#".interpolate(this); + }, + + toString: function() { + return "[#{left}, #{top}]".interpolate(this); + }, + + toArray: function() { + return [this.left, this.top]; + } + }); + + function getLayout(element, preCompute) { + return new Element.Layout(element, preCompute); + } + + function measure(element, property) { + return $(element).getLayout().get(property); + } + + function getDimensions(element) { + element = $(element); + var display = Element.getStyle(element, 'display'); + + 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 + }; + + var newStyles = { + visibility: 'hidden', + display: 'block' + }; + + if (originalStyles.position !== 'fixed') + newStyles.position = 'absolute'; + + Element.setStyle(element, newStyles); + + var dimensions = { + width: element.offsetWidth, + height: element.offsetHeight + }; + + Element.setStyle(element, originalStyles); + + return dimensions; + } + + function getOffsetParent(element) { + element = $(element); + + if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) + return $(document.body); + + 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') { + return isHtml(element) ? $(document.body) : $(element); + } + } + + return $(document.body); + } + + + function cumulativeOffset(element) { + element = $(element); + var valueT = 0, valueL = 0; + if (element.parentNode) { + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + } + return new Element.Offset(valueL, valueT); + } + + function positionedOffset(element) { + element = $(element); + + var layout = element.getLayout(); + + var valueT = 0, valueL = 0; + do { + 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; + } + } while (element); + + valueL -= layout.get('margin-top'); + valueT -= layout.get('margin-left'); + + return new Element.Offset(valueL, valueT); + } + + function cumulativeScrollOffset(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return new Element.Offset(valueL, valueT); + } + + function viewportOffset(forElement) { + element = $(element); + var valueT = 0, valueL = 0, docBody = document.body; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == docBody && + Element.getStyle(element, 'position') == 'absolute') break; + } while (element = element.offsetParent); + + element = forElement; + do { + if (element != docBody) { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + return new Element.Offset(valueL, valueT); + } + + function absolutize(element) { + element = $(element); + + if (Element.getStyle(element, 'position') === 'absolute') { + return element; + } + + var offsetParent = getOffsetParent(element); + var eOffset = element.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.setStyle({ + position: 'absolute', + top: offset.top + 'px', + left: offset.left + 'px', + width: layout.get('width') + 'px', + height: layout.get('height') + 'px' + }); + + return element; + } + + function relativize(element) { + element = $(element); + if (Element.getStyle(element, 'position') === 'relative') { + return element; + } + + 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); + + if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) + return $(document.body); + + 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; + } + ); + + 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 offsetParent = element.getOffsetParent(); + if (offsetParent && offsetParent.getStyle('position') === 'fixed') + hasLayout(offsetParent); + + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + }); + } else if (Prototype.Browser.Webkit) { + cumulativeOffset = function(element) { + element = $(element); + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return new Element.Offset(valueL, valueT); + }; + } + + + Element.addMethods({ + getLayout: getLayout, + measure: measure, + getDimensions: getDimensions, + getOffsetParent: getOffsetParent, + cumulativeOffset: cumulativeOffset, + positionedOffset: positionedOffset, + cumulativeScrollOffset: cumulativeScrollOffset, + viewportOffset: viewportOffset, + absolutize: absolutize, + relativize: relativize + }); + + function isBody(element) { + return element.nodeName.toUpperCase() === 'BODY'; + } + + function isHtml(element) { + return element.nodeName.toUpperCase() === 'HTML'; + } + + function isDocument(element) { + return element.nodeType === Node.DOCUMENT_NODE; + } + + function isDetached(element) { + return element !== document.body && + !Element.descendantOf(element, document.body); + } + + if ('getBoundingClientRect' in document.documentElement) { + Element.addMethods({ + 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); +}; + +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 + }; +})(); +Prototype._original_property = window.Sizzle; +/*! + * 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]; + + 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 ); + } + } + } +}; + +var origPOS = Expr.match.POS; + +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 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +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; + }; +} + +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; + }; +} + +(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 +})(); + +(function(){ + + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function(match, context){ + var results = context.getElementsByTagName(match[1]); + + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + div.innerHTML = ""; + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + Expr.attrHandle.href = function(elem){ + return elem.getAttribute("href", 2); + }; + } + + div = null; // release memory in IE +})(); + +if ( document.querySelectorAll ) (function(){ + var oldSizzle = Sizzle, div = document.createElement("div"); + div.innerHTML = "

                          "; + + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function(query, context, extra, seed){ + context = context || document; + + if ( !seed && context.nodeType === 9 && !isXML(context) ) { + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(e){} + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + div = null; // release memory in IE +})(); + +if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){ + var div = document.createElement("div"); + div.innerHTML = "
                          "; + + if ( div.getElementsByClassName("e").length === 0 ) + return; + + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) + return; + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function(match, context, isXML) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + 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; + + 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; + } + } +} + +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; + } + } +} + +var contains = document.compareDocumentPosition ? function(a, b){ + return a.compareDocumentPosition(b) & 16; +} : function(a, b){ + return a !== b && (a.contains ? a.contains(b) : true); +}; + +var isXML = function(elem){ + return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || + !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML"; +}; + +var posProcess = function(selector, context){ + var tmpSet = [], later = "", match, + root = context.nodeType ? [context] : context; + + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + + +window.Sizzle = Sizzle; + +})(); + +;(function(engine) { + var extendElements = Prototype.Selector.extendElements; + + function select(selector, scope) { + return extendElements(engine(selector, scope || document)); + } + + function match(element, selector) { + return engine.matches(selector, [element]).length == 1; + } + + Prototype.Selector.engine = engine; + Prototype.Selector.select = select; + Prototype.Selector.match = match; +})(Sizzle); + +window.Sizzle = Prototype._original_property; +delete Prototype._original_property; + +var Form = { + reset: function(form) { + form = $(form); + form.reset(); + return form; + }, + + 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; + + if (options.hash) { + initial = {}; + accumulator = function(result, key, value) { + if (key in result) { + if (!Object.isArray(result[key])) result[key] = [result[key]]; + result[key].push(value); + } else result[key] = value; + return result; + }; + } else { + initial = ''; + accumulator = function(result, key, value) { + return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value); + }; + } + + 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)))) { + result = accumulator(result, key, value); + } + } + return result; + }); + } +}; + +Form.Methods = { + 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++) { + arr.push(element); + } + return arr.inject([], function(elements, child) { + if (serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + }); + }, + + getInputs: function(form, typeName, name) { + form = $(form); + 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++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + Form.getElements(form).invoke('disable'); + return form; + }, + + enable: function(form) { + form = $(form); + 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); + }); + }, + + 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 || { }); + + var params = options.parameters, action = form.readAttribute('action') || ''; + if (action.blank()) action = window.location.href; + options.parameters = form.serialize(true); + + if (params) { + if (Object.isString(params)) params = params.toQueryParams(); + Object.extend(options.parameters, params); + } + + if (form.hasAttribute('method') && !options.method) + options.method = form.method; + + return new Ajax.Request(action, options); + } +}; + +/*--------------------------------------------------------------------------*/ + + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +}; + +Form.Element.Methods = { + + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = { }; + pair[element.name] = value; + return Object.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + setValue: function(element, value) { + element = $(element); + var method = element.tagName.toLowerCase(); + Form.Element.Serializers[method](element, value); + return element; + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + try { + element.focus(); + if (element.select && (element.tagName.toLowerCase() != 'input' || + !(/^(?:button|reset|submit)$/i.test(element.type)))) + element.select(); + } catch (e) { } + return element; + }, + + disable: function(element) { + element = $(element); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.disabled = false; + return element; + } +}; + +/*--------------------------------------------------------------------------*/ + +var Field = Form.Element; + +var $F = Form.Element.Methods.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = (function() { + function input(element, value) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return inputSelector(element, value); + default: + return valueSelector(element, value); + } + } + + function inputSelector(element, value) { + if (Object.isUndefined(value)) + return element.checked ? element.value : null; + else element.checked = !!value; + } + + function valueSelector(element, value) { + if (Object.isUndefined(value)) return element.value; + else element.value = value; + } + + function select(element, value) { + if (Object.isUndefined(value)) + return (element.type === 'select-one' ? selectOne : selectMany)(element); + + 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); + if (single) { + if (currentValue == value) { + opt.selected = true; + return; + } + } + else opt.selected = value.include(currentValue); + } + } + + function selectOne(element) { + var index = element.selectedIndex; + return index >= 0 ? optionValue(element.options[index]) : null; + } + + function selectMany(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(optionValue(opt)); + } + return values; + } + + function optionValue(opt) { + return Element.hasAttribute(opt, 'value') ? opt.value : opt.text; + } + + return { + input: input, + inputSelector: inputSelector, + textarea: valueSelector, + select: select, + selectOne: selectOne, + selectMany: selectMany, + optionValue: optionValue, + button: valueSelector + }; +})(); + +/*--------------------------------------------------------------------------*/ + + +Abstract.TimedObserver = Class.create(PeriodicalExecuter, { + initialize: function($super, element, frequency, callback) { + $super(callback, frequency); + this.element = $(element); + this.lastValue = this.getValue(); + }, + + execute: function() { + var value = this.getValue(); + 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() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = Class.create({ + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback, this); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +}); + +Form.Element.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); +(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_PAGEDOWN: 34, + KEY_INSERT: 45, + + cache: {} + }; + + var docEl = document.documentElement; + var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl + && 'onmouseleave' in docEl; + + + + var isIELegacyEvent = function(event) { return false; }; + + if (window.attachEvent) { + if (window.addEventListener) { + isIELegacyEvent = function(event) { + return !(event instanceof window.Event); + }; + } else { + isIELegacyEvent = function(event) { return true; }; + } + } + + var _isButton; + + function _isButtonForDOMEvents(event, code) { + return event.which ? (event.which === code + 1) : (event.button === code); + } + + var legacyButtonMap = { 0: 1, 1: 4, 2: 2 }; + function _isButtonForLegacyEvents(event, code) { + return event.button === legacyButtonMap[code]; + } + + 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; + } + } + + if (window.attachEvent) { + if (!window.addEventListener) { + _isButton = _isButtonForLegacyEvents; + } else { + _isButton = function(event, code) { + return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) : + _isButtonForDOMEvents(event, code); + }; + } + } else if (Prototype.Browser.WebKit) { + _isButton = _isButtonForWebKit; + } else { + _isButton = _isButtonForDOMEvents; + } + + function isLeftClick(event) { return _isButton(event, 0); } + + function isMiddleClick(event) { return _isButton(event, 1); } + + function isRightClick(event) { return _isButton(event, 2); } + + function element(event) { + event = Event.extend(event); + + 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 (node.nodeType == Node.TEXT_NODE) + node = node.parentNode; + + return Element.extend(node); + } + + function findElement(event, expression) { + var element = Event.element(event); + + if (!expression) return element; + while (element) { + if (Object.isElement(element) && Prototype.Selector.match(element, expression)) { + return Element.extend(element); + } + element = element.parentNode; + } + } + + function pointer(event) { + return { x: pointerX(event), y: pointerY(event) }; + } + + function pointerX(event) { + var docElement = document.documentElement, + body = document.body || { scrollLeft: 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 }; + + return event.pageY || (event.clientY + + (docElement.scrollTop || body.scrollTop) - + (docElement.clientTop || 0)); + } + + function stop(event) { + Event.extend(event); + event.preventDefault(); + event.stopPropagation(); + + event.stopped = true; + } + + Event.Methods = { + isLeftClick: isLeftClick, + isMiddleClick: isMiddleClick, + isRightClick: isRightClick, + + element: element, + findElement: findElement, + + pointer: pointer, + pointerX: pointerX, + pointerY: pointerY, + + stop: stop + }; + + var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { + m[name] = Event.Methods[name].methodize(); + return m; + }); + + if (window.attachEvent) { + function _relatedTarget(event) { + var element; + switch (event.type) { + case 'mouseover': + case 'mouseenter': + element = event.fromElement; + break; + case 'mouseout': + case 'mouseleave': + element = event.toElement; + break; + default: + return null; + } + return Element.extend(element); + } + + var additionalMethods = { + stopPropagation: function() { this.cancelBubble = true; }, + preventDefault: function() { this.returnValue = false; }, + inspect: function() { return '[object Event]'; } + }; + + Event.extend = function(event, element) { + if (!event) return false; + + if (!isIELegacyEvent(event)) return event; + + if (event._extendedByPrototype) return event; + event._extendedByPrototype = Prototype.emptyFunction; + + var pointer = Event.pointer(event); + + Object.extend(event, { + target: event.srcElement || element, + relatedTarget: _relatedTarget(event), + pageX: pointer.x, + pageY: pointer.y + }); + + Object.extend(event, methods); + Object.extend(event, additionalMethods); + + return event; + }; + } else { + Event.extend = Prototype.K; + } + + if (window.addEventListener) { + 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'); + + if (Object.isUndefined(registry)) { + CACHE.push(element); + registry = Element.retrieve(element, 'prototype_event_registry', $H()); + } + + var respondersForEvent = registry.get(eventName); + if (Object.isUndefined(respondersForEvent)) { + respondersForEvent = []; + registry.set(eventName, respondersForEvent); + } + + if (respondersForEvent.pluck('handler').include(handler)) return false; + + var responder; + if (eventName.include(":")) { + responder = function(event) { + if (Object.isUndefined(event.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 (eventName === "mouseenter" || eventName === "mouseleave") { + responder = function(event) { + Event.extend(event, element); + + var parent = event.relatedTarget; + while (parent && parent !== element) { + try { parent = parent.parentNode; } + catch(e) { parent = element; } + } + + if (parent === element) return; + + handler.call(element, event); + }; + } + } else { + responder = function(event) { + Event.extend(event, element); + handler.call(element, event); + }; + } + } + + responder.handler = handler; + respondersForEvent.push(responder); + return responder; + } + + function _destroyCache() { + for (var i = 0, length = CACHE.length; i < length; i++) { + Event.stopObserving(CACHE[i]); + CACHE[i] = null; + } + } + + var CACHE = []; + + if (Prototype.Browser.IE) + window.attachEvent('onunload', _destroyCache); + + if (Prototype.Browser.WebKit) + window.addEventListener('unload', Prototype.emptyFunction, false); + + + var _getDOMEventName = Prototype.K, + translations = { mouseenter: "mouseover", mouseleave: "mouseout" }; + + if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) { + _getDOMEventName = function(eventName) { + return (translations[eventName] || eventName); + }; + } + + function observe(element, eventName, handler) { + element = $(element); + + var responder = _createResponder(element, eventName, handler); + + if (!responder) return element; + + if (eventName.include(':')) { + if (element.addEventListener) + element.addEventListener("dataavailable", responder, false); + else { + element.attachEvent("ondataavailable", responder); + element.attachEvent("onlosecapture", responder); + } + } else { + var actualEventName = _getDOMEventName(eventName); + + if (element.addEventListener) + element.addEventListener(actualEventName, responder, false); + else + element.attachEvent("on" + actualEventName, responder); + } + + return element; + } + + function stopObserving(element, eventName, handler) { + element = $(element); + + var registry = Element.retrieve(element, 'prototype_event_registry'); + if (!registry) return element; + + if (!eventName) { + registry.each( function(pair) { + var eventName = pair.key; + stopObserving(element, eventName); + }); + return element; + } + + var responders = registry.get(eventName); + if (!responders) return element; + + if (!handler) { + responders.each(function(r) { + stopObserving(element, eventName, r.handler); + }); + return element; + } + + var i = responders.length, responder; + while (i--) { + if (responders[i].handler === handler) { + responder = responders[i]; + break; + } + } + if (!responder) return element; + + if (eventName.include(':')) { + if (element.removeEventListener) + element.removeEventListener("dataavailable", responder, false); + else { + element.detachEvent("ondataavailable", responder); + element.detachEvent("onlosecapture", responder); + } + } else { + var actualEventName = _getDOMEventName(eventName); + if (element.removeEventListener) + element.removeEventListener(actualEventName, responder, false); + else + element.detachEvent('on' + actualEventName, responder); + } + + registry.set(eventName, responders.without(responder)); + + return element; + } + + function fire(element, eventName, memo, bubble) { + element = $(element); + + 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); + } else { + event = document.createEventObject(); + event.eventType = bubble ? 'ondataavailable' : 'onlosecapture'; + } + + event.eventName = eventName; + event.memo = memo || { }; + + 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); + this.eventName = eventName; + this.selector = selector; + this.callback = callback; + this.handler = this.handleEvent.bind(this); + }, + + start: function() { + Event.observe(this.element, this.eventName, this.handler); + return this; + }, + + stop: function() { + Event.stopObserving(this.element, this.eventName, this.handler); + return this; + }, + + 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; + } + + return new Event.Handler(element, eventName, selector, callback).start(); + } + + Object.extend(Event, Event.Methods); + + Object.extend(Event, { + fire: fire, + observe: observe, + stopObserving: stopObserving, + on: on + }); + + Element.addMethods({ + fire: fire, + + observe: observe, + + stopObserving: stopObserving, + + on: on + }); + + Object.extend(document, { + fire: fire.methodize(), + + observe: observe.methodize(), + + stopObserving: stopObserving.methodize(), + + on: on.methodize(), + + loaded: false + }); + + if (window.Event) Object.extend(window.Event, Event); + else window.Event = Event; +})(); + +(function() { + /* Support for the DOMContentLoaded event is based on work by Dan Webb, + Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */ + + var timer; + + function fireContentLoadedEvent() { + if (document.loaded) return; + if (timer) window.clearTimeout(timer); + document.loaded = true; + document.fire('dom:loaded'); + } + + function checkReadyState() { + if (document.readyState === 'complete') { + document.stopObserving('readystatechange', checkReadyState); + fireContentLoadedEvent(); + } + } + + function pollDoScroll() { + try { document.documentElement.doScroll('left'); } + catch(e) { + timer = pollDoScroll.defer(); + return; + } + fireContentLoadedEvent(); + } + + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false); + } else { + document.observe('readystatechange', checkReadyState); + if (window == top) + timer = pollDoScroll.defer(); + } + + Event.observe(window, 'load', fireContentLoadedEvent); +})(); + +Element.addMethods(); + +/*------------------------------- DEPRECATED -------------------------------*/ + +Hash.toQueryString = Object.toQueryString; + +var Toggle = { display: Element.toggle }; + +Element.Methods.childOf = Element.Methods.descendantOf; + +var Insertion = { + Before: function(element, content) { + return Element.insert(element, {before:content}); + }, + + Top: function(element, content) { + return Element.insert(element, {top:content}); + }, + + Bottom: function(element, content) { + return Element.insert(element, {bottom:content}); + }, + + After: function(element, content) { + return Element.insert(element, {after:content}); + } +}; + +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; + }, + + 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); + }, + + 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); + }, + + 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; + }, + + + cumulativeOffset: Element.Methods.cumulativeOffset, + + positionedOffset: Element.Methods.positionedOffset, + + absolutize: function(element) { + Position.prepare(); + return Element.absolutize(element); + }, + + relativize: function(element) { + Position.prepare(); + return Element.relativize(element); + }, + + realOffset: Element.Methods.cumulativeScrollOffset, + + offsetParent: Element.Methods.getOffsetParent, + + page: Element.Methods.viewportOffset, + + 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; + }; + + return function(className, parentElement) { + return $(parentElement || document.body).getElementsByClassName(className); + }; +}(Element.Methods); + +/*--------------------------------------------------------------------------*/ + +Element.ClassNames = Class.create(); +Element.ClassNames.prototype = { + initialize: function(element) { + this.element = $(element); + }, + + _each: function(iterator) { + this.element.className.split(/\s+/).select(function(name) { + return name.length > 0; + })._each(iterator); + }, + + set: function(className) { + this.element.className = className; + }, + + add: function(classNameToAdd) { + if (this.include(classNameToAdd)) return; + this.set($A(this).concat(classNameToAdd).join(' ')); + }, + + remove: function(classNameToRemove) { + if (!this.include(classNameToRemove)) return; + this.set($A(this).without(classNameToRemove).join(' ')); + }, + + toString: function() { + return $A(this).join(' '); + } +}; + +Object.extend(Element.ClassNames.prototype, Enumerable); + +/*--------------------------------------------------------------------------*/ + +(function() { + window.Selector = Class.create({ + initialize: function(expression) { + this.expression = expression.strip(); + }, + + findElements: function(rootElement) { + return Prototype.Selector.select(this.expression, rootElement); + }, + + match: function(element) { + return Prototype.Selector.match(element, this.expression); + }, + + toString: function() { + return this.expression; + }, + + inspect: function() { + return "#"; + } + }); + + Object.extend(Selector, { + matchElements: function(elements, expression) { + var match = Prototype.Selector.match, + results = []; + + for (var i = 0, length = elements.length; i < length; i++) { + var element = elements[i]; + if (match(element, expression)) { + results.push(Element.extend(element)); + } + } + return results; + }, + + findElement: function(elements, expression, index) { + index = index || 0; + 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++) { + return Element.extend(element); + } + } + }, + + findChildElements: function(element, expressions) { + var selector = expressions.toArray().join(', '); + return Prototype.Selector.select(selector, element || document); + } + }); +})(); diff --git a/src/usr/local/www/javascript/scriptaculous/scriptaculous.js b/src/usr/local/www/javascript/scriptaculous/scriptaculous.js new file mode 100644 index 0000000..6bf437a --- /dev/null +++ b/src/usr/local/www/javascript/scriptaculous/scriptaculous.js @@ -0,0 +1,68 @@ +// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 + +// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +var Scriptaculous = { + Version: '1.8.3', + require: function(libraryName) { + try{ + // inserting via DOM fails in Safari 2.0, so brute force approach + document.write(' to your HTML + Add class="sortable" to any table you'd like to make sortable + Click on the headers to sort + + Thanks to many, many people for contributions and suggestions. + Licenced as X11: http://www.kryogenix.org/code/browser/licence.html + This basically means: do what you want with it. + + -- pfSense modifications -- + Allow for sorting of IP adresses + 2012-09-15 Allow for multiple header rows, using "sortableHeaderRowIdentifier" class for the TR that has the column headers. (used in firewall-log) + 2012-09-15 Allow sorting multiple dual/mutlti rows together, using sortablemultirow="2" attribute for the table + 2012-09-15 Allow sorting of IP:Port texts, changed sort compare function + 2012-11-05 Allow sorting of IP:Port and *:port texts toghether also AAA_23 AAA_123 in 'numeric order' (used in Diagnostics\Sockets column LOCAL) +*/ + + +var stIsIE = /*@cc_on!@*/false; + +sorttable = { + init: function() { + // quit if this function has already been called + if (arguments.callee.done) return; + // flag this function so we don't do the same thing twice + arguments.callee.done = true; + // kill the timer + if (_timer) clearInterval(_timer); + + if (!document.createElement || !document.getElementsByTagName) return; + + sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/; + + forEach(document.getElementsByTagName('table'), function(table) { + if (table.className.search(/\bsortable\b/) != -1) { + sorttable.makeSortable(table); + } + }); + + }, + + makeSortable: function(table) { + if (table.getElementsByTagName('thead').length == 0) { + // table doesn't have a tHead. Since it should have, create one and + // put the first table row in it. + the = document.createElement('thead'); + the.appendChild(table.rows[0]); + table.insertBefore(the,table.firstChild); + } + // Safari doesn't support table.tHead, sigh + if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0]; + + headrow = undefined; + if (table.tHead.rows.length == 1) + headrow = table.tHead.rows[0].cells; + else + { + //if multiple rows are found one must be marked with class + for (var i=0; i5' : ' ▴'; + this.appendChild(sortrevind); + return; + } + if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) { + // if we're already sorted by this column in reverse, just + // re-reverse the table, which is quicker + sorttable.reverse(this.sorttable_tbody, sortableMultirow); + this.className = this.className.replace('sorttable_sorted_reverse', + 'sorttable_sorted'); + this.removeChild(document.getElementById('sorttable_sortrevind')); + sortfwdind = document.createElement('span'); + sortfwdind.id = "sorttable_sortfwdind"; + sortfwdind.innerHTML = stIsIE ? ' 6' : ' ▾'; + this.appendChild(sortfwdind); + return; + } + + // remove sorttable_sorted classes + theadrow = this.parentNode; + forEach(theadrow.childNodes, function(cell) { + if (cell.nodeType == 1) { // an element + cell.className = cell.className.replace('sorttable_sorted_reverse',''); + cell.className = cell.className.replace('sorttable_sorted',''); + } + }); + sortfwdind = document.getElementById('sorttable_sortfwdind'); + if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); } + sortrevind = document.getElementById('sorttable_sortrevind'); + if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); } + + this.className += ' sorttable_sorted'; + sortfwdind = document.createElement('span'); + sortfwdind.id = "sorttable_sortfwdind"; + sortfwdind.innerHTML = stIsIE ? ' 6' : ' ▾'; + this.appendChild(sortfwdind); + + // build an array to sort. This is a Schwartzian transform thing, + // i.e., we "decorate" each row with the actual sort key, + // sort based on the sort keys, and then put the rows back in order + // which is a lot faster because you only do getInnerText once per row + row_array = []; + col = this.sorttable_columnindex; + rows = this.sorttable_tbody.rows; + for (var j=0; j 12) { + // definitely dd/mm + return sorttable.sort_ddmm; + } else if (second > 12) { + return sorttable.sort_mmdd; + } else { + // looks like a date, but we can't tell which, so assume + // that it's dd/mm (English imperialism!) and keep looking + sortfn = sorttable.sort_ddmm; + } + } + } + } + return sortfn; + }, + + getInnerText: function(node) { + // gets the text we want to use for sorting for a cell. + // strips leading and trailing whitespace. + // this is *not* a generic getInnerText function; it's special to sorttable. + // for example, you can override the cell text with a customkey attribute. + // it also gets .value for fields. + + hasInputs = (typeof node.getElementsByTagName == 'function') && + node.getElementsByTagName('input').length; + + if (node.getAttribute("sorttable_customkey") != null) { + return node.getAttribute("sorttable_customkey"); + } + else if (typeof node.textContent != 'undefined' && !hasInputs) { + return node.textContent.replace(/^\s+|\s+$/g, ''); + } + else if (typeof node.innerText != 'undefined' && !hasInputs) { + return node.innerText.replace(/^\s+|\s+$/g, ''); + } + else if (typeof node.text != 'undefined' && !hasInputs) { + return node.text.replace(/^\s+|\s+$/g, ''); + } + else { + switch (node.nodeType) { + case 3: + if (node.nodeName.toLowerCase() == 'input') { + return node.value.replace(/^\s+|\s+$/g, ''); + } + case 4: + return node.nodeValue.replace(/^\s+|\s+$/g, ''); + break; + case 1: + case 11: + var innerText = ''; + for (var i = 0; i < node.childNodes.length; i++) { + innerText += sorttable.getInnerText(node.childNodes[i]); + } + return innerText.replace(/^\s+|\s+$/g, ''); + break; + default: + return ''; + } + } + }, + + reverse: function(tbody, sortableMultirow) { + // reverse the rows in a tbody + newrows = []; + for (var i=0; i=0; i-=sortableMultirow) { + for(var j=sortableMultirow-1;j>=0;j--) + { + tbody.appendChild(newrows[i-j]); + } + } + delete newrows; + }, + + /* sort functions + each sort function takes two parameters, a and b + you are comparing a[0] and b[0] */ + sort_numeric: function(a,b) { + aa = parseFloat(a[0].replace(/[^0-9.-]/g,'')); + if (isNaN(aa)) aa = 0; + bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); + if (isNaN(bb)) bb = 0; + return aa-bb; + }, + sort_alpha: function(a,b) { + if (a[0]==b[0]) return 0; + if (a[0] b2match) return 1; + if (a2match < b2match) return -1; + } + if (a[0] == b[0]) return 0; + if (a[0] < b[0]) return -1; + return 1; + }, + sort_ipaddr: function(a,b) { + aip = ip2ulong(a[0]); + bip = ip2ulong(b[0]); + if (aip && bip) + { + if (aip == bip) return 0; + if (aip < bip) return -1; + return 1; + } else { + if (aip !== false || bip !== false) + return aip === false ? -1 : 1; + else + { + return sorttable.sortWithNumber(a,b); + } + } + }, + + shaker_sort: function(list, comp_func) { + // A stable sort function to allow multi-level sorting of data + // see: http://en.wikipedia.org/wiki/Cocktail_sort + // thanks to Joseph Nahmias + var b = 0; + var t = list.length - 1; + var swap = true; + + while(swap) { + swap = false; + for(var i = b; i < t; ++i) { + if ( comp_func(list[i], list[i+1]) > 0 ) { + var q = list[i]; list[i] = list[i+1]; list[i+1] = q; + swap = true; + } + } // for + t--; + + if (!swap) break; + + for(var i = t; i > b; --i) { + if ( comp_func(list[i], list[i-1]) < 0 ) { + var q = list[i]; list[i] = list[i-1]; list[i-1] = q; + swap = true; + } + } // for + b++; + + } // while(swap) + } +}; + +/* ****************************************************************** + Supporting functions: bundled here to avoid depending on a library + ****************************************************************** */ + +function ip2ulong(ip) { + ip += ""; + var ulip = false; + var octets = []; + ipportmatch = ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:[0-9]{1,5}\b/);// IP:port + if (ipportmatch) { + ipportmatch += ""; + ipport = ipportmatch.split(':'); + octets = ipport[0].split('.'); + for (i=0; i < 4; i++) { + ulip += octets[i] * Math.pow(256, (5-i)); + } + ulip += parseInt(ipport[1]); + } else { + ipmatch = ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);// IP only + if (ipmatch) { + ipmatch+=""; + octets = ipmatch.split('.'); + for (i=0; i < 4; i++) { + ulip += octets[i] * Math.pow(256, (5-i)); + } + } + } + return ulip; +} + +// Dean Edwards/Matthias Miller/John Resig + +/* for Mozilla/Opera9 */ +if (document.addEventListener) { + document.addEventListener("DOMContentLoaded", sorttable.init, false); +} + +/* for Safari */ +if (/WebKit/i.test(navigator.userAgent)) { // sniff + var _timer = setInterval(function() { + if (/loaded|complete/.test(document.readyState)) { + sorttable.init(); // call the onload handler + } + }, 10); +} + +/* for other browsers */ +window.onload = sorttable.init; + +// written by Dean Edwards, 2005 +// with input from Tino Zijdel, Matthias Miller, Diego Perini + +// http://dean.edwards.name/weblog/2005/10/add-event/ + +function dean_addEvent(element, type, handler) { + if (element.addEventListener) { + element.addEventListener(type, handler, false); + } else { + // assign each event handler a unique ID + if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++; + // create a hash table of event types for the element + if (!element.events) element.events = {}; + // create a hash table of event handlers for each element/event pair + var handlers = element.events[type]; + if (!handlers) { + handlers = element.events[type] = {}; + // store the existing event handler (if there is one) + if (element["on" + type]) { + handlers[0] = element["on" + type]; + } + } + // store the event handler in the hash table + handlers[handler.$$guid] = handler; + // assign a global event handler to do all the work + element["on" + type] = handleEvent; + } +}; +// a counter used to create unique IDs +dean_addEvent.guid = 1; + +function removeEvent(element, type, handler) { + if (element.removeEventListener) { + element.removeEventListener(type, handler, false); + } else { + // delete the event handler from the hash table + if (element.events && element.events[type]) { + delete element.events[type][handler.$$guid]; + } + } +}; + +function handleEvent(event) { + var returnValue = true; + // grab the event object (IE uses a global event object) + event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event); + // get a reference to the hash table of event handlers + var handlers = this.events[event.type]; + // execute each event handler + for (var i in handlers) { + this.$$handleEvent = handlers[i]; + if (this.$$handleEvent(event) === false) { + returnValue = false; + } + } + return returnValue; +}; + +function fixEvent(event) { + // add W3C standard event methods + event.preventDefault = fixEvent.preventDefault; + event.stopPropagation = fixEvent.stopPropagation; + return event; +}; +fixEvent.preventDefault = function() { + this.returnValue = false; +}; +fixEvent.stopPropagation = function() { + this.cancelBubble = true; +}; + +// Dean's forEach: http://dean.edwards.name/base/forEach.js +/* + forEach, version 1.0 + Copyright 2006, Dean Edwards + License: http://www.opensource.org/licenses/mit-license.php +*/ + +// array-like enumeration +if (!Array.forEach) { // mozilla already supports this + Array.forEach = function(array, block, context) { + for (var i = 0; i < array.length; i++) { + block.call(context, array[i], i, array); + } + }; +} + +// generic enumeration +Function.prototype.forEach = function(object, block, context) { + for (var key in object) { + if (typeof this.prototype[key] == "undefined") { + block.call(context, object[key], key, object); + } + } +}; + +// character enumeration +String.forEach = function(string, block, context) { + Array.forEach(string.split(""), function(chr, index) { + block.call(context, chr, index, string); + }); +}; + +// globally resolve forEach enumeration +var forEach = function(object, block, context) { + if (object) { + var resolve = Object; // default + if (object instanceof Function) { + // functions have a "length" property + resolve = Function; + } else if (object.forEach instanceof Function) { + // the object implements a custom forEach method so use that + object.forEach(block, context); + return; + } else if (typeof object == "string") { + // the object is a string + resolve = String; + } else if (typeof object.length == "number") { + // the object is array-like + resolve = Array; + } + resolve.forEach(object, block, context); + } +}; + diff --git a/src/usr/local/www/javascript/suggestions.js b/src/usr/local/www/javascript/suggestions.js new file mode 100644 index 0000000..682a352 --- /dev/null +++ b/src/usr/local/www/javascript/suggestions.js @@ -0,0 +1,33 @@ + +/** + * Provides suggestions for state names (USA). + * @class + * @scope public + */ +function StateSuggestions(text) { + this.states = text; +} + +/** + * Request suggestions for the given autosuggest control. + * @scope protected + * @param oAutoSuggestControl The autosuggest control to provide suggestions for. + */ +StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/, + bTypeAhead /*:boolean*/) { + var aSuggestions = []; + var sTextboxValue = oAutoSuggestControl.textbox.value; + + if (sTextboxValue.length > 0){ + + //search for matching states + for (var i=0; i < this.states.length; i++) { + if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) { + aSuggestions.push(this.states[i]); + } + } + } + + //provide suggestions to the control + oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead); +}; diff --git a/src/usr/local/www/javascript/ticker.js b/src/usr/local/www/javascript/ticker.js new file mode 100644 index 0000000..defb1d8 --- /dev/null +++ b/src/usr/local/www/javascript/ticker.js @@ -0,0 +1,73 @@ +/* $Id$ */ +/* + ticker.js + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + All rights reserved. + + originally part of m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2004 Manuel Kasper . + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + pfSense_MODULE: utils + +*/ +function notice_action(action,msgid) { + jQuery.ajax({ + type: 'post', + cache: false, + url: 'index.php', + data: {closenotice: msgid}, + success: function(response) { + jQuery('#menu_messages').html(response); + } + }); +} + +function pulsateText(elem) { + jQuery(elem).effect("pulsate", { times:12 }, 500); + jQuery(elem).effect("pulsate", { times:6 }, 1500); + jQuery(elem).effect("pulsate", { times:3 }, 2500); +} + +jQuery(document).ready(function() { + pulsateText('#marquee-text'); + jQuery('#marquee-text a').hover(function () { + jQuery(this).css('cursor','pointer'); + }); +}); + +function alias_popup(alias_id,theme,loading) { + domTT_update('ttalias_'+alias_id,""+loading+""); + jQuery.ajax({ + type: 'post', + cache: false, + url: "/index.php", + data: {aliasid:alias_id, act:'alias_info_popup'}, + success: function(response) { + //alert('
                          '+response.match(/

                          .*<\/table>/i)+'
                          '); + domTT_update('ttalias_'+alias_id,'
                          '+response.match(/

                          .*<\/table>/i)+'
                          '); + } + }); +} \ No newline at end of file diff --git a/src/usr/local/www/javascript/wizard/autosuggest.js b/src/usr/local/www/javascript/wizard/autosuggest.js new file mode 100644 index 0000000..d9b5ac0 --- /dev/null +++ b/src/usr/local/www/javascript/wizard/autosuggest.js @@ -0,0 +1,337 @@ + +/** + * An autosuggest textbox control. + * @class + * @scope public + */ +function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, + oProvider /*:SuggestionProvider*/) { + + /** + * The currently selected suggestions. + * @scope private + */ + this.cur /*:int*/ = -1; + + /** + * The dropdown list layer. + * @scope private + */ + this.layer = null; + + /** + * Suggestion provider for the autosuggest feature. + * @scope private. + */ + this.provider /*:SuggestionProvider*/ = oProvider; + + /** + * The textbox to capture. + * @scope private + */ + this.textbox /*:HTMLInputElement*/ = oTextbox; + + //initialize the control + this.init(); + +} + +/** + * Autosuggests one or more suggestions for what the user has typed. + * If no suggestions are passed in, then no autosuggest occurs. + * @scope private + * @param aSuggestions An array of suggestion strings. + * @param bTypeAhead If the control should provide a type ahead suggestion. + */ +AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/, + bTypeAhead /*:boolean*/) { + + //make sure there's at least one suggestion + if (aSuggestions.length > 0) { + if (bTypeAhead) { + this.typeAhead(aSuggestions[0]); + } + + this.showSuggestions(aSuggestions); + } else { + this.hideSuggestions(); + } +}; + +/** + * Creates the dropdown layer to display multiple suggestions. + * @scope private + */ +AutoSuggestControl.prototype.createDropDown = function () { + + var oThis = this; + + //create the layer and assign styles + this.layer = document.createElement("div"); + this.layer.className = "suggestions"; + this.layer.style.visibility = "hidden"; + this.layer.style.width = this.textbox.offsetWidth; + + //when the user clicks on the a suggestion, get the text (innerHTML) + //and place it into a textbox + this.layer.onmousedown = + this.layer.onmouseup = + this.layer.onmouseover = function (oEvent) { + oEvent = oEvent || window.event; + oTarget = oEvent.target || oEvent.srcElement; + + if (oEvent.type == "mousedown") { + oThis.textbox.value = oTarget.firstChild.nodeValue; + oThis.hideSuggestions(); + } else if (oEvent.type == "mouseover") { + oThis.highlightSuggestion(oTarget); + } else { + oThis.textbox.focus(); + } + }; + + + document.body.appendChild(this.layer); +}; + +/** + * Gets the left coordinate of the textbox. + * @scope private + * @return The left coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getLeft = function () /*:int*/ { + + var oNode = this.textbox; + var iLeft = 0; + + while(oNode.tagName != "BODY") { + iLeft += oNode.offsetLeft; + oNode = oNode.offsetParent; + } + + return iLeft; +}; + +/** + * Gets the top coordinate of the textbox. + * @scope private + * @return The top coordinate of the textbox in pixels. + */ +AutoSuggestControl.prototype.getTop = function () /*:int*/ { + + var oNode = this.textbox; + var iTop = 0; + + while(oNode.tagName != "BODY") { + iTop += oNode.offsetTop; + oNode = oNode.offsetParent; + } + + return iTop; +}; + +/** + * Handles three keydown events. + * @scope private + * @param oEvent The event object for the keydown event. + */ +AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) { + + switch(oEvent.keyCode) { + case 38: //up arrow + this.previousSuggestion(); + break; + case 40: //down arrow + this.nextSuggestion(); + break; + case 13: //enter + this.hideSuggestions(); + break; + } + +}; + +/** + * Handles keyup events. + * @scope private + * @param oEvent The event object for the keyup event. + */ +AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) { + + var iKeyCode = oEvent.keyCode; + + //for backspace (8) and delete (46), shows suggestions without typeahead + if (iKeyCode == 8 || iKeyCode == 46) { + this.provider.requestSuggestions(this, false); + + //make sure not to interfere with non-character keys + } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) { + //ignore + } else { + //request suggestions from the suggestion provider with typeahead + this.provider.requestSuggestions(this, true); + } +}; + +/** + * Hides the suggestion dropdown. + * @scope private + */ +AutoSuggestControl.prototype.hideSuggestions = function () { + this.layer.style.visibility = "hidden"; +}; + +/** + * Highlights the given node in the suggestions dropdown. + * @scope private + * @param oSuggestionNode The node representing a suggestion in the dropdown. + */ +AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) { + + for (var i=0; i < this.layer.childNodes.length; i++) { + var oNode = this.layer.childNodes[i]; + if (oNode == oSuggestionNode) { + oNode.className = "current"; + } else if (oNode.className == "current") { + oNode.className = ""; + } + } +}; + +/** + * Initializes the textbox with event handlers for + * auto suggest functionality. + * @scope private + */ +AutoSuggestControl.prototype.init = function () { + + //save a reference to this object + var oThis = this; + + //assign the onkeyup event handler + this.textbox.onkeyup = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyUp() method with the event object + oThis.handleKeyUp(oEvent); + }; + + //assign onkeydown event handler + this.textbox.onkeydown = function (oEvent) { + + //check for the proper location of the event object + if (!oEvent) { + oEvent = window.event; + } + + //call the handleKeyDown() method with the event object + oThis.handleKeyDown(oEvent); + }; + + //assign onblur event handler (hides suggestions) + this.textbox.onblur = function () { + oThis.hideSuggestions(); + }; + + //create the suggestions dropdown + this.createDropDown(); +}; + +/** + * Highlights the next suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.nextSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) { + var oNode = cSuggestionNodes[++this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Highlights the previous suggestion in the dropdown and + * places the suggestion into the textbox. + * @scope private + */ +AutoSuggestControl.prototype.previousSuggestion = function () { + var cSuggestionNodes = this.layer.childNodes; + + if (cSuggestionNodes.length > 0 && this.cur > 0) { + var oNode = cSuggestionNodes[--this.cur]; + this.highlightSuggestion(oNode); + this.textbox.value = oNode.firstChild.nodeValue; + } +}; + +/** + * Selects a range of text in the textbox. + * @scope public + * @param iStart The start index (base 0) of the selection. + * @param iLength The number of characters to select. + */ +AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) { + + //use text ranges for Internet Explorer + if (this.textbox.createTextRange) { + var oRange = this.textbox.createTextRange(); + oRange.moveStart("character", iStart); + oRange.moveEnd("character", iLength - this.textbox.value.length); + oRange.select(); + + //use setSelectionRange() for Mozilla + } else if (this.textbox.setSelectionRange) { + this.textbox.setSelectionRange(iStart, iLength); + } + + //set focus back to the textbox + this.textbox.focus(); +}; + +/** + * Builds the suggestion layer contents, moves it into position, + * and displays the layer. + * @scope private + * @param aSuggestions An array of suggestions for the control. + */ +AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) { + + var oDiv = null; + this.layer.innerHTML = ""; //clear contents of the layer + + for (var i=0; i < aSuggestions.length; i++) { + oDiv = document.createElement("div"); + oDiv.appendChild(document.createTextNode(aSuggestions[i])); + this.layer.appendChild(oDiv); + } + + this.layer.style.left = this.getLeft() + "px"; + this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; + this.layer.style.visibility = "visible"; + +}; + +/** + * Inserts a suggestion into the textbox, highlighting the + * suggested part of the text. + * @scope private + * @param sSuggestion The suggestion for the textbox. + */ +AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) { + + //check for support of typeahead functionality + if (this.textbox.createTextRange || this.textbox.setSelectionRange){ + var iLen = this.textbox.value.length; + this.textbox.value = sSuggestion; + this.selectRange(iLen, sSuggestion.length); + } +}; + diff --git a/src/usr/local/www/javascript/wizard/disablekeys.js b/src/usr/local/www/javascript/wizard/disablekeys.js new file mode 100644 index 0000000..5d6c87a --- /dev/null +++ b/src/usr/local/www/javascript/wizard/disablekeys.js @@ -0,0 +1,6 @@ +function kH(e) { + var pK = document.all? window.event.keyCode:e.which; + return pK != 13; +} +document.onkeypress = kH; +if (document.layers) document.captureEvents(Event.KEYPRESS); \ No newline at end of file diff --git a/src/usr/local/www/javascript/wizard/suggestions.js b/src/usr/local/www/javascript/wizard/suggestions.js new file mode 100644 index 0000000..4d1e127 --- /dev/null +++ b/src/usr/local/www/javascript/wizard/suggestions.js @@ -0,0 +1,33 @@ + +/** + * Provides suggestions for state names (USA). + * @class + * @scope public + */ +function StateSuggestions(text) { + this.states = text; +} + +/** + * Request suggestions for the given autosuggest control. + * @scope protected + * @param oAutoSuggestControl The autosuggest control to provide suggestions for. + */ +StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/, + bTypeAhead /*:boolean*/) { + var aSuggestions = []; + var sTextboxValue = oAutoSuggestControl.textbox.value; + + if (sTextboxValue.length > 0){ + + //search for matching states + for (var i=0; i < this.states.length; i++) { + if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) { + aSuggestions.push(this.states[i]); + } + } + } + + //provide suggestions to the control + oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead); +}; -- cgit v1.1